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.13.0. 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 that rand_s() is available on Windows systems with MSVC 2005
72 ** or higher.
73 */
74 #if defined(_MSC_VER) && _MSC_VER>=1400
75 # define _CRT_RAND_S
76 #endif
77 
78 /*
79 ** Include the header file used to customize the compiler options for MSVC.
80 ** This should be done first so that it can successfully prevent spurious
81 ** compiler warnings due to subsequent content in this file and other files
82 ** that are included by this file.
83 */
84 /************** Include msvc.h in the middle of sqliteInt.h ******************/
85 /************** Begin file msvc.h ********************************************/
86 /*
87 ** 2015 January 12
88 **
89 ** The author disclaims copyright to this source code. In place of
90 ** a legal notice, here is a blessing:
91 **
92 ** May you do good and not evil.
93 ** May you find forgiveness for yourself and forgive others.
94 ** May you share freely, never taking more than you give.
95 **
96 ******************************************************************************
97 **
98 ** This file contains code that is specific to MSVC.
99 */
100 #ifndef _MSVC_H_
101 #define _MSVC_H_
102 
103 #if defined(_MSC_VER)
104 #pragma warning(disable : 4054)
105 #pragma warning(disable : 4055)
106 #pragma warning(disable : 4100)
107 #pragma warning(disable : 4127)
108 #pragma warning(disable : 4130)
109 #pragma warning(disable : 4152)
110 #pragma warning(disable : 4189)
111 #pragma warning(disable : 4206)
112 #pragma warning(disable : 4210)
113 #pragma warning(disable : 4232)
114 #pragma warning(disable : 4244)
115 #pragma warning(disable : 4305)
116 #pragma warning(disable : 4306)
117 #pragma warning(disable : 4702)
118 #pragma warning(disable : 4706)
119 #endif /* defined(_MSC_VER) */
120 
121 #endif /* _MSVC_H_ */
122 
123 /************** End of msvc.h ************************************************/
124 /************** Continuing where we left off in sqliteInt.h ******************/
125 
126 /*
127 ** Special setup for VxWorks
128 */
129 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
130 /************** Begin file vxworks.h *****************************************/
131 /*
132 ** 2015-03-02
133 **
134 ** The author disclaims copyright to this source code. In place of
135 ** a legal notice, here is a blessing:
136 **
137 ** May you do good and not evil.
138 ** May you find forgiveness for yourself and forgive others.
139 ** May you share freely, never taking more than you give.
140 **
141 ******************************************************************************
142 **
143 ** This file contains code that is specific to Wind River's VxWorks
144 */
145 #if defined(__RTP__) || defined(_WRS2_KERNEL)
146 /* This is VxWorks. Set up things specially for that OS
147 */
148 #include <vxWorks.h>
149 #include <pthread.h> /* amalgamator: dontcache */
150 #define OS_VXWORKS 1
151 #define SQLITE_OS_OTHER 0
152 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
153 #define SQLITE_OMIT_LOAD_EXTENSION 1
154 #define SQLITE_ENABLE_LOCKING_STYLE 0
155 #define HAVE_UTIME 1
156 #else
157 /* This is not VxWorks. */
158 #define OS_VXWORKS 0
159 #define HAVE_FCHOWN 1
160 #define HAVE_READLINK 1
161 #define HAVE_LSTAT 1
162 #endif /* defined(_WRS2_KERNEL) */
163 
164 /************** End of vxworks.h *********************************************/
165 /************** Continuing where we left off in sqliteInt.h ******************/
166 
167 /*
168 ** These #defines should enable >2GB file support on POSIX if the
169 ** underlying operating system supports it. If the OS lacks
170 ** large file support, or if the OS is windows, these should be no-ops.
171 **
172 ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
173 ** system #includes. Hence, this block of code must be the very first
174 ** code in all source files.
175 **
176 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
177 ** on the compiler command line. This is necessary if you are compiling
178 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
179 ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
180 ** without this option, LFS is enable. But LFS does not exist in the kernel
181 ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
182 ** portability you should omit LFS.
183 **
184 ** The previous paragraph was written in 2005. (This paragraph is written
185 ** on 2008-11-28.) These days, all Linux kernels support large files, so
186 ** you should probably leave LFS enabled. But some embedded platforms might
187 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
188 **
189 ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
190 */
191 #ifndef SQLITE_DISABLE_LFS
192 # define _LARGE_FILE 1
193 # ifndef _FILE_OFFSET_BITS
194 # define _FILE_OFFSET_BITS 64
195 # endif
196 # define _LARGEFILE_SOURCE 1
197 #endif
198 
199 /* What version of GCC is being used. 0 means GCC is not being used */
200 #ifdef __GNUC__
201 # define GCC_VERSION (__GNUC__*1000000+__GNUC_MINOR__*1000+__GNUC_PATCHLEVEL__)
202 #else
203 # define GCC_VERSION 0
204 #endif
205 
206 /* Needed for various definitions... */
207 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
208 # define _GNU_SOURCE
209 #endif
210 
211 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
212 # define _BSD_SOURCE
213 #endif
214 
215 /*
216 ** For MinGW, check to see if we can include the header file containing its
217 ** version information, among other things. Normally, this internal MinGW
218 ** header file would [only] be included automatically by other MinGW header
219 ** files; however, the contained version information is now required by this
220 ** header file to work around binary compatibility issues (see below) and
221 ** this is the only known way to reliably obtain it. This entire #if block
222 ** would be completely unnecessary if there was any other way of detecting
223 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
224 ** some MinGW-specific macros). When compiling for MinGW, either the
225 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
226 ** defined; otherwise, detection of conditions specific to MinGW will be
227 ** disabled.
228 */
229 #if defined(_HAVE_MINGW_H)
230 # include "mingw.h"
231 #elif defined(_HAVE__MINGW_H)
232 # include "_mingw.h"
233 #endif
234 
235 /*
236 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
237 ** define is required to maintain binary compatibility with the MSVC runtime
238 ** library in use (e.g. for Windows XP).
239 */
240 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
241  defined(_WIN32) && !defined(_WIN64) && \
242  defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
243  defined(__MSVCRT__)
244 # define _USE_32BIT_TIME_T
245 #endif
246 
247 /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
248 ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
249 ** MinGW.
250 */
251 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
252 /************** Begin file sqlite3.h *****************************************/
253 /*
254 ** 2001 September 15
255 **
256 ** The author disclaims copyright to this source code. In place of
257 ** a legal notice, here is a blessing:
258 **
259 ** May you do good and not evil.
260 ** May you find forgiveness for yourself and forgive others.
261 ** May you share freely, never taking more than you give.
262 **
263 *************************************************************************
264 ** This header file defines the interface that the SQLite library
265 ** presents to client programs. If a C-function, structure, datatype,
266 ** or constant definition does not appear in this file, then it is
267 ** not a published API of SQLite, is subject to change without
268 ** notice, and should not be referenced by programs that use SQLite.
269 **
270 ** Some of the definitions that are in this file are marked as
271 ** "experimental". Experimental interfaces are normally new
272 ** features recently added to SQLite. We do not anticipate changes
273 ** to experimental interfaces but reserve the right to make minor changes
274 ** if experience from use "in the wild" suggest such changes are prudent.
275 **
276 ** The official C-language API documentation for SQLite is derived
277 ** from comments in this file. This file is the authoritative source
278 ** on how SQLite interfaces are supposed to operate.
279 **
280 ** The name of this file under configuration management is "sqlite.h.in".
281 ** The makefile makes some minor changes to this file (such as inserting
282 ** the version number) and changes its name to "sqlite3.h" as
283 ** part of the build process.
284 */
285 #ifndef _SQLITE3_H_
286 #define _SQLITE3_H_
287 #include <stdarg.h> /* Needed for the definition of va_list */
288 
289 /*
290 ** Make sure we can call this stuff from C++.
291 */
292 #if 0
293 extern "C" {
294 #endif
295 
296 
297 /*
298 ** Provide the ability to override linkage features of the interface.
299 */
300 #ifndef SQLITE_EXTERN
301 # define SQLITE_EXTERN extern
302 #endif
303 #ifndef SQLITE_API
304 # define SQLITE_API
305 #endif
306 #ifndef SQLITE_CDECL
307 # define SQLITE_CDECL
308 #endif
309 #ifndef SQLITE_STDCALL
310 # define SQLITE_STDCALL
311 #endif
312 
313 /*
314 ** These no-op macros are used in front of interfaces to mark those
315 ** interfaces as either deprecated or experimental. New applications
316 ** should not use deprecated interfaces - they are supported for backwards
317 ** compatibility only. Application writers should be aware that
318 ** experimental interfaces are subject to change in point releases.
319 **
320 ** These macros used to resolve to various kinds of compiler magic that
321 ** would generate warning messages when they were used. But that
322 ** compiler magic ended up generating such a flurry of bug reports
323 ** that we have taken it all out and gone back to using simple
324 ** noop macros.
325 */
326 #define SQLITE_DEPRECATED
327 #define SQLITE_EXPERIMENTAL
328 
329 /*
330 ** Ensure these symbols were not defined by some previous header file.
331 */
332 #ifdef SQLITE_VERSION
333 # undef SQLITE_VERSION
334 #endif
335 #ifdef SQLITE_VERSION_NUMBER
336 # undef SQLITE_VERSION_NUMBER
337 #endif
338 
339 /*
340 ** CAPI3REF: Compile-Time Library Version Numbers
341 **
342 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
343 ** evaluates to a string literal that is the SQLite version in the
344 ** format "X.Y.Z" where X is the major version number (always 3 for
345 ** SQLite3) and Y is the minor version number and Z is the release number.)^
346 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
347 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
348 ** numbers used in [SQLITE_VERSION].)^
349 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
350 ** be larger than the release from which it is derived. Either Y will
351 ** be held constant and Z will be incremented or else Y will be incremented
352 ** and Z will be reset to zero.
353 **
354 ** Since version 3.6.18, SQLite source code has been stored in the
355 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
356 ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
357 ** a string which identifies a particular check-in of SQLite
358 ** within its configuration management system. ^The SQLITE_SOURCE_ID
359 ** string contains the date and time of the check-in (UTC) and an SHA1
360 ** hash of the entire source tree.
361 **
362 ** See also: [sqlite3_libversion()],
363 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
364 ** [sqlite_version()] and [sqlite_source_id()].
365 */
366 #define SQLITE_VERSION "3.13.0"
367 #define SQLITE_VERSION_NUMBER 3013000
368 #define SQLITE_SOURCE_ID "2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2"
369 
370 /*
371 ** CAPI3REF: Run-Time Library Version Numbers
372 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
373 **
374 ** These interfaces provide the same information as the [SQLITE_VERSION],
375 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
376 ** but are associated with the library instead of the header file. ^(Cautious
377 ** programmers might include assert() statements in their application to
378 ** verify that values returned by these interfaces match the macros in
379 ** the header, and thus ensure that the application is
380 ** compiled with matching library and header files.
381 **
382 ** <blockquote><pre>
383 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
384 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
385 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
386 ** </pre></blockquote>)^
387 **
388 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
389 ** macro. ^The sqlite3_libversion() function returns a pointer to the
390 ** to the sqlite3_version[] string constant. The sqlite3_libversion()
391 ** function is provided for use in DLLs since DLL users usually do not have
392 ** direct access to string constants within the DLL. ^The
393 ** sqlite3_libversion_number() function returns an integer equal to
394 ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
395 ** a pointer to a string constant whose value is the same as the
396 ** [SQLITE_SOURCE_ID] C preprocessor macro.
397 **
398 ** See also: [sqlite_version()] and [sqlite_source_id()].
399 */
402 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
404 
405 /*
406 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
407 **
408 ** ^The sqlite3_compileoption_used() function returns 0 or 1
409 ** indicating whether the specified option was defined at
410 ** compile time. ^The SQLITE_ prefix may be omitted from the
411 ** option name passed to sqlite3_compileoption_used().
412 **
413 ** ^The sqlite3_compileoption_get() function allows iterating
414 ** over the list of options that were defined at compile time by
415 ** returning the N-th compile time option string. ^If N is out of range,
416 ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
417 ** prefix is omitted from any strings returned by
418 ** sqlite3_compileoption_get().
419 **
420 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
421 ** and sqlite3_compileoption_get() may be omitted by specifying the
422 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
423 **
424 ** See also: SQL functions [sqlite_compileoption_used()] and
425 ** [sqlite_compileoption_get()] and the [compile_options pragma].
426 */
427 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
428 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
430 #endif
431 
432 /*
433 ** CAPI3REF: Test To See If The Library Is Threadsafe
434 **
435 ** ^The sqlite3_threadsafe() function returns zero if and only if
436 ** SQLite was compiled with mutexing code omitted due to the
437 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
438 **
439 ** SQLite can be compiled with or without mutexes. When
440 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
441 ** are enabled and SQLite is threadsafe. When the
442 ** [SQLITE_THREADSAFE] macro is 0,
443 ** the mutexes are omitted. Without the mutexes, it is not safe
444 ** to use SQLite concurrently from more than one thread.
445 **
446 ** Enabling mutexes incurs a measurable performance penalty.
447 ** So if speed is of utmost importance, it makes sense to disable
448 ** the mutexes. But for maximum safety, mutexes should be enabled.
449 ** ^The default behavior is for mutexes to be enabled.
450 **
451 ** This interface can be used by an application to make sure that the
452 ** version of SQLite that it is linking against was compiled with
453 ** the desired setting of the [SQLITE_THREADSAFE] macro.
454 **
455 ** This interface only reports on the compile-time mutex setting
456 ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
457 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
458 ** can be fully or partially disabled using a call to [sqlite3_config()]
459 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
460 ** or [SQLITE_CONFIG_SERIALIZED]. ^(The return value of the
461 ** sqlite3_threadsafe() function shows only the compile-time setting of
462 ** thread safety, not any run-time changes to that setting made by
463 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
464 ** is unchanged by calls to sqlite3_config().)^
465 **
466 ** See the [threading mode] documentation for additional information.
467 */
469 
470 /*
471 ** CAPI3REF: Database Connection Handle
472 ** KEYWORDS: {database connection} {database connections}
473 **
474 ** Each open SQLite database is represented by a pointer to an instance of
475 ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
476 ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
477 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
478 ** and [sqlite3_close_v2()] are its destructors. There are many other
479 ** interfaces (such as
480 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
481 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
482 ** sqlite3 object.
483 */
484 typedef struct sqlite3 sqlite3;
485 
486 /*
487 ** CAPI3REF: 64-Bit Integer Types
488 ** KEYWORDS: sqlite_int64 sqlite_uint64
489 **
490 ** Because there is no cross-platform way to specify 64-bit integer types
491 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
492 **
493 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
494 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
495 ** compatibility only.
496 **
497 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
498 ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
499 ** sqlite3_uint64 and sqlite_uint64 types can store integer values
500 ** between 0 and +18446744073709551615 inclusive.
501 */
502 #ifdef SQLITE_INT64_TYPE
503  typedef SQLITE_INT64_TYPE sqlite_int64;
504  typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
505 #elif defined(_MSC_VER) || defined(__BORLANDC__)
506  typedef __int64 sqlite_int64;
507  typedef unsigned __int64 sqlite_uint64;
508 #else
509  typedef long long int sqlite_int64;
510  typedef unsigned long long int sqlite_uint64;
511 #endif
512 typedef sqlite_int64 sqlite3_int64;
513 typedef sqlite_uint64 sqlite3_uint64;
514 
515 /*
516 ** If compiling for a processor that lacks floating point support,
517 ** substitute integer for floating-point.
518 */
519 #ifdef SQLITE_OMIT_FLOATING_POINT
520 # define double sqlite3_int64
521 #endif
522 
523 /*
524 ** CAPI3REF: Closing A Database Connection
525 ** DESTRUCTOR: sqlite3
526 **
527 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
528 ** for the [sqlite3] object.
529 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
530 ** the [sqlite3] object is successfully destroyed and all associated
531 ** resources are deallocated.
532 **
533 ** ^If the database connection is associated with unfinalized prepared
534 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
535 ** will leave the database connection open and return [SQLITE_BUSY].
536 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
537 ** and/or unfinished sqlite3_backups, then the database connection becomes
538 ** an unusable "zombie" which will automatically be deallocated when the
539 ** last prepared statement is finalized or the last sqlite3_backup is
540 ** finished. The sqlite3_close_v2() interface is intended for use with
541 ** host languages that are garbage collected, and where the order in which
542 ** destructors are called is arbitrary.
543 **
544 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
545 ** [sqlite3_blob_close | close] all [BLOB handles], and
546 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
547 ** with the [sqlite3] object prior to attempting to close the object. ^If
548 ** sqlite3_close_v2() is called on a [database connection] that still has
549 ** outstanding [prepared statements], [BLOB handles], and/or
550 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
551 ** of resources is deferred until all [prepared statements], [BLOB handles],
552 ** and [sqlite3_backup] objects are also destroyed.
553 **
554 ** ^If an [sqlite3] object is destroyed while a transaction is open,
555 ** the transaction is automatically rolled back.
556 **
557 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
558 ** must be either a NULL
559 ** pointer or an [sqlite3] object pointer obtained
560 ** from [sqlite3_open()], [sqlite3_open16()], or
561 ** [sqlite3_open_v2()], and not previously closed.
562 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
563 ** argument is a harmless no-op.
564 */
567 
568 /*
569 ** The type for a callback function.
570 ** This is legacy and deprecated. It is included for historical
571 ** compatibility and is not documented.
572 */
573 typedef int (*sqlite3_callback)(void*,int,char**, char**);
574 
575 /*
576 ** CAPI3REF: One-Step Query Execution Interface
577 ** METHOD: sqlite3
578 **
579 ** The sqlite3_exec() interface is a convenience wrapper around
580 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
581 ** that allows an application to run multiple statements of SQL
582 ** without having to use a lot of C code.
583 **
584 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
585 ** semicolon-separate SQL statements passed into its 2nd argument,
586 ** in the context of the [database connection] passed in as its 1st
587 ** argument. ^If the callback function of the 3rd argument to
588 ** sqlite3_exec() is not NULL, then it is invoked for each result row
589 ** coming out of the evaluated SQL statements. ^The 4th argument to
590 ** sqlite3_exec() is relayed through to the 1st argument of each
591 ** callback invocation. ^If the callback pointer to sqlite3_exec()
592 ** is NULL, then no callback is ever invoked and result rows are
593 ** ignored.
594 **
595 ** ^If an error occurs while evaluating the SQL statements passed into
596 ** sqlite3_exec(), then execution of the current statement stops and
597 ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
598 ** is not NULL then any error message is written into memory obtained
599 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
600 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
601 ** on error message strings returned through the 5th parameter of
602 ** sqlite3_exec() after the error message string is no longer needed.
603 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
604 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
605 ** NULL before returning.
606 **
607 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
608 ** routine returns SQLITE_ABORT without invoking the callback again and
609 ** without running any subsequent SQL statements.
610 **
611 ** ^The 2nd argument to the sqlite3_exec() callback function is the
612 ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
613 ** callback is an array of pointers to strings obtained as if from
614 ** [sqlite3_column_text()], one for each column. ^If an element of a
615 ** result row is NULL then the corresponding string pointer for the
616 ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
617 ** sqlite3_exec() callback is an array of pointers to strings where each
618 ** entry represents the name of corresponding result column as obtained
619 ** from [sqlite3_column_name()].
620 **
621 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
622 ** to an empty string, or a pointer that contains only whitespace and/or
623 ** SQL comments, then no SQL statements are evaluated and the database
624 ** is not changed.
625 **
626 ** Restrictions:
627 **
628 ** <ul>
629 ** <li> The application must ensure that the 1st parameter to sqlite3_exec()
630 ** is a valid and open [database connection].
631 ** <li> The application must not close the [database connection] specified by
632 ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
633 ** <li> The application must not modify the SQL statement text passed into
634 ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
635 ** </ul>
636 */
638  sqlite3*, /* An open database */
639  const char *sql, /* SQL to be evaluated */
640  int (*callback)(void*,int,char**,char**), /* Callback function */
641  void *, /* 1st argument to callback */
642  char **errmsg /* Error msg written here */
643 );
644 
645 /*
646 ** CAPI3REF: Result Codes
647 ** KEYWORDS: {result code definitions}
648 **
649 ** Many SQLite functions return an integer result code from the set shown
650 ** here in order to indicate success or failure.
651 **
652 ** New error codes may be added in future versions of SQLite.
653 **
654 ** See also: [extended result code definitions]
655 */
656 #define SQLITE_OK 0 /* Successful result */
657 /* beginning-of-error-codes */
658 #define SQLITE_ERROR 1 /* SQL error or missing database */
659 #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
660 #define SQLITE_PERM 3 /* Access permission denied */
661 #define SQLITE_ABORT 4 /* Callback routine requested an abort */
662 #define SQLITE_BUSY 5 /* The database file is locked */
663 #define SQLITE_LOCKED 6 /* A table in the database is locked */
664 #define SQLITE_NOMEM 7 /* A malloc() failed */
665 #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
666 #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
667 #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
668 #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
669 #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
670 #define SQLITE_FULL 13 /* Insertion failed because database is full */
671 #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
672 #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
673 #define SQLITE_EMPTY 16 /* Database is empty */
674 #define SQLITE_SCHEMA 17 /* The database schema changed */
675 #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
676 #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
677 #define SQLITE_MISMATCH 20 /* Data type mismatch */
678 #define SQLITE_MISUSE 21 /* Library used incorrectly */
679 #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
680 #define SQLITE_AUTH 23 /* Authorization denied */
681 #define SQLITE_FORMAT 24 /* Auxiliary database format error */
682 #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
683 #define SQLITE_NOTADB 26 /* File opened that is not a database file */
684 #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
685 #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
686 #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
687 #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
688 /* end-of-error-codes */
689 
690 /*
691 ** CAPI3REF: Extended Result Codes
692 ** KEYWORDS: {extended result code definitions}
693 **
694 ** In its default configuration, SQLite API routines return one of 30 integer
695 ** [result codes]. However, experience has shown that many of
696 ** these result codes are too coarse-grained. They do not provide as
697 ** much information about problems as programmers might like. In an effort to
698 ** address this, newer versions of SQLite (version 3.3.8 and later) include
699 ** support for additional result codes that provide more detailed information
700 ** about errors. These [extended result codes] are enabled or disabled
701 ** on a per database connection basis using the
702 ** [sqlite3_extended_result_codes()] API. Or, the extended code for
703 ** the most recent error can be obtained using
704 ** [sqlite3_extended_errcode()].
705 */
706 #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
707 #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
708 #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
709 #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
710 #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
711 #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
712 #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
713 #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
714 #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
715 #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
716 #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
717 #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
718 #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
719 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
720 #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
721 #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
722 #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
723 #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
724 #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
725 #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
726 #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
727 #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
728 #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
729 #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
730 #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
731 #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
732 #define SQLITE_IOERR_VNODE (SQLITE_IOERR | (27<<8))
733 #define SQLITE_IOERR_AUTH (SQLITE_IOERR | (28<<8))
734 #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
735 #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
736 #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
737 #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
738 #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
739 #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
740 #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
741 #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
742 #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
743 #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
744 #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
745 #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
746 #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
747 #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
748 #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
749 #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
750 #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
751 #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
752 #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
753 #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
754 #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
755 #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
756 #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
757 #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
758 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
759 #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
760 #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
761 
762 /*
763 ** CAPI3REF: Flags For File Open Operations
764 **
765 ** These bit values are intended for use in the
766 ** 3rd parameter to the [sqlite3_open_v2()] interface and
767 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
768 */
769 #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
770 #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
771 #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
772 #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
773 #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
774 #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
775 #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
776 #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
777 #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
778 #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
779 #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
780 #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
781 #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
782 #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
783 #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
784 #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
785 #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
786 #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
787 #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
788 #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
789 
790 /* Reserved: 0x00F00000 */
791 
792 /*
793 ** CAPI3REF: Device Characteristics
794 **
795 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
796 ** object returns an integer which is a vector of these
797 ** bit values expressing I/O characteristics of the mass storage
798 ** device that holds the file that the [sqlite3_io_methods]
799 ** refers to.
800 **
801 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
802 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
803 ** mean that writes of blocks that are nnn bytes in size and
804 ** are aligned to an address which is an integer multiple of
805 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
806 ** that when data is appended to a file, the data is appended
807 ** first then the size of the file is extended, never the other
808 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
809 ** information is written to disk in the same order as calls
810 ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
811 ** after reboot following a crash or power loss, the only bytes in a
812 ** file that were written at the application level might have changed
813 ** and that adjacent bytes, even bytes within the same sector are
814 ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
815 ** flag indicate that a file cannot be deleted when open. The
816 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
817 ** read-only media and cannot be changed even by processes with
818 ** elevated privileges.
819 */
820 #define SQLITE_IOCAP_ATOMIC 0x00000001
821 #define SQLITE_IOCAP_ATOMIC512 0x00000002
822 #define SQLITE_IOCAP_ATOMIC1K 0x00000004
823 #define SQLITE_IOCAP_ATOMIC2K 0x00000008
824 #define SQLITE_IOCAP_ATOMIC4K 0x00000010
825 #define SQLITE_IOCAP_ATOMIC8K 0x00000020
826 #define SQLITE_IOCAP_ATOMIC16K 0x00000040
827 #define SQLITE_IOCAP_ATOMIC32K 0x00000080
828 #define SQLITE_IOCAP_ATOMIC64K 0x00000100
829 #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
830 #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
831 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
832 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
833 #define SQLITE_IOCAP_IMMUTABLE 0x00002000
834 
835 /*
836 ** CAPI3REF: File Locking Levels
837 **
838 ** SQLite uses one of these integer values as the second
839 ** argument to calls it makes to the xLock() and xUnlock() methods
840 ** of an [sqlite3_io_methods] object.
841 */
842 #define SQLITE_LOCK_NONE 0
843 #define SQLITE_LOCK_SHARED 1
844 #define SQLITE_LOCK_RESERVED 2
845 #define SQLITE_LOCK_PENDING 3
846 #define SQLITE_LOCK_EXCLUSIVE 4
847 
848 /*
849 ** CAPI3REF: Synchronization Type Flags
850 **
851 ** When SQLite invokes the xSync() method of an
852 ** [sqlite3_io_methods] object it uses a combination of
853 ** these integer values as the second argument.
854 **
855 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
856 ** sync operation only needs to flush data to mass storage. Inode
857 ** information need not be flushed. If the lower four bits of the flag
858 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
859 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
860 ** to use Mac OS X style fullsync instead of fsync().
861 **
862 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
863 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
864 ** settings. The [synchronous pragma] determines when calls to the
865 ** xSync VFS method occur and applies uniformly across all platforms.
866 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
867 ** energetic or rigorous or forceful the sync operations are and
868 ** only make a difference on Mac OSX for the default SQLite code.
869 ** (Third-party VFS implementations might also make the distinction
870 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
871 ** operating systems natively supported by SQLite, only Mac OSX
872 ** cares about the difference.)
873 */
874 #define SQLITE_SYNC_NORMAL 0x00002
875 #define SQLITE_SYNC_FULL 0x00003
876 #define SQLITE_SYNC_DATAONLY 0x00010
877 
878 /*
879 ** CAPI3REF: OS Interface Open File Handle
880 **
881 ** An [sqlite3_file] object represents an open file in the
882 ** [sqlite3_vfs | OS interface layer]. Individual OS interface
883 ** implementations will
884 ** want to subclass this object by appending additional fields
885 ** for their own use. The pMethods entry is a pointer to an
886 ** [sqlite3_io_methods] object that defines methods for performing
887 ** I/O operations on the open file.
888 */
889 typedef struct sqlite3_file sqlite3_file;
890 struct sqlite3_file {
891  const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
892 };
893 
894 /*
895 ** CAPI3REF: OS Interface File Virtual Methods Object
896 **
897 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
898 ** [sqlite3_file] object (or, more commonly, a subclass of the
899 ** [sqlite3_file] object) with a pointer to an instance of this object.
900 ** This object defines the methods used to perform various operations
901 ** against the open file represented by the [sqlite3_file] object.
902 **
903 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
904 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
905 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
906 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
907 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
908 ** to NULL.
909 **
910 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
911 ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
912 ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
913 ** flag may be ORed in to indicate that only the data of the file
914 ** and not its inode needs to be synced.
915 **
916 ** The integer values to xLock() and xUnlock() are one of
917 ** <ul>
918 ** <li> [SQLITE_LOCK_NONE],
919 ** <li> [SQLITE_LOCK_SHARED],
920 ** <li> [SQLITE_LOCK_RESERVED],
921 ** <li> [SQLITE_LOCK_PENDING], or
922 ** <li> [SQLITE_LOCK_EXCLUSIVE].
923 ** </ul>
924 ** xLock() increases the lock. xUnlock() decreases the lock.
925 ** The xCheckReservedLock() method checks whether any database connection,
926 ** either in this process or in some other process, is holding a RESERVED,
927 ** PENDING, or EXCLUSIVE lock on the file. It returns true
928 ** if such a lock exists and false otherwise.
929 **
930 ** The xFileControl() method is a generic interface that allows custom
931 ** VFS implementations to directly control an open file using the
932 ** [sqlite3_file_control()] interface. The second "op" argument is an
933 ** integer opcode. The third argument is a generic pointer intended to
934 ** point to a structure that may contain arguments or space in which to
935 ** write return values. Potential uses for xFileControl() might be
936 ** functions to enable blocking locks with timeouts, to change the
937 ** locking strategy (for example to use dot-file locks), to inquire
938 ** about the status of a lock, or to break stale locks. The SQLite
939 ** core reserves all opcodes less than 100 for its own use.
940 ** A [file control opcodes | list of opcodes] less than 100 is available.
941 ** Applications that define a custom xFileControl method should use opcodes
942 ** greater than 100 to avoid conflicts. VFS implementations should
943 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
944 ** recognize.
945 **
946 ** The xSectorSize() method returns the sector size of the
947 ** device that underlies the file. The sector size is the
948 ** minimum write that can be performed without disturbing
949 ** other bytes in the file. The xDeviceCharacteristics()
950 ** method returns a bit vector describing behaviors of the
951 ** underlying device:
952 **
953 ** <ul>
954 ** <li> [SQLITE_IOCAP_ATOMIC]
955 ** <li> [SQLITE_IOCAP_ATOMIC512]
956 ** <li> [SQLITE_IOCAP_ATOMIC1K]
957 ** <li> [SQLITE_IOCAP_ATOMIC2K]
958 ** <li> [SQLITE_IOCAP_ATOMIC4K]
959 ** <li> [SQLITE_IOCAP_ATOMIC8K]
960 ** <li> [SQLITE_IOCAP_ATOMIC16K]
961 ** <li> [SQLITE_IOCAP_ATOMIC32K]
962 ** <li> [SQLITE_IOCAP_ATOMIC64K]
963 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
964 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
965 ** </ul>
966 **
967 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
968 ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
969 ** mean that writes of blocks that are nnn bytes in size and
970 ** are aligned to an address which is an integer multiple of
971 ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
972 ** that when data is appended to a file, the data is appended
973 ** first then the size of the file is extended, never the other
974 ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
975 ** information is written to disk in the same order as calls
976 ** to xWrite().
977 **
978 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
979 ** in the unread portions of the buffer with zeros. A VFS that
980 ** fails to zero-fill short reads might seem to work. However,
981 ** failure to zero-fill short reads will eventually lead to
982 ** database corruption.
983 */
986  int iVersion;
987  int (*xClose)(sqlite3_file*);
988  int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
989  int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
990  int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
991  int (*xSync)(sqlite3_file*, int flags);
992  int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
993  int (*xLock)(sqlite3_file*, int);
994  int (*xUnlock)(sqlite3_file*, int);
995  int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
996  int (*xFileControl)(sqlite3_file*, int op, void *pArg);
997  int (*xSectorSize)(sqlite3_file*);
998  int (*xDeviceCharacteristics)(sqlite3_file*);
999  /* Methods above are valid for version 1 */
1000  int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
1001  int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
1002  void (*xShmBarrier)(sqlite3_file*);
1003  int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
1004  /* Methods above are valid for version 2 */
1005  int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
1006  int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
1007  /* Methods above are valid for version 3 */
1008  /* Additional methods may be added in future releases */
1009 };
1010 
1011 /*
1012 ** CAPI3REF: Standard File Control Opcodes
1013 ** KEYWORDS: {file control opcodes} {file control opcode}
1014 **
1015 ** These integer constants are opcodes for the xFileControl method
1016 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1017 ** interface.
1018 **
1019 ** <ul>
1020 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
1021 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
1022 ** opcode causes the xFileControl method to write the current state of
1023 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1024 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1025 ** into an integer that the pArg argument points to. This capability
1026 ** is used during testing and is only available when the SQLITE_TEST
1027 ** compile-time option is used.
1028 **
1029 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
1030 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
1031 ** layer a hint of how large the database file will grow to be during the
1032 ** current transaction. This hint is not guaranteed to be accurate but it
1033 ** is often close. The underlying VFS might choose to preallocate database
1034 ** file space based on this hint in order to help writes to the database
1035 ** file run faster.
1036 **
1037 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
1038 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
1039 ** extends and truncates the database file in chunks of a size specified
1040 ** by the user. The fourth argument to [sqlite3_file_control()] should
1041 ** point to an integer (type int) containing the new chunk-size to use
1042 ** for the nominated database. Allocating database file space in large
1043 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
1044 ** improve performance on some systems.
1045 **
1046 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
1047 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
1048 ** to the [sqlite3_file] object associated with a particular database
1049 ** connection. See also [SQLITE_FCNTL_JOURNAL_POINTER].
1050 **
1051 ** <li>[[SQLITE_FCNTL_JOURNAL_POINTER]]
1052 ** The [SQLITE_FCNTL_JOURNAL_POINTER] opcode is used to obtain a pointer
1053 ** to the [sqlite3_file] object associated with the journal file (either
1054 ** the [rollback journal] or the [write-ahead log]) for a particular database
1055 ** connection. See also [SQLITE_FCNTL_FILE_POINTER].
1056 **
1057 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1058 ** No longer in use.
1059 **
1060 ** <li>[[SQLITE_FCNTL_SYNC]]
1061 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1062 ** sent to the VFS immediately before the xSync method is invoked on a
1063 ** database file descriptor. Or, if the xSync method is not invoked
1064 ** because the user has configured SQLite with
1065 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
1066 ** of the xSync method. In most cases, the pointer argument passed with
1067 ** this file-control is NULL. However, if the database file is being synced
1068 ** as part of a multi-database commit, the argument points to a nul-terminated
1069 ** string containing the transactions master-journal file name. VFSes that
1070 ** do not need this signal should silently ignore this opcode. Applications
1071 ** should not call [sqlite3_file_control()] with this opcode as doing so may
1072 ** disrupt the operation of the specialized VFSes that do require it.
1073 **
1074 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1075 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1076 ** and sent to the VFS after a transaction has been committed immediately
1077 ** but before the database is unlocked. VFSes that do not need this signal
1078 ** should silently ignore this opcode. Applications should not call
1079 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
1080 ** operation of the specialized VFSes that do require it.
1081 **
1082 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1083 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1084 ** retry counts and intervals for certain disk I/O operations for the
1085 ** windows [VFS] in order to provide robustness in the presence of
1086 ** anti-virus programs. By default, the windows VFS will retry file read,
1087 ** file write, and file delete operations up to 10 times, with a delay
1088 ** of 25 milliseconds before the first retry and with the delay increasing
1089 ** by an additional 25 milliseconds with each subsequent retry. This
1090 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1091 ** to be adjusted. The values are changed for all database connections
1092 ** within the same process. The argument is a pointer to an array of two
1093 ** integers where the first integer i the new retry count and the second
1094 ** integer is the delay. If either integer is negative, then the setting
1095 ** is not changed but instead the prior value of that setting is written
1096 ** into the array entry, allowing the current retry settings to be
1097 ** interrogated. The zDbName parameter is ignored.
1098 **
1099 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1100 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1101 ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
1102 ** write ahead log and shared memory files used for transaction control
1103 ** are automatically deleted when the latest connection to the database
1104 ** closes. Setting persistent WAL mode causes those files to persist after
1105 ** close. Persisting the files is useful when other processes that do not
1106 ** have write permission on the directory containing the database file want
1107 ** to read the database file, as the WAL and shared memory files must exist
1108 ** in order for the database to be readable. The fourth parameter to
1109 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1110 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1111 ** WAL mode. If the integer is -1, then it is overwritten with the current
1112 ** WAL persistence setting.
1113 **
1114 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1115 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1116 ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
1117 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1118 ** xDeviceCharacteristics methods. The fourth parameter to
1119 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1120 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1121 ** mode. If the integer is -1, then it is overwritten with the current
1122 ** zero-damage mode setting.
1123 **
1124 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1125 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1126 ** a write transaction to indicate that, unless it is rolled back for some
1127 ** reason, the entire database file will be overwritten by the current
1128 ** transaction. This is used by VACUUM operations.
1129 **
1130 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1131 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1132 ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
1133 ** final bottom-level VFS are written into memory obtained from
1134 ** [sqlite3_malloc()] and the result is stored in the char* variable
1135 ** that the fourth parameter of [sqlite3_file_control()] points to.
1136 ** The caller is responsible for freeing the memory when done. As with
1137 ** all file-control actions, there is no guarantee that this will actually
1138 ** do anything. Callers should initialize the char* variable to a NULL
1139 ** pointer in case this file-control is not implemented. This file-control
1140 ** is intended for diagnostic use only.
1141 **
1142 ** <li>[[SQLITE_FCNTL_VFS_POINTER]]
1143 ** ^The [SQLITE_FCNTL_VFS_POINTER] opcode finds a pointer to the top-level
1144 ** [VFSes] currently in use. ^(The argument X in
1145 ** sqlite3_file_control(db,SQLITE_FCNTL_VFS_POINTER,X) must be
1146 ** of type "[sqlite3_vfs] **". This opcodes will set *X
1147 ** to a pointer to the top-level VFS.)^
1148 ** ^When there are multiple VFS shims in the stack, this opcode finds the
1149 ** upper-most shim only.
1150 **
1151 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1152 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
1153 ** file control is sent to the open [sqlite3_file] object corresponding
1154 ** to the database file to which the pragma statement refers. ^The argument
1155 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1156 ** pointers to strings (char**) in which the second element of the array
1157 ** is the name of the pragma and the third element is the argument to the
1158 ** pragma or NULL if the pragma has no argument. ^The handler for an
1159 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1160 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1161 ** or the equivalent and that string will become the result of the pragma or
1162 ** the error message if the pragma fails. ^If the
1163 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
1164 ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
1165 ** file control returns [SQLITE_OK], then the parser assumes that the
1166 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1167 ** prepared statement if result string is NULL, or that returns a copy
1168 ** of the result string if the string is non-NULL.
1169 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1170 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1171 ** that the VFS encountered an error while handling the [PRAGMA] and the
1172 ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
1173 ** file control occurs at the beginning of pragma statement analysis and so
1174 ** it is able to override built-in [PRAGMA] statements.
1175 **
1176 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1177 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1178 ** file-control may be invoked by SQLite on the database file handle
1179 ** shortly after it is opened in order to provide a custom VFS with access
1180 ** to the connections busy-handler callback. The argument is of type (void **)
1181 ** - an array of two (void *) values. The first (void *) actually points
1182 ** to a function of type (int (*)(void *)). In order to invoke the connections
1183 ** busy-handler, this function should be invoked with the second (void *) in
1184 ** the array as the only argument. If it returns non-zero, then the operation
1185 ** should be retried. If it returns zero, the custom VFS should abandon the
1186 ** current operation.
1187 **
1188 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1189 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1190 ** to have SQLite generate a
1191 ** temporary filename using the same algorithm that is followed to generate
1192 ** temporary filenames for TEMP tables and other internal uses. The
1193 ** argument should be a char** which will be filled with the filename
1194 ** written into memory obtained from [sqlite3_malloc()]. The caller should
1195 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1196 **
1197 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1198 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1199 ** maximum number of bytes that will be used for memory-mapped I/O.
1200 ** The argument is a pointer to a value of type sqlite3_int64 that
1201 ** is an advisory maximum number of bytes in the file to memory map. The
1202 ** pointer is overwritten with the old value. The limit is not changed if
1203 ** the value originally pointed to is negative, and so the current limit
1204 ** can be queried by passing in a pointer to a negative number. This
1205 ** file-control is used internally to implement [PRAGMA mmap_size].
1206 **
1207 ** <li>[[SQLITE_FCNTL_TRACE]]
1208 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1209 ** to the VFS about what the higher layers of the SQLite stack are doing.
1210 ** This file control is used by some VFS activity tracing [shims].
1211 ** The argument is a zero-terminated string. Higher layers in the
1212 ** SQLite stack may generate instances of this file control if
1213 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1214 **
1215 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1216 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1217 ** pointer to an integer and it writes a boolean into that integer depending
1218 ** on whether or not the file has been renamed, moved, or deleted since it
1219 ** was first opened.
1220 **
1221 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1222 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
1223 ** opcode causes the xFileControl method to swap the file handle with the one
1224 ** pointed to by the pArg argument. This capability is used during testing
1225 ** and only needs to be supported when SQLITE_TEST is defined.
1226 **
1227 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1228 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1229 ** be advantageous to block on the next WAL lock if the lock is not immediately
1230 ** available. The WAL subsystem issues this signal during rare
1231 ** circumstances in order to fix a problem with priority inversion.
1232 ** Applications should <em>not</em> use this file-control.
1233 **
1234 ** <li>[[SQLITE_FCNTL_ZIPVFS]]
1235 ** The [SQLITE_FCNTL_ZIPVFS] opcode is implemented by zipvfs only. All other
1236 ** VFS should return SQLITE_NOTFOUND for this opcode.
1237 **
1238 ** <li>[[SQLITE_FCNTL_RBU]]
1239 ** The [SQLITE_FCNTL_RBU] opcode is implemented by the special VFS used by
1240 ** the RBU extension only. All other VFS should return SQLITE_NOTFOUND for
1241 ** this opcode.
1242 ** </ul>
1243 */
1244 #define SQLITE_FCNTL_LOCKSTATE 1
1245 #define SQLITE_FCNTL_GET_LOCKPROXYFILE 2
1246 #define SQLITE_FCNTL_SET_LOCKPROXYFILE 3
1247 #define SQLITE_FCNTL_LAST_ERRNO 4
1248 #define SQLITE_FCNTL_SIZE_HINT 5
1249 #define SQLITE_FCNTL_CHUNK_SIZE 6
1250 #define SQLITE_FCNTL_FILE_POINTER 7
1251 #define SQLITE_FCNTL_SYNC_OMITTED 8
1252 #define SQLITE_FCNTL_WIN32_AV_RETRY 9
1253 #define SQLITE_FCNTL_PERSIST_WAL 10
1254 #define SQLITE_FCNTL_OVERWRITE 11
1255 #define SQLITE_FCNTL_VFSNAME 12
1256 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
1257 #define SQLITE_FCNTL_PRAGMA 14
1258 #define SQLITE_FCNTL_BUSYHANDLER 15
1259 #define SQLITE_FCNTL_TEMPFILENAME 16
1260 #define SQLITE_FCNTL_MMAP_SIZE 18
1261 #define SQLITE_FCNTL_TRACE 19
1262 #define SQLITE_FCNTL_HAS_MOVED 20
1263 #define SQLITE_FCNTL_SYNC 21
1264 #define SQLITE_FCNTL_COMMIT_PHASETWO 22
1265 #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
1266 #define SQLITE_FCNTL_WAL_BLOCK 24
1267 #define SQLITE_FCNTL_ZIPVFS 25
1268 #define SQLITE_FCNTL_RBU 26
1269 #define SQLITE_FCNTL_VFS_POINTER 27
1270 #define SQLITE_FCNTL_JOURNAL_POINTER 28
1271 
1272 /* deprecated names */
1273 #define SQLITE_GET_LOCKPROXYFILE SQLITE_FCNTL_GET_LOCKPROXYFILE
1274 #define SQLITE_SET_LOCKPROXYFILE SQLITE_FCNTL_SET_LOCKPROXYFILE
1275 #define SQLITE_LAST_ERRNO SQLITE_FCNTL_LAST_ERRNO
1276 
1277 
1278 /*
1279 ** CAPI3REF: Mutex Handle
1280 **
1281 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1282 ** abstract type for a mutex object. The SQLite core never looks
1283 ** at the internal representation of an [sqlite3_mutex]. It only
1284 ** deals with pointers to the [sqlite3_mutex] object.
1285 **
1286 ** Mutexes are created using [sqlite3_mutex_alloc()].
1287 */
1289 
1290 /*
1291 ** CAPI3REF: OS Interface Object
1292 **
1293 ** An instance of the sqlite3_vfs object defines the interface between
1294 ** the SQLite core and the underlying operating system. The "vfs"
1295 ** in the name of the object stands for "virtual file system". See
1296 ** the [VFS | VFS documentation] for further information.
1297 **
1298 ** The value of the iVersion field is initially 1 but may be larger in
1299 ** future versions of SQLite. Additional fields may be appended to this
1300 ** object when the iVersion value is increased. Note that the structure
1301 ** of the sqlite3_vfs object changes in the transaction between
1302 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1303 ** modified.
1304 **
1305 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1306 ** structure used by this VFS. mxPathname is the maximum length of
1307 ** a pathname in this VFS.
1308 **
1309 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1310 ** the pNext pointer. The [sqlite3_vfs_register()]
1311 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1312 ** in a thread-safe way. The [sqlite3_vfs_find()] interface
1313 ** searches the list. Neither the application code nor the VFS
1314 ** implementation should use the pNext pointer.
1315 **
1316 ** The pNext field is the only field in the sqlite3_vfs
1317 ** structure that SQLite will ever modify. SQLite will only access
1318 ** or modify this field while holding a particular static mutex.
1319 ** The application should never modify anything within the sqlite3_vfs
1320 ** object once the object has been registered.
1321 **
1322 ** The zName field holds the name of the VFS module. The name must
1323 ** be unique across all VFS modules.
1324 **
1325 ** [[sqlite3_vfs.xOpen]]
1326 ** ^SQLite guarantees that the zFilename parameter to xOpen
1327 ** is either a NULL pointer or string obtained
1328 ** from xFullPathname() with an optional suffix added.
1329 ** ^If a suffix is added to the zFilename parameter, it will
1330 ** consist of a single "-" character followed by no more than
1331 ** 11 alphanumeric and/or "-" characters.
1332 ** ^SQLite further guarantees that
1333 ** the string will be valid and unchanged until xClose() is
1334 ** called. Because of the previous sentence,
1335 ** the [sqlite3_file] can safely store a pointer to the
1336 ** filename if it needs to remember the filename for some reason.
1337 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1338 ** must invent its own temporary name for the file. ^Whenever the
1339 ** xFilename parameter is NULL it will also be the case that the
1340 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1341 **
1342 ** The flags argument to xOpen() includes all bits set in
1343 ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
1344 ** or [sqlite3_open16()] is used, then flags includes at least
1345 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
1346 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1347 ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
1348 **
1349 ** ^(SQLite will also add one of the following flags to the xOpen()
1350 ** call, depending on the object being opened:
1351 **
1352 ** <ul>
1353 ** <li> [SQLITE_OPEN_MAIN_DB]
1354 ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
1355 ** <li> [SQLITE_OPEN_TEMP_DB]
1356 ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
1357 ** <li> [SQLITE_OPEN_TRANSIENT_DB]
1358 ** <li> [SQLITE_OPEN_SUBJOURNAL]
1359 ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
1360 ** <li> [SQLITE_OPEN_WAL]
1361 ** </ul>)^
1362 **
1363 ** The file I/O implementation can use the object type flags to
1364 ** change the way it deals with files. For example, an application
1365 ** that does not care about crash recovery or rollback might make
1366 ** the open of a journal file a no-op. Writes to this journal would
1367 ** also be no-ops, and any attempt to read the journal would return
1368 ** SQLITE_IOERR. Or the implementation might recognize that a database
1369 ** file will be doing page-aligned sector reads and writes in a random
1370 ** order and set up its I/O subsystem accordingly.
1371 **
1372 ** SQLite might also add one of the following flags to the xOpen method:
1373 **
1374 ** <ul>
1375 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1376 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1377 ** </ul>
1378 **
1379 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1380 ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
1381 ** will be set for TEMP databases and their journals, transient
1382 ** databases, and subjournals.
1383 **
1384 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1385 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1386 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1387 ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
1388 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1389 ** be created, and that it is an error if it already exists.
1390 ** It is <i>not</i> used to indicate the file should be opened
1391 ** for exclusive access.
1392 **
1393 ** ^At least szOsFile bytes of memory are allocated by SQLite
1394 ** to hold the [sqlite3_file] structure passed as the third
1395 ** argument to xOpen. The xOpen method does not have to
1396 ** allocate the structure; it should just fill it in. Note that
1397 ** the xOpen method must set the sqlite3_file.pMethods to either
1398 ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
1399 ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
1400 ** element will be valid after xOpen returns regardless of the success
1401 ** or failure of the xOpen call.
1402 **
1403 ** [[sqlite3_vfs.xAccess]]
1404 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1405 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1406 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1407 ** to test whether a file is at least readable. The file can be a
1408 ** directory.
1409 **
1410 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1411 ** output buffer xFullPathname. The exact size of the output buffer
1412 ** is also passed as a parameter to both methods. If the output buffer
1413 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1414 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1415 ** to prevent this by setting mxPathname to a sufficiently large value.
1416 **
1417 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1418 ** interfaces are not strictly a part of the filesystem, but they are
1419 ** included in the VFS structure for completeness.
1420 ** The xRandomness() function attempts to return nBytes bytes
1421 ** of good-quality randomness into zOut. The return value is
1422 ** the actual number of bytes of randomness obtained.
1423 ** The xSleep() method causes the calling thread to sleep for at
1424 ** least the number of microseconds given. ^The xCurrentTime()
1425 ** method returns a Julian Day Number for the current date and time as
1426 ** a floating point value.
1427 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1428 ** Day Number multiplied by 86400000 (the number of milliseconds in
1429 ** a 24-hour day).
1430 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1431 ** date and time if that method is available (if iVersion is 2 or
1432 ** greater and the function pointer is not NULL) and will fall back
1433 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1434 **
1435 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1436 ** are not used by the SQLite core. These optional interfaces are provided
1437 ** by some VFSes to facilitate testing of the VFS code. By overriding
1438 ** system calls with functions under its control, a test program can
1439 ** simulate faults and error conditions that would otherwise be difficult
1440 ** or impossible to induce. The set of system calls that can be overridden
1441 ** varies from one VFS to another, and from one version of the same VFS to the
1442 ** next. Applications that use these interfaces must be prepared for any
1443 ** or all of these interfaces to be NULL or for their behavior to change
1444 ** from one release to the next. Applications must not attempt to access
1445 ** any of these methods if the iVersion of the VFS is less than 3.
1446 */
1447 typedef struct sqlite3_vfs sqlite3_vfs;
1449 struct sqlite3_vfs {
1450  int iVersion; /* Structure version number (currently 3) */
1451  int szOsFile; /* Size of subclassed sqlite3_file */
1452  int mxPathname; /* Maximum file pathname length */
1453  sqlite3_vfs *pNext; /* Next registered VFS */
1454  const char *zName; /* Name of this virtual file system */
1455  void *pAppData; /* Pointer to application-specific data */
1456  int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1457  int flags, int *pOutFlags);
1458  int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1459  int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1460  int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1461  void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1462  void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1463  void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1464  void (*xDlClose)(sqlite3_vfs*, void*);
1465  int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1466  int (*xSleep)(sqlite3_vfs*, int microseconds);
1467  int (*xCurrentTime)(sqlite3_vfs*, double*);
1468  int (*xGetLastError)(sqlite3_vfs*, int, char *);
1469  /*
1470  ** The methods above are in version 1 of the sqlite_vfs object
1471  ** definition. Those that follow are added in version 2 or later
1472  */
1473  int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1474  /*
1475  ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1476  ** Those below are for version 3 and greater.
1477  */
1478  int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1479  sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1480  const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1481  /*
1482  ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1483  ** New fields may be appended in future versions. The iVersion
1484  ** value will increment whenever this happens.
1485  */
1486 };
1487 
1488 /*
1489 ** CAPI3REF: Flags for the xAccess VFS method
1490 **
1491 ** These integer constants can be used as the third parameter to
1492 ** the xAccess method of an [sqlite3_vfs] object. They determine
1493 ** what kind of permissions the xAccess method is looking for.
1494 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1495 ** simply checks whether the file exists.
1496 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1497 ** checks whether the named directory is both readable and writable
1498 ** (in other words, if files can be added, removed, and renamed within
1499 ** the directory).
1500 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1501 ** [temp_store_directory pragma], though this could change in a future
1502 ** release of SQLite.
1503 ** With SQLITE_ACCESS_READ, the xAccess method
1504 ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
1505 ** currently unused, though it might be used in a future release of
1506 ** SQLite.
1507 */
1508 #define SQLITE_ACCESS_EXISTS 0
1509 #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
1510 #define SQLITE_ACCESS_READ 2 /* Unused */
1511 
1512 /*
1513 ** CAPI3REF: Flags for the xShmLock VFS method
1514 **
1515 ** These integer constants define the various locking operations
1516 ** allowed by the xShmLock method of [sqlite3_io_methods]. The
1517 ** following are the only legal combinations of flags to the
1518 ** xShmLock method:
1519 **
1520 ** <ul>
1521 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1522 ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1523 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1524 ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1525 ** </ul>
1526 **
1527 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1528 ** was given on the corresponding lock.
1529 **
1530 ** The xShmLock method can transition between unlocked and SHARED or
1531 ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
1532 ** and EXCLUSIVE.
1533 */
1534 #define SQLITE_SHM_UNLOCK 1
1535 #define SQLITE_SHM_LOCK 2
1536 #define SQLITE_SHM_SHARED 4
1537 #define SQLITE_SHM_EXCLUSIVE 8
1538 
1539 /*
1540 ** CAPI3REF: Maximum xShmLock index
1541 **
1542 ** The xShmLock method on [sqlite3_io_methods] may use values
1543 ** between 0 and this upper bound as its "offset" argument.
1544 ** The SQLite core will never attempt to acquire or release a
1545 ** lock outside of this range
1546 */
1547 #define SQLITE_SHM_NLOCK 8
1548 
1549 
1550 /*
1551 ** CAPI3REF: Initialize The SQLite Library
1552 **
1553 ** ^The sqlite3_initialize() routine initializes the
1554 ** SQLite library. ^The sqlite3_shutdown() routine
1555 ** deallocates any resources that were allocated by sqlite3_initialize().
1556 ** These routines are designed to aid in process initialization and
1557 ** shutdown on embedded systems. Workstation applications using
1558 ** SQLite normally do not need to invoke either of these routines.
1559 **
1560 ** A call to sqlite3_initialize() is an "effective" call if it is
1561 ** the first time sqlite3_initialize() is invoked during the lifetime of
1562 ** the process, or if it is the first time sqlite3_initialize() is invoked
1563 ** following a call to sqlite3_shutdown(). ^(Only an effective call
1564 ** of sqlite3_initialize() does any initialization. All other calls
1565 ** are harmless no-ops.)^
1566 **
1567 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1568 ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
1569 ** an effective call to sqlite3_shutdown() does any deinitialization.
1570 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1571 **
1572 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1573 ** is not. The sqlite3_shutdown() interface must only be called from a
1574 ** single thread. All open [database connections] must be closed and all
1575 ** other SQLite resources must be deallocated prior to invoking
1576 ** sqlite3_shutdown().
1577 **
1578 ** Among other things, ^sqlite3_initialize() will invoke
1579 ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
1580 ** will invoke sqlite3_os_end().
1581 **
1582 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1583 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1584 ** the library (perhaps it is unable to allocate a needed resource such
1585 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1586 **
1587 ** ^The sqlite3_initialize() routine is called internally by many other
1588 ** SQLite interfaces so that an application usually does not need to
1589 ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
1590 ** calls sqlite3_initialize() so the SQLite library will be automatically
1591 ** initialized when [sqlite3_open()] is called if it has not be initialized
1592 ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1593 ** compile-time option, then the automatic calls to sqlite3_initialize()
1594 ** are omitted and the application must call sqlite3_initialize() directly
1595 ** prior to using any other SQLite interface. For maximum portability,
1596 ** it is recommended that applications always invoke sqlite3_initialize()
1597 ** directly prior to using any other SQLite interface. Future releases
1598 ** of SQLite may require this. In other words, the behavior exhibited
1599 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1600 ** default behavior in some future release of SQLite.
1601 **
1602 ** The sqlite3_os_init() routine does operating-system specific
1603 ** initialization of the SQLite library. The sqlite3_os_end()
1604 ** routine undoes the effect of sqlite3_os_init(). Typical tasks
1605 ** performed by these routines include allocation or deallocation
1606 ** of static resources, initialization of global variables,
1607 ** setting up a default [sqlite3_vfs] module, or setting up
1608 ** a default configuration using [sqlite3_config()].
1609 **
1610 ** The application should never invoke either sqlite3_os_init()
1611 ** or sqlite3_os_end() directly. The application should only invoke
1612 ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
1613 ** interface is called automatically by sqlite3_initialize() and
1614 ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
1615 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1616 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1617 ** When [custom builds | built for other platforms]
1618 ** (using the [SQLITE_OS_OTHER=1] compile-time
1619 ** option) the application must supply a suitable implementation for
1620 ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
1621 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1622 ** must return [SQLITE_OK] on success and some other [error code] upon
1623 ** failure.
1624 */
1629 
1630 /*
1631 ** CAPI3REF: Configuring The SQLite Library
1632 **
1633 ** The sqlite3_config() interface is used to make global configuration
1634 ** changes to SQLite in order to tune SQLite to the specific needs of
1635 ** the application. The default configuration is recommended for most
1636 ** applications and so this routine is usually not necessary. It is
1637 ** provided to support rare applications with unusual needs.
1638 **
1639 ** <b>The sqlite3_config() interface is not threadsafe. The application
1640 ** must ensure that no other SQLite interfaces are invoked by other
1641 ** threads while sqlite3_config() is running.</b>
1642 **
1643 ** The sqlite3_config() interface
1644 ** may only be invoked prior to library initialization using
1645 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1646 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1647 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1648 ** Note, however, that ^sqlite3_config() can be called as part of the
1649 ** implementation of an application-defined [sqlite3_os_init()].
1650 **
1651 ** The first argument to sqlite3_config() is an integer
1652 ** [configuration option] that determines
1653 ** what property of SQLite is to be configured. Subsequent arguments
1654 ** vary depending on the [configuration option]
1655 ** in the first argument.
1656 **
1657 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1658 ** ^If the option is unknown or SQLite is unable to set the option
1659 ** then this routine returns a non-zero [error code].
1660 */
1661 SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1662 
1663 /*
1664 ** CAPI3REF: Configure database connections
1665 ** METHOD: sqlite3
1666 **
1667 ** The sqlite3_db_config() interface is used to make configuration
1668 ** changes to a [database connection]. The interface is similar to
1669 ** [sqlite3_config()] except that the changes apply to a single
1670 ** [database connection] (specified in the first argument).
1671 **
1672 ** The second argument to sqlite3_db_config(D,V,...) is the
1673 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
1674 ** that indicates what aspect of the [database connection] is being configured.
1675 ** Subsequent arguments vary depending on the configuration verb.
1676 **
1677 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1678 ** the call is considered successful.
1679 */
1681 
1682 /*
1683 ** CAPI3REF: Memory Allocation Routines
1684 **
1685 ** An instance of this object defines the interface between SQLite
1686 ** and low-level memory allocation routines.
1687 **
1688 ** This object is used in only one place in the SQLite interface.
1689 ** A pointer to an instance of this object is the argument to
1690 ** [sqlite3_config()] when the configuration option is
1691 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
1692 ** By creating an instance of this object
1693 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1694 ** during configuration, an application can specify an alternative
1695 ** memory allocation subsystem for SQLite to use for all of its
1696 ** dynamic memory needs.
1697 **
1698 ** Note that SQLite comes with several [built-in memory allocators]
1699 ** that are perfectly adequate for the overwhelming majority of applications
1700 ** and that this object is only useful to a tiny minority of applications
1701 ** with specialized memory allocation requirements. This object is
1702 ** also used during testing of SQLite in order to specify an alternative
1703 ** memory allocator that simulates memory out-of-memory conditions in
1704 ** order to verify that SQLite recovers gracefully from such
1705 ** conditions.
1706 **
1707 ** The xMalloc, xRealloc, and xFree methods must work like the
1708 ** malloc(), realloc() and free() functions from the standard C library.
1709 ** ^SQLite guarantees that the second argument to
1710 ** xRealloc is always a value returned by a prior call to xRoundup.
1711 **
1712 ** xSize should return the allocated size of a memory allocation
1713 ** previously obtained from xMalloc or xRealloc. The allocated size
1714 ** is always at least as big as the requested size but may be larger.
1715 **
1716 ** The xRoundup method returns what would be the allocated size of
1717 ** a memory allocation given a particular requested size. Most memory
1718 ** allocators round up memory allocations at least to the next multiple
1719 ** of 8. Some allocators round up to a larger multiple or to a power of 2.
1720 ** Every memory allocation request coming in through [sqlite3_malloc()]
1721 ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
1722 ** that causes the corresponding memory allocation to fail.
1723 **
1724 ** The xInit method initializes the memory allocator. For example,
1725 ** it might allocate any require mutexes or initialize internal data
1726 ** structures. The xShutdown method is invoked (indirectly) by
1727 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1728 ** by xInit. The pAppData pointer is used as the only parameter to
1729 ** xInit and xShutdown.
1730 **
1731 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1732 ** the xInit method, so the xInit method need not be threadsafe. The
1733 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1734 ** not need to be threadsafe either. For all other methods, SQLite
1735 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1736 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1737 ** it is by default) and so the methods are automatically serialized.
1738 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1739 ** methods must be threadsafe or else make their own arrangements for
1740 ** serialization.
1741 **
1742 ** SQLite will never invoke xInit() more than once without an intervening
1743 ** call to xShutdown().
1744 */
1747  void *(*xMalloc)(int); /* Memory allocation function */
1748  void (*xFree)(void*); /* Free a prior allocation */
1749  void *(*xRealloc)(void*,int); /* Resize an allocation */
1750  int (*xSize)(void*); /* Return the size of an allocation */
1751  int (*xRoundup)(int); /* Round up request size to allocation size */
1752  int (*xInit)(void*); /* Initialize the memory allocator */
1753  void (*xShutdown)(void*); /* Deinitialize the memory allocator */
1754  void *pAppData; /* Argument to xInit() and xShutdown() */
1755 };
1756 
1757 /*
1758 ** CAPI3REF: Configuration Options
1759 ** KEYWORDS: {configuration option}
1760 **
1761 ** These constants are the available integer configuration options that
1762 ** can be passed as the first argument to the [sqlite3_config()] interface.
1763 **
1764 ** New configuration options may be added in future releases of SQLite.
1765 ** Existing configuration options might be discontinued. Applications
1766 ** should check the return code from [sqlite3_config()] to make sure that
1767 ** the call worked. The [sqlite3_config()] interface will return a
1768 ** non-zero [error code] if a discontinued or unsupported configuration option
1769 ** is invoked.
1770 **
1771 ** <dl>
1772 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1773 ** <dd>There are no arguments to this option. ^This option sets the
1774 ** [threading mode] to Single-thread. In other words, it disables
1775 ** all mutexing and puts SQLite into a mode where it can only be used
1776 ** by a single thread. ^If SQLite is compiled with
1777 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1778 ** it is not possible to change the [threading mode] from its default
1779 ** value of Single-thread and so [sqlite3_config()] will return
1780 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1781 ** configuration option.</dd>
1782 **
1783 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1784 ** <dd>There are no arguments to this option. ^This option sets the
1785 ** [threading mode] to Multi-thread. In other words, it disables
1786 ** mutexing on [database connection] and [prepared statement] objects.
1787 ** The application is responsible for serializing access to
1788 ** [database connections] and [prepared statements]. But other mutexes
1789 ** are enabled so that SQLite will be safe to use in a multi-threaded
1790 ** environment as long as no two threads attempt to use the same
1791 ** [database connection] at the same time. ^If SQLite is compiled with
1792 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1793 ** it is not possible to set the Multi-thread [threading mode] and
1794 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1795 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1796 **
1797 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1798 ** <dd>There are no arguments to this option. ^This option sets the
1799 ** [threading mode] to Serialized. In other words, this option enables
1800 ** all mutexes including the recursive
1801 ** mutexes on [database connection] and [prepared statement] objects.
1802 ** In this mode (which is the default when SQLite is compiled with
1803 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1804 ** to [database connections] and [prepared statements] so that the
1805 ** application is free to use the same [database connection] or the
1806 ** same [prepared statement] in different threads at the same time.
1807 ** ^If SQLite is compiled with
1808 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1809 ** it is not possible to set the Serialized [threading mode] and
1810 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1811 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1812 **
1813 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1814 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is
1815 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1816 ** The argument specifies
1817 ** alternative low-level memory allocation routines to be used in place of
1818 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1819 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1820 ** before the [sqlite3_config()] call returns.</dd>
1821 **
1822 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1823 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1824 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1825 ** The [sqlite3_mem_methods]
1826 ** structure is filled with the currently defined memory allocation routines.)^
1827 ** This option can be used to overload the default memory allocation
1828 ** routines with a wrapper that simulations memory allocation failure or
1829 ** tracks memory usage, for example. </dd>
1830 **
1831 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1832 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1833 ** interpreted as a boolean, which enables or disables the collection of
1834 ** memory allocation statistics. ^(When memory allocation statistics are
1835 ** disabled, the following SQLite interfaces become non-operational:
1836 ** <ul>
1837 ** <li> [sqlite3_memory_used()]
1838 ** <li> [sqlite3_memory_highwater()]
1839 ** <li> [sqlite3_soft_heap_limit64()]
1840 ** <li> [sqlite3_status64()]
1841 ** </ul>)^
1842 ** ^Memory allocation statistics are enabled by default unless SQLite is
1843 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1844 ** allocation statistics are disabled by default.
1845 ** </dd>
1846 **
1847 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1848 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1849 ** that SQLite can use for scratch memory. ^(There are three arguments
1850 ** to SQLITE_CONFIG_SCRATCH: A pointer an 8-byte
1851 ** aligned memory buffer from which the scratch allocations will be
1852 ** drawn, the size of each scratch allocation (sz),
1853 ** and the maximum number of scratch allocations (N).)^
1854 ** The first argument must be a pointer to an 8-byte aligned buffer
1855 ** of at least sz*N bytes of memory.
1856 ** ^SQLite will not use more than one scratch buffers per thread.
1857 ** ^SQLite will never request a scratch buffer that is more than 6
1858 ** times the database page size.
1859 ** ^If SQLite needs needs additional
1860 ** scratch memory beyond what is provided by this configuration option, then
1861 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1862 ** ^When the application provides any amount of scratch memory using
1863 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1864 ** [sqlite3_malloc|heap allocations].
1865 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1866 ** fragmentation in low-memory embedded systems.
1867 ** </dd>
1868 **
1869 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1870 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a memory pool
1871 ** that SQLite can use for the database page cache with the default page
1872 ** cache implementation.
1873 ** This configuration option is a no-op if an application-define page
1874 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2].
1875 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1876 ** 8-byte aligned memory (pMem), the size of each page cache line (sz),
1877 ** and the number of cache lines (N).
1878 ** The sz argument should be the size of the largest database page
1879 ** (a power of two between 512 and 65536) plus some extra bytes for each
1880 ** page header. ^The number of extra bytes needed by the page header
1881 ** can be determined using [SQLITE_CONFIG_PCACHE_HDRSZ].
1882 ** ^It is harmless, apart from the wasted memory,
1883 ** for the sz parameter to be larger than necessary. The pMem
1884 ** argument must be either a NULL pointer or a pointer to an 8-byte
1885 ** aligned block of memory of at least sz*N bytes, otherwise
1886 ** subsequent behavior is undefined.
1887 ** ^When pMem is not NULL, SQLite will strive to use the memory provided
1888 ** to satisfy page cache needs, falling back to [sqlite3_malloc()] if
1889 ** a page cache line is larger than sz bytes or if all of the pMem buffer
1890 ** is exhausted.
1891 ** ^If pMem is NULL and N is non-zero, then each database connection
1892 ** does an initial bulk allocation for page cache memory
1893 ** from [sqlite3_malloc()] sufficient for N cache lines if N is positive or
1894 ** of -1024*N bytes if N is negative, . ^If additional
1895 ** page cache memory is needed beyond what is provided by the initial
1896 ** allocation, then SQLite goes to [sqlite3_malloc()] separately for each
1897 ** additional cache line. </dd>
1898 **
1899 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1900 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer
1901 ** that SQLite will use for all of its dynamic memory allocation needs
1902 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1903 ** [SQLITE_CONFIG_PAGECACHE].
1904 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1905 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1906 ** [SQLITE_ERROR] if invoked otherwise.
1907 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1908 ** An 8-byte aligned pointer to the memory,
1909 ** the number of bytes in the memory buffer, and the minimum allocation size.
1910 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1911 ** to using its default memory allocator (the system malloc() implementation),
1912 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
1913 ** memory pointer is not NULL then the alternative memory
1914 ** allocator is engaged to handle all of SQLites memory allocation needs.
1915 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1916 ** boundary or subsequent behavior of SQLite will be undefined.
1917 ** The minimum allocation size is capped at 2**12. Reasonable values
1918 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1919 **
1920 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1921 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1922 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1923 ** The argument specifies alternative low-level mutex routines to be used
1924 ** in place the mutex routines built into SQLite.)^ ^SQLite makes a copy of
1925 ** the content of the [sqlite3_mutex_methods] structure before the call to
1926 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1927 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1928 ** the entire mutexing subsystem is omitted from the build and hence calls to
1929 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1930 ** return [SQLITE_ERROR].</dd>
1931 **
1932 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1933 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1934 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure. The
1935 ** [sqlite3_mutex_methods]
1936 ** structure is filled with the currently defined mutex routines.)^
1937 ** This option can be used to overload the default mutex allocation
1938 ** routines with a wrapper used to track mutex usage for performance
1939 ** profiling or testing, for example. ^If SQLite is compiled with
1940 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1941 ** the entire mutexing subsystem is omitted from the build and hence calls to
1942 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1943 ** return [SQLITE_ERROR].</dd>
1944 **
1945 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1946 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1947 ** the default size of lookaside memory on each [database connection].
1948 ** The first argument is the
1949 ** size of each lookaside buffer slot and the second is the number of
1950 ** slots allocated to each database connection.)^ ^(SQLITE_CONFIG_LOOKASIDE
1951 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1952 ** option to [sqlite3_db_config()] can be used to change the lookaside
1953 ** configuration on individual connections.)^ </dd>
1954 **
1955 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1956 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is
1957 ** a pointer to an [sqlite3_pcache_methods2] object. This object specifies
1958 ** the interface to a custom page cache implementation.)^
1959 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1960 **
1961 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1962 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1963 ** is a pointer to an [sqlite3_pcache_methods2] object. SQLite copies of
1964 ** the current page cache implementation into that object.)^ </dd>
1965 **
1966 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1967 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1968 ** global [error log].
1969 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1970 ** function with a call signature of void(*)(void*,int,const char*),
1971 ** and a pointer to void. ^If the function pointer is not NULL, it is
1972 ** invoked by [sqlite3_log()] to process each logging event. ^If the
1973 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1974 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1975 ** passed through as the first parameter to the application-defined logger
1976 ** function whenever that function is invoked. ^The second parameter to
1977 ** the logger function is a copy of the first parameter to the corresponding
1978 ** [sqlite3_log()] call and is intended to be a [result code] or an
1979 ** [extended result code]. ^The third parameter passed to the logger is
1980 ** log message after formatting via [sqlite3_snprintf()].
1981 ** The SQLite logging interface is not reentrant; the logger function
1982 ** supplied by the application must not invoke any SQLite interface.
1983 ** In a multi-threaded application, the application-defined logger
1984 ** function must be threadsafe. </dd>
1985 **
1986 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1987 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
1988 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
1989 ** then URI handling is globally disabled.)^ ^If URI handling is globally
1990 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
1991 ** [sqlite3_open16()] or
1992 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1993 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1994 ** connection is opened. ^If it is globally disabled, filenames are
1995 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1996 ** database connection is opened. ^(By default, URI handling is globally
1997 ** disabled. The default value may be changed by compiling with the
1998 ** [SQLITE_USE_URI] symbol defined.)^
1999 **
2000 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
2001 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
2002 ** argument which is interpreted as a boolean in order to enable or disable
2003 ** the use of covering indices for full table scans in the query optimizer.
2004 ** ^The default setting is determined
2005 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
2006 ** if that compile-time option is omitted.
2007 ** The ability to disable the use of covering indices for full table scans
2008 ** is because some incorrectly coded legacy applications might malfunction
2009 ** when the optimization is enabled. Providing the ability to
2010 ** disable the optimization allows the older, buggy application code to work
2011 ** without change even with newer versions of SQLite.
2012 **
2013 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
2014 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
2015 ** <dd> These options are obsolete and should not be used by new code.
2016 ** They are retained for backwards compatibility but are now no-ops.
2017 ** </dd>
2018 **
2019 ** [[SQLITE_CONFIG_SQLLOG]]
2020 ** <dt>SQLITE_CONFIG_SQLLOG
2021 ** <dd>This option is only available if sqlite is compiled with the
2022 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
2023 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
2024 ** The second should be of type (void*). The callback is invoked by the library
2025 ** in three separate circumstances, identified by the value passed as the
2026 ** fourth parameter. If the fourth parameter is 0, then the database connection
2027 ** passed as the second argument has just been opened. The third argument
2028 ** points to a buffer containing the name of the main database file. If the
2029 ** fourth parameter is 1, then the SQL statement that the third parameter
2030 ** points to has just been executed. Or, if the fourth parameter is 2, then
2031 ** the connection being passed as the second parameter is being closed. The
2032 ** third parameter is passed NULL In this case. An example of using this
2033 ** configuration option can be seen in the "test_sqllog.c" source file in
2034 ** the canonical SQLite source tree.</dd>
2035 **
2036 ** [[SQLITE_CONFIG_MMAP_SIZE]]
2037 ** <dt>SQLITE_CONFIG_MMAP_SIZE
2038 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
2039 ** that are the default mmap size limit (the default setting for
2040 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
2041 ** ^The default setting can be overridden by each database connection using
2042 ** either the [PRAGMA mmap_size] command, or by using the
2043 ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
2044 ** will be silently truncated if necessary so that it does not exceed the
2045 ** compile-time maximum mmap size set by the
2046 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
2047 ** ^If either argument to this option is negative, then that argument is
2048 ** changed to its compile-time default.
2049 **
2050 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
2051 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
2052 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
2053 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
2054 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
2055 ** that specifies the maximum size of the created heap.
2056 **
2057 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
2058 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
2059 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
2060 ** is a pointer to an integer and writes into that integer the number of extra
2061 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
2062 ** The amount of extra space required can change depending on the compiler,
2063 ** target platform, and SQLite version.
2064 **
2065 ** [[SQLITE_CONFIG_PMASZ]]
2066 ** <dt>SQLITE_CONFIG_PMASZ
2067 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
2068 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
2069 ** sorter to that integer. The default minimum PMA Size is set by the
2070 ** [SQLITE_SORTER_PMASZ] compile-time option. New threads are launched
2071 ** to help with sort operations when multithreaded sorting
2072 ** is enabled (using the [PRAGMA threads] command) and the amount of content
2073 ** to be sorted exceeds the page size times the minimum of the
2074 ** [PRAGMA cache_size] setting and this value.
2075 **
2076 ** [[SQLITE_CONFIG_STMTJRNL_SPILL]]
2077 ** <dt>SQLITE_CONFIG_STMTJRNL_SPILL
2078 ** <dd>^The SQLITE_CONFIG_STMTJRNL_SPILL option takes a single parameter which
2079 ** becomes the [statement journal] spill-to-disk threshold.
2080 ** [Statement journals] are held in memory until their size (in bytes)
2081 ** exceeds this threshold, at which point they are written to disk.
2082 ** Or if the threshold is -1, statement journals are always held
2083 ** exclusively in memory.
2084 ** Since many statement journals never become large, setting the spill
2085 ** threshold to a value such as 64KiB can greatly reduce the amount of
2086 ** I/O required to support statement rollback.
2087 ** The default value for this setting is controlled by the
2088 ** [SQLITE_STMTJRNL_SPILL] compile-time option.
2089 ** </dl>
2090 */
2091 #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
2092 #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
2093 #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
2094 #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
2095 #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
2096 #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
2097 #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
2098 #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
2099 #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
2100 #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
2101 #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
2102 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
2103 #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
2104 #define SQLITE_CONFIG_PCACHE 14 /* no-op */
2105 #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
2106 #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
2107 #define SQLITE_CONFIG_URI 17 /* int */
2108 #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
2109 #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
2110 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
2111 #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
2112 #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
2113 #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
2114 #define SQLITE_CONFIG_PCACHE_HDRSZ 24 /* int *psz */
2115 #define SQLITE_CONFIG_PMASZ 25 /* unsigned int szPma */
2116 #define SQLITE_CONFIG_STMTJRNL_SPILL 26 /* int nByte */
2117 
2118 /*
2119 ** CAPI3REF: Database Connection Configuration Options
2120 **
2121 ** These constants are the available integer configuration options that
2122 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2123 **
2124 ** New configuration options may be added in future releases of SQLite.
2125 ** Existing configuration options might be discontinued. Applications
2126 ** should check the return code from [sqlite3_db_config()] to make sure that
2127 ** the call worked. ^The [sqlite3_db_config()] interface will return a
2128 ** non-zero [error code] if a discontinued or unsupported configuration option
2129 ** is invoked.
2130 **
2131 ** <dl>
2132 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2133 ** <dd> ^This option takes three additional arguments that determine the
2134 ** [lookaside memory allocator] configuration for the [database connection].
2135 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2136 ** pointer to a memory buffer to use for lookaside memory.
2137 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2138 ** may be NULL in which case SQLite will allocate the
2139 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2140 ** size of each lookaside buffer slot. ^The third argument is the number of
2141 ** slots. The size of the buffer in the first argument must be greater than
2142 ** or equal to the product of the second and third arguments. The buffer
2143 ** must be aligned to an 8-byte boundary. ^If the second argument to
2144 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2145 ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
2146 ** configuration for a database connection can only be changed when that
2147 ** connection is not currently using lookaside memory, or in other words
2148 ** when the "current value" returned by
2149 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2150 ** Any attempt to change the lookaside memory configuration when lookaside
2151 ** memory is in use leaves the configuration unchanged and returns
2152 ** [SQLITE_BUSY].)^</dd>
2153 **
2154 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2155 ** <dd> ^This option is used to enable or disable the enforcement of
2156 ** [foreign key constraints]. There should be two additional arguments.
2157 ** The first argument is an integer which is 0 to disable FK enforcement,
2158 ** positive to enable FK enforcement or negative to leave FK enforcement
2159 ** unchanged. The second parameter is a pointer to an integer into which
2160 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2161 ** following this call. The second parameter may be a NULL pointer, in
2162 ** which case the FK enforcement setting is not reported back. </dd>
2163 **
2164 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2165 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2166 ** There should be two additional arguments.
2167 ** The first argument is an integer which is 0 to disable triggers,
2168 ** positive to enable triggers or negative to leave the setting unchanged.
2169 ** The second parameter is a pointer to an integer into which
2170 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2171 ** following this call. The second parameter may be a NULL pointer, in
2172 ** which case the trigger setting is not reported back. </dd>
2173 **
2174 ** <dt>SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER</dt>
2175 ** <dd> ^This option is used to enable or disable the two-argument
2176 ** version of the [fts3_tokenizer()] function which is part of the
2177 ** [FTS3] full-text search engine extension.
2178 ** There should be two additional arguments.
2179 ** The first argument is an integer which is 0 to disable fts3_tokenizer() or
2180 ** positive to enable fts3_tokenizer() or negative to leave the setting
2181 ** unchanged.
2182 ** The second parameter is a pointer to an integer into which
2183 ** is written 0 or 1 to indicate whether fts3_tokenizer is disabled or enabled
2184 ** following this call. The second parameter may be a NULL pointer, in
2185 ** which case the new setting is not reported back. </dd>
2186 **
2187 ** <dt>SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION</dt>
2188 ** <dd> ^This option is used to enable or disable the [sqlite3_load_extension()]
2189 ** interface independently of the [load_extension()] SQL function.
2190 ** The [sqlite3_enable_load_extension()] API enables or disables both the
2191 ** C-API [sqlite3_load_extension()] and the SQL function [load_extension()].
2192 ** There should be two additional arguments.
2193 ** When the first argument to this interface is 1, then only the C-API is
2194 ** enabled and the SQL function remains disabled. If the first argment to
2195 ** this interface is 0, then both the C-API and the SQL function are disabled.
2196 ** If the first argument is -1, then no changes are made to state of either the
2197 ** C-API or the SQL function.
2198 ** The second parameter is a pointer to an integer into which
2199 ** is written 0 or 1 to indicate whether [sqlite3_load_extension()] interface
2200 ** is disabled or enabled following this call. The second parameter may
2201 ** be a NULL pointer, in which case the new setting is not reported back.
2202 ** </dd>
2203 **
2204 ** </dl>
2205 */
2206 #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
2207 #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
2208 #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
2209 #define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER 1004 /* int int* */
2210 #define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION 1005 /* int int* */
2211 
2212 
2213 /*
2214 ** CAPI3REF: Enable Or Disable Extended Result Codes
2215 ** METHOD: sqlite3
2216 **
2217 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2218 ** [extended result codes] feature of SQLite. ^The extended result
2219 ** codes are disabled by default for historical compatibility.
2220 */
2222 
2223 /*
2224 ** CAPI3REF: Last Insert Rowid
2225 ** METHOD: sqlite3
2226 **
2227 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2228 ** has a unique 64-bit signed
2229 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2230 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2231 ** names are not also used by explicitly declared columns. ^If
2232 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2233 ** is another alias for the rowid.
2234 **
2235 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
2236 ** most recent successful [INSERT] into a rowid table or [virtual table]
2237 ** on database connection D.
2238 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2239 ** ^If no successful [INSERT]s into rowid tables
2240 ** have ever occurred on the database connection D,
2241 ** then sqlite3_last_insert_rowid(D) returns zero.
2242 **
2243 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2244 ** method, then this routine will return the [rowid] of the inserted
2245 ** row as long as the trigger or virtual table method is running.
2246 ** But once the trigger or virtual table method ends, the value returned
2247 ** by this routine reverts to what it was before the trigger or virtual
2248 ** table method began.)^
2249 **
2250 ** ^An [INSERT] that fails due to a constraint violation is not a
2251 ** successful [INSERT] and does not change the value returned by this
2252 ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2253 ** and INSERT OR ABORT make no changes to the return value of this
2254 ** routine when their insertion fails. ^(When INSERT OR REPLACE
2255 ** encounters a constraint violation, it does not fail. The
2256 ** INSERT continues to completion after deleting rows that caused
2257 ** the constraint problem so INSERT OR REPLACE will always change
2258 ** the return value of this interface.)^
2259 **
2260 ** ^For the purposes of this routine, an [INSERT] is considered to
2261 ** be successful even if it is subsequently rolled back.
2262 **
2263 ** This function is accessible to SQL statements via the
2264 ** [last_insert_rowid() SQL function].
2265 **
2266 ** If a separate thread performs a new [INSERT] on the same
2267 ** database connection while the [sqlite3_last_insert_rowid()]
2268 ** function is running and thus changes the last insert [rowid],
2269 ** then the value returned by [sqlite3_last_insert_rowid()] is
2270 ** unpredictable and might not equal either the old or the new
2271 ** last insert [rowid].
2272 */
2274 
2275 /*
2276 ** CAPI3REF: Count The Number Of Rows Modified
2277 ** METHOD: sqlite3
2278 **
2279 ** ^This function returns the number of rows modified, inserted or
2280 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2281 ** statement on the database connection specified by the only parameter.
2282 ** ^Executing any other type of SQL statement does not modify the value
2283 ** returned by this function.
2284 **
2285 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2286 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers],
2287 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2288 **
2289 ** Changes to a view that are intercepted by
2290 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value
2291 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or
2292 ** DELETE statement run on a view is always zero. Only changes made to real
2293 ** tables are counted.
2294 **
2295 ** Things are more complicated if the sqlite3_changes() function is
2296 ** executed while a trigger program is running. This may happen if the
2297 ** program uses the [changes() SQL function], or if some other callback
2298 ** function invokes sqlite3_changes() directly. Essentially:
2299 **
2300 ** <ul>
2301 ** <li> ^(Before entering a trigger program the value returned by
2302 ** sqlite3_changes() function is saved. After the trigger program
2303 ** has finished, the original value is restored.)^
2304 **
2305 ** <li> ^(Within a trigger program each INSERT, UPDATE and DELETE
2306 ** statement sets the value returned by sqlite3_changes()
2307 ** upon completion as normal. Of course, this value will not include
2308 ** any changes performed by sub-triggers, as the sqlite3_changes()
2309 ** value will be saved and restored after each sub-trigger has run.)^
2310 ** </ul>
2311 **
2312 ** ^This means that if the changes() SQL function (or similar) is used
2313 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it
2314 ** returns the value as set when the calling statement began executing.
2315 ** ^If it is used by the second or subsequent such statement within a trigger
2316 ** program, the value returned reflects the number of rows modified by the
2317 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2318 **
2319 ** See also the [sqlite3_total_changes()] interface, the
2320 ** [count_changes pragma], and the [changes() SQL function].
2321 **
2322 ** If a separate thread makes changes on the same database connection
2323 ** while [sqlite3_changes()] is running then the value returned
2324 ** is unpredictable and not meaningful.
2325 */
2327 
2328 /*
2329 ** CAPI3REF: Total Number Of Rows Modified
2330 ** METHOD: sqlite3
2331 **
2332 ** ^This function returns the total number of rows inserted, modified or
2333 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2334 ** since the database connection was opened, including those executed as
2335 ** part of trigger programs. ^Executing any other type of SQL statement
2336 ** does not affect the value returned by sqlite3_total_changes().
2337 **
2338 ** ^Changes made as part of [foreign key actions] are included in the
2339 ** count, but those made as part of REPLACE constraint resolution are
2340 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers
2341 ** are not counted.
2342 **
2343 ** See also the [sqlite3_changes()] interface, the
2344 ** [count_changes pragma], and the [total_changes() SQL function].
2345 **
2346 ** If a separate thread makes changes on the same database connection
2347 ** while [sqlite3_total_changes()] is running then the value
2348 ** returned is unpredictable and not meaningful.
2349 */
2351 
2352 /*
2353 ** CAPI3REF: Interrupt A Long-Running Query
2354 ** METHOD: sqlite3
2355 **
2356 ** ^This function causes any pending database operation to abort and
2357 ** return at its earliest opportunity. This routine is typically
2358 ** called in response to a user action such as pressing "Cancel"
2359 ** or Ctrl-C where the user wants a long query operation to halt
2360 ** immediately.
2361 **
2362 ** ^It is safe to call this routine from a thread different from the
2363 ** thread that is currently running the database operation. But it
2364 ** is not safe to call this routine with a [database connection] that
2365 ** is closed or might close before sqlite3_interrupt() returns.
2366 **
2367 ** ^If an SQL operation is very nearly finished at the time when
2368 ** sqlite3_interrupt() is called, then it might not have an opportunity
2369 ** to be interrupted and might continue to completion.
2370 **
2371 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2372 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2373 ** that is inside an explicit transaction, then the entire transaction
2374 ** will be rolled back automatically.
2375 **
2376 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2377 ** SQL statements on [database connection] D complete. ^Any new SQL statements
2378 ** that are started after the sqlite3_interrupt() call and before the
2379 ** running statements reaches zero are interrupted as if they had been
2380 ** running prior to the sqlite3_interrupt() call. ^New SQL statements
2381 ** that are started after the running statement count reaches zero are
2382 ** not effected by the sqlite3_interrupt().
2383 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2384 ** SQL statements is a no-op and has no effect on SQL statements
2385 ** that are started after the sqlite3_interrupt() call returns.
2386 **
2387 ** If the database connection closes while [sqlite3_interrupt()]
2388 ** is running then bad things will likely happen.
2389 */
2391 
2392 /*
2393 ** CAPI3REF: Determine If An SQL Statement Is Complete
2394 **
2395 ** These routines are useful during command-line input to determine if the
2396 ** currently entered text seems to form a complete SQL statement or
2397 ** if additional input is needed before sending the text into
2398 ** SQLite for parsing. ^These routines return 1 if the input string
2399 ** appears to be a complete SQL statement. ^A statement is judged to be
2400 ** complete if it ends with a semicolon token and is not a prefix of a
2401 ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
2402 ** string literals or quoted identifier names or comments are not
2403 ** independent tokens (they are part of the token in which they are
2404 ** embedded) and thus do not count as a statement terminator. ^Whitespace
2405 ** and comments that follow the final semicolon are ignored.
2406 **
2407 ** ^These routines return 0 if the statement is incomplete. ^If a
2408 ** memory allocation fails, then SQLITE_NOMEM is returned.
2409 **
2410 ** ^These routines do not parse the SQL statements thus
2411 ** will not detect syntactically incorrect SQL.
2412 **
2413 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
2414 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2415 ** automatically by sqlite3_complete16(). If that initialization fails,
2416 ** then the return value from sqlite3_complete16() will be non-zero
2417 ** regardless of whether or not the input SQL is complete.)^
2418 **
2419 ** The input to [sqlite3_complete()] must be a zero-terminated
2420 ** UTF-8 string.
2421 **
2422 ** The input to [sqlite3_complete16()] must be a zero-terminated
2423 ** UTF-16 string in native byte order.
2424 */
2425 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2426 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2427 
2428 /*
2429 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2430 ** KEYWORDS: {busy-handler callback} {busy handler}
2431 ** METHOD: sqlite3
2432 **
2433 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2434 ** that might be invoked with argument P whenever
2435 ** an attempt is made to access a database table associated with
2436 ** [database connection] D when another thread
2437 ** or process has the table locked.
2438 ** The sqlite3_busy_handler() interface is used to implement
2439 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2440 **
2441 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2442 ** is returned immediately upon encountering the lock. ^If the busy callback
2443 ** is not NULL, then the callback might be invoked with two arguments.
2444 **
2445 ** ^The first argument to the busy handler is a copy of the void* pointer which
2446 ** is the third argument to sqlite3_busy_handler(). ^The second argument to
2447 ** the busy handler callback is the number of times that the busy handler has
2448 ** been invoked previously for the same locking event. ^If the
2449 ** busy callback returns 0, then no additional attempts are made to
2450 ** access the database and [SQLITE_BUSY] is returned
2451 ** to the application.
2452 ** ^If the callback returns non-zero, then another attempt
2453 ** is made to access the database and the cycle repeats.
2454 **
2455 ** The presence of a busy handler does not guarantee that it will be invoked
2456 ** when there is lock contention. ^If SQLite determines that invoking the busy
2457 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2458 ** to the application instead of invoking the
2459 ** busy handler.
2460 ** Consider a scenario where one process is holding a read lock that
2461 ** it is trying to promote to a reserved lock and
2462 ** a second process is holding a reserved lock that it is trying
2463 ** to promote to an exclusive lock. The first process cannot proceed
2464 ** because it is blocked by the second and the second process cannot
2465 ** proceed because it is blocked by the first. If both processes
2466 ** invoke the busy handlers, neither will make any progress. Therefore,
2467 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2468 ** will induce the first process to release its read lock and allow
2469 ** the second process to proceed.
2470 **
2471 ** ^The default busy callback is NULL.
2472 **
2473 ** ^(There can only be a single busy handler defined for each
2474 ** [database connection]. Setting a new busy handler clears any
2475 ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
2476 ** or evaluating [PRAGMA busy_timeout=N] will change the
2477 ** busy handler and thus clear any previously set busy handler.
2478 **
2479 ** The busy callback should not take any actions which modify the
2480 ** database connection that invoked the busy handler. In other words,
2481 ** the busy handler is not reentrant. Any such actions
2482 ** result in undefined behavior.
2483 **
2484 ** A busy handler must not close the database connection
2485 ** or [prepared statement] that invoked the busy handler.
2486 */
2487 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2488 
2489 /*
2490 ** CAPI3REF: Set A Busy Timeout
2491 ** METHOD: sqlite3
2492 **
2493 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2494 ** for a specified amount of time when a table is locked. ^The handler
2495 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2496 ** have accumulated. ^After at least "ms" milliseconds of sleeping,
2497 ** the handler returns 0 which causes [sqlite3_step()] to return
2498 ** [SQLITE_BUSY].
2499 **
2500 ** ^Calling this routine with an argument less than or equal to zero
2501 ** turns off all busy handlers.
2502 **
2503 ** ^(There can only be a single busy handler for a particular
2504 ** [database connection] at any given moment. If another busy handler
2505 ** was defined (using [sqlite3_busy_handler()]) prior to calling
2506 ** this routine, that other busy handler is cleared.)^
2507 **
2508 ** See also: [PRAGMA busy_timeout]
2509 */
2511 
2512 /*
2513 ** CAPI3REF: Convenience Routines For Running Queries
2514 ** METHOD: sqlite3
2515 **
2516 ** This is a legacy interface that is preserved for backwards compatibility.
2517 ** Use of this interface is not recommended.
2518 **
2519 ** Definition: A <b>result table</b> is memory data structure created by the
2520 ** [sqlite3_get_table()] interface. A result table records the
2521 ** complete query results from one or more queries.
2522 **
2523 ** The table conceptually has a number of rows and columns. But
2524 ** these numbers are not part of the result table itself. These
2525 ** numbers are obtained separately. Let N be the number of rows
2526 ** and M be the number of columns.
2527 **
2528 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2529 ** There are (N+1)*M elements in the array. The first M pointers point
2530 ** to zero-terminated strings that contain the names of the columns.
2531 ** The remaining entries all point to query results. NULL values result
2532 ** in NULL pointers. All other values are in their UTF-8 zero-terminated
2533 ** string representation as returned by [sqlite3_column_text()].
2534 **
2535 ** A result table might consist of one or more memory allocations.
2536 ** It is not safe to pass a result table directly to [sqlite3_free()].
2537 ** A result table should be deallocated using [sqlite3_free_table()].
2538 **
2539 ** ^(As an example of the result table format, suppose a query result
2540 ** is as follows:
2541 **
2542 ** <blockquote><pre>
2543 ** Name | Age
2544 ** -----------------------
2545 ** Alice | 43
2546 ** Bob | 28
2547 ** Cindy | 21
2548 ** </pre></blockquote>
2549 **
2550 ** There are two column (M==2) and three rows (N==3). Thus the
2551 ** result table has 8 entries. Suppose the result table is stored
2552 ** in an array names azResult. Then azResult holds this content:
2553 **
2554 ** <blockquote><pre>
2555 ** azResult&#91;0] = "Name";
2556 ** azResult&#91;1] = "Age";
2557 ** azResult&#91;2] = "Alice";
2558 ** azResult&#91;3] = "43";
2559 ** azResult&#91;4] = "Bob";
2560 ** azResult&#91;5] = "28";
2561 ** azResult&#91;6] = "Cindy";
2562 ** azResult&#91;7] = "21";
2563 ** </pre></blockquote>)^
2564 **
2565 ** ^The sqlite3_get_table() function evaluates one or more
2566 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2567 ** string of its 2nd parameter and returns a result table to the
2568 ** pointer given in its 3rd parameter.
2569 **
2570 ** After the application has finished with the result from sqlite3_get_table(),
2571 ** it must pass the result table pointer to sqlite3_free_table() in order to
2572 ** release the memory that was malloced. Because of the way the
2573 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2574 ** function must not try to call [sqlite3_free()] directly. Only
2575 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2576 **
2577 ** The sqlite3_get_table() interface is implemented as a wrapper around
2578 ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
2579 ** to any internal data structures of SQLite. It uses only the public
2580 ** interface defined here. As a consequence, errors that occur in the
2581 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2582 ** reflected in subsequent calls to [sqlite3_errcode()] or
2583 ** [sqlite3_errmsg()].
2584 */
2586  sqlite3 *db, /* An open database */
2587  const char *zSql, /* SQL to be evaluated */
2588  char ***pazResult, /* Results of the query */
2589  int *pnRow, /* Number of result rows written here */
2590  int *pnColumn, /* Number of result columns written here */
2591  char **pzErrmsg /* Error msg written here */
2592 );
2594 
2595 /*
2596 ** CAPI3REF: Formatted String Printing Functions
2597 **
2598 ** These routines are work-alikes of the "printf()" family of functions
2599 ** from the standard C library.
2600 ** These routines understand most of the common K&R formatting options,
2601 ** plus some additional non-standard formats, detailed below.
2602 ** Note that some of the more obscure formatting options from recent
2603 ** C-library standards are omitted from this implementation.
2604 **
2605 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2606 ** results into memory obtained from [sqlite3_malloc()].
2607 ** The strings returned by these two routines should be
2608 ** released by [sqlite3_free()]. ^Both routines return a
2609 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2610 ** memory to hold the resulting string.
2611 **
2612 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2613 ** the standard C library. The result is written into the
2614 ** buffer supplied as the second parameter whose size is given by
2615 ** the first parameter. Note that the order of the
2616 ** first two parameters is reversed from snprintf().)^ This is an
2617 ** historical accident that cannot be fixed without breaking
2618 ** backwards compatibility. ^(Note also that sqlite3_snprintf()
2619 ** returns a pointer to its buffer instead of the number of
2620 ** characters actually written into the buffer.)^ We admit that
2621 ** the number of characters written would be a more useful return
2622 ** value but we cannot change the implementation of sqlite3_snprintf()
2623 ** now without breaking compatibility.
2624 **
2625 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2626 ** guarantees that the buffer is always zero-terminated. ^The first
2627 ** parameter "n" is the total size of the buffer, including space for
2628 ** the zero terminator. So the longest string that can be completely
2629 ** written will be n-1 characters.
2630 **
2631 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2632 **
2633 ** These routines all implement some additional formatting
2634 ** options that are useful for constructing SQL statements.
2635 ** All of the usual printf() formatting options apply. In addition, there
2636 ** is are "%q", "%Q", "%w" and "%z" options.
2637 **
2638 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2639 ** string from the argument list. But %q also doubles every '\'' character.
2640 ** %q is designed for use inside a string literal.)^ By doubling each '\''
2641 ** character it escapes that character and allows it to be inserted into
2642 ** the string.
2643 **
2644 ** For example, assume the string variable zText contains text as follows:
2645 **
2646 ** <blockquote><pre>
2647 ** char *zText = "It's a happy day!";
2648 ** </pre></blockquote>
2649 **
2650 ** One can use this text in an SQL statement as follows:
2651 **
2652 ** <blockquote><pre>
2653 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2654 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2655 ** sqlite3_free(zSQL);
2656 ** </pre></blockquote>
2657 **
2658 ** Because the %q format string is used, the '\'' character in zText
2659 ** is escaped and the SQL generated is as follows:
2660 **
2661 ** <blockquote><pre>
2662 ** INSERT INTO table1 VALUES('It''s a happy day!')
2663 ** </pre></blockquote>
2664 **
2665 ** This is correct. Had we used %s instead of %q, the generated SQL
2666 ** would have looked like this:
2667 **
2668 ** <blockquote><pre>
2669 ** INSERT INTO table1 VALUES('It's a happy day!');
2670 ** </pre></blockquote>
2671 **
2672 ** This second example is an SQL syntax error. As a general rule you should
2673 ** always use %q instead of %s when inserting text into a string literal.
2674 **
2675 ** ^(The %Q option works like %q except it also adds single quotes around
2676 ** the outside of the total string. Additionally, if the parameter in the
2677 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2678 ** single quotes).)^ So, for example, one could say:
2679 **
2680 ** <blockquote><pre>
2681 ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2682 ** sqlite3_exec(db, zSQL, 0, 0, 0);
2683 ** sqlite3_free(zSQL);
2684 ** </pre></blockquote>
2685 **
2686 ** The code above will render a correct SQL statement in the zSQL
2687 ** variable even if the zText variable is a NULL pointer.
2688 **
2689 ** ^(The "%w" formatting option is like "%q" except that it expects to
2690 ** be contained within double-quotes instead of single quotes, and it
2691 ** escapes the double-quote character instead of the single-quote
2692 ** character.)^ The "%w" formatting option is intended for safely inserting
2693 ** table and column names into a constructed SQL statement.
2694 **
2695 ** ^(The "%z" formatting option works like "%s" but with the
2696 ** addition that after the string has been read and copied into
2697 ** the result, [sqlite3_free()] is called on the input string.)^
2698 */
2699 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2700 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2701 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2702 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2703 
2704 /*
2705 ** CAPI3REF: Memory Allocation Subsystem
2706 **
2707 ** The SQLite core uses these three routines for all of its own
2708 ** internal memory allocation needs. "Core" in the previous sentence
2709 ** does not include operating-system specific VFS implementation. The
2710 ** Windows VFS uses native malloc() and free() for some operations.
2711 **
2712 ** ^The sqlite3_malloc() routine returns a pointer to a block
2713 ** of memory at least N bytes in length, where N is the parameter.
2714 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2715 ** memory, it returns a NULL pointer. ^If the parameter N to
2716 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2717 ** a NULL pointer.
2718 **
2719 ** ^The sqlite3_malloc64(N) routine works just like
2720 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2721 ** of a signed 32-bit integer.
2722 **
2723 ** ^Calling sqlite3_free() with a pointer previously returned
2724 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2725 ** that it might be reused. ^The sqlite3_free() routine is
2726 ** a no-op if is called with a NULL pointer. Passing a NULL pointer
2727 ** to sqlite3_free() is harmless. After being freed, memory
2728 ** should neither be read nor written. Even reading previously freed
2729 ** memory might result in a segmentation fault or other severe error.
2730 ** Memory corruption, a segmentation fault, or other severe error
2731 ** might result if sqlite3_free() is called with a non-NULL pointer that
2732 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2733 **
2734 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2735 ** prior memory allocation X to be at least N bytes.
2736 ** ^If the X parameter to sqlite3_realloc(X,N)
2737 ** is a NULL pointer then its behavior is identical to calling
2738 ** sqlite3_malloc(N).
2739 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2740 ** negative then the behavior is exactly the same as calling
2741 ** sqlite3_free(X).
2742 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2743 ** of at least N bytes in size or NULL if insufficient memory is available.
2744 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2745 ** of the prior allocation are copied into the beginning of buffer returned
2746 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2747 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2748 ** prior allocation is not freed.
2749 **
2750 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2751 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2752 ** of a 32-bit signed integer.
2753 **
2754 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2755 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2756 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2757 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2758 ** of bytes requested when X was allocated. ^If X is a NULL pointer then
2759 ** sqlite3_msize(X) returns zero. If X points to something that is not
2760 ** the beginning of memory allocation, or if it points to a formerly
2761 ** valid memory allocation that has now been freed, then the behavior
2762 ** of sqlite3_msize(X) is undefined and possibly harmful.
2763 **
2764 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2765 ** sqlite3_malloc64(), and sqlite3_realloc64()
2766 ** is always aligned to at least an 8 byte boundary, or to a
2767 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2768 ** option is used.
2769 **
2770 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2771 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2772 ** implementation of these routines to be omitted. That capability
2773 ** is no longer provided. Only built-in memory allocators can be used.
2774 **
2775 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2776 ** the system malloc() and free() directly when converting
2777 ** filenames between the UTF-8 encoding used by SQLite
2778 ** and whatever filename encoding is used by the particular Windows
2779 ** installation. Memory allocation errors were detected, but
2780 ** they were reported back as [SQLITE_CANTOPEN] or
2781 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2782 **
2783 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2784 ** must be either NULL or else pointers obtained from a prior
2785 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2786 ** not yet been released.
2787 **
2788 ** The application must not read or write any part of
2789 ** a block of memory after it has been released using
2790 ** [sqlite3_free()] or [sqlite3_realloc()].
2791 */
2793 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2794 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2795 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2797 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2798 
2799 /*
2800 ** CAPI3REF: Memory Allocator Statistics
2801 **
2802 ** SQLite provides these two interfaces for reporting on the status
2803 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2804 ** routines, which form the built-in memory allocation subsystem.
2805 **
2806 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2807 ** of memory currently outstanding (malloced but not freed).
2808 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2809 ** value of [sqlite3_memory_used()] since the high-water mark
2810 ** was last reset. ^The values returned by [sqlite3_memory_used()] and
2811 ** [sqlite3_memory_highwater()] include any overhead
2812 ** added by SQLite in its implementation of [sqlite3_malloc()],
2813 ** but not overhead added by the any underlying system library
2814 ** routines that [sqlite3_malloc()] may call.
2815 **
2816 ** ^The memory high-water mark is reset to the current value of
2817 ** [sqlite3_memory_used()] if and only if the parameter to
2818 ** [sqlite3_memory_highwater()] is true. ^The value returned
2819 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2820 ** prior to the reset.
2821 */
2822 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2823 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2824 
2825 /*
2826 ** CAPI3REF: Pseudo-Random Number Generator
2827 **
2828 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2829 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2830 ** already uses the largest possible [ROWID]. The PRNG is also used for
2831 ** the build-in random() and randomblob() SQL functions. This interface allows
2832 ** applications to access the same PRNG for other purposes.
2833 **
2834 ** ^A call to this routine stores N bytes of randomness into buffer P.
2835 ** ^The P parameter can be a NULL pointer.
2836 **
2837 ** ^If this routine has not been previously called or if the previous
2838 ** call had N less than one or a NULL pointer for P, then the PRNG is
2839 ** seeded using randomness obtained from the xRandomness method of
2840 ** the default [sqlite3_vfs] object.
2841 ** ^If the previous call to this routine had an N of 1 or more and a
2842 ** non-NULL P then the pseudo-randomness is generated
2843 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2844 ** method.
2845 */
2846 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2847 
2848 /*
2849 ** CAPI3REF: Compile-Time Authorization Callbacks
2850 ** METHOD: sqlite3
2851 **
2852 ** ^This routine registers an authorizer callback with a particular
2853 ** [database connection], supplied in the first argument.
2854 ** ^The authorizer callback is invoked as SQL statements are being compiled
2855 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2856 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
2857 ** points during the compilation process, as logic is being created
2858 ** to perform various actions, the authorizer callback is invoked to
2859 ** see if those actions are allowed. ^The authorizer callback should
2860 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2861 ** specific action but allow the SQL statement to continue to be
2862 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2863 ** rejected with an error. ^If the authorizer callback returns
2864 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2865 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2866 ** the authorizer will fail with an error message.
2867 **
2868 ** When the callback returns [SQLITE_OK], that means the operation
2869 ** requested is ok. ^When the callback returns [SQLITE_DENY], the
2870 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2871 ** authorizer will fail with an error message explaining that
2872 ** access is denied.
2873 **
2874 ** ^The first parameter to the authorizer callback is a copy of the third
2875 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2876 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2877 ** the particular action to be authorized. ^The third through sixth parameters
2878 ** to the callback are zero-terminated strings that contain additional
2879 ** details about the action to be authorized.
2880 **
2881 ** ^If the action code is [SQLITE_READ]
2882 ** and the callback returns [SQLITE_IGNORE] then the
2883 ** [prepared statement] statement is constructed to substitute
2884 ** a NULL value in place of the table column that would have
2885 ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
2886 ** return can be used to deny an untrusted user access to individual
2887 ** columns of a table.
2888 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2889 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2890 ** [truncate optimization] is disabled and all rows are deleted individually.
2891 **
2892 ** An authorizer is used when [sqlite3_prepare | preparing]
2893 ** SQL statements from an untrusted source, to ensure that the SQL statements
2894 ** do not try to access data they are not allowed to see, or that they do not
2895 ** try to execute malicious statements that damage the database. For
2896 ** example, an application may allow a user to enter arbitrary
2897 ** SQL queries for evaluation by a database. But the application does
2898 ** not want the user to be able to make arbitrary changes to the
2899 ** database. An authorizer could then be put in place while the
2900 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2901 ** disallows everything except [SELECT] statements.
2902 **
2903 ** Applications that need to process SQL from untrusted sources
2904 ** might also consider lowering resource limits using [sqlite3_limit()]
2905 ** and limiting database size using the [max_page_count] [PRAGMA]
2906 ** in addition to using an authorizer.
2907 **
2908 ** ^(Only a single authorizer can be in place on a database connection
2909 ** at a time. Each call to sqlite3_set_authorizer overrides the
2910 ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
2911 ** The authorizer is disabled by default.
2912 **
2913 ** The authorizer callback must not do anything that will modify
2914 ** the database connection that invoked the authorizer callback.
2915 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2916 ** database connections for the meaning of "modify" in this paragraph.
2917 **
2918 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2919 ** statement might be re-prepared during [sqlite3_step()] due to a
2920 ** schema change. Hence, the application should ensure that the
2921 ** correct authorizer callback remains in place during the [sqlite3_step()].
2922 **
2923 ** ^Note that the authorizer callback is invoked only during
2924 ** [sqlite3_prepare()] or its variants. Authorization is not
2925 ** performed during statement evaluation in [sqlite3_step()], unless
2926 ** as stated in the previous paragraph, sqlite3_step() invokes
2927 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2928 */
2930  sqlite3*,
2931  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2932  void *pUserData
2933 );
2934 
2935 /*
2936 ** CAPI3REF: Authorizer Return Codes
2937 **
2938 ** The [sqlite3_set_authorizer | authorizer callback function] must
2939 ** return either [SQLITE_OK] or one of these two constants in order
2940 ** to signal SQLite whether or not the action is permitted. See the
2941 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2942 ** information.
2943 **
2944 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2945 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2946 */
2947 #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
2948 #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
2949 
2950 /*
2951 ** CAPI3REF: Authorizer Action Codes
2952 **
2953 ** The [sqlite3_set_authorizer()] interface registers a callback function
2954 ** that is invoked to authorize certain SQL statement actions. The
2955 ** second parameter to the callback is an integer code that specifies
2956 ** what action is being authorized. These are the integer action codes that
2957 ** the authorizer callback may be passed.
2958 **
2959 ** These action code values signify what kind of operation is to be
2960 ** authorized. The 3rd and 4th parameters to the authorization
2961 ** callback function will be parameters or NULL depending on which of these
2962 ** codes is used as the second parameter. ^(The 5th parameter to the
2963 ** authorizer callback is the name of the database ("main", "temp",
2964 ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
2965 ** is the name of the inner-most trigger or view that is responsible for
2966 ** the access attempt or NULL if this access attempt is directly from
2967 ** top-level SQL code.
2968 */
2969 /******************************************* 3rd ************ 4th ***********/
2970 #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
2971 #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
2972 #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
2973 #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
2974 #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
2975 #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
2976 #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
2977 #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
2978 #define SQLITE_DELETE 9 /* Table Name NULL */
2979 #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
2980 #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
2981 #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
2982 #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
2983 #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
2984 #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
2985 #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
2986 #define SQLITE_DROP_VIEW 17 /* View Name NULL */
2987 #define SQLITE_INSERT 18 /* Table Name NULL */
2988 #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
2989 #define SQLITE_READ 20 /* Table Name Column Name */
2990 #define SQLITE_SELECT 21 /* NULL NULL */
2991 #define SQLITE_TRANSACTION 22 /* Operation NULL */
2992 #define SQLITE_UPDATE 23 /* Table Name Column Name */
2993 #define SQLITE_ATTACH 24 /* Filename NULL */
2994 #define SQLITE_DETACH 25 /* Database Name NULL */
2995 #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
2996 #define SQLITE_REINDEX 27 /* Index Name NULL */
2997 #define SQLITE_ANALYZE 28 /* Table Name NULL */
2998 #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
2999 #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
3000 #define SQLITE_FUNCTION 31 /* NULL Function Name */
3001 #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
3002 #define SQLITE_COPY 0 /* No longer used */
3003 #define SQLITE_RECURSIVE 33 /* NULL NULL */
3004 
3005 /*
3006 ** CAPI3REF: Tracing And Profiling Functions
3007 ** METHOD: sqlite3
3008 **
3009 ** These routines register callback functions that can be used for
3010 ** tracing and profiling the execution of SQL statements.
3011 **
3012 ** ^The callback function registered by sqlite3_trace() is invoked at
3013 ** various times when an SQL statement is being run by [sqlite3_step()].
3014 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
3015 ** SQL statement text as the statement first begins executing.
3016 ** ^(Additional sqlite3_trace() callbacks might occur
3017 ** as each triggered subprogram is entered. The callbacks for triggers
3018 ** contain a UTF-8 SQL comment that identifies the trigger.)^
3019 **
3020 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
3021 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
3022 **
3023 ** ^The callback function registered by sqlite3_profile() is invoked
3024 ** as each SQL statement finishes. ^The profile callback contains
3025 ** the original statement text and an estimate of wall-clock time
3026 ** of how long that statement took to run. ^The profile callback
3027 ** time is in units of nanoseconds, however the current implementation
3028 ** is only capable of millisecond resolution so the six least significant
3029 ** digits in the time are meaningless. Future versions of SQLite
3030 ** might provide greater resolution on the profiler callback. The
3031 ** sqlite3_profile() function is considered experimental and is
3032 ** subject to change in future versions of SQLite.
3033 */
3034 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
3036  void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
3037 
3038 /*
3039 ** CAPI3REF: Query Progress Callbacks
3040 ** METHOD: sqlite3
3041 **
3042 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
3043 ** function X to be invoked periodically during long running calls to
3044 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
3045 ** database connection D. An example use for this
3046 ** interface is to keep a GUI updated during a large query.
3047 **
3048 ** ^The parameter P is passed through as the only parameter to the
3049 ** callback function X. ^The parameter N is the approximate number of
3050 ** [virtual machine instructions] that are evaluated between successive
3051 ** invocations of the callback X. ^If N is less than one then the progress
3052 ** handler is disabled.
3053 **
3054 ** ^Only a single progress handler may be defined at one time per
3055 ** [database connection]; setting a new progress handler cancels the
3056 ** old one. ^Setting parameter X to NULL disables the progress handler.
3057 ** ^The progress handler is also disabled by setting N to a value less
3058 ** than 1.
3059 **
3060 ** ^If the progress callback returns non-zero, the operation is
3061 ** interrupted. This feature can be used to implement a
3062 ** "Cancel" button on a GUI progress dialog box.
3063 **
3064 ** The progress handler callback must not do anything that will modify
3065 ** the database connection that invoked the progress handler.
3066 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
3067 ** database connections for the meaning of "modify" in this paragraph.
3068 **
3069 */
3070 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
3071 
3072 /*
3073 ** CAPI3REF: Opening A New Database Connection
3074 ** CONSTRUCTOR: sqlite3
3075 **
3076 ** ^These routines open an SQLite database file as specified by the
3077 ** filename argument. ^The filename argument is interpreted as UTF-8 for
3078 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
3079 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
3080 ** returned in *ppDb, even if an error occurs. The only exception is that
3081 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
3082 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
3083 ** object.)^ ^(If the database is opened (and/or created) successfully, then
3084 ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
3085 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
3086 ** an English language description of the error following a failure of any
3087 ** of the sqlite3_open() routines.
3088 **
3089 ** ^The default encoding will be UTF-8 for databases created using
3090 ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
3091 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
3092 **
3093 ** Whether or not an error occurs when it is opened, resources
3094 ** associated with the [database connection] handle should be released by
3095 ** passing it to [sqlite3_close()] when it is no longer required.
3096 **
3097 ** The sqlite3_open_v2() interface works like sqlite3_open()
3098 ** except that it accepts two additional parameters for additional control
3099 ** over the new database connection. ^(The flags parameter to
3100 ** sqlite3_open_v2() can take one of
3101 ** the following three values, optionally combined with the
3102 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
3103 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
3104 **
3105 ** <dl>
3106 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
3107 ** <dd>The database is opened in read-only mode. If the database does not
3108 ** already exist, an error is returned.</dd>)^
3109 **
3110 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
3111 ** <dd>The database is opened for reading and writing if possible, or reading
3112 ** only if the file is write protected by the operating system. In either
3113 ** case the database must already exist, otherwise an error is returned.</dd>)^
3114 **
3115 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
3116 ** <dd>The database is opened for reading and writing, and is created if
3117 ** it does not already exist. This is the behavior that is always used for
3118 ** sqlite3_open() and sqlite3_open16().</dd>)^
3119 ** </dl>
3120 **
3121 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
3122 ** combinations shown above optionally combined with other
3123 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
3124 ** then the behavior is undefined.
3125 **
3126 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
3127 ** opens in the multi-thread [threading mode] as long as the single-thread
3128 ** mode has not been set at compile-time or start-time. ^If the
3129 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
3130 ** in the serialized [threading mode] unless single-thread was
3131 ** previously selected at compile-time or start-time.
3132 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
3133 ** eligible to use [shared cache mode], regardless of whether or not shared
3134 ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
3135 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
3136 ** participate in [shared cache mode] even if it is enabled.
3137 **
3138 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
3139 ** [sqlite3_vfs] object that defines the operating system interface that
3140 ** the new database connection should use. ^If the fourth parameter is
3141 ** a NULL pointer then the default [sqlite3_vfs] object is used.
3142 **
3143 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3144 ** is created for the connection. ^This in-memory database will vanish when
3145 ** the database connection is closed. Future versions of SQLite might
3146 ** make use of additional special filenames that begin with the ":" character.
3147 ** It is recommended that when a database filename actually does begin with
3148 ** a ":" character you should prefix the filename with a pathname such as
3149 ** "./" to avoid ambiguity.
3150 **
3151 ** ^If the filename is an empty string, then a private, temporary
3152 ** on-disk database will be created. ^This private database will be
3153 ** automatically deleted as soon as the database connection is closed.
3154 **
3155 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3156 **
3157 ** ^If [URI filename] interpretation is enabled, and the filename argument
3158 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3159 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3160 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3161 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3162 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3163 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3164 ** by default, but future releases of SQLite might enable URI filename
3165 ** interpretation by default. See "[URI filenames]" for additional
3166 ** information.
3167 **
3168 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3169 ** authority, then it must be either an empty string or the string
3170 ** "localhost". ^If the authority is not an empty string or "localhost", an
3171 ** error is returned to the caller. ^The fragment component of a URI, if
3172 ** present, is ignored.
3173 **
3174 ** ^SQLite uses the path component of the URI as the name of the disk file
3175 ** which contains the database. ^If the path begins with a '/' character,
3176 ** then it is interpreted as an absolute path. ^If the path does not begin
3177 ** with a '/' (meaning that the authority section is omitted from the URI)
3178 ** then the path is interpreted as a relative path.
3179 ** ^(On windows, the first component of an absolute path
3180 ** is a drive specification (e.g. "C:").)^
3181 **
3182 ** [[core URI query parameters]]
3183 ** The query component of a URI may contain parameters that are interpreted
3184 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3185 ** SQLite and its built-in [VFSes] interpret the
3186 ** following query parameters:
3187 **
3188 ** <ul>
3189 ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3190 ** a VFS object that provides the operating system interface that should
3191 ** be used to access the database file on disk. ^If this option is set to
3192 ** an empty string the default VFS object is used. ^Specifying an unknown
3193 ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3194 ** present, then the VFS specified by the option takes precedence over
3195 ** the value passed as the fourth parameter to sqlite3_open_v2().
3196 **
3197 ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3198 ** "rwc", or "memory". Attempting to set it to any other value is
3199 ** an error)^.
3200 ** ^If "ro" is specified, then the database is opened for read-only
3201 ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
3202 ** third argument to sqlite3_open_v2(). ^If the mode option is set to
3203 ** "rw", then the database is opened for read-write (but not create)
3204 ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
3205 ** been set. ^Value "rwc" is equivalent to setting both
3206 ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
3207 ** set to "memory" then a pure [in-memory database] that never reads
3208 ** or writes from disk is used. ^It is an error to specify a value for
3209 ** the mode parameter that is less restrictive than that specified by
3210 ** the flags passed in the third parameter to sqlite3_open_v2().
3211 **
3212 ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3213 ** "private". ^Setting it to "shared" is equivalent to setting the
3214 ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3215 ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
3216 ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3217 ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3218 ** a URI filename, its value overrides any behavior requested by setting
3219 ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3220 **
3221 ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3222 ** [powersafe overwrite] property does or does not apply to the
3223 ** storage media on which the database file resides.
3224 **
3225 ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3226 ** which if set disables file locking in rollback journal modes. This
3227 ** is useful for accessing a database on a filesystem that does not
3228 ** support locking. Caution: Database corruption might result if two
3229 ** or more processes write to the same database and any one of those
3230 ** processes uses nolock=1.
3231 **
3232 ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3233 ** parameter that indicates that the database file is stored on
3234 ** read-only media. ^When immutable is set, SQLite assumes that the
3235 ** database file cannot be changed, even by a process with higher
3236 ** privilege, and so the database is opened read-only and all locking
3237 ** and change detection is disabled. Caution: Setting the immutable
3238 ** property on a database file that does in fact change can result
3239 ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
3240 ** See also: [SQLITE_IOCAP_IMMUTABLE].
3241 **
3242 ** </ul>
3243 **
3244 ** ^Specifying an unknown parameter in the query component of a URI is not an
3245 ** error. Future versions of SQLite might understand additional query
3246 ** parameters. See "[query parameters with special meaning to SQLite]" for
3247 ** additional information.
3248 **
3249 ** [[URI filename examples]] <h3>URI filename examples</h3>
3250 **
3251 ** <table border="1" align=center cellpadding=5>
3252 ** <tr><th> URI filenames <th> Results
3253 ** <tr><td> file:data.db <td>
3254 ** Open the file "data.db" in the current directory.
3255 ** <tr><td> file:/home/fred/data.db<br>
3256 ** file:///home/fred/data.db <br>
3257 ** file://localhost/home/fred/data.db <br> <td>
3258 ** Open the database file "/home/fred/data.db".
3259 ** <tr><td> file://darkstar/home/fred/data.db <td>
3260 ** An error. "darkstar" is not a recognized authority.
3261 ** <tr><td style="white-space:nowrap">
3262 ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3263 ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
3264 ** C:. Note that the %20 escaping in this example is not strictly
3265 ** necessary - space characters can be used literally
3266 ** in URI filenames.
3267 ** <tr><td> file:data.db?mode=ro&cache=private <td>
3268 ** Open file "data.db" in the current directory for read-only access.
3269 ** Regardless of whether or not shared-cache mode is enabled by
3270 ** default, use a private cache.
3271 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3272 ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3273 ** that uses dot-files in place of posix advisory locking.
3274 ** <tr><td> file:data.db?mode=readonly <td>
3275 ** An error. "readonly" is not a valid option for the "mode" parameter.
3276 ** </table>
3277 **
3278 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3279 ** query components of a URI. A hexadecimal escape sequence consists of a
3280 ** percent sign - "%" - followed by exactly two hexadecimal digits
3281 ** specifying an octet value. ^Before the path or query components of a
3282 ** URI filename are interpreted, they are encoded using UTF-8 and all
3283 ** hexadecimal escape sequences replaced by a single byte containing the
3284 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3285 ** the results are undefined.
3286 **
3287 ** <b>Note to Windows users:</b> The encoding used for the filename argument
3288 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3289 ** codepage is currently defined. Filenames containing international
3290 ** characters must be converted to UTF-8 prior to passing them into
3291 ** sqlite3_open() or sqlite3_open_v2().
3292 **
3293 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
3294 ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
3295 ** features that require the use of temporary files may fail.
3296 **
3297 ** See also: [sqlite3_temp_directory]
3298 */
3300  const char *filename, /* Database filename (UTF-8) */
3301  sqlite3 **ppDb /* OUT: SQLite db handle */
3302 );
3304  const void *filename, /* Database filename (UTF-16) */
3305  sqlite3 **ppDb /* OUT: SQLite db handle */
3306 );
3308  const char *filename, /* Database filename (UTF-8) */
3309  sqlite3 **ppDb, /* OUT: SQLite db handle */
3310  int flags, /* Flags */
3311  const char *zVfs /* Name of VFS module to use */
3312 );
3313 
3314 /*
3315 ** CAPI3REF: Obtain Values For URI Parameters
3316 **
3317 ** These are utility routines, useful to VFS implementations, that check
3318 ** to see if a database file was a URI that contained a specific query
3319 ** parameter, and if so obtains the value of that query parameter.
3320 **
3321 ** If F is the database filename pointer passed into the xOpen() method of
3322 ** a VFS implementation when the flags parameter to xOpen() has one or
3323 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3324 ** P is the name of the query parameter, then
3325 ** sqlite3_uri_parameter(F,P) returns the value of the P
3326 ** parameter if it exists or a NULL pointer if P does not appear as a
3327 ** query parameter on F. If P is a query parameter of F
3328 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3329 ** a pointer to an empty string.
3330 **
3331 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3332 ** parameter and returns true (1) or false (0) according to the value
3333 ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3334 ** value of query parameter P is one of "yes", "true", or "on" in any
3335 ** case or if the value begins with a non-zero number. The
3336 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3337 ** query parameter P is one of "no", "false", or "off" in any case or
3338 ** if the value begins with a numeric zero. If P is not a query
3339 ** parameter on F or if the value of P is does not match any of the
3340 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3341 **
3342 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3343 ** 64-bit signed integer and returns that integer, or D if P does not
3344 ** exist. If the value of P is something other than an integer, then
3345 ** zero is returned.
3346 **
3347 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3348 ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
3349 ** is not a database file pathname pointer that SQLite passed into the xOpen
3350 ** VFS method, then the behavior of this routine is undefined and probably
3351 ** undesirable.
3352 */
3353 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3354 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3355 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3356 
3357 
3358 /*
3359 ** CAPI3REF: Error Codes And Messages
3360 ** METHOD: sqlite3
3361 **
3362 ** ^If the most recent sqlite3_* API call associated with
3363 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3364 ** returns the numeric [result code] or [extended result code] for that
3365 ** API call.
3366 ** If the most recent API call was successful,
3367 ** then the return value from sqlite3_errcode() is undefined.
3368 ** ^The sqlite3_extended_errcode()
3369 ** interface is the same except that it always returns the
3370 ** [extended result code] even when extended result codes are
3371 ** disabled.
3372 **
3373 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3374 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3375 ** ^(Memory to hold the error message string is managed internally.
3376 ** The application does not need to worry about freeing the result.
3377 ** However, the error string might be overwritten or deallocated by
3378 ** subsequent calls to other SQLite interface functions.)^
3379 **
3380 ** ^The sqlite3_errstr() interface returns the English-language text
3381 ** that describes the [result code], as UTF-8.
3382 ** ^(Memory to hold the error message string is managed internally
3383 ** and must not be freed by the application)^.
3384 **
3385 ** When the serialized [threading mode] is in use, it might be the
3386 ** case that a second error occurs on a separate thread in between
3387 ** the time of the first error and the call to these interfaces.
3388 ** When that happens, the second error will be reported since these
3389 ** interfaces always report the most recent result. To avoid
3390 ** this, each thread can obtain exclusive use of the [database connection] D
3391 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3392 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3393 ** all calls to the interfaces listed here are completed.
3394 **
3395 ** If an interface fails with SQLITE_MISUSE, that means the interface
3396 ** was invoked incorrectly by the application. In that case, the
3397 ** error code and message may or may not be set.
3398 */
3403 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3404 
3405 /*
3406 ** CAPI3REF: Prepared Statement Object
3407 ** KEYWORDS: {prepared statement} {prepared statements}
3408 **
3409 ** An instance of this object represents a single SQL statement that
3410 ** has been compiled into binary form and is ready to be evaluated.
3411 **
3412 ** Think of each SQL statement as a separate computer program. The
3413 ** original SQL text is source code. A prepared statement object
3414 ** is the compiled object code. All SQL must be converted into a
3415 ** prepared statement before it can be run.
3416 **
3417 ** The life-cycle of a prepared statement object usually goes like this:
3418 **
3419 ** <ol>
3420 ** <li> Create the prepared statement object using [sqlite3_prepare_v2()].
3421 ** <li> Bind values to [parameters] using the sqlite3_bind_*()
3422 ** interfaces.
3423 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3424 ** <li> Reset the prepared statement using [sqlite3_reset()] then go back
3425 ** to step 2. Do this zero or more times.
3426 ** <li> Destroy the object using [sqlite3_finalize()].
3427 ** </ol>
3428 */
3430 
3431 /*
3432 ** CAPI3REF: Run-time Limits
3433 ** METHOD: sqlite3
3434 **
3435 ** ^(This interface allows the size of various constructs to be limited
3436 ** on a connection by connection basis. The first parameter is the
3437 ** [database connection] whose limit is to be set or queried. The
3438 ** second parameter is one of the [limit categories] that define a
3439 ** class of constructs to be size limited. The third parameter is the
3440 ** new limit for that construct.)^
3441 **
3442 ** ^If the new limit is a negative number, the limit is unchanged.
3443 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
3444 ** [limits | hard upper bound]
3445 ** set at compile-time by a C preprocessor macro called
3446 ** [limits | SQLITE_MAX_<i>NAME</i>].
3447 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3448 ** ^Attempts to increase a limit above its hard upper bound are
3449 ** silently truncated to the hard upper bound.
3450 **
3451 ** ^Regardless of whether or not the limit was changed, the
3452 ** [sqlite3_limit()] interface returns the prior value of the limit.
3453 ** ^Hence, to find the current value of a limit without changing it,
3454 ** simply invoke this interface with the third parameter set to -1.
3455 **
3456 ** Run-time limits are intended for use in applications that manage
3457 ** both their own internal database and also databases that are controlled
3458 ** by untrusted external sources. An example application might be a
3459 ** web browser that has its own databases for storing history and
3460 ** separate databases controlled by JavaScript applications downloaded
3461 ** off the Internet. The internal databases can be given the
3462 ** large, default limits. Databases managed by external sources can
3463 ** be given much smaller limits designed to prevent a denial of service
3464 ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
3465 ** interface to further control untrusted SQL. The size of the database
3466 ** created by an untrusted script can be contained using the
3467 ** [max_page_count] [PRAGMA].
3468 **
3469 ** New run-time limit categories may be added in future releases.
3470 */
3471 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3472 
3473 /*
3474 ** CAPI3REF: Run-Time Limit Categories
3475 ** KEYWORDS: {limit category} {*limit categories}
3476 **
3477 ** These constants define various performance limits
3478 ** that can be lowered at run-time using [sqlite3_limit()].
3479 ** The synopsis of the meanings of the various limits is shown below.
3480 ** Additional information is available at [limits | Limits in SQLite].
3481 **
3482 ** <dl>
3483 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3484 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3485 **
3486 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3487 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3488 **
3489 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3490 ** <dd>The maximum number of columns in a table definition or in the
3491 ** result set of a [SELECT] or the maximum number of columns in an index
3492 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3493 **
3494 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3495 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3496 **
3497 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3498 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3499 **
3500 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3501 ** <dd>The maximum number of instructions in a virtual machine program
3502 ** used to implement an SQL statement. This limit is not currently
3503 ** enforced, though that might be added in some future release of
3504 ** SQLite.</dd>)^
3505 **
3506 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3507 ** <dd>The maximum number of arguments on a function.</dd>)^
3508 **
3509 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3510 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3511 **
3512 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3513 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3514 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3515 ** [GLOB] operators.</dd>)^
3516 **
3517 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3518 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3519 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3520 **
3521 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3522 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3523 **
3524 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3525 ** <dd>The maximum number of auxiliary worker threads that a single
3526 ** [prepared statement] may start.</dd>)^
3527 ** </dl>
3528 */
3529 #define SQLITE_LIMIT_LENGTH 0
3530 #define SQLITE_LIMIT_SQL_LENGTH 1
3531 #define SQLITE_LIMIT_COLUMN 2
3532 #define SQLITE_LIMIT_EXPR_DEPTH 3
3533 #define SQLITE_LIMIT_COMPOUND_SELECT 4
3534 #define SQLITE_LIMIT_VDBE_OP 5
3535 #define SQLITE_LIMIT_FUNCTION_ARG 6
3536 #define SQLITE_LIMIT_ATTACHED 7
3537 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
3538 #define SQLITE_LIMIT_VARIABLE_NUMBER 9
3539 #define SQLITE_LIMIT_TRIGGER_DEPTH 10
3540 #define SQLITE_LIMIT_WORKER_THREADS 11
3541 
3542 /*
3543 ** CAPI3REF: Compiling An SQL Statement
3544 ** KEYWORDS: {SQL statement compiler}
3545 ** METHOD: sqlite3
3546 ** CONSTRUCTOR: sqlite3_stmt
3547 **
3548 ** To execute an SQL query, it must first be compiled into a byte-code
3549 ** program using one of these routines.
3550 **
3551 ** The first argument, "db", is a [database connection] obtained from a
3552 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3553 ** [sqlite3_open16()]. The database connection must not have been closed.
3554 **
3555 ** The second argument, "zSql", is the statement to be compiled, encoded
3556 ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
3557 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3558 ** use UTF-16.
3559 **
3560 ** ^If the nByte argument is negative, then zSql is read up to the
3561 ** first zero terminator. ^If nByte is positive, then it is the
3562 ** number of bytes read from zSql. ^If nByte is zero, then no prepared
3563 ** statement is generated.
3564 ** If the caller knows that the supplied string is nul-terminated, then
3565 ** there is a small performance advantage to passing an nByte parameter that
3566 ** is the number of bytes in the input string <i>including</i>
3567 ** the nul-terminator.
3568 **
3569 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3570 ** past the end of the first SQL statement in zSql. These routines only
3571 ** compile the first statement in zSql, so *pzTail is left pointing to
3572 ** what remains uncompiled.
3573 **
3574 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3575 ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
3576 ** to NULL. ^If the input text contains no SQL (if the input is an empty
3577 ** string or a comment) then *ppStmt is set to NULL.
3578 ** The calling procedure is responsible for deleting the compiled
3579 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3580 ** ppStmt may not be NULL.
3581 **
3582 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3583 ** otherwise an [error code] is returned.
3584 **
3585 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3586 ** recommended for all new programs. The two older interfaces are retained
3587 ** for backwards compatibility, but their use is discouraged.
3588 ** ^In the "v2" interfaces, the prepared statement
3589 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3590 ** original SQL text. This causes the [sqlite3_step()] interface to
3591 ** behave differently in three ways:
3592 **
3593 ** <ol>
3594 ** <li>
3595 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3596 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3597 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3598 ** retries will occur before sqlite3_step() gives up and returns an error.
3599 ** </li>
3600 **
3601 ** <li>
3602 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3603 ** [error codes] or [extended error codes]. ^The legacy behavior was that
3604 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3605 ** and the application would have to make a second call to [sqlite3_reset()]
3606 ** in order to find the underlying cause of the problem. With the "v2" prepare
3607 ** interfaces, the underlying reason for the error is returned immediately.
3608 ** </li>
3609 **
3610 ** <li>
3611 ** ^If the specific value bound to [parameter | host parameter] in the
3612 ** WHERE clause might influence the choice of query plan for a statement,
3613 ** then the statement will be automatically recompiled, as if there had been
3614 ** a schema change, on the first [sqlite3_step()] call following any change
3615 ** to the [sqlite3_bind_text | bindings] of that [parameter].
3616 ** ^The specific value of WHERE-clause [parameter] might influence the
3617 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3618 ** or [GLOB] operator or if the parameter is compared to an indexed column
3619 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3620 ** </li>
3621 ** </ol>
3622 */
3624  sqlite3 *db, /* Database handle */
3625  const char *zSql, /* SQL statement, UTF-8 encoded */
3626  int nByte, /* Maximum length of zSql in bytes. */
3627  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3628  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3629 );
3631  sqlite3 *db, /* Database handle */
3632  const char *zSql, /* SQL statement, UTF-8 encoded */
3633  int nByte, /* Maximum length of zSql in bytes. */
3634  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3635  const char **pzTail /* OUT: Pointer to unused portion of zSql */
3636 );
3638  sqlite3 *db, /* Database handle */
3639  const void *zSql, /* SQL statement, UTF-16 encoded */
3640  int nByte, /* Maximum length of zSql in bytes. */
3641  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3642  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3643 );
3645  sqlite3 *db, /* Database handle */
3646  const void *zSql, /* SQL statement, UTF-16 encoded */
3647  int nByte, /* Maximum length of zSql in bytes. */
3648  sqlite3_stmt **ppStmt, /* OUT: Statement handle */
3649  const void **pzTail /* OUT: Pointer to unused portion of zSql */
3650 );
3651 
3652 /*
3653 ** CAPI3REF: Retrieving Statement SQL
3654 ** METHOD: sqlite3_stmt
3655 **
3656 ** ^This interface can be used to retrieve a saved copy of the original
3657 ** SQL text used to create a [prepared statement] if that statement was
3658 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3659 */
3661 
3662 /*
3663 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3664 ** METHOD: sqlite3_stmt
3665 **
3666 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3667 ** and only if the [prepared statement] X makes no direct changes to
3668 ** the content of the database file.
3669 **
3670 ** Note that [application-defined SQL functions] or
3671 ** [virtual tables] might change the database indirectly as a side effect.
3672 ** ^(For example, if an application defines a function "eval()" that
3673 ** calls [sqlite3_exec()], then the following SQL statement would
3674 ** change the database file through side-effects:
3675 **
3676 ** <blockquote><pre>
3677 ** SELECT eval('DELETE FROM t1') FROM t2;
3678 ** </pre></blockquote>
3679 **
3680 ** But because the [SELECT] statement does not change the database file
3681 ** directly, sqlite3_stmt_readonly() would still return true.)^
3682 **
3683 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3684 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3685 ** since the statements themselves do not actually modify the database but
3686 ** rather they control the timing of when other statements modify the
3687 ** database. ^The [ATTACH] and [DETACH] statements also cause
3688 ** sqlite3_stmt_readonly() to return true since, while those statements
3689 ** change the configuration of a database connection, they do not make
3690 ** changes to the content of the database files on disk.
3691 */
3693 
3694 /*
3695 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3696 ** METHOD: sqlite3_stmt
3697 **
3698 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3699 ** [prepared statement] S has been stepped at least once using
3700 ** [sqlite3_step(S)] but has neither run to completion (returned
3701 ** [SQLITE_DONE] from [sqlite3_step(S)]) nor
3702 ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
3703 ** interface returns false if S is a NULL pointer. If S is not a
3704 ** NULL pointer and is not a pointer to a valid [prepared statement]
3705 ** object, then the behavior is undefined and probably undesirable.
3706 **
3707 ** This interface can be used in combination [sqlite3_next_stmt()]
3708 ** to locate all prepared statements associated with a database
3709 ** connection that are in need of being reset. This can be used,
3710 ** for example, in diagnostic routines to search for prepared
3711 ** statements that are holding a transaction open.
3712 */
3714 
3715 /*
3716 ** CAPI3REF: Dynamically Typed Value Object
3717 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3718 **
3719 ** SQLite uses the sqlite3_value object to represent all values
3720 ** that can be stored in a database table. SQLite uses dynamic typing
3721 ** for the values it stores. ^Values stored in sqlite3_value objects
3722 ** can be integers, floating point values, strings, BLOBs, or NULL.
3723 **
3724 ** An sqlite3_value object may be either "protected" or "unprotected".
3725 ** Some interfaces require a protected sqlite3_value. Other interfaces
3726 ** will accept either a protected or an unprotected sqlite3_value.
3727 ** Every interface that accepts sqlite3_value arguments specifies
3728 ** whether or not it requires a protected sqlite3_value. The
3729 ** [sqlite3_value_dup()] interface can be used to construct a new
3730 ** protected sqlite3_value from an unprotected sqlite3_value.
3731 **
3732 ** The terms "protected" and "unprotected" refer to whether or not
3733 ** a mutex is held. An internal mutex is held for a protected
3734 ** sqlite3_value object but no mutex is held for an unprotected
3735 ** sqlite3_value object. If SQLite is compiled to be single-threaded
3736 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3737 ** or if SQLite is run in one of reduced mutex modes
3738 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3739 ** then there is no distinction between protected and unprotected
3740 ** sqlite3_value objects and they can be used interchangeably. However,
3741 ** for maximum code portability it is recommended that applications
3742 ** still make the distinction between protected and unprotected
3743 ** sqlite3_value objects even when not strictly required.
3744 **
3745 ** ^The sqlite3_value objects that are passed as parameters into the
3746 ** implementation of [application-defined SQL functions] are protected.
3747 ** ^The sqlite3_value object returned by
3748 ** [sqlite3_column_value()] is unprotected.
3749 ** Unprotected sqlite3_value objects may only be used with
3750 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3751 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3752 ** interfaces require protected sqlite3_value objects.
3753 */
3754 typedef struct Mem sqlite3_value;
3755 
3756 /*
3757 ** CAPI3REF: SQL Function Context Object
3758 **
3759 ** The context in which an SQL function executes is stored in an
3760 ** sqlite3_context object. ^A pointer to an sqlite3_context object
3761 ** is always first parameter to [application-defined SQL functions].
3762 ** The application-defined SQL function implementation will pass this
3763 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3764 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3765 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3766 ** and/or [sqlite3_set_auxdata()].
3767 */
3769 
3770 /*
3771 ** CAPI3REF: Binding Values To Prepared Statements
3772 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3773 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3774 ** METHOD: sqlite3_stmt
3775 **
3776 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3777 ** literals may be replaced by a [parameter] that matches one of following
3778 ** templates:
3779 **
3780 ** <ul>
3781 ** <li> ?
3782 ** <li> ?NNN
3783 ** <li> :VVV
3784 ** <li> @VVV
3785 ** <li> $VVV
3786 ** </ul>
3787 **
3788 ** In the templates above, NNN represents an integer literal,
3789 ** and VVV represents an alphanumeric identifier.)^ ^The values of these
3790 ** parameters (also called "host parameter names" or "SQL parameters")
3791 ** can be set using the sqlite3_bind_*() routines defined here.
3792 **
3793 ** ^The first argument to the sqlite3_bind_*() routines is always
3794 ** a pointer to the [sqlite3_stmt] object returned from
3795 ** [sqlite3_prepare_v2()] or its variants.
3796 **
3797 ** ^The second argument is the index of the SQL parameter to be set.
3798 ** ^The leftmost SQL parameter has an index of 1. ^When the same named
3799 ** SQL parameter is used more than once, second and subsequent
3800 ** occurrences have the same index as the first occurrence.
3801 ** ^The index for named parameters can be looked up using the
3802 ** [sqlite3_bind_parameter_index()] API if desired. ^The index
3803 ** for "?NNN" parameters is the value of NNN.
3804 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3805 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3806 **
3807 ** ^The third argument is the value to bind to the parameter.
3808 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3809 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3810 ** is ignored and the end result is the same as sqlite3_bind_null().
3811 **
3812 ** ^(In those routines that have a fourth argument, its value is the
3813 ** number of bytes in the parameter. To be clear: the value is the
3814 ** number of <u>bytes</u> in the value, not the number of characters.)^
3815 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3816 ** is negative, then the length of the string is
3817 ** the number of bytes up to the first zero terminator.
3818 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3819 ** the behavior is undefined.
3820 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3821 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3822 ** that parameter must be the byte offset
3823 ** where the NUL terminator would occur assuming the string were NUL
3824 ** terminated. If any NUL characters occur at byte offsets less than
3825 ** the value of the fourth parameter then the resulting string value will
3826 ** contain embedded NULs. The result of expressions involving strings
3827 ** with embedded NULs is undefined.
3828 **
3829 ** ^The fifth argument to the BLOB and string binding interfaces
3830 ** is a destructor used to dispose of the BLOB or
3831 ** string after SQLite has finished with it. ^The destructor is called
3832 ** to dispose of the BLOB or string even if the call to bind API fails.
3833 ** ^If the fifth argument is
3834 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3835 ** information is in static, unmanaged space and does not need to be freed.
3836 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3837 ** SQLite makes its own private copy of the data immediately, before
3838 ** the sqlite3_bind_*() routine returns.
3839 **
3840 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3841 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3842 ** to specify the encoding of the text in the third parameter. If
3843 ** the sixth argument to sqlite3_bind_text64() is not one of the
3844 ** allowed values shown above, or if the text encoding is different
3845 ** from the encoding specified by the sixth parameter, then the behavior
3846 ** is undefined.
3847 **
3848 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3849 ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
3850 ** (just an integer to hold its size) while it is being processed.
3851 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3852 ** content is later written using
3853 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3854 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3855 **
3856 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3857 ** for the [prepared statement] or with a prepared statement for which
3858 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3859 ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
3860 ** routine is passed a [prepared statement] that has been finalized, the
3861 ** result is undefined and probably harmful.
3862 **
3863 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3864 ** ^Unbound parameters are interpreted as NULL.
3865 **
3866 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3867 ** [error code] if anything goes wrong.
3868 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3869 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3870 ** [SQLITE_MAX_LENGTH].
3871 ** ^[SQLITE_RANGE] is returned if the parameter
3872 ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
3873 **
3874 ** See also: [sqlite3_bind_parameter_count()],
3875 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3876 */
3877 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3878 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3879  void(*)(void*));
3882 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3884 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3885 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3886 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3887  void(*)(void*), unsigned char encoding);
3891 
3892 /*
3893 ** CAPI3REF: Number Of SQL Parameters
3894 ** METHOD: sqlite3_stmt
3895 **
3896 ** ^This routine can be used to find the number of [SQL parameters]
3897 ** in a [prepared statement]. SQL parameters are tokens of the
3898 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3899 ** placeholders for values that are [sqlite3_bind_blob | bound]
3900 ** to the parameters at a later time.
3901 **
3902 ** ^(This routine actually returns the index of the largest (rightmost)
3903 ** parameter. For all forms except ?NNN, this will correspond to the
3904 ** number of unique parameters. If parameters of the ?NNN form are used,
3905 ** there may be gaps in the list.)^
3906 **
3907 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3908 ** [sqlite3_bind_parameter_name()], and
3909 ** [sqlite3_bind_parameter_index()].
3910 */
3912 
3913 /*
3914 ** CAPI3REF: Name Of A Host Parameter
3915 ** METHOD: sqlite3_stmt
3916 **
3917 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3918 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3919 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3920 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3921 ** respectively.
3922 ** In other words, the initial ":" or "$" or "@" or "?"
3923 ** is included as part of the name.)^
3924 ** ^Parameters of the form "?" without a following integer have no name
3925 ** and are referred to as "nameless" or "anonymous parameters".
3926 **
3927 ** ^The first host parameter has an index of 1, not 0.
3928 **
3929 ** ^If the value N is out of range or if the N-th parameter is
3930 ** nameless, then NULL is returned. ^The returned string is
3931 ** always in UTF-8 encoding even if the named parameter was
3932 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3933 ** [sqlite3_prepare16_v2()].
3934 **
3935 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3936 ** [sqlite3_bind_parameter_count()], and
3937 ** [sqlite3_bind_parameter_index()].
3938 */
3940 
3941 /*
3942 ** CAPI3REF: Index Of A Parameter With A Given Name
3943 ** METHOD: sqlite3_stmt
3944 **
3945 ** ^Return the index of an SQL parameter given its name. ^The
3946 ** index value returned is suitable for use as the second
3947 ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
3948 ** is returned if no matching parameter is found. ^The parameter
3949 ** name must be given in UTF-8 even if the original statement
3950 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3951 **
3952 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3953 ** [sqlite3_bind_parameter_count()], and
3954 ** [sqlite3_bind_parameter_name()].
3955 */
3957 
3958 /*
3959 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3960 ** METHOD: sqlite3_stmt
3961 **
3962 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3963 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3964 ** ^Use this routine to reset all host parameters to NULL.
3965 */
3967 
3968 /*
3969 ** CAPI3REF: Number Of Columns In A Result Set
3970 ** METHOD: sqlite3_stmt
3971 **
3972 ** ^Return the number of columns in the result set returned by the
3973 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3974 ** statement that does not return data (for example an [UPDATE]).
3975 **
3976 ** See also: [sqlite3_data_count()]
3977 */
3979 
3980 /*
3981 ** CAPI3REF: Column Names In A Result Set
3982 ** METHOD: sqlite3_stmt
3983 **
3984 ** ^These routines return the name assigned to a particular column
3985 ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
3986 ** interface returns a pointer to a zero-terminated UTF-8 string
3987 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3988 ** UTF-16 string. ^The first parameter is the [prepared statement]
3989 ** that implements the [SELECT] statement. ^The second parameter is the
3990 ** column number. ^The leftmost column is number 0.
3991 **
3992 ** ^The returned string pointer is valid until either the [prepared statement]
3993 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3994 ** reprepared by the first call to [sqlite3_step()] for a particular run
3995 ** or until the next call to
3996 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3997 **
3998 ** ^If sqlite3_malloc() fails during the processing of either routine
3999 ** (for example during a conversion from UTF-8 to UTF-16) then a
4000 ** NULL pointer is returned.
4001 **
4002 ** ^The name of a result column is the value of the "AS" clause for
4003 ** that column, if there is an AS clause. If there is no AS clause
4004 ** then the name of the column is unspecified and may change from
4005 ** one release of SQLite to the next.
4006 */
4009 
4010 /*
4011 ** CAPI3REF: Source Of Data In A Query Result
4012 ** METHOD: sqlite3_stmt
4013 **
4014 ** ^These routines provide a means to determine the database, table, and
4015 ** table column that is the origin of a particular result column in
4016 ** [SELECT] statement.
4017 ** ^The name of the database or table or column can be returned as
4018 ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
4019 ** the database name, the _table_ routines return the table name, and
4020 ** the origin_ routines return the column name.
4021 ** ^The returned string is valid until the [prepared statement] is destroyed
4022 ** using [sqlite3_finalize()] or until the statement is automatically
4023 ** reprepared by the first call to [sqlite3_step()] for a particular run
4024 ** or until the same information is requested
4025 ** again in a different encoding.
4026 **
4027 ** ^The names returned are the original un-aliased names of the
4028 ** database, table, and column.
4029 **
4030 ** ^The first argument to these interfaces is a [prepared statement].
4031 ** ^These functions return information about the Nth result column returned by
4032 ** the statement, where N is the second function argument.
4033 ** ^The left-most column is column 0 for these routines.
4034 **
4035 ** ^If the Nth column returned by the statement is an expression or
4036 ** subquery and is not a column value, then all of these functions return
4037 ** NULL. ^These routine might also return NULL if a memory allocation error
4038 ** occurs. ^Otherwise, they return the name of the attached database, table,
4039 ** or column that query result column was extracted from.
4040 **
4041 ** ^As with all other SQLite APIs, those whose names end with "16" return
4042 ** UTF-16 encoded strings and the other functions return UTF-8.
4043 **
4044 ** ^These APIs are only available if the library was compiled with the
4045 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
4046 **
4047 ** If two or more threads call one or more of these routines against the same
4048 ** prepared statement and column at the same time then the results are
4049 ** undefined.
4050 **
4051 ** If two or more threads call one or more
4052 ** [sqlite3_column_database_name | column metadata interfaces]
4053 ** for the same [prepared statement] and result column
4054 ** at the same time then the results are undefined.
4055 */
4062 
4063 /*
4064 ** CAPI3REF: Declared Datatype Of A Query Result
4065 ** METHOD: sqlite3_stmt
4066 **
4067 ** ^(The first parameter is a [prepared statement].
4068 ** If this statement is a [SELECT] statement and the Nth column of the
4069 ** returned result set of that [SELECT] is a table column (not an
4070 ** expression or subquery) then the declared type of the table
4071 ** column is returned.)^ ^If the Nth column of the result set is an
4072 ** expression or subquery, then a NULL pointer is returned.
4073 ** ^The returned string is always UTF-8 encoded.
4074 **
4075 ** ^(For example, given the database schema:
4076 **
4077 ** CREATE TABLE t1(c1 VARIANT);
4078 **
4079 ** and the following statement to be compiled:
4080 **
4081 ** SELECT c1 + 1, c1 FROM t1;
4082 **
4083 ** this routine would return the string "VARIANT" for the second result
4084 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
4085 **
4086 ** ^SQLite uses dynamic run-time typing. ^So just because a column
4087 ** is declared to contain a particular type does not mean that the
4088 ** data stored in that column is of the declared type. SQLite is
4089 ** strongly typed, but the typing is dynamic not static. ^Type
4090 ** is associated with individual values, not with the containers
4091 ** used to hold those values.
4092 */
4095 
4096 /*
4097 ** CAPI3REF: Evaluate An SQL Statement
4098 ** METHOD: sqlite3_stmt
4099 **
4100 ** After a [prepared statement] has been prepared using either
4101 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
4102 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
4103 ** must be called one or more times to evaluate the statement.
4104 **
4105 ** The details of the behavior of the sqlite3_step() interface depend
4106 ** on whether the statement was prepared using the newer "v2" interface
4107 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
4108 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
4109 ** new "v2" interface is recommended for new applications but the legacy
4110 ** interface will continue to be supported.
4111 **
4112 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
4113 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
4114 ** ^With the "v2" interface, any of the other [result codes] or
4115 ** [extended result codes] might be returned as well.
4116 **
4117 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
4118 ** database locks it needs to do its job. ^If the statement is a [COMMIT]
4119 ** or occurs outside of an explicit transaction, then you can retry the
4120 ** statement. If the statement is not a [COMMIT] and occurs within an
4121 ** explicit transaction then you should rollback the transaction before
4122 ** continuing.
4123 **
4124 ** ^[SQLITE_DONE] means that the statement has finished executing
4125 ** successfully. sqlite3_step() should not be called again on this virtual
4126 ** machine without first calling [sqlite3_reset()] to reset the virtual
4127 ** machine back to its initial state.
4128 **
4129 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
4130 ** is returned each time a new row of data is ready for processing by the
4131 ** caller. The values may be accessed using the [column access functions].
4132 ** sqlite3_step() is called again to retrieve the next row of data.
4133 **
4134 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
4135 ** violation) has occurred. sqlite3_step() should not be called again on
4136 ** the VM. More information may be found by calling [sqlite3_errmsg()].
4137 ** ^With the legacy interface, a more specific error code (for example,
4138 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
4139 ** can be obtained by calling [sqlite3_reset()] on the
4140 ** [prepared statement]. ^In the "v2" interface,
4141 ** the more specific error code is returned directly by sqlite3_step().
4142 **
4143 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
4144 ** Perhaps it was called on a [prepared statement] that has
4145 ** already been [sqlite3_finalize | finalized] or on one that had
4146 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
4147 ** be the case that the same database connection is being used by two or
4148 ** more threads at the same moment in time.
4149 **
4150 ** For all versions of SQLite up to and including 3.6.23.1, a call to
4151 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
4152 ** other than [SQLITE_ROW] before any subsequent invocation of
4153 ** sqlite3_step(). Failure to reset the prepared statement using
4154 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
4155 ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
4156 ** calling [sqlite3_reset()] automatically in this circumstance rather
4157 ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
4158 ** break because any application that ever receives an SQLITE_MISUSE error
4159 ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
4160 ** can be used to restore the legacy behavior.
4161 **
4162 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
4163 ** API always returns a generic error code, [SQLITE_ERROR], following any
4164 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
4165 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4166 ** specific [error codes] that better describes the error.
4167 ** We admit that this is a goofy design. The problem has been fixed
4168 ** with the "v2" interface. If you prepare all of your SQL statements
4169 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4170 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4171 ** then the more specific [error codes] are returned directly
4172 ** by sqlite3_step(). The use of the "v2" interface is recommended.
4173 */
4175 
4176 /*
4177 ** CAPI3REF: Number of columns in a result set
4178 ** METHOD: sqlite3_stmt
4179 **
4180 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4181 ** current row of the result set of [prepared statement] P.
4182 ** ^If prepared statement P does not have results ready to return
4183 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4184 ** interfaces) then sqlite3_data_count(P) returns 0.
4185 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4186 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4187 ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
4188 ** will return non-zero if previous call to [sqlite3_step](P) returned
4189 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4190 ** where it always returns zero since each step of that multi-step
4191 ** pragma returns 0 columns of data.
4192 **
4193 ** See also: [sqlite3_column_count()]
4194 */
4196 
4197 /*
4198 ** CAPI3REF: Fundamental Datatypes
4199 ** KEYWORDS: SQLITE_TEXT
4200 **
4201 ** ^(Every value in SQLite has one of five fundamental datatypes:
4202 **
4203 ** <ul>
4204 ** <li> 64-bit signed integer
4205 ** <li> 64-bit IEEE floating point number
4206 ** <li> string
4207 ** <li> BLOB
4208 ** <li> NULL
4209 ** </ul>)^
4210 **
4211 ** These constants are codes for each of those types.
4212 **
4213 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4214 ** for a completely different meaning. Software that links against both
4215 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4216 ** SQLITE_TEXT.
4217 */
4218 #define SQLITE_INTEGER 1
4219 #define SQLITE_FLOAT 2
4220 #define SQLITE_BLOB 4
4221 #define SQLITE_NULL 5
4222 #ifdef SQLITE_TEXT
4223 # undef SQLITE_TEXT
4224 #else
4225 # define SQLITE_TEXT 3
4226 #endif
4227 #define SQLITE3_TEXT 3
4228 
4229 /*
4230 ** CAPI3REF: Result Values From A Query
4231 ** KEYWORDS: {column access functions}
4232 ** METHOD: sqlite3_stmt
4233 **
4234 ** ^These routines return information about a single column of the current
4235 ** result row of a query. ^In every case the first argument is a pointer
4236 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4237 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4238 ** and the second argument is the index of the column for which information
4239 ** should be returned. ^The leftmost column of the result set has the index 0.
4240 ** ^The number of columns in the result can be determined using
4241 ** [sqlite3_column_count()].
4242 **
4243 ** If the SQL statement does not currently point to a valid row, or if the
4244 ** column index is out of range, the result is undefined.
4245 ** These routines may only be called when the most recent call to
4246 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4247 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4248 ** If any of these routines are called after [sqlite3_reset()] or
4249 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4250 ** something other than [SQLITE_ROW], the results are undefined.
4251 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4252 ** are called from a different thread while any of these routines
4253 ** are pending, then the results are undefined.
4254 **
4255 ** ^The sqlite3_column_type() routine returns the
4256 ** [SQLITE_INTEGER | datatype code] for the initial data type
4257 ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
4258 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
4259 ** returned by sqlite3_column_type() is only meaningful if no type
4260 ** conversions have occurred as described below. After a type conversion,
4261 ** the value returned by sqlite3_column_type() is undefined. Future
4262 ** versions of SQLite may change the behavior of sqlite3_column_type()
4263 ** following a type conversion.
4264 **
4265 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4266 ** routine returns the number of bytes in that BLOB or string.
4267 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4268 ** the string to UTF-8 and then returns the number of bytes.
4269 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4270 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4271 ** the number of bytes in that string.
4272 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4273 **
4274 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4275 ** routine returns the number of bytes in that BLOB or string.
4276 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4277 ** the string to UTF-16 and then returns the number of bytes.
4278 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4279 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4280 ** the number of bytes in that string.
4281 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4282 **
4283 ** ^The values returned by [sqlite3_column_bytes()] and
4284 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4285 ** of the string. ^For clarity: the values returned by
4286 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4287 ** bytes in the string, not the number of characters.
4288 **
4289 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4290 ** even empty strings, are always zero-terminated. ^The return
4291 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4292 **
4293 ** <b>Warning:</b> ^The object returned by [sqlite3_column_value()] is an
4294 ** [unprotected sqlite3_value] object. In a multithreaded environment,
4295 ** an unprotected sqlite3_value object may only be used safely with
4296 ** [sqlite3_bind_value()] and [sqlite3_result_value()].
4297 ** If the [unprotected sqlite3_value] object returned by
4298 ** [sqlite3_column_value()] is used in any other way, including calls
4299 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4300 ** or [sqlite3_value_bytes()], the behavior is not threadsafe.
4301 **
4302 ** These routines attempt to convert the value where appropriate. ^For
4303 ** example, if the internal representation is FLOAT and a text result
4304 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4305 ** conversion automatically. ^(The following table details the conversions
4306 ** that are applied:
4307 **
4308 ** <blockquote>
4309 ** <table border="1">
4310 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
4311 **
4312 ** <tr><td> NULL <td> INTEGER <td> Result is 0
4313 ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
4314 ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
4315 ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
4316 ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
4317 ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
4318 ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
4319 ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
4320 ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
4321 ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
4322 ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
4323 ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
4324 ** <tr><td> TEXT <td> BLOB <td> No change
4325 ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
4326 ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
4327 ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
4328 ** </table>
4329 ** </blockquote>)^
4330 **
4331 ** Note that when type conversions occur, pointers returned by prior
4332 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4333 ** sqlite3_column_text16() may be invalidated.
4334 ** Type conversions and pointer invalidations might occur
4335 ** in the following cases:
4336 **
4337 ** <ul>
4338 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4339 ** sqlite3_column_text16() is called. A zero-terminator might
4340 ** need to be added to the string.</li>
4341 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4342 ** sqlite3_column_text16() is called. The content must be converted
4343 ** to UTF-16.</li>
4344 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4345 ** sqlite3_column_text() is called. The content must be converted
4346 ** to UTF-8.</li>
4347 ** </ul>
4348 **
4349 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4350 ** not invalidate a prior pointer, though of course the content of the buffer
4351 ** that the prior pointer references will have been modified. Other kinds
4352 ** of conversion are done in place when it is possible, but sometimes they
4353 ** are not possible and in those cases prior pointers are invalidated.
4354 **
4355 ** The safest policy is to invoke these routines
4356 ** in one of the following ways:
4357 **
4358 ** <ul>
4359 ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4360 ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4361 ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4362 ** </ul>
4363 **
4364 ** In other words, you should call sqlite3_column_text(),
4365 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4366 ** into the desired format, then invoke sqlite3_column_bytes() or
4367 ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
4368 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4369 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4370 ** with calls to sqlite3_column_bytes().
4371 **
4372 ** ^The pointers returned are valid until a type conversion occurs as
4373 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4374 ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
4375 ** and BLOBs is freed automatically. Do <em>not</em> pass the pointers returned
4376 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4377 ** [sqlite3_free()].
4378 **
4379 ** ^(If a memory allocation error occurs during the evaluation of any
4380 ** of these routines, a default value is returned. The default value
4381 ** is either the integer 0, the floating point number 0.0, or a NULL
4382 ** pointer. Subsequent calls to [sqlite3_errcode()] will return
4383 ** [SQLITE_NOMEM].)^
4384 */
4391 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4395 
4396 /*
4397 ** CAPI3REF: Destroy A Prepared Statement Object
4398 ** DESTRUCTOR: sqlite3_stmt
4399 **
4400 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4401 ** ^If the most recent evaluation of the statement encountered no errors
4402 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4403 ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
4404 ** sqlite3_finalize(S) returns the appropriate [error code] or
4405 ** [extended error code].
4406 **
4407 ** ^The sqlite3_finalize(S) routine can be called at any point during
4408 ** the life cycle of [prepared statement] S:
4409 ** before statement S is ever evaluated, after
4410 ** one or more calls to [sqlite3_reset()], or after any call
4411 ** to [sqlite3_step()] regardless of whether or not the statement has
4412 ** completed execution.
4413 **
4414 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4415 **
4416 ** The application must finalize every [prepared statement] in order to avoid
4417 ** resource leaks. It is a grievous error for the application to try to use
4418 ** a prepared statement after it has been finalized. Any use of a prepared
4419 ** statement after it has been finalized can result in undefined and
4420 ** undesirable behavior such as segfaults and heap corruption.
4421 */
4423 
4424 /*
4425 ** CAPI3REF: Reset A Prepared Statement Object
4426 ** METHOD: sqlite3_stmt
4427 **
4428 ** The sqlite3_reset() function is called to reset a [prepared statement]
4429 ** object back to its initial state, ready to be re-executed.
4430 ** ^Any SQL statement variables that had values bound to them using
4431 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4432 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4433 **
4434 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4435 ** back to the beginning of its program.
4436 **
4437 ** ^If the most recent call to [sqlite3_step(S)] for the
4438 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4439 ** or if [sqlite3_step(S)] has never before been called on S,
4440 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4441 **
4442 ** ^If the most recent call to [sqlite3_step(S)] for the
4443 ** [prepared statement] S indicated an error, then
4444 ** [sqlite3_reset(S)] returns an appropriate [error code].
4445 **
4446 ** ^The [sqlite3_reset(S)] interface does not change the values
4447 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4448 */
4450 
4451 /*
4452 ** CAPI3REF: Create Or Redefine SQL Functions
4453 ** KEYWORDS: {function creation routines}
4454 ** KEYWORDS: {application-defined SQL function}
4455 ** KEYWORDS: {application-defined SQL functions}
4456 ** METHOD: sqlite3
4457 **
4458 ** ^These functions (collectively known as "function creation routines")
4459 ** are used to add SQL functions or aggregates or to redefine the behavior
4460 ** of existing SQL functions or aggregates. The only differences between
4461 ** these routines are the text encoding expected for
4462 ** the second parameter (the name of the function being created)
4463 ** and the presence or absence of a destructor callback for
4464 ** the application data pointer.
4465 **
4466 ** ^The first parameter is the [database connection] to which the SQL
4467 ** function is to be added. ^If an application uses more than one database
4468 ** connection then application-defined SQL functions must be added
4469 ** to each database connection separately.
4470 **
4471 ** ^The second parameter is the name of the SQL function to be created or
4472 ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
4473 ** representation, exclusive of the zero-terminator. ^Note that the name
4474 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
4475 ** ^Any attempt to create a function with a longer name
4476 ** will result in [SQLITE_MISUSE] being returned.
4477 **
4478 ** ^The third parameter (nArg)
4479 ** is the number of arguments that the SQL function or
4480 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4481 ** aggregate may take any number of arguments between 0 and the limit
4482 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
4483 ** parameter is less than -1 or greater than 127 then the behavior is
4484 ** undefined.
4485 **
4486 ** ^The fourth parameter, eTextRep, specifies what
4487 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4488 ** its parameters. The application should set this parameter to
4489 ** [SQLITE_UTF16LE] if the function implementation invokes
4490 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4491 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4492 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4493 ** otherwise. ^The same SQL function may be registered multiple times using
4494 ** different preferred text encodings, with different implementations for
4495 ** each encoding.
4496 ** ^When multiple implementations of the same function are available, SQLite
4497 ** will pick the one that involves the least amount of data conversion.
4498 **
4499 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4500 ** to signal that the function will always return the same result given
4501 ** the same inputs within a single SQL statement. Most SQL functions are
4502 ** deterministic. The built-in [random()] SQL function is an example of a
4503 ** function that is not deterministic. The SQLite query planner is able to
4504 ** perform additional optimizations on deterministic functions, so use
4505 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4506 **
4507 ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
4508 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4509 **
4510 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4511 ** pointers to C-language functions that implement the SQL function or
4512 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4513 ** callback only; NULL pointers must be passed as the xStep and xFinal
4514 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4515 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4516 ** SQL function or aggregate, pass NULL pointers for all three function
4517 ** callbacks.
4518 **
4519 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4520 ** then it is destructor for the application data pointer.
4521 ** The destructor is invoked when the function is deleted, either by being
4522 ** overloaded or when the database connection closes.)^
4523 ** ^The destructor is also invoked if the call to
4524 ** sqlite3_create_function_v2() fails.
4525 ** ^When the destructor callback of the tenth parameter is invoked, it
4526 ** is passed a single argument which is a copy of the application data
4527 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4528 **
4529 ** ^It is permitted to register multiple implementations of the same
4530 ** functions with the same name but with either differing numbers of
4531 ** arguments or differing preferred text encodings. ^SQLite will use
4532 ** the implementation that most closely matches the way in which the
4533 ** SQL function is used. ^A function implementation with a non-negative
4534 ** nArg parameter is a better match than a function implementation with
4535 ** a negative nArg. ^A function where the preferred text encoding
4536 ** matches the database encoding is a better
4537 ** match than a function where the encoding is different.
4538 ** ^A function where the encoding difference is between UTF16le and UTF16be
4539 ** is a closer match than a function where the encoding difference is
4540 ** between UTF8 and UTF16.
4541 **
4542 ** ^Built-in functions may be overloaded by new application-defined functions.
4543 **
4544 ** ^An application-defined function is permitted to call other
4545 ** SQLite interfaces. However, such calls must not
4546 ** close the database connection nor finalize or reset the prepared
4547 ** statement in which the function is running.
4548 */
4550  sqlite3 *db,
4551  const char *zFunctionName,
4552  int nArg,
4553  int eTextRep,
4554  void *pApp,
4555  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4556  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4557  void (*xFinal)(sqlite3_context*)
4558 );
4560  sqlite3 *db,
4561  const void *zFunctionName,
4562  int nArg,
4563  int eTextRep,
4564  void *pApp,
4565  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4566  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4567  void (*xFinal)(sqlite3_context*)
4568 );
4570  sqlite3 *db,
4571  const char *zFunctionName,
4572  int nArg,
4573  int eTextRep,
4574  void *pApp,
4575  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4576  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4577  void (*xFinal)(sqlite3_context*),
4578  void(*xDestroy)(void*)
4579 );
4580 
4581 /*
4582 ** CAPI3REF: Text Encodings
4583 **
4584 ** These constant define integer codes that represent the various
4585 ** text encodings supported by SQLite.
4586 */
4587 #define SQLITE_UTF8 1 /* IMP: R-37514-35566 */
4588 #define SQLITE_UTF16LE 2 /* IMP: R-03371-37637 */
4589 #define SQLITE_UTF16BE 3 /* IMP: R-51971-34154 */
4590 #define SQLITE_UTF16 4 /* Use native byte order */
4591 #define SQLITE_ANY 5 /* Deprecated */
4592 #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
4593 
4594 /*
4595 ** CAPI3REF: Function Flags
4596 **
4597 ** These constants may be ORed together with the
4598 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4599 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4600 ** [sqlite3_create_function_v2()].
4601 */
4602 #define SQLITE_DETERMINISTIC 0x800
4603 
4604 /*
4605 ** CAPI3REF: Deprecated Functions
4606 ** DEPRECATED
4607 **
4608 ** These functions are [deprecated]. In order to maintain
4609 ** backwards compatibility with older code, these functions continue
4610 ** to be supported. However, new applications should avoid
4611 ** the use of these functions. To encourage programmers to avoid
4612 ** these functions, we will not explain what they do.
4613 */
4614 #ifndef SQLITE_OMIT_DEPRECATED
4620 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4621  void*,sqlite3_int64);
4622 #endif
4623 
4624 /*
4625 ** CAPI3REF: Obtaining SQL Values
4626 ** METHOD: sqlite3_value
4627 **
4628 ** The C-language implementation of SQL functions and aggregates uses
4629 ** this set of interface routines to access the parameter values on
4630 ** the function or aggregate.
4631 **
4632 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4633 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4634 ** define callbacks that implement the SQL functions and aggregates.
4635 ** The 3rd parameter to these callbacks is an array of pointers to
4636 ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
4637 ** each parameter to the SQL function. These routines are used to
4638 ** extract values from the [sqlite3_value] objects.
4639 **
4640 ** These routines work only with [protected sqlite3_value] objects.
4641 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4642 ** object results in undefined behavior.
4643 **
4644 ** ^These routines work just like the corresponding [column access functions]
4645 ** except that these routines take a single [protected sqlite3_value] object
4646 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4647 **
4648 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4649 ** in the native byte-order of the host machine. ^The
4650 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4651 ** extract UTF-16 strings as big-endian and little-endian respectively.
4652 **
4653 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4654 ** numeric affinity to the value. This means that an attempt is
4655 ** made to convert the value to an integer or floating point. If
4656 ** such a conversion is possible without loss of information (in other
4657 ** words, if the value is a string that looks like a number)
4658 ** then the conversion is performed. Otherwise no conversion occurs.
4659 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4660 **
4661 ** Please pay particular attention to the fact that the pointer returned
4662 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4663 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4664 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4665 ** or [sqlite3_value_text16()].
4666 **
4667 ** These routines must be called from the same thread as
4668 ** the SQL function that supplied the [sqlite3_value*] parameters.
4669 */
4682 
4683 /*
4684 ** CAPI3REF: Finding The Subtype Of SQL Values
4685 ** METHOD: sqlite3_value
4686 **
4687 ** The sqlite3_value_subtype(V) function returns the subtype for
4688 ** an [application-defined SQL function] argument V. The subtype
4689 ** information can be used to pass a limited amount of context from
4690 ** one SQL function to another. Use the [sqlite3_result_subtype()]
4691 ** routine to set the subtype for the return value of an SQL function.
4692 **
4693 ** SQLite makes no use of subtype itself. It merely passes the subtype
4694 ** from the result of one [application-defined SQL function] into the
4695 ** input of another.
4696 */
4698 
4699 /*
4700 ** CAPI3REF: Copy And Free SQL Values
4701 ** METHOD: sqlite3_value
4702 **
4703 ** ^The sqlite3_value_dup(V) interface makes a copy of the [sqlite3_value]
4704 ** object D and returns a pointer to that copy. ^The [sqlite3_value] returned
4705 ** is a [protected sqlite3_value] object even if the input is not.
4706 ** ^The sqlite3_value_dup(V) interface returns NULL if V is NULL or if a
4707 ** memory allocation fails.
4708 **
4709 ** ^The sqlite3_value_free(V) interface frees an [sqlite3_value] object
4710 ** previously obtained from [sqlite3_value_dup()]. ^If V is a NULL pointer
4711 ** then sqlite3_value_free(V) is a harmless no-op.
4712 */
4715 
4716 /*
4717 ** CAPI3REF: Obtain Aggregate Function Context
4718 ** METHOD: sqlite3_context
4719 **
4720 ** Implementations of aggregate SQL functions use this
4721 ** routine to allocate memory for storing their state.
4722 **
4723 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
4724 ** for a particular aggregate function, SQLite
4725 ** allocates N of memory, zeroes out that memory, and returns a pointer
4726 ** to the new memory. ^On second and subsequent calls to
4727 ** sqlite3_aggregate_context() for the same aggregate function instance,
4728 ** the same buffer is returned. Sqlite3_aggregate_context() is normally
4729 ** called once for each invocation of the xStep callback and then one
4730 ** last time when the xFinal callback is invoked. ^(When no rows match
4731 ** an aggregate query, the xStep() callback of the aggregate function
4732 ** implementation is never called and xFinal() is called exactly once.
4733 ** In those cases, sqlite3_aggregate_context() might be called for the
4734 ** first time from within xFinal().)^
4735 **
4736 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
4737 ** when first called if N is less than or equal to zero or if a memory
4738 ** allocate error occurs.
4739 **
4740 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4741 ** determined by the N parameter on first successful call. Changing the
4742 ** value of N in subsequent call to sqlite3_aggregate_context() within
4743 ** the same aggregate function instance will not resize the memory
4744 ** allocation.)^ Within the xFinal callback, it is customary to set
4745 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
4746 ** pointless memory allocations occur.
4747 **
4748 ** ^SQLite automatically frees the memory allocated by
4749 ** sqlite3_aggregate_context() when the aggregate query concludes.
4750 **
4751 ** The first parameter must be a copy of the
4752 ** [sqlite3_context | SQL function context] that is the first parameter
4753 ** to the xStep or xFinal callback routine that implements the aggregate
4754 ** function.
4755 **
4756 ** This routine must be called from the same thread in which
4757 ** the aggregate SQL function is running.
4758 */
4760 
4761 /*
4762 ** CAPI3REF: User Data For Functions
4763 ** METHOD: sqlite3_context
4764 **
4765 ** ^The sqlite3_user_data() interface returns a copy of
4766 ** the pointer that was the pUserData parameter (the 5th parameter)
4767 ** of the [sqlite3_create_function()]
4768 ** and [sqlite3_create_function16()] routines that originally
4769 ** registered the application defined function.
4770 **
4771 ** This routine must be called from the same thread in which
4772 ** the application-defined function is running.
4773 */
4775 
4776 /*
4777 ** CAPI3REF: Database Connection For Functions
4778 ** METHOD: sqlite3_context
4779 **
4780 ** ^The sqlite3_context_db_handle() interface returns a copy of
4781 ** the pointer to the [database connection] (the 1st parameter)
4782 ** of the [sqlite3_create_function()]
4783 ** and [sqlite3_create_function16()] routines that originally
4784 ** registered the application defined function.
4785 */
4787 
4788 /*
4789 ** CAPI3REF: Function Auxiliary Data
4790 ** METHOD: sqlite3_context
4791 **
4792 ** These functions may be used by (non-aggregate) SQL functions to
4793 ** associate metadata with argument values. If the same value is passed to
4794 ** multiple invocations of the same SQL function during query execution, under
4795 ** some circumstances the associated metadata may be preserved. An example
4796 ** of where this might be useful is in a regular-expression matching
4797 ** function. The compiled version of the regular expression can be stored as
4798 ** metadata associated with the pattern string.
4799 ** Then as long as the pattern string remains the same,
4800 ** the compiled regular expression can be reused on multiple
4801 ** invocations of the same function.
4802 **
4803 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4804 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4805 ** value to the application-defined function. ^If there is no metadata
4806 ** associated with the function argument, this sqlite3_get_auxdata() interface
4807 ** returns a NULL pointer.
4808 **
4809 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4810 ** argument of the application-defined function. ^Subsequent
4811 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4812 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4813 ** NULL if the metadata has been discarded.
4814 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4815 ** SQLite will invoke the destructor function X with parameter P exactly
4816 ** once, when the metadata is discarded.
4817 ** SQLite is free to discard the metadata at any time, including: <ul>
4818 ** <li> when the corresponding function parameter changes, or
4819 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4820 ** SQL statement, or
4821 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4822 ** <li> during the original sqlite3_set_auxdata() call when a memory
4823 ** allocation error occurs. </ul>)^
4824 **
4825 ** Note the last bullet in particular. The destructor X in
4826 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4827 ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
4828 ** should be called near the end of the function implementation and the
4829 ** function implementation should not make any use of P after
4830 ** sqlite3_set_auxdata() has been called.
4831 **
4832 ** ^(In practice, metadata is preserved between function calls for
4833 ** function parameters that are compile-time constants, including literal
4834 ** values and [parameters] and expressions composed from the same.)^
4835 **
4836 ** These routines must be called from the same thread in which
4837 ** the SQL function is running.
4838 */
4840 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4841 
4842 
4843 /*
4844 ** CAPI3REF: Constants Defining Special Destructor Behavior
4845 **
4846 ** These are special values for the destructor that is passed in as the
4847 ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
4848 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4849 ** and will never change. It does not need to be destroyed. ^The
4850 ** SQLITE_TRANSIENT value means that the content will likely change in
4851 ** the near future and that SQLite should make its own private copy of
4852 ** the content before returning.
4853 **
4854 ** The typedef is necessary to work around problems in certain
4855 ** C++ compilers.
4856 */
4857 typedef void (*sqlite3_destructor_type)(void*);
4858 #define SQLITE_STATIC ((sqlite3_destructor_type)0)
4859 #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
4860 
4861 /*
4862 ** CAPI3REF: Setting The Result Of An SQL Function
4863 ** METHOD: sqlite3_context
4864 **
4865 ** These routines are used by the xFunc or xFinal callbacks that
4866 ** implement SQL functions and aggregates. See
4867 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4868 ** for additional information.
4869 **
4870 ** These functions work very much like the [parameter binding] family of
4871 ** functions used to bind values to host parameters in prepared statements.
4872 ** Refer to the [SQL parameter] documentation for additional information.
4873 **
4874 ** ^The sqlite3_result_blob() interface sets the result from
4875 ** an application-defined function to be the BLOB whose content is pointed
4876 ** to by the second parameter and which is N bytes long where N is the
4877 ** third parameter.
4878 **
4879 ** ^The sqlite3_result_zeroblob(C,N) and sqlite3_result_zeroblob64(C,N)
4880 ** interfaces set the result of the application-defined function to be
4881 ** a BLOB containing all zero bytes and N bytes in size.
4882 **
4883 ** ^The sqlite3_result_double() interface sets the result from
4884 ** an application-defined function to be a floating point value specified
4885 ** by its 2nd argument.
4886 **
4887 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4888 ** cause the implemented SQL function to throw an exception.
4889 ** ^SQLite uses the string pointed to by the
4890 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4891 ** as the text of an error message. ^SQLite interprets the error
4892 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4893 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4894 ** byte order. ^If the third parameter to sqlite3_result_error()
4895 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4896 ** message all text up through the first zero character.
4897 ** ^If the third parameter to sqlite3_result_error() or
4898 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4899 ** bytes (not characters) from the 2nd parameter as the error message.
4900 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4901 ** routines make a private copy of the error message text before
4902 ** they return. Hence, the calling function can deallocate or
4903 ** modify the text after they return without harm.
4904 ** ^The sqlite3_result_error_code() function changes the error code
4905 ** returned by SQLite as a result of an error in a function. ^By default,
4906 ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
4907 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4908 **
4909 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4910 ** error indicating that a string or BLOB is too long to represent.
4911 **
4912 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4913 ** error indicating that a memory allocation failed.
4914 **
4915 ** ^The sqlite3_result_int() interface sets the return value
4916 ** of the application-defined function to be the 32-bit signed integer
4917 ** value given in the 2nd argument.
4918 ** ^The sqlite3_result_int64() interface sets the return value
4919 ** of the application-defined function to be the 64-bit signed integer
4920 ** value given in the 2nd argument.
4921 **
4922 ** ^The sqlite3_result_null() interface sets the return value
4923 ** of the application-defined function to be NULL.
4924 **
4925 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4926 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4927 ** set the return value of the application-defined function to be
4928 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4929 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4930 ** ^The sqlite3_result_text64() interface sets the return value of an
4931 ** application-defined function to be a text string in an encoding
4932 ** specified by the fifth (and last) parameter, which must be one
4933 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4934 ** ^SQLite takes the text result from the application from
4935 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4936 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4937 ** is negative, then SQLite takes result text from the 2nd parameter
4938 ** through the first zero character.
4939 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4940 ** is non-negative, then as many bytes (not characters) of the text
4941 ** pointed to by the 2nd parameter are taken as the application-defined
4942 ** function result. If the 3rd parameter is non-negative, then it
4943 ** must be the byte offset into the string where the NUL terminator would
4944 ** appear if the string where NUL terminated. If any NUL characters occur
4945 ** in the string at a byte offset that is less than the value of the 3rd
4946 ** parameter, then the resulting string will contain embedded NULs and the
4947 ** result of expressions operating on strings with embedded NULs is undefined.
4948 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4949 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4950 ** function as the destructor on the text or BLOB result when it has
4951 ** finished using that result.
4952 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4953 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4954 ** assumes that the text or BLOB result is in constant space and does not
4955 ** copy the content of the parameter nor call a destructor on the content
4956 ** when it has finished using that result.
4957 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4958 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4959 ** then SQLite makes a copy of the result into space obtained from
4960 ** from [sqlite3_malloc()] before it returns.
4961 **
4962 ** ^The sqlite3_result_value() interface sets the result of
4963 ** the application-defined function to be a copy of the
4964 ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
4965 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4966 ** so that the [sqlite3_value] specified in the parameter may change or
4967 ** be deallocated after sqlite3_result_value() returns without harm.
4968 ** ^A [protected sqlite3_value] object may always be used where an
4969 ** [unprotected sqlite3_value] object is required, so either
4970 ** kind of [sqlite3_value] object can be used with this interface.
4971 **
4972 ** If these routines are called from within the different thread
4973 ** than the one containing the application-defined function that received
4974 ** the [sqlite3_context] pointer, the results are undefined.
4975 */
4976 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4978  sqlite3_uint64,void(*)(void*));
4988 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4989 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4990  void(*)(void*), unsigned char encoding);
4991 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4992 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4993 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4997 
4998 
4999 /*
5000 ** CAPI3REF: Setting The Subtype Of An SQL Function
5001 ** METHOD: sqlite3_context
5002 **
5003 ** The sqlite3_result_subtype(C,T) function causes the subtype of
5004 ** the result from the [application-defined SQL function] with
5005 ** [sqlite3_context] C to be the value T. Only the lower 8 bits
5006 ** of the subtype T are preserved in current versions of SQLite;
5007 ** higher order bits are discarded.
5008 ** The number of subtype bytes preserved by SQLite might increase
5009 ** in future releases of SQLite.
5010 */
5012 
5013 /*
5014 ** CAPI3REF: Define New Collating Sequences
5015 ** METHOD: sqlite3
5016 **
5017 ** ^These functions add, remove, or modify a [collation] associated
5018 ** with the [database connection] specified as the first argument.
5019 **
5020 ** ^The name of the collation is a UTF-8 string
5021 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
5022 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
5023 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
5024 ** considered to be the same name.
5025 **
5026 ** ^(The third argument (eTextRep) must be one of the constants:
5027 ** <ul>
5028 ** <li> [SQLITE_UTF8],
5029 ** <li> [SQLITE_UTF16LE],
5030 ** <li> [SQLITE_UTF16BE],
5031 ** <li> [SQLITE_UTF16], or
5032 ** <li> [SQLITE_UTF16_ALIGNED].
5033 ** </ul>)^
5034 ** ^The eTextRep argument determines the encoding of strings passed
5035 ** to the collating function callback, xCallback.
5036 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
5037 ** force strings to be UTF16 with native byte order.
5038 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
5039 ** on an even byte address.
5040 **
5041 ** ^The fourth argument, pArg, is an application data pointer that is passed
5042 ** through as the first argument to the collating function callback.
5043 **
5044 ** ^The fifth argument, xCallback, is a pointer to the collating function.
5045 ** ^Multiple collating functions can be registered using the same name but
5046 ** with different eTextRep parameters and SQLite will use whichever
5047 ** function requires the least amount of data transformation.
5048 ** ^If the xCallback argument is NULL then the collating function is
5049 ** deleted. ^When all collating functions having the same name are deleted,
5050 ** that collation is no longer usable.
5051 **
5052 ** ^The collating function callback is invoked with a copy of the pArg
5053 ** application data pointer and with two strings in the encoding specified
5054 ** by the eTextRep argument. The collating function must return an
5055 ** integer that is negative, zero, or positive
5056 ** if the first string is less than, equal to, or greater than the second,
5057 ** respectively. A collating function must always return the same answer
5058 ** given the same inputs. If two or more collating functions are registered
5059 ** to the same collation name (using different eTextRep values) then all
5060 ** must give an equivalent answer when invoked with equivalent strings.
5061 ** The collating function must obey the following properties for all
5062 ** strings A, B, and C:
5063 **
5064 ** <ol>
5065 ** <li> If A==B then B==A.
5066 ** <li> If A==B and B==C then A==C.
5067 ** <li> If A&lt;B THEN B&gt;A.
5068 ** <li> If A&lt;B and B&lt;C then A&lt;C.
5069 ** </ol>
5070 **
5071 ** If a collating function fails any of the above constraints and that
5072 ** collating function is registered and used, then the behavior of SQLite
5073 ** is undefined.
5074 **
5075 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
5076 ** with the addition that the xDestroy callback is invoked on pArg when
5077 ** the collating function is deleted.
5078 ** ^Collating functions are deleted when they are overridden by later
5079 ** calls to the collation creation functions or when the
5080 ** [database connection] is closed using [sqlite3_close()].
5081 **
5082 ** ^The xDestroy callback is <u>not</u> called if the
5083 ** sqlite3_create_collation_v2() function fails. Applications that invoke
5084 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
5085 ** check the return code and dispose of the application data pointer
5086 ** themselves rather than expecting SQLite to deal with it for them.
5087 ** This is different from every other SQLite interface. The inconsistency
5088 ** is unfortunate but cannot be changed without breaking backwards
5089 ** compatibility.
5090 **
5091 ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
5092 */
5094  sqlite3*,
5095  const char *zName,
5096  int eTextRep,
5097  void *pArg,
5098  int(*xCompare)(void*,int,const void*,int,const void*)
5099 );
5101  sqlite3*,
5102  const char *zName,
5103  int eTextRep,
5104  void *pArg,
5105  int(*xCompare)(void*,int,const void*,int,const void*),
5106  void(*xDestroy)(void*)
5107 );
5109  sqlite3*,
5110  const void *zName,
5111  int eTextRep,
5112  void *pArg,
5113  int(*xCompare)(void*,int,const void*,int,const void*)
5114 );
5115 
5116 /*
5117 ** CAPI3REF: Collation Needed Callbacks
5118 ** METHOD: sqlite3
5119 **
5120 ** ^To avoid having to register all collation sequences before a database
5121 ** can be used, a single callback function may be registered with the
5122 ** [database connection] to be invoked whenever an undefined collation
5123 ** sequence is required.
5124 **
5125 ** ^If the function is registered using the sqlite3_collation_needed() API,
5126 ** then it is passed the names of undefined collation sequences as strings
5127 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
5128 ** the names are passed as UTF-16 in machine native byte order.
5129 ** ^A call to either function replaces the existing collation-needed callback.
5130 **
5131 ** ^(When the callback is invoked, the first argument passed is a copy
5132 ** of the second argument to sqlite3_collation_needed() or
5133 ** sqlite3_collation_needed16(). The second argument is the database
5134 ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
5135 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
5136 ** sequence function required. The fourth parameter is the name of the
5137 ** required collation sequence.)^
5138 **
5139 ** The callback function should register the desired collation using
5140 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
5141 ** [sqlite3_create_collation_v2()].
5142 */
5144  sqlite3*,
5145  void*,
5146  void(*)(void*,sqlite3*,int eTextRep,const char*)
5147 );
5149  sqlite3*,
5150  void*,
5151  void(*)(void*,sqlite3*,int eTextRep,const void*)
5152 );
5153 
5154 #ifdef SQLITE_HAS_CODEC
5155 /*
5156 ** Specify the key for an encrypted database. This routine should be
5157 ** called right after sqlite3_open().
5158 **
5159 ** The code to implement this API is not available in the public release
5160 ** of SQLite.
5161 */
5162 SQLITE_API int SQLITE_STDCALL sqlite3_key(
5163  sqlite3 *db, /* Database to be rekeyed */
5164  const void *pKey, int nKey /* The key */
5165 );
5166 SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
5167  sqlite3 *db, /* Database to be rekeyed */
5168  const char *zDbName, /* Name of the database */
5169  const void *pKey, int nKey /* The key */
5170 );
5171 
5172 /*
5173 ** Change the key on an open database. If the current database is not
5174 ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
5175 ** database is decrypted.
5176 **
5177 ** The code to implement this API is not available in the public release
5178 ** of SQLite.
5179 */
5180 SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
5181  sqlite3 *db, /* Database to be rekeyed */
5182  const void *pKey, int nKey /* The new key */
5183 );
5184 SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
5185  sqlite3 *db, /* Database to be rekeyed */
5186  const char *zDbName, /* Name of the database */
5187  const void *pKey, int nKey /* The new key */
5188 );
5189 
5190 /*
5191 ** Specify the activation key for a SEE database. Unless
5192 ** activated, none of the SEE routines will work.
5193 */
5194 SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
5195  const char *zPassPhrase /* Activation phrase */
5196 );
5197 #endif
5198 
5199 #ifdef SQLITE_ENABLE_CEROD
5200 /*
5201 ** Specify the activation key for a CEROD database. Unless
5202 ** activated, none of the CEROD routines will work.
5203 */
5204 SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
5205  const char *zPassPhrase /* Activation phrase */
5206 );
5207 #endif
5208 
5209 /*
5210 ** CAPI3REF: Suspend Execution For A Short Time
5211 **
5212 ** The sqlite3_sleep() function causes the current thread to suspend execution
5213 ** for at least a number of milliseconds specified in its parameter.
5214 **
5215 ** If the operating system does not support sleep requests with
5216 ** millisecond time resolution, then the time will be rounded up to
5217 ** the nearest second. The number of milliseconds of sleep actually
5218 ** requested from the operating system is returned.
5219 **
5220 ** ^SQLite implements this interface by calling the xSleep()
5221 ** method of the default [sqlite3_vfs] object. If the xSleep() method
5222 ** of the default VFS is not implemented correctly, or not implemented at
5223 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5224 ** in the previous paragraphs.
5225 */
5227 
5228 /*
5229 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5230 **
5231 ** ^(If this global variable is made to point to a string which is
5232 ** the name of a folder (a.k.a. directory), then all temporary files
5233 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5234 ** will be placed in that directory.)^ ^If this variable
5235 ** is a NULL pointer, then SQLite performs a search for an appropriate
5236 ** temporary file directory.
5237 **
5238 ** Applications are strongly discouraged from using this global variable.
5239 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5240 ** But for all other platforms, it is highly recommended that applications
5241 ** neither read nor write this variable. This global variable is a relic
5242 ** that exists for backwards compatibility of legacy applications and should
5243 ** be avoided in new projects.
5244 **
5245 ** It is not safe to read or modify this variable in more than one
5246 ** thread at a time. It is not safe to read or modify this variable
5247 ** if a [database connection] is being used at the same time in a separate
5248 ** thread.
5249 ** It is intended that this variable be set once
5250 ** as part of process initialization and before any SQLite interface
5251 ** routines have been called and that this variable remain unchanged
5252 ** thereafter.
5253 **
5254 ** ^The [temp_store_directory pragma] may modify this variable and cause
5255 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5256 ** the [temp_store_directory pragma] always assumes that any string
5257 ** that this variable points to is held in memory obtained from
5258 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5259 ** using [sqlite3_free].
5260 ** Hence, if this variable is modified directly, either it should be
5261 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5262 ** or else the use of the [temp_store_directory pragma] should be avoided.
5263 ** Except when requested by the [temp_store_directory pragma], SQLite
5264 ** does not free the memory that sqlite3_temp_directory points to. If
5265 ** the application wants that memory to be freed, it must do
5266 ** so itself, taking care to only do so after all [database connection]
5267 ** objects have been destroyed.
5268 **
5269 ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
5270 ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
5271 ** features that require the use of temporary files may fail. Here is an
5272 ** example of how to do this using C++ with the Windows Runtime:
5273 **
5274 ** <blockquote><pre>
5275 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5276 ** &nbsp; TemporaryFolder->Path->Data();
5277 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5278 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5279 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5280 ** &nbsp; NULL, NULL);
5281 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5282 ** </pre></blockquote>
5283 */
5285 
5286 /*
5287 ** CAPI3REF: Name Of The Folder Holding Database Files
5288 **
5289 ** ^(If this global variable is made to point to a string which is
5290 ** the name of a folder (a.k.a. directory), then all database files
5291 ** specified with a relative pathname and created or accessed by
5292 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5293 ** to be relative to that directory.)^ ^If this variable is a NULL
5294 ** pointer, then SQLite assumes that all database files specified
5295 ** with a relative pathname are relative to the current directory
5296 ** for the process. Only the windows VFS makes use of this global
5297 ** variable; it is ignored by the unix VFS.
5298 **
5299 ** Changing the value of this variable while a database connection is
5300 ** open can result in a corrupt database.
5301 **
5302 ** It is not safe to read or modify this variable in more than one
5303 ** thread at a time. It is not safe to read or modify this variable
5304 ** if a [database connection] is being used at the same time in a separate
5305 ** thread.
5306 ** It is intended that this variable be set once
5307 ** as part of process initialization and before any SQLite interface
5308 ** routines have been called and that this variable remain unchanged
5309 ** thereafter.
5310 **
5311 ** ^The [data_store_directory pragma] may modify this variable and cause
5312 ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
5313 ** the [data_store_directory pragma] always assumes that any string
5314 ** that this variable points to is held in memory obtained from
5315 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5316 ** using [sqlite3_free].
5317 ** Hence, if this variable is modified directly, either it should be
5318 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5319 ** or else the use of the [data_store_directory pragma] should be avoided.
5320 */
5322 
5323 /*
5324 ** CAPI3REF: Test For Auto-Commit Mode
5325 ** KEYWORDS: {autocommit mode}
5326 ** METHOD: sqlite3
5327 **
5328 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5329 ** zero if the given database connection is or is not in autocommit mode,
5330 ** respectively. ^Autocommit mode is on by default.
5331 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5332 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5333 **
5334 ** If certain kinds of errors occur on a statement within a multi-statement
5335 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5336 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5337 ** transaction might be rolled back automatically. The only way to
5338 ** find out whether SQLite automatically rolled back the transaction after
5339 ** an error is to use this function.
5340 **
5341 ** If another thread changes the autocommit status of the database
5342 ** connection while this routine is running, then the return value
5343 ** is undefined.
5344 */
5346 
5347 /*
5348 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5349 ** METHOD: sqlite3_stmt
5350 **
5351 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5352 ** to which a [prepared statement] belongs. ^The [database connection]
5353 ** returned by sqlite3_db_handle is the same [database connection]
5354 ** that was the first argument
5355 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5356 ** create the statement in the first place.
5357 */
5359 
5360 /*
5361 ** CAPI3REF: Return The Filename For A Database Connection
5362 ** METHOD: sqlite3
5363 **
5364 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5365 ** associated with database N of connection D. ^The main database file
5366 ** has the name "main". If there is no attached database N on the database
5367 ** connection D, or if database N is a temporary or in-memory database, then
5368 ** a NULL pointer is returned.
5369 **
5370 ** ^The filename returned by this function is the output of the
5371 ** xFullPathname method of the [VFS]. ^In other words, the filename
5372 ** will be an absolute pathname, even if the filename used
5373 ** to open the database originally was a URI or relative pathname.
5374 */
5375 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5376 
5377 /*
5378 ** CAPI3REF: Determine if a database is read-only
5379 ** METHOD: sqlite3
5380 **
5381 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5382 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5383 ** the name of a database on connection D.
5384 */
5385 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5386 
5387 /*
5388 ** CAPI3REF: Find the next prepared statement
5389 ** METHOD: sqlite3
5390 **
5391 ** ^This interface returns a pointer to the next [prepared statement] after
5392 ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
5393 ** then this interface returns a pointer to the first prepared statement
5394 ** associated with the database connection pDb. ^If no prepared statement
5395 ** satisfies the conditions of this routine, it returns NULL.
5396 **
5397 ** The [database connection] pointer D in a call to
5398 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5399 ** connection and in particular must not be a NULL pointer.
5400 */
5402 
5403 /*
5404 ** CAPI3REF: Commit And Rollback Notification Callbacks
5405 ** METHOD: sqlite3
5406 **
5407 ** ^The sqlite3_commit_hook() interface registers a callback
5408 ** function to be invoked whenever a transaction is [COMMIT | committed].
5409 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5410 ** for the same database connection is overridden.
5411 ** ^The sqlite3_rollback_hook() interface registers a callback
5412 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5413 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5414 ** for the same database connection is overridden.
5415 ** ^The pArg argument is passed through to the callback.
5416 ** ^If the callback on a commit hook function returns non-zero,
5417 ** then the commit is converted into a rollback.
5418 **
5419 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5420 ** return the P argument from the previous call of the same function
5421 ** on the same [database connection] D, or NULL for
5422 ** the first call for each function on D.
5423 **
5424 ** The commit and rollback hook callbacks are not reentrant.
5425 ** The callback implementation must not do anything that will modify
5426 ** the database connection that invoked the callback. Any actions
5427 ** to modify the database connection must be deferred until after the
5428 ** completion of the [sqlite3_step()] call that triggered the commit
5429 ** or rollback hook in the first place.
5430 ** Note that running any other SQL statements, including SELECT statements,
5431 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5432 ** the database connections for the meaning of "modify" in this paragraph.
5433 **
5434 ** ^Registering a NULL function disables the callback.
5435 **
5436 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5437 ** operation is allowed to continue normally. ^If the commit hook
5438 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5439 ** ^The rollback hook is invoked on a rollback that results from a commit
5440 ** hook returning non-zero, just as it would be with any other rollback.
5441 **
5442 ** ^For the purposes of this API, a transaction is said to have been
5443 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5444 ** an error or constraint causes an implicit rollback to occur.
5445 ** ^The rollback callback is not invoked if a transaction is
5446 ** automatically rolled back because the database connection is closed.
5447 **
5448 ** See also the [sqlite3_update_hook()] interface.
5449 */
5450 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5451 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5452 
5453 /*
5454 ** CAPI3REF: Data Change Notification Callbacks
5455 ** METHOD: sqlite3
5456 **
5457 ** ^The sqlite3_update_hook() interface registers a callback function
5458 ** with the [database connection] identified by the first argument
5459 ** to be invoked whenever a row is updated, inserted or deleted in
5460 ** a [rowid table].
5461 ** ^Any callback set by a previous call to this function
5462 ** for the same database connection is overridden.
5463 **
5464 ** ^The second argument is a pointer to the function to invoke when a
5465 ** row is updated, inserted or deleted in a rowid table.
5466 ** ^The first argument to the callback is a copy of the third argument
5467 ** to sqlite3_update_hook().
5468 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5469 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5470 ** to be invoked.
5471 ** ^The third and fourth arguments to the callback contain pointers to the
5472 ** database and table name containing the affected row.
5473 ** ^The final callback parameter is the [rowid] of the row.
5474 ** ^In the case of an update, this is the [rowid] after the update takes place.
5475 **
5476 ** ^(The update hook is not invoked when internal system tables are
5477 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5478 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5479 **
5480 ** ^In the current implementation, the update hook
5481 ** is not invoked when duplication rows are deleted because of an
5482 ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
5483 ** invoked when rows are deleted using the [truncate optimization].
5484 ** The exceptions defined in this paragraph might change in a future
5485 ** release of SQLite.
5486 **
5487 ** The update hook implementation must not do anything that will modify
5488 ** the database connection that invoked the update hook. Any actions
5489 ** to modify the database connection must be deferred until after the
5490 ** completion of the [sqlite3_step()] call that triggered the update hook.
5491 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5492 ** database connections for the meaning of "modify" in this paragraph.
5493 **
5494 ** ^The sqlite3_update_hook(D,C,P) function
5495 ** returns the P argument from the previous call
5496 ** on the same [database connection] D, or NULL for
5497 ** the first call on D.
5498 **
5499 ** See also the [sqlite3_commit_hook()], [sqlite3_rollback_hook()],
5500 ** and [sqlite3_preupdate_hook()] interfaces.
5501 */
5503  sqlite3*,
5504  void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5505  void*
5506 );
5507 
5508 /*
5509 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5510 **
5511 ** ^(This routine enables or disables the sharing of the database cache
5512 ** and schema data structures between [database connection | connections]
5513 ** to the same database. Sharing is enabled if the argument is true
5514 ** and disabled if the argument is false.)^
5515 **
5516 ** ^Cache sharing is enabled and disabled for an entire process.
5517 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5518 ** sharing was enabled or disabled for each thread separately.
5519 **
5520 ** ^(The cache sharing mode set by this interface effects all subsequent
5521 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5522 ** Existing database connections continue use the sharing mode
5523 ** that was in effect at the time they were opened.)^
5524 **
5525 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5526 ** successfully. An [error code] is returned otherwise.)^
5527 **
5528 ** ^Shared cache is disabled by default. But this might change in
5529 ** future releases of SQLite. Applications that care about shared
5530 ** cache setting should set it explicitly.
5531 **
5532 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5533 ** and will always return SQLITE_MISUSE. On those systems,
5534 ** shared cache mode should be enabled per-database connection via
5535 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5536 **
5537 ** This interface is threadsafe on processors where writing a
5538 ** 32-bit integer is atomic.
5539 **
5540 ** See Also: [SQLite Shared-Cache Mode]
5541 */
5543 
5544 /*
5545 ** CAPI3REF: Attempt To Free Heap Memory
5546 **
5547 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5548 ** of heap memory by deallocating non-essential memory allocations
5549 ** held by the database library. Memory used to cache database
5550 ** pages to improve performance is an example of non-essential memory.
5551 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5552 ** which might be more or less than the amount requested.
5553 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5554 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5555 **
5556 ** See also: [sqlite3_db_release_memory()]
5557 */
5559 
5560 /*
5561 ** CAPI3REF: Free Memory Used By A Database Connection
5562 ** METHOD: sqlite3
5563 **
5564 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5565 ** memory as possible from database connection D. Unlike the
5566 ** [sqlite3_release_memory()] interface, this interface is in effect even
5567 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5568 ** omitted.
5569 **
5570 ** See also: [sqlite3_release_memory()]
5571 */
5573 
5574 /*
5575 ** CAPI3REF: Impose A Limit On Heap Size
5576 **
5577 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5578 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5579 ** ^SQLite strives to keep heap memory utilization below the soft heap
5580 ** limit by reducing the number of pages held in the page cache
5581 ** as heap memory usages approaches the limit.
5582 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5583 ** below the limit, it will exceed the limit rather than generate
5584 ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
5585 ** is advisory only.
5586 **
5587 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5588 ** the soft heap limit prior to the call, or negative in the case of an
5589 ** error. ^If the argument N is negative
5590 ** then no change is made to the soft heap limit. Hence, the current
5591 ** size of the soft heap limit can be determined by invoking
5592 ** sqlite3_soft_heap_limit64() with a negative argument.
5593 **
5594 ** ^If the argument N is zero then the soft heap limit is disabled.
5595 **
5596 ** ^(The soft heap limit is not enforced in the current implementation
5597 ** if one or more of following conditions are true:
5598 **
5599 ** <ul>
5600 ** <li> The soft heap limit is set to zero.
5601 ** <li> Memory accounting is disabled using a combination of the
5602 ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5603 ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5604 ** <li> An alternative page cache implementation is specified using
5605 ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5606 ** <li> The page cache allocates from its own memory pool supplied
5607 ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5608 ** from the heap.
5609 ** </ul>)^
5610 **
5611 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5612 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5613 ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5614 ** the soft heap limit is enforced on every memory allocation. Without
5615 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5616 ** when memory is allocated by the page cache. Testing suggests that because
5617 ** the page cache is the predominate memory user in SQLite, most
5618 ** applications will achieve adequate soft heap limit enforcement without
5619 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5620 **
5621 ** The circumstances under which SQLite will enforce the soft heap limit may
5622 ** changes in future releases of SQLite.
5623 */
5624 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5625 
5626 /*
5627 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5628 ** DEPRECATED
5629 **
5630 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5631 ** interface. This routine is provided for historical compatibility
5632 ** only. All new applications should use the
5633 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5634 */
5636 
5637 
5638 /*
5639 ** CAPI3REF: Extract Metadata About A Column Of A Table
5640 ** METHOD: sqlite3
5641 **
5642 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5643 ** information about column C of table T in database D
5644 ** on [database connection] X.)^ ^The sqlite3_table_column_metadata()
5645 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5646 ** the final five arguments with appropriate values if the specified
5647 ** column exists. ^The sqlite3_table_column_metadata() interface returns
5648 ** SQLITE_ERROR and if the specified column does not exist.
5649 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5650 ** NULL pointer, then this routine simply checks for the existance of the
5651 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5652 ** does not.
5653 **
5654 ** ^The column is identified by the second, third and fourth parameters to
5655 ** this function. ^(The second parameter is either the name of the database
5656 ** (i.e. "main", "temp", or an attached database) containing the specified
5657 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5658 ** for the table using the same algorithm used by the database engine to
5659 ** resolve unqualified table references.
5660 **
5661 ** ^The third and fourth parameters to this function are the table and column
5662 ** name of the desired column, respectively.
5663 **
5664 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5665 ** and subsequent parameters to this function. ^Any of these arguments may be
5666 ** NULL, in which case the corresponding element of metadata is omitted.
5667 **
5668 ** ^(<blockquote>
5669 ** <table border="1">
5670 ** <tr><th> Parameter <th> Output<br>Type <th> Description
5671 **
5672 ** <tr><td> 5th <td> const char* <td> Data type
5673 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5674 ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
5675 ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
5676 ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
5677 ** </table>
5678 ** </blockquote>)^
5679 **
5680 ** ^The memory pointed to by the character pointers returned for the
5681 ** declaration type and collation sequence is valid until the next
5682 ** call to any SQLite API function.
5683 **
5684 ** ^If the specified table is actually a view, an [error code] is returned.
5685 **
5686 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table
5687 ** is not a [WITHOUT ROWID] table and an
5688 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5689 ** parameters are set for the explicitly declared column. ^(If there is no
5690 ** [INTEGER PRIMARY KEY] column, then the outputs
5691 ** for the [rowid] are set as follows:
5692 **
5693 ** <pre>
5694 ** data type: "INTEGER"
5695 ** collation sequence: "BINARY"
5696 ** not null: 0
5697 ** primary key: 1
5698 ** auto increment: 0
5699 ** </pre>)^
5700 **
5701 ** ^This function causes all database schemas to be read from disk and
5702 ** parsed, if that has not already been done, and returns an error if
5703 ** any errors are encountered while loading the schema.
5704 */
5706  sqlite3 *db, /* Connection handle */
5707  const char *zDbName, /* Database name or NULL */
5708  const char *zTableName, /* Table name */
5709  const char *zColumnName, /* Column name */
5710  char const **pzDataType, /* OUTPUT: Declared data type */
5711  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
5712  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
5713  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
5714  int *pAutoinc /* OUTPUT: True if column is auto-increment */
5715 );
5716 
5717 /*
5718 ** CAPI3REF: Load An Extension
5719 ** METHOD: sqlite3
5720 **
5721 ** ^This interface loads an SQLite extension library from the named file.
5722 **
5723 ** ^The sqlite3_load_extension() interface attempts to load an
5724 ** [SQLite extension] library contained in the file zFile. If
5725 ** the file cannot be loaded directly, attempts are made to load
5726 ** with various operating-system specific extensions added.
5727 ** So for example, if "samplelib" cannot be loaded, then names like
5728 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5729 ** be tried also.
5730 **
5731 ** ^The entry point is zProc.
5732 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5733 ** entry point name on its own. It first tries "sqlite3_extension_init".
5734 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5735 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5736 ** characters in the filename from the last "/" to the first following
5737 ** "." and omitting any initial "lib".)^
5738 ** ^The sqlite3_load_extension() interface returns
5739 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5740 ** ^If an error occurs and pzErrMsg is not 0, then the
5741 ** [sqlite3_load_extension()] interface shall attempt to
5742 ** fill *pzErrMsg with error message text stored in memory
5743 ** obtained from [sqlite3_malloc()]. The calling function
5744 ** should free this memory by calling [sqlite3_free()].
5745 **
5746 ** ^Extension loading must be enabled using
5747 ** [sqlite3_enable_load_extension()] or
5748 ** [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],1,NULL)
5749 ** prior to calling this API,
5750 ** otherwise an error will be returned.
5751 **
5752 ** <b>Security warning:</b> It is recommended that the
5753 ** [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method be used to enable only this
5754 ** interface. The use of the [sqlite3_enable_load_extension()] interface
5755 ** should be avoided. This will keep the SQL function [load_extension()]
5756 ** disabled and prevent SQL injections from giving attackers
5757 ** access to extension loading capabilities.
5758 **
5759 ** See also the [load_extension() SQL function].
5760 */
5762  sqlite3 *db, /* Load the extension into this database connection */
5763  const char *zFile, /* Name of the shared library containing extension */
5764  const char *zProc, /* Entry point. Derived from zFile if 0 */
5765  char **pzErrMsg /* Put error message here if not 0 */
5766 );
5767 
5768 /*
5769 ** CAPI3REF: Enable Or Disable Extension Loading
5770 ** METHOD: sqlite3
5771 **
5772 ** ^So as not to open security holes in older applications that are
5773 ** unprepared to deal with [extension loading], and as a means of disabling
5774 ** [extension loading] while evaluating user-entered SQL, the following API
5775 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5776 **
5777 ** ^Extension loading is off by default.
5778 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5779 ** to turn extension loading on and call it with onoff==0 to turn
5780 ** it back off again.
5781 **
5782 ** ^This interface enables or disables both the C-API
5783 ** [sqlite3_load_extension()] and the SQL function [load_extension()].
5784 ** Use [sqlite3_db_config](db,[SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION],..)
5785 ** to enable or disable only the C-API.
5786 **
5787 ** <b>Security warning:</b> It is recommended that extension loading
5788 ** be disabled using the [SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION] method
5789 ** rather than this interface, so the [load_extension()] SQL function
5790 ** remains disabled. This will prevent SQL injections from giving attackers
5791 ** access to extension loading capabilities.
5792 */
5794 
5795 /*
5796 ** CAPI3REF: Automatically Load Statically Linked Extensions
5797 **
5798 ** ^This interface causes the xEntryPoint() function to be invoked for
5799 ** each new [database connection] that is created. The idea here is that
5800 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5801 ** that is to be automatically loaded into all new database connections.
5802 **
5803 ** ^(Even though the function prototype shows that xEntryPoint() takes
5804 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5805 ** arguments and expects and integer result as if the signature of the
5806 ** entry point where as follows:
5807 **
5808 ** <blockquote><pre>
5809 ** &nbsp; int xEntryPoint(
5810 ** &nbsp; sqlite3 *db,
5811 ** &nbsp; const char **pzErrMsg,
5812 ** &nbsp; const struct sqlite3_api_routines *pThunk
5813 ** &nbsp; );
5814 ** </pre></blockquote>)^
5815 **
5816 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5817 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5818 ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
5819 ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
5820 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
5821 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5822 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5823 **
5824 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5825 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5826 ** will be called more than once for each database connection that is opened.
5827 **
5828 ** See also: [sqlite3_reset_auto_extension()]
5829 ** and [sqlite3_cancel_auto_extension()]
5830 */
5831 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
5832 
5833 /*
5834 ** CAPI3REF: Cancel Automatic Extension Loading
5835 **
5836 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5837 ** initialization routine X that was registered using a prior call to
5838 ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
5839 ** routine returns 1 if initialization routine X was successfully
5840 ** unregistered and it returns 0 if X was not on the list of initialization
5841 ** routines.
5842 */
5843 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5844 
5845 /*
5846 ** CAPI3REF: Reset Automatic Extension Loading
5847 **
5848 ** ^This interface disables all automatic extensions previously
5849 ** registered using [sqlite3_auto_extension()].
5850 */
5852 
5853 /*
5854 ** The interface to the virtual-table mechanism is currently considered
5855 ** to be experimental. The interface might change in incompatible ways.
5856 ** If this is a problem for you, do not use the interface at this time.
5857 **
5858 ** When the virtual-table mechanism stabilizes, we will declare the
5859 ** interface fixed, support it indefinitely, and remove this comment.
5860 */
5861 
5862 /*
5863 ** Structures used by the virtual table interface
5864 */
5869 
5870 /*
5871 ** CAPI3REF: Virtual Table Object
5872 ** KEYWORDS: sqlite3_module {virtual table module}
5873 **
5874 ** This structure, sometimes called a "virtual table module",
5875 ** defines the implementation of a [virtual tables].
5876 ** This structure consists mostly of methods for the module.
5877 **
5878 ** ^A virtual table module is created by filling in a persistent
5879 ** instance of this structure and passing a pointer to that instance
5880 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5881 ** ^The registration remains valid until it is replaced by a different
5882 ** module or until the [database connection] closes. The content
5883 ** of this structure must not change while it is registered with
5884 ** any database connection.
5885 */
5888  int (*xCreate)(sqlite3*, void *pAux,
5889  int argc, const char *const*argv,
5890  sqlite3_vtab **ppVTab, char**);
5891  int (*xConnect)(sqlite3*, void *pAux,
5892  int argc, const char *const*argv,
5893  sqlite3_vtab **ppVTab, char**);
5894  int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5895  int (*xDisconnect)(sqlite3_vtab *pVTab);
5896  int (*xDestroy)(sqlite3_vtab *pVTab);
5897  int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5898  int (*xClose)(sqlite3_vtab_cursor*);
5899  int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5900  int argc, sqlite3_value **argv);
5901  int (*xNext)(sqlite3_vtab_cursor*);
5902  int (*xEof)(sqlite3_vtab_cursor*);
5903  int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5904  int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5905  int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5906  int (*xBegin)(sqlite3_vtab *pVTab);
5907  int (*xSync)(sqlite3_vtab *pVTab);
5908  int (*xCommit)(sqlite3_vtab *pVTab);
5909  int (*xRollback)(sqlite3_vtab *pVTab);
5910  int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5911  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5912  void **ppArg);
5913  int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5914  /* The methods above are in version 1 of the sqlite_module object. Those
5915  ** below are for version 2 and greater. */
5916  int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5917  int (*xRelease)(sqlite3_vtab *pVTab, int);
5918  int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5919 };
5920 
5921 /*
5922 ** CAPI3REF: Virtual Table Indexing Information
5923 ** KEYWORDS: sqlite3_index_info
5924 **
5925 ** The sqlite3_index_info structure and its substructures is used as part
5926 ** of the [virtual table] interface to
5927 ** pass information into and receive the reply from the [xBestIndex]
5928 ** method of a [virtual table module]. The fields under **Inputs** are the
5929 ** inputs to xBestIndex and are read-only. xBestIndex inserts its
5930 ** results into the **Outputs** fields.
5931 **
5932 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5933 **
5934 ** <blockquote>column OP expr</blockquote>
5935 **
5936 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
5937 ** stored in aConstraint[].op using one of the
5938 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5939 ** ^(The index of the column is stored in
5940 ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
5941 ** expr on the right-hand side can be evaluated (and thus the constraint
5942 ** is usable) and false if it cannot.)^
5943 **
5944 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5945 ** and makes other simplifications to the WHERE clause in an attempt to
5946 ** get as many WHERE clause terms into the form shown above as possible.
5947 ** ^The aConstraint[] array only reports WHERE clause terms that are
5948 ** relevant to the particular virtual table being queried.
5949 **
5950 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5951 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5952 **
5953 ** The colUsed field indicates which columns of the virtual table may be
5954 ** required by the current scan. Virtual table columns are numbered from
5955 ** zero in the order in which they appear within the CREATE TABLE statement
5956 ** passed to sqlite3_declare_vtab(). For the first 63 columns (columns 0-62),
5957 ** the corresponding bit is set within the colUsed mask if the column may be
5958 ** required by SQLite. If the table has at least 64 columns and any column
5959 ** to the right of the first 63 is required, then bit 63 of colUsed is also
5960 ** set. In other words, column iCol may be required if the expression
5961 ** (colUsed & ((sqlite3_uint64)1 << (iCol>=63 ? 63 : iCol))) evaluates to
5962 ** non-zero.
5963 **
5964 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5965 ** about what parameters to pass to xFilter. ^If argvIndex>0 then
5966 ** the right-hand side of the corresponding aConstraint[] is evaluated
5967 ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
5968 ** is true, then the constraint is assumed to be fully handled by the
5969 ** virtual table and is not checked again by SQLite.)^
5970 **
5971 ** ^The idxNum and idxPtr values are recorded and passed into the
5972 ** [xFilter] method.
5973 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5974 ** needToFreeIdxPtr is true.
5975 **
5976 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5977 ** the correct order to satisfy the ORDER BY clause so that no separate
5978 ** sorting step is required.
5979 **
5980 ** ^The estimatedCost value is an estimate of the cost of a particular
5981 ** strategy. A cost of N indicates that the cost of the strategy is similar
5982 ** to a linear scan of an SQLite table with N rows. A cost of log(N)
5983 ** indicates that the expense of the operation is similar to that of a
5984 ** binary search on a unique indexed field of an SQLite table with N rows.
5985 **
5986 ** ^The estimatedRows value is an estimate of the number of rows that
5987 ** will be returned by the strategy.
5988 **
5989 ** The xBestIndex method may optionally populate the idxFlags field with a
5990 ** mask of SQLITE_INDEX_SCAN_* flags. Currently there is only one such flag -
5991 ** SQLITE_INDEX_SCAN_UNIQUE. If the xBestIndex method sets this flag, SQLite
5992 ** assumes that the strategy may visit at most one row.
5993 **
5994 ** Additionally, if xBestIndex sets the SQLITE_INDEX_SCAN_UNIQUE flag, then
5995 ** SQLite also assumes that if a call to the xUpdate() method is made as
5996 ** part of the same statement to delete or update a virtual table row and the
5997 ** implementation returns SQLITE_CONSTRAINT, then there is no need to rollback
5998 ** any database changes. In other words, if the xUpdate() returns
5999 ** SQLITE_CONSTRAINT, the database contents must be exactly as they were
6000 ** before xUpdate was called. By contrast, if SQLITE_INDEX_SCAN_UNIQUE is not
6001 ** set and xUpdate returns SQLITE_CONSTRAINT, any database changes made by
6002 ** the xUpdate method are automatically rolled back by SQLite.
6003 **
6004 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
6005 ** structure for SQLite version 3.8.2. If a virtual table extension is
6006 ** used with an SQLite version earlier than 3.8.2, the results of attempting
6007 ** to read or write the estimatedRows field are undefined (but are likely
6008 ** to included crashing the application). The estimatedRows field should
6009 ** therefore only be used if [sqlite3_libversion_number()] returns a
6010 ** value greater than or equal to 3008002. Similarly, the idxFlags field
6011 ** was added for version 3.9.0. It may therefore only be used if
6012 ** sqlite3_libversion_number() returns a value greater than or equal to
6013 ** 3009000.
6014 */
6016  /* Inputs */
6017  int nConstraint; /* Number of entries in aConstraint */
6019  int iColumn; /* Column constrained. -1 for ROWID */
6020  unsigned char op; /* Constraint operator */
6021  unsigned char usable; /* True if this constraint is usable */
6022  int iTermOffset; /* Used internally - xBestIndex should ignore */
6023  } *aConstraint; /* Table of WHERE clause constraints */
6024  int nOrderBy; /* Number of terms in the ORDER BY clause */
6026  int iColumn; /* Column number */
6027  unsigned char desc; /* True for DESC. False for ASC. */
6028  } *aOrderBy; /* The ORDER BY clause */
6029  /* Outputs */
6031  int argvIndex; /* if >0, constraint is part of argv to xFilter */
6032  unsigned char omit; /* Do not code a test for this constraint */
6033  } *aConstraintUsage;
6034  int idxNum; /* Number used to identify the index */
6035  char *idxStr; /* String, possibly obtained from sqlite3_malloc */
6036  int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
6037  int orderByConsumed; /* True if output is already ordered */
6038  double estimatedCost; /* Estimated cost of using this index */
6039  /* Fields below are only available in SQLite 3.8.2 and later */
6040  sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
6041  /* Fields below are only available in SQLite 3.9.0 and later */
6042  int idxFlags; /* Mask of SQLITE_INDEX_SCAN_* flags */
6043  /* Fields below are only available in SQLite 3.10.0 and later */
6044  sqlite3_uint64 colUsed; /* Input: Mask of columns used by statement */
6045 };
6046 
6047 /*
6048 ** CAPI3REF: Virtual Table Scan Flags
6049 */
6050 #define SQLITE_INDEX_SCAN_UNIQUE 1 /* Scan visits at most 1 row */
6051 
6052 /*
6053 ** CAPI3REF: Virtual Table Constraint Operator Codes
6054 **
6055 ** These macros defined the allowed values for the
6056 ** [sqlite3_index_info].aConstraint[].op field. Each value represents
6057 ** an operator that is part of a constraint term in the wHERE clause of
6058 ** a query that uses a [virtual table].
6059 */
6060 #define SQLITE_INDEX_CONSTRAINT_EQ 2
6061 #define SQLITE_INDEX_CONSTRAINT_GT 4
6062 #define SQLITE_INDEX_CONSTRAINT_LE 8
6063 #define SQLITE_INDEX_CONSTRAINT_LT 16
6064 #define SQLITE_INDEX_CONSTRAINT_GE 32
6065 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
6066 #define SQLITE_INDEX_CONSTRAINT_LIKE 65
6067 #define SQLITE_INDEX_CONSTRAINT_GLOB 66
6068 #define SQLITE_INDEX_CONSTRAINT_REGEXP 67
6069 
6070 /*
6071 ** CAPI3REF: Register A Virtual Table Implementation
6072 ** METHOD: sqlite3
6073 **
6074 ** ^These routines are used to register a new [virtual table module] name.
6075 ** ^Module names must be registered before
6076 ** creating a new [virtual table] using the module and before using a
6077 ** preexisting [virtual table] for the module.
6078 **
6079 ** ^The module name is registered on the [database connection] specified
6080 ** by the first parameter. ^The name of the module is given by the
6081 ** second parameter. ^The third parameter is a pointer to
6082 ** the implementation of the [virtual table module]. ^The fourth
6083 ** parameter is an arbitrary client data pointer that is passed through
6084 ** into the [xCreate] and [xConnect] methods of the virtual table module
6085 ** when a new virtual table is be being created or reinitialized.
6086 **
6087 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
6088 ** is a pointer to a destructor for the pClientData. ^SQLite will
6089 ** invoke the destructor function (if it is not NULL) when SQLite
6090 ** no longer needs the pClientData pointer. ^The destructor will also
6091 ** be invoked if the call to sqlite3_create_module_v2() fails.
6092 ** ^The sqlite3_create_module()
6093 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
6094 ** destructor.
6095 */
6097  sqlite3 *db, /* SQLite connection to register module with */
6098  const char *zName, /* Name of the module */
6099  const sqlite3_module *p, /* Methods for the module */
6100  void *pClientData /* Client data for xCreate/xConnect */
6101 );
6103  sqlite3 *db, /* SQLite connection to register module with */
6104  const char *zName, /* Name of the module */
6105  const sqlite3_module *p, /* Methods for the module */
6106  void *pClientData, /* Client data for xCreate/xConnect */
6107  void(*xDestroy)(void*) /* Module destructor function */
6108 );
6109 
6110 /*
6111 ** CAPI3REF: Virtual Table Instance Object
6112 ** KEYWORDS: sqlite3_vtab
6113 **
6114 ** Every [virtual table module] implementation uses a subclass
6115 ** of this object to describe a particular instance
6116 ** of the [virtual table]. Each subclass will
6117 ** be tailored to the specific needs of the module implementation.
6118 ** The purpose of this superclass is to define certain fields that are
6119 ** common to all module implementations.
6120 **
6121 ** ^Virtual tables methods can set an error message by assigning a
6122 ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
6123 ** take care that any prior string is freed by a call to [sqlite3_free()]
6124 ** prior to assigning a new string to zErrMsg. ^After the error message
6125 ** is delivered up to the client application, the string will be automatically
6126 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
6127 */
6129  const sqlite3_module *pModule; /* The module for this virtual table */
6130  int nRef; /* Number of open cursors */
6131  char *zErrMsg; /* Error message from sqlite3_mprintf() */
6132  /* Virtual table implementations will typically add additional fields */
6133 };
6134 
6135 /*
6136 ** CAPI3REF: Virtual Table Cursor Object
6137 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
6138 **
6139 ** Every [virtual table module] implementation uses a subclass of the
6140 ** following structure to describe cursors that point into the
6141 ** [virtual table] and are used
6142 ** to loop through the virtual table. Cursors are created using the
6143 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
6144 ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
6145 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
6146 ** of the module. Each module implementation will define
6147 ** the content of a cursor structure to suit its own needs.
6148 **
6149 ** This superclass exists in order to define fields of the cursor that
6150 ** are common to all implementations.
6151 */
6153  sqlite3_vtab *pVtab; /* Virtual table of this cursor */
6154  /* Virtual table implementations will typically add additional fields */
6155 };
6156 
6157 /*
6158 ** CAPI3REF: Declare The Schema Of A Virtual Table
6159 **
6160 ** ^The [xCreate] and [xConnect] methods of a
6161 ** [virtual table module] call this interface
6162 ** to declare the format (the names and datatypes of the columns) of
6163 ** the virtual tables they implement.
6164 */
6165 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
6166 
6167 /*
6168 ** CAPI3REF: Overload A Function For A Virtual Table
6169 ** METHOD: sqlite3
6170 **
6171 ** ^(Virtual tables can provide alternative implementations of functions
6172 ** using the [xFindFunction] method of the [virtual table module].
6173 ** But global versions of those functions
6174 ** must exist in order to be overloaded.)^
6175 **
6176 ** ^(This API makes sure a global version of a function with a particular
6177 ** name and number of parameters exists. If no such function exists
6178 ** before this API is called, a new function is created.)^ ^The implementation
6179 ** of the new function always causes an exception to be thrown. So
6180 ** the new function is not good for anything by itself. Its only
6181 ** purpose is to be a placeholder function that can be overloaded
6182 ** by a [virtual table].
6183 */
6184 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
6185 
6186 /*
6187 ** The interface to the virtual-table mechanism defined above (back up
6188 ** to a comment remarkably similar to this one) is currently considered
6189 ** to be experimental. The interface might change in incompatible ways.
6190 ** If this is a problem for you, do not use the interface at this time.
6191 **
6192 ** When the virtual-table mechanism stabilizes, we will declare the
6193 ** interface fixed, support it indefinitely, and remove this comment.
6194 */
6195 
6196 /*
6197 ** CAPI3REF: A Handle To An Open BLOB
6198 ** KEYWORDS: {BLOB handle} {BLOB handles}
6199 **
6200 ** An instance of this object represents an open BLOB on which
6201 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
6202 ** ^Objects of this type are created by [sqlite3_blob_open()]
6203 ** and destroyed by [sqlite3_blob_close()].
6204 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
6205 ** can be used to read or write small subsections of the BLOB.
6206 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
6207 */
6209 
6210 /*
6211 ** CAPI3REF: Open A BLOB For Incremental I/O
6212 ** METHOD: sqlite3
6213 ** CONSTRUCTOR: sqlite3_blob
6214 **
6215 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
6216 ** in row iRow, column zColumn, table zTable in database zDb;
6217 ** in other words, the same BLOB that would be selected by:
6218 **
6219 ** <pre>
6220 ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
6221 ** </pre>)^
6222 **
6223 ** ^(Parameter zDb is not the filename that contains the database, but
6224 ** rather the symbolic name of the database. For attached databases, this is
6225 ** the name that appears after the AS keyword in the [ATTACH] statement.
6226 ** For the main database file, the database name is "main". For TEMP
6227 ** tables, the database name is "temp".)^
6228 **
6229 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
6230 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
6231 ** read-only access.
6232 **
6233 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
6234 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
6235 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
6236 ** the API is not misused, it is always safe to call [sqlite3_blob_close()]
6237 ** on *ppBlob after this function it returns.
6238 **
6239 ** This function fails with SQLITE_ERROR if any of the following are true:
6240 ** <ul>
6241 ** <li> ^(Database zDb does not exist)^,
6242 ** <li> ^(Table zTable does not exist within database zDb)^,
6243 ** <li> ^(Table zTable is a WITHOUT ROWID table)^,
6244 ** <li> ^(Column zColumn does not exist)^,
6245 ** <li> ^(Row iRow is not present in the table)^,
6246 ** <li> ^(The specified column of row iRow contains a value that is not
6247 ** a TEXT or BLOB value)^,
6248 ** <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE
6249 ** constraint and the blob is being opened for read/write access)^,
6250 ** <li> ^([foreign key constraints | Foreign key constraints] are enabled,
6251 ** column zColumn is part of a [child key] definition and the blob is
6252 ** being opened for read/write access)^.
6253 ** </ul>
6254 **
6255 ** ^Unless it returns SQLITE_MISUSE, this function sets the
6256 ** [database connection] error code and message accessible via
6257 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6258 **
6259 **
6260 ** ^(If the row that a BLOB handle points to is modified by an
6261 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
6262 ** then the BLOB handle is marked as "expired".
6263 ** This is true if any column of the row is changed, even a column
6264 ** other than the one the BLOB handle is open on.)^
6265 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
6266 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
6267 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
6268 ** rolled back by the expiration of the BLOB. Such changes will eventually
6269 ** commit if the transaction continues to completion.)^
6270 **
6271 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
6272 ** the opened blob. ^The size of a blob may not be changed by this
6273 ** interface. Use the [UPDATE] SQL command to change the size of a
6274 ** blob.
6275 **
6276 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
6277 ** and the built-in [zeroblob] SQL function may be used to create a
6278 ** zero-filled blob to read or write using the incremental-blob interface.
6279 **
6280 ** To avoid a resource leak, every open [BLOB handle] should eventually
6281 ** be released by a call to [sqlite3_blob_close()].
6282 */
6284  sqlite3*,
6285  const char *zDb,
6286  const char *zTable,
6287  const char *zColumn,
6288  sqlite3_int64 iRow,
6289  int flags,
6290  sqlite3_blob **ppBlob
6291 );
6292 
6293 /*
6294 ** CAPI3REF: Move a BLOB Handle to a New Row
6295 ** METHOD: sqlite3_blob
6296 **
6297 ** ^This function is used to move an existing blob handle so that it points
6298 ** to a different row of the same database table. ^The new row is identified
6299 ** by the rowid value passed as the second argument. Only the row can be
6300 ** changed. ^The database, table and column on which the blob handle is open
6301 ** remain the same. Moving an existing blob handle to a new row can be
6302 ** faster than closing the existing handle and opening a new one.
6303 **
6304 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6305 ** it must exist and there must be either a blob or text value stored in
6306 ** the nominated column.)^ ^If the new row is not present in the table, or if
6307 ** it does not contain a blob or text value, or if another error occurs, an
6308 ** SQLite error code is returned and the blob handle is considered aborted.
6309 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6310 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6311 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6312 ** always returns zero.
6313 **
6314 ** ^This function sets the database handle error code and message.
6315 */
6317 
6318 /*
6319 ** CAPI3REF: Close A BLOB Handle
6320 ** DESTRUCTOR: sqlite3_blob
6321 **
6322 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6323 ** unconditionally. Even if this routine returns an error code, the
6324 ** handle is still closed.)^
6325 **
6326 ** ^If the blob handle being closed was opened for read-write access, and if
6327 ** the database is in auto-commit mode and there are no other open read-write
6328 ** blob handles or active write statements, the current transaction is
6329 ** committed. ^If an error occurs while committing the transaction, an error
6330 ** code is returned and the transaction rolled back.
6331 **
6332 ** Calling this function with an argument that is not a NULL pointer or an
6333 ** open blob handle results in undefined behaviour. ^Calling this routine
6334 ** with a null pointer (such as would be returned by a failed call to
6335 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6336 ** is passed a valid open blob handle, the values returned by the
6337 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6338 */
6340 
6341 /*
6342 ** CAPI3REF: Return The Size Of An Open BLOB
6343 ** METHOD: sqlite3_blob
6344 **
6345 ** ^Returns the size in bytes of the BLOB accessible via the
6346 ** successfully opened [BLOB handle] in its only argument. ^The
6347 ** incremental blob I/O routines can only read or overwriting existing
6348 ** blob content; they cannot change the size of a blob.
6349 **
6350 ** This routine only works on a [BLOB handle] which has been created
6351 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6352 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6353 ** to this routine results in undefined and probably undesirable behavior.
6354 */
6356 
6357 /*
6358 ** CAPI3REF: Read Data From A BLOB Incrementally
6359 ** METHOD: sqlite3_blob
6360 **
6361 ** ^(This function is used to read data from an open [BLOB handle] into a
6362 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6363 ** from the open BLOB, starting at offset iOffset.)^
6364 **
6365 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6366 ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
6367 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6368 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6369 ** can be determined using the [sqlite3_blob_bytes()] interface.
6370 **
6371 ** ^An attempt to read from an expired [BLOB handle] fails with an
6372 ** error code of [SQLITE_ABORT].
6373 **
6374 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6375 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6376 **
6377 ** This routine only works on a [BLOB handle] which has been created
6378 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6379 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6380 ** to this routine results in undefined and probably undesirable behavior.
6381 **
6382 ** See also: [sqlite3_blob_write()].
6383 */
6384 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6385 
6386 /*
6387 ** CAPI3REF: Write Data Into A BLOB Incrementally
6388 ** METHOD: sqlite3_blob
6389 **
6390 ** ^(This function is used to write data into an open [BLOB handle] from a
6391 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6392 ** into the open BLOB, starting at offset iOffset.)^
6393 **
6394 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6395 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6396 ** ^Unless SQLITE_MISUSE is returned, this function sets the
6397 ** [database connection] error code and message accessible via
6398 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions.
6399 **
6400 ** ^If the [BLOB handle] passed as the first argument was not opened for
6401 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6402 ** this function returns [SQLITE_READONLY].
6403 **
6404 ** This function may only modify the contents of the BLOB; it is
6405 ** not possible to increase the size of a BLOB using this API.
6406 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6407 ** [SQLITE_ERROR] is returned and no data is written. The size of the
6408 ** BLOB (and hence the maximum value of N+iOffset) can be determined
6409 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less
6410 ** than zero [SQLITE_ERROR] is returned and no data is written.
6411 **
6412 ** ^An attempt to write to an expired [BLOB handle] fails with an
6413 ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
6414 ** before the [BLOB handle] expired are not rolled back by the
6415 ** expiration of the handle, though of course those changes might
6416 ** have been overwritten by the statement that expired the BLOB handle
6417 ** or by other independent statements.
6418 **
6419 ** This routine only works on a [BLOB handle] which has been created
6420 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6421 ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
6422 ** to this routine results in undefined and probably undesirable behavior.
6423 **
6424 ** See also: [sqlite3_blob_read()].
6425 */
6426 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6427 
6428 /*
6429 ** CAPI3REF: Virtual File System Objects
6430 **
6431 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6432 ** that SQLite uses to interact
6433 ** with the underlying operating system. Most SQLite builds come with a
6434 ** single default VFS that is appropriate for the host computer.
6435 ** New VFSes can be registered and existing VFSes can be unregistered.
6436 ** The following interfaces are provided.
6437 **
6438 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6439 ** ^Names are case sensitive.
6440 ** ^Names are zero-terminated UTF-8 strings.
6441 ** ^If there is no match, a NULL pointer is returned.
6442 ** ^If zVfsName is NULL then the default VFS is returned.
6443 **
6444 ** ^New VFSes are registered with sqlite3_vfs_register().
6445 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6446 ** ^The same VFS can be registered multiple times without injury.
6447 ** ^To make an existing VFS into the default VFS, register it again
6448 ** with the makeDflt flag set. If two different VFSes with the
6449 ** same name are registered, the behavior is undefined. If a
6450 ** VFS is registered with a name that is NULL or an empty string,
6451 ** then the behavior is undefined.
6452 **
6453 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6454 ** ^(If the default VFS is unregistered, another VFS is chosen as
6455 ** the default. The choice for the new VFS is arbitrary.)^
6456 */
6457 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6458 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6460 
6461 /*
6462 ** CAPI3REF: Mutexes
6463 **
6464 ** The SQLite core uses these routines for thread
6465 ** synchronization. Though they are intended for internal
6466 ** use by SQLite, code that links against SQLite is
6467 ** permitted to use any of these routines.
6468 **
6469 ** The SQLite source code contains multiple implementations
6470 ** of these mutex routines. An appropriate implementation
6471 ** is selected automatically at compile-time. The following
6472 ** implementations are available in the SQLite core:
6473 **
6474 ** <ul>
6475 ** <li> SQLITE_MUTEX_PTHREADS
6476 ** <li> SQLITE_MUTEX_W32
6477 ** <li> SQLITE_MUTEX_NOOP
6478 ** </ul>
6479 **
6480 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6481 ** that does no real locking and is appropriate for use in
6482 ** a single-threaded application. The SQLITE_MUTEX_PTHREADS and
6483 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6484 ** and Windows.
6485 **
6486 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6487 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6488 ** implementation is included with the library. In this case the
6489 ** application must supply a custom mutex implementation using the
6490 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6491 ** before calling sqlite3_initialize() or any other public sqlite3_
6492 ** function that calls sqlite3_initialize().
6493 **
6494 ** ^The sqlite3_mutex_alloc() routine allocates a new
6495 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6496 ** routine returns NULL if it is unable to allocate the requested
6497 ** mutex. The argument to sqlite3_mutex_alloc() must one of these
6498 ** integer constants:
6499 **
6500 ** <ul>
6501 ** <li> SQLITE_MUTEX_FAST
6502 ** <li> SQLITE_MUTEX_RECURSIVE
6503 ** <li> SQLITE_MUTEX_STATIC_MASTER
6504 ** <li> SQLITE_MUTEX_STATIC_MEM
6505 ** <li> SQLITE_MUTEX_STATIC_OPEN
6506 ** <li> SQLITE_MUTEX_STATIC_PRNG
6507 ** <li> SQLITE_MUTEX_STATIC_LRU
6508 ** <li> SQLITE_MUTEX_STATIC_PMEM
6509 ** <li> SQLITE_MUTEX_STATIC_APP1
6510 ** <li> SQLITE_MUTEX_STATIC_APP2
6511 ** <li> SQLITE_MUTEX_STATIC_APP3
6512 ** <li> SQLITE_MUTEX_STATIC_VFS1
6513 ** <li> SQLITE_MUTEX_STATIC_VFS2
6514 ** <li> SQLITE_MUTEX_STATIC_VFS3
6515 ** </ul>
6516 **
6517 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6518 ** cause sqlite3_mutex_alloc() to create
6519 ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6520 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6521 ** The mutex implementation does not need to make a distinction
6522 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6523 ** not want to. SQLite will only request a recursive mutex in
6524 ** cases where it really needs one. If a faster non-recursive mutex
6525 ** implementation is available on the host platform, the mutex subsystem
6526 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6527 **
6528 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6529 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6530 ** a pointer to a static preexisting mutex. ^Nine static mutexes are
6531 ** used by the current version of SQLite. Future versions of SQLite
6532 ** may add additional static mutexes. Static mutexes are for internal
6533 ** use by SQLite only. Applications that use SQLite mutexes should
6534 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6535 ** SQLITE_MUTEX_RECURSIVE.
6536 **
6537 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6538 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6539 ** returns a different mutex on every call. ^For the static
6540 ** mutex types, the same mutex is returned on every call that has
6541 ** the same type number.
6542 **
6543 ** ^The sqlite3_mutex_free() routine deallocates a previously
6544 ** allocated dynamic mutex. Attempting to deallocate a static
6545 ** mutex results in undefined behavior.
6546 **
6547 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6548 ** to enter a mutex. ^If another thread is already within the mutex,
6549 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6550 ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6551 ** upon successful entry. ^(Mutexes created using
6552 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6553 ** In such cases, the
6554 ** mutex must be exited an equal number of times before another thread
6555 ** can enter.)^ If the same thread tries to enter any mutex other
6556 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6557 **
6558 ** ^(Some systems (for example, Windows 95) do not support the operation
6559 ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
6560 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6561 ** sqlite3_mutex_try() as an optimization so this is acceptable
6562 ** behavior.)^
6563 **
6564 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6565 ** previously entered by the same thread. The behavior
6566 ** is undefined if the mutex is not currently entered by the
6567 ** calling thread or is not currently allocated.
6568 **
6569 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6570 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6571 ** behave as no-ops.
6572 **
6573 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6574 */
6580 
6581 /*
6582 ** CAPI3REF: Mutex Methods Object
6583 **
6584 ** An instance of this structure defines the low-level routines
6585 ** used to allocate and use mutexes.
6586 **
6587 ** Usually, the default mutex implementations provided by SQLite are
6588 ** sufficient, however the application has the option of substituting a custom
6589 ** implementation for specialized deployments or systems for which SQLite
6590 ** does not provide a suitable implementation. In this case, the application
6591 ** creates and populates an instance of this structure to pass
6592 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6593 ** Additionally, an instance of this structure can be used as an
6594 ** output variable when querying the system for the current mutex
6595 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6596 **
6597 ** ^The xMutexInit method defined by this structure is invoked as
6598 ** part of system initialization by the sqlite3_initialize() function.
6599 ** ^The xMutexInit routine is called by SQLite exactly once for each
6600 ** effective call to [sqlite3_initialize()].
6601 **
6602 ** ^The xMutexEnd method defined by this structure is invoked as
6603 ** part of system shutdown by the sqlite3_shutdown() function. The
6604 ** implementation of this method is expected to release all outstanding
6605 ** resources obtained by the mutex methods implementation, especially
6606 ** those obtained by the xMutexInit method. ^The xMutexEnd()
6607 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6608 **
6609 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6610 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6611 ** xMutexNotheld) implement the following interfaces (respectively):
6612 **
6613 ** <ul>
6614 ** <li> [sqlite3_mutex_alloc()] </li>
6615 ** <li> [sqlite3_mutex_free()] </li>
6616 ** <li> [sqlite3_mutex_enter()] </li>
6617 ** <li> [sqlite3_mutex_try()] </li>
6618 ** <li> [sqlite3_mutex_leave()] </li>
6619 ** <li> [sqlite3_mutex_held()] </li>
6620 ** <li> [sqlite3_mutex_notheld()] </li>
6621 ** </ul>)^
6622 **
6623 ** The only difference is that the public sqlite3_XXX functions enumerated
6624 ** above silently ignore any invocations that pass a NULL pointer instead
6625 ** of a valid mutex handle. The implementations of the methods defined
6626 ** by this structure are not required to handle this case, the results
6627 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6628 ** (i.e. it is acceptable to provide an implementation that segfaults if
6629 ** it is passed a NULL pointer).
6630 **
6631 ** The xMutexInit() method must be threadsafe. It must be harmless to
6632 ** invoke xMutexInit() multiple times within the same process and without
6633 ** intervening calls to xMutexEnd(). Second and subsequent calls to
6634 ** xMutexInit() must be no-ops.
6635 **
6636 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6637 ** and its associates). Similarly, xMutexAlloc() must not use SQLite memory
6638 ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
6639 ** memory allocation for a fast or recursive mutex.
6640 **
6641 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6642 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6643 ** If xMutexInit fails in any way, it is expected to clean up after itself
6644 ** prior to returning.
6645 */
6648  int (*xMutexInit)(void);
6649  int (*xMutexEnd)(void);
6650  sqlite3_mutex *(*xMutexAlloc)(int);
6651  void (*xMutexFree)(sqlite3_mutex *);
6652  void (*xMutexEnter)(sqlite3_mutex *);
6653  int (*xMutexTry)(sqlite3_mutex *);
6654  void (*xMutexLeave)(sqlite3_mutex *);
6655  int (*xMutexHeld)(sqlite3_mutex *);
6656  int (*xMutexNotheld)(sqlite3_mutex *);
6657 };
6658 
6659 /*
6660 ** CAPI3REF: Mutex Verification Routines
6661 **
6662 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6663 ** are intended for use inside assert() statements. The SQLite core
6664 ** never uses these routines except inside an assert() and applications
6665 ** are advised to follow the lead of the core. The SQLite core only
6666 ** provides implementations for these routines when it is compiled
6667 ** with the SQLITE_DEBUG flag. External mutex implementations
6668 ** are only required to provide these routines if SQLITE_DEBUG is
6669 ** defined and if NDEBUG is not defined.
6670 **
6671 ** These routines should return true if the mutex in their argument
6672 ** is held or not held, respectively, by the calling thread.
6673 **
6674 ** The implementation is not required to provide versions of these
6675 ** routines that actually work. If the implementation does not provide working
6676 ** versions of these routines, it should at least provide stubs that always
6677 ** return true so that one does not get spurious assertion failures.
6678 **
6679 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6680 ** the routine should return 1. This seems counter-intuitive since
6681 ** clearly the mutex cannot be held if it does not exist. But
6682 ** the reason the mutex does not exist is because the build is not
6683 ** using mutexes. And we do not want the assert() containing the
6684 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6685 ** the appropriate thing to do. The sqlite3_mutex_notheld()
6686 ** interface should also return 1 when given a NULL pointer.
6687 */
6688 #ifndef NDEBUG
6691 #endif
6692 
6693 /*
6694 ** CAPI3REF: Mutex Types
6695 **
6696 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6697 ** which is one of these integer constants.
6698 **
6699 ** The set of static mutexes may change from one SQLite release to the
6700 ** next. Applications that override the built-in mutex logic must be
6701 ** prepared to accommodate additional static mutexes.
6702 */
6703 #define SQLITE_MUTEX_FAST 0
6704 #define SQLITE_MUTEX_RECURSIVE 1
6705 #define SQLITE_MUTEX_STATIC_MASTER 2
6706 #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
6707 #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
6708 #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
6709 #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
6710 #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
6711 #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
6712 #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
6713 #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
6714 #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
6715 #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
6716 #define SQLITE_MUTEX_STATIC_VFS1 11 /* For use by built-in VFS */
6717 #define SQLITE_MUTEX_STATIC_VFS2 12 /* For use by extension VFS */
6718 #define SQLITE_MUTEX_STATIC_VFS3 13 /* For use by application VFS */
6719 
6720 /*
6721 ** CAPI3REF: Retrieve the mutex for a database connection
6722 ** METHOD: sqlite3
6723 **
6724 ** ^This interface returns a pointer the [sqlite3_mutex] object that
6725 ** serializes access to the [database connection] given in the argument
6726 ** when the [threading mode] is Serialized.
6727 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6728 ** routine returns a NULL pointer.
6729 */
6731 
6732 /*
6733 ** CAPI3REF: Low-Level Control Of Database Files
6734 ** METHOD: sqlite3
6735 **
6736 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6737 ** xFileControl method for the [sqlite3_io_methods] object associated
6738 ** with a particular database identified by the second argument. ^The
6739 ** name of the database is "main" for the main database or "temp" for the
6740 ** TEMP database, or the name that appears after the AS keyword for
6741 ** databases that are added using the [ATTACH] SQL command.
6742 ** ^A NULL pointer can be used in place of "main" to refer to the
6743 ** main database file.
6744 ** ^The third and fourth parameters to this routine
6745 ** are passed directly through to the second and third parameters of
6746 ** the xFileControl method. ^The return value of the xFileControl
6747 ** method becomes the return value of this routine.
6748 **
6749 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6750 ** a pointer to the underlying [sqlite3_file] object to be written into
6751 ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
6752 ** case is a short-circuit path which does not actually invoke the
6753 ** underlying sqlite3_io_methods.xFileControl method.
6754 **
6755 ** ^If the second parameter (zDbName) does not match the name of any
6756 ** open database file, then SQLITE_ERROR is returned. ^This error
6757 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6758 ** or [sqlite3_errmsg()]. The underlying xFileControl method might
6759 ** also return SQLITE_ERROR. There is no way to distinguish between
6760 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6761 ** xFileControl method.
6762 **
6763 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6764 */
6765 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6766 
6767 /*
6768 ** CAPI3REF: Testing Interface
6769 **
6770 ** ^The sqlite3_test_control() interface is used to read out internal
6771 ** state of SQLite and to inject faults into SQLite for testing
6772 ** purposes. ^The first parameter is an operation code that determines
6773 ** the number, meaning, and operation of all subsequent parameters.
6774 **
6775 ** This interface is not for use by applications. It exists solely
6776 ** for verifying the correct operation of the SQLite library. Depending
6777 ** on how the SQLite library is compiled, this interface might not exist.
6778 **
6779 ** The details of the operation codes, their meanings, the parameters
6780 ** they take, and what they do are all subject to change without notice.
6781 ** Unlike most of the SQLite API, this function is not guaranteed to
6782 ** operate consistently from one release to the next.
6783 */
6785 
6786 /*
6787 ** CAPI3REF: Testing Interface Operation Codes
6788 **
6789 ** These constants are the valid operation code parameters used
6790 ** as the first argument to [sqlite3_test_control()].
6791 **
6792 ** These parameters and their meanings are subject to change
6793 ** without notice. These values are for testing purposes only.
6794 ** Applications should not use any of these parameters or the
6795 ** [sqlite3_test_control()] interface.
6796 */
6797 #define SQLITE_TESTCTRL_FIRST 5
6798 #define SQLITE_TESTCTRL_PRNG_SAVE 5
6799 #define SQLITE_TESTCTRL_PRNG_RESTORE 6
6800 #define SQLITE_TESTCTRL_PRNG_RESET 7
6801 #define SQLITE_TESTCTRL_BITVEC_TEST 8
6802 #define SQLITE_TESTCTRL_FAULT_INSTALL 9
6803 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
6804 #define SQLITE_TESTCTRL_PENDING_BYTE 11
6805 #define SQLITE_TESTCTRL_ASSERT 12
6806 #define SQLITE_TESTCTRL_ALWAYS 13
6807 #define SQLITE_TESTCTRL_RESERVE 14
6808 #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
6809 #define SQLITE_TESTCTRL_ISKEYWORD 16
6810 #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
6811 #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
6812 #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
6813 #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
6814 #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
6815 #define SQLITE_TESTCTRL_BYTEORDER 22
6816 #define SQLITE_TESTCTRL_ISINIT 23
6817 #define SQLITE_TESTCTRL_SORTER_MMAP 24
6818 #define SQLITE_TESTCTRL_IMPOSTER 25
6819 #define SQLITE_TESTCTRL_LAST 25
6820 
6821 /*
6822 ** CAPI3REF: SQLite Runtime Status
6823 **
6824 ** ^These interfaces are used to retrieve runtime status information
6825 ** about the performance of SQLite, and optionally to reset various
6826 ** highwater marks. ^The first argument is an integer code for
6827 ** the specific parameter to measure. ^(Recognized integer codes
6828 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6829 ** ^The current value of the parameter is returned into *pCurrent.
6830 ** ^The highest recorded value is returned in *pHighwater. ^If the
6831 ** resetFlag is true, then the highest record value is reset after
6832 ** *pHighwater is written. ^(Some parameters do not record the highest
6833 ** value. For those parameters
6834 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6835 ** ^(Other parameters record only the highwater mark and not the current
6836 ** value. For these latter parameters nothing is written into *pCurrent.)^
6837 **
6838 ** ^The sqlite3_status() and sqlite3_status64() routines return
6839 ** SQLITE_OK on success and a non-zero [error code] on failure.
6840 **
6841 ** If either the current value or the highwater mark is too large to
6842 ** be represented by a 32-bit integer, then the values returned by
6843 ** sqlite3_status() are undefined.
6844 **
6845 ** See also: [sqlite3_db_status()]
6846 */
6847 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6849  int op,
6850  sqlite3_int64 *pCurrent,
6851  sqlite3_int64 *pHighwater,
6852  int resetFlag
6853 );
6854 
6855 
6856 /*
6857 ** CAPI3REF: Status Parameters
6858 ** KEYWORDS: {status parameters}
6859 **
6860 ** These integer constants designate various run-time status parameters
6861 ** that can be returned by [sqlite3_status()].
6862 **
6863 ** <dl>
6864 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6865 ** <dd>This parameter is the current amount of memory checked out
6866 ** using [sqlite3_malloc()], either directly or indirectly. The
6867 ** figure includes calls made to [sqlite3_malloc()] by the application
6868 ** and internal memory usage by the SQLite library. Scratch memory
6869 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6870 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6871 ** this parameter. The amount returned is the sum of the allocation
6872 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6873 **
6874 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6875 ** <dd>This parameter records the largest memory allocation request
6876 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6877 ** internal equivalents). Only the value returned in the
6878 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6879 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6880 **
6881 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6882 ** <dd>This parameter records the number of separate memory allocations
6883 ** currently checked out.</dd>)^
6884 **
6885 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6886 ** <dd>This parameter returns the number of pages used out of the
6887 ** [pagecache memory allocator] that was configured using
6888 ** [SQLITE_CONFIG_PAGECACHE]. The
6889 ** value returned is in pages, not in bytes.</dd>)^
6890 **
6891 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
6892 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6893 ** <dd>This parameter returns the number of bytes of page cache
6894 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6895 ** buffer and where forced to overflow to [sqlite3_malloc()]. The
6896 ** returned value includes allocations that overflowed because they
6897 ** where too large (they were larger than the "sz" parameter to
6898 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6899 ** no space was left in the page cache.</dd>)^
6900 **
6901 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6902 ** <dd>This parameter records the largest memory allocation request
6903 ** handed to [pagecache memory allocator]. Only the value returned in the
6904 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6905 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6906 **
6907 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6908 ** <dd>This parameter returns the number of allocations used out of the
6909 ** [scratch memory allocator] configured using
6910 ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
6911 ** in bytes. Since a single thread may only have one scratch allocation
6912 ** outstanding at time, this parameter also reports the number of threads
6913 ** using scratch memory at the same time.</dd>)^
6914 **
6915 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6916 ** <dd>This parameter returns the number of bytes of scratch memory
6917 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6918 ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
6919 ** returned include overflows because the requested allocation was too
6920 ** larger (that is, because the requested allocation was larger than the
6921 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6922 ** slots were available.
6923 ** </dd>)^
6924 **
6925 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6926 ** <dd>This parameter records the largest memory allocation request
6927 ** handed to [scratch memory allocator]. Only the value returned in the
6928 ** *pHighwater parameter to [sqlite3_status()] is of interest.
6929 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6930 **
6931 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6932 ** <dd>The *pHighwater parameter records the deepest parser stack.
6933 ** The *pCurrent value is undefined. The *pHighwater value is only
6934 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6935 ** </dl>
6936 **
6937 ** New status parameters may be added from time to time.
6938 */
6939 #define SQLITE_STATUS_MEMORY_USED 0
6940 #define SQLITE_STATUS_PAGECACHE_USED 1
6941 #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
6942 #define SQLITE_STATUS_SCRATCH_USED 3
6943 #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
6944 #define SQLITE_STATUS_MALLOC_SIZE 5
6945 #define SQLITE_STATUS_PARSER_STACK 6
6946 #define SQLITE_STATUS_PAGECACHE_SIZE 7
6947 #define SQLITE_STATUS_SCRATCH_SIZE 8
6948 #define SQLITE_STATUS_MALLOC_COUNT 9
6949 
6950 /*
6951 ** CAPI3REF: Database Connection Status
6952 ** METHOD: sqlite3
6953 **
6954 ** ^This interface is used to retrieve runtime status information
6955 ** about a single [database connection]. ^The first argument is the
6956 ** database connection object to be interrogated. ^The second argument
6957 ** is an integer constant, taken from the set of
6958 ** [SQLITE_DBSTATUS options], that
6959 ** determines the parameter to interrogate. The set of
6960 ** [SQLITE_DBSTATUS options] is likely
6961 ** to grow in future releases of SQLite.
6962 **
6963 ** ^The current value of the requested parameter is written into *pCur
6964 ** and the highest instantaneous value is written into *pHiwtr. ^If
6965 ** the resetFlg is true, then the highest instantaneous value is
6966 ** reset back down to the current value.
6967 **
6968 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6969 ** non-zero [error code] on failure.
6970 **
6971 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6972 */
6973 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6974 
6975 /*
6976 ** CAPI3REF: Status Parameters for database connections
6977 ** KEYWORDS: {SQLITE_DBSTATUS options}
6978 **
6979 ** These constants are the available integer "verbs" that can be passed as
6980 ** the second argument to the [sqlite3_db_status()] interface.
6981 **
6982 ** New verbs may be added in future releases of SQLite. Existing verbs
6983 ** might be discontinued. Applications should check the return code from
6984 ** [sqlite3_db_status()] to make sure that the call worked.
6985 ** The [sqlite3_db_status()] interface will return a non-zero error code
6986 ** if a discontinued or unsupported verb is invoked.
6987 **
6988 ** <dl>
6989 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6990 ** <dd>This parameter returns the number of lookaside memory slots currently
6991 ** checked out.</dd>)^
6992 **
6993 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6994 ** <dd>This parameter returns the number malloc attempts that were
6995 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6996 ** the current value is always zero.)^
6997 **
6998 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6999 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
7000 ** <dd>This parameter returns the number malloc attempts that might have
7001 ** been satisfied using lookaside memory but failed due to the amount of
7002 ** memory requested being larger than the lookaside slot size.
7003 ** Only the high-water value is meaningful;
7004 ** the current value is always zero.)^
7005 **
7006 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
7007 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
7008 ** <dd>This parameter returns the number malloc attempts that might have
7009 ** been satisfied using lookaside memory but failed due to all lookaside
7010 ** memory already being in use.
7011 ** Only the high-water value is meaningful;
7012 ** the current value is always zero.)^
7013 **
7014 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
7015 ** <dd>This parameter returns the approximate number of bytes of heap
7016 ** memory used by all pager caches associated with the database connection.)^
7017 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
7018 **
7019 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
7020 ** <dd>This parameter returns the approximate number of bytes of heap
7021 ** memory used to store the schema for all databases associated
7022 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
7023 ** ^The full amount of memory used by the schemas is reported, even if the
7024 ** schema memory is shared with other database connections due to
7025 ** [shared cache mode] being enabled.
7026 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
7027 **
7028 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
7029 ** <dd>This parameter returns the approximate number of bytes of heap
7030 ** and lookaside memory used by all prepared statements associated with
7031 ** the database connection.)^
7032 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
7033 ** </dd>
7034 **
7035 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
7036 ** <dd>This parameter returns the number of pager cache hits that have
7037 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
7038 ** is always 0.
7039 ** </dd>
7040 **
7041 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
7042 ** <dd>This parameter returns the number of pager cache misses that have
7043 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
7044 ** is always 0.
7045 ** </dd>
7046 **
7047 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
7048 ** <dd>This parameter returns the number of dirty cache entries that have
7049 ** been written to disk. Specifically, the number of pages written to the
7050 ** wal file in wal mode databases, or the number of pages written to the
7051 ** database file in rollback mode databases. Any pages written as part of
7052 ** transaction rollback or database recovery operations are not included.
7053 ** If an IO or other error occurs while writing a page to disk, the effect
7054 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
7055 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
7056 ** </dd>
7057 **
7058 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
7059 ** <dd>This parameter returns zero for the current value if and only if
7060 ** all foreign key constraints (deferred or immediate) have been
7061 ** resolved.)^ ^The highwater mark is always 0.
7062 ** </dd>
7063 ** </dl>
7064 */
7065 #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
7066 #define SQLITE_DBSTATUS_CACHE_USED 1
7067 #define SQLITE_DBSTATUS_SCHEMA_USED 2
7068 #define SQLITE_DBSTATUS_STMT_USED 3
7069 #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
7070 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
7071 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
7072 #define SQLITE_DBSTATUS_CACHE_HIT 7
7073 #define SQLITE_DBSTATUS_CACHE_MISS 8
7074 #define SQLITE_DBSTATUS_CACHE_WRITE 9
7075 #define SQLITE_DBSTATUS_DEFERRED_FKS 10
7076 #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
7077 
7078 
7079 /*
7080 ** CAPI3REF: Prepared Statement Status
7081 ** METHOD: sqlite3_stmt
7082 **
7083 ** ^(Each prepared statement maintains various
7084 ** [SQLITE_STMTSTATUS counters] that measure the number
7085 ** of times it has performed specific operations.)^ These counters can
7086 ** be used to monitor the performance characteristics of the prepared
7087 ** statements. For example, if the number of table steps greatly exceeds
7088 ** the number of table searches or result rows, that would tend to indicate
7089 ** that the prepared statement is using a full table scan rather than
7090 ** an index.
7091 **
7092 ** ^(This interface is used to retrieve and reset counter values from
7093 ** a [prepared statement]. The first argument is the prepared statement
7094 ** object to be interrogated. The second argument
7095 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
7096 ** to be interrogated.)^
7097 ** ^The current value of the requested counter is returned.
7098 ** ^If the resetFlg is true, then the counter is reset to zero after this
7099 ** interface call returns.
7100 **
7101 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
7102 */
7103 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
7104 
7105 /*
7106 ** CAPI3REF: Status Parameters for prepared statements
7107 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
7108 **
7109 ** These preprocessor macros define integer codes that name counter
7110 ** values associated with the [sqlite3_stmt_status()] interface.
7111 ** The meanings of the various counters are as follows:
7112 **
7113 ** <dl>
7114 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
7115 ** <dd>^This is the number of times that SQLite has stepped forward in
7116 ** a table as part of a full table scan. Large numbers for this counter
7117 ** may indicate opportunities for performance improvement through
7118 ** careful use of indices.</dd>
7119 **
7120 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
7121 ** <dd>^This is the number of sort operations that have occurred.
7122 ** A non-zero value in this counter may indicate an opportunity to
7123 ** improvement performance through careful use of indices.</dd>
7124 **
7125 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
7126 ** <dd>^This is the number of rows inserted into transient indices that
7127 ** were created automatically in order to help joins run faster.
7128 ** A non-zero value in this counter may indicate an opportunity to
7129 ** improvement performance by adding permanent indices that do not
7130 ** need to be reinitialized each time the statement is run.</dd>
7131 **
7132 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
7133 ** <dd>^This is the number of virtual machine operations executed
7134 ** by the prepared statement if that number is less than or equal
7135 ** to 2147483647. The number of virtual machine operations can be
7136 ** used as a proxy for the total work done by the prepared statement.
7137 ** If the number of virtual machine operations exceeds 2147483647
7138 ** then the value returned by this statement status code is undefined.
7139 ** </dd>
7140 ** </dl>
7141 */
7142 #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
7143 #define SQLITE_STMTSTATUS_SORT 2
7144 #define SQLITE_STMTSTATUS_AUTOINDEX 3
7145 #define SQLITE_STMTSTATUS_VM_STEP 4
7146 
7147 /*
7148 ** CAPI3REF: Custom Page Cache Object
7149 **
7150 ** The sqlite3_pcache type is opaque. It is implemented by
7151 ** the pluggable module. The SQLite core has no knowledge of
7152 ** its size or internal structure and never deals with the
7153 ** sqlite3_pcache object except by holding and passing pointers
7154 ** to the object.
7155 **
7156 ** See [sqlite3_pcache_methods2] for additional information.
7157 */
7159 
7160 /*
7161 ** CAPI3REF: Custom Page Cache Object
7162 **
7163 ** The sqlite3_pcache_page object represents a single page in the
7164 ** page cache. The page cache will allocate instances of this
7165 ** object. Various methods of the page cache use pointers to instances
7166 ** of this object as parameters or as their return value.
7167 **
7168 ** See [sqlite3_pcache_methods2] for additional information.
7169 */
7172  void *pBuf; /* The content of the page */
7173  void *pExtra; /* Extra information associated with the page */
7174 };
7175 
7176 /*
7177 ** CAPI3REF: Application Defined Page Cache.
7178 ** KEYWORDS: {page cache}
7179 **
7180 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
7181 ** register an alternative page cache implementation by passing in an
7182 ** instance of the sqlite3_pcache_methods2 structure.)^
7183 ** In many applications, most of the heap memory allocated by
7184 ** SQLite is used for the page cache.
7185 ** By implementing a
7186 ** custom page cache using this API, an application can better control
7187 ** the amount of memory consumed by SQLite, the way in which
7188 ** that memory is allocated and released, and the policies used to
7189 ** determine exactly which parts of a database file are cached and for
7190 ** how long.
7191 **
7192 ** The alternative page cache mechanism is an
7193 ** extreme measure that is only needed by the most demanding applications.
7194 ** The built-in page cache is recommended for most uses.
7195 **
7196 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
7197 ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
7198 ** the application may discard the parameter after the call to
7199 ** [sqlite3_config()] returns.)^
7200 **
7201 ** [[the xInit() page cache method]]
7202 ** ^(The xInit() method is called once for each effective
7203 ** call to [sqlite3_initialize()])^
7204 ** (usually only once during the lifetime of the process). ^(The xInit()
7205 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
7206 ** The intent of the xInit() method is to set up global data structures
7207 ** required by the custom page cache implementation.
7208 ** ^(If the xInit() method is NULL, then the
7209 ** built-in default page cache is used instead of the application defined
7210 ** page cache.)^
7211 **
7212 ** [[the xShutdown() page cache method]]
7213 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
7214 ** It can be used to clean up
7215 ** any outstanding resources before process shutdown, if required.
7216 ** ^The xShutdown() method may be NULL.
7217 **
7218 ** ^SQLite automatically serializes calls to the xInit method,
7219 ** so the xInit method need not be threadsafe. ^The
7220 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
7221 ** not need to be threadsafe either. All other methods must be threadsafe
7222 ** in multithreaded applications.
7223 **
7224 ** ^SQLite will never invoke xInit() more than once without an intervening
7225 ** call to xShutdown().
7226 **
7227 ** [[the xCreate() page cache methods]]
7228 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
7229 ** SQLite will typically create one cache instance for each open database file,
7230 ** though this is not guaranteed. ^The
7231 ** first parameter, szPage, is the size in bytes of the pages that must
7232 ** be allocated by the cache. ^szPage will always a power of two. ^The
7233 ** second parameter szExtra is a number of bytes of extra storage
7234 ** associated with each page cache entry. ^The szExtra parameter will
7235 ** a number less than 250. SQLite will use the
7236 ** extra szExtra bytes on each page to store metadata about the underlying
7237 ** database page on disk. The value passed into szExtra depends
7238 ** on the SQLite version, the target platform, and how SQLite was compiled.
7239 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
7240 ** created will be used to cache database pages of a file stored on disk, or
7241 ** false if it is used for an in-memory database. The cache implementation
7242 ** does not have to do anything special based with the value of bPurgeable;
7243 ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
7244 ** never invoke xUnpin() except to deliberately delete a page.
7245 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
7246 ** false will always have the "discard" flag set to true.
7247 ** ^Hence, a cache created with bPurgeable false will
7248 ** never contain any unpinned pages.
7249 **
7250 ** [[the xCachesize() page cache method]]
7251 ** ^(The xCachesize() method may be called at any time by SQLite to set the
7252 ** suggested maximum cache-size (number of pages stored by) the cache
7253 ** instance passed as the first argument. This is the value configured using
7254 ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
7255 ** parameter, the implementation is not required to do anything with this
7256 ** value; it is advisory only.
7257 **
7258 ** [[the xPagecount() page cache methods]]
7259 ** The xPagecount() method must return the number of pages currently
7260 ** stored in the cache, both pinned and unpinned.
7261 **
7262 ** [[the xFetch() page cache methods]]
7263 ** The xFetch() method locates a page in the cache and returns a pointer to
7264 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
7265 ** The pBuf element of the returned sqlite3_pcache_page object will be a
7266 ** pointer to a buffer of szPage bytes used to store the content of a
7267 ** single database page. The pExtra element of sqlite3_pcache_page will be
7268 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
7269 ** for each entry in the page cache.
7270 **
7271 ** The page to be fetched is determined by the key. ^The minimum key value
7272 ** is 1. After it has been retrieved using xFetch, the page is considered
7273 ** to be "pinned".
7274 **
7275 ** If the requested page is already in the page cache, then the page cache
7276 ** implementation must return a pointer to the page buffer with its content
7277 ** intact. If the requested page is not already in the cache, then the
7278 ** cache implementation should use the value of the createFlag
7279 ** parameter to help it determined what action to take:
7280 **
7281 ** <table border=1 width=85% align=center>
7282 ** <tr><th> createFlag <th> Behavior when page is not already in cache
7283 ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
7284 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
7285 ** Otherwise return NULL.
7286 ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
7287 ** NULL if allocating a new page is effectively impossible.
7288 ** </table>
7289 **
7290 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
7291 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
7292 ** failed.)^ In between the to xFetch() calls, SQLite may
7293 ** attempt to unpin one or more cache pages by spilling the content of
7294 ** pinned pages to disk and synching the operating system disk cache.
7295 **
7296 ** [[the xUnpin() page cache method]]
7297 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
7298 ** as its second argument. If the third parameter, discard, is non-zero,
7299 ** then the page must be evicted from the cache.
7300 ** ^If the discard parameter is
7301 ** zero, then the page may be discarded or retained at the discretion of
7302 ** page cache implementation. ^The page cache implementation
7303 ** may choose to evict unpinned pages at any time.
7304 **
7305 ** The cache must not perform any reference counting. A single
7306 ** call to xUnpin() unpins the page regardless of the number of prior calls
7307 ** to xFetch().
7308 **
7309 ** [[the xRekey() page cache methods]]
7310 ** The xRekey() method is used to change the key value associated with the
7311 ** page passed as the second argument. If the cache
7312 ** previously contains an entry associated with newKey, it must be
7313 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7314 ** to be pinned.
7315 **
7316 ** When SQLite calls the xTruncate() method, the cache must discard all
7317 ** existing cache entries with page numbers (keys) greater than or equal
7318 ** to the value of the iLimit parameter passed to xTruncate(). If any
7319 ** of these pages are pinned, they are implicitly unpinned, meaning that
7320 ** they can be safely discarded.
7321 **
7322 ** [[the xDestroy() page cache method]]
7323 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7324 ** All resources associated with the specified cache should be freed. ^After
7325 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7326 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7327 ** functions.
7328 **
7329 ** [[the xShrink() page cache method]]
7330 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7331 ** free up as much of heap memory as possible. The page cache implementation
7332 ** is not obligated to free any memory, but well-behaved implementations should
7333 ** do their best.
7334 */
7338  void *pArg;
7339  int (*xInit)(void*);
7340  void (*xShutdown)(void*);
7341  sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7342  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7343  int (*xPagecount)(sqlite3_pcache*);
7344  sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7345  void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7346  void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
7347  unsigned oldKey, unsigned newKey);
7348  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7349  void (*xDestroy)(sqlite3_pcache*);
7350  void (*xShrink)(sqlite3_pcache*);
7351 };
7352 
7353 /*
7354 ** This is the obsolete pcache_methods object that has now been replaced
7355 ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
7356 ** retained in the header file for backwards compatibility only.
7357 */
7360  void *pArg;
7361  int (*xInit)(void*);
7362  void (*xShutdown)(void*);
7363  sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7364  void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7365  int (*xPagecount)(sqlite3_pcache*);
7366  void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7367  void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7368  void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7369  void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7370  void (*xDestroy)(sqlite3_pcache*);
7371 };
7372 
7373 
7374 /*
7375 ** CAPI3REF: Online Backup Object
7376 **
7377 ** The sqlite3_backup object records state information about an ongoing
7378 ** online backup operation. ^The sqlite3_backup object is created by
7379 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7380 ** [sqlite3_backup_finish()].
7381 **
7382 ** See Also: [Using the SQLite Online Backup API]
7383 */
7385 
7386 /*
7387 ** CAPI3REF: Online Backup API.
7388 **
7389 ** The backup API copies the content of one database into another.
7390 ** It is useful either for creating backups of databases or
7391 ** for copying in-memory databases to or from persistent files.
7392 **
7393 ** See Also: [Using the SQLite Online Backup API]
7394 **
7395 ** ^SQLite holds a write transaction open on the destination database file
7396 ** for the duration of the backup operation.
7397 ** ^The source database is read-locked only while it is being read;
7398 ** it is not locked continuously for the entire backup operation.
7399 ** ^Thus, the backup may be performed on a live source database without
7400 ** preventing other database connections from
7401 ** reading or writing to the source database while the backup is underway.
7402 **
7403 ** ^(To perform a backup operation:
7404 ** <ol>
7405 ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
7406 ** backup,
7407 ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
7408 ** the data between the two databases, and finally
7409 ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
7410 ** associated with the backup operation.
7411 ** </ol>)^
7412 ** There should be exactly one call to sqlite3_backup_finish() for each
7413 ** successful call to sqlite3_backup_init().
7414 **
7415 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7416 **
7417 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
7418 ** [database connection] associated with the destination database
7419 ** and the database name, respectively.
7420 ** ^The database name is "main" for the main database, "temp" for the
7421 ** temporary database, or the name specified after the AS keyword in
7422 ** an [ATTACH] statement for an attached database.
7423 ** ^The S and M arguments passed to
7424 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7425 ** and database name of the source database, respectively.
7426 ** ^The source and destination [database connections] (parameters S and D)
7427 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7428 ** an error.
7429 **
7430 ** ^A call to sqlite3_backup_init() will fail, returning NULL, if
7431 ** there is already a read or read-write transaction open on the
7432 ** destination database.
7433 **
7434 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7435 ** returned and an error code and error message are stored in the
7436 ** destination [database connection] D.
7437 ** ^The error code and message for the failed call to sqlite3_backup_init()
7438 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7439 ** [sqlite3_errmsg16()] functions.
7440 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7441 ** [sqlite3_backup] object.
7442 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7443 ** sqlite3_backup_finish() functions to perform the specified backup
7444 ** operation.
7445 **
7446 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7447 **
7448 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
7449 ** the source and destination databases specified by [sqlite3_backup] object B.
7450 ** ^If N is negative, all remaining source pages are copied.
7451 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7452 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7453 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7454 ** from source to destination, then it returns [SQLITE_DONE].
7455 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7456 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7457 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7458 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7459 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7460 **
7461 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7462 ** <ol>
7463 ** <li> the destination database was opened read-only, or
7464 ** <li> the destination database is using write-ahead-log journaling
7465 ** and the destination and source page sizes differ, or
7466 ** <li> the destination database is an in-memory database and the
7467 ** destination and source page sizes differ.
7468 ** </ol>)^
7469 **
7470 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7471 ** the [sqlite3_busy_handler | busy-handler function]
7472 ** is invoked (if one is specified). ^If the
7473 ** busy-handler returns non-zero before the lock is available, then
7474 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7475 ** sqlite3_backup_step() can be retried later. ^If the source
7476 ** [database connection]
7477 ** is being used to write to the source database when sqlite3_backup_step()
7478 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7479 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7480 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7481 ** [SQLITE_READONLY] is returned, then
7482 ** there is no point in retrying the call to sqlite3_backup_step(). These
7483 ** errors are considered fatal.)^ The application must accept
7484 ** that the backup operation has failed and pass the backup operation handle
7485 ** to the sqlite3_backup_finish() to release associated resources.
7486 **
7487 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7488 ** on the destination file. ^The exclusive lock is not released until either
7489 ** sqlite3_backup_finish() is called or the backup operation is complete
7490 ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
7491 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7492 ** lasts for the duration of the sqlite3_backup_step() call.
7493 ** ^Because the source database is not locked between calls to
7494 ** sqlite3_backup_step(), the source database may be modified mid-way
7495 ** through the backup process. ^If the source database is modified by an
7496 ** external process or via a database connection other than the one being
7497 ** used by the backup operation, then the backup will be automatically
7498 ** restarted by the next call to sqlite3_backup_step(). ^If the source
7499 ** database is modified by the using the same database connection as is used
7500 ** by the backup operation, then the backup database is automatically
7501 ** updated at the same time.
7502 **
7503 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7504 **
7505 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
7506 ** application wishes to abandon the backup operation, the application
7507 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7508 ** ^The sqlite3_backup_finish() interfaces releases all
7509 ** resources associated with the [sqlite3_backup] object.
7510 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7511 ** active write-transaction on the destination database is rolled back.
7512 ** The [sqlite3_backup] object is invalid
7513 ** and may not be used following a call to sqlite3_backup_finish().
7514 **
7515 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7516 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7517 ** sqlite3_backup_step() completed.
7518 ** ^If an out-of-memory condition or IO error occurred during any prior
7519 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7520 ** sqlite3_backup_finish() returns the corresponding [error code].
7521 **
7522 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7523 ** is not a permanent error and does not affect the return value of
7524 ** sqlite3_backup_finish().
7525 **
7526 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7527 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7528 **
7529 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7530 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7531 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7532 ** in the source database at the conclusion of the most recent
7533 ** sqlite3_backup_step().
7534 ** ^(The values returned by these functions are only updated by
7535 ** sqlite3_backup_step(). If the source database is modified in a way that
7536 ** changes the size of the source database or the number of pages remaining,
7537 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7538 ** and sqlite3_backup_remaining() until after the next
7539 ** sqlite3_backup_step().)^
7540 **
7541 ** <b>Concurrent Usage of Database Handles</b>
7542 **
7543 ** ^The source [database connection] may be used by the application for other
7544 ** purposes while a backup operation is underway or being initialized.
7545 ** ^If SQLite is compiled and configured to support threadsafe database
7546 ** connections, then the source database connection may be used concurrently
7547 ** from within other threads.
7548 **
7549 ** However, the application must guarantee that the destination
7550 ** [database connection] is not passed to any other API (by any thread) after
7551 ** sqlite3_backup_init() is called and before the corresponding call to
7552 ** sqlite3_backup_finish(). SQLite does not currently check to see
7553 ** if the application incorrectly accesses the destination [database connection]
7554 ** and so no error code is reported, but the operations may malfunction
7555 ** nevertheless. Use of the destination database connection while a
7556 ** backup is in progress might also also cause a mutex deadlock.
7557 **
7558 ** If running in [shared cache mode], the application must
7559 ** guarantee that the shared cache used by the destination database
7560 ** is not accessed while the backup is running. In practice this means
7561 ** that the application must guarantee that the disk file being
7562 ** backed up to is not accessed by any connection within the process,
7563 ** not just the specific connection that was passed to sqlite3_backup_init().
7564 **
7565 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
7566 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7567 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7568 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7569 ** same time as another thread is invoking sqlite3_backup_step() it is
7570 ** possible that they return invalid values.
7571 */
7573  sqlite3 *pDest, /* Destination database handle */
7574  const char *zDestName, /* Destination database name */
7575  sqlite3 *pSource, /* Source database handle */
7576  const char *zSourceName /* Source database name */
7577 );
7582 
7583 /*
7584 ** CAPI3REF: Unlock Notification
7585 ** METHOD: sqlite3
7586 **
7587 ** ^When running in shared-cache mode, a database operation may fail with
7588 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7589 ** individual tables within the shared-cache cannot be obtained. See
7590 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
7591 ** ^This API may be used to register a callback that SQLite will invoke
7592 ** when the connection currently holding the required lock relinquishes it.
7593 ** ^This API is only available if the library was compiled with the
7594 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7595 **
7596 ** See Also: [Using the SQLite Unlock Notification Feature].
7597 **
7598 ** ^Shared-cache locks are released when a database connection concludes
7599 ** its current transaction, either by committing it or rolling it back.
7600 **
7601 ** ^When a connection (known as the blocked connection) fails to obtain a
7602 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7603 ** identity of the database connection (the blocking connection) that
7604 ** has locked the required resource is stored internally. ^After an
7605 ** application receives an SQLITE_LOCKED error, it may call the
7606 ** sqlite3_unlock_notify() method with the blocked connection handle as
7607 ** the first argument to register for a callback that will be invoked
7608 ** when the blocking connections current transaction is concluded. ^The
7609 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7610 ** call that concludes the blocking connections transaction.
7611 **
7612 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7613 ** there is a chance that the blocking connection will have already
7614 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7615 ** If this happens, then the specified callback is invoked immediately,
7616 ** from within the call to sqlite3_unlock_notify().)^
7617 **
7618 ** ^If the blocked connection is attempting to obtain a write-lock on a
7619 ** shared-cache table, and more than one other connection currently holds
7620 ** a read-lock on the same table, then SQLite arbitrarily selects one of
7621 ** the other connections to use as the blocking connection.
7622 **
7623 ** ^(There may be at most one unlock-notify callback registered by a
7624 ** blocked connection. If sqlite3_unlock_notify() is called when the
7625 ** blocked connection already has a registered unlock-notify callback,
7626 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7627 ** called with a NULL pointer as its second argument, then any existing
7628 ** unlock-notify callback is canceled. ^The blocked connections
7629 ** unlock-notify callback may also be canceled by closing the blocked
7630 ** connection using [sqlite3_close()].
7631 **
7632 ** The unlock-notify callback is not reentrant. If an application invokes
7633 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7634 ** crash or deadlock may be the result.
7635 **
7636 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7637 ** returns SQLITE_OK.
7638 **
7639 ** <b>Callback Invocation Details</b>
7640 **
7641 ** When an unlock-notify callback is registered, the application provides a
7642 ** single void* pointer that is passed to the callback when it is invoked.
7643 ** However, the signature of the callback function allows SQLite to pass
7644 ** it an array of void* context pointers. The first argument passed to
7645 ** an unlock-notify callback is a pointer to an array of void* pointers,
7646 ** and the second is the number of entries in the array.
7647 **
7648 ** When a blocking connections transaction is concluded, there may be
7649 ** more than one blocked connection that has registered for an unlock-notify
7650 ** callback. ^If two or more such blocked connections have specified the
7651 ** same callback function, then instead of invoking the callback function
7652 ** multiple times, it is invoked once with the set of void* context pointers
7653 ** specified by the blocked connections bundled together into an array.
7654 ** This gives the application an opportunity to prioritize any actions
7655 ** related to the set of unblocked database connections.
7656 **
7657 ** <b>Deadlock Detection</b>
7658 **
7659 ** Assuming that after registering for an unlock-notify callback a
7660 ** database waits for the callback to be issued before taking any further
7661 ** action (a reasonable assumption), then using this API may cause the
7662 ** application to deadlock. For example, if connection X is waiting for
7663 ** connection Y's transaction to be concluded, and similarly connection
7664 ** Y is waiting on connection X's transaction, then neither connection
7665 ** will proceed and the system may remain deadlocked indefinitely.
7666 **
7667 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7668 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7669 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7670 ** unlock-notify callback is registered. The system is said to be in
7671 ** a deadlocked state if connection A has registered for an unlock-notify
7672 ** callback on the conclusion of connection B's transaction, and connection
7673 ** B has itself registered for an unlock-notify callback when connection
7674 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7675 ** the system is also considered to be deadlocked if connection B has
7676 ** registered for an unlock-notify callback on the conclusion of connection
7677 ** C's transaction, where connection C is waiting on connection A. ^Any
7678 ** number of levels of indirection are allowed.
7679 **
7680 ** <b>The "DROP TABLE" Exception</b>
7681 **
7682 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
7683 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7684 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7685 ** SQLite checks if there are any currently executing SELECT statements
7686 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7687 ** returned. In this case there is no "blocking connection", so invoking
7688 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7689 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7690 ** or "DROP INDEX" query, an infinite loop might be the result.
7691 **
7692 ** One way around this problem is to check the extended error code returned
7693 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7694 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7695 ** the special "DROP TABLE/INDEX" case, the extended error code is just
7696 ** SQLITE_LOCKED.)^
7697 */
7699  sqlite3 *pBlocked, /* Waiting connection */
7700  void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
7701  void *pNotifyArg /* Argument to pass to xNotify */
7702 );
7703 
7704 
7705 /*
7706 ** CAPI3REF: String Comparison
7707 **
7708 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7709 ** and extensions to compare the contents of two buffers containing UTF-8
7710 ** strings in a case-independent fashion, using the same definition of "case
7711 ** independence" that SQLite uses internally when comparing identifiers.
7712 */
7713 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7714 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7715 
7716 /*
7717 ** CAPI3REF: String Globbing
7718 *
7719 ** ^The [sqlite3_strglob(P,X)] interface returns zero if and only if
7720 ** string X matches the [GLOB] pattern P.
7721 ** ^The definition of [GLOB] pattern matching used in
7722 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7723 ** SQL dialect understood by SQLite. ^The [sqlite3_strglob(P,X)] function
7724 ** is case sensitive.
7725 **
7726 ** Note that this routine returns zero on a match and non-zero if the strings
7727 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7728 **
7729 ** See also: [sqlite3_strlike()].
7730 */
7731 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7732 
7733 /*
7734 ** CAPI3REF: String LIKE Matching
7735 *
7736 ** ^The [sqlite3_strlike(P,X,E)] interface returns zero if and only if
7737 ** string X matches the [LIKE] pattern P with escape character E.
7738 ** ^The definition of [LIKE] pattern matching used in
7739 ** [sqlite3_strlike(P,X,E)] is the same as for the "X LIKE P ESCAPE E"
7740 ** operator in the SQL dialect understood by SQLite. ^For "X LIKE P" without
7741 ** the ESCAPE clause, set the E parameter of [sqlite3_strlike(P,X,E)] to 0.
7742 ** ^As with the LIKE operator, the [sqlite3_strlike(P,X,E)] function is case
7743 ** insensitive - equivalent upper and lower case ASCII characters match
7744 ** one another.
7745 **
7746 ** ^The [sqlite3_strlike(P,X,E)] function matches Unicode characters, though
7747 ** only ASCII characters are case folded.
7748 **
7749 ** Note that this routine returns zero on a match and non-zero if the strings
7750 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7751 **
7752 ** See also: [sqlite3_strglob()].
7753 */
7754 SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc);
7755 
7756 /*
7757 ** CAPI3REF: Error Logging Interface
7758 **
7759 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7760 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7761 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7762 ** used with [sqlite3_snprintf()] to generate the final output string.
7763 **
7764 ** The sqlite3_log() interface is intended for use by extensions such as
7765 ** virtual tables, collating functions, and SQL functions. While there is
7766 ** nothing to prevent an application from calling sqlite3_log(), doing so
7767 ** is considered bad form.
7768 **
7769 ** The zFormat string must not be NULL.
7770 **
7771 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7772 ** will not use dynamically allocated memory. The log message is stored in
7773 ** a fixed-length buffer on the stack. If the log message is longer than
7774 ** a few hundred characters, it will be truncated to the length of the
7775 ** buffer.
7776 */
7777 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7778 
7779 /*
7780 ** CAPI3REF: Write-Ahead Log Commit Hook
7781 ** METHOD: sqlite3
7782 **
7783 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7784 ** is invoked each time data is committed to a database in wal mode.
7785 **
7786 ** ^(The callback is invoked by SQLite after the commit has taken place and
7787 ** the associated write-lock on the database released)^, so the implementation
7788 ** may read, write or [checkpoint] the database as required.
7789 **
7790 ** ^The first parameter passed to the callback function when it is invoked
7791 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7792 ** registering the callback. ^The second is a copy of the database handle.
7793 ** ^The third parameter is the name of the database that was written to -
7794 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7795 ** is the number of pages currently in the write-ahead log file,
7796 ** including those that were just committed.
7797 **
7798 ** The callback function should normally return [SQLITE_OK]. ^If an error
7799 ** code is returned, that error will propagate back up through the
7800 ** SQLite code base to cause the statement that provoked the callback
7801 ** to report an error, though the commit will have still occurred. If the
7802 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7803 ** that does not correspond to any valid SQLite error code, the results
7804 ** are undefined.
7805 **
7806 ** A single database handle may have at most a single write-ahead log callback
7807 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7808 ** previously registered write-ahead log callback. ^Note that the
7809 ** [sqlite3_wal_autocheckpoint()] interface and the
7810 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7811 ** overwrite any prior [sqlite3_wal_hook()] settings.
7812 */
7814  sqlite3*,
7815  int(*)(void *,sqlite3*,const char*,int),
7816  void*
7817 );
7818 
7819 /*
7820 ** CAPI3REF: Configure an auto-checkpoint
7821 ** METHOD: sqlite3
7822 **
7823 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7824 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7825 ** to automatically [checkpoint]
7826 ** after committing a transaction if there are N or
7827 ** more frames in the [write-ahead log] file. ^Passing zero or
7828 ** a negative value as the nFrame parameter disables automatic
7829 ** checkpoints entirely.
7830 **
7831 ** ^The callback registered by this function replaces any existing callback
7832 ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
7833 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7834 ** configured by this function.
7835 **
7836 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7837 ** from SQL.
7838 **
7839 ** ^Checkpoints initiated by this mechanism are
7840 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7841 **
7842 ** ^Every new [database connection] defaults to having the auto-checkpoint
7843 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7844 ** pages. The use of this interface
7845 ** is only necessary if the default setting is found to be suboptimal
7846 ** for a particular application.
7847 */
7849 
7850 /*
7851 ** CAPI3REF: Checkpoint a database
7852 ** METHOD: sqlite3
7853 **
7854 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
7855 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
7856 **
7857 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the
7858 ** [write-ahead log] for database X on [database connection] D to be
7859 ** transferred into the database file and for the write-ahead log to
7860 ** be reset. See the [checkpointing] documentation for addition
7861 ** information.
7862 **
7863 ** This interface used to be the only way to cause a checkpoint to
7864 ** occur. But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
7865 ** interface was added. This interface is retained for backwards
7866 ** compatibility and as a convenience for applications that need to manually
7867 ** start a callback but which do not need the full power (and corresponding
7868 ** complication) of [sqlite3_wal_checkpoint_v2()].
7869 */
7870 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7871 
7872 /*
7873 ** CAPI3REF: Checkpoint a database
7874 ** METHOD: sqlite3
7875 **
7876 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
7877 ** operation on database X of [database connection] D in mode M. Status
7878 ** information is written back into integers pointed to by L and C.)^
7879 ** ^(The M parameter must be a valid [checkpoint mode]:)^
7880 **
7881 ** <dl>
7882 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7883 ** ^Checkpoint as many frames as possible without waiting for any database
7884 ** readers or writers to finish, then sync the database file if all frames
7885 ** in the log were checkpointed. ^The [busy-handler callback]
7886 ** is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.
7887 ** ^On the other hand, passive mode might leave the checkpoint unfinished
7888 ** if there are concurrent readers or writers.
7889 **
7890 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7891 ** ^This mode blocks (it invokes the
7892 ** [sqlite3_busy_handler|busy-handler callback]) until there is no
7893 ** database writer and all readers are reading from the most recent database
7894 ** snapshot. ^It then checkpoints all frames in the log file and syncs the
7895 ** database file. ^This mode blocks new database writers while it is pending,
7896 ** but new database readers are allowed to continue unimpeded.
7897 **
7898 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7899 ** ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
7900 ** that after checkpointing the log file it blocks (calls the
7901 ** [busy-handler callback])
7902 ** until all readers are reading from the database file only. ^This ensures
7903 ** that the next writer will restart the log file from the beginning.
7904 ** ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
7905 ** database writer attempts while it is pending, but does not impede readers.
7906 **
7907 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
7908 ** ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
7909 ** addition that it also truncates the log file to zero bytes just prior
7910 ** to a successful return.
7911 ** </dl>
7912 **
7913 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
7914 ** the log file or to -1 if the checkpoint could not run because
7915 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
7916 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
7917 ** log file (including any that were already checkpointed before the function
7918 ** was called) or to -1 if the checkpoint could not run due to an error or
7919 ** because the database is not in WAL mode. ^Note that upon successful
7920 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
7921 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
7922 **
7923 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
7924 ** any other process is running a checkpoint operation at the same time, the
7925 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a
7926 ** busy-handler configured, it will not be invoked in this case.
7927 **
7928 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the
7929 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
7930 ** obtained immediately, and a busy-handler is configured, it is invoked and
7931 ** the writer lock retried until either the busy-handler returns 0 or the lock
7932 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
7933 ** database readers as described above. ^If the busy-handler returns 0 before
7934 ** the writer lock is obtained or while waiting for database readers, the
7935 ** checkpoint operation proceeds from that point in the same way as
7936 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
7937 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
7938 **
7939 ** ^If parameter zDb is NULL or points to a zero length string, then the
7940 ** specified operation is attempted on all WAL databases [attached] to
7941 ** [database connection] db. In this case the
7942 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If
7943 ** an SQLITE_BUSY error is encountered when processing one or more of the
7944 ** attached WAL databases, the operation is still attempted on any remaining
7945 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other
7946 ** error occurs while processing an attached database, processing is abandoned
7947 ** and the error code is returned to the caller immediately. ^If no error
7948 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
7949 ** databases, SQLITE_OK is returned.
7950 **
7951 ** ^If database zDb is the name of an attached database that is not in WAL
7952 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
7953 ** zDb is not NULL (or a zero length string) and is not the name of any
7954 ** attached database, SQLITE_ERROR is returned to the caller.
7955 **
7956 ** ^Unless it returns SQLITE_MISUSE,
7957 ** the sqlite3_wal_checkpoint_v2() interface
7958 ** sets the error information that is queried by
7959 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
7960 **
7961 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
7962 ** from SQL.
7963 */
7965  sqlite3 *db, /* Database handle */
7966  const char *zDb, /* Name of attached database (or NULL) */
7967  int eMode, /* SQLITE_CHECKPOINT_* value */
7968  int *pnLog, /* OUT: Size of WAL log in frames */
7969  int *pnCkpt /* OUT: Total number of frames checkpointed */
7970 );
7971 
7972 /*
7973 ** CAPI3REF: Checkpoint Mode Values
7974 ** KEYWORDS: {checkpoint mode}
7975 **
7976 ** These constants define all valid values for the "checkpoint mode" passed
7977 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
7978 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
7979 ** meaning of each of these checkpoint modes.
7980 */
7981 #define SQLITE_CHECKPOINT_PASSIVE 0 /* Do as much as possible w/o blocking */
7982 #define SQLITE_CHECKPOINT_FULL 1 /* Wait for writers, then checkpoint */
7983 #define SQLITE_CHECKPOINT_RESTART 2 /* Like FULL but wait for for readers */
7984 #define SQLITE_CHECKPOINT_TRUNCATE 3 /* Like RESTART but also truncate WAL */
7985 
7986 /*
7987 ** CAPI3REF: Virtual Table Interface Configuration
7988 **
7989 ** This function may be called by either the [xConnect] or [xCreate] method
7990 ** of a [virtual table] implementation to configure
7991 ** various facets of the virtual table interface.
7992 **
7993 ** If this interface is invoked outside the context of an xConnect or
7994 ** xCreate virtual table method then the behavior is undefined.
7995 **
7996 ** At present, there is only one option that may be configured using
7997 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
7998 ** may be added in the future.
7999 */
8001 
8002 /*
8003 ** CAPI3REF: Virtual Table Configuration Options
8004 **
8005 ** These macros define the various options to the
8006 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
8007 ** can use to customize and optimize their behavior.
8008 **
8009 ** <dl>
8010 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
8011 ** <dd>Calls of the form
8012 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
8013 ** where X is an integer. If X is zero, then the [virtual table] whose
8014 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
8015 ** support constraints. In this configuration (which is the default) if
8016 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
8017 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
8018 ** specified as part of the users SQL statement, regardless of the actual
8019 ** ON CONFLICT mode specified.
8020 **
8021 ** If X is non-zero, then the virtual table implementation guarantees
8022 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
8023 ** any modifications to internal or persistent data structures have been made.
8024 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
8025 ** is able to roll back a statement or database transaction, and abandon
8026 ** or continue processing the current SQL statement as appropriate.
8027 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
8028 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
8029 ** had been ABORT.
8030 **
8031 ** Virtual table implementations that are required to handle OR REPLACE
8032 ** must do so within the [xUpdate] method. If a call to the
8033 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
8034 ** CONFLICT policy is REPLACE, the virtual table implementation should
8035 ** silently replace the appropriate rows within the xUpdate callback and
8036 ** return SQLITE_OK. Or, if this is not possible, it may return
8037 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
8038 ** constraint handling.
8039 ** </dl>
8040 */
8041 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
8042 
8043 /*
8044 ** CAPI3REF: Determine The Virtual Table Conflict Policy
8045 **
8046 ** This function may only be called from within a call to the [xUpdate] method
8047 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
8048 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
8049 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
8050 ** of the SQL statement that triggered the call to the [xUpdate] method of the
8051 ** [virtual table].
8052 */
8054 
8055 /*
8056 ** CAPI3REF: Conflict resolution modes
8057 ** KEYWORDS: {conflict resolution mode}
8058 **
8059 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
8060 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
8061 ** is for the SQL statement being evaluated.
8062 **
8063 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
8064 ** return value from the [sqlite3_set_authorizer()] callback and that
8065 ** [SQLITE_ABORT] is also a [result code].
8066 */
8067 #define SQLITE_ROLLBACK 1
8068 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
8069 #define SQLITE_FAIL 3
8070 /* #define SQLITE_ABORT 4 // Also an error code */
8071 #define SQLITE_REPLACE 5
8072 
8073 /*
8074 ** CAPI3REF: Prepared Statement Scan Status Opcodes
8075 ** KEYWORDS: {scanstatus options}
8076 **
8077 ** The following constants can be used for the T parameter to the
8078 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface. Each constant designates a
8079 ** different metric for sqlite3_stmt_scanstatus() to return.
8080 **
8081 ** When the value returned to V is a string, space to hold that string is
8082 ** managed by the prepared statement S and will be automatically freed when
8083 ** S is finalized.
8084 **
8085 ** <dl>
8086 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
8087 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
8088 ** set to the total number of times that the X-th loop has run.</dd>
8089 **
8090 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
8091 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
8092 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
8093 **
8094 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
8095 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
8096 ** query planner's estimate for the average number of rows output from each
8097 ** iteration of the X-th loop. If the query planner's estimates was accurate,
8098 ** then this value will approximate the quotient NVISIT/NLOOP and the
8099 ** product of this value for all prior loops with the same SELECTID will
8100 ** be the NLOOP value for the current loop.
8101 **
8102 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
8103 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8104 ** to a zero-terminated UTF-8 string containing the name of the index or table
8105 ** used for the X-th loop.
8106 **
8107 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
8108 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
8109 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
8110 ** description for the X-th loop.
8111 **
8112 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
8113 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
8114 ** "select-id" for the X-th loop. The select-id identifies which query or
8115 ** subquery the loop is part of. The main query has a select-id of zero.
8116 ** The select-id is the same value as is output in the first column
8117 ** of an [EXPLAIN QUERY PLAN] query.
8118 ** </dl>
8119 */
8120 #define SQLITE_SCANSTAT_NLOOP 0
8121 #define SQLITE_SCANSTAT_NVISIT 1
8122 #define SQLITE_SCANSTAT_EST 2
8123 #define SQLITE_SCANSTAT_NAME 3
8124 #define SQLITE_SCANSTAT_EXPLAIN 4
8125 #define SQLITE_SCANSTAT_SELECTID 5
8126 
8127 /*
8128 ** CAPI3REF: Prepared Statement Scan Status
8129 ** METHOD: sqlite3_stmt
8130 **
8131 ** This interface returns information about the predicted and measured
8132 ** performance for pStmt. Advanced applications can use this
8133 ** interface to compare the predicted and the measured performance and
8134 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
8135 **
8136 ** Since this interface is expected to be rarely used, it is only
8137 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
8138 ** compile-time option.
8139 **
8140 ** The "iScanStatusOp" parameter determines which status information to return.
8141 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
8142 ** of this interface is undefined.
8143 ** ^The requested measurement is written into a variable pointed to by
8144 ** the "pOut" parameter.
8145 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
8146 ** Loops are numbered starting from zero. ^If idx is out of range - less than
8147 ** zero or greater than or equal to the total number of loops used to implement
8148 ** the statement - a non-zero value is returned and the variable that pOut
8149 ** points to is unchanged.
8150 **
8151 ** ^Statistics might not be available for all loops in all statements. ^In cases
8152 ** where there exist loops with no available statistics, this function behaves
8153 ** as if the loop did not exist - it returns non-zero and leave the variable
8154 ** that pOut points to unchanged.
8155 **
8156 ** See also: [sqlite3_stmt_scanstatus_reset()]
8157 */
8159  sqlite3_stmt *pStmt, /* Prepared statement for which info desired */
8160  int idx, /* Index of loop to report on */
8161  int iScanStatusOp, /* Information desired. SQLITE_SCANSTAT_* */
8162  void *pOut /* Result written here */
8163 );
8164 
8165 /*
8166 ** CAPI3REF: Zero Scan-Status Counters
8167 ** METHOD: sqlite3_stmt
8168 **
8169 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
8170 **
8171 ** This API is only available if the library is built with pre-processor
8172 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
8173 */
8175 
8176 /*
8177 ** CAPI3REF: Flush caches to disk mid-transaction
8178 **
8179 ** ^If a write-transaction is open on [database connection] D when the
8180 ** [sqlite3_db_cacheflush(D)] interface invoked, any dirty
8181 ** pages in the pager-cache that are not currently in use are written out
8182 ** to disk. A dirty page may be in use if a database cursor created by an
8183 ** active SQL statement is reading from it, or if it is page 1 of a database
8184 ** file (page 1 is always "in use"). ^The [sqlite3_db_cacheflush(D)]
8185 ** interface flushes caches for all schemas - "main", "temp", and
8186 ** any [attached] databases.
8187 **
8188 ** ^If this function needs to obtain extra database locks before dirty pages
8189 ** can be flushed to disk, it does so. ^If those locks cannot be obtained
8190 ** immediately and there is a busy-handler callback configured, it is invoked
8191 ** in the usual manner. ^If the required lock still cannot be obtained, then
8192 ** the database is skipped and an attempt made to flush any dirty pages
8193 ** belonging to the next (if any) database. ^If any databases are skipped
8194 ** because locks cannot be obtained, but no other error occurs, this
8195 ** function returns SQLITE_BUSY.
8196 **
8197 ** ^If any other error occurs while flushing dirty pages to disk (for
8198 ** example an IO error or out-of-memory condition), then processing is
8199 ** abandoned and an SQLite [error code] is returned to the caller immediately.
8200 **
8201 ** ^Otherwise, if no error occurs, [sqlite3_db_cacheflush()] returns SQLITE_OK.
8202 **
8203 ** ^This function does not set the database handle error code or message
8204 ** returned by the [sqlite3_errcode()] and [sqlite3_errmsg()] functions.
8205 */
8207 
8208 /*
8209 ** CAPI3REF: The pre-update hook.
8210 **
8211 ** ^These interfaces are only available if SQLite is compiled using the
8212 ** [SQLITE_ENABLE_PREUPDATE_HOOK] compile-time option.
8213 **
8214 ** ^The [sqlite3_preupdate_hook()] interface registers a callback function
8215 ** that is invoked prior to each [INSERT], [UPDATE], and [DELETE] operation
8216 ** on a [rowid table].
8217 ** ^At most one preupdate hook may be registered at a time on a single
8218 ** [database connection]; each call to [sqlite3_preupdate_hook()] overrides
8219 ** the previous setting.
8220 ** ^The preupdate hook is disabled by invoking [sqlite3_preupdate_hook()]
8221 ** with a NULL pointer as the second parameter.
8222 ** ^The third parameter to [sqlite3_preupdate_hook()] is passed through as
8223 ** the first parameter to callbacks.
8224 **
8225 ** ^The preupdate hook only fires for changes to [rowid tables]; the preupdate
8226 ** hook is not invoked for changes to [virtual tables] or [WITHOUT ROWID]
8227 ** tables.
8228 **
8229 ** ^The second parameter to the preupdate callback is a pointer to
8230 ** the [database connection] that registered the preupdate hook.
8231 ** ^The third parameter to the preupdate callback is one of the constants
8232 ** [SQLITE_INSERT], [SQLITE_DELETE], or [SQLITE_UPDATE] to indentify the
8233 ** kind of update operation that is about to occur.
8234 ** ^(The fourth parameter to the preupdate callback is the name of the
8235 ** database within the database connection that is being modified. This
8236 ** will be "main" for the main database or "temp" for TEMP tables or
8237 ** the name given after the AS keyword in the [ATTACH] statement for attached
8238 ** databases.)^
8239 ** ^The fifth parameter to the preupdate callback is the name of the
8240 ** table that is being modified.
8241 ** ^The sixth parameter to the preupdate callback is the initial [rowid] of the
8242 ** row being changes for SQLITE_UPDATE and SQLITE_DELETE changes and is
8243 ** undefined for SQLITE_INSERT changes.
8244 ** ^The seventh parameter to the preupdate callback is the final [rowid] of
8245 ** the row being changed for SQLITE_UPDATE and SQLITE_INSERT changes and is
8246 ** undefined for SQLITE_DELETE changes.
8247 **
8248 ** The [sqlite3_preupdate_old()], [sqlite3_preupdate_new()],
8249 ** [sqlite3_preupdate_count()], and [sqlite3_preupdate_depth()] interfaces
8250 ** provide additional information about a preupdate event. These routines
8251 ** may only be called from within a preupdate callback. Invoking any of
8252 ** these routines from outside of a preupdate callback or with a
8253 ** [database connection] pointer that is different from the one supplied
8254 ** to the preupdate callback results in undefined and probably undesirable
8255 ** behavior.
8256 **
8257 ** ^The [sqlite3_preupdate_count(D)] interface returns the number of columns
8258 ** in the row that is being inserted, updated, or deleted.
8259 **
8260 ** ^The [sqlite3_preupdate_old(D,N,P)] interface writes into P a pointer to
8261 ** a [protected sqlite3_value] that contains the value of the Nth column of
8262 ** the table row before it is updated. The N parameter must be between 0
8263 ** and one less than the number of columns or the behavior will be
8264 ** undefined. This must only be used within SQLITE_UPDATE and SQLITE_DELETE
8265 ** preupdate callbacks; if it is used by an SQLITE_INSERT callback then the
8266 ** behavior is undefined. The [sqlite3_value] that P points to
8267 ** will be destroyed when the preupdate callback returns.
8268 **
8269 ** ^The [sqlite3_preupdate_new(D,N,P)] interface writes into P a pointer to
8270 ** a [protected sqlite3_value] that contains the value of the Nth column of
8271 ** the table row after it is updated. The N parameter must be between 0
8272 ** and one less than the number of columns or the behavior will be
8273 ** undefined. This must only be used within SQLITE_INSERT and SQLITE_UPDATE
8274 ** preupdate callbacks; if it is used by an SQLITE_DELETE callback then the
8275 ** behavior is undefined. The [sqlite3_value] that P points to
8276 ** will be destroyed when the preupdate callback returns.
8277 **
8278 ** ^The [sqlite3_preupdate_depth(D)] interface returns 0 if the preupdate
8279 ** callback was invoked as a result of a direct insert, update, or delete
8280 ** operation; or 1 for inserts, updates, or deletes invoked by top-level
8281 ** triggers; or 2 for changes resulting from triggers called by top-level
8282 ** triggers; and so forth.
8283 **
8284 ** See also: [sqlite3_update_hook()]
8285 */
8287  sqlite3 *db,
8288  void(*xPreUpdate)(
8289  void *pCtx, /* Copy of third arg to preupdate_hook() */
8290  sqlite3 *db, /* Database handle */
8291  int op, /* SQLITE_UPDATE, DELETE or INSERT */
8292  char const *zDb, /* Database name */
8293  char const *zName, /* Table name */
8294  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
8295  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
8296  ),
8297  void*
8298 );
8303 
8304 /*
8305 ** CAPI3REF: Low-level system error code
8306 **
8307 ** ^Attempt to return the underlying operating system error code or error
8308 ** number that caused the most recent I/O error or failure to open a file.
8309 ** The return value is OS-dependent. For example, on unix systems, after
8310 ** [sqlite3_open_v2()] returns [SQLITE_CANTOPEN], this interface could be
8311 ** called to get back the underlying "errno" that caused the problem, such
8312 ** as ENOSPC, EAUTH, EISDIR, and so forth.
8313 */
8315 
8316 /*
8317 ** CAPI3REF: Database Snapshot
8318 ** KEYWORDS: {snapshot}
8319 ** EXPERIMENTAL
8320 **
8321 ** An instance of the snapshot object records the state of a [WAL mode]
8322 ** database for some specific point in history.
8323 **
8324 ** In [WAL mode], multiple [database connections] that are open on the
8325 ** same database file can each be reading a different historical version
8326 ** of the database file. When a [database connection] begins a read
8327 ** transaction, that connection sees an unchanging copy of the database
8328 ** as it existed for the point in time when the transaction first started.
8329 ** Subsequent changes to the database from other connections are not seen
8330 ** by the reader until a new read transaction is started.
8331 **
8332 ** The sqlite3_snapshot object records state information about an historical
8333 ** version of the database file so that it is possible to later open a new read
8334 ** transaction that sees that historical version of the database rather than
8335 ** the most recent version.
8336 **
8337 ** The constructor for this object is [sqlite3_snapshot_get()]. The
8338 ** [sqlite3_snapshot_open()] method causes a fresh read transaction to refer
8339 ** to an historical snapshot (if possible). The destructor for
8340 ** sqlite3_snapshot objects is [sqlite3_snapshot_free()].
8341 */
8343 
8344 /*
8345 ** CAPI3REF: Record A Database Snapshot
8346 ** EXPERIMENTAL
8347 **
8348 ** ^The [sqlite3_snapshot_get(D,S,P)] interface attempts to make a
8349 ** new [sqlite3_snapshot] object that records the current state of
8350 ** schema S in database connection D. ^On success, the
8351 ** [sqlite3_snapshot_get(D,S,P)] interface writes a pointer to the newly
8352 ** created [sqlite3_snapshot] object into *P and returns SQLITE_OK.
8353 ** ^If schema S of [database connection] D is not a [WAL mode] database
8354 ** that is in a read transaction, then [sqlite3_snapshot_get(D,S,P)]
8355 ** leaves the *P value unchanged and returns an appropriate [error code].
8356 **
8357 ** The [sqlite3_snapshot] object returned from a successful call to
8358 ** [sqlite3_snapshot_get()] must be freed using [sqlite3_snapshot_free()]
8359 ** to avoid a memory leak.
8360 **
8361 ** The [sqlite3_snapshot_get()] interface is only available when the
8362 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8363 */
8365  sqlite3 *db,
8366  const char *zSchema,
8367  sqlite3_snapshot **ppSnapshot
8368 );
8369 
8370 /*
8371 ** CAPI3REF: Start a read transaction on an historical snapshot
8372 ** EXPERIMENTAL
8373 **
8374 ** ^The [sqlite3_snapshot_open(D,S,P)] interface starts a
8375 ** read transaction for schema S of
8376 ** [database connection] D such that the read transaction
8377 ** refers to historical [snapshot] P, rather than the most
8378 ** recent change to the database.
8379 ** ^The [sqlite3_snapshot_open()] interface returns SQLITE_OK on success
8380 ** or an appropriate [error code] if it fails.
8381 **
8382 ** ^In order to succeed, a call to [sqlite3_snapshot_open(D,S,P)] must be
8383 ** the first operation following the [BEGIN] that takes the schema S
8384 ** out of [autocommit mode].
8385 ** ^In other words, schema S must not currently be in
8386 ** a transaction for [sqlite3_snapshot_open(D,S,P)] to work, but the
8387 ** database connection D must be out of [autocommit mode].
8388 ** ^A [snapshot] will fail to open if it has been overwritten by a
8389 ** [checkpoint].
8390 ** ^(A call to [sqlite3_snapshot_open(D,S,P)] will fail if the
8391 ** database connection D does not know that the database file for
8392 ** schema S is in [WAL mode]. A database connection might not know
8393 ** that the database file is in [WAL mode] if there has been no prior
8394 ** I/O on that database connection, or if the database entered [WAL mode]
8395 ** after the most recent I/O on the database connection.)^
8396 ** (Hint: Run "[PRAGMA application_id]" against a newly opened
8397 ** database connection in order to make it ready to use snapshots.)
8398 **
8399 ** The [sqlite3_snapshot_open()] interface is only available when the
8400 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8401 */
8403  sqlite3 *db,
8404  const char *zSchema,
8405  sqlite3_snapshot *pSnapshot
8406 );
8407 
8408 /*
8409 ** CAPI3REF: Destroy a snapshot
8410 ** EXPERIMENTAL
8411 **
8412 ** ^The [sqlite3_snapshot_free(P)] interface destroys [sqlite3_snapshot] P.
8413 ** The application must eventually free every [sqlite3_snapshot] object
8414 ** using this routine to avoid a memory leak.
8415 **
8416 ** The [sqlite3_snapshot_free()] interface is only available when the
8417 ** SQLITE_ENABLE_SNAPSHOT compile-time option is used.
8418 */
8420 
8421 /*
8422 ** CAPI3REF: Compare the ages of two snapshot handles.
8423 ** EXPERIMENTAL
8424 **
8425 ** The sqlite3_snapshot_cmp(P1, P2) interface is used to compare the ages
8426 ** of two valid snapshot handles.
8427 **
8428 ** If the two snapshot handles are not associated with the same database
8429 ** file, the result of the comparison is undefined.
8430 **
8431 ** Additionally, the result of the comparison is only valid if both of the
8432 ** snapshot handles were obtained by calling sqlite3_snapshot_get() since the
8433 ** last time the wal file was deleted. The wal file is deleted when the
8434 ** database is changed back to rollback mode or when the number of database
8435 ** clients drops to zero. If either snapshot handle was obtained before the
8436 ** wal file was last deleted, the value returned by this function
8437 ** is undefined.
8438 **
8439 ** Otherwise, this API returns a negative value if P1 refers to an older
8440 ** snapshot than P2, zero if the two handles refer to the same database
8441 ** snapshot, and a positive value if P1 is a newer snapshot than P2.
8442 */
8446 );
8447 
8448 /*
8449 ** Undo the hack that converts floating point types to integer for
8450 ** builds on processors without floating point support.
8451 */
8452 #ifdef SQLITE_OMIT_FLOATING_POINT
8453 # undef double
8454 #endif
8455 
8456 #if 0
8457 } /* End of the 'extern "C"' block */
8458 #endif
8459 #endif /* _SQLITE3_H_ */
8460 
8461 /******** Begin file sqlite3rtree.h *********/
8462 /*
8463 ** 2010 August 30
8464 **
8465 ** The author disclaims copyright to this source code. In place of
8466 ** a legal notice, here is a blessing:
8467 **
8468 ** May you do good and not evil.
8469 ** May you find forgiveness for yourself and forgive others.
8470 ** May you share freely, never taking more than you give.
8471 **
8472 *************************************************************************
8473 */
8474 
8475 #ifndef _SQLITE3RTREE_H_
8476 #define _SQLITE3RTREE_H_
8477 
8478 
8479 #if 0
8480 extern "C" {
8481 #endif
8482 
8485 
8486 /* The double-precision datatype used by RTree depends on the
8487 ** SQLITE_RTREE_INT_ONLY compile-time option.
8488 */
8489 #ifdef SQLITE_RTREE_INT_ONLY
8490  typedef sqlite3_int64 sqlite3_rtree_dbl;
8491 #else
8492  typedef double sqlite3_rtree_dbl;
8493 #endif
8494 
8495 /*
8496 ** Register a geometry callback named zGeom that can be used as part of an
8497 ** R-Tree geometry query as follows:
8498 **
8499 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
8500 */
8502  sqlite3 *db,
8503  const char *zGeom,
8504  int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
8505  void *pContext
8506 );
8507 
8508 
8509 /*
8510 ** A pointer to a structure of the following type is passed as the first
8511 ** argument to callbacks registered using rtree_geometry_callback().
8512 */
8514  void *pContext; /* Copy of pContext passed to s_r_g_c() */
8515  int nParam; /* Size of array aParam[] */
8516  sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
8517  void *pUser; /* Callback implementation user data */
8518  void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
8519 };
8520 
8521 /*
8522 ** Register a 2nd-generation geometry callback named zScore that can be
8523 ** used as part of an R-Tree geometry query as follows:
8524 **
8525 ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
8526 */
8528  sqlite3 *db,
8529  const char *zQueryFunc,
8530  int (*xQueryFunc)(sqlite3_rtree_query_info*),
8531  void *pContext,
8532  void (*xDestructor)(void*)
8533 );
8534 
8535 
8536 /*
8537 ** A pointer to a structure of the following type is passed as the
8538 ** argument to scored geometry callback registered using
8539 ** sqlite3_rtree_query_callback().
8540 **
8541 ** Note that the first 5 fields of this structure are identical to
8542 ** sqlite3_rtree_geometry. This structure is a subclass of
8543 ** sqlite3_rtree_geometry.
8544 */
8546  void *pContext; /* pContext from when function registered */
8547  int nParam; /* Number of function parameters */
8548  sqlite3_rtree_dbl *aParam; /* value of function parameters */
8549  void *pUser; /* callback can use this, if desired */
8550  void (*xDelUser)(void*); /* function to free pUser */
8551  sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
8552  unsigned int *anQueue; /* Number of pending entries in the queue */
8553  int nCoord; /* Number of coordinates */
8554  int iLevel; /* Level of current node or entry */
8555  int mxLevel; /* The largest iLevel value in the tree */
8556  sqlite3_int64 iRowid; /* Rowid for current entry */
8557  sqlite3_rtree_dbl rParentScore; /* Score of parent node */
8558  int eParentWithin; /* Visibility of parent node */
8559  int eWithin; /* OUT: Visiblity */
8560  sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
8561  /* The following fields are only available in 3.8.11 and later */
8562  sqlite3_value **apSqlParam; /* Original SQL values of parameters */
8563 };
8564 
8565 /*
8566 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
8567 */
8568 #define NOT_WITHIN 0 /* Object completely outside of query region */
8569 #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
8570 #define FULLY_WITHIN 2 /* Object fully contained within query region */
8571 
8572 
8573 #if 0
8574 } /* end of the 'extern "C"' block */
8575 #endif
8576 
8577 #endif /* ifndef _SQLITE3RTREE_H_ */
8578 
8579 /******** End of sqlite3rtree.h *********/
8580 /******** Begin file sqlite3session.h *********/
8581 
8582 #if !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION)
8583 #define __SQLITESESSION_H_ 1
8584 
8585 /*
8586 ** Make sure we can call this stuff from C++.
8587 */
8588 #if 0
8589 extern "C" {
8590 #endif
8591 
8592 
8593 /*
8594 ** CAPI3REF: Session Object Handle
8595 */
8596 typedef struct sqlite3_session sqlite3_session;
8597 
8598 /*
8599 ** CAPI3REF: Changeset Iterator Handle
8600 */
8601 typedef struct sqlite3_changeset_iter sqlite3_changeset_iter;
8602 
8603 /*
8604 ** CAPI3REF: Create A New Session Object
8605 **
8606 ** Create a new session object attached to database handle db. If successful,
8607 ** a pointer to the new object is written to *ppSession and SQLITE_OK is
8608 ** returned. If an error occurs, *ppSession is set to NULL and an SQLite
8609 ** error code (e.g. SQLITE_NOMEM) is returned.
8610 **
8611 ** It is possible to create multiple session objects attached to a single
8612 ** database handle.
8613 **
8614 ** Session objects created using this function should be deleted using the
8615 ** [sqlite3session_delete()] function before the database handle that they
8616 ** are attached to is itself closed. If the database handle is closed before
8617 ** the session object is deleted, then the results of calling any session
8618 ** module function, including [sqlite3session_delete()] on the session object
8619 ** are undefined.
8620 **
8621 ** Because the session module uses the [sqlite3_preupdate_hook()] API, it
8622 ** is not possible for an application to register a pre-update hook on a
8623 ** database handle that has one or more session objects attached. Nor is
8624 ** it possible to create a session object attached to a database handle for
8625 ** which a pre-update hook is already defined. The results of attempting
8626 ** either of these things are undefined.
8627 **
8628 ** The session object will be used to create changesets for tables in
8629 ** database zDb, where zDb is either "main", or "temp", or the name of an
8630 ** attached database. It is not an error if database zDb is not attached
8631 ** to the database when the session object is created.
8632 */
8633 int sqlite3session_create(
8634  sqlite3 *db, /* Database handle */
8635  const char *zDb, /* Name of db (e.g. "main") */
8636  sqlite3_session **ppSession /* OUT: New session object */
8637 );
8638 
8639 /*
8640 ** CAPI3REF: Delete A Session Object
8641 **
8642 ** Delete a session object previously allocated using
8643 ** [sqlite3session_create()]. Once a session object has been deleted, the
8644 ** results of attempting to use pSession with any other session module
8645 ** function are undefined.
8646 **
8647 ** Session objects must be deleted before the database handle to which they
8648 ** are attached is closed. Refer to the documentation for
8649 ** [sqlite3session_create()] for details.
8650 */
8651 void sqlite3session_delete(sqlite3_session *pSession);
8652 
8653 
8654 /*
8655 ** CAPI3REF: Enable Or Disable A Session Object
8656 **
8657 ** Enable or disable the recording of changes by a session object. When
8658 ** enabled, a session object records changes made to the database. When
8659 ** disabled - it does not. A newly created session object is enabled.
8660 ** Refer to the documentation for [sqlite3session_changeset()] for further
8661 ** details regarding how enabling and disabling a session object affects
8662 ** the eventual changesets.
8663 **
8664 ** Passing zero to this function disables the session. Passing a value
8665 ** greater than zero enables it. Passing a value less than zero is a
8666 ** no-op, and may be used to query the current state of the session.
8667 **
8668 ** The return value indicates the final state of the session object: 0 if
8669 ** the session is disabled, or 1 if it is enabled.
8670 */
8671 int sqlite3session_enable(sqlite3_session *pSession, int bEnable);
8672 
8673 /*
8674 ** CAPI3REF: Set Or Clear the Indirect Change Flag
8675 **
8676 ** Each change recorded by a session object is marked as either direct or
8677 ** indirect. A change is marked as indirect if either:
8678 **
8679 ** <ul>
8680 ** <li> The session object "indirect" flag is set when the change is
8681 ** made, or
8682 ** <li> The change is made by an SQL trigger or foreign key action
8683 ** instead of directly as a result of a users SQL statement.
8684 ** </ul>
8685 **
8686 ** If a single row is affected by more than one operation within a session,
8687 ** then the change is considered indirect if all operations meet the criteria
8688 ** for an indirect change above, or direct otherwise.
8689 **
8690 ** This function is used to set, clear or query the session object indirect
8691 ** flag. If the second argument passed to this function is zero, then the
8692 ** indirect flag is cleared. If it is greater than zero, the indirect flag
8693 ** is set. Passing a value less than zero does not modify the current value
8694 ** of the indirect flag, and may be used to query the current state of the
8695 ** indirect flag for the specified session object.
8696 **
8697 ** The return value indicates the final state of the indirect flag: 0 if
8698 ** it is clear, or 1 if it is set.
8699 */
8700 int sqlite3session_indirect(sqlite3_session *pSession, int bIndirect);
8701 
8702 /*
8703 ** CAPI3REF: Attach A Table To A Session Object
8704 **
8705 ** If argument zTab is not NULL, then it is the name of a table to attach
8706 ** to the session object passed as the first argument. All subsequent changes
8707 ** made to the table while the session object is enabled will be recorded. See
8708 ** documentation for [sqlite3session_changeset()] for further details.
8709 **
8710 ** Or, if argument zTab is NULL, then changes are recorded for all tables
8711 ** in the database. If additional tables are added to the database (by
8712 ** executing "CREATE TABLE" statements) after this call is made, changes for
8713 ** the new tables are also recorded.
8714 **
8715 ** Changes can only be recorded for tables that have a PRIMARY KEY explicitly
8716 ** defined as part of their CREATE TABLE statement. It does not matter if the
8717 ** PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias) or not. The PRIMARY
8718 ** KEY may consist of a single column, or may be a composite key.
8719 **
8720 ** It is not an error if the named table does not exist in the database. Nor
8721 ** is it an error if the named table does not have a PRIMARY KEY. However,
8722 ** no changes will be recorded in either of these scenarios.
8723 **
8724 ** Changes are not recorded for individual rows that have NULL values stored
8725 ** in one or more of their PRIMARY KEY columns.
8726 **
8727 ** SQLITE_OK is returned if the call completes without error. Or, if an error
8728 ** occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
8729 */
8730 int sqlite3session_attach(
8731  sqlite3_session *pSession, /* Session object */
8732  const char *zTab /* Table name */
8733 );
8734 
8735 /*
8736 ** CAPI3REF: Set a table filter on a Session Object.
8737 **
8738 ** The second argument (xFilter) is the "filter callback". For changes to rows
8739 ** in tables that are not attached to the Session oject, the filter is called
8740 ** to determine whether changes to the table's rows should be tracked or not.
8741 ** If xFilter returns 0, changes is not tracked. Note that once a table is
8742 ** attached, xFilter will not be called again.
8743 */
8744 void sqlite3session_table_filter(
8745  sqlite3_session *pSession, /* Session object */
8746  int(*xFilter)(
8747  void *pCtx, /* Copy of third arg to _filter_table() */
8748  const char *zTab /* Table name */
8749  ),
8750  void *pCtx /* First argument passed to xFilter */
8751 );
8752 
8753 /*
8754 ** CAPI3REF: Generate A Changeset From A Session Object
8755 **
8756 ** Obtain a changeset containing changes to the tables attached to the
8757 ** session object passed as the first argument. If successful,
8758 ** set *ppChangeset to point to a buffer containing the changeset
8759 ** and *pnChangeset to the size of the changeset in bytes before returning
8760 ** SQLITE_OK. If an error occurs, set both *ppChangeset and *pnChangeset to
8761 ** zero and return an SQLite error code.
8762 **
8763 ** A changeset consists of zero or more INSERT, UPDATE and/or DELETE changes,
8764 ** each representing a change to a single row of an attached table. An INSERT
8765 ** change contains the values of each field of a new database row. A DELETE
8766 ** contains the original values of each field of a deleted database row. An
8767 ** UPDATE change contains the original values of each field of an updated
8768 ** database row along with the updated values for each updated non-primary-key
8769 ** column. It is not possible for an UPDATE change to represent a change that
8770 ** modifies the values of primary key columns. If such a change is made, it
8771 ** is represented in a changeset as a DELETE followed by an INSERT.
8772 **
8773 ** Changes are not recorded for rows that have NULL values stored in one or
8774 ** more of their PRIMARY KEY columns. If such a row is inserted or deleted,
8775 ** no corresponding change is present in the changesets returned by this
8776 ** function. If an existing row with one or more NULL values stored in
8777 ** PRIMARY KEY columns is updated so that all PRIMARY KEY columns are non-NULL,
8778 ** only an INSERT is appears in the changeset. Similarly, if an existing row
8779 ** with non-NULL PRIMARY KEY values is updated so that one or more of its
8780 ** PRIMARY KEY columns are set to NULL, the resulting changeset contains a
8781 ** DELETE change only.
8782 **
8783 ** The contents of a changeset may be traversed using an iterator created
8784 ** using the [sqlite3changeset_start()] API. A changeset may be applied to
8785 ** a database with a compatible schema using the [sqlite3changeset_apply()]
8786 ** API.
8787 **
8788 ** Within a changeset generated by this function, all changes related to a
8789 ** single table are grouped together. In other words, when iterating through
8790 ** a changeset or when applying a changeset to a database, all changes related
8791 ** to a single table are processed before moving on to the next table. Tables
8792 ** are sorted in the same order in which they were attached (or auto-attached)
8793 ** to the sqlite3_session object. The order in which the changes related to
8794 ** a single table are stored is undefined.
8795 **
8796 ** Following a successful call to this function, it is the responsibility of
8797 ** the caller to eventually free the buffer that *ppChangeset points to using
8798 ** [sqlite3_free()].
8799 **
8800 ** <h3>Changeset Generation</h3>
8801 **
8802 ** Once a table has been attached to a session object, the session object
8803 ** records the primary key values of all new rows inserted into the table.
8804 ** It also records the original primary key and other column values of any
8805 ** deleted or updated rows. For each unique primary key value, data is only
8806 ** recorded once - the first time a row with said primary key is inserted,
8807 ** updated or deleted in the lifetime of the session.
8808 **
8809 ** There is one exception to the previous paragraph: when a row is inserted,
8810 ** updated or deleted, if one or more of its primary key columns contain a
8811 ** NULL value, no record of the change is made.
8812 **
8813 ** The session object therefore accumulates two types of records - those
8814 ** that consist of primary key values only (created when the user inserts
8815 ** a new record) and those that consist of the primary key values and the
8816 ** original values of other table columns (created when the users deletes
8817 ** or updates a record).
8818 **
8819 ** When this function is called, the requested changeset is created using
8820 ** both the accumulated records and the current contents of the database
8821 ** file. Specifically:
8822 **
8823 ** <ul>
8824 ** <li> For each record generated by an insert, the database is queried
8825 ** for a row with a matching primary key. If one is found, an INSERT
8826 ** change is added to the changeset. If no such row is found, no change
8827 ** is added to the changeset.
8828 **
8829 ** <li> For each record generated by an update or delete, the database is
8830 ** queried for a row with a matching primary key. If such a row is
8831 ** found and one or more of the non-primary key fields have been
8832 ** modified from their original values, an UPDATE change is added to
8833 ** the changeset. Or, if no such row is found in the table, a DELETE
8834 ** change is added to the changeset. If there is a row with a matching
8835 ** primary key in the database, but all fields contain their original
8836 ** values, no change is added to the changeset.
8837 ** </ul>
8838 **
8839 ** This means, amongst other things, that if a row is inserted and then later
8840 ** deleted while a session object is active, neither the insert nor the delete
8841 ** will be present in the changeset. Or if a row is deleted and then later a
8842 ** row with the same primary key values inserted while a session object is
8843 ** active, the resulting changeset will contain an UPDATE change instead of
8844 ** a DELETE and an INSERT.
8845 **
8846 ** When a session object is disabled (see the [sqlite3session_enable()] API),
8847 ** it does not accumulate records when rows are inserted, updated or deleted.
8848 ** This may appear to have some counter-intuitive effects if a single row
8849 ** is written to more than once during a session. For example, if a row
8850 ** is inserted while a session object is enabled, then later deleted while
8851 ** the same session object is disabled, no INSERT record will appear in the
8852 ** changeset, even though the delete took place while the session was disabled.
8853 ** Or, if one field of a row is updated while a session is disabled, and
8854 ** another field of the same row is updated while the session is enabled, the
8855 ** resulting changeset will contain an UPDATE change that updates both fields.
8856 */
8857 int sqlite3session_changeset(
8858  sqlite3_session *pSession, /* Session object */
8859  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
8860  void **ppChangeset /* OUT: Buffer containing changeset */
8861 );
8862 
8863 /*
8864 ** CAPI3REF: Load The Difference Between Tables Into A Session
8865 **
8866 ** If it is not already attached to the session object passed as the first
8867 ** argument, this function attaches table zTbl in the same manner as the
8868 ** [sqlite3session_attach()] function. If zTbl does not exist, or if it
8869 ** does not have a primary key, this function is a no-op (but does not return
8870 ** an error).
8871 **
8872 ** Argument zFromDb must be the name of a database ("main", "temp" etc.)
8873 ** attached to the same database handle as the session object that contains
8874 ** a table compatible with the table attached to the session by this function.
8875 ** A table is considered compatible if it:
8876 **
8877 ** <ul>
8878 ** <li> Has the same name,
8879 ** <li> Has the same set of columns declared in the same order, and
8880 ** <li> Has the same PRIMARY KEY definition.
8881 ** </ul>
8882 **
8883 ** If the tables are not compatible, SQLITE_SCHEMA is returned. If the tables
8884 ** are compatible but do not have any PRIMARY KEY columns, it is not an error
8885 ** but no changes are added to the session object. As with other session
8886 ** APIs, tables without PRIMARY KEYs are simply ignored.
8887 **
8888 ** This function adds a set of changes to the session object that could be
8889 ** used to update the table in database zFrom (call this the "from-table")
8890 ** so that its content is the same as the table attached to the session
8891 ** object (call this the "to-table"). Specifically:
8892 **
8893 ** <ul>
8894 ** <li> For each row (primary key) that exists in the to-table but not in
8895 ** the from-table, an INSERT record is added to the session object.
8896 **
8897 ** <li> For each row (primary key) that exists in the to-table but not in
8898 ** the from-table, a DELETE record is added to the session object.
8899 **
8900 ** <li> For each row (primary key) that exists in both tables, but features
8901 ** different in each, an UPDATE record is added to the session.
8902 ** </ul>
8903 **
8904 ** To clarify, if this function is called and then a changeset constructed
8905 ** using [sqlite3session_changeset()], then after applying that changeset to
8906 ** database zFrom the contents of the two compatible tables would be
8907 ** identical.
8908 **
8909 ** It an error if database zFrom does not exist or does not contain the
8910 ** required compatible table.
8911 **
8912 ** If the operation successful, SQLITE_OK is returned. Otherwise, an SQLite
8913 ** error code. In this case, if argument pzErrMsg is not NULL, *pzErrMsg
8914 ** may be set to point to a buffer containing an English language error
8915 ** message. It is the responsibility of the caller to free this buffer using
8916 ** sqlite3_free().
8917 */
8918 int sqlite3session_diff(
8919  sqlite3_session *pSession,
8920  const char *zFromDb,
8921  const char *zTbl,
8922  char **pzErrMsg
8923 );
8924 
8925 
8926 /*
8927 ** CAPI3REF: Generate A Patchset From A Session Object
8928 **
8929 ** The differences between a patchset and a changeset are that:
8930 **
8931 ** <ul>
8932 ** <li> DELETE records consist of the primary key fields only. The
8933 ** original values of other fields are omitted.
8934 ** <li> The original values of any modified fields are omitted from
8935 ** UPDATE records.
8936 ** </ul>
8937 **
8938 ** A patchset blob may be used with up to date versions of all
8939 ** sqlite3changeset_xxx API functions except for sqlite3changeset_invert(),
8940 ** which returns SQLITE_CORRUPT if it is passed a patchset. Similarly,
8941 ** attempting to use a patchset blob with old versions of the
8942 ** sqlite3changeset_xxx APIs also provokes an SQLITE_CORRUPT error.
8943 **
8944 ** Because the non-primary key "old.*" fields are omitted, no
8945 ** SQLITE_CHANGESET_DATA conflicts can be detected or reported if a patchset
8946 ** is passed to the sqlite3changeset_apply() API. Other conflict types work
8947 ** in the same way as for changesets.
8948 **
8949 ** Changes within a patchset are ordered in the same way as for changesets
8950 ** generated by the sqlite3session_changeset() function (i.e. all changes for
8951 ** a single table are grouped together, tables appear in the order in which
8952 ** they were attached to the session object).
8953 */
8954 int sqlite3session_patchset(
8955  sqlite3_session *pSession, /* Session object */
8956  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
8957  void **ppPatchset /* OUT: Buffer containing changeset */
8958 );
8959 
8960 /*
8961 ** CAPI3REF: Test if a changeset has recorded any changes.
8962 **
8963 ** Return non-zero if no changes to attached tables have been recorded by
8964 ** the session object passed as the first argument. Otherwise, if one or
8965 ** more changes have been recorded, return zero.
8966 **
8967 ** Even if this function returns zero, it is possible that calling
8968 ** [sqlite3session_changeset()] on the session handle may still return a
8969 ** changeset that contains no changes. This can happen when a row in
8970 ** an attached table is modified and then later on the original values
8971 ** are restored. However, if this function returns non-zero, then it is
8972 ** guaranteed that a call to sqlite3session_changeset() will return a
8973 ** changeset containing zero changes.
8974 */
8975 int sqlite3session_isempty(sqlite3_session *pSession);
8976 
8977 /*
8978 ** CAPI3REF: Create An Iterator To Traverse A Changeset
8979 **
8980 ** Create an iterator used to iterate through the contents of a changeset.
8981 ** If successful, *pp is set to point to the iterator handle and SQLITE_OK
8982 ** is returned. Otherwise, if an error occurs, *pp is set to zero and an
8983 ** SQLite error code is returned.
8984 **
8985 ** The following functions can be used to advance and query a changeset
8986 ** iterator created by this function:
8987 **
8988 ** <ul>
8989 ** <li> [sqlite3changeset_next()]
8990 ** <li> [sqlite3changeset_op()]
8991 ** <li> [sqlite3changeset_new()]
8992 ** <li> [sqlite3changeset_old()]
8993 ** </ul>
8994 **
8995 ** It is the responsibility of the caller to eventually destroy the iterator
8996 ** by passing it to [sqlite3changeset_finalize()]. The buffer containing the
8997 ** changeset (pChangeset) must remain valid until after the iterator is
8998 ** destroyed.
8999 **
9000 ** Assuming the changeset blob was created by one of the
9001 ** [sqlite3session_changeset()], [sqlite3changeset_concat()] or
9002 ** [sqlite3changeset_invert()] functions, all changes within the changeset
9003 ** that apply to a single table are grouped together. This means that when
9004 ** an application iterates through a changeset using an iterator created by
9005 ** this function, all changes that relate to a single table are visted
9006 ** consecutively. There is no chance that the iterator will visit a change
9007 ** the applies to table X, then one for table Y, and then later on visit
9008 ** another change for table X.
9009 */
9010 int sqlite3changeset_start(
9011  sqlite3_changeset_iter **pp, /* OUT: New changeset iterator handle */
9012  int nChangeset, /* Size of changeset blob in bytes */
9013  void *pChangeset /* Pointer to blob containing changeset */
9014 );
9015 
9016 
9017 /*
9018 ** CAPI3REF: Advance A Changeset Iterator
9019 **
9020 ** This function may only be used with iterators created by function
9021 ** [sqlite3changeset_start()]. If it is called on an iterator passed to
9022 ** a conflict-handler callback by [sqlite3changeset_apply()], SQLITE_MISUSE
9023 ** is returned and the call has no effect.
9024 **
9025 ** Immediately after an iterator is created by sqlite3changeset_start(), it
9026 ** does not point to any change in the changeset. Assuming the changeset
9027 ** is not empty, the first call to this function advances the iterator to
9028 ** point to the first change in the changeset. Each subsequent call advances
9029 ** the iterator to point to the next change in the changeset (if any). If
9030 ** no error occurs and the iterator points to a valid change after a call
9031 ** to sqlite3changeset_next() has advanced it, SQLITE_ROW is returned.
9032 ** Otherwise, if all changes in the changeset have already been visited,
9033 ** SQLITE_DONE is returned.
9034 **
9035 ** If an error occurs, an SQLite error code is returned. Possible error
9036 ** codes include SQLITE_CORRUPT (if the changeset buffer is corrupt) or
9037 ** SQLITE_NOMEM.
9038 */
9039 int sqlite3changeset_next(sqlite3_changeset_iter *pIter);
9040 
9041 /*
9042 ** CAPI3REF: Obtain The Current Operation From A Changeset Iterator
9043 **
9044 ** The pIter argument passed to this function may either be an iterator
9045 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9046 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9047 ** call to [sqlite3changeset_next()] must have returned [SQLITE_ROW]. If this
9048 ** is not the case, this function returns [SQLITE_MISUSE].
9049 **
9050 ** If argument pzTab is not NULL, then *pzTab is set to point to a
9051 ** nul-terminated utf-8 encoded string containing the name of the table
9052 ** affected by the current change. The buffer remains valid until either
9053 ** sqlite3changeset_next() is called on the iterator or until the
9054 ** conflict-handler function returns. If pnCol is not NULL, then *pnCol is
9055 ** set to the number of columns in the table affected by the change. If
9056 ** pbIncorrect is not NULL, then *pbIndirect is set to true (1) if the change
9057 ** is an indirect change, or false (0) otherwise. See the documentation for
9058 ** [sqlite3session_indirect()] for a description of direct and indirect
9059 ** changes. Finally, if pOp is not NULL, then *pOp is set to one of
9060 ** [SQLITE_INSERT], [SQLITE_DELETE] or [SQLITE_UPDATE], depending on the
9061 ** type of change that the iterator currently points to.
9062 **
9063 ** If no error occurs, SQLITE_OK is returned. If an error does occur, an
9064 ** SQLite error code is returned. The values of the output variables may not
9065 ** be trusted in this case.
9066 */
9067 int sqlite3changeset_op(
9068  sqlite3_changeset_iter *pIter, /* Iterator object */
9069  const char **pzTab, /* OUT: Pointer to table name */
9070  int *pnCol, /* OUT: Number of columns in table */
9071  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
9072  int *pbIndirect /* OUT: True for an 'indirect' change */
9073 );
9074 
9075 /*
9076 ** CAPI3REF: Obtain The Primary Key Definition Of A Table
9077 **
9078 ** For each modified table, a changeset includes the following:
9079 **
9080 ** <ul>
9081 ** <li> The number of columns in the table, and
9082 ** <li> Which of those columns make up the tables PRIMARY KEY.
9083 ** </ul>
9084 **
9085 ** This function is used to find which columns comprise the PRIMARY KEY of
9086 ** the table modified by the change that iterator pIter currently points to.
9087 ** If successful, *pabPK is set to point to an array of nCol entries, where
9088 ** nCol is the number of columns in the table. Elements of *pabPK are set to
9089 ** 0x01 if the corresponding column is part of the tables primary key, or
9090 ** 0x00 if it is not.
9091 **
9092 ** If argumet pnCol is not NULL, then *pnCol is set to the number of columns
9093 ** in the table.
9094 **
9095 ** If this function is called when the iterator does not point to a valid
9096 ** entry, SQLITE_MISUSE is returned and the output variables zeroed. Otherwise,
9097 ** SQLITE_OK is returned and the output variables populated as described
9098 ** above.
9099 */
9100 int sqlite3changeset_pk(
9101  sqlite3_changeset_iter *pIter, /* Iterator object */
9102  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
9103  int *pnCol /* OUT: Number of entries in output array */
9104 );
9105 
9106 /*
9107 ** CAPI3REF: Obtain old.* Values From A Changeset Iterator
9108 **
9109 ** The pIter argument passed to this function may either be an iterator
9110 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9111 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9112 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9113 ** Furthermore, it may only be called if the type of change that the iterator
9114 ** currently points to is either [SQLITE_DELETE] or [SQLITE_UPDATE]. Otherwise,
9115 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9116 **
9117 ** Argument iVal must be greater than or equal to 0, and less than the number
9118 ** of columns in the table affected by the current change. Otherwise,
9119 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9120 **
9121 ** If successful, this function sets *ppValue to point to a protected
9122 ** sqlite3_value object containing the iVal'th value from the vector of
9123 ** original row values stored as part of the UPDATE or DELETE change and
9124 ** returns SQLITE_OK. The name of the function comes from the fact that this
9125 ** is similar to the "old.*" columns available to update or delete triggers.
9126 **
9127 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9128 ** is returned and *ppValue is set to NULL.
9129 */
9130 int sqlite3changeset_old(
9131  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9132  int iVal, /* Column number */
9133  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
9134 );
9135 
9136 /*
9137 ** CAPI3REF: Obtain new.* Values From A Changeset Iterator
9138 **
9139 ** The pIter argument passed to this function may either be an iterator
9140 ** passed to a conflict-handler by [sqlite3changeset_apply()], or an iterator
9141 ** created by [sqlite3changeset_start()]. In the latter case, the most recent
9142 ** call to [sqlite3changeset_next()] must have returned SQLITE_ROW.
9143 ** Furthermore, it may only be called if the type of change that the iterator
9144 ** currently points to is either [SQLITE_UPDATE] or [SQLITE_INSERT]. Otherwise,
9145 ** this function returns [SQLITE_MISUSE] and sets *ppValue to NULL.
9146 **
9147 ** Argument iVal must be greater than or equal to 0, and less than the number
9148 ** of columns in the table affected by the current change. Otherwise,
9149 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9150 **
9151 ** If successful, this function sets *ppValue to point to a protected
9152 ** sqlite3_value object containing the iVal'th value from the vector of
9153 ** new row values stored as part of the UPDATE or INSERT change and
9154 ** returns SQLITE_OK. If the change is an UPDATE and does not include
9155 ** a new value for the requested column, *ppValue is set to NULL and
9156 ** SQLITE_OK returned. The name of the function comes from the fact that
9157 ** this is similar to the "new.*" columns available to update or delete
9158 ** triggers.
9159 **
9160 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9161 ** is returned and *ppValue is set to NULL.
9162 */
9163 int sqlite3changeset_new(
9164  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9165  int iVal, /* Column number */
9166  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
9167 );
9168 
9169 /*
9170 ** CAPI3REF: Obtain Conflicting Row Values From A Changeset Iterator
9171 **
9172 ** This function should only be used with iterator objects passed to a
9173 ** conflict-handler callback by [sqlite3changeset_apply()] with either
9174 ** [SQLITE_CHANGESET_DATA] or [SQLITE_CHANGESET_CONFLICT]. If this function
9175 ** is called on any other iterator, [SQLITE_MISUSE] is returned and *ppValue
9176 ** is set to NULL.
9177 **
9178 ** Argument iVal must be greater than or equal to 0, and less than the number
9179 ** of columns in the table affected by the current change. Otherwise,
9180 ** [SQLITE_RANGE] is returned and *ppValue is set to NULL.
9181 **
9182 ** If successful, this function sets *ppValue to point to a protected
9183 ** sqlite3_value object containing the iVal'th value from the
9184 ** "conflicting row" associated with the current conflict-handler callback
9185 ** and returns SQLITE_OK.
9186 **
9187 ** If some other error occurs (e.g. an OOM condition), an SQLite error code
9188 ** is returned and *ppValue is set to NULL.
9189 */
9190 int sqlite3changeset_conflict(
9191  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9192  int iVal, /* Column number */
9193  sqlite3_value **ppValue /* OUT: Value from conflicting row */
9194 );
9195 
9196 /*
9197 ** CAPI3REF: Determine The Number Of Foreign Key Constraint Violations
9198 **
9199 ** This function may only be called with an iterator passed to an
9200 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
9201 ** it sets the output variable to the total number of known foreign key
9202 ** violations in the destination database and returns SQLITE_OK.
9203 **
9204 ** In all other cases this function returns SQLITE_MISUSE.
9205 */
9206 int sqlite3changeset_fk_conflicts(
9207  sqlite3_changeset_iter *pIter, /* Changeset iterator */
9208  int *pnOut /* OUT: Number of FK violations */
9209 );
9210 
9211 
9212 /*
9213 ** CAPI3REF: Finalize A Changeset Iterator
9214 **
9215 ** This function is used to finalize an iterator allocated with
9216 ** [sqlite3changeset_start()].
9217 **
9218 ** This function should only be called on iterators created using the
9219 ** [sqlite3changeset_start()] function. If an application calls this
9220 ** function with an iterator passed to a conflict-handler by
9221 ** [sqlite3changeset_apply()], [SQLITE_MISUSE] is immediately returned and the
9222 ** call has no effect.
9223 **
9224 ** If an error was encountered within a call to an sqlite3changeset_xxx()
9225 ** function (for example an [SQLITE_CORRUPT] in [sqlite3changeset_next()] or an
9226 ** [SQLITE_NOMEM] in [sqlite3changeset_new()]) then an error code corresponding
9227 ** to that error is returned by this function. Otherwise, SQLITE_OK is
9228 ** returned. This is to allow the following pattern (pseudo-code):
9229 **
9230 ** sqlite3changeset_start();
9231 ** while( SQLITE_ROW==sqlite3changeset_next() ){
9232 ** // Do something with change.
9233 ** }
9234 ** rc = sqlite3changeset_finalize();
9235 ** if( rc!=SQLITE_OK ){
9236 ** // An error has occurred
9237 ** }
9238 */
9239 int sqlite3changeset_finalize(sqlite3_changeset_iter *pIter);
9240 
9241 /*
9242 ** CAPI3REF: Invert A Changeset
9243 **
9244 ** This function is used to "invert" a changeset object. Applying an inverted
9245 ** changeset to a database reverses the effects of applying the uninverted
9246 ** changeset. Specifically:
9247 **
9248 ** <ul>
9249 ** <li> Each DELETE change is changed to an INSERT, and
9250 ** <li> Each INSERT change is changed to a DELETE, and
9251 ** <li> For each UPDATE change, the old.* and new.* values are exchanged.
9252 ** </ul>
9253 **
9254 ** This function does not change the order in which changes appear within
9255 ** the changeset. It merely reverses the sense of each individual change.
9256 **
9257 ** If successful, a pointer to a buffer containing the inverted changeset
9258 ** is stored in *ppOut, the size of the same buffer is stored in *pnOut, and
9259 ** SQLITE_OK is returned. If an error occurs, both *pnOut and *ppOut are
9260 ** zeroed and an SQLite error code returned.
9261 **
9262 ** It is the responsibility of the caller to eventually call sqlite3_free()
9263 ** on the *ppOut pointer to free the buffer allocation following a successful
9264 ** call to this function.
9265 **
9266 ** WARNING/TODO: This function currently assumes that the input is a valid
9267 ** changeset. If it is not, the results are undefined.
9268 */
9269 int sqlite3changeset_invert(
9270  int nIn, const void *pIn, /* Input changeset */
9271  int *pnOut, void **ppOut /* OUT: Inverse of input */
9272 );
9273 
9274 /*
9275 ** CAPI3REF: Concatenate Two Changeset Objects
9276 **
9277 ** This function is used to concatenate two changesets, A and B, into a
9278 ** single changeset. The result is a changeset equivalent to applying
9279 ** changeset A followed by changeset B.
9280 **
9281 ** This function combines the two input changesets using an
9282 ** sqlite3_changegroup object. Calling it produces similar results as the
9283 ** following code fragment:
9284 **
9285 ** sqlite3_changegroup *pGrp;
9286 ** rc = sqlite3_changegroup_new(&pGrp);
9287 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nA, pA);
9288 ** if( rc==SQLITE_OK ) rc = sqlite3changegroup_add(pGrp, nB, pB);
9289 ** if( rc==SQLITE_OK ){
9290 ** rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
9291 ** }else{
9292 ** *ppOut = 0;
9293 ** *pnOut = 0;
9294 ** }
9295 **
9296 ** Refer to the sqlite3_changegroup documentation below for details.
9297 */
9298 int sqlite3changeset_concat(
9299  int nA, /* Number of bytes in buffer pA */
9300  void *pA, /* Pointer to buffer containing changeset A */
9301  int nB, /* Number of bytes in buffer pB */
9302  void *pB, /* Pointer to buffer containing changeset B */
9303  int *pnOut, /* OUT: Number of bytes in output changeset */
9304  void **ppOut /* OUT: Buffer containing output changeset */
9305 );
9306 
9307 
9308 /*
9309 ** Changegroup handle.
9310 */
9311 typedef struct sqlite3_changegroup sqlite3_changegroup;
9312 
9313 /*
9314 ** CAPI3REF: Combine two or more changesets into a single changeset.
9315 **
9316 ** An sqlite3_changegroup object is used to combine two or more changesets
9317 ** (or patchsets) into a single changeset (or patchset). A single changegroup
9318 ** object may combine changesets or patchsets, but not both. The output is
9319 ** always in the same format as the input.
9320 **
9321 ** If successful, this function returns SQLITE_OK and populates (*pp) with
9322 ** a pointer to a new sqlite3_changegroup object before returning. The caller
9323 ** should eventually free the returned object using a call to
9324 ** sqlite3changegroup_delete(). If an error occurs, an SQLite error code
9325 ** (i.e. SQLITE_NOMEM) is returned and *pp is set to NULL.
9326 **
9327 ** The usual usage pattern for an sqlite3_changegroup object is as follows:
9328 **
9329 ** <ul>
9330 ** <li> It is created using a call to sqlite3changegroup_new().
9331 **
9332 ** <li> Zero or more changesets (or patchsets) are added to the object
9333 ** by calling sqlite3changegroup_add().
9334 **
9335 ** <li> The result of combining all input changesets together is obtained
9336 ** by the application via a call to sqlite3changegroup_output().
9337 **
9338 ** <li> The object is deleted using a call to sqlite3changegroup_delete().
9339 ** </ul>
9340 **
9341 ** Any number of calls to add() and output() may be made between the calls to
9342 ** new() and delete(), and in any order.
9343 **
9344 ** As well as the regular sqlite3changegroup_add() and
9345 ** sqlite3changegroup_output() functions, also available are the streaming
9346 ** versions sqlite3changegroup_add_strm() and sqlite3changegroup_output_strm().
9347 */
9348 int sqlite3changegroup_new(sqlite3_changegroup **pp);
9349 
9350 /*
9351 ** Add all changes within the changeset (or patchset) in buffer pData (size
9352 ** nData bytes) to the changegroup.
9353 **
9354 ** If the buffer contains a patchset, then all prior calls to this function
9355 ** on the same changegroup object must also have specified patchsets. Or, if
9356 ** the buffer contains a changeset, so must have the earlier calls to this
9357 ** function. Otherwise, SQLITE_ERROR is returned and no changes are added
9358 ** to the changegroup.
9359 **
9360 ** Rows within the changeset and changegroup are identified by the values in
9361 ** their PRIMARY KEY columns. A change in the changeset is considered to
9362 ** apply to the same row as a change already present in the changegroup if
9363 ** the two rows have the same primary key.
9364 **
9365 ** Changes to rows that that do not already appear in the changegroup are
9366 ** simply copied into it. Or, if both the new changeset and the changegroup
9367 ** contain changes that apply to a single row, the final contents of the
9368 ** changegroup depends on the type of each change, as follows:
9369 **
9370 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9371 ** <tr><th style="white-space:pre">Existing Change </th>
9372 ** <th style="white-space:pre">New Change </th>
9373 ** <th>Output Change
9374 ** <tr><td>INSERT <td>INSERT <td>
9375 ** The new change is ignored. This case does not occur if the new
9376 ** changeset was recorded immediately after the changesets already
9377 ** added to the changegroup.
9378 ** <tr><td>INSERT <td>UPDATE <td>
9379 ** The INSERT change remains in the changegroup. The values in the
9380 ** INSERT change are modified as if the row was inserted by the
9381 ** existing change and then updated according to the new change.
9382 ** <tr><td>INSERT <td>DELETE <td>
9383 ** The existing INSERT is removed from the changegroup. The DELETE is
9384 ** not added.
9385 ** <tr><td>UPDATE <td>INSERT <td>
9386 ** The new change is ignored. This case does not occur if the new
9387 ** changeset was recorded immediately after the changesets already
9388 ** added to the changegroup.
9389 ** <tr><td>UPDATE <td>UPDATE <td>
9390 ** The existing UPDATE remains within the changegroup. It is amended
9391 ** so that the accompanying values are as if the row was updated once
9392 ** by the existing change and then again by the new change.
9393 ** <tr><td>UPDATE <td>DELETE <td>
9394 ** The existing UPDATE is replaced by the new DELETE within the
9395 ** changegroup.
9396 ** <tr><td>DELETE <td>INSERT <td>
9397 ** If one or more of the column values in the row inserted by the
9398 ** new change differ from those in the row deleted by the existing
9399 ** change, the existing DELETE is replaced by an UPDATE within the
9400 ** changegroup. Otherwise, if the inserted row is exactly the same
9401 ** as the deleted row, the existing DELETE is simply discarded.
9402 ** <tr><td>DELETE <td>UPDATE <td>
9403 ** The new change is ignored. This case does not occur if the new
9404 ** changeset was recorded immediately after the changesets already
9405 ** added to the changegroup.
9406 ** <tr><td>DELETE <td>DELETE <td>
9407 ** The new change is ignored. This case does not occur if the new
9408 ** changeset was recorded immediately after the changesets already
9409 ** added to the changegroup.
9410 ** </table>
9411 **
9412 ** If the new changeset contains changes to a table that is already present
9413 ** in the changegroup, then the number of columns and the position of the
9414 ** primary key columns for the table must be consistent. If this is not the
9415 ** case, this function fails with SQLITE_SCHEMA. If the input changeset
9416 ** appears to be corrupt and the corruption is detected, SQLITE_CORRUPT is
9417 ** returned. Or, if an out-of-memory condition occurs during processing, this
9418 ** function returns SQLITE_NOMEM. In all cases, if an error occurs the
9419 ** final contents of the changegroup is undefined.
9420 **
9421 ** If no error occurs, SQLITE_OK is returned.
9422 */
9423 int sqlite3changegroup_add(sqlite3_changegroup*, int nData, void *pData);
9424 
9425 /*
9426 ** Obtain a buffer containing a changeset (or patchset) representing the
9427 ** current contents of the changegroup. If the inputs to the changegroup
9428 ** were themselves changesets, the output is a changeset. Or, if the
9429 ** inputs were patchsets, the output is also a patchset.
9430 **
9431 ** As with the output of the sqlite3session_changeset() and
9432 ** sqlite3session_patchset() functions, all changes related to a single
9433 ** table are grouped together in the output of this function. Tables appear
9434 ** in the same order as for the very first changeset added to the changegroup.
9435 ** If the second or subsequent changesets added to the changegroup contain
9436 ** changes for tables that do not appear in the first changeset, they are
9437 ** appended onto the end of the output changeset, again in the order in
9438 ** which they are first encountered.
9439 **
9440 ** If an error occurs, an SQLite error code is returned and the output
9441 ** variables (*pnData) and (*ppData) are set to 0. Otherwise, SQLITE_OK
9442 ** is returned and the output variables are set to the size of and a
9443 ** pointer to the output buffer, respectively. In this case it is the
9444 ** responsibility of the caller to eventually free the buffer using a
9445 ** call to sqlite3_free().
9446 */
9447 int sqlite3changegroup_output(
9448  sqlite3_changegroup*,
9449  int *pnData, /* OUT: Size of output buffer in bytes */
9450  void **ppData /* OUT: Pointer to output buffer */
9451 );
9452 
9453 /*
9454 ** Delete a changegroup object.
9455 */
9456 void sqlite3changegroup_delete(sqlite3_changegroup*);
9457 
9458 /*
9459 ** CAPI3REF: Apply A Changeset To A Database
9460 **
9461 ** Apply a changeset to a database. This function attempts to update the
9462 ** "main" database attached to handle db with the changes found in the
9463 ** changeset passed via the second and third arguments.
9464 **
9465 ** The fourth argument (xFilter) passed to this function is the "filter
9466 ** callback". If it is not NULL, then for each table affected by at least one
9467 ** change in the changeset, the filter callback is invoked with
9468 ** the table name as the second argument, and a copy of the context pointer
9469 ** passed as the sixth argument to this function as the first. If the "filter
9470 ** callback" returns zero, then no attempt is made to apply any changes to
9471 ** the table. Otherwise, if the return value is non-zero or the xFilter
9472 ** argument to this function is NULL, all changes related to the table are
9473 ** attempted.
9474 **
9475 ** For each table that is not excluded by the filter callback, this function
9476 ** tests that the target database contains a compatible table. A table is
9477 ** considered compatible if all of the following are true:
9478 **
9479 ** <ul>
9480 ** <li> The table has the same name as the name recorded in the
9481 ** changeset, and
9482 ** <li> The table has the same number of columns as recorded in the
9483 ** changeset, and
9484 ** <li> The table has primary key columns in the same position as
9485 ** recorded in the changeset.
9486 ** </ul>
9487 **
9488 ** If there is no compatible table, it is not an error, but none of the
9489 ** changes associated with the table are applied. A warning message is issued
9490 ** via the sqlite3_log() mechanism with the error code SQLITE_SCHEMA. At most
9491 ** one such warning is issued for each table in the changeset.
9492 **
9493 ** For each change for which there is a compatible table, an attempt is made
9494 ** to modify the table contents according to the UPDATE, INSERT or DELETE
9495 ** change. If a change cannot be applied cleanly, the conflict handler
9496 ** function passed as the fifth argument to sqlite3changeset_apply() may be
9497 ** invoked. A description of exactly when the conflict handler is invoked for
9498 ** each type of change is below.
9499 **
9500 ** Unlike the xFilter argument, xConflict may not be passed NULL. The results
9501 ** of passing anything other than a valid function pointer as the xConflict
9502 ** argument are undefined.
9503 **
9504 ** Each time the conflict handler function is invoked, it must return one
9505 ** of [SQLITE_CHANGESET_OMIT], [SQLITE_CHANGESET_ABORT] or
9506 ** [SQLITE_CHANGESET_REPLACE]. SQLITE_CHANGESET_REPLACE may only be returned
9507 ** if the second argument passed to the conflict handler is either
9508 ** SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If the conflict-handler
9509 ** returns an illegal value, any changes already made are rolled back and
9510 ** the call to sqlite3changeset_apply() returns SQLITE_MISUSE. Different
9511 ** actions are taken by sqlite3changeset_apply() depending on the value
9512 ** returned by each invocation of the conflict-handler function. Refer to
9513 ** the documentation for the three
9514 ** [SQLITE_CHANGESET_OMIT|available return values] for details.
9515 **
9516 ** <dl>
9517 ** <dt>DELETE Changes<dd>
9518 ** For each DELETE change, this function checks if the target database
9519 ** contains a row with the same primary key value (or values) as the
9520 ** original row values stored in the changeset. If it does, and the values
9521 ** stored in all non-primary key columns also match the values stored in
9522 ** the changeset the row is deleted from the target database.
9523 **
9524 ** If a row with matching primary key values is found, but one or more of
9525 ** the non-primary key fields contains a value different from the original
9526 ** row value stored in the changeset, the conflict-handler function is
9527 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument.
9528 **
9529 ** If no row with matching primary key values is found in the database,
9530 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9531 ** passed as the second argument.
9532 **
9533 ** If the DELETE operation is attempted, but SQLite returns SQLITE_CONSTRAINT
9534 ** (which can only happen if a foreign key constraint is violated), the
9535 ** conflict-handler function is invoked with [SQLITE_CHANGESET_CONSTRAINT]
9536 ** passed as the second argument. This includes the case where the DELETE
9537 ** operation is attempted because an earlier call to the conflict handler
9538 ** function returned [SQLITE_CHANGESET_REPLACE].
9539 **
9540 ** <dt>INSERT Changes<dd>
9541 ** For each INSERT change, an attempt is made to insert the new row into
9542 ** the database.
9543 **
9544 ** If the attempt to insert the row fails because the database already
9545 ** contains a row with the same primary key values, the conflict handler
9546 ** function is invoked with the second argument set to
9547 ** [SQLITE_CHANGESET_CONFLICT].
9548 **
9549 ** If the attempt to insert the row fails because of some other constraint
9550 ** violation (e.g. NOT NULL or UNIQUE), the conflict handler function is
9551 ** invoked with the second argument set to [SQLITE_CHANGESET_CONSTRAINT].
9552 ** This includes the case where the INSERT operation is re-attempted because
9553 ** an earlier call to the conflict handler function returned
9554 ** [SQLITE_CHANGESET_REPLACE].
9555 **
9556 ** <dt>UPDATE Changes<dd>
9557 ** For each UPDATE change, this function checks if the target database
9558 ** contains a row with the same primary key value (or values) as the
9559 ** original row values stored in the changeset. If it does, and the values
9560 ** stored in all non-primary key columns also match the values stored in
9561 ** the changeset the row is updated within the target database.
9562 **
9563 ** If a row with matching primary key values is found, but one or more of
9564 ** the non-primary key fields contains a value different from an original
9565 ** row value stored in the changeset, the conflict-handler function is
9566 ** invoked with [SQLITE_CHANGESET_DATA] as the second argument. Since
9567 ** UPDATE changes only contain values for non-primary key fields that are
9568 ** to be modified, only those fields need to match the original values to
9569 ** avoid the SQLITE_CHANGESET_DATA conflict-handler callback.
9570 **
9571 ** If no row with matching primary key values is found in the database,
9572 ** the conflict-handler function is invoked with [SQLITE_CHANGESET_NOTFOUND]
9573 ** passed as the second argument.
9574 **
9575 ** If the UPDATE operation is attempted, but SQLite returns
9576 ** SQLITE_CONSTRAINT, the conflict-handler function is invoked with
9577 ** [SQLITE_CHANGESET_CONSTRAINT] passed as the second argument.
9578 ** This includes the case where the UPDATE operation is attempted after
9579 ** an earlier call to the conflict handler function returned
9580 ** [SQLITE_CHANGESET_REPLACE].
9581 ** </dl>
9582 **
9583 ** It is safe to execute SQL statements, including those that write to the
9584 ** table that the callback related to, from within the xConflict callback.
9585 ** This can be used to further customize the applications conflict
9586 ** resolution strategy.
9587 **
9588 ** All changes made by this function are enclosed in a savepoint transaction.
9589 ** If any other error (aside from a constraint failure when attempting to
9590 ** write to the target database) occurs, then the savepoint transaction is
9591 ** rolled back, restoring the target database to its original state, and an
9592 ** SQLite error code returned.
9593 */
9594 int sqlite3changeset_apply(
9595  sqlite3 *db, /* Apply change to "main" db of this handle */
9596  int nChangeset, /* Size of changeset in bytes */
9597  void *pChangeset, /* Changeset blob */
9598  int(*xFilter)(
9599  void *pCtx, /* Copy of sixth arg to _apply() */
9600  const char *zTab /* Table name */
9601  ),
9602  int(*xConflict)(
9603  void *pCtx, /* Copy of sixth arg to _apply() */
9604  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9605  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9606  ),
9607  void *pCtx /* First argument passed to xConflict */
9608 );
9609 
9610 /*
9611 ** CAPI3REF: Constants Passed To The Conflict Handler
9612 **
9613 ** Values that may be passed as the second argument to a conflict-handler.
9614 **
9615 ** <dl>
9616 ** <dt>SQLITE_CHANGESET_DATA<dd>
9617 ** The conflict handler is invoked with CHANGESET_DATA as the second argument
9618 ** when processing a DELETE or UPDATE change if a row with the required
9619 ** PRIMARY KEY fields is present in the database, but one or more other
9620 ** (non primary-key) fields modified by the update do not contain the
9621 ** expected "before" values.
9622 **
9623 ** The conflicting row, in this case, is the database row with the matching
9624 ** primary key.
9625 **
9626 ** <dt>SQLITE_CHANGESET_NOTFOUND<dd>
9627 ** The conflict handler is invoked with CHANGESET_NOTFOUND as the second
9628 ** argument when processing a DELETE or UPDATE change if a row with the
9629 ** required PRIMARY KEY fields is not present in the database.
9630 **
9631 ** There is no conflicting row in this case. The results of invoking the
9632 ** sqlite3changeset_conflict() API are undefined.
9633 **
9634 ** <dt>SQLITE_CHANGESET_CONFLICT<dd>
9635 ** CHANGESET_CONFLICT is passed as the second argument to the conflict
9636 ** handler while processing an INSERT change if the operation would result
9637 ** in duplicate primary key values.
9638 **
9639 ** The conflicting row in this case is the database row with the matching
9640 ** primary key.
9641 **
9642 ** <dt>SQLITE_CHANGESET_FOREIGN_KEY<dd>
9643 ** If foreign key handling is enabled, and applying a changeset leaves the
9644 ** database in a state containing foreign key violations, the conflict
9645 ** handler is invoked with CHANGESET_FOREIGN_KEY as the second argument
9646 ** exactly once before the changeset is committed. If the conflict handler
9647 ** returns CHANGESET_OMIT, the changes, including those that caused the
9648 ** foreign key constraint violation, are committed. Or, if it returns
9649 ** CHANGESET_ABORT, the changeset is rolled back.
9650 **
9651 ** No current or conflicting row information is provided. The only function
9652 ** it is possible to call on the supplied sqlite3_changeset_iter handle
9653 ** is sqlite3changeset_fk_conflicts().
9654 **
9655 ** <dt>SQLITE_CHANGESET_CONSTRAINT<dd>
9656 ** If any other constraint violation occurs while applying a change (i.e.
9657 ** a UNIQUE, CHECK or NOT NULL constraint), the conflict handler is
9658 ** invoked with CHANGESET_CONSTRAINT as the second argument.
9659 **
9660 ** There is no conflicting row in this case. The results of invoking the
9661 ** sqlite3changeset_conflict() API are undefined.
9662 **
9663 ** </dl>
9664 */
9665 #define SQLITE_CHANGESET_DATA 1
9666 #define SQLITE_CHANGESET_NOTFOUND 2
9667 #define SQLITE_CHANGESET_CONFLICT 3
9668 #define SQLITE_CHANGESET_CONSTRAINT 4
9669 #define SQLITE_CHANGESET_FOREIGN_KEY 5
9670 
9671 /*
9672 ** CAPI3REF: Constants Returned By The Conflict Handler
9673 **
9674 ** A conflict handler callback must return one of the following three values.
9675 **
9676 ** <dl>
9677 ** <dt>SQLITE_CHANGESET_OMIT<dd>
9678 ** If a conflict handler returns this value no special action is taken. The
9679 ** change that caused the conflict is not applied. The session module
9680 ** continues to the next change in the changeset.
9681 **
9682 ** <dt>SQLITE_CHANGESET_REPLACE<dd>
9683 ** This value may only be returned if the second argument to the conflict
9684 ** handler was SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT. If this
9685 ** is not the case, any changes applied so far are rolled back and the
9686 ** call to sqlite3changeset_apply() returns SQLITE_MISUSE.
9687 **
9688 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_DATA conflict
9689 ** handler, then the conflicting row is either updated or deleted, depending
9690 ** on the type of change.
9691 **
9692 ** If CHANGESET_REPLACE is returned by an SQLITE_CHANGESET_CONFLICT conflict
9693 ** handler, then the conflicting row is removed from the database and a
9694 ** second attempt to apply the change is made. If this second attempt fails,
9695 ** the original row is restored to the database before continuing.
9696 **
9697 ** <dt>SQLITE_CHANGESET_ABORT<dd>
9698 ** If this value is returned, any changes applied so far are rolled back
9699 ** and the call to sqlite3changeset_apply() returns SQLITE_ABORT.
9700 ** </dl>
9701 */
9702 #define SQLITE_CHANGESET_OMIT 0
9703 #define SQLITE_CHANGESET_REPLACE 1
9704 #define SQLITE_CHANGESET_ABORT 2
9705 
9706 /*
9707 ** CAPI3REF: Streaming Versions of API functions.
9708 **
9709 ** The six streaming API xxx_strm() functions serve similar purposes to the
9710 ** corresponding non-streaming API functions:
9711 **
9712 ** <table border=1 style="margin-left:8ex;margin-right:8ex">
9713 ** <tr><th>Streaming function<th>Non-streaming equivalent</th>
9714 ** <tr><td>sqlite3changeset_apply_str<td>[sqlite3changeset_apply]
9715 ** <tr><td>sqlite3changeset_concat_str<td>[sqlite3changeset_concat]
9716 ** <tr><td>sqlite3changeset_invert_str<td>[sqlite3changeset_invert]
9717 ** <tr><td>sqlite3changeset_start_str<td>[sqlite3changeset_start]
9718 ** <tr><td>sqlite3session_changeset_str<td>[sqlite3session_changeset]
9719 ** <tr><td>sqlite3session_patchset_str<td>[sqlite3session_patchset]
9720 ** </table>
9721 **
9722 ** Non-streaming functions that accept changesets (or patchsets) as input
9723 ** require that the entire changeset be stored in a single buffer in memory.
9724 ** Similarly, those that return a changeset or patchset do so by returning
9725 ** a pointer to a single large buffer allocated using sqlite3_malloc().
9726 ** Normally this is convenient. However, if an application running in a
9727 ** low-memory environment is required to handle very large changesets, the
9728 ** large contiguous memory allocations required can become onerous.
9729 **
9730 ** In order to avoid this problem, instead of a single large buffer, input
9731 ** is passed to a streaming API functions by way of a callback function that
9732 ** the sessions module invokes to incrementally request input data as it is
9733 ** required. In all cases, a pair of API function parameters such as
9734 **
9735 ** <pre>
9736 ** &nbsp; int nChangeset,
9737 ** &nbsp; void *pChangeset,
9738 ** </pre>
9739 **
9740 ** Is replaced by:
9741 **
9742 ** <pre>
9743 ** &nbsp; int (*xInput)(void *pIn, void *pData, int *pnData),
9744 ** &nbsp; void *pIn,
9745 ** </pre>
9746 **
9747 ** Each time the xInput callback is invoked by the sessions module, the first
9748 ** argument passed is a copy of the supplied pIn context pointer. The second
9749 ** argument, pData, points to a buffer (*pnData) bytes in size. Assuming no
9750 ** error occurs the xInput method should copy up to (*pnData) bytes of data
9751 ** into the buffer and set (*pnData) to the actual number of bytes copied
9752 ** before returning SQLITE_OK. If the input is completely exhausted, (*pnData)
9753 ** should be set to zero to indicate this. Or, if an error occurs, an SQLite
9754 ** error code should be returned. In all cases, if an xInput callback returns
9755 ** an error, all processing is abandoned and the streaming API function
9756 ** returns a copy of the error code to the caller.
9757 **
9758 ** In the case of sqlite3changeset_start_strm(), the xInput callback may be
9759 ** invoked by the sessions module at any point during the lifetime of the
9760 ** iterator. If such an xInput callback returns an error, the iterator enters
9761 ** an error state, whereby all subsequent calls to iterator functions
9762 ** immediately fail with the same error code as returned by xInput.
9763 **
9764 ** Similarly, streaming API functions that return changesets (or patchsets)
9765 ** return them in chunks by way of a callback function instead of via a
9766 ** pointer to a single large buffer. In this case, a pair of parameters such
9767 ** as:
9768 **
9769 ** <pre>
9770 ** &nbsp; int *pnChangeset,
9771 ** &nbsp; void **ppChangeset,
9772 ** </pre>
9773 **
9774 ** Is replaced by:
9775 **
9776 ** <pre>
9777 ** &nbsp; int (*xOutput)(void *pOut, const void *pData, int nData),
9778 ** &nbsp; void *pOut
9779 ** </pre>
9780 **
9781 ** The xOutput callback is invoked zero or more times to return data to
9782 ** the application. The first parameter passed to each call is a copy of the
9783 ** pOut pointer supplied by the application. The second parameter, pData,
9784 ** points to a buffer nData bytes in size containing the chunk of output
9785 ** data being returned. If the xOutput callback successfully processes the
9786 ** supplied data, it should return SQLITE_OK to indicate success. Otherwise,
9787 ** it should return some other SQLite error code. In this case processing
9788 ** is immediately abandoned and the streaming API function returns a copy
9789 ** of the xOutput error code to the application.
9790 **
9791 ** The sessions module never invokes an xOutput callback with the third
9792 ** parameter set to a value less than or equal to zero. Other than this,
9793 ** no guarantees are made as to the size of the chunks of data returned.
9794 */
9795 int sqlite3changeset_apply_strm(
9796  sqlite3 *db, /* Apply change to "main" db of this handle */
9797  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
9798  void *pIn, /* First arg for xInput */
9799  int(*xFilter)(
9800  void *pCtx, /* Copy of sixth arg to _apply() */
9801  const char *zTab /* Table name */
9802  ),
9803  int(*xConflict)(
9804  void *pCtx, /* Copy of sixth arg to _apply() */
9805  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
9806  sqlite3_changeset_iter *p /* Handle describing change and conflict */
9807  ),
9808  void *pCtx /* First argument passed to xConflict */
9809 );
9810 int sqlite3changeset_concat_strm(
9811  int (*xInputA)(void *pIn, void *pData, int *pnData),
9812  void *pInA,
9813  int (*xInputB)(void *pIn, void *pData, int *pnData),
9814  void *pInB,
9815  int (*xOutput)(void *pOut, const void *pData, int nData),
9816  void *pOut
9817 );
9818 int sqlite3changeset_invert_strm(
9819  int (*xInput)(void *pIn, void *pData, int *pnData),
9820  void *pIn,
9821  int (*xOutput)(void *pOut, const void *pData, int nData),
9822  void *pOut
9823 );
9824 int sqlite3changeset_start_strm(
9825  sqlite3_changeset_iter **pp,
9826  int (*xInput)(void *pIn, void *pData, int *pnData),
9827  void *pIn
9828 );
9829 int sqlite3session_changeset_strm(
9830  sqlite3_session *pSession,
9831  int (*xOutput)(void *pOut, const void *pData, int nData),
9832  void *pOut
9833 );
9834 int sqlite3session_patchset_strm(
9835  sqlite3_session *pSession,
9836  int (*xOutput)(void *pOut, const void *pData, int nData),
9837  void *pOut
9838 );
9839 int sqlite3changegroup_add_strm(sqlite3_changegroup*,
9840  int (*xInput)(void *pIn, void *pData, int *pnData),
9841  void *pIn
9842 );
9843 int sqlite3changegroup_output_strm(sqlite3_changegroup*,
9844  int (*xOutput)(void *pOut, const void *pData, int nData),
9845  void *pOut
9846 );
9847 
9848 
9849 /*
9850 ** Make sure we can call this stuff from C++.
9851 */
9852 #if 0
9853 }
9854 #endif
9855 
9856 #endif /* !defined(__SQLITESESSION_H_) && defined(SQLITE_ENABLE_SESSION) */
9857 
9858 /******** End of sqlite3session.h *********/
9859 /******** Begin file fts5.h *********/
9860 /*
9861 ** 2014 May 31
9862 **
9863 ** The author disclaims copyright to this source code. In place of
9864 ** a legal notice, here is a blessing:
9865 **
9866 ** May you do good and not evil.
9867 ** May you find forgiveness for yourself and forgive others.
9868 ** May you share freely, never taking more than you give.
9869 **
9870 ******************************************************************************
9871 **
9872 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
9873 ** FTS5 may be extended with:
9874 **
9875 ** * custom tokenizers, and
9876 ** * custom auxiliary functions.
9877 */
9878 
9879 
9880 #ifndef _FTS5_H
9881 #define _FTS5_H
9882 
9883 
9884 #if 0
9885 extern "C" {
9886 #endif
9887 
9888 /*************************************************************************
9889 ** CUSTOM AUXILIARY FUNCTIONS
9890 **
9891 ** Virtual table implementations may overload SQL functions by implementing
9892 ** the sqlite3_module.xFindFunction() method.
9893 */
9894 
9896 typedef struct Fts5Context Fts5Context;
9898 
9900  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
9901  Fts5Context *pFts, /* First arg to pass to pApi functions */
9902  sqlite3_context *pCtx, /* Context for returning result/error */
9903  int nVal, /* Number of values in apVal[] array */
9904  sqlite3_value **apVal /* Array of trailing arguments */
9905 );
9906 
9908  const unsigned char *a;
9909  const unsigned char *b;
9910 };
9911 
9912 /*
9913 ** EXTENSION API FUNCTIONS
9914 **
9915 ** xUserData(pFts):
9916 ** Return a copy of the context pointer the extension function was
9917 ** registered with.
9918 **
9919 ** xColumnTotalSize(pFts, iCol, pnToken):
9920 ** If parameter iCol is less than zero, set output variable *pnToken
9921 ** to the total number of tokens in the FTS5 table. Or, if iCol is
9922 ** non-negative but less than the number of columns in the table, return
9923 ** the total number of tokens in column iCol, considering all rows in
9924 ** the FTS5 table.
9925 **
9926 ** If parameter iCol is greater than or equal to the number of columns
9927 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
9928 ** an OOM condition or IO error), an appropriate SQLite error code is
9929 ** returned.
9930 **
9931 ** xColumnCount(pFts):
9932 ** Return the number of columns in the table.
9933 **
9934 ** xColumnSize(pFts, iCol, pnToken):
9935 ** If parameter iCol is less than zero, set output variable *pnToken
9936 ** to the total number of tokens in the current row. Or, if iCol is
9937 ** non-negative but less than the number of columns in the table, set
9938 ** *pnToken to the number of tokens in column iCol of the current row.
9939 **
9940 ** If parameter iCol is greater than or equal to the number of columns
9941 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
9942 ** an OOM condition or IO error), an appropriate SQLite error code is
9943 ** returned.
9944 **
9945 ** This function may be quite inefficient if used with an FTS5 table
9946 ** created with the "columnsize=0" option.
9947 **
9948 ** xColumnText:
9949 ** This function attempts to retrieve the text of column iCol of the
9950 ** current document. If successful, (*pz) is set to point to a buffer
9951 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
9952 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
9953 ** if an error occurs, an SQLite error code is returned and the final values
9954 ** of (*pz) and (*pn) are undefined.
9955 **
9956 ** xPhraseCount:
9957 ** Returns the number of phrases in the current query expression.
9958 **
9959 ** xPhraseSize:
9960 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
9961 ** are numbered starting from zero.
9962 **
9963 ** xInstCount:
9964 ** Set *pnInst to the total number of occurrences of all phrases within
9965 ** the query within the current row. Return SQLITE_OK if successful, or
9966 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
9967 **
9968 ** This API can be quite slow if used with an FTS5 table created with the
9969 ** "detail=none" or "detail=column" option. If the FTS5 table is created
9970 ** with either "detail=none" or "detail=column" and "content=" option
9971 ** (i.e. if it is a contentless table), then this API always returns 0.
9972 **
9973 ** xInst:
9974 ** Query for the details of phrase match iIdx within the current row.
9975 ** Phrase matches are numbered starting from zero, so the iIdx argument
9976 ** should be greater than or equal to zero and smaller than the value
9977 ** output by xInstCount().
9978 **
9979 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
9980 ** to the column in which it occurs and *piOff the token offset of the
9981 ** first token of the phrase. The exception is if the table was created
9982 ** with the offsets=0 option specified. In this case *piOff is always
9983 ** set to -1.
9984 **
9985 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
9986 ** if an error occurs.
9987 **
9988 ** This API can be quite slow if used with an FTS5 table created with the
9989 ** "detail=none" or "detail=column" option.
9990 **
9991 ** xRowid:
9992 ** Returns the rowid of the current row.
9993 **
9994 ** xTokenize:
9995 ** Tokenize text using the tokenizer belonging to the FTS5 table.
9996 **
9997 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
9998 ** This API function is used to query the FTS table for phrase iPhrase
9999 ** of the current query. Specifically, a query equivalent to:
10000 **
10001 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
10002 **
10003 ** with $p set to a phrase equivalent to the phrase iPhrase of the
10004 ** current query is executed. Any column filter that applies to
10005 ** phrase iPhrase of the current query is included in $p. For each
10006 ** row visited, the callback function passed as the fourth argument
10007 ** is invoked. The context and API objects passed to the callback
10008 ** function may be used to access the properties of each matched row.
10009 ** Invoking Api.xUserData() returns a copy of the pointer passed as
10010 ** the third argument to pUserData.
10011 **
10012 ** If the callback function returns any value other than SQLITE_OK, the
10013 ** query is abandoned and the xQueryPhrase function returns immediately.
10014 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
10015 ** Otherwise, the error code is propagated upwards.
10016 **
10017 ** If the query runs to completion without incident, SQLITE_OK is returned.
10018 ** Or, if some error occurs before the query completes or is aborted by
10019 ** the callback, an SQLite error code is returned.
10020 **
10021 **
10022 ** xSetAuxdata(pFts5, pAux, xDelete)
10023 **
10024 ** Save the pointer passed as the second argument as the extension functions
10025 ** "auxiliary data". The pointer may then be retrieved by the current or any
10026 ** future invocation of the same fts5 extension function made as part of
10027 ** of the same MATCH query using the xGetAuxdata() API.
10028 **
10029 ** Each extension function is allocated a single auxiliary data slot for
10030 ** each FTS query (MATCH expression). If the extension function is invoked
10031 ** more than once for a single FTS query, then all invocations share a
10032 ** single auxiliary data context.
10033 **
10034 ** If there is already an auxiliary data pointer when this function is
10035 ** invoked, then it is replaced by the new pointer. If an xDelete callback
10036 ** was specified along with the original pointer, it is invoked at this
10037 ** point.
10038 **
10039 ** The xDelete callback, if one is specified, is also invoked on the
10040 ** auxiliary data pointer after the FTS5 query has finished.
10041 **
10042 ** If an error (e.g. an OOM condition) occurs within this function, an
10043 ** the auxiliary data is set to NULL and an error code returned. If the
10044 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
10045 ** pointer before returning.
10046 **
10047 **
10048 ** xGetAuxdata(pFts5, bClear)
10049 **
10050 ** Returns the current auxiliary data pointer for the fts5 extension
10051 ** function. See the xSetAuxdata() method for details.
10052 **
10053 ** If the bClear argument is non-zero, then the auxiliary data is cleared
10054 ** (set to NULL) before this function returns. In this case the xDelete,
10055 ** if any, is not invoked.
10056 **
10057 **
10058 ** xRowCount(pFts5, pnRow)
10059 **
10060 ** This function is used to retrieve the total number of rows in the table.
10061 ** In other words, the same value that would be returned by:
10062 **
10063 ** SELECT count(*) FROM ftstable;
10064 **
10065 ** xPhraseFirst()
10066 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
10067 ** method, to iterate through all instances of a single query phrase within
10068 ** the current row. This is the same information as is accessible via the
10069 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
10070 ** to use, this API may be faster under some circumstances. To iterate
10071 ** through instances of phrase iPhrase, use the following code:
10072 **
10073 ** Fts5PhraseIter iter;
10074 ** int iCol, iOff;
10075 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
10076 ** iCol>=0;
10077 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
10078 ** ){
10079 ** // An instance of phrase iPhrase at offset iOff of column iCol
10080 ** }
10081 **
10082 ** The Fts5PhraseIter structure is defined above. Applications should not
10083 ** modify this structure directly - it should only be used as shown above
10084 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
10085 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
10086 **
10087 ** This API can be quite slow if used with an FTS5 table created with the
10088 ** "detail=none" or "detail=column" option. If the FTS5 table is created
10089 ** with either "detail=none" or "detail=column" and "content=" option
10090 ** (i.e. if it is a contentless table), then this API always iterates
10091 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
10092 **
10093 ** xPhraseNext()
10094 ** See xPhraseFirst above.
10095 **
10096 ** xPhraseFirstColumn()
10097 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
10098 ** and xPhraseNext() APIs described above. The difference is that instead
10099 ** of iterating through all instances of a phrase in the current row, these
10100 ** APIs are used to iterate through the set of columns in the current row
10101 ** that contain one or more instances of a specified phrase. For example:
10102 **
10103 ** Fts5PhraseIter iter;
10104 ** int iCol;
10105 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
10106 ** iCol>=0;
10107 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
10108 ** ){
10109 ** // Column iCol contains at least one instance of phrase iPhrase
10110 ** }
10111 **
10112 ** This API can be quite slow if used with an FTS5 table created with the
10113 ** "detail=none" option. If the FTS5 table is created with either
10114 ** "detail=none" "content=" option (i.e. if it is a contentless table),
10115 ** then this API always iterates through an empty set (all calls to
10116 ** xPhraseFirstColumn() set iCol to -1).
10117 **
10118 ** The information accessed using this API and its companion
10119 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
10120 ** (or xInst/xInstCount). The chief advantage of this API is that it is
10121 ** significantly more efficient than those alternatives when used with
10122 ** "detail=column" tables.
10123 **
10124 ** xPhraseNextColumn()
10125 ** See xPhraseFirstColumn above.
10126 */
10128  int iVersion; /* Currently always set to 3 */
10129 
10130  void *(*xUserData)(Fts5Context*);
10131 
10132  int (*xColumnCount)(Fts5Context*);
10133  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
10134  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
10135 
10136  int (*xTokenize)(Fts5Context*,
10137  const char *pText, int nText, /* Text to tokenize */
10138  void *pCtx, /* Context passed to xToken() */
10139  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
10140  );
10141 
10142  int (*xPhraseCount)(Fts5Context*);
10143  int (*xPhraseSize)(Fts5Context*, int iPhrase);
10144 
10145  int (*xInstCount)(Fts5Context*, int *pnInst);
10146  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
10147 
10149  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
10150  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
10151 
10152  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
10153  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
10154  );
10155  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
10156  void *(*xGetAuxdata)(Fts5Context*, int bClear);
10157 
10158  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
10159  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
10160 
10161  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
10162  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
10163 };
10164 
10165 /*
10166 ** CUSTOM AUXILIARY FUNCTIONS
10167 *************************************************************************/
10168 
10169 /*************************************************************************
10170 ** CUSTOM TOKENIZERS
10171 **
10172 ** Applications may also register custom tokenizer types. A tokenizer
10173 ** is registered by providing fts5 with a populated instance of the
10174 ** following structure. All structure methods must be defined, setting
10175 ** any member of the fts5_tokenizer struct to NULL leads to undefined
10176 ** behaviour. The structure methods are expected to function as follows:
10177 **
10178 ** xCreate:
10179 ** This function is used to allocate and inititalize a tokenizer instance.
10180 ** A tokenizer instance is required to actually tokenize text.
10181 **
10182 ** The first argument passed to this function is a copy of the (void*)
10183 ** pointer provided by the application when the fts5_tokenizer object
10184 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
10185 ** The second and third arguments are an array of nul-terminated strings
10186 ** containing the tokenizer arguments, if any, specified following the
10187 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
10188 ** to create the FTS5 table.
10189 **
10190 ** The final argument is an output variable. If successful, (*ppOut)
10191 ** should be set to point to the new tokenizer handle and SQLITE_OK
10192 ** returned. If an error occurs, some value other than SQLITE_OK should
10193 ** be returned. In this case, fts5 assumes that the final value of *ppOut
10194 ** is undefined.
10195 **
10196 ** xDelete:
10197 ** This function is invoked to delete a tokenizer handle previously
10198 ** allocated using xCreate(). Fts5 guarantees that this function will
10199 ** be invoked exactly once for each successful call to xCreate().
10200 **
10201 ** xTokenize:
10202 ** This function is expected to tokenize the nText byte string indicated
10203 ** by argument pText. pText may or may not be nul-terminated. The first
10204 ** argument passed to this function is a pointer to an Fts5Tokenizer object
10205 ** returned by an earlier call to xCreate().
10206 **
10207 ** The second argument indicates the reason that FTS5 is requesting
10208 ** tokenization of the supplied text. This is always one of the following
10209 ** four values:
10210 **
10211 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
10212 ** or removed from the FTS table. The tokenizer is being invoked to
10213 ** determine the set of tokens to add to (or delete from) the
10214 ** FTS index.
10215 **
10216 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
10217 ** against the FTS index. The tokenizer is being called to tokenize
10218 ** a bareword or quoted string specified as part of the query.
10219 **
10220 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
10221 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
10222 ** followed by a "*" character, indicating that the last token
10223 ** returned by the tokenizer will be treated as a token prefix.
10224 **
10225 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
10226 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
10227 ** function. Or an fts5_api.xColumnSize() request made by the same
10228 ** on a columnsize=0 database.
10229 ** </ul>
10230 **
10231 ** For each token in the input string, the supplied callback xToken() must
10232 ** be invoked. The first argument to it should be a copy of the pointer
10233 ** passed as the second argument to xTokenize(). The third and fourth
10234 ** arguments are a pointer to a buffer containing the token text, and the
10235 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
10236 ** of the first byte of and first byte immediately following the text from
10237 ** which the token is derived within the input.
10238 **
10239 ** The second argument passed to the xToken() callback ("tflags") should
10240 ** normally be set to 0. The exception is if the tokenizer supports
10241 ** synonyms. In this case see the discussion below for details.
10242 **
10243 ** FTS5 assumes the xToken() callback is invoked for each token in the
10244 ** order that they occur within the input text.
10245 **
10246 ** If an xToken() callback returns any value other than SQLITE_OK, then
10247 ** the tokenization should be abandoned and the xTokenize() method should
10248 ** immediately return a copy of the xToken() return value. Or, if the
10249 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
10250 ** if an error occurs with the xTokenize() implementation itself, it
10251 ** may abandon the tokenization and return any error code other than
10252 ** SQLITE_OK or SQLITE_DONE.
10253 **
10254 ** SYNONYM SUPPORT
10255 **
10256 ** Custom tokenizers may also support synonyms. Consider a case in which a
10257 ** user wishes to query for a phrase such as "first place". Using the
10258 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
10259 ** of "first place" within the document set, but not alternative forms
10260 ** such as "1st place". In some applications, it would be better to match
10261 ** all instances of "first place" or "1st place" regardless of which form
10262 ** the user specified in the MATCH query text.
10263 **
10264 ** There are several ways to approach this in FTS5:
10265 **
10266 ** <ol><li> By mapping all synonyms to a single token. In this case, the
10267 ** In the above example, this means that the tokenizer returns the
10268 ** same token for inputs "first" and "1st". Say that token is in
10269 ** fact "first", so that when the user inserts the document "I won
10270 ** 1st place" entries are added to the index for tokens "i", "won",
10271 ** "first" and "place". If the user then queries for '1st + place',
10272 ** the tokenizer substitutes "first" for "1st" and the query works
10273 ** as expected.
10274 **
10275 ** <li> By adding multiple synonyms for a single term to the FTS index.
10276 ** In this case, when tokenizing query text, the tokenizer may
10277 ** provide multiple synonyms for a single term within the document.
10278 ** FTS5 then queries the index for each synonym individually. For
10279 ** example, faced with the query:
10280 **
10281 ** <codeblock>
10282 ** ... MATCH 'first place'</codeblock>
10283 **
10284 ** the tokenizer offers both "1st" and "first" as synonyms for the
10285 ** first token in the MATCH query and FTS5 effectively runs a query
10286 ** similar to:
10287 **
10288 ** <codeblock>
10289 ** ... MATCH '(first OR 1st) place'</codeblock>
10290 **
10291 ** except that, for the purposes of auxiliary functions, the query
10292 ** still appears to contain just two phrases - "(first OR 1st)"
10293 ** being treated as a single phrase.
10294 **
10295 ** <li> By adding multiple synonyms for a single term to the FTS index.
10296 ** Using this method, when tokenizing document text, the tokenizer
10297 ** provides multiple synonyms for each token. So that when a
10298 ** document such as "I won first place" is tokenized, entries are
10299 ** added to the FTS index for "i", "won", "first", "1st" and
10300 ** "place".
10301 **
10302 ** This way, even if the tokenizer does not provide synonyms
10303 ** when tokenizing query text (it should not - to do would be
10304 ** inefficient), it doesn't matter if the user queries for
10305 ** 'first + place' or '1st + place', as there are entires in the
10306 ** FTS index corresponding to both forms of the first token.
10307 ** </ol>
10308 **
10309 ** Whether it is parsing document or query text, any call to xToken that
10310 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
10311 ** is considered to supply a synonym for the previous token. For example,
10312 ** when parsing the document "I won first place", a tokenizer that supports
10313 ** synonyms would call xToken() 5 times, as follows:
10314 **
10315 ** <codeblock>
10316 ** xToken(pCtx, 0, "i", 1, 0, 1);
10317 ** xToken(pCtx, 0, "won", 3, 2, 5);
10318 ** xToken(pCtx, 0, "first", 5, 6, 11);
10319 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
10320 ** xToken(pCtx, 0, "place", 5, 12, 17);
10321 **</codeblock>
10322 **
10323 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
10324 ** xToken() is called. Multiple synonyms may be specified for a single token
10325 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
10326 ** There is no limit to the number of synonyms that may be provided for a
10327 ** single token.
10328 **
10329 ** In many cases, method (1) above is the best approach. It does not add
10330 ** extra data to the FTS index or require FTS5 to query for multiple terms,
10331 ** so it is efficient in terms of disk space and query speed. However, it
10332 ** does not support prefix queries very well. If, as suggested above, the
10333 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
10334 **
10335 ** <codeblock>
10336 ** ... MATCH '1s*'</codeblock>
10337 **
10338 ** will not match documents that contain the token "1st" (as the tokenizer
10339 ** will probably not map "1s" to any prefix of "first").
10340 **
10341 ** For full prefix support, method (3) may be preferred. In this case,
10342 ** because the index contains entries for both "first" and "1st", prefix
10343 ** queries such as 'fi*' or '1s*' will match correctly. However, because
10344 ** extra entries are added to the FTS index, this method uses more space
10345 ** within the database.
10346 **
10347 ** Method (2) offers a midpoint between (1) and (3). Using this method,
10348 ** a query such as '1s*' will match documents that contain the literal
10349 ** token "1st", but not "first" (assuming the tokenizer is not able to
10350 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
10351 ** will match against "1st" and "first". This method does not require
10352 ** extra disk space, as no extra entries are added to the FTS index.
10353 ** On the other hand, it may require more CPU cycles to run MATCH queries,
10354 ** as separate queries of the FTS index are required for each synonym.
10355 **
10356 ** When using methods (2) or (3), it is important that the tokenizer only
10357 ** provide synonyms when tokenizing document text (method (2)) or query
10358 ** text (method (3)), not both. Doing so will not cause any errors, but is
10359 ** inefficient.
10360 */
10364  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
10365  void (*xDelete)(Fts5Tokenizer*);
10366  int (*xTokenize)(Fts5Tokenizer*,
10367  void *pCtx,
10368  int flags, /* Mask of FTS5_TOKENIZE_* flags */
10369  const char *pText, int nText,
10370  int (*xToken)(
10371  void *pCtx, /* Copy of 2nd argument to xTokenize() */
10372  int tflags, /* Mask of FTS5_TOKEN_* flags */
10373  const char *pToken, /* Pointer to buffer containing token */
10374  int nToken, /* Size of token in bytes */
10375  int iStart, /* Byte offset of token within input text */
10376  int iEnd /* Byte offset of end of token within input text */
10377  )
10378  );
10379 };
10380 
10381 /* Flags that may be passed as the third argument to xTokenize() */
10382 #define FTS5_TOKENIZE_QUERY 0x0001
10383 #define FTS5_TOKENIZE_PREFIX 0x0002
10384 #define FTS5_TOKENIZE_DOCUMENT 0x0004
10385 #define FTS5_TOKENIZE_AUX 0x0008
10386 
10387 /* Flags that may be passed by the tokenizer implementation back to FTS5
10388 ** as the third argument to the supplied xToken callback. */
10389 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
10390 
10391 /*
10392 ** END OF CUSTOM TOKENIZERS
10393 *************************************************************************/
10394 
10395 /*************************************************************************
10396 ** FTS5 EXTENSION REGISTRATION API
10397 */
10398 typedef struct fts5_api fts5_api;
10399 struct fts5_api {
10400  int iVersion; /* Currently always set to 2 */
10401 
10402  /* Create a new tokenizer */
10403  int (*xCreateTokenizer)(
10404  fts5_api *pApi,
10405  const char *zName,
10406  void *pContext,
10407  fts5_tokenizer *pTokenizer,
10408  void (*xDestroy)(void*)
10409  );
10410 
10411  /* Find an existing tokenizer */
10412  int (*xFindTokenizer)(
10413  fts5_api *pApi,
10414  const char *zName,
10415  void **ppContext,
10416  fts5_tokenizer *pTokenizer
10417  );
10418 
10419  /* Create a new auxiliary function */
10420  int (*xCreateFunction)(
10421  fts5_api *pApi,
10422  const char *zName,
10423  void *pContext,
10424  fts5_extension_function xFunction,
10425  void (*xDestroy)(void*)
10426  );
10427 };
10428 
10429 /*
10430 ** END OF REGISTRATION API
10431 *************************************************************************/
10432 
10433 #if 0
10434 } /* end of the 'extern "C"' block */
10435 #endif
10436 
10437 #endif /* _FTS5_H */
10438 
10439 
10440 /******** End of fts5.h *********/
10441 
10442 /************** End of sqlite3.h *********************************************/
10443 /************** Continuing where we left off in sqliteInt.h ******************/
10444 
10445 /*
10446 ** Include the configuration header output by 'configure' if we're using the
10447 ** autoconf-based build
10448 */
10449 #ifdef _HAVE_SQLITE_CONFIG_H
10450 #include "pipeline/resolver.h"
10451 #endif
10452 
10453 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
10454 /************** Begin file sqliteLimit.h *************************************/
10455 /*
10456 ** 2007 May 7
10457 **
10458 ** The author disclaims copyright to this source code. In place of
10459 ** a legal notice, here is a blessing:
10460 **
10461 ** May you do good and not evil.
10462 ** May you find forgiveness for yourself and forgive others.
10463 ** May you share freely, never taking more than you give.
10464 **
10465 *************************************************************************
10466 **
10467 ** This file defines various limits of what SQLite can process.
10468 */
10469 
10470 /*
10471 ** The maximum length of a TEXT or BLOB in bytes. This also
10472 ** limits the size of a row in a table or index.
10473 **
10474 ** The hard limit is the ability of a 32-bit signed integer
10475 ** to count the size: 2^31-1 or 2147483647.
10476 */
10477 #ifndef SQLITE_MAX_LENGTH
10478 # define SQLITE_MAX_LENGTH 1000000000
10479 #endif
10480 
10481 /*
10482 ** This is the maximum number of
10483 **
10484 ** * Columns in a table
10485 ** * Columns in an index
10486 ** * Columns in a view
10487 ** * Terms in the SET clause of an UPDATE statement
10488 ** * Terms in the result set of a SELECT statement
10489 ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
10490 ** * Terms in the VALUES clause of an INSERT statement
10491 **
10492 ** The hard upper limit here is 32676. Most database people will
10493 ** tell you that in a well-normalized database, you usually should
10494 ** not have more than a dozen or so columns in any table. And if
10495 ** that is the case, there is no point in having more than a few
10496 ** dozen values in any of the other situations described above.
10497 */
10498 #ifndef SQLITE_MAX_COLUMN
10499 # define SQLITE_MAX_COLUMN 2000
10500 #endif
10501 
10502 /*
10503 ** The maximum length of a single SQL statement in bytes.
10504 **
10505 ** It used to be the case that setting this value to zero would
10506 ** turn the limit off. That is no longer true. It is not possible
10507 ** to turn this limit off.
10508 */
10509 #ifndef SQLITE_MAX_SQL_LENGTH
10510 # define SQLITE_MAX_SQL_LENGTH 1000000000
10511 #endif
10512 
10513 /*
10514 ** The maximum depth of an expression tree. This is limited to
10515 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
10516 ** want to place more severe limits on the complexity of an
10517 ** expression.
10518 **
10519 ** A value of 0 used to mean that the limit was not enforced.
10520 ** But that is no longer true. The limit is now strictly enforced
10521 ** at all times.
10522 */
10523 #ifndef SQLITE_MAX_EXPR_DEPTH
10524 # define SQLITE_MAX_EXPR_DEPTH 1000
10525 #endif
10526 
10527 /*
10528 ** The maximum number of terms in a compound SELECT statement.
10529 ** The code generator for compound SELECT statements does one
10530 ** level of recursion for each term. A stack overflow can result
10531 ** if the number of terms is too large. In practice, most SQL
10532 ** never has more than 3 or 4 terms. Use a value of 0 to disable
10533 ** any limit on the number of terms in a compount SELECT.
10534 */
10535 #ifndef SQLITE_MAX_COMPOUND_SELECT
10536 # define SQLITE_MAX_COMPOUND_SELECT 500
10537 #endif
10538 
10539 /*
10540 ** The maximum number of opcodes in a VDBE program.
10541 ** Not currently enforced.
10542 */
10543 #ifndef SQLITE_MAX_VDBE_OP
10544 # define SQLITE_MAX_VDBE_OP 25000
10545 #endif
10546 
10547 /*
10548 ** The maximum number of arguments to an SQL function.
10549 */
10550 #ifndef SQLITE_MAX_FUNCTION_ARG
10551 # define SQLITE_MAX_FUNCTION_ARG 127
10552 #endif
10553 
10554 /*
10555 ** The suggested maximum number of in-memory pages to use for
10556 ** the main database table and for temporary tables.
10557 **
10558 ** IMPLEMENTATION-OF: R-30185-15359 The default suggested cache size is -2000,
10559 ** which means the cache size is limited to 2048000 bytes of memory.
10560 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
10561 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
10562 */
10563 #ifndef SQLITE_DEFAULT_CACHE_SIZE
10564 # define SQLITE_DEFAULT_CACHE_SIZE -2000
10565 #endif
10566 
10567 /*
10568 ** The default number of frames to accumulate in the log file before
10569 ** checkpointing the database in WAL mode.
10570 */
10571 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
10572 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
10573 #endif
10574 
10575 /*
10576 ** The maximum number of attached databases. This must be between 0
10577 ** and 125. The upper bound of 125 is because the attached databases are
10578 ** counted using a signed 8-bit integer which has a maximum value of 127
10579 ** and we have to allow 2 extra counts for the "main" and "temp" databases.
10580 */
10581 #ifndef SQLITE_MAX_ATTACHED
10582 # define SQLITE_MAX_ATTACHED 10
10583 #endif
10584 
10585 
10586 /*
10587 ** The maximum value of a ?nnn wildcard that the parser will accept.
10588 */
10589 #ifndef SQLITE_MAX_VARIABLE_NUMBER
10590 # define SQLITE_MAX_VARIABLE_NUMBER 999
10591 #endif
10592 
10593 /* Maximum page size. The upper bound on this value is 65536. This a limit
10594 ** imposed by the use of 16-bit offsets within each page.
10595 **
10596 ** Earlier versions of SQLite allowed the user to change this value at
10597 ** compile time. This is no longer permitted, on the grounds that it creates
10598 ** a library that is technically incompatible with an SQLite library
10599 ** compiled with a different limit. If a process operating on a database
10600 ** with a page-size of 65536 bytes crashes, then an instance of SQLite
10601 ** compiled with the default page-size limit will not be able to rollback
10602 ** the aborted transaction. This could lead to database corruption.
10603 */
10604 #ifdef SQLITE_MAX_PAGE_SIZE
10605 # undef SQLITE_MAX_PAGE_SIZE
10606 #endif
10607 #define SQLITE_MAX_PAGE_SIZE 65536
10608 
10609 
10610 /*
10611 ** The default size of a database page.
10612 */
10613 #ifndef SQLITE_DEFAULT_PAGE_SIZE
10614 # define SQLITE_DEFAULT_PAGE_SIZE 4096
10615 #endif
10616 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10617 # undef SQLITE_DEFAULT_PAGE_SIZE
10618 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10619 #endif
10620 
10621 /*
10622 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
10623 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
10624 ** device characteristics (sector-size and atomic write() support),
10625 ** SQLite may choose a larger value. This constant is the maximum value
10626 ** SQLite will choose on its own.
10627 */
10628 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
10629 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
10630 #endif
10631 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
10632 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
10633 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
10634 #endif
10635 
10636 
10637 /*
10638 ** Maximum number of pages in one database file.
10639 **
10640 ** This is really just the default value for the max_page_count pragma.
10641 ** This value can be lowered (or raised) at run-time using that the
10642 ** max_page_count macro.
10643 */
10644 #ifndef SQLITE_MAX_PAGE_COUNT
10645 # define SQLITE_MAX_PAGE_COUNT 1073741823
10646 #endif
10647 
10648 /*
10649 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
10650 ** operator.
10651 */
10652 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
10653 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
10654 #endif
10655 
10656 /*
10657 ** Maximum depth of recursion for triggers.
10658 **
10659 ** A value of 1 means that a trigger program will not be able to itself
10660 ** fire any triggers. A value of 0 means that no trigger programs at all
10661 ** may be executed.
10662 */
10663 #ifndef SQLITE_MAX_TRIGGER_DEPTH
10664 # define SQLITE_MAX_TRIGGER_DEPTH 1000
10665 #endif
10666 
10667 /************** End of sqliteLimit.h *****************************************/
10668 /************** Continuing where we left off in sqliteInt.h ******************/
10669 
10670 /* Disable nuisance warnings on Borland compilers */
10671 #if defined(__BORLANDC__)
10672 #pragma warn -rch /* unreachable code */
10673 #pragma warn -ccc /* Condition is always true or false */
10674 #pragma warn -aus /* Assigned value is never used */
10675 #pragma warn -csu /* Comparing signed and unsigned */
10676 #pragma warn -spa /* Suspicious pointer arithmetic */
10677 #endif
10678 
10679 /*
10680 ** Include standard header files as necessary
10681 */
10682 #ifdef HAVE_STDINT_H
10683 #include <stdint.h>
10684 #endif
10685 #ifdef HAVE_INTTYPES_H
10686 #include <inttypes.h>
10687 #endif
10688 
10689 /*
10690 ** The following macros are used to cast pointers to integers and
10691 ** integers to pointers. The way you do this varies from one compiler
10692 ** to the next, so we have developed the following set of #if statements
10693 ** to generate appropriate macros for a wide range of compilers.
10694 **
10695 ** The correct "ANSI" way to do this is to use the intptr_t type.
10696 ** Unfortunately, that typedef is not available on all compilers, or
10697 ** if it is available, it requires an #include of specific headers
10698 ** that vary from one machine to the next.
10699 **
10700 ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
10701 ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
10702 ** So we have to define the macros in different ways depending on the
10703 ** compiler.
10704 */
10705 #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
10706 # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
10707 # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
10708 #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
10709 # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
10710 # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
10711 #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
10712 # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
10713 # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
10714 #else /* Generates a warning - but it always works */
10715 # define SQLITE_INT_TO_PTR(X) ((void*)(X))
10716 # define SQLITE_PTR_TO_INT(X) ((int)(X))
10717 #endif
10718 
10719 /*
10720 ** A macro to hint to the compiler that a function should not be
10721 ** inlined.
10722 */
10723 #if defined(__GNUC__)
10724 # define SQLITE_NOINLINE __attribute__((noinline))
10725 #elif defined(_MSC_VER) && _MSC_VER>=1310
10726 # define SQLITE_NOINLINE __declspec(noinline)
10727 #else
10728 # define SQLITE_NOINLINE
10729 #endif
10730 
10731 /*
10732 ** Make sure that the compiler intrinsics we desire are enabled when
10733 ** compiling with an appropriate version of MSVC unless prevented by
10734 ** the SQLITE_DISABLE_INTRINSIC define.
10735 */
10736 #if !defined(SQLITE_DISABLE_INTRINSIC)
10737 # if defined(_MSC_VER) && _MSC_VER>=1300
10738 # if !defined(_WIN32_WCE)
10739 # include <intrin.h>
10740 # pragma intrinsic(_byteswap_ushort)
10741 # pragma intrinsic(_byteswap_ulong)
10742 # pragma intrinsic(_ReadWriteBarrier)
10743 # else
10744 # include <cmnintrin.h>
10745 # endif
10746 # endif
10747 #endif
10748 
10749 /*
10750 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
10751 ** 0 means mutexes are permanently disable and the library is never
10752 ** threadsafe. 1 means the library is serialized which is the highest
10753 ** level of threadsafety. 2 means the library is multithreaded - multiple
10754 ** threads can use SQLite as long as no two threads try to use the same
10755 ** database connection at the same time.
10756 **
10757 ** Older versions of SQLite used an optional THREADSAFE macro.
10758 ** We support that for legacy.
10759 */
10760 #if !defined(SQLITE_THREADSAFE)
10761 # if defined(THREADSAFE)
10762 # define SQLITE_THREADSAFE THREADSAFE
10763 # else
10764 # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
10765 # endif
10766 #endif
10767 
10768 /*
10769 ** Powersafe overwrite is on by default. But can be turned off using
10770 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
10771 */
10772 #ifndef SQLITE_POWERSAFE_OVERWRITE
10773 # define SQLITE_POWERSAFE_OVERWRITE 1
10774 #endif
10775 
10776 /*
10777 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
10778 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
10779 ** which case memory allocation statistics are disabled by default.
10780 */
10781 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
10782 # define SQLITE_DEFAULT_MEMSTATUS 1
10783 #endif
10784 
10785 /*
10786 ** Exactly one of the following macros must be defined in order to
10787 ** specify which memory allocation subsystem to use.
10788 **
10789 ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
10790 ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
10791 ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
10792 ** SQLITE_MEMDEBUG // Debugging version of system malloc()
10793 **
10794 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
10795 ** assert() macro is enabled, each call into the Win32 native heap subsystem
10796 ** will cause HeapValidate to be called. If heap validation should fail, an
10797 ** assertion will be triggered.
10798 **
10799 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
10800 ** the default.
10801 */
10802 #if defined(SQLITE_SYSTEM_MALLOC) \
10803  + defined(SQLITE_WIN32_MALLOC) \
10804  + defined(SQLITE_ZERO_MALLOC) \
10805  + defined(SQLITE_MEMDEBUG)>1
10806 # error "Two or more of the following compile-time configuration options\
10807  are defined but at most one is allowed:\
10808  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
10809  SQLITE_ZERO_MALLOC"
10810 #endif
10811 #if defined(SQLITE_SYSTEM_MALLOC) \
10812  + defined(SQLITE_WIN32_MALLOC) \
10813  + defined(SQLITE_ZERO_MALLOC) \
10814  + defined(SQLITE_MEMDEBUG)==0
10815 # define SQLITE_SYSTEM_MALLOC 1
10816 #endif
10817 
10818 /*
10819 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
10820 ** sizes of memory allocations below this value where possible.
10821 */
10822 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
10823 # define SQLITE_MALLOC_SOFT_LIMIT 1024
10824 #endif
10825 
10826 /*
10827 ** We need to define _XOPEN_SOURCE as follows in order to enable
10828 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
10829 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
10830 ** it.
10831 */
10832 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
10833 # define _XOPEN_SOURCE 600
10834 #endif
10835 
10836 /*
10837 ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
10838 ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
10839 ** make it true by defining or undefining NDEBUG.
10840 **
10841 ** Setting NDEBUG makes the code smaller and faster by disabling the
10842 ** assert() statements in the code. So we want the default action
10843 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
10844 ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
10845 ** feature.
10846 */
10847 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
10848 # define NDEBUG 1
10849 #endif
10850 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
10851 # undef NDEBUG
10852 #endif
10853 
10854 /*
10855 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
10856 */
10857 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
10858 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
10859 #endif
10860 
10861 /*
10862 ** The testcase() macro is used to aid in coverage testing. When
10863 ** doing coverage testing, the condition inside the argument to
10864 ** testcase() must be evaluated both true and false in order to
10865 ** get full branch coverage. The testcase() macro is inserted
10866 ** to help ensure adequate test coverage in places where simple
10867 ** condition/decision coverage is inadequate. For example, testcase()
10868 ** can be used to make sure boundary values are tested. For
10869 ** bitmask tests, testcase() can be used to make sure each bit
10870 ** is significant and used at least once. On switch statements
10871 ** where multiple cases go to the same block of code, testcase()
10872 ** can insure that all cases are evaluated.
10873 **
10874 */
10875 #ifdef SQLITE_COVERAGE_TEST
10876 SQLITE_PRIVATE void sqlite3Coverage(int);
10877 # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
10878 #else
10879 # define testcase(X)
10880 #endif
10881 
10882 /*
10883 ** The TESTONLY macro is used to enclose variable declarations or
10884 ** other bits of code that are needed to support the arguments
10885 ** within testcase() and assert() macros.
10886 */
10887 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
10888 # define TESTONLY(X) X
10889 #else
10890 # define TESTONLY(X)
10891 #endif
10892 
10893 /*
10894 ** Sometimes we need a small amount of code such as a variable initialization
10895 ** to setup for a later assert() statement. We do not want this code to
10896 ** appear when assert() is disabled. The following macro is therefore
10897 ** used to contain that setup code. The "VVA" acronym stands for
10898 ** "Verification, Validation, and Accreditation". In other words, the
10899 ** code within VVA_ONLY() will only run during verification processes.
10900 */
10901 #ifndef NDEBUG
10902 # define VVA_ONLY(X) X
10903 #else
10904 # define VVA_ONLY(X)
10905 #endif
10906 
10907 /*
10908 ** The ALWAYS and NEVER macros surround boolean expressions which
10909 ** are intended to always be true or false, respectively. Such
10910 ** expressions could be omitted from the code completely. But they
10911 ** are included in a few cases in order to enhance the resilience
10912 ** of SQLite to unexpected behavior - to make the code "self-healing"
10913 ** or "ductile" rather than being "brittle" and crashing at the first
10914 ** hint of unplanned behavior.
10915 **
10916 ** In other words, ALWAYS and NEVER are added for defensive code.
10917 **
10918 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
10919 ** be true and false so that the unreachable code they specify will
10920 ** not be counted as untested code.
10921 */
10922 #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
10923 # define ALWAYS(X) (1)
10924 # define NEVER(X) (0)
10925 #elif !defined(NDEBUG)
10926 # define ALWAYS(X) ((X)?1:(assert(0),0))
10927 # define NEVER(X) ((X)?(assert(0),1):0)
10928 #else
10929 # define ALWAYS(X) (X)
10930 # define NEVER(X) (X)
10931 #endif
10932 
10933 /*
10934 ** Some malloc failures are only possible if SQLITE_TEST_REALLOC_STRESS is
10935 ** defined. We need to defend against those failures when testing with
10936 ** SQLITE_TEST_REALLOC_STRESS, but we don't want the unreachable branches
10937 ** during a normal build. The following macro can be used to disable tests
10938 ** that are always false except when SQLITE_TEST_REALLOC_STRESS is set.
10939 */
10940 #if defined(SQLITE_TEST_REALLOC_STRESS)
10941 # define ONLY_IF_REALLOC_STRESS(X) (X)
10942 #elif !defined(NDEBUG)
10943 # define ONLY_IF_REALLOC_STRESS(X) ((X)?(assert(0),1):0)
10944 #else
10945 # define ONLY_IF_REALLOC_STRESS(X) (0)
10946 #endif
10947 
10948 /*
10949 ** Declarations used for tracing the operating system interfaces.
10950 */
10951 #if defined(SQLITE_FORCE_OS_TRACE) || defined(SQLITE_TEST) || \
10952  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
10953  extern int sqlite3OSTrace;
10954 # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
10955 # define SQLITE_HAVE_OS_TRACE
10956 #else
10957 # define OSTRACE(X)
10958 # undef SQLITE_HAVE_OS_TRACE
10959 #endif
10960 
10961 /*
10962 ** Is the sqlite3ErrName() function needed in the build? Currently,
10963 ** it is needed by "mutex_w32.c" (when debugging), "os_win.c" (when
10964 ** OSTRACE is enabled), and by several "test*.c" files (which are
10965 ** compiled using SQLITE_TEST).
10966 */
10967 #if defined(SQLITE_HAVE_OS_TRACE) || defined(SQLITE_TEST) || \
10968  (defined(SQLITE_DEBUG) && SQLITE_OS_WIN)
10969 # define SQLITE_NEED_ERR_NAME
10970 #else
10971 # undef SQLITE_NEED_ERR_NAME
10972 #endif
10973 
10974 /*
10975 ** SQLITE_ENABLE_EXPLAIN_COMMENTS is incompatible with SQLITE_OMIT_EXPLAIN
10976 */
10977 #ifdef SQLITE_OMIT_EXPLAIN
10978 # undef SQLITE_ENABLE_EXPLAIN_COMMENTS
10979 #endif
10980 
10981 /*
10982 ** Return true (non-zero) if the input is an integer that is too large
10983 ** to fit in 32-bits. This macro is used inside of various testcase()
10984 ** macros to verify that we have tested SQLite for large-file support.
10985 */
10986 #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
10987 
10988 /*
10989 ** The macro unlikely() is a hint that surrounds a boolean
10990 ** expression that is usually false. Macro likely() surrounds
10991 ** a boolean expression that is usually true. These hints could,
10992 ** in theory, be used by the compiler to generate better code, but
10993 ** currently they are just comments for human readers.
10994 */
10995 #define likely(X) (X)
10996 #define unlikely(X) (X)
10997 
10998 /************** Include hash.h in the middle of sqliteInt.h ******************/
10999 /************** Begin file hash.h ********************************************/
11000 /*
11001 ** 2001 September 22
11002 **
11003 ** The author disclaims copyright to this source code. In place of
11004 ** a legal notice, here is a blessing:
11005 **
11006 ** May you do good and not evil.
11007 ** May you find forgiveness for yourself and forgive others.
11008 ** May you share freely, never taking more than you give.
11009 **
11010 *************************************************************************
11011 ** This is the header file for the generic hash-table implementation
11012 ** used in SQLite.
11013 */
11014 #ifndef _SQLITE_HASH_H_
11015 #define _SQLITE_HASH_H_
11016 
11017 /* Forward declarations of structures. */
11018 typedef struct Hash Hash;
11019 typedef struct HashElem HashElem;
11020 
11021 /* A complete hash table is an instance of the following structure.
11022 ** The internals of this structure are intended to be opaque -- client
11023 ** code should not attempt to access or modify the fields of this structure
11024 ** directly. Change this structure only by using the routines below.
11025 ** However, some of the "procedures" and "functions" for modifying and
11026 ** accessing this structure are really macros, so we can't really make
11027 ** this structure opaque.
11028 **
11029 ** All elements of the hash table are on a single doubly-linked list.
11030 ** Hash.first points to the head of this list.
11031 **
11032 ** There are Hash.htsize buckets. Each bucket points to a spot in
11033 ** the global doubly-linked list. The contents of the bucket are the
11034 ** element pointed to plus the next _ht.count-1 elements in the list.
11035 **
11036 ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
11037 ** by a linear search of the global list. For small tables, the
11038 ** Hash.ht table is never allocated because if there are few elements
11039 ** in the table, it is faster to do a linear search than to manage
11040 ** the hash table.
11041 */
11042 struct Hash {
11043  unsigned int htsize; /* Number of buckets in the hash table */
11044  unsigned int count; /* Number of entries in this table */
11045  HashElem *first; /* The first element of the array */
11046  struct _ht { /* the hash table */
11047  int count; /* Number of entries with this hash */
11048  HashElem *chain; /* Pointer to first entry with this hash */
11049  } *ht;
11050 };
11051 
11052 /* Each element in the hash table is an instance of the following
11053 ** structure. All elements are stored on a single doubly-linked list.
11054 **
11055 ** Again, this structure is intended to be opaque, but it can't really
11056 ** be opaque because it is used by macros.
11057 */
11058 struct HashElem {
11059  HashElem *next, *prev; /* Next and previous elements in the table */
11060  void *data; /* Data associated with this element */
11061  const char *pKey; /* Key associated with this element */
11062 };
11063 
11064 /*
11065 ** Access routines. To delete, insert a NULL pointer.
11066 */
11068 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
11069 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
11071 
11072 /*
11073 ** Macros for looping over all elements of a hash table. The idiom is
11074 ** like this:
11075 **
11076 ** Hash h;
11077 ** HashElem *p;
11078 ** ...
11079 ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
11080 ** SomeStructure *pData = sqliteHashData(p);
11081 ** // do something with pData
11082 ** }
11083 */
11084 #define sqliteHashFirst(H) ((H)->first)
11085 #define sqliteHashNext(E) ((E)->next)
11086 #define sqliteHashData(E) ((E)->data)
11087 /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
11088 /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
11089 
11090 /*
11091 ** Number of entries in a hash table
11092 */
11093 /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
11094 
11095 #endif /* _SQLITE_HASH_H_ */
11096 
11097 /************** End of hash.h ************************************************/
11098 /************** Continuing where we left off in sqliteInt.h ******************/
11099 /************** Include parse.h in the middle of sqliteInt.h *****************/
11100 /************** Begin file parse.h *******************************************/
11101 #define TK_SEMI 1
11102 #define TK_EXPLAIN 2
11103 #define TK_QUERY 3
11104 #define TK_PLAN 4
11105 #define TK_BEGIN 5
11106 #define TK_TRANSACTION 6
11107 #define TK_DEFERRED 7
11108 #define TK_IMMEDIATE 8
11109 #define TK_EXCLUSIVE 9
11110 #define TK_COMMIT 10
11111 #define TK_END 11
11112 #define TK_ROLLBACK 12
11113 #define TK_SAVEPOINT 13
11114 #define TK_RELEASE 14
11115 #define TK_TO 15
11116 #define TK_TABLE 16
11117 #define TK_CREATE 17
11118 #define TK_IF 18
11119 #define TK_NOT 19
11120 #define TK_EXISTS 20
11121 #define TK_TEMP 21
11122 #define TK_LP 22
11123 #define TK_RP 23
11124 #define TK_AS 24
11125 #define TK_WITHOUT 25
11126 #define TK_COMMA 26
11127 #define TK_OR 27
11128 #define TK_AND 28
11129 #define TK_IS 29
11130 #define TK_MATCH 30
11131 #define TK_LIKE_KW 31
11132 #define TK_BETWEEN 32
11133 #define TK_IN 33
11134 #define TK_ISNULL 34
11135 #define TK_NOTNULL 35
11136 #define TK_NE 36
11137 #define TK_EQ 37
11138 #define TK_GT 38
11139 #define TK_LE 39
11140 #define TK_LT 40
11141 #define TK_GE 41
11142 #define TK_ESCAPE 42
11143 #define TK_BITAND 43
11144 #define TK_BITOR 44
11145 #define TK_LSHIFT 45
11146 #define TK_RSHIFT 46
11147 #define TK_PLUS 47
11148 #define TK_MINUS 48
11149 #define TK_STAR 49
11150 #define TK_SLASH 50
11151 #define TK_REM 51
11152 #define TK_CONCAT 52
11153 #define TK_COLLATE 53
11154 #define TK_BITNOT 54
11155 #define TK_ID 55
11156 #define TK_INDEXED 56
11157 #define TK_ABORT 57
11158 #define TK_ACTION 58
11159 #define TK_AFTER 59
11160 #define TK_ANALYZE 60
11161 #define TK_ASC 61
11162 #define TK_ATTACH 62
11163 #define TK_BEFORE 63
11164 #define TK_BY 64
11165 #define TK_CASCADE 65
11166 #define TK_CAST 66
11167 #define TK_COLUMNKW 67
11168 #define TK_CONFLICT 68
11169 #define TK_DATABASE 69
11170 #define TK_DESC 70
11171 #define TK_DETACH 71
11172 #define TK_EACH 72
11173 #define TK_FAIL 73
11174 #define TK_FOR 74
11175 #define TK_IGNORE 75
11176 #define TK_INITIALLY 76
11177 #define TK_INSTEAD 77
11178 #define TK_NO 78
11179 #define TK_KEY 79
11180 #define TK_OF 80
11181 #define TK_OFFSET 81
11182 #define TK_PRAGMA 82
11183 #define TK_RAISE 83
11184 #define TK_RECURSIVE 84
11185 #define TK_REPLACE 85
11186 #define TK_RESTRICT 86
11187 #define TK_ROW 87
11188 #define TK_TRIGGER 88
11189 #define TK_VACUUM 89
11190 #define TK_VIEW 90
11191 #define TK_VIRTUAL 91
11192 #define TK_WITH 92
11193 #define TK_REINDEX 93
11194 #define TK_RENAME 94
11195 #define TK_CTIME_KW 95
11196 #define TK_ANY 96
11197 #define TK_STRING 97
11198 #define TK_JOIN_KW 98
11199 #define TK_CONSTRAINT 99
11200 #define TK_DEFAULT 100
11201 #define TK_NULL 101
11202 #define TK_PRIMARY 102
11203 #define TK_UNIQUE 103
11204 #define TK_CHECK 104
11205 #define TK_REFERENCES 105
11206 #define TK_AUTOINCR 106
11207 #define TK_ON 107
11208 #define TK_INSERT 108
11209 #define TK_DELETE 109
11210 #define TK_UPDATE 110
11211 #define TK_SET 111
11212 #define TK_DEFERRABLE 112
11213 #define TK_FOREIGN 113
11214 #define TK_DROP 114
11215 #define TK_UNION 115
11216 #define TK_ALL 116
11217 #define TK_EXCEPT 117
11218 #define TK_INTERSECT 118
11219 #define TK_SELECT 119
11220 #define TK_VALUES 120
11221 #define TK_DISTINCT 121
11222 #define TK_DOT 122
11223 #define TK_FROM 123
11224 #define TK_JOIN 124
11225 #define TK_USING 125
11226 #define TK_ORDER 126
11227 #define TK_GROUP 127
11228 #define TK_HAVING 128
11229 #define TK_LIMIT 129
11230 #define TK_WHERE 130
11231 #define TK_INTO 131
11232 #define TK_INTEGER 132
11233 #define TK_FLOAT 133
11234 #define TK_BLOB 134
11235 #define TK_VARIABLE 135
11236 #define TK_CASE 136
11237 #define TK_WHEN 137
11238 #define TK_THEN 138
11239 #define TK_ELSE 139
11240 #define TK_INDEX 140
11241 #define TK_ALTER 141
11242 #define TK_ADD 142
11243 #define TK_TO_TEXT 143
11244 #define TK_TO_BLOB 144
11245 #define TK_TO_NUMERIC 145
11246 #define TK_TO_INT 146
11247 #define TK_TO_REAL 147
11248 #define TK_ISNOT 148
11249 #define TK_END_OF_FILE 149
11250 #define TK_UNCLOSED_STRING 150
11251 #define TK_FUNCTION 151
11252 #define TK_COLUMN 152
11253 #define TK_AGG_FUNCTION 153
11254 #define TK_AGG_COLUMN 154
11255 #define TK_UMINUS 155
11256 #define TK_UPLUS 156
11257 #define TK_REGISTER 157
11258 #define TK_ASTERISK 158
11259 #define TK_SPAN 159
11260 #define TK_SPACE 160
11261 #define TK_ILLEGAL 161
11262 
11263 /* The token codes above must all fit in 8 bits */
11264 #define TKFLG_MASK 0xff
11265 
11266 /* Flags that can be added to a token code when it is not
11267 ** being stored in a u8: */
11268 #define TKFLG_DONTFOLD 0x100 /* Omit constant folding optimizations */
11269 
11270 /************** End of parse.h ***********************************************/
11271 /************** Continuing where we left off in sqliteInt.h ******************/
11272 #include <stdio.h>
11273 #include <stdlib.h>
11274 #include <string.h>
11275 #include <assert.h>
11276 #include <stddef.h>
11277 
11278 /*
11279 ** If compiling for a processor that lacks floating point support,
11280 ** substitute integer for floating-point
11281 */
11282 #ifdef SQLITE_OMIT_FLOATING_POINT
11283 # define double sqlite_int64
11284 # define float sqlite_int64
11285 # define LONGDOUBLE_TYPE sqlite_int64
11286 # ifndef SQLITE_BIG_DBL
11287 # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
11288 # endif
11289 # define SQLITE_OMIT_DATETIME_FUNCS 1
11290 # define SQLITE_OMIT_TRACE 1
11291 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11292 # undef SQLITE_HAVE_ISNAN
11293 #endif
11294 #ifndef SQLITE_BIG_DBL
11295 # define SQLITE_BIG_DBL (1e99)
11296 #endif
11297 
11298 /*
11299 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
11300 ** afterward. Having this macro allows us to cause the C compiler
11301 ** to omit code used by TEMP tables without messy #ifndef statements.
11302 */
11303 #ifdef SQLITE_OMIT_TEMPDB
11304 #define OMIT_TEMPDB 1
11305 #else
11306 #define OMIT_TEMPDB 0
11307 #endif
11308 
11309 /*
11310 ** The "file format" number is an integer that is incremented whenever
11311 ** the VDBE-level file format changes. The following macros define the
11312 ** the default file format for new databases and the maximum file format
11313 ** that the library can read.
11314 */
11315 #define SQLITE_MAX_FILE_FORMAT 4
11316 #ifndef SQLITE_DEFAULT_FILE_FORMAT
11317 # define SQLITE_DEFAULT_FILE_FORMAT 4
11318 #endif
11319 
11320 /*
11321 ** Determine whether triggers are recursive by default. This can be
11322 ** changed at run-time using a pragma.
11323 */
11324 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
11325 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
11326 #endif
11327 
11328 /*
11329 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
11330 ** on the command-line
11331 */
11332 #ifndef SQLITE_TEMP_STORE
11333 # define SQLITE_TEMP_STORE 1
11334 # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
11335 #endif
11336 
11337 /*
11338 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
11339 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
11340 ** to zero.
11341 */
11342 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
11343 # undef SQLITE_MAX_WORKER_THREADS
11344 # define SQLITE_MAX_WORKER_THREADS 0
11345 #endif
11346 #ifndef SQLITE_MAX_WORKER_THREADS
11347 # define SQLITE_MAX_WORKER_THREADS 8
11348 #endif
11349 #ifndef SQLITE_DEFAULT_WORKER_THREADS
11350 # define SQLITE_DEFAULT_WORKER_THREADS 0
11351 #endif
11352 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
11353 # undef SQLITE_MAX_WORKER_THREADS
11354 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
11355 #endif
11356 
11357 /*
11358 ** The default initial allocation for the pagecache when using separate
11359 ** pagecaches for each database connection. A positive number is the
11360 ** number of pages. A negative number N translations means that a buffer
11361 ** of -1024*N bytes is allocated and used for as many pages as it will hold.
11362 */
11363 #ifndef SQLITE_DEFAULT_PCACHE_INITSZ
11364 # define SQLITE_DEFAULT_PCACHE_INITSZ 100
11365 #endif
11366 
11367 /*
11368 ** GCC does not define the offsetof() macro so we'll have to do it
11369 ** ourselves.
11370 */
11371 #ifndef offsetof
11372 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
11373 #endif
11374 
11375 /*
11376 ** Macros to compute minimum and maximum of two numbers.
11377 */
11378 #ifndef MIN
11379 # define MIN(A,B) ((A)<(B)?(A):(B))
11380 #endif
11381 #ifndef MAX
11382 # define MAX(A,B) ((A)>(B)?(A):(B))
11383 #endif
11384 
11385 /*
11386 ** Swap two objects of type TYPE.
11387 */
11388 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
11389 
11390 /*
11391 ** Check to see if this machine uses EBCDIC. (Yes, believe it or
11392 ** not, there are still machines out there that use EBCDIC.)
11393 */
11394 #if 'A' == '\301'
11395 # define SQLITE_EBCDIC 1
11396 #else
11397 # define SQLITE_ASCII 1
11398 #endif
11399 
11400 /*
11401 ** Integers of known sizes. These typedefs might change for architectures
11402 ** where the sizes very. Preprocessor macros are available so that the
11403 ** types can be conveniently redefined at compile-type. Like this:
11404 **
11405 ** cc '-DUINTPTR_TYPE=long long int' ...
11406 */
11407 #ifndef UINT32_TYPE
11408 # ifdef HAVE_UINT32_T
11409 # define UINT32_TYPE uint32_t
11410 # else
11411 # define UINT32_TYPE unsigned int
11412 # endif
11413 #endif
11414 #ifndef UINT16_TYPE
11415 # ifdef HAVE_UINT16_T
11416 # define UINT16_TYPE uint16_t
11417 # else
11418 # define UINT16_TYPE unsigned short int
11419 # endif
11420 #endif
11421 #ifndef INT16_TYPE
11422 # ifdef HAVE_INT16_T
11423 # define INT16_TYPE int16_t
11424 # else
11425 # define INT16_TYPE short int
11426 # endif
11427 #endif
11428 #ifndef UINT8_TYPE
11429 # ifdef HAVE_UINT8_T
11430 # define UINT8_TYPE uint8_t
11431 # else
11432 # define UINT8_TYPE unsigned char
11433 # endif
11434 #endif
11435 #ifndef INT8_TYPE
11436 # ifdef HAVE_INT8_T
11437 # define INT8_TYPE int8_t
11438 # else
11439 # define INT8_TYPE signed char
11440 # endif
11441 #endif
11442 #ifndef LONGDOUBLE_TYPE
11443 # define LONGDOUBLE_TYPE long double
11444 #endif
11445 typedef sqlite_int64 i64; /* 8-byte signed integer */
11446 typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
11447 typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
11448 typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
11449 typedef INT16_TYPE i16; /* 2-byte signed integer */
11450 typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
11451 typedef INT8_TYPE i8; /* 1-byte signed integer */
11452 
11453 /*
11454 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
11455 ** that can be stored in a u32 without loss of data. The value
11456 ** is 0x00000000ffffffff. But because of quirks of some compilers, we
11457 ** have to specify the value in the less intuitive manner shown:
11458 */
11459 #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
11460 
11461 /*
11462 ** The datatype used to store estimates of the number of rows in a
11463 ** table or index. This is an unsigned integer type. For 99.9% of
11464 ** the world, a 32-bit integer is sufficient. But a 64-bit integer
11465 ** can be used at compile-time if desired.
11466 */
11467 #ifdef SQLITE_64BIT_STATS
11468  typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
11469 #else
11470  typedef u32 tRowcnt; /* 32-bit is the default */
11471 #endif
11472 
11473 /*
11474 ** Estimated quantities used for query planning are stored as 16-bit
11475 ** logarithms. For quantity X, the value stored is 10*log2(X). This
11476 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
11477 ** But the allowed values are "grainy". Not every value is representable.
11478 ** For example, quantities 16 and 17 are both represented by a LogEst
11479 ** of 40. However, since LogEst quantities are suppose to be estimates,
11480 ** not exact values, this imprecision is not a problem.
11481 **
11482 ** "LogEst" is short for "Logarithmic Estimate".
11483 **
11484 ** Examples:
11485 ** 1 -> 0 20 -> 43 10000 -> 132
11486 ** 2 -> 10 25 -> 46 25000 -> 146
11487 ** 3 -> 16 100 -> 66 1000000 -> 199
11488 ** 4 -> 20 1000 -> 99 1048576 -> 200
11489 ** 10 -> 33 1024 -> 100 4294967296 -> 320
11490 **
11491 ** The LogEst can be negative to indicate fractional values.
11492 ** Examples:
11493 **
11494 ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
11495 */
11497 
11498 /*
11499 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
11500 */
11501 #ifndef SQLITE_PTRSIZE
11502 # if defined(__SIZEOF_POINTER__)
11503 # define SQLITE_PTRSIZE __SIZEOF_POINTER__
11504 # elif defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11505  defined(_M_ARM) || defined(__arm__) || defined(__x86)
11506 # define SQLITE_PTRSIZE 4
11507 # else
11508 # define SQLITE_PTRSIZE 8
11509 # endif
11510 #endif
11511 
11512 /* The uptr type is an unsigned integer large enough to hold a pointer
11513 */
11514 #if defined(HAVE_STDINT_H)
11515  typedef uintptr_t uptr;
11516 #elif SQLITE_PTRSIZE==4
11517  typedef u32 uptr;
11518 #else
11519  typedef u64 uptr;
11520 #endif
11521 
11522 /*
11523 ** The SQLITE_WITHIN(P,S,E) macro checks to see if pointer P points to
11524 ** something between S (inclusive) and E (exclusive).
11525 **
11526 ** In other words, S is a buffer and E is a pointer to the first byte after
11527 ** the end of buffer S. This macro returns true if P points to something
11528 ** contained within the buffer S.
11529 */
11530 #define SQLITE_WITHIN(P,S,E) (((uptr)(P)>=(uptr)(S))&&((uptr)(P)<(uptr)(E)))
11531 
11532 
11533 /*
11534 ** Macros to determine whether the machine is big or little endian,
11535 ** and whether or not that determination is run-time or compile-time.
11536 **
11537 ** For best performance, an attempt is made to guess at the byte-order
11538 ** using C-preprocessor macros. If that is unsuccessful, or if
11539 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
11540 ** at run-time.
11541 */
11542 #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
11543  defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
11544  defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
11545  defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
11546 # define SQLITE_BYTEORDER 1234
11547 # define SQLITE_BIGENDIAN 0
11548 # define SQLITE_LITTLEENDIAN 1
11549 # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
11550 #endif
11551 #if (defined(sparc) || defined(__ppc__)) \
11552  && !defined(SQLITE_RUNTIME_BYTEORDER)
11553 # define SQLITE_BYTEORDER 4321
11554 # define SQLITE_BIGENDIAN 1
11555 # define SQLITE_LITTLEENDIAN 0
11556 # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
11557 #endif
11558 #if !defined(SQLITE_BYTEORDER)
11559 # ifdef SQLITE_AMALGAMATION
11560  const int sqlite3one = 1;
11561 # else
11562  extern const int sqlite3one;
11563 # endif
11564 # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
11565 # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
11566 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
11567 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
11568 #endif
11569 
11570 /*
11571 ** Constants for the largest and smallest possible 64-bit signed integers.
11572 ** These macros are designed to work correctly on both 32-bit and 64-bit
11573 ** compilers.
11574 */
11575 #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
11576 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
11577 
11578 /*
11579 ** Round up a number to the next larger multiple of 8. This is used
11580 ** to force 8-byte alignment on 64-bit architectures.
11581 */
11582 #define ROUND8(x) (((x)+7)&~7)
11583 
11584 /*
11585 ** Round down to the nearest multiple of 8
11586 */
11587 #define ROUNDDOWN8(x) ((x)&~7)
11588 
11589 /*
11590 ** Assert that the pointer X is aligned to an 8-byte boundary. This
11591 ** macro is used only within assert() to verify that the code gets
11592 ** all alignment restrictions correct.
11593 **
11594 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
11595 ** underlying malloc() implementation might return us 4-byte aligned
11596 ** pointers. In that case, only verify 4-byte alignment.
11597 */
11598 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
11599 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
11600 #else
11601 # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
11602 #endif
11603 
11604 /*
11605 ** Disable MMAP on platforms where it is known to not work
11606 */
11607 #if defined(__OpenBSD__) || defined(__QNXNTO__)
11608 # undef SQLITE_MAX_MMAP_SIZE
11609 # define SQLITE_MAX_MMAP_SIZE 0
11610 #endif
11611 
11612 /*
11613 ** Default maximum size of memory used by memory-mapped I/O in the VFS
11614 */
11615 #ifdef __APPLE__
11616 # include <TargetConditionals.h>
11617 #endif
11618 #ifndef SQLITE_MAX_MMAP_SIZE
11619 # if defined(__linux__) \
11620  || defined(_WIN32) \
11621  || (defined(__APPLE__) && defined(__MACH__)) \
11622  || defined(__sun) \
11623  || defined(__FreeBSD__) \
11624  || defined(__DragonFly__)
11625 # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
11626 # else
11627 # define SQLITE_MAX_MMAP_SIZE 0
11628 # endif
11629 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
11630 #endif
11631 
11632 /*
11633 ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
11634 ** default MMAP_SIZE is specified at compile-time, make sure that it does
11635 ** not exceed the maximum mmap size.
11636 */
11637 #ifndef SQLITE_DEFAULT_MMAP_SIZE
11638 # define SQLITE_DEFAULT_MMAP_SIZE 0
11639 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
11640 #endif
11641 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
11642 # undef SQLITE_DEFAULT_MMAP_SIZE
11643 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
11644 #endif
11645 
11646 /*
11647 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
11648 ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
11649 ** define SQLITE_ENABLE_STAT3_OR_STAT4
11650 */
11651 #ifdef SQLITE_ENABLE_STAT4
11652 # undef SQLITE_ENABLE_STAT3
11653 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11654 #elif SQLITE_ENABLE_STAT3
11655 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
11656 #elif SQLITE_ENABLE_STAT3_OR_STAT4
11657 # undef SQLITE_ENABLE_STAT3_OR_STAT4
11658 #endif
11659 
11660 /*
11661 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
11662 ** the Select query generator tracing logic is turned on.
11663 */
11664 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
11665 # define SELECTTRACE_ENABLED 1
11666 #else
11667 # define SELECTTRACE_ENABLED 0
11668 #endif
11669 
11670 /*
11671 ** An instance of the following structure is used to store the busy-handler
11672 ** callback for a given sqlite handle.
11673 **
11674 ** The sqlite.busyHandler member of the sqlite struct contains the busy
11675 ** callback for the database handle. Each pager opened via the sqlite
11676 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
11677 ** callback is currently invoked only from within pager.c.
11678 */
11679 typedef struct BusyHandler BusyHandler;
11680 struct BusyHandler {
11681  int (*xFunc)(void *,int); /* The busy callback */
11682  void *pArg; /* First arg to busy callback */
11683  int nBusy; /* Incremented with each busy call */
11684 };
11685 
11686 /*
11687 ** Name of the master database table. The master database table
11688 ** is a special table that holds the names and attributes of all
11689 ** user tables and indices.
11690 */
11691 #define MASTER_NAME "sqlite_master"
11692 #define TEMP_MASTER_NAME "sqlite_temp_master"
11693 
11694 /*
11695 ** The root-page of the master database table.
11696 */
11697 #define MASTER_ROOT 1
11698 
11699 /*
11700 ** The name of the schema table.
11701 */
11702 #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
11703 
11704 /*
11705 ** A convenience macro that returns the number of elements in
11706 ** an array.
11707 */
11708 #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
11709 
11710 /*
11711 ** Determine if the argument is a power of two
11712 */
11713 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
11714 
11715 /*
11716 ** The following value as a destructor means to use sqlite3DbFree().
11717 ** The sqlite3DbFree() routine requires two parameters instead of the
11718 ** one parameter that destructors normally want. So we have to introduce
11719 ** this magic value that the code knows to handle differently. Any
11720 ** pointer will work here as long as it is distinct from SQLITE_STATIC
11721 ** and SQLITE_TRANSIENT.
11722 */
11723 #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
11724 
11725 /*
11726 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
11727 ** not support Writable Static Data (WSD) such as global and static variables.
11728 ** All variables must either be on the stack or dynamically allocated from
11729 ** the heap. When WSD is unsupported, the variable declarations scattered
11730 ** throughout the SQLite code must become constants instead. The SQLITE_WSD
11731 ** macro is used for this purpose. And instead of referencing the variable
11732 ** directly, we use its constant as a key to lookup the run-time allocated
11733 ** buffer that holds real variable. The constant is also the initializer
11734 ** for the run-time allocated buffer.
11735 **
11736 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
11737 ** macros become no-ops and have zero performance impact.
11738 */
11739 #ifdef SQLITE_OMIT_WSD
11740  #define SQLITE_WSD const
11741  #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
11742  #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
11743 SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
11744 SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
11745 #else
11746  #define SQLITE_WSD
11747  #define GLOBAL(t,v) v
11748  #define sqlite3GlobalConfig sqlite3Config
11749 #endif
11750 
11751 /*
11752 ** The following macros are used to suppress compiler warnings and to
11753 ** make it clear to human readers when a function parameter is deliberately
11754 ** left unused within the body of a function. This usually happens when
11755 ** a function is called via a function pointer. For example the
11756 ** implementation of an SQL aggregate step callback may not use the
11757 ** parameter indicating the number of arguments passed to the aggregate,
11758 ** if it knows that this is enforced elsewhere.
11759 **
11760 ** When a function parameter is not used at all within the body of a function,
11761 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
11762 ** However, these macros may also be used to suppress warnings related to
11763 ** parameters that may or may not be used depending on compilation options.
11764 ** For example those parameters only used in assert() statements. In these
11765 ** cases the parameters are named as per the usual conventions.
11766 */
11767 #define UNUSED_PARAMETER(x) (void)(x)
11768 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
11769 
11770 /*
11771 ** Forward references to structures
11772 */
11773 typedef struct AggInfo AggInfo;
11774 typedef struct AuthContext AuthContext;
11775 typedef struct AutoincInfo AutoincInfo;
11776 typedef struct Bitvec Bitvec;
11777 typedef struct CollSeq CollSeq;
11778 typedef struct Column Column;
11779 typedef struct Db Db;
11780 typedef struct Schema Schema;
11781 typedef struct Expr Expr;
11782 typedef struct ExprList ExprList;
11783 typedef struct ExprSpan ExprSpan;
11784 typedef struct FKey FKey;
11786 typedef struct FuncDef FuncDef;
11787 typedef struct FuncDefHash FuncDefHash;
11788 typedef struct IdList IdList;
11789 typedef struct Index Index;
11790 typedef struct IndexSample IndexSample;
11791 typedef struct KeyClass KeyClass;
11792 typedef struct KeyInfo KeyInfo;
11793 typedef struct Lookaside Lookaside;
11795 typedef struct Module Module;
11796 typedef struct NameContext NameContext;
11797 typedef struct Parse Parse;
11798 typedef struct PreUpdate PreUpdate;
11800 typedef struct RowSet RowSet;
11801 typedef struct Savepoint Savepoint;
11802 typedef struct Select Select;
11804 typedef struct SelectDest SelectDest;
11805 typedef struct SrcList SrcList;
11806 typedef struct StrAccum StrAccum;
11807 typedef struct Table Table;
11808 typedef struct TableLock TableLock;
11809 typedef struct Token Token;
11810 typedef struct TreeView TreeView;
11811 typedef struct Trigger Trigger;
11812 typedef struct TriggerPrg TriggerPrg;
11813 typedef struct TriggerStep TriggerStep;
11815 typedef struct VTable VTable;
11816 typedef struct VtabCtx VtabCtx;
11817 typedef struct Walker Walker;
11818 typedef struct WhereInfo WhereInfo;
11819 typedef struct With With;
11820 
11821 /*
11822 ** Defer sourcing vdbe.h and btree.h until after the "u8" and
11823 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
11824 ** pointer types (i.e. FuncDef) defined above.
11825 */
11826 /************** Include btree.h in the middle of sqliteInt.h *****************/
11827 /************** Begin file btree.h *******************************************/
11828 /*
11829 ** 2001 September 15
11830 **
11831 ** The author disclaims copyright to this source code. In place of
11832 ** a legal notice, here is a blessing:
11833 **
11834 ** May you do good and not evil.
11835 ** May you find forgiveness for yourself and forgive others.
11836 ** May you share freely, never taking more than you give.
11837 **
11838 *************************************************************************
11839 ** This header file defines the interface that the sqlite B-Tree file
11840 ** subsystem. See comments in the source code for a detailed description
11841 ** of what each interface routine does.
11842 */
11843 #ifndef _BTREE_H_
11844 #define _BTREE_H_
11845 
11846 /* TODO: This definition is just included so other modules compile. It
11847 ** needs to be revisited.
11848 */
11849 #define SQLITE_N_BTREE_META 16
11850 
11851 /*
11852 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
11853 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
11854 */
11855 #ifndef SQLITE_DEFAULT_AUTOVACUUM
11856  #define SQLITE_DEFAULT_AUTOVACUUM 0
11857 #endif
11858 
11859 #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
11860 #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
11861 #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
11862 
11863 /*
11864 ** Forward declarations of structure
11865 */
11866 typedef struct Btree Btree;
11867 typedef struct BtCursor BtCursor;
11868 typedef struct BtShared BtShared;
11869 
11870 
11872  sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
11873  const char *zFilename, /* Name of database file to open */
11874  sqlite3 *db, /* Associated database connection */
11875  Btree **ppBtree, /* Return open Btree* here */
11876  int flags, /* Flags */
11877  int vfsFlags /* Flags passed through to VFS open */
11878 );
11879 
11880 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
11881 ** following values.
11882 **
11883 ** NOTE: These values must match the corresponding PAGER_ values in
11884 ** pager.h.
11885 */
11886 #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
11887 #define BTREE_MEMORY 2 /* This is an in-memory DB */
11888 #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
11889 #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
11890 
11894 #if SQLITE_MAX_MMAP_SIZE>0
11895 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
11896 #endif
11898 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
11908 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
11913 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
11917 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
11919 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
11920 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
11921 
11925 
11927 
11928 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
11929 ** of the flags shown below.
11930 **
11931 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
11932 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
11933 ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
11934 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
11935 ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
11936 ** indices.)
11937 */
11938 #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
11939 #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
11940 
11941 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
11945 
11946 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
11948 
11950 
11951 /*
11952 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
11953 ** should be one of the following values. The integer values are assigned
11954 ** to constants so that the offset of the corresponding field in an
11955 ** SQLite database header may be found using the following formula:
11956 **
11957 ** offset = 36 + (idx * 4)
11958 **
11959 ** For example, the free-page-count field is located at byte offset 36 of
11960 ** the database file header. The incr-vacuum-flag field is located at
11961 ** byte offset 64 (== 36+4*7).
11962 **
11963 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
11964 ** It is a read-only number computed by the pager. But we merge it with
11965 ** the header value access routines since its access pattern is the same.
11966 ** Call it a "virtual meta value".
11967 */
11968 #define BTREE_FREE_PAGE_COUNT 0
11969 #define BTREE_SCHEMA_VERSION 1
11970 #define BTREE_FILE_FORMAT 2
11971 #define BTREE_DEFAULT_CACHE_SIZE 3
11972 #define BTREE_LARGEST_ROOT_PAGE 4
11973 #define BTREE_TEXT_ENCODING 5
11974 #define BTREE_USER_VERSION 6
11975 #define BTREE_INCR_VACUUM 7
11976 #define BTREE_APPLICATION_ID 8
11977 #define BTREE_DATA_VERSION 15 /* A virtual meta-value */
11978 
11979 /*
11980 ** Kinds of hints that can be passed into the sqlite3BtreeCursorHint()
11981 ** interface.
11982 **
11983 ** BTREE_HINT_RANGE (arguments: Expr*, Mem*)
11984 **
11985 ** The first argument is an Expr* (which is guaranteed to be constant for
11986 ** the lifetime of the cursor) that defines constraints on which rows
11987 ** might be fetched with this cursor. The Expr* tree may contain
11988 ** TK_REGISTER nodes that refer to values stored in the array of registers
11989 ** passed as the second parameter. In other words, if Expr.op==TK_REGISTER
11990 ** then the value of the node is the value in Mem[pExpr.iTable]. Any
11991 ** TK_COLUMN node in the expression tree refers to the Expr.iColumn-th
11992 ** column of the b-tree of the cursor. The Expr tree will not contain
11993 ** any function calls nor subqueries nor references to b-trees other than
11994 ** the cursor being hinted.
11995 **
11996 ** The design of the _RANGE hint is aid b-tree implementations that try
11997 ** to prefetch content from remote machines - to provide those
11998 ** implementations with limits on what needs to be prefetched and thereby
11999 ** reduce network bandwidth.
12000 **
12001 ** Note that BTREE_HINT_FLAGS with BTREE_BULKLOAD is the only hint used by
12002 ** standard SQLite. The other hints are provided for extentions that use
12003 ** the SQLite parser and code generator but substitute their own storage
12004 ** engine.
12005 */
12006 #define BTREE_HINT_RANGE 0 /* Range constraints on queries */
12007 
12008 /*
12009 ** Values that may be OR'd together to form the argument to the
12010 ** BTREE_HINT_FLAGS hint for sqlite3BtreeCursorHint():
12011 **
12012 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
12013 ** to be filled with content that is already in sorted order.
12014 **
12015 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
12016 ** OP_SeekLE opcodes for a range search, but where the range of entries
12017 ** selected will all have the same key. In other words, the cursor will
12018 ** be used only for equality key searches.
12019 **
12020 */
12021 #define BTREE_BULKLOAD 0x00000001 /* Used to full index in sorted order */
12022 #define BTREE_SEEK_EQ 0x00000002 /* EQ seeks only - no range seeks */
12023 
12024 /*
12025 ** Flags passed as the third argument to sqlite3BtreeCursor().
12026 **
12027 ** For read-only cursors the wrFlag argument is always zero. For read-write
12028 ** cursors it may be set to either (BTREE_WRCSR|BTREE_FORDELETE) or just
12029 ** (BTREE_WRCSR). If the BTREE_FORDELETE bit is set, then the cursor will
12030 ** only be used by SQLite for the following:
12031 **
12032 ** * to seek to and then delete specific entries, and/or
12033 **
12034 ** * to read values that will be used to create keys that other
12035 ** BTREE_FORDELETE cursors will seek to and delete.
12036 **
12037 ** The BTREE_FORDELETE flag is an optimization hint. It is not used by
12038 ** by this, the native b-tree engine of SQLite, but it is available to
12039 ** alternative storage engines that might be substituted in place of this
12040 ** b-tree system. For alternative storage engines in which a delete of
12041 ** the main table row automatically deletes corresponding index rows,
12042 ** the FORDELETE flag hint allows those alternative storage engines to
12043 ** skip a lot of work. Namely: FORDELETE cursors may treat all SEEK
12044 ** and DELETE operations as no-ops, and any READ operation against a
12045 ** FORDELETE cursor may return a null row: 0x01 0x00.
12046 */
12047 #define BTREE_WRCSR 0x00000004 /* read-write cursor */
12048 #define BTREE_FORDELETE 0x00000008 /* Cursor is for seek/delete only */
12049 
12051  Btree*, /* BTree containing table to open */
12052  int iTable, /* Index of root page */
12053  int wrFlag, /* 1 for writing. 0 for read-only */
12054  struct KeyInfo*, /* First argument to compare function */
12055  BtCursor *pCursor /* Space to write cursor structure */
12056 );
12060 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12061 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor*, int, ...);
12062 #endif
12063 
12066  BtCursor*,
12067  UnpackedRecord *pUnKey,
12068  i64 intKey,
12069  int bias,
12070  int *pRes
12071 );
12075 
12076 /* Allowed flags for the 2nd argument to sqlite3BtreeDelete() */
12077 #define BTREE_SAVEPOSITION 0x02 /* Leave cursor pointing at NEXT or PREV */
12078 #define BTREE_AUXDELETE 0x04 /* not the primary delete operation */
12079 
12080 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
12081  const void *pData, int nData,
12082  int nZero, int bias, int seekResult);
12083 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
12084 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
12085 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
12088 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
12089 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
12090 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
12091 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
12092 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
12093 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
12094 
12095 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
12097 
12098 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
12101 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
12105 
12106 #ifndef NDEBUG
12107 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
12108 #endif
12109 
12110 #ifndef SQLITE_OMIT_BTREECOUNT
12112 #endif
12113 
12114 #ifdef SQLITE_TEST
12115 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
12116 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
12117 #endif
12118 
12119 #ifndef SQLITE_OMIT_WAL
12120 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
12121 #endif
12122 
12123 /*
12124 ** If we are not using shared cache, then there is no need to
12125 ** use mutexes to access the BtShared structures. So make the
12126 ** Enter and Leave procedures no-ops.
12127 */
12128 #ifndef SQLITE_OMIT_SHARED_CACHE
12133 #else
12134 # define sqlite3BtreeEnter(X)
12135 # define sqlite3BtreeEnterAll(X)
12136 # define sqlite3BtreeSharable(X) 0
12137 # define sqlite3BtreeEnterCursor(X)
12138 #endif
12139 
12140 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
12144 #ifndef NDEBUG
12145  /* These routines are used inside assert() statements only. */
12146 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
12147 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
12148 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
12149 #endif
12150 #else
12151 
12152 # define sqlite3BtreeLeave(X)
12153 # define sqlite3BtreeLeaveCursor(X)
12154 # define sqlite3BtreeLeaveAll(X)
12155 
12156 # define sqlite3BtreeHoldsMutex(X) 1
12157 # define sqlite3BtreeHoldsAllMutexes(X) 1
12158 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
12159 #endif
12160 
12161 
12162 #endif /* _BTREE_H_ */
12163 
12164 /************** End of btree.h ***********************************************/
12165 /************** Continuing where we left off in sqliteInt.h ******************/
12166 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
12167 /************** Begin file vdbe.h ********************************************/
12168 /*
12169 ** 2001 September 15
12170 **
12171 ** The author disclaims copyright to this source code. In place of
12172 ** a legal notice, here is a blessing:
12173 **
12174 ** May you do good and not evil.
12175 ** May you find forgiveness for yourself and forgive others.
12176 ** May you share freely, never taking more than you give.
12177 **
12178 *************************************************************************
12179 ** Header file for the Virtual DataBase Engine (VDBE)
12180 **
12181 ** This header defines the interface to the virtual database engine
12182 ** or VDBE. The VDBE implements an abstract machine that runs a
12183 ** simple program to access and modify the underlying database.
12184 */
12185 #ifndef _SQLITE_VDBE_H_
12186 #define _SQLITE_VDBE_H_
12187 /* #include <stdio.h> */
12188 
12189 /*
12190 ** A single VDBE is an opaque structure named "Vdbe". Only routines
12191 ** in the source file sqliteVdbe.c are allowed to see the insides
12192 ** of this structure.
12193 */
12194 typedef struct Vdbe Vdbe;
12195 
12196 /*
12197 ** The names of the following types declared in vdbeInt.h are required
12198 ** for the VdbeOp definition.
12199 */
12200 typedef struct Mem Mem;
12201 typedef struct SubProgram SubProgram;
12202 
12203 /*
12204 ** A single instruction of the virtual machine has an opcode
12205 ** and as many as three operands. The instruction is recorded
12206 ** as an instance of the following structure:
12207 */
12208 struct VdbeOp {
12209  u8 opcode; /* What operation to perform */
12210  signed char p4type; /* One of the P4_xxx constants for p4 */
12212  u8 p5; /* Fifth parameter is an unsigned character */
12213  int p1; /* First operand */
12214  int p2; /* Second parameter (often the jump destination) */
12215  int p3; /* The third parameter */
12216  union p4union { /* fourth parameter */
12217  int i; /* Integer value if p4type==P4_INT32 */
12218  void *p; /* Generic pointer */
12219  char *z; /* Pointer to data for string (char array) types */
12220  i64 *pI64; /* Used when p4type is P4_INT64 */
12221  double *pReal; /* Used when p4type is P4_REAL */
12222  FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
12223  sqlite3_context *pCtx; /* Used when p4type is P4_FUNCCTX */
12224  CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
12225  Mem *pMem; /* Used when p4type is P4_MEM */
12226  VTable *pVtab; /* Used when p4type is P4_VTAB */
12227  KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
12228  int *ai; /* Used when p4type is P4_INTARRAY */
12229  SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
12230  Table *pTab; /* Used when p4type is P4_TABLE */
12231 #ifdef SQLITE_ENABLE_CURSOR_HINTS
12232  Expr *pExpr; /* Used when p4type is P4_EXPR */
12233 #endif
12234  int (*xAdvance)(BtCursor *, int *);
12235  } p4;
12236 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12237  char *zComment; /* Comment to improve readability */
12238 #endif
12239 #ifdef VDBE_PROFILE
12240  u32 cnt; /* Number of times this instruction was executed */
12241  u64 cycles; /* Total time spent executing this instruction */
12242 #endif
12243 #ifdef SQLITE_VDBE_COVERAGE
12244  int iSrcLine; /* Source-code line that generated this opcode */
12245 #endif
12246 };
12247 typedef struct VdbeOp VdbeOp;
12248 
12249 
12250 /*
12251 ** A sub-routine used to implement a trigger program.
12252 */
12253 struct SubProgram {
12254  VdbeOp *aOp; /* Array of opcodes for sub-program */
12255  int nOp; /* Elements in aOp[] */
12256  int nMem; /* Number of memory cells required */
12257  int nCsr; /* Number of cursors required */
12258  int nOnce; /* Number of OP_Once instructions */
12259  void *token; /* id that may be used to recursive triggers */
12260  SubProgram *pNext; /* Next sub-program already visited */
12261 };
12262 
12263 /*
12264 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
12265 ** it takes up less space.
12266 */
12267 struct VdbeOpList {
12268  u8 opcode; /* What operation to perform */
12269  signed char p1; /* First operand */
12270  signed char p2; /* Second parameter (often the jump destination) */
12271  signed char p3; /* Third parameter */
12272 };
12273 typedef struct VdbeOpList VdbeOpList;
12274 
12275 /*
12276 ** Allowed values of VdbeOp.p4type
12277 */
12278 #define P4_NOTUSED 0 /* The P4 parameter is not used */
12279 #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
12280 #define P4_STATIC (-2) /* Pointer to a static string */
12281 #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
12282 #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
12283 #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
12284 #define P4_EXPR (-7) /* P4 is a pointer to an Expr tree */
12285 #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
12286 #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
12287 #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
12288 #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
12289 #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
12290 #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
12291 #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
12292 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
12293 #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
12294 #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
12295 #define P4_TABLE (-20) /* P4 is a pointer to a Table structure */
12296 #define P4_FUNCCTX (-21) /* P4 is a pointer to an sqlite3_context object */
12297 
12298 /* Error message codes for OP_Halt */
12299 #define P5_ConstraintNotNull 1
12300 #define P5_ConstraintUnique 2
12301 #define P5_ConstraintCheck 3
12302 #define P5_ConstraintFK 4
12303 
12304 /*
12305 ** The Vdbe.aColName array contains 5n Mem structures, where n is the
12306 ** number of columns of data returned by the statement.
12307 */
12308 #define COLNAME_NAME 0
12309 #define COLNAME_DECLTYPE 1
12310 #define COLNAME_DATABASE 2
12311 #define COLNAME_TABLE 3
12312 #define COLNAME_COLUMN 4
12313 #ifdef SQLITE_ENABLE_COLUMN_METADATA
12314 # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
12315 #else
12316 # ifdef SQLITE_OMIT_DECLTYPE
12317 # define COLNAME_N 1 /* Store only the name */
12318 # else
12319 # define COLNAME_N 2 /* Store the name and decltype */
12320 # endif
12321 #endif
12322 
12323 /*
12324 ** The following macro converts a relative address in the p2 field
12325 ** of a VdbeOp structure into a negative number so that
12326 ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
12327 ** the macro again restores the address.
12328 */
12329 #define ADDR(X) (-1-(X))
12330 
12331 /*
12332 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
12333 ** header file that defines a number for each opcode used by the VDBE.
12334 */
12335 /************** Include opcodes.h in the middle of vdbe.h ********************/
12336 /************** Begin file opcodes.h *****************************************/
12337 /* Automatically generated. Do not edit */
12338 /* See the tool/mkopcodeh.tcl script for details */
12339 #define OP_Savepoint 0
12340 #define OP_AutoCommit 1
12341 #define OP_Transaction 2
12342 #define OP_SorterNext 3
12343 #define OP_PrevIfOpen 4
12344 #define OP_NextIfOpen 5
12345 #define OP_Prev 6
12346 #define OP_Next 7
12347 #define OP_Checkpoint 8
12348 #define OP_JournalMode 9
12349 #define OP_Vacuum 10
12350 #define OP_VFilter 11 /* synopsis: iplan=r[P3] zplan='P4' */
12351 #define OP_VUpdate 12 /* synopsis: data=r[P3@P2] */
12352 #define OP_Goto 13
12353 #define OP_Gosub 14
12354 #define OP_InitCoroutine 15
12355 #define OP_Yield 16
12356 #define OP_MustBeInt 17
12357 #define OP_Jump 18
12358 #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
12359 #define OP_Once 20
12360 #define OP_If 21
12361 #define OP_IfNot 22
12362 #define OP_SeekLT 23 /* synopsis: key=r[P3@P4] */
12363 #define OP_SeekLE 24 /* synopsis: key=r[P3@P4] */
12364 #define OP_SeekGE 25 /* synopsis: key=r[P3@P4] */
12365 #define OP_SeekGT 26 /* synopsis: key=r[P3@P4] */
12366 #define OP_Or 27 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
12367 #define OP_And 28 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
12368 #define OP_NoConflict 29 /* synopsis: key=r[P3@P4] */
12369 #define OP_NotFound 30 /* synopsis: key=r[P3@P4] */
12370 #define OP_Found 31 /* synopsis: key=r[P3@P4] */
12371 #define OP_NotExists 32 /* synopsis: intkey=r[P3] */
12372 #define OP_Last 33
12373 #define OP_IsNull 34 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
12374 #define OP_NotNull 35 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
12375 #define OP_Ne 36 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
12376 #define OP_Eq 37 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
12377 #define OP_Gt 38 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
12378 #define OP_Le 39 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
12379 #define OP_Lt 40 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
12380 #define OP_Ge 41 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
12381 #define OP_SorterSort 42
12382 #define OP_BitAnd 43 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
12383 #define OP_BitOr 44 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
12384 #define OP_ShiftLeft 45 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
12385 #define OP_ShiftRight 46 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
12386 #define OP_Add 47 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
12387 #define OP_Subtract 48 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
12388 #define OP_Multiply 49 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
12389 #define OP_Divide 50 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
12390 #define OP_Remainder 51 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
12391 #define OP_Concat 52 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
12392 #define OP_Sort 53
12393 #define OP_BitNot 54 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
12394 #define OP_Rewind 55
12395 #define OP_IdxLE 56 /* synopsis: key=r[P3@P4] */
12396 #define OP_IdxGT 57 /* synopsis: key=r[P3@P4] */
12397 #define OP_IdxLT 58 /* synopsis: key=r[P3@P4] */
12398 #define OP_IdxGE 59 /* synopsis: key=r[P3@P4] */
12399 #define OP_RowSetRead 60 /* synopsis: r[P3]=rowset(P1) */
12400 #define OP_RowSetTest 61 /* synopsis: if r[P3] in rowset(P1) goto P2 */
12401 #define OP_Program 62
12402 #define OP_FkIfZero 63 /* synopsis: if fkctr[P1]==0 goto P2 */
12403 #define OP_IfPos 64 /* synopsis: if r[P1]>0 then r[P1]-=P3, goto P2 */
12404 #define OP_IfNotZero 65 /* synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2 */
12405 #define OP_DecrJumpZero 66 /* synopsis: if (--r[P1])==0 goto P2 */
12406 #define OP_IncrVacuum 67
12407 #define OP_VNext 68
12408 #define OP_Init 69 /* synopsis: Start at P2 */
12409 #define OP_Return 70
12410 #define OP_EndCoroutine 71
12411 #define OP_HaltIfNull 72 /* synopsis: if r[P3]=null halt */
12412 #define OP_Halt 73
12413 #define OP_Integer 74 /* synopsis: r[P2]=P1 */
12414 #define OP_Int64 75 /* synopsis: r[P2]=P4 */
12415 #define OP_String 76 /* synopsis: r[P2]='P4' (len=P1) */
12416 #define OP_Null 77 /* synopsis: r[P2..P3]=NULL */
12417 #define OP_SoftNull 78 /* synopsis: r[P1]=NULL */
12418 #define OP_Blob 79 /* synopsis: r[P2]=P4 (len=P1) */
12419 #define OP_Variable 80 /* synopsis: r[P2]=parameter(P1,P4) */
12420 #define OP_Move 81 /* synopsis: r[P2@P3]=r[P1@P3] */
12421 #define OP_Copy 82 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
12422 #define OP_SCopy 83 /* synopsis: r[P2]=r[P1] */
12423 #define OP_IntCopy 84 /* synopsis: r[P2]=r[P1] */
12424 #define OP_ResultRow 85 /* synopsis: output=r[P1@P2] */
12425 #define OP_CollSeq 86
12426 #define OP_Function0 87 /* synopsis: r[P3]=func(r[P2@P5]) */
12427 #define OP_Function 88 /* synopsis: r[P3]=func(r[P2@P5]) */
12428 #define OP_AddImm 89 /* synopsis: r[P1]=r[P1]+P2 */
12429 #define OP_RealAffinity 90
12430 #define OP_Cast 91 /* synopsis: affinity(r[P1]) */
12431 #define OP_Permutation 92
12432 #define OP_Compare 93 /* synopsis: r[P1@P3] <-> r[P2@P3] */
12433 #define OP_Column 94 /* synopsis: r[P3]=PX */
12434 #define OP_Affinity 95 /* synopsis: affinity(r[P1@P2]) */
12435 #define OP_MakeRecord 96 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
12436 #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
12437 #define OP_Count 98 /* synopsis: r[P2]=count() */
12438 #define OP_ReadCookie 99
12439 #define OP_SetCookie 100
12440 #define OP_ReopenIdx 101 /* synopsis: root=P2 iDb=P3 */
12441 #define OP_OpenRead 102 /* synopsis: root=P2 iDb=P3 */
12442 #define OP_OpenWrite 103 /* synopsis: root=P2 iDb=P3 */
12443 #define OP_OpenAutoindex 104 /* synopsis: nColumn=P2 */
12444 #define OP_OpenEphemeral 105 /* synopsis: nColumn=P2 */
12445 #define OP_SorterOpen 106
12446 #define OP_SequenceTest 107 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
12447 #define OP_OpenPseudo 108 /* synopsis: P3 columns in r[P2] */
12448 #define OP_Close 109
12449 #define OP_ColumnsUsed 110
12450 #define OP_Sequence 111 /* synopsis: r[P2]=cursor[P1].ctr++ */
12451 #define OP_NewRowid 112 /* synopsis: r[P2]=rowid */
12452 #define OP_Insert 113 /* synopsis: intkey=r[P3] data=r[P2] */
12453 #define OP_InsertInt 114 /* synopsis: intkey=P3 data=r[P2] */
12454 #define OP_Delete 115
12455 #define OP_ResetCount 116
12456 #define OP_SorterCompare 117 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
12457 #define OP_SorterData 118 /* synopsis: r[P2]=data */
12458 #define OP_RowKey 119 /* synopsis: r[P2]=key */
12459 #define OP_RowData 120 /* synopsis: r[P2]=data */
12460 #define OP_Rowid 121 /* synopsis: r[P2]=rowid */
12461 #define OP_NullRow 122
12462 #define OP_SorterInsert 123
12463 #define OP_IdxInsert 124 /* synopsis: key=r[P2] */
12464 #define OP_IdxDelete 125 /* synopsis: key=r[P2@P3] */
12465 #define OP_Seek 126 /* synopsis: Move P3 to P1.rowid */
12466 #define OP_IdxRowid 127 /* synopsis: r[P2]=rowid */
12467 #define OP_Destroy 128
12468 #define OP_Clear 129
12469 #define OP_ResetSorter 130
12470 #define OP_CreateIndex 131 /* synopsis: r[P2]=root iDb=P1 */
12471 #define OP_CreateTable 132 /* synopsis: r[P2]=root iDb=P1 */
12472 #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
12473 #define OP_ParseSchema 134
12474 #define OP_LoadAnalysis 135
12475 #define OP_DropTable 136
12476 #define OP_DropIndex 137
12477 #define OP_DropTrigger 138
12478 #define OP_IntegrityCk 139
12479 #define OP_RowSetAdd 140 /* synopsis: rowset(P1)=r[P2] */
12480 #define OP_Param 141
12481 #define OP_FkCounter 142 /* synopsis: fkctr[P1]+=P2 */
12482 #define OP_MemMax 143 /* synopsis: r[P1]=max(r[P1],r[P2]) */
12483 #define OP_OffsetLimit 144 /* synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1) */
12484 #define OP_AggStep0 145 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12485 #define OP_AggStep 146 /* synopsis: accum=r[P3] step(r[P2@P5]) */
12486 #define OP_AggFinal 147 /* synopsis: accum=r[P1] N=P2 */
12487 #define OP_Expire 148
12488 #define OP_TableLock 149 /* synopsis: iDb=P1 root=P2 write=P3 */
12489 #define OP_VBegin 150
12490 #define OP_VCreate 151
12491 #define OP_VDestroy 152
12492 #define OP_VOpen 153
12493 #define OP_VColumn 154 /* synopsis: r[P3]=vcolumn(P2) */
12494 #define OP_VRename 155
12495 #define OP_Pagecount 156
12496 #define OP_MaxPgcnt 157
12497 #define OP_CursorHint 158
12498 #define OP_Noop 159
12499 #define OP_Explain 160
12500 
12501 /* Properties such as "out2" or "jump" that are specified in
12502 ** comments following the "case" for each opcode in the vdbe.c
12503 ** are encoded into bitvectors as follows:
12504 */
12505 #define OPFLG_JUMP 0x01 /* jump: P2 holds jmp target */
12506 #define OPFLG_IN1 0x02 /* in1: P1 is an input */
12507 #define OPFLG_IN2 0x04 /* in2: P2 is an input */
12508 #define OPFLG_IN3 0x08 /* in3: P3 is an input */
12509 #define OPFLG_OUT2 0x10 /* out2: P2 is an output */
12510 #define OPFLG_OUT3 0x20 /* out3: P3 is an output */
12511 #define OPFLG_INITIALIZER {\
12512 /* 0 */ 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x01, 0x01,\
12513 /* 8 */ 0x00, 0x10, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01,\
12514 /* 16 */ 0x03, 0x03, 0x01, 0x12, 0x01, 0x03, 0x03, 0x09,\
12515 /* 24 */ 0x09, 0x09, 0x09, 0x26, 0x26, 0x09, 0x09, 0x09,\
12516 /* 32 */ 0x09, 0x01, 0x03, 0x03, 0x0b, 0x0b, 0x0b, 0x0b,\
12517 /* 40 */ 0x0b, 0x0b, 0x01, 0x26, 0x26, 0x26, 0x26, 0x26,\
12518 /* 48 */ 0x26, 0x26, 0x26, 0x26, 0x26, 0x01, 0x12, 0x01,\
12519 /* 56 */ 0x01, 0x01, 0x01, 0x01, 0x23, 0x0b, 0x01, 0x01,\
12520 /* 64 */ 0x03, 0x03, 0x03, 0x01, 0x01, 0x01, 0x02, 0x02,\
12521 /* 72 */ 0x08, 0x00, 0x10, 0x10, 0x10, 0x10, 0x00, 0x10,\
12522 /* 80 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00, 0x00,\
12523 /* 88 */ 0x00, 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
12524 /* 96 */ 0x00, 0x10, 0x10, 0x10, 0x00, 0x00, 0x00, 0x00,\
12525 /* 104 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10,\
12526 /* 112 */ 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12527 /* 120 */ 0x00, 0x10, 0x00, 0x04, 0x04, 0x00, 0x00, 0x10,\
12528 /* 128 */ 0x10, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x00,\
12529 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x06, 0x10, 0x00, 0x04,\
12530 /* 144 */ 0x1a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
12531 /* 152 */ 0x00, 0x00, 0x00, 0x00, 0x10, 0x10, 0x00, 0x00,\
12532 /* 160 */ 0x00,}
12533 
12534 /* The sqlite3P2Values() routine is able to run faster if it knows
12535 ** the value of the largest JUMP opcode. The smaller the maximum
12536 ** JUMP opcode the better, so the mkopcodeh.tcl script that
12537 ** generated this include file strives to group all JUMP opcodes
12538 ** together near the beginning of the list.
12539 */
12540 #define SQLITE_MX_JUMP_OPCODE 69 /* Maximum JUMP opcode */
12541 
12542 /************** End of opcodes.h *********************************************/
12543 /************** Continuing where we left off in vdbe.h ***********************/
12544 
12545 /*
12546 ** Prototypes for the VDBE interface. See comments on the implementation
12547 ** for a description of what each of these routines does.
12548 */
12551 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
12552 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
12554 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe*,int,const char*);
12555 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe*,int,const char*,...);
12556 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
12557 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
12558 SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe*,int,int,int,int,const u8*,int);
12559 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
12561 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
12563 #else
12564 # define sqlite3VdbeVerifyNoMallocRequired(A,B)
12565 #endif
12566 SQLITE_PRIVATE VdbeOp *sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
12569 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
12570 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
12571 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
12576 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
12589 #ifdef SQLITE_DEBUG
12590 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
12591 #endif
12596 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
12599 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
12604 #ifndef SQLITE_OMIT_TRACE
12605 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
12606 #endif
12607 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
12608 
12611 SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int);
12613 
12614 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
12616 
12617 #ifndef SQLITE_OMIT_TRIGGER
12619 #endif
12620 
12621 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
12622 ** each VDBE opcode.
12623 **
12624 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
12625 ** comments in VDBE programs that show key decision points in the code
12626 ** generator.
12627 */
12628 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
12629 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
12630 # define VdbeComment(X) sqlite3VdbeComment X
12631 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
12632 # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
12633 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
12634 # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
12635 # else
12636 # define VdbeModuleComment(X)
12637 # endif
12638 #else
12639 # define VdbeComment(X)
12640 # define VdbeNoopComment(X)
12641 # define VdbeModuleComment(X)
12642 #endif
12643 
12644 /*
12645 ** The VdbeCoverage macros are used to set a coverage testing point
12646 ** for VDBE branch instructions. The coverage testing points are line
12647 ** numbers in the sqlite3.c source file. VDBE branch coverage testing
12648 ** only works with an amalagmation build. That's ok since a VDBE branch
12649 ** coverage build designed for testing the test suite only. No application
12650 ** should ever ship with VDBE branch coverage measuring turned on.
12651 **
12652 ** VdbeCoverage(v) // Mark the previously coded instruction
12653 ** // as a branch
12654 **
12655 ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
12656 **
12657 ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
12658 **
12659 ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
12660 **
12661 ** Every VDBE branch operation must be tagged with one of the macros above.
12662 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
12663 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
12664 ** routine in vdbe.c, alerting the developer to the missed tag.
12665 */
12666 #ifdef SQLITE_VDBE_COVERAGE
12667 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
12668 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
12669 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
12670 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
12671 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
12672 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
12673 #else
12674 # define VdbeCoverage(v)
12675 # define VdbeCoverageIf(v,x)
12676 # define VdbeCoverageAlwaysTaken(v)
12677 # define VdbeCoverageNeverTaken(v)
12678 # define VDBE_OFFSET_LINENO(x) 0
12679 #endif
12680 
12681 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
12682 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
12683 #else
12684 # define sqlite3VdbeScanStatus(a,b,c,d,e)
12685 #endif
12686 
12687 #endif
12688 
12689 /************** End of vdbe.h ************************************************/
12690 /************** Continuing where we left off in sqliteInt.h ******************/
12691 /************** Include pager.h in the middle of sqliteInt.h *****************/
12692 /************** Begin file pager.h *******************************************/
12693 /*
12694 ** 2001 September 15
12695 **
12696 ** The author disclaims copyright to this source code. In place of
12697 ** a legal notice, here is a blessing:
12698 **
12699 ** May you do good and not evil.
12700 ** May you find forgiveness for yourself and forgive others.
12701 ** May you share freely, never taking more than you give.
12702 **
12703 *************************************************************************
12704 ** This header file defines the interface that the sqlite page cache
12705 ** subsystem. The page cache subsystem reads and writes a file a page
12706 ** at a time and provides a journal for rollback.
12707 */
12708 
12709 #ifndef _PAGER_H_
12710 #define _PAGER_H_
12711 
12712 /*
12713 ** Default maximum size for persistent journal files. A negative
12714 ** value means no limit. This value may be overridden using the
12715 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
12716 */
12717 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
12718  #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
12719 #endif
12720 
12721 /*
12722 ** The type used to represent a page number. The first page in a file
12723 ** is called page 1. 0 is used to represent "not a page".
12724 */
12725 typedef u32 Pgno;
12726 
12727 /*
12728 ** Each open file is managed by a separate instance of the "Pager" structure.
12729 */
12730 typedef struct Pager Pager;
12731 
12732 /*
12733 ** Handle type for pages.
12734 */
12735 typedef struct PgHdr DbPage;
12736 
12737 /*
12738 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
12739 ** reserved for working around a windows/posix incompatibility). It is
12740 ** used in the journal to signify that the remainder of the journal file
12741 ** is devoted to storing a master journal name - there are no more pages to
12742 ** roll back. See comments for function writeMasterJournal() in pager.c
12743 ** for details.
12744 */
12745 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
12746 
12747 /*
12748 ** Allowed values for the flags parameter to sqlite3PagerOpen().
12749 **
12750 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
12751 */
12752 #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
12753 #define PAGER_MEMORY 0x0002 /* In-memory database */
12754 
12755 /*
12756 ** Valid values for the second argument to sqlite3PagerLockingMode().
12757 */
12758 #define PAGER_LOCKINGMODE_QUERY -1
12759 #define PAGER_LOCKINGMODE_NORMAL 0
12760 #define PAGER_LOCKINGMODE_EXCLUSIVE 1
12761 
12762 /*
12763 ** Numeric constants that encode the journalmode.
12764 **
12765 ** The numeric values encoded here (other than PAGER_JOURNALMODE_QUERY)
12766 ** are exposed in the API via the "PRAGMA journal_mode" command and
12767 ** therefore cannot be changed without a compatibility break.
12768 */
12769 #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
12770 #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
12771 #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
12772 #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
12773 #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
12774 #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
12775 #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
12776 
12777 /*
12778 ** Flags that make up the mask passed to sqlite3PagerGet().
12779 */
12780 #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
12781 #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
12782 
12783 /*
12784 ** Flags for sqlite3PagerSetFlags()
12785 **
12786 ** Value constraints (enforced via assert()):
12787 ** PAGER_FULLFSYNC == SQLITE_FullFSync
12788 ** PAGER_CKPT_FULLFSYNC == SQLITE_CkptFullFSync
12789 ** PAGER_CACHE_SPILL == SQLITE_CacheSpill
12790 */
12791 #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
12792 #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
12793 #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
12794 #define PAGER_SYNCHRONOUS_EXTRA 0x04 /* PRAGMA synchronous=EXTRA */
12795 #define PAGER_SYNCHRONOUS_MASK 0x07 /* Mask for four values above */
12796 #define PAGER_FULLFSYNC 0x08 /* PRAGMA fullfsync=ON */
12797 #define PAGER_CKPT_FULLFSYNC 0x10 /* PRAGMA checkpoint_fullfsync=ON */
12798 #define PAGER_CACHESPILL 0x20 /* PRAGMA cache_spill=ON */
12799 #define PAGER_FLAGS_MASK 0x38 /* All above except SYNCHRONOUS */
12800 
12801 /*
12802 ** The remainder of this file contains the declarations of the functions
12803 ** that make up the Pager sub-system API. See source code comments for
12804 ** a detailed description of each routine.
12805 */
12806 
12807 /* Open and close a Pager connection. */
12809  sqlite3_vfs*,
12810  Pager **ppPager,
12811  const char*,
12812  int,
12813  int,
12814  int,
12815  void(*)(DbPage*)
12816 );
12818 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
12819 
12820 /* Functions used to configure a Pager object. */
12821 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
12823 #ifdef SQLITE_HAS_CODEC
12824 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager*,Pager*);
12825 #endif
12829 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
12831 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
12839 
12840 /* Functions used to obtain and release page references. */
12841 SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
12846 
12847 /* Operations on page references. */
12854 
12855 /* Functions used to manage pager transactions and savepoints. */
12857 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
12858 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
12860 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
12864 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
12866 
12867 #ifndef SQLITE_OMIT_WAL
12868 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
12871 SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
12873 # ifdef SQLITE_ENABLE_SNAPSHOT
12874 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot);
12875 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot);
12876 # endif
12877 #endif
12878 
12879 #ifdef SQLITE_ENABLE_ZIPVFS
12880 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
12881 #endif
12882 
12883 /* Functions used to query pager state and configuration. */
12886 #ifdef SQLITE_DEBUG
12887 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
12888 #endif
12890 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
12891 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager*);
12892 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
12893 SQLITE_PRIVATE sqlite3_file *sqlite3PagerJrnlFile(Pager*);
12897 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
12899 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
12900 
12901 /* Functions used to truncate the database file. */
12903 
12904 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
12905 
12906 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
12907 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
12908 #endif
12909 
12910 /* Functions to support testing and debugging. */
12911 #if !defined(NDEBUG) || defined(SQLITE_TEST)
12912 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
12913 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
12914 #endif
12915 #ifdef SQLITE_TEST
12916 SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
12917 SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
12918  void disable_simulated_io_errors(void);
12919  void enable_simulated_io_errors(void);
12920 #else
12921 # define disable_simulated_io_errors()
12922 # define enable_simulated_io_errors()
12923 #endif
12924 
12925 #endif /* _PAGER_H_ */
12926 
12927 /************** End of pager.h ***********************************************/
12928 /************** Continuing where we left off in sqliteInt.h ******************/
12929 /************** Include pcache.h in the middle of sqliteInt.h ****************/
12930 /************** Begin file pcache.h ******************************************/
12931 /*
12932 ** 2008 August 05
12933 **
12934 ** The author disclaims copyright to this source code. In place of
12935 ** a legal notice, here is a blessing:
12936 **
12937 ** May you do good and not evil.
12938 ** May you find forgiveness for yourself and forgive others.
12939 ** May you share freely, never taking more than you give.
12940 **
12941 *************************************************************************
12942 ** This header file defines the interface that the sqlite page cache
12943 ** subsystem.
12944 */
12945 
12946 #ifndef _PCACHE_H_
12947 
12948 typedef struct PgHdr PgHdr;
12949 typedef struct PCache PCache;
12950 
12951 /*
12952 ** Every page in the cache is controlled by an instance of the following
12953 ** structure.
12954 */
12955 struct PgHdr {
12956  sqlite3_pcache_page *pPage; /* Pcache object page handle */
12957  void *pData; /* Page data */
12958  void *pExtra; /* Extra content */
12959  PgHdr *pDirty; /* Transient list of dirty sorted by pgno */
12960  Pager *pPager; /* The pager this page is part of */
12961  Pgno pgno; /* Page number for this page */
12962 #ifdef SQLITE_CHECK_PAGES
12963  u32 pageHash; /* Hash of page content */
12964 #endif
12965  u16 flags; /* PGHDR flags defined below */
12966 
12967  /**********************************************************************
12968  ** Elements above are public. All that follows is private to pcache.c
12969  ** and should not be accessed by other modules.
12970  */
12971  i16 nRef; /* Number of users of this page */
12972  PCache *pCache; /* Cache that owns this page */
12973 
12974  PgHdr *pDirtyNext; /* Next element in list of dirty pages */
12975  PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
12976 };
12977 
12978 /* Bit values for PgHdr.flags */
12979 #define PGHDR_CLEAN 0x001 /* Page not on the PCache.pDirty list */
12980 #define PGHDR_DIRTY 0x002 /* Page is on the PCache.pDirty list */
12981 #define PGHDR_WRITEABLE 0x004 /* Journaled and ready to modify */
12982 #define PGHDR_NEED_SYNC 0x008 /* Fsync the rollback journal before
12983  ** writing this page to the database */
12984 #define PGHDR_DONT_WRITE 0x010 /* Do not write content to disk */
12985 #define PGHDR_MMAP 0x020 /* This is an mmap page object */
12986 
12987 #define PGHDR_WAL_APPEND 0x040 /* Appended to wal file */
12988 
12989 /* Initialize and shutdown the page cache subsystem */
12992 
12993 /* Page cache buffer management:
12994 ** These routines implement SQLITE_CONFIG_PAGECACHE.
12995 */
12996 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
12997 
12998 /* Create a new pager cache.
12999 ** Under memory stress, invoke xStress to try to make pages clean.
13000 ** Only clean and unpinned pages can be reclaimed.
13001 */
13003  int szPage, /* Size of every page */
13004  int szExtra, /* Extra space associated with each page */
13005  int bPurgeable, /* True if pages are on backing store */
13006  int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
13007  void *pStress, /* Argument to xStress */
13008  PCache *pToInit /* Preallocated space for the PCache */
13009 );
13010 
13011 /* Modify the page-size after the cache has been created. */
13013 
13014 /* Return the size in bytes of a PCache object. Used to preallocate
13015 ** storage space.
13016 */
13018 
13019 /* One release per successful fetch. Page is pinned until released.
13020 ** Reference counted.
13021 */
13026 
13027 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
13028 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
13029 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
13030 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
13032 
13033 /* Change a page number. Used by incr-vacuum. */
13035 
13036 /* Remove all pages with pgno>x. Reset the cache if x==0 */
13038 
13039 /* Get a list of all dirty pages in the cache, sorted by page number */
13041 
13042 /* Reset and close the cache object */
13044 
13045 /* Clear flags from pages of the page cache */
13047 
13048 /* Discard the contents of the cache */
13050 
13051 /* Return the total number of outstanding page references */
13053 
13054 /* Increment the reference count of an existing page */
13056 
13058 
13059 /* Return the total number of pages stored in the cache */
13061 
13062 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
13063 /* Iterate through all dirty pages currently stored in the cache. This
13064 ** interface is only available if SQLITE_CHECK_PAGES is defined when the
13065 ** library is built.
13066 */
13067 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
13068 #endif
13069 
13070 #if defined(SQLITE_DEBUG)
13071 /* Check invariants on a PgHdr object */
13072 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr*);
13073 #endif
13074 
13075 /* Set and get the suggested cache-size for the specified pager-cache.
13076 **
13077 ** If no global maximum is configured, then the system attempts to limit
13078 ** the total number of pages cached by purgeable pager-caches to the sum
13079 ** of the suggested cache-sizes.
13080 */
13082 #ifdef SQLITE_TEST
13083 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
13084 #endif
13085 
13086 /* Set or get the suggested spill-size for the specified pager-cache.
13087 **
13088 ** The spill-size is the minimum number of pages in cache before the cache
13089 ** will attempt to spill dirty pages by calling xStress.
13090 */
13092 
13093 /* Free up as much memory as possible from the page cache */
13095 
13096 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
13097 /* Try to return memory used by the pcache module to the main memory heap */
13098 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
13099 #endif
13100 
13101 #ifdef SQLITE_TEST
13102 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
13103 #endif
13104 
13106 
13107 /* Return the header size */
13110 
13111 /* Number of dirty pages as a percentage of the configured cache size */
13113 
13114 #endif /* _PCACHE_H_ */
13115 
13116 /************** End of pcache.h **********************************************/
13117 /************** Continuing where we left off in sqliteInt.h ******************/
13118 /************** Include os.h in the middle of sqliteInt.h ********************/
13119 /************** Begin file os.h **********************************************/
13120 /*
13121 ** 2001 September 16
13122 **
13123 ** The author disclaims copyright to this source code. In place of
13124 ** a legal notice, here is a blessing:
13125 **
13126 ** May you do good and not evil.
13127 ** May you find forgiveness for yourself and forgive others.
13128 ** May you share freely, never taking more than you give.
13129 **
13130 ******************************************************************************
13131 **
13132 ** This header file (together with is companion C source-code file
13133 ** "os.c") attempt to abstract the underlying operating system so that
13134 ** the SQLite library will work on both POSIX and windows systems.
13135 **
13136 ** This header file is #include-ed by sqliteInt.h and thus ends up
13137 ** being included by every source file.
13138 */
13139 #ifndef _SQLITE_OS_H_
13140 #define _SQLITE_OS_H_
13141 
13142 /*
13143 ** Attempt to automatically detect the operating system and setup the
13144 ** necessary pre-processor macros for it.
13145 */
13146 /************** Include os_setup.h in the middle of os.h *********************/
13147 /************** Begin file os_setup.h ****************************************/
13148 /*
13149 ** 2013 November 25
13150 **
13151 ** The author disclaims copyright to this source code. In place of
13152 ** a legal notice, here is a blessing:
13153 **
13154 ** May you do good and not evil.
13155 ** May you find forgiveness for yourself and forgive others.
13156 ** May you share freely, never taking more than you give.
13157 **
13158 ******************************************************************************
13159 **
13160 ** This file contains pre-processor directives related to operating system
13161 ** detection and/or setup.
13162 */
13163 #ifndef _OS_SETUP_H_
13164 #define _OS_SETUP_H_
13165 
13166 /*
13167 ** Figure out if we are dealing with Unix, Windows, or some other operating
13168 ** system.
13169 **
13170 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
13171 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
13172 ** the three will be 1. The other two will be 0.
13173 */
13174 #if defined(SQLITE_OS_OTHER)
13175 # if SQLITE_OS_OTHER==1
13176 # undef SQLITE_OS_UNIX
13177 # define SQLITE_OS_UNIX 0
13178 # undef SQLITE_OS_WIN
13179 # define SQLITE_OS_WIN 0
13180 # else
13181 # undef SQLITE_OS_OTHER
13182 # endif
13183 #endif
13184 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
13185 # define SQLITE_OS_OTHER 0
13186 # ifndef SQLITE_OS_WIN
13187 # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
13188  defined(__MINGW32__) || defined(__BORLANDC__)
13189 # define SQLITE_OS_WIN 1
13190 # define SQLITE_OS_UNIX 0
13191 # else
13192 # define SQLITE_OS_WIN 0
13193 # define SQLITE_OS_UNIX 1
13194 # endif
13195 # else
13196 # define SQLITE_OS_UNIX 0
13197 # endif
13198 #else
13199 # ifndef SQLITE_OS_WIN
13200 # define SQLITE_OS_WIN 0
13201 # endif
13202 #endif
13203 
13204 #endif /* _OS_SETUP_H_ */
13205 
13206 /************** End of os_setup.h ********************************************/
13207 /************** Continuing where we left off in os.h *************************/
13208 
13209 /* If the SET_FULLSYNC macro is not defined above, then make it
13210 ** a no-op
13211 */
13212 #ifndef SET_FULLSYNC
13213 # define SET_FULLSYNC(x,y)
13214 #endif
13215 
13216 /*
13217 ** The default size of a disk sector
13218 */
13219 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
13220 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
13221 #endif
13222 
13223 /*
13224 ** Temporary files are named starting with this prefix followed by 16 random
13225 ** alphanumeric characters, and no file extension. They are stored in the
13226 ** OS's standard temporary file directory, and are deleted prior to exit.
13227 ** If sqlite is being embedded in another program, you may wish to change the
13228 ** prefix to reflect your program's name, so that if your program exits
13229 ** prematurely, old temporary files can be easily identified. This can be done
13230 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
13231 **
13232 ** 2006-10-31: The default prefix used to be "sqlite_". But then
13233 ** Mcafee started using SQLite in their anti-virus product and it
13234 ** started putting files with the "sqlite" name in the c:/temp folder.
13235 ** This annoyed many windows users. Those users would then do a
13236 ** Google search for "sqlite", find the telephone numbers of the
13237 ** developers and call to wake them up at night and complain.
13238 ** For this reason, the default name prefix is changed to be "sqlite"
13239 ** spelled backwards. So the temp files are still identified, but
13240 ** anybody smart enough to figure out the code is also likely smart
13241 ** enough to know that calling the developer will not help get rid
13242 ** of the file.
13243 */
13244 #ifndef SQLITE_TEMP_FILE_PREFIX
13245 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
13246 #endif
13247 
13248 /*
13249 ** The following values may be passed as the second argument to
13250 ** sqlite3OsLock(). The various locks exhibit the following semantics:
13251 **
13252 ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
13253 ** RESERVED: A single process may hold a RESERVED lock on a file at
13254 ** any time. Other processes may hold and obtain new SHARED locks.
13255 ** PENDING: A single process may hold a PENDING lock on a file at
13256 ** any one time. Existing SHARED locks may persist, but no new
13257 ** SHARED locks may be obtained by other processes.
13258 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
13259 **
13260 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
13261 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
13262 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
13263 ** sqlite3OsLock().
13264 */
13265 #define NO_LOCK 0
13266 #define SHARED_LOCK 1
13267 #define RESERVED_LOCK 2
13268 #define PENDING_LOCK 3
13269 #define EXCLUSIVE_LOCK 4
13270 
13271 /*
13272 ** File Locking Notes: (Mostly about windows but also some info for Unix)
13273 **
13274 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
13275 ** those functions are not available. So we use only LockFile() and
13276 ** UnlockFile().
13277 **
13278 ** LockFile() prevents not just writing but also reading by other processes.
13279 ** A SHARED_LOCK is obtained by locking a single randomly-chosen
13280 ** byte out of a specific range of bytes. The lock byte is obtained at
13281 ** random so two separate readers can probably access the file at the
13282 ** same time, unless they are unlucky and choose the same lock byte.
13283 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
13284 ** There can only be one writer. A RESERVED_LOCK is obtained by locking
13285 ** a single byte of the file that is designated as the reserved lock byte.
13286 ** A PENDING_LOCK is obtained by locking a designated byte different from
13287 ** the RESERVED_LOCK byte.
13288 **
13289 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
13290 ** which means we can use reader/writer locks. When reader/writer locks
13291 ** are used, the lock is placed on the same range of bytes that is used
13292 ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
13293 ** will support two or more Win95 readers or two or more WinNT readers.
13294 ** But a single Win95 reader will lock out all WinNT readers and a single
13295 ** WinNT reader will lock out all other Win95 readers.
13296 **
13297 ** The following #defines specify the range of bytes used for locking.
13298 ** SHARED_SIZE is the number of bytes available in the pool from which
13299 ** a random byte is selected for a shared lock. The pool of bytes for
13300 ** shared locks begins at SHARED_FIRST.
13301 **
13302 ** The same locking strategy and
13303 ** byte ranges are used for Unix. This leaves open the possibility of having
13304 ** clients on win95, winNT, and unix all talking to the same shared file
13305 ** and all locking correctly. To do so would require that samba (or whatever
13306 ** tool is being used for file sharing) implements locks correctly between
13307 ** windows and unix. I'm guessing that isn't likely to happen, but by
13308 ** using the same locking range we are at least open to the possibility.
13309 **
13310 ** Locking in windows is manditory. For this reason, we cannot store
13311 ** actual data in the bytes used for locking. The pager never allocates
13312 ** the pages involved in locking therefore. SHARED_SIZE is selected so
13313 ** that all locks will fit on a single page even at the minimum page size.
13314 ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
13315 ** is set high so that we don't have to allocate an unused page except
13316 ** for very large databases. But one should test the page skipping logic
13317 ** by setting PENDING_BYTE low and running the entire regression suite.
13318 **
13319 ** Changing the value of PENDING_BYTE results in a subtly incompatible
13320 ** file format. Depending on how it is changed, you might not notice
13321 ** the incompatibility right away, even running a full regression test.
13322 ** The default location of PENDING_BYTE is the first byte past the
13323 ** 1GB boundary.
13324 **
13325 */
13326 #ifdef SQLITE_OMIT_WSD
13327 # define PENDING_BYTE (0x40000000)
13328 #else
13329 # define PENDING_BYTE sqlite3PendingByte
13330 #endif
13331 #define RESERVED_BYTE (PENDING_BYTE+1)
13332 #define SHARED_FIRST (PENDING_BYTE+2)
13333 #define SHARED_SIZE 510
13334 
13335 /*
13336 ** Wrapper around OS specific sqlite3_os_init() function.
13337 */
13338 SQLITE_PRIVATE int sqlite3OsInit(void);
13339 
13340 /*
13341 ** Functions for accessing sqlite3_file methods
13342 */
13343 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file*);
13344 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
13345 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
13346 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
13347 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
13348 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
13349 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
13350 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
13351 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
13352 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
13353 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
13354 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
13355 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
13356 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
13357 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
13358 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
13359 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
13360 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
13361 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
13362 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
13363 
13364 
13365 /*
13366 ** Functions for accessing sqlite3_vfs methods
13367 */
13368 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
13369 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
13370 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
13371 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
13372 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13373 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
13374 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
13375 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
13376 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
13377 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
13378 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
13379 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
13380 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs*);
13381 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
13382 
13383 /*
13384 ** Convenience functions for opening and closing files using
13385 ** sqlite3_malloc() to obtain space for the file-handle structure.
13386 */
13387 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
13388 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *);
13389 
13390 #endif /* _SQLITE_OS_H_ */
13391 
13392 /************** End of os.h **************************************************/
13393 /************** Continuing where we left off in sqliteInt.h ******************/
13394 /************** Include mutex.h in the middle of sqliteInt.h *****************/
13395 /************** Begin file mutex.h *******************************************/
13396 /*
13397 ** 2007 August 28
13398 **
13399 ** The author disclaims copyright to this source code. In place of
13400 ** a legal notice, here is a blessing:
13401 **
13402 ** May you do good and not evil.
13403 ** May you find forgiveness for yourself and forgive others.
13404 ** May you share freely, never taking more than you give.
13405 **
13406 *************************************************************************
13407 **
13408 ** This file contains the common header for all mutex implementations.
13409 ** The sqliteInt.h header #includes this file so that it is available
13410 ** to all source files. We break it out in an effort to keep the code
13411 ** better organized.
13412 **
13413 ** NOTE: source files should *not* #include this header file directly.
13414 ** Source files should #include the sqliteInt.h file and let that file
13415 ** include this one indirectly.
13416 */
13417 
13418 
13419 /*
13420 ** Figure out what version of the code to use. The choices are
13421 **
13422 ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
13423 ** mutexes implementation cannot be overridden
13424 ** at start-time.
13425 **
13426 ** SQLITE_MUTEX_NOOP For single-threaded applications. No
13427 ** mutual exclusion is provided. But this
13428 ** implementation can be overridden at
13429 ** start-time.
13430 **
13431 ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
13432 **
13433 ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
13434 */
13435 #if !SQLITE_THREADSAFE
13436 # define SQLITE_MUTEX_OMIT
13437 #endif
13438 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
13439 # if SQLITE_OS_UNIX
13440 # define SQLITE_MUTEX_PTHREADS
13441 # elif SQLITE_OS_WIN
13442 # define SQLITE_MUTEX_W32
13443 # else
13444 # define SQLITE_MUTEX_NOOP
13445 # endif
13446 #endif
13447 
13448 #ifdef SQLITE_MUTEX_OMIT
13449 /*
13450 ** If this is a no-op implementation, implement everything as macros.
13451 */
13452 #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
13453 #define sqlite3_mutex_free(X)
13454 #define sqlite3_mutex_enter(X)
13455 #define sqlite3_mutex_try(X) SQLITE_OK
13456 #define sqlite3_mutex_leave(X)
13457 #define sqlite3_mutex_held(X) ((void)(X),1)
13458 #define sqlite3_mutex_notheld(X) ((void)(X),1)
13459 #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
13460 #define sqlite3MutexInit() SQLITE_OK
13461 #define sqlite3MutexEnd()
13462 #define MUTEX_LOGIC(X)
13463 #else
13464 #define MUTEX_LOGIC(X) X
13465 #endif /* defined(SQLITE_MUTEX_OMIT) */
13466 
13467 /************** End of mutex.h ***********************************************/
13468 /************** Continuing where we left off in sqliteInt.h ******************/
13469 
13470 /* The SQLITE_EXTRA_DURABLE compile-time option used to set the default
13471 ** synchronous setting to EXTRA. It is no longer supported.
13472 */
13473 #ifdef SQLITE_EXTRA_DURABLE
13474 # warning Use SQLITE_DEFAULT_SYNCHRONOUS=3 instead of SQLITE_EXTRA_DURABLE
13475 # define SQLITE_DEFAULT_SYNCHRONOUS 3
13476 #endif
13477 
13478 /*
13479 ** Default synchronous levels.
13480 **
13481 ** Note that (for historcal reasons) the PAGER_SYNCHRONOUS_* macros differ
13482 ** from the SQLITE_DEFAULT_SYNCHRONOUS value by 1.
13483 **
13484 ** PAGER_SYNCHRONOUS DEFAULT_SYNCHRONOUS
13485 ** OFF 1 0
13486 ** NORMAL 2 1
13487 ** FULL 3 2
13488 ** EXTRA 4 3
13489 **
13490 ** The "PRAGMA synchronous" statement also uses the zero-based numbers.
13491 ** In other words, the zero-based numbers are used for all external interfaces
13492 ** and the one-based values are used internally.
13493 */
13494 #ifndef SQLITE_DEFAULT_SYNCHRONOUS
13495 # define SQLITE_DEFAULT_SYNCHRONOUS (PAGER_SYNCHRONOUS_FULL-1)
13496 #endif
13497 #ifndef SQLITE_DEFAULT_WAL_SYNCHRONOUS
13498 # define SQLITE_DEFAULT_WAL_SYNCHRONOUS SQLITE_DEFAULT_SYNCHRONOUS
13499 #endif
13500 
13501 /*
13502 ** Each database file to be accessed by the system is an instance
13503 ** of the following structure. There are normally two of these structures
13504 ** in the sqlite.aDb[] array. aDb[0] is the main database file and
13505 ** aDb[1] is the database file used to hold temporary tables. Additional
13506 ** databases may be attached.
13507 */
13508 struct Db {
13509  char *zName; /* Name of this database */
13510  Btree *pBt; /* The B*Tree structure for this database file */
13511  u8 safety_level; /* How aggressive at syncing data to disk */
13512  u8 bSyncSet; /* True if "PRAGMA synchronous=N" has been run */
13513  Schema *pSchema; /* Pointer to database schema (possibly shared) */
13514 };
13515 
13516 /*
13517 ** An instance of the following structure stores a database schema.
13518 **
13519 ** Most Schema objects are associated with a Btree. The exception is
13520 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
13521 ** In shared cache mode, a single Schema object can be shared by multiple
13522 ** Btrees that refer to the same underlying BtShared object.
13523 **
13524 ** Schema objects are automatically deallocated when the last Btree that
13525 ** references them is destroyed. The TEMP Schema is manually freed by
13526 ** sqlite3_close().
13527 *
13528 ** A thread must be holding a mutex on the corresponding Btree in order
13529 ** to access Schema content. This implies that the thread must also be
13530 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
13531 ** For a TEMP Schema, only the connection mutex is required.
13532 */
13533 struct Schema {
13534  int schema_cookie; /* Database schema version number for this file */
13535  int iGeneration; /* Generation counter. Incremented with each change */
13536  Hash tblHash; /* All tables indexed by name */
13537  Hash idxHash; /* All (named) indices indexed by name */
13538  Hash trigHash; /* All triggers indexed by name */
13539  Hash fkeyHash; /* All foreign keys by referenced table name */
13540  Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
13541  u8 file_format; /* Schema format version for this file */
13542  u8 enc; /* Text encoding used by this database */
13543  u16 schemaFlags; /* Flags associated with this schema */
13544  int cache_size; /* Number of pages to use in the cache */
13545 };
13546 
13547 /*
13548 ** These macros can be used to test, set, or clear bits in the
13549 ** Db.pSchema->flags field.
13550 */
13551 #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
13552 #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
13553 #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
13554 #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
13555 
13556 /*
13557 ** Allowed values for the DB.pSchema->flags field.
13558 **
13559 ** The DB_SchemaLoaded flag is set after the database schema has been
13560 ** read into internal hash tables.
13561 **
13562 ** DB_UnresetViews means that one or more views have column names that
13563 ** have been filled out. If the schema changes, these column names might
13564 ** changes and so the view will need to be reset.
13565 */
13566 #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
13567 #define DB_UnresetViews 0x0002 /* Some views have defined column names */
13568 #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
13569 
13570 /*
13571 ** The number of different kinds of things that can be limited
13572 ** using the sqlite3_limit() interface.
13573 */
13574 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
13575 
13576 /*
13577 ** Lookaside malloc is a set of fixed-size buffers that can be used
13578 ** to satisfy small transient memory allocation requests for objects
13579 ** associated with a particular database connection. The use of
13580 ** lookaside malloc provides a significant performance enhancement
13581 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
13582 ** SQL statements.
13583 **
13584 ** The Lookaside structure holds configuration information about the
13585 ** lookaside malloc subsystem. Each available memory allocation in
13586 ** the lookaside subsystem is stored on a linked list of LookasideSlot
13587 ** objects.
13588 **
13589 ** Lookaside allocations are only allowed for objects that are associated
13590 ** with a particular database connection. Hence, schema information cannot
13591 ** be stored in lookaside because in shared cache mode the schema information
13592 ** is shared by multiple database connections. Therefore, while parsing
13593 ** schema information, the Lookaside.bEnabled flag is cleared so that
13594 ** lookaside allocations are not used to construct the schema objects.
13595 */
13596 struct Lookaside {
13597  u32 bDisable; /* Only operate the lookaside when zero */
13598  u16 sz; /* Size of each buffer in bytes */
13599  u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
13600  int nOut; /* Number of buffers currently checked out */
13601  int mxOut; /* Highwater mark for nOut */
13602  int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
13603  LookasideSlot *pFree; /* List of available buffers */
13604  void *pStart; /* First byte of available memory space */
13605  void *pEnd; /* First byte past end of available space */
13606 };
13608  LookasideSlot *pNext; /* Next buffer in the list of free buffers */
13609 };
13610 
13611 /*
13612 ** A hash table for built-in function definitions. (Application-defined
13613 ** functions use a regular table table from hash.h.)
13614 **
13615 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
13616 ** Collisions are on the FuncDef.u.pHash chain.
13617 */
13618 #define SQLITE_FUNC_HASH_SZ 23
13619 struct FuncDefHash {
13620  FuncDef *a[SQLITE_FUNC_HASH_SZ]; /* Hash table for functions */
13621 };
13622 
13623 #ifdef SQLITE_USER_AUTHENTICATION
13624 /*
13625 ** Information held in the "sqlite3" database connection object and used
13626 ** to manage user authentication.
13627 */
13628 typedef struct sqlite3_userauth sqlite3_userauth;
13629 struct sqlite3_userauth {
13630  u8 authLevel; /* Current authentication level */
13631  int nAuthPW; /* Size of the zAuthPW in bytes */
13632  char *zAuthPW; /* Password used to authenticate */
13633  char *zAuthUser; /* User name used to authenticate */
13634 };
13635 
13636 /* Allowed values for sqlite3_userauth.authLevel */
13637 #define UAUTH_Unknown 0 /* Authentication not yet checked */
13638 #define UAUTH_Fail 1 /* User authentication failed */
13639 #define UAUTH_User 2 /* Authenticated as a normal user */
13640 #define UAUTH_Admin 3 /* Authenticated as an administrator */
13641 
13642 /* Functions used only by user authorization logic */
13643 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
13644 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
13645 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
13646 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
13647 
13648 #endif /* SQLITE_USER_AUTHENTICATION */
13649 
13650 /*
13651 ** typedef for the authorization callback function.
13652 */
13653 #ifdef SQLITE_USER_AUTHENTICATION
13654  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13655  const char*, const char*);
13656 #else
13657  typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
13658  const char*);
13659 #endif
13660 
13661 
13662 /*
13663 ** Each database connection is an instance of the following structure.
13664 */
13665 struct sqlite3 {
13666  sqlite3_vfs *pVfs; /* OS Interface */
13667  struct Vdbe *pVdbe; /* List of active virtual machines */
13668  CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
13669  sqlite3_mutex *mutex; /* Connection mutex */
13670  Db *aDb; /* All backends */
13671  int nDb; /* Number of backends currently in use */
13672  int flags; /* Miscellaneous flags. See below */
13673  i64 lastRowid; /* ROWID of most recent insert (see above) */
13674  i64 szMmap; /* Default mmap_size setting */
13675  unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
13676  int errCode; /* Most recent error code (SQLITE_*) */
13677  int errMask; /* & result codes with this before returning */
13678  int iSysErrno; /* Errno value from last system error */
13679  u16 dbOptFlags; /* Flags to enable/disable optimizations */
13680  u8 enc; /* Text encoding */
13681  u8 autoCommit; /* The auto-commit flag. */
13682  u8 temp_store; /* 1: file 2: memory 0: default */
13683  u8 mallocFailed; /* True if we have seen a malloc failure */
13684  u8 bBenignMalloc; /* Do not require OOMs if true */
13685  u8 dfltLockMode; /* Default locking-mode for attached dbs */
13686  signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
13687  u8 suppressErr; /* Do not issue error messages if true */
13688  u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
13689  u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
13690  int nextPagesize; /* Pagesize after VACUUM if >0 */
13691  u32 magic; /* Magic number for detect library misuse */
13692  int nChange; /* Value returned by sqlite3_changes() */
13693  int nTotalChange; /* Value returned by sqlite3_total_changes() */
13694  int aLimit[SQLITE_N_LIMIT]; /* Limits */
13695  int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
13696  struct sqlite3InitInfo { /* Information used during initialization */
13697  int newTnum; /* Rootpage of table being initialized */
13698  u8 iDb; /* Which db file is being initialized */
13699  u8 busy; /* TRUE if currently initializing */
13700  u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
13701  u8 imposterTable; /* Building an imposter table */
13702  } init;
13703  int nVdbeActive; /* Number of VDBEs currently running */
13704  int nVdbeRead; /* Number of active VDBEs that read or write */
13705  int nVdbeWrite; /* Number of active VDBEs that read and write */
13706  int nVdbeExec; /* Number of nested calls to VdbeExec() */
13707  int nVDestroy; /* Number of active OP_VDestroy operations */
13708  int nExtension; /* Number of loaded extensions */
13709  void **aExtension; /* Array of shared library handles */
13710  void (*xTrace)(void*,const char*); /* Trace function */
13711  void *pTraceArg; /* Argument to the trace function */
13712  void (*xProfile)(void*,const char*,u64); /* Profiling function */
13713  void *pProfileArg; /* Argument to profile function */
13714  void *pCommitArg; /* Argument to xCommitCallback() */
13715  int (*xCommitCallback)(void*); /* Invoked at every commit. */
13716  void *pRollbackArg; /* Argument to xRollbackCallback() */
13717  void (*xRollbackCallback)(void*); /* Invoked at every commit. */
13718  void *pUpdateArg;
13719  void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
13720 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
13721  void *pPreUpdateArg; /* First argument to xPreUpdateCallback */
13722  void (*xPreUpdateCallback)( /* Registered using sqlite3_preupdate_hook() */
13723  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64
13724  );
13725  PreUpdate *pPreUpdate; /* Context for active pre-update callback */
13726 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
13727 #ifndef SQLITE_OMIT_WAL
13728  int (*xWalCallback)(void *, sqlite3 *, const char *, int);
13729  void *pWalArg;
13730 #endif
13731  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
13732  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
13734  sqlite3_value *pErr; /* Most recent error message */
13735  union {
13736  volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
13737  double notUsed1; /* Spacer */
13738  } u1;
13739  Lookaside lookaside; /* Lookaside malloc configuration */
13740 #ifndef SQLITE_OMIT_AUTHORIZATION
13741  sqlite3_xauth xAuth; /* Access authorization function */
13742  void *pAuthArg; /* 1st argument to the access auth function */
13743 #endif
13744 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
13745  int (*xProgress)(void *); /* The progress callback */
13746  void *pProgressArg; /* Argument to the progress callback */
13747  unsigned nProgressOps; /* Number of opcodes for progress callback */
13748 #endif
13749 #ifndef SQLITE_OMIT_VIRTUALTABLE
13750  int nVTrans; /* Allocated size of aVTrans */
13751  Hash aModule; /* populated by sqlite3_create_module() */
13752  VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
13753  VTable **aVTrans; /* Virtual tables with open transactions */
13754  VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
13755 #endif
13756  Hash aFunc; /* Hash table of connection functions */
13757  Hash aCollSeq; /* All collating sequences */
13758  BusyHandler busyHandler; /* Busy callback */
13759  Db aDbStatic[2]; /* Static space for the 2 default backends */
13760  Savepoint *pSavepoint; /* List of active savepoints */
13761  int busyTimeout; /* Busy handler timeout, in msec */
13762  int nSavepoint; /* Number of non-transaction savepoints */
13763  int nStatement; /* Number of nested statement-transactions */
13764  i64 nDeferredCons; /* Net deferred constraints this transaction. */
13765  i64 nDeferredImmCons; /* Net deferred immediate constraints */
13766  int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
13767 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13768  /* The following variables are all protected by the STATIC_MASTER
13769  ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
13770  **
13771  ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
13772  ** unlock so that it can proceed.
13773  **
13774  ** When X.pBlockingConnection==Y, that means that something that X tried
13775  ** tried to do recently failed with an SQLITE_LOCKED error due to locks
13776  ** held by Y.
13777  */
13778  sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
13779  sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
13780  void *pUnlockArg; /* Argument to xUnlockNotify */
13781  void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
13782  sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
13783 #endif
13784 #ifdef SQLITE_USER_AUTHENTICATION
13785  sqlite3_userauth auth; /* User authentication information */
13786 #endif
13787 };
13788 
13789 /*
13790 ** A macro to discover the encoding of a database.
13791 */
13792 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
13793 #define ENC(db) ((db)->enc)
13794 
13795 /*
13796 ** Possible values for the sqlite3.flags.
13797 **
13798 ** Value constraints (enforced via assert()):
13799 ** SQLITE_FullFSync == PAGER_FULLFSYNC
13800 ** SQLITE_CkptFullFSync == PAGER_CKPT_FULLFSYNC
13801 ** SQLITE_CacheSpill == PAGER_CACHE_SPILL
13802 */
13803 #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
13804 #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
13805 #define SQLITE_FullColNames 0x00000004 /* Show full column names on SELECT */
13806 #define SQLITE_FullFSync 0x00000008 /* Use full fsync on the backend */
13807 #define SQLITE_CkptFullFSync 0x00000010 /* Use full fsync for checkpoint */
13808 #define SQLITE_CacheSpill 0x00000020 /* OK to spill pager cache */
13809 #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
13810 #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
13811  /* DELETE, or UPDATE and return */
13812  /* the count using a callback. */
13813 #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
13814  /* result set is empty */
13815 #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
13816 #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
13817 #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
13818 #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
13819 #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
13820 #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
13821 #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
13822 #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
13823 #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
13824 #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
13825 #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
13826 #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
13827 #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
13828 #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
13829 #define SQLITE_LoadExtFunc 0x00800000 /* Enable load_extension() SQL func */
13830 #define SQLITE_EnableTrigger 0x01000000 /* True to enable triggers */
13831 #define SQLITE_DeferFKs 0x02000000 /* Defer all FK constraints */
13832 #define SQLITE_QueryOnly 0x04000000 /* Disable database changes */
13833 #define SQLITE_VdbeEQP 0x08000000 /* Debug EXPLAIN QUERY PLAN */
13834 #define SQLITE_Vacuum 0x10000000 /* Currently in a VACUUM */
13835 #define SQLITE_CellSizeCk 0x20000000 /* Check btree cell sizes on load */
13836 #define SQLITE_Fts3Tokenizer 0x40000000 /* Enable fts3_tokenizer(2) */
13837 
13838 
13839 /*
13840 ** Bits of the sqlite3.dbOptFlags field that are used by the
13841 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
13842 ** selectively disable various optimizations.
13843 */
13844 #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
13845 #define SQLITE_ColumnCache 0x0002 /* Column cache */
13846 #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
13847 #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
13848 /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
13849 #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
13850 #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
13851 #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
13852 #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
13853 #define SQLITE_Transitive 0x0200 /* Transitive constraints */
13854 #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
13855 #define SQLITE_Stat34 0x0800 /* Use STAT3 or STAT4 data */
13856 #define SQLITE_CursorHints 0x2000 /* Add OP_CursorHint opcodes */
13857 #define SQLITE_AllOpts 0xffff /* All optimizations */
13858 
13859 /*
13860 ** Macros for testing whether or not optimizations are enabled or disabled.
13861 */
13862 #ifndef SQLITE_OMIT_BUILTIN_TEST
13863 #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
13864 #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
13865 #else
13866 #define OptimizationDisabled(db, mask) 0
13867 #define OptimizationEnabled(db, mask) 1
13868 #endif
13869 
13870 /*
13871 ** Return true if it OK to factor constant expressions into the initialization
13872 ** code. The argument is a Parse object for the code generator.
13873 */
13874 #define ConstFactorOk(P) ((P)->okConstFactor)
13875 
13876 /*
13877 ** Possible values for the sqlite.magic field.
13878 ** The numbers are obtained at random and have no special meaning, other
13879 ** than being distinct from one another.
13880 */
13881 #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
13882 #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
13883 #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
13884 #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
13885 #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
13886 #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
13887 
13888 /*
13889 ** Each SQL function is defined by an instance of the following
13890 ** structure. For global built-in functions (ex: substr(), max(), count())
13891 ** a pointer to this structure is held in the sqlite3BuiltinFunctions object.
13892 ** For per-connection application-defined functions, a pointer to this
13893 ** structure is held in the db->aHash hash table.
13894 **
13895 ** The u.pHash field is used by the global built-ins. The u.pDestructor
13896 ** field is used by per-connection app-def functions.
13897 */
13898 struct FuncDef {
13899  i8 nArg; /* Number of arguments. -1 means unlimited */
13900  u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
13901  void *pUserData; /* User data parameter */
13902  FuncDef *pNext; /* Next function with same name */
13903  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**); /* func or agg-step */
13904  void (*xFinalize)(sqlite3_context*); /* Agg finalizer */
13905  const char *zName; /* SQL name of the function. */
13906  union {
13907  FuncDef *pHash; /* Next with a different name but the same hash */
13908  FuncDestructor *pDestructor; /* Reference counted destructor function */
13909  } u;
13910 };
13911 
13912 /*
13913 ** This structure encapsulates a user-function destructor callback (as
13914 ** configured using create_function_v2()) and a reference counter. When
13915 ** create_function_v2() is called to create a function with a destructor,
13916 ** a single object of this type is allocated. FuncDestructor.nRef is set to
13917 ** the number of FuncDef objects created (either 1 or 3, depending on whether
13918 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
13919 ** member of each of the new FuncDef objects is set to point to the allocated
13920 ** FuncDestructor.
13921 **
13922 ** Thereafter, when one of the FuncDef objects is deleted, the reference
13923 ** count on this object is decremented. When it reaches 0, the destructor
13924 ** is invoked and the FuncDestructor structure freed.
13925 */
13927  int nRef;
13928  void (*xDestroy)(void *);
13929  void *pUserData;
13930 };
13931 
13932 /*
13933 ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
13934 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. And
13935 ** SQLITE_FUNC_CONSTANT must be the same as SQLITE_DETERMINISTIC. There
13936 ** are assert() statements in the code to verify this.
13937 **
13938 ** Value constraints (enforced via assert()):
13939 ** SQLITE_FUNC_MINMAX == NC_MinMaxAgg == SF_MinMaxAgg
13940 ** SQLITE_FUNC_LENGTH == OPFLAG_LENGTHARG
13941 ** SQLITE_FUNC_TYPEOF == OPFLAG_TYPEOFARG
13942 ** SQLITE_FUNC_CONSTANT == SQLITE_DETERMINISTIC from the API
13943 ** SQLITE_FUNC_ENCMASK depends on SQLITE_UTF* macros in the API
13944 */
13945 #define SQLITE_FUNC_ENCMASK 0x0003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
13946 #define SQLITE_FUNC_LIKE 0x0004 /* Candidate for the LIKE optimization */
13947 #define SQLITE_FUNC_CASE 0x0008 /* Case-sensitive LIKE-type function */
13948 #define SQLITE_FUNC_EPHEM 0x0010 /* Ephemeral. Delete with VDBE */
13949 #define SQLITE_FUNC_NEEDCOLL 0x0020 /* sqlite3GetFuncCollSeq() might be called*/
13950 #define SQLITE_FUNC_LENGTH 0x0040 /* Built-in length() function */
13951 #define SQLITE_FUNC_TYPEOF 0x0080 /* Built-in typeof() function */
13952 #define SQLITE_FUNC_COUNT 0x0100 /* Built-in count(*) aggregate */
13953 #define SQLITE_FUNC_COALESCE 0x0200 /* Built-in coalesce() or ifnull() */
13954 #define SQLITE_FUNC_UNLIKELY 0x0400 /* Built-in unlikely() function */
13955 #define SQLITE_FUNC_CONSTANT 0x0800 /* Constant inputs give a constant output */
13956 #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
13957 #define SQLITE_FUNC_SLOCHNG 0x2000 /* "Slow Change". Value constant during a
13958  ** single query - might change over time */
13959 
13960 /*
13961 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
13962 ** used to create the initializers for the FuncDef structures.
13963 **
13964 ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
13965 ** Used to create a scalar function definition of a function zName
13966 ** implemented by C function xFunc that accepts nArg arguments. The
13967 ** value passed as iArg is cast to a (void*) and made available
13968 ** as the user-data (sqlite3_user_data()) for the function. If
13969 ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
13970 **
13971 ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
13972 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
13973 **
13974 ** DFUNCTION(zName, nArg, iArg, bNC, xFunc)
13975 ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag and
13976 ** adds the SQLITE_FUNC_SLOCHNG flag. Used for date & time functions
13977 ** and functions like sqlite_version() that can change, but not during
13978 ** a single query.
13979 **
13980 ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
13981 ** Used to create an aggregate function definition implemented by
13982 ** the C functions xStep and xFinal. The first four parameters
13983 ** are interpreted in the same way as the first 4 parameters to
13984 ** FUNCTION().
13985 **
13986 ** LIKEFUNC(zName, nArg, pArg, flags)
13987 ** Used to create a scalar function definition of a function zName
13988 ** that accepts nArg arguments and is implemented by a call to C
13989 ** function likeFunc. Argument pArg is cast to a (void *) and made
13990 ** available as the function user-data (sqlite3_user_data()). The
13991 ** FuncDef.flags variable is set to the value passed as the flags
13992 ** parameter.
13993 */
13994 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
13995  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
13996  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
13997 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
13998  {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
13999  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14000 #define DFUNCTION(zName, nArg, iArg, bNC, xFunc) \
14001  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14002  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14003 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
14004  {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
14005  SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, #zName, {0} }
14006 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
14007  {nArg, SQLITE_FUNC_SLOCHNG|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
14008  pArg, 0, xFunc, 0, #zName, }
14009 #define LIKEFUNC(zName, nArg, arg, flags) \
14010  {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
14011  (void *)arg, 0, likeFunc, 0, #zName, {0} }
14012 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
14013  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
14014  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14015 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
14016  {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
14017  SQLITE_INT_TO_PTR(arg), 0, xStep,xFinal,#zName, {0}}
14018 
14019 /*
14020 ** All current savepoints are stored in a linked list starting at
14021 ** sqlite3.pSavepoint. The first element in the list is the most recently
14022 ** opened savepoint. Savepoints are added to the list by the vdbe
14023 ** OP_Savepoint instruction.
14024 */
14025 struct Savepoint {
14026  char *zName; /* Savepoint name (nul-terminated) */
14027  i64 nDeferredCons; /* Number of deferred fk violations */
14028  i64 nDeferredImmCons; /* Number of deferred imm fk. */
14029  Savepoint *pNext; /* Parent savepoint (if any) */
14030 };
14031 
14032 /*
14033 ** The following are used as the second parameter to sqlite3Savepoint(),
14034 ** and as the P1 argument to the OP_Savepoint instruction.
14035 */
14036 #define SAVEPOINT_BEGIN 0
14037 #define SAVEPOINT_RELEASE 1
14038 #define SAVEPOINT_ROLLBACK 2
14039 
14040 
14041 /*
14042 ** Each SQLite module (virtual table definition) is defined by an
14043 ** instance of the following structure, stored in the sqlite3.aModule
14044 ** hash table.
14045 */
14046 struct Module {
14047  const sqlite3_module *pModule; /* Callback pointers */
14048  const char *zName; /* Name passed to create_module() */
14049  void *pAux; /* pAux passed to create_module() */
14050  void (*xDestroy)(void *); /* Module destructor function */
14051  Table *pEpoTab; /* Eponymous table for this module */
14052 };
14053 
14054 /*
14055 ** information about each column of an SQL table is held in an instance
14056 ** of this structure.
14057 */
14058 struct Column {
14059  char *zName; /* Name of this column, \000, then the type */
14060  Expr *pDflt; /* Default value of this column */
14061  char *zColl; /* Collating sequence. If NULL, use the default */
14062  u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
14063  char affinity; /* One of the SQLITE_AFF_... values */
14064  u8 szEst; /* Estimated size of value in this column. sizeof(INT)==1 */
14065  u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
14066 };
14067 
14068 /* Allowed values for Column.colFlags:
14069 */
14070 #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
14071 #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
14072 #define COLFLAG_HASTYPE 0x0004 /* Type name follows column name */
14073 
14074 /*
14075 ** A "Collating Sequence" is defined by an instance of the following
14076 ** structure. Conceptually, a collating sequence consists of a name and
14077 ** a comparison routine that defines the order of that sequence.
14078 **
14079 ** If CollSeq.xCmp is NULL, it means that the
14080 ** collating sequence is undefined. Indices built on an undefined
14081 ** collating sequence may not be read or written.
14082 */
14083 struct CollSeq {
14084  char *zName; /* Name of the collating sequence, UTF-8 encoded */
14085  u8 enc; /* Text encoding handled by xCmp() */
14086  void *pUser; /* First argument to xCmp() */
14087  int (*xCmp)(void*,int, const void*, int, const void*);
14088  void (*xDel)(void*); /* Destructor for pUser */
14089 };
14090 
14091 /*
14092 ** A sort order can be either ASC or DESC.
14093 */
14094 #define SQLITE_SO_ASC 0 /* Sort in ascending order */
14095 #define SQLITE_SO_DESC 1 /* Sort in ascending order */
14096 #define SQLITE_SO_UNDEFINED -1 /* No sort order specified */
14097 
14098 /*
14099 ** Column affinity types.
14100 **
14101 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
14102 ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
14103 ** the speed a little by numbering the values consecutively.
14104 **
14105 ** But rather than start with 0 or 1, we begin with 'A'. That way,
14106 ** when multiple affinity types are concatenated into a string and
14107 ** used as the P4 operand, they will be more readable.
14108 **
14109 ** Note also that the numeric types are grouped together so that testing
14110 ** for a numeric type is a single comparison. And the BLOB type is first.
14111 */
14112 #define SQLITE_AFF_BLOB 'A'
14113 #define SQLITE_AFF_TEXT 'B'
14114 #define SQLITE_AFF_NUMERIC 'C'
14115 #define SQLITE_AFF_INTEGER 'D'
14116 #define SQLITE_AFF_REAL 'E'
14117 
14118 #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
14119 
14120 /*
14121 ** The SQLITE_AFF_MASK values masks off the significant bits of an
14122 ** affinity value.
14123 */
14124 #define SQLITE_AFF_MASK 0x47
14125 
14126 /*
14127 ** Additional bit values that can be ORed with an affinity without
14128 ** changing the affinity.
14129 **
14130 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
14131 ** It causes an assert() to fire if either operand to a comparison
14132 ** operator is NULL. It is added to certain comparison operators to
14133 ** prove that the operands are always NOT NULL.
14134 */
14135 #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
14136 #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
14137 #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
14138 #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
14139 
14140 /*
14141 ** An object of this type is created for each virtual table present in
14142 ** the database schema.
14143 **
14144 ** If the database schema is shared, then there is one instance of this
14145 ** structure for each database connection (sqlite3*) that uses the shared
14146 ** schema. This is because each database connection requires its own unique
14147 ** instance of the sqlite3_vtab* handle used to access the virtual table
14148 ** implementation. sqlite3_vtab* handles can not be shared between
14149 ** database connections, even when the rest of the in-memory database
14150 ** schema is shared, as the implementation often stores the database
14151 ** connection handle passed to it via the xConnect() or xCreate() method
14152 ** during initialization internally. This database connection handle may
14153 ** then be used by the virtual table implementation to access real tables
14154 ** within the database. So that they appear as part of the callers
14155 ** transaction, these accesses need to be made via the same database
14156 ** connection as that used to execute SQL operations on the virtual table.
14157 **
14158 ** All VTable objects that correspond to a single table in a shared
14159 ** database schema are initially stored in a linked-list pointed to by
14160 ** the Table.pVTable member variable of the corresponding Table object.
14161 ** When an sqlite3_prepare() operation is required to access the virtual
14162 ** table, it searches the list for the VTable that corresponds to the
14163 ** database connection doing the preparing so as to use the correct
14164 ** sqlite3_vtab* handle in the compiled query.
14165 **
14166 ** When an in-memory Table object is deleted (for example when the
14167 ** schema is being reloaded for some reason), the VTable objects are not
14168 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
14169 ** immediately. Instead, they are moved from the Table.pVTable list to
14170 ** another linked list headed by the sqlite3.pDisconnect member of the
14171 ** corresponding sqlite3 structure. They are then deleted/xDisconnected
14172 ** next time a statement is prepared using said sqlite3*. This is done
14173 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
14174 ** Refer to comments above function sqlite3VtabUnlockList() for an
14175 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
14176 ** list without holding the corresponding sqlite3.mutex mutex.
14177 **
14178 ** The memory for objects of this type is always allocated by
14179 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
14180 ** the first argument.
14181 */
14182 struct VTable {
14183  sqlite3 *db; /* Database connection associated with this table */
14184  Module *pMod; /* Pointer to module implementation */
14185  sqlite3_vtab *pVtab; /* Pointer to vtab instance */
14186  int nRef; /* Number of pointers to this structure */
14187  u8 bConstraint; /* True if constraints are supported */
14188  int iSavepoint; /* Depth of the SAVEPOINT stack */
14189  VTable *pNext; /* Next in linked list (see above) */
14190 };
14191 
14192 /*
14193 ** The schema for each SQL table and view is represented in memory
14194 ** by an instance of the following structure.
14195 */
14196 struct Table {
14197  char *zName; /* Name of the table or view */
14198  Column *aCol; /* Information about each column */
14199  Index *pIndex; /* List of SQL indexes on this table. */
14200  Select *pSelect; /* NULL for tables. Points to definition if a view. */
14201  FKey *pFKey; /* Linked list of all foreign keys in this table */
14202  char *zColAff; /* String defining the affinity of each column */
14203  ExprList *pCheck; /* All CHECK constraints */
14204  /* ... also used as column name list in a VIEW */
14205  int tnum; /* Root BTree page for this table */
14206  i16 iPKey; /* If not negative, use aCol[iPKey] as the rowid */
14207  i16 nCol; /* Number of columns in this table */
14208  u16 nRef; /* Number of pointers to this Table */
14209  LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
14210  LogEst szTabRow; /* Estimated size of each table row in bytes */
14211 #ifdef SQLITE_ENABLE_COSTMULT
14212  LogEst costMult; /* Cost multiplier for using this table */
14213 #endif
14214  u8 tabFlags; /* Mask of TF_* values */
14215  u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
14216 #ifndef SQLITE_OMIT_ALTERTABLE
14217  int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
14218 #endif
14219 #ifndef SQLITE_OMIT_VIRTUALTABLE
14220  int nModuleArg; /* Number of arguments to the module */
14221  char **azModuleArg; /* 0: module 1: schema 2: vtab name 3...: args */
14222  VTable *pVTable; /* List of VTable objects. */
14223 #endif
14224  Trigger *pTrigger; /* List of triggers stored in pSchema */
14225  Schema *pSchema; /* Schema that contains this table */
14226  Table *pNextZombie; /* Next on the Parse.pZombieTab list */
14227 };
14228 
14229 /*
14230 ** Allowed values for Table.tabFlags.
14231 **
14232 ** TF_OOOHidden applies to tables or view that have hidden columns that are
14233 ** followed by non-hidden columns. Example: "CREATE VIRTUAL TABLE x USING
14234 ** vtab1(a HIDDEN, b);". Since "b" is a non-hidden column but "a" is hidden,
14235 ** the TF_OOOHidden attribute would apply in this case. Such tables require
14236 ** special handling during INSERT processing.
14237 */
14238 #define TF_Readonly 0x01 /* Read-only system table */
14239 #define TF_Ephemeral 0x02 /* An ephemeral table */
14240 #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
14241 #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
14242 #define TF_Virtual 0x10 /* Is a virtual table */
14243 #define TF_WithoutRowid 0x20 /* No rowid. PRIMARY KEY is the key */
14244 #define TF_NoVisibleRowid 0x40 /* No user-visible "rowid" column */
14245 #define TF_OOOHidden 0x80 /* Out-of-Order hidden columns */
14246 
14247 
14248 /*
14249 ** Test to see whether or not a table is a virtual table. This is
14250 ** done as a macro so that it will be optimized out when virtual
14251 ** table support is omitted from the build.
14252 */
14253 #ifndef SQLITE_OMIT_VIRTUALTABLE
14254 # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
14255 #else
14256 # define IsVirtual(X) 0
14257 #endif
14258 
14259 /*
14260 ** Macros to determine if a column is hidden. IsOrdinaryHiddenColumn()
14261 ** only works for non-virtual tables (ordinary tables and views) and is
14262 ** always false unless SQLITE_ENABLE_HIDDEN_COLUMNS is defined. The
14263 ** IsHiddenColumn() macro is general purpose.
14264 */
14265 #if defined(SQLITE_ENABLE_HIDDEN_COLUMNS)
14266 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14267 # define IsOrdinaryHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14268 #elif !defined(SQLITE_OMIT_VIRTUALTABLE)
14269 # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
14270 # define IsOrdinaryHiddenColumn(X) 0
14271 #else
14272 # define IsHiddenColumn(X) 0
14273 # define IsOrdinaryHiddenColumn(X) 0
14274 #endif
14275 
14276 
14277 /* Does the table have a rowid */
14278 #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
14279 #define VisibleRowid(X) (((X)->tabFlags & TF_NoVisibleRowid)==0)
14280 
14281 /*
14282 ** Each foreign key constraint is an instance of the following structure.
14283 **
14284 ** A foreign key is associated with two tables. The "from" table is
14285 ** the table that contains the REFERENCES clause that creates the foreign
14286 ** key. The "to" table is the table that is named in the REFERENCES clause.
14287 ** Consider this example:
14288 **
14289 ** CREATE TABLE ex1(
14290 ** a INTEGER PRIMARY KEY,
14291 ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
14292 ** );
14293 **
14294 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
14295 ** Equivalent names:
14296 **
14297 ** from-table == child-table
14298 ** to-table == parent-table
14299 **
14300 ** Each REFERENCES clause generates an instance of the following structure
14301 ** which is attached to the from-table. The to-table need not exist when
14302 ** the from-table is created. The existence of the to-table is not checked.
14303 **
14304 ** The list of all parents for child Table X is held at X.pFKey.
14305 **
14306 ** A list of all children for a table named Z (which might not even exist)
14307 ** is held in Schema.fkeyHash with a hash key of Z.
14308 */
14309 struct FKey {
14310  Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
14311  FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
14312  char *zTo; /* Name of table that the key points to (aka: Parent) */
14313  FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
14314  FKey *pPrevTo; /* Previous with the same zTo */
14315  int nCol; /* Number of columns in this key */
14316  /* EV: R-30323-21917 */
14317  u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
14318  u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
14319  Trigger *apTrigger[2];/* Triggers for aAction[] actions */
14320  struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
14321  int iFrom; /* Index of column in pFrom */
14322  char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
14323  } aCol[1]; /* One entry for each of nCol columns */
14324 };
14325 
14326 /*
14327 ** SQLite supports many different ways to resolve a constraint
14328 ** error. ROLLBACK processing means that a constraint violation
14329 ** causes the operation in process to fail and for the current transaction
14330 ** to be rolled back. ABORT processing means the operation in process
14331 ** fails and any prior changes from that one operation are backed out,
14332 ** but the transaction is not rolled back. FAIL processing means that
14333 ** the operation in progress stops and returns an error code. But prior
14334 ** changes due to the same operation are not backed out and no rollback
14335 ** occurs. IGNORE means that the particular row that caused the constraint
14336 ** error is not inserted or updated. Processing continues and no error
14337 ** is returned. REPLACE means that preexisting database rows that caused
14338 ** a UNIQUE constraint violation are removed so that the new insert or
14339 ** update can proceed. Processing continues and no error is reported.
14340 **
14341 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
14342 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
14343 ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
14344 ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
14345 ** referenced table row is propagated into the row that holds the
14346 ** foreign key.
14347 **
14348 ** The following symbolic values are used to record which type
14349 ** of action to take.
14350 */
14351 #define OE_None 0 /* There is no constraint to check */
14352 #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
14353 #define OE_Abort 2 /* Back out changes but do no rollback transaction */
14354 #define OE_Fail 3 /* Stop the operation but leave all prior changes */
14355 #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
14356 #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
14357 
14358 #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
14359 #define OE_SetNull 7 /* Set the foreign key value to NULL */
14360 #define OE_SetDflt 8 /* Set the foreign key value to its default */
14361 #define OE_Cascade 9 /* Cascade the changes */
14362 
14363 #define OE_Default 10 /* Do whatever the default action is */
14364 
14365 
14366 /*
14367 ** An instance of the following structure is passed as the first
14368 ** argument to sqlite3VdbeKeyCompare and is used to control the
14369 ** comparison of the two index keys.
14370 **
14371 ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
14372 ** are nField slots for the columns of an index then one extra slot
14373 ** for the rowid at the end.
14374 */
14375 struct KeyInfo {
14376  u32 nRef; /* Number of references to this KeyInfo object */
14377  u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
14378  u16 nField; /* Number of key columns in the index */
14379  u16 nXField; /* Number of columns beyond the key columns */
14380  sqlite3 *db; /* The database connection */
14381  u8 *aSortOrder; /* Sort order for each column. */
14382  CollSeq *aColl[1]; /* Collating sequence for each term of the key */
14383 };
14384 
14385 /*
14386 ** This object holds a record which has been parsed out into individual
14387 ** fields, for the purposes of doing a comparison.
14388 **
14389 ** A record is an object that contains one or more fields of data.
14390 ** Records are used to store the content of a table row and to store
14391 ** the key of an index. A blob encoding of a record is created by
14392 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
14393 ** OP_Column opcode.
14394 **
14395 ** An instance of this object serves as a "key" for doing a search on
14396 ** an index b+tree. The goal of the search is to find the entry that
14397 ** is closed to the key described by this object. This object might hold
14398 ** just a prefix of the key. The number of fields is given by
14399 ** pKeyInfo->nField.
14400 **
14401 ** The r1 and r2 fields are the values to return if this key is less than
14402 ** or greater than a key in the btree, respectively. These are normally
14403 ** -1 and +1 respectively, but might be inverted to +1 and -1 if the b-tree
14404 ** is in DESC order.
14405 **
14406 ** The key comparison functions actually return default_rc when they find
14407 ** an equals comparison. default_rc can be -1, 0, or +1. If there are
14408 ** multiple entries in the b-tree with the same key (when only looking
14409 ** at the first pKeyInfo->nFields,) then default_rc can be set to -1 to
14410 ** cause the search to find the last match, or +1 to cause the search to
14411 ** find the first match.
14412 **
14413 ** The key comparison functions will set eqSeen to true if they ever
14414 ** get and equal results when comparing this structure to a b-tree record.
14415 ** When default_rc!=0, the search might end up on the record immediately
14416 ** before the first match or immediately after the last match. The
14417 ** eqSeen field will indicate whether or not an exact match exists in the
14418 ** b-tree.
14419 */
14421  KeyInfo *pKeyInfo; /* Collation and sort-order information */
14422  Mem *aMem; /* Values */
14423  u16 nField; /* Number of entries in apMem[] */
14424  i8 default_rc; /* Comparison result if keys are equal */
14425  u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
14426  i8 r1; /* Value to return if (lhs > rhs) */
14427  i8 r2; /* Value to return if (rhs < lhs) */
14428  u8 eqSeen; /* True if an equality comparison has been seen */
14429 };
14430 
14431 
14432 /*
14433 ** Each SQL index is represented in memory by an
14434 ** instance of the following structure.
14435 **
14436 ** The columns of the table that are to be indexed are described
14437 ** by the aiColumn[] field of this structure. For example, suppose
14438 ** we have the following table and index:
14439 **
14440 ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
14441 ** CREATE INDEX Ex2 ON Ex1(c3,c1);
14442 **
14443 ** In the Table structure describing Ex1, nCol==3 because there are
14444 ** three columns in the table. In the Index structure describing
14445 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
14446 ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
14447 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
14448 ** The second column to be indexed (c1) has an index of 0 in
14449 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
14450 **
14451 ** The Index.onError field determines whether or not the indexed columns
14452 ** must be unique and what to do if they are not. When Index.onError=OE_None,
14453 ** it means this is not a unique index. Otherwise it is a unique index
14454 ** and the value of Index.onError indicate the which conflict resolution
14455 ** algorithm to employ whenever an attempt is made to insert a non-unique
14456 ** element.
14457 **
14458 ** While parsing a CREATE TABLE or CREATE INDEX statement in order to
14459 ** generate VDBE code (as opposed to parsing one read from an sqlite_master
14460 ** table as part of parsing an existing database schema), transient instances
14461 ** of this structure may be created. In this case the Index.tnum variable is
14462 ** used to store the address of a VDBE instruction, not a database page
14463 ** number (it cannot - the database page is not allocated until the VDBE
14464 ** program is executed). See convertToWithoutRowidTable() for details.
14465 */
14466 struct Index {
14467  char *zName; /* Name of this index */
14468  i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
14469  LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
14470  Table *pTable; /* The SQL table being indexed */
14471  char *zColAff; /* String defining the affinity of each column */
14472  Index *pNext; /* The next index associated with the same table */
14473  Schema *pSchema; /* Schema containing this index */
14474  u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
14475  const char **azColl; /* Array of collation sequence names for index */
14476  Expr *pPartIdxWhere; /* WHERE clause for partial indices */
14477  ExprList *aColExpr; /* Column expressions */
14478  int tnum; /* DB Page containing root of this index */
14479  LogEst szIdxRow; /* Estimated average row size in bytes */
14480  u16 nKeyCol; /* Number of columns forming the key */
14481  u16 nColumn; /* Number of columns stored in the index */
14482  u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
14483  unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
14484  unsigned bUnordered:1; /* Use this index for == or IN queries only */
14485  unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
14486  unsigned isResized:1; /* True if resizeIndexObject() has been called */
14487  unsigned isCovering:1; /* True if this is a covering index */
14488  unsigned noSkipScan:1; /* Do not try to use skip-scan if true */
14489 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
14490  int nSample; /* Number of elements in aSample[] */
14491  int nSampleCol; /* Size of IndexSample.anEq[] and so on */
14492  tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
14493  IndexSample *aSample; /* Samples of the left-most key */
14494  tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this index */
14495  tRowcnt nRowEst0; /* Non-logarithmic number of rows in the index */
14496 #endif
14497 };
14498 
14499 /*
14500 ** Allowed values for Index.idxType
14501 */
14502 #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
14503 #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
14504 #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
14505 
14506 /* Return true if index X is a PRIMARY KEY index */
14507 #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
14508 
14509 /* Return true if index X is a UNIQUE index */
14510 #define IsUniqueIndex(X) ((X)->onError!=OE_None)
14511 
14512 /* The Index.aiColumn[] values are normally positive integer. But
14513 ** there are some negative values that have special meaning:
14514 */
14515 #define XN_ROWID (-1) /* Indexed column is the rowid */
14516 #define XN_EXPR (-2) /* Indexed column is an expression */
14517 
14518 /*
14519 ** Each sample stored in the sqlite_stat3 table is represented in memory
14520 ** using a structure of this type. See documentation at the top of the
14521 ** analyze.c source file for additional information.
14522 */
14523 struct IndexSample {
14524  void *p; /* Pointer to sampled record */
14525  int n; /* Size of record in bytes */
14526  tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
14527  tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
14528  tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
14529 };
14530 
14531 /*
14532 ** Each token coming out of the lexer is an instance of
14533 ** this structure. Tokens are also used as part of an expression.
14534 **
14535 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
14536 ** may contain random values. Do not make any assumptions about Token.dyn
14537 ** and Token.n when Token.z==0.
14538 */
14539 struct Token {
14540  const char *z; /* Text of the token. Not NULL-terminated! */
14541  unsigned int n; /* Number of characters in this token */
14542 };
14543 
14544 /*
14545 ** An instance of this structure contains information needed to generate
14546 ** code for a SELECT that contains aggregate functions.
14547 **
14548 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
14549 ** pointer to this structure. The Expr.iColumn field is the index in
14550 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
14551 ** code for that node.
14552 **
14553 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
14554 ** original Select structure that describes the SELECT statement. These
14555 ** fields do not need to be freed when deallocating the AggInfo structure.
14556 */
14557 struct AggInfo {
14558  u8 directMode; /* Direct rendering mode means take data directly
14559  ** from source tables rather than from accumulators */
14560  u8 useSortingIdx; /* In direct mode, reference the sorting index rather
14561  ** than the source table */
14562  int sortingIdx; /* Cursor number of the sorting index */
14563  int sortingIdxPTab; /* Cursor number of pseudo-table */
14564  int nSortingColumn; /* Number of columns in the sorting index */
14565  int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
14566  ExprList *pGroupBy; /* The group by clause */
14567  struct AggInfo_col { /* For each column used in source tables */
14568  Table *pTab; /* Source table */
14569  int iTable; /* Cursor number of the source table */
14570  int iColumn; /* Column number within the source table */
14571  int iSorterColumn; /* Column number in the sorting index */
14572  int iMem; /* Memory location that acts as accumulator */
14573  Expr *pExpr; /* The original expression */
14574  } *aCol;
14575  int nColumn; /* Number of used entries in aCol[] */
14576  int nAccumulator; /* Number of columns that show through to the output.
14577  ** Additional columns are used only as parameters to
14578  ** aggregate functions */
14579  struct AggInfo_func { /* For each aggregate function */
14580  Expr *pExpr; /* Expression encoding the function */
14581  FuncDef *pFunc; /* The aggregate function implementation */
14582  int iMem; /* Memory location that acts as accumulator */
14583  int iDistinct; /* Ephemeral table used to enforce DISTINCT */
14584  } *aFunc;
14585  int nFunc; /* Number of entries in aFunc[] */
14586 };
14587 
14588 /*
14589 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
14590 ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
14591 ** than 32767 we have to make it 32-bit. 16-bit is preferred because
14592 ** it uses less memory in the Expr object, which is a big memory user
14593 ** in systems with lots of prepared statements. And few applications
14594 ** need more than about 10 or 20 variables. But some extreme users want
14595 ** to have prepared statements with over 32767 variables, and for them
14596 ** the option is available (at compile-time).
14597 */
14598 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
14599 typedef i16 ynVar;
14600 #else
14601 typedef int ynVar;
14602 #endif
14603 
14604 /*
14605 ** Each node of an expression in the parse tree is an instance
14606 ** of this structure.
14607 **
14608 ** Expr.op is the opcode. The integer parser token codes are reused
14609 ** as opcodes here. For example, the parser defines TK_GE to be an integer
14610 ** code representing the ">=" operator. This same integer code is reused
14611 ** to represent the greater-than-or-equal-to operator in the expression
14612 ** tree.
14613 **
14614 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
14615 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
14616 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
14617 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
14618 ** then Expr.token contains the name of the function.
14619 **
14620 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
14621 ** binary operator. Either or both may be NULL.
14622 **
14623 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
14624 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
14625 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
14626 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
14627 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
14628 ** valid.
14629 **
14630 ** An expression of the form ID or ID.ID refers to a column in a table.
14631 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
14632 ** the integer cursor number of a VDBE cursor pointing to that table and
14633 ** Expr.iColumn is the column number for the specific column. If the
14634 ** expression is used as a result in an aggregate SELECT, then the
14635 ** value is also stored in the Expr.iAgg column in the aggregate so that
14636 ** it can be accessed after all aggregates are computed.
14637 **
14638 ** If the expression is an unbound variable marker (a question mark
14639 ** character '?' in the original SQL) then the Expr.iTable holds the index
14640 ** number for that variable.
14641 **
14642 ** If the expression is a subquery then Expr.iColumn holds an integer
14643 ** register number containing the result of the subquery. If the
14644 ** subquery gives a constant result, then iTable is -1. If the subquery
14645 ** gives a different answer at different times during statement processing
14646 ** then iTable is the address of a subroutine that computes the subquery.
14647 **
14648 ** If the Expr is of type OP_Column, and the table it is selecting from
14649 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
14650 ** corresponding table definition.
14651 **
14652 ** ALLOCATION NOTES:
14653 **
14654 ** Expr objects can use a lot of memory space in database schema. To
14655 ** help reduce memory requirements, sometimes an Expr object will be
14656 ** truncated. And to reduce the number of memory allocations, sometimes
14657 ** two or more Expr objects will be stored in a single memory allocation,
14658 ** together with Expr.zToken strings.
14659 **
14660 ** If the EP_Reduced and EP_TokenOnly flags are set when
14661 ** an Expr object is truncated. When EP_Reduced is set, then all
14662 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
14663 ** are contained within the same memory allocation. Note, however, that
14664 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
14665 ** allocated, regardless of whether or not EP_Reduced is set.
14666 */
14667 struct Expr {
14668  u8 op; /* Operation performed by this node */
14669  char affinity; /* The affinity of the column or 0 if not a column */
14670  u32 flags; /* Various flags. EP_* See below */
14671  union {
14672  char *zToken; /* Token value. Zero terminated and dequoted */
14673  int iValue; /* Non-negative integer value if EP_IntValue */
14674  } u;
14675 
14676  /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
14677  ** space is allocated for the fields below this point. An attempt to
14678  ** access them will result in a segfault or malfunction.
14679  *********************************************************************/
14680 
14681  Expr *pLeft; /* Left subnode */
14682  Expr *pRight; /* Right subnode */
14683  union {
14684  ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
14685  Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
14686  } x;
14687 
14688  /* If the EP_Reduced flag is set in the Expr.flags mask, then no
14689  ** space is allocated for the fields below this point. An attempt to
14690  ** access them will result in a segfault or malfunction.
14691  *********************************************************************/
14692 
14693 #if SQLITE_MAX_EXPR_DEPTH>0
14694  int nHeight; /* Height of the tree headed by this node */
14695 #endif
14696  int iTable; /* TK_COLUMN: cursor number of table holding column
14697  ** TK_REGISTER: register number
14698  ** TK_TRIGGER: 1 -> new, 0 -> old
14699  ** EP_Unlikely: 134217728 times likelihood */
14700  ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
14701  ** TK_VARIABLE: variable number (always >= 1). */
14702  i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
14703  i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
14704  u8 op2; /* TK_REGISTER: original value of Expr.op
14705  ** TK_COLUMN: the value of p5 for OP_Column
14706  ** TK_AGG_FUNCTION: nesting depth */
14707  AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
14708  Table *pTab; /* Table for TK_COLUMN expressions. */
14709 };
14710 
14711 /*
14712 ** The following are the meanings of bits in the Expr.flags field.
14713 */
14714 #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
14715 #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
14716 #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
14717 #define EP_Error 0x000008 /* Expression contains one or more errors */
14718 #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
14719 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
14720 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
14721 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
14722 #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
14723 #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
14724 #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
14725 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
14726 #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
14727 #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
14728 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
14729 #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
14730 #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
14731 #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
14732 #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
14733 #define EP_ConstFunc 0x080000 /* A SQLITE_FUNC_CONSTANT or _SLOCHNG function */
14734 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
14735 #define EP_Subquery 0x200000 /* Tree contains a TK_SELECT operator */
14736 #define EP_Alias 0x400000 /* Is an alias for a result set column */
14737 
14738 /*
14739 ** Combinations of two or more EP_* flags
14740 */
14741 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
14742 
14743 /*
14744 ** These macros can be used to test, set, or clear bits in the
14745 ** Expr.flags field.
14746 */
14747 #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
14748 #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
14749 #define ExprSetProperty(E,P) (E)->flags|=(P)
14750 #define ExprClearProperty(E,P) (E)->flags&=~(P)
14751 
14752 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
14753 ** and Accreditation only. It works like ExprSetProperty() during VVA
14754 ** processes but is a no-op for delivery.
14755 */
14756 #ifdef SQLITE_DEBUG
14757 # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
14758 #else
14759 # define ExprSetVVAProperty(E,P)
14760 #endif
14761 
14762 /*
14763 ** Macros to determine the number of bytes required by a normal Expr
14764 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
14765 ** and an Expr struct with the EP_TokenOnly flag set.
14766 */
14767 #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
14768 #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
14769 #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
14770 
14771 /*
14772 ** Flags passed to the sqlite3ExprDup() function. See the header comment
14773 ** above sqlite3ExprDup() for details.
14774 */
14775 #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
14776 
14777 /*
14778 ** A list of expressions. Each expression may optionally have a
14779 ** name. An expr/name combination can be used in several ways, such
14780 ** as the list of "expr AS ID" fields following a "SELECT" or in the
14781 ** list of "ID = expr" items in an UPDATE. A list of expressions can
14782 ** also be used as the argument to a function, in which case the a.zName
14783 ** field is not used.
14784 **
14785 ** By default the Expr.zSpan field holds a human-readable description of
14786 ** the expression that is used in the generation of error messages and
14787 ** column labels. In this case, Expr.zSpan is typically the text of a
14788 ** column expression as it exists in a SELECT statement. However, if
14789 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
14790 ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
14791 ** form is used for name resolution with nested FROM clauses.
14792 */
14793 struct ExprList {
14794  int nExpr; /* Number of expressions on the list */
14795  struct ExprList_item { /* For each expression in the list */
14796  Expr *pExpr; /* The list of expressions */
14797  char *zName; /* Token associated with this expression */
14798  char *zSpan; /* Original text of the expression */
14799  u8 sortOrder; /* 1 for DESC or 0 for ASC */
14800  unsigned done :1; /* A flag to indicate when processing is finished */
14801  unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
14802  unsigned reusable :1; /* Constant expression is reusable */
14803  union {
14804  struct {
14805  u16 iOrderByCol; /* For ORDER BY, column number in result set */
14806  u16 iAlias; /* Index into Parse.aAlias[] for zName */
14807  } x;
14808  int iConstExprReg; /* Register in which Expr value is cached */
14809  } u;
14810  } *a; /* Alloc a power of two greater or equal to nExpr */
14811 };
14812 
14813 /*
14814 ** An instance of this structure is used by the parser to record both
14815 ** the parse tree for an expression and the span of input text for an
14816 ** expression.
14817 */
14818 struct ExprSpan {
14819  Expr *pExpr; /* The expression parse tree */
14820  const char *zStart; /* First character of input text */
14821  const char *zEnd; /* One character past the end of input text */
14822 };
14823 
14824 /*
14825 ** An instance of this structure can hold a simple list of identifiers,
14826 ** such as the list "a,b,c" in the following statements:
14827 **
14828 ** INSERT INTO t(a,b,c) VALUES ...;
14829 ** CREATE INDEX idx ON t(a,b,c);
14830 ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
14831 **
14832 ** The IdList.a.idx field is used when the IdList represents the list of
14833 ** column names after a table name in an INSERT statement. In the statement
14834 **
14835 ** INSERT INTO t(a,b,c) ...
14836 **
14837 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
14838 */
14839 struct IdList {
14840  struct IdList_item {
14841  char *zName; /* Name of the identifier */
14842  int idx; /* Index in some Table.aCol[] of a column named zName */
14843  } *a;
14844  int nId; /* Number of identifiers on the list */
14845 };
14846 
14847 /*
14848 ** The bitmask datatype defined below is used for various optimizations.
14849 **
14850 ** Changing this from a 64-bit to a 32-bit type limits the number of
14851 ** tables in a join to 32 instead of 64. But it also reduces the size
14852 ** of the library by 738 bytes on ix86.
14853 */
14854 #ifdef SQLITE_BITMASK_TYPE
14855  typedef SQLITE_BITMASK_TYPE Bitmask;
14856 #else
14857  typedef u64 Bitmask;
14858 #endif
14859 
14860 /*
14861 ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
14862 */
14863 #define BMS ((int)(sizeof(Bitmask)*8))
14864 
14865 /*
14866 ** A bit in a Bitmask
14867 */
14868 #define MASKBIT(n) (((Bitmask)1)<<(n))
14869 #define MASKBIT32(n) (((unsigned int)1)<<(n))
14870 #define ALLBITS ((Bitmask)-1)
14871 
14872 /*
14873 ** The following structure describes the FROM clause of a SELECT statement.
14874 ** Each table or subquery in the FROM clause is a separate element of
14875 ** the SrcList.a[] array.
14876 **
14877 ** With the addition of multiple database support, the following structure
14878 ** can also be used to describe a particular table such as the table that
14879 ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
14880 ** such a table must be a simple name: ID. But in SQLite, the table can
14881 ** now be identified by a database name, a dot, then the table name: ID.ID.
14882 **
14883 ** The jointype starts out showing the join type between the current table
14884 ** and the next table on the list. The parser builds the list this way.
14885 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
14886 ** jointype expresses the join between the table and the previous table.
14887 **
14888 ** In the colUsed field, the high-order bit (bit 63) is set if the table
14889 ** contains more than 63 columns and the 64-th or later column is used.
14890 */
14891 struct SrcList {
14892  int nSrc; /* Number of tables or subqueries in the FROM clause */
14893  u32 nAlloc; /* Number of entries allocated in a[] below */
14894  struct SrcList_item {
14895  Schema *pSchema; /* Schema to which this item is fixed */
14896  char *zDatabase; /* Name of database holding this table */
14897  char *zName; /* Name of the table */
14898  char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
14899  Table *pTab; /* An SQL table corresponding to zName */
14900  Select *pSelect; /* A SELECT statement used in place of a table name */
14901  int addrFillSub; /* Address of subroutine to manifest a subquery */
14902  int regReturn; /* Register holding return address of addrFillSub */
14903  int regResult; /* Registers holding results of a co-routine */
14904  struct {
14905  u8 jointype; /* Type of join between this able and the previous */
14906  unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
14907  unsigned isIndexedBy :1; /* True if there is an INDEXED BY clause */
14908  unsigned isTabFunc :1; /* True if table-valued-function syntax */
14909  unsigned isCorrelated :1; /* True if sub-query is correlated */
14910  unsigned viaCoroutine :1; /* Implemented as a co-routine */
14911  unsigned isRecursive :1; /* True for recursive reference in WITH */
14912  } fg;
14913 #ifndef SQLITE_OMIT_EXPLAIN
14914  u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
14915 #endif
14916  int iCursor; /* The VDBE cursor number used to access this table */
14917  Expr *pOn; /* The ON clause of a join */
14918  IdList *pUsing; /* The USING clause of a join */
14919  Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
14920  union {
14921  char *zIndexedBy; /* Identifier from "INDEXED BY <zIndex>" clause */
14922  ExprList *pFuncArg; /* Arguments to table-valued-function */
14923  } u1;
14924  Index *pIBIndex; /* Index structure corresponding to u1.zIndexedBy */
14925  } a[1]; /* One entry for each identifier on the list */
14926 };
14927 
14928 /*
14929 ** Permitted values of the SrcList.a.jointype field
14930 */
14931 #define JT_INNER 0x0001 /* Any kind of inner or cross join */
14932 #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
14933 #define JT_NATURAL 0x0004 /* True for a "natural" join */
14934 #define JT_LEFT 0x0008 /* Left outer join */
14935 #define JT_RIGHT 0x0010 /* Right outer join */
14936 #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
14937 #define JT_ERROR 0x0040 /* unknown or unsupported join type */
14938 
14939 
14940 /*
14941 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
14942 ** and the WhereInfo.wctrlFlags member.
14943 **
14944 ** Value constraints (enforced via assert()):
14945 ** WHERE_USE_LIMIT == SF_FixedLimit
14946 */
14947 #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
14948 #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
14949 #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
14950 #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
14951 #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
14952 #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
14953 #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
14954 #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
14955 #define WHERE_NO_AUTOINDEX 0x0080 /* Disallow automatic indexes */
14956 #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
14957 #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
14958 #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
14959 #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
14960 #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
14961 #define WHERE_ONEPASS_MULTIROW 0x2000 /* ONEPASS is ok with multiple rows */
14962 #define WHERE_USE_LIMIT 0x4000 /* There is a constant LIMIT clause */
14963 #define WHERE_SEEK_TABLE 0x8000 /* Do not defer seeks on main table */
14964 
14965 /* Allowed return values from sqlite3WhereIsDistinct()
14966 */
14967 #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
14968 #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
14969 #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
14970 #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
14971 
14972 /*
14973 ** A NameContext defines a context in which to resolve table and column
14974 ** names. The context consists of a list of tables (the pSrcList) field and
14975 ** a list of named expression (pEList). The named expression list may
14976 ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
14977 ** to the table being operated on by INSERT, UPDATE, or DELETE. The
14978 ** pEList corresponds to the result set of a SELECT and is NULL for
14979 ** other statements.
14980 **
14981 ** NameContexts can be nested. When resolving names, the inner-most
14982 ** context is searched first. If no match is found, the next outer
14983 ** context is checked. If there is still no match, the next context
14984 ** is checked. This process continues until either a match is found
14985 ** or all contexts are check. When a match is found, the nRef member of
14986 ** the context containing the match is incremented.
14987 **
14988 ** Each subquery gets a new NameContext. The pNext field points to the
14989 ** NameContext in the parent query. Thus the process of scanning the
14990 ** NameContext list corresponds to searching through successively outer
14991 ** subqueries looking for a match.
14992 */
14993 struct NameContext {
14994  Parse *pParse; /* The parser */
14995  SrcList *pSrcList; /* One or more tables used to resolve names */
14996  ExprList *pEList; /* Optional list of result-set columns */
14997  AggInfo *pAggInfo; /* Information about aggregates at this level */
14998  NameContext *pNext; /* Next outer name context. NULL for outermost */
14999  int nRef; /* Number of names resolved by this context */
15000  int nErr; /* Number of errors encountered while resolving names */
15001  u16 ncFlags; /* Zero or more NC_* flags defined below */
15002 };
15003 
15004 /*
15005 ** Allowed values for the NameContext, ncFlags field.
15006 **
15007 ** Value constraints (all checked via assert()):
15008 ** NC_HasAgg == SF_HasAgg
15009 ** NC_MinMaxAgg == SF_MinMaxAgg == SQLITE_FUNC_MINMAX
15010 **
15011 */
15012 #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
15013 #define NC_PartIdx 0x0002 /* True if resolving a partial index WHERE */
15014 #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
15015 #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
15016 #define NC_HasAgg 0x0010 /* One or more aggregate functions seen */
15017 #define NC_IdxExpr 0x0020 /* True if resolving columns of CREATE INDEX */
15018 #define NC_VarSelect 0x0040 /* A correlated subquery has been seen */
15019 #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
15020 
15021 /*
15022 ** An instance of the following structure contains all information
15023 ** needed to generate code for a single SELECT statement.
15024 **
15025 ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
15026 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
15027 ** limit and nOffset to the value of the offset (or 0 if there is not
15028 ** offset). But later on, nLimit and nOffset become the memory locations
15029 ** in the VDBE that record the limit and offset counters.
15030 **
15031 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
15032 ** These addresses must be stored so that we can go back and fill in
15033 ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
15034 ** the number of columns in P2 can be computed at the same time
15035 ** as the OP_OpenEphm instruction is coded because not
15036 ** enough information about the compound query is known at that point.
15037 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
15038 ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
15039 ** sequences for the ORDER BY clause.
15040 */
15041 struct Select {
15042  ExprList *pEList; /* The fields of the result */
15043  u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
15044  LogEst nSelectRow; /* Estimated number of result rows */
15045  u32 selFlags; /* Various SF_* values */
15046  int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
15047 #if SELECTTRACE_ENABLED
15048  char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
15049 #endif
15050  int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
15051  SrcList *pSrc; /* The FROM clause */
15052  Expr *pWhere; /* The WHERE clause */
15053  ExprList *pGroupBy; /* The GROUP BY clause */
15054  Expr *pHaving; /* The HAVING clause */
15055  ExprList *pOrderBy; /* The ORDER BY clause */
15056  Select *pPrior; /* Prior select in a compound select statement */
15057  Select *pNext; /* Next select to the left in a compound */
15058  Expr *pLimit; /* LIMIT expression. NULL means not used. */
15059  Expr *pOffset; /* OFFSET expression. NULL means not used. */
15060  With *pWith; /* WITH clause attached to this select. Or NULL. */
15061 };
15062 
15063 /*
15064 ** Allowed values for Select.selFlags. The "SF" prefix stands for
15065 ** "Select Flag".
15066 **
15067 ** Value constraints (all checked via assert())
15068 ** SF_HasAgg == NC_HasAgg
15069 ** SF_MinMaxAgg == NC_MinMaxAgg == SQLITE_FUNC_MINMAX
15070 ** SF_FixedLimit == WHERE_USE_LIMIT
15071 */
15072 #define SF_Distinct 0x00001 /* Output should be DISTINCT */
15073 #define SF_All 0x00002 /* Includes the ALL keyword */
15074 #define SF_Resolved 0x00004 /* Identifiers have been resolved */
15075 #define SF_Aggregate 0x00008 /* Contains agg functions or a GROUP BY */
15076 #define SF_HasAgg 0x00010 /* Contains aggregate functions */
15077 #define SF_UsesEphemeral 0x00020 /* Uses the OpenEphemeral opcode */
15078 #define SF_Expanded 0x00040 /* sqlite3SelectExpand() called on this */
15079 #define SF_HasTypeInfo 0x00080 /* FROM subqueries have Table metadata */
15080 #define SF_Compound 0x00100 /* Part of a compound query */
15081 #define SF_Values 0x00200 /* Synthesized from VALUES clause */
15082 #define SF_MultiValue 0x00400 /* Single VALUES term with multiple rows */
15083 #define SF_NestedFrom 0x00800 /* Part of a parenthesized FROM clause */
15084 #define SF_MinMaxAgg 0x01000 /* Aggregate containing min() or max() */
15085 #define SF_Recursive 0x02000 /* The recursive part of a recursive CTE */
15086 #define SF_FixedLimit 0x04000 /* nSelectRow set by a constant LIMIT */
15087 #define SF_MaybeConvert 0x08000 /* Need convertCompoundSelectToSubquery() */
15088 #define SF_Converted 0x10000 /* By convertCompoundSelectToSubquery() */
15089 #define SF_IncludeHidden 0x20000 /* Include hidden columns in output */
15090 
15091 
15092 /*
15093 ** The results of a SELECT can be distributed in several ways, as defined
15094 ** by one of the following macros. The "SRT" prefix means "SELECT Result
15095 ** Type".
15096 **
15097 ** SRT_Union Store results as a key in a temporary index
15098 ** identified by pDest->iSDParm.
15099 **
15100 ** SRT_Except Remove results from the temporary index pDest->iSDParm.
15101 **
15102 ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
15103 ** set is not empty.
15104 **
15105 ** SRT_Discard Throw the results away. This is used by SELECT
15106 ** statements within triggers whose only purpose is
15107 ** the side-effects of functions.
15108 **
15109 ** All of the above are free to ignore their ORDER BY clause. Those that
15110 ** follow must honor the ORDER BY clause.
15111 **
15112 ** SRT_Output Generate a row of output (using the OP_ResultRow
15113 ** opcode) for each row in the result set.
15114 **
15115 ** SRT_Mem Only valid if the result is a single column.
15116 ** Store the first column of the first result row
15117 ** in register pDest->iSDParm then abandon the rest
15118 ** of the query. This destination implies "LIMIT 1".
15119 **
15120 ** SRT_Set The result must be a single column. Store each
15121 ** row of result as the key in table pDest->iSDParm.
15122 ** Apply the affinity pDest->affSdst before storing
15123 ** results. Used to implement "IN (SELECT ...)".
15124 **
15125 ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
15126 ** the result there. The cursor is left open after
15127 ** returning. This is like SRT_Table except that
15128 ** this destination uses OP_OpenEphemeral to create
15129 ** the table first.
15130 **
15131 ** SRT_Coroutine Generate a co-routine that returns a new row of
15132 ** results each time it is invoked. The entry point
15133 ** of the co-routine is stored in register pDest->iSDParm
15134 ** and the result row is stored in pDest->nDest registers
15135 ** starting with pDest->iSdst.
15136 **
15137 ** SRT_Table Store results in temporary table pDest->iSDParm.
15138 ** SRT_Fifo This is like SRT_EphemTab except that the table
15139 ** is assumed to already be open. SRT_Fifo has
15140 ** the additional property of being able to ignore
15141 ** the ORDER BY clause.
15142 **
15143 ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
15144 ** But also use temporary table pDest->iSDParm+1 as
15145 ** a record of all prior results and ignore any duplicate
15146 ** rows. Name means: "Distinct Fifo".
15147 **
15148 ** SRT_Queue Store results in priority queue pDest->iSDParm (really
15149 ** an index). Append a sequence number so that all entries
15150 ** are distinct.
15151 **
15152 ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
15153 ** the same record has never been stored before. The
15154 ** index at pDest->iSDParm+1 hold all prior stores.
15155 */
15156 #define SRT_Union 1 /* Store result as keys in an index */
15157 #define SRT_Except 2 /* Remove result from a UNION index */
15158 #define SRT_Exists 3 /* Store 1 if the result is not empty */
15159 #define SRT_Discard 4 /* Do not save the results anywhere */
15160 #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
15161 #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
15162 #define SRT_Queue 7 /* Store result in an queue */
15163 #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
15164 
15165 /* The ORDER BY clause is ignored for all of the above */
15166 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
15167 
15168 #define SRT_Output 9 /* Output each row of result */
15169 #define SRT_Mem 10 /* Store result in a memory cell */
15170 #define SRT_Set 11 /* Store results as keys in an index */
15171 #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
15172 #define SRT_Coroutine 13 /* Generate a single row of result */
15173 #define SRT_Table 14 /* Store result as data with an automatic rowid */
15174 
15175 /*
15176 ** An instance of this object describes where to put of the results of
15177 ** a SELECT statement.
15178 */
15179 struct SelectDest {
15180  u8 eDest; /* How to dispose of the results. On of SRT_* above. */
15181  char affSdst; /* Affinity used when eDest==SRT_Set */
15182  int iSDParm; /* A parameter used by the eDest disposal method */
15183  int iSdst; /* Base register where results are written */
15184  int nSdst; /* Number of registers allocated */
15185  ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
15186 };
15187 
15188 /*
15189 ** During code generation of statements that do inserts into AUTOINCREMENT
15190 ** tables, the following information is attached to the Table.u.autoInc.p
15191 ** pointer of each autoincrement table to record some side information that
15192 ** the code generator needs. We have to keep per-table autoincrement
15193 ** information in case inserts are done within triggers. Triggers do not
15194 ** normally coordinate their activities, but we do need to coordinate the
15195 ** loading and saving of autoincrement information.
15196 */
15197 struct AutoincInfo {
15198  AutoincInfo *pNext; /* Next info block in a list of them all */
15199  Table *pTab; /* Table this info block refers to */
15200  int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
15201  int regCtr; /* Memory register holding the rowid counter */
15202 };
15203 
15204 /*
15205 ** Size of the column cache
15206 */
15207 #ifndef SQLITE_N_COLCACHE
15208 # define SQLITE_N_COLCACHE 10
15209 #endif
15210 
15211 /*
15212 ** At least one instance of the following structure is created for each
15213 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
15214 ** statement. All such objects are stored in the linked list headed at
15215 ** Parse.pTriggerPrg and deleted once statement compilation has been
15216 ** completed.
15217 **
15218 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
15219 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
15220 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
15221 ** The Parse.pTriggerPrg list never contains two entries with the same
15222 ** values for both pTrigger and orconf.
15223 **
15224 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
15225 ** accessed (or set to 0 for triggers fired as a result of INSERT
15226 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
15227 ** a mask of new.* columns used by the program.
15228 */
15229 struct TriggerPrg {
15230  Trigger *pTrigger; /* Trigger this program was coded from */
15231  TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
15232  SubProgram *pProgram; /* Program implementing pTrigger/orconf */
15233  int orconf; /* Default ON CONFLICT policy */
15234  u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
15235 };
15236 
15237 /*
15238 ** The yDbMask datatype for the bitmask of all attached databases.
15239 */
15240 #if SQLITE_MAX_ATTACHED>30
15241  typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
15242 # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
15243 # define DbMaskZero(M) memset((M),0,sizeof(M))
15244 # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
15245 # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
15246 # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
15247 #else
15248  typedef unsigned int yDbMask;
15249 # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
15250 # define DbMaskZero(M) (M)=0
15251 # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
15252 # define DbMaskAllZero(M) (M)==0
15253 # define DbMaskNonZero(M) (M)!=0
15254 #endif
15255 
15256 /*
15257 ** An SQL parser context. A copy of this structure is passed through
15258 ** the parser and down into all the parser action routine in order to
15259 ** carry around information that is global to the entire parse.
15260 **
15261 ** The structure is divided into two parts. When the parser and code
15262 ** generate call themselves recursively, the first part of the structure
15263 ** is constant but the second part is reset at the beginning and end of
15264 ** each recursion.
15265 **
15266 ** The nTableLock and aTableLock variables are only used if the shared-cache
15267 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
15268 ** used to store the set of table-locks required by the statement being
15269 ** compiled. Function sqlite3TableLock() is used to add entries to the
15270 ** list.
15271 */
15272 struct Parse {
15273  sqlite3 *db; /* The main database structure */
15274  char *zErrMsg; /* An error message */
15275  Vdbe *pVdbe; /* An engine for executing database bytecode */
15276  int rc; /* Return code from execution */
15277  u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
15278  u8 checkSchema; /* Causes schema cookie check after an error */
15279  u8 nested; /* Number of nested calls to the parser/code generator */
15280  u8 nTempReg; /* Number of temporary registers in aTempReg[] */
15281  u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
15282  u8 mayAbort; /* True if statement may throw an ABORT exception */
15283  u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
15284  u8 okConstFactor; /* OK to factor out constants */
15285  u8 disableLookaside; /* Number of times lookaside has been disabled */
15286  u8 nColCache; /* Number of entries in aColCache[] */
15287  int aTempReg[8]; /* Holding area for temporary registers */
15288  int nRangeReg; /* Size of the temporary register block */
15289  int iRangeReg; /* First register in temporary register block */
15290  int nErr; /* Number of errors seen */
15291  int nTab; /* Number of previously allocated VDBE cursors */
15292  int nMem; /* Number of memory cells used so far */
15293  int nSet; /* Number of sets used so far */
15294  int nOnce; /* Number of OP_Once instructions so far */
15295  int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
15296  int szOpAlloc; /* Bytes of memory space allocated for Vdbe.aOp[] */
15297  int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
15298  int ckBase; /* Base register of data during check constraints */
15299  int iSelfTab; /* Table of an index whose exprs are being coded */
15300  int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
15301  int iCacheCnt; /* Counter used to generate aColCache[].lru values */
15302  int nLabel; /* Number of labels used */
15303  int *aLabel; /* Space to hold the labels */
15304  struct yColCache {
15305  int iTable; /* Table cursor number */
15306  i16 iColumn; /* Table column number */
15307  u8 tempReg; /* iReg is a temp register that needs to be freed */
15308  int iLevel; /* Nesting level */
15309  int iReg; /* Reg with value of this column. 0 means none. */
15310  int lru; /* Least recently used entry has the smallest value */
15311  } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
15312  ExprList *pConstExpr;/* Constant expressions */
15313  Token constraintName;/* Name of the constraint currently being parsed */
15314  yDbMask writeMask; /* Start a write transaction on these databases */
15315  yDbMask cookieMask; /* Bitmask of schema verified databases */
15316  int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
15317  int regRowid; /* Register holding rowid of CREATE TABLE entry */
15318  int regRoot; /* Register holding root page number for new objects */
15319  int nMaxArg; /* Max args passed to user function by sub-program */
15320 #if SELECTTRACE_ENABLED
15321  int nSelect; /* Number of SELECT statements seen */
15322  int nSelectIndent; /* How far to indent SELECTTRACE() output */
15323 #endif
15324 #ifndef SQLITE_OMIT_SHARED_CACHE
15325  int nTableLock; /* Number of locks in aTableLock */
15326  TableLock *aTableLock; /* Required table locks for shared-cache mode */
15327 #endif
15328  AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
15329 
15330  /* Information used while coding trigger programs. */
15331  Parse *pToplevel; /* Parse structure for main program (or NULL) */
15332  Table *pTriggerTab; /* Table triggers are being coded for */
15333  int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
15334  u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
15335  u32 oldmask; /* Mask of old.* columns referenced */
15336  u32 newmask; /* Mask of new.* columns referenced */
15337  u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
15338  u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
15339  u8 disableTriggers; /* True to disable triggers */
15340 
15341  /************************************************************************
15342  ** Above is constant between recursions. Below is reset before and after
15343  ** each recursion. The boundary between these two regions is determined
15344  ** using offsetof(Parse,nVar) so the nVar field must be the first field
15345  ** in the recursive region.
15346  ************************************************************************/
15347 
15348  ynVar nVar; /* Number of '?' variables seen in the SQL so far */
15349  int nzVar; /* Number of available slots in azVar[] */
15350  u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
15351  u8 explain; /* True if the EXPLAIN flag is found on the query */
15352 #ifndef SQLITE_OMIT_VIRTUALTABLE
15353  u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
15354  int nVtabLock; /* Number of virtual tables to lock */
15355 #endif
15356  int nAlias; /* Number of aliased result set columns */
15357  int nHeight; /* Expression tree height of current sub-select */
15358 #ifndef SQLITE_OMIT_EXPLAIN
15359  int iSelectId; /* ID of current select for EXPLAIN output */
15360  int iNextSelectId; /* Next available select ID for EXPLAIN output */
15361 #endif
15362  char **azVar; /* Pointers to names of parameters */
15363  Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
15364  const char *zTail; /* All SQL text past the last semicolon parsed */
15365  Table *pNewTable; /* A table being constructed by CREATE TABLE */
15366  Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
15367  const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
15368  Token sNameToken; /* Token with unqualified schema object name */
15369  Token sLastToken; /* The last token parsed */
15370 #ifndef SQLITE_OMIT_VIRTUALTABLE
15371  Token sArg; /* Complete text of a module argument */
15372  Table **apVtabLock; /* Pointer to virtual tables needing locking */
15373 #endif
15374  Table *pZombieTab; /* List of Table objects to delete after code gen */
15375  TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
15376  With *pWith; /* Current WITH clause, or NULL */
15377  With *pWithToFree; /* Free this WITH object at the end of the parse */
15378 };
15379 
15380 /*
15381 ** Return true if currently inside an sqlite3_declare_vtab() call.
15382 */
15383 #ifdef SQLITE_OMIT_VIRTUALTABLE
15384  #define IN_DECLARE_VTAB 0
15385 #else
15386  #define IN_DECLARE_VTAB (pParse->declareVtab)
15387 #endif
15388 
15389 /*
15390 ** An instance of the following structure can be declared on a stack and used
15391 ** to save the Parse.zAuthContext value so that it can be restored later.
15392 */
15393 struct AuthContext {
15394  const char *zAuthContext; /* Put saved Parse.zAuthContext here */
15395  Parse *pParse; /* The Parse structure */
15396 };
15397 
15398 /*
15399 ** Bitfield flags for P5 value in various opcodes.
15400 **
15401 ** Value constraints (enforced via assert()):
15402 ** OPFLAG_LENGTHARG == SQLITE_FUNC_LENGTH
15403 ** OPFLAG_TYPEOFARG == SQLITE_FUNC_TYPEOF
15404 ** OPFLAG_BULKCSR == BTREE_BULKLOAD
15405 ** OPFLAG_SEEKEQ == BTREE_SEEK_EQ
15406 ** OPFLAG_FORDELETE == BTREE_FORDELETE
15407 ** OPFLAG_SAVEPOSITION == BTREE_SAVEPOSITION
15408 ** OPFLAG_AUXDELETE == BTREE_AUXDELETE
15409 */
15410 #define OPFLAG_NCHANGE 0x01 /* OP_Insert: Set to update db->nChange */
15411  /* Also used in P2 (not P5) of OP_Delete */
15412 #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
15413 #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
15414 #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
15415 #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
15416 #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
15417 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
15418 #define OPFLAG_ISNOOP 0x40 /* OP_Delete does pre-update-hook only */
15419 #endif
15420 #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
15421 #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
15422 #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
15423 #define OPFLAG_SEEKEQ 0x02 /* OP_Open** cursor uses EQ seek only */
15424 #define OPFLAG_FORDELETE 0x08 /* OP_Open should use BTREE_FORDELETE */
15425 #define OPFLAG_P2ISREG 0x10 /* P2 to OP_Open** is a register number */
15426 #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
15427 #define OPFLAG_SAVEPOSITION 0x02 /* OP_Delete: keep cursor position */
15428 #define OPFLAG_AUXDELETE 0x04 /* OP_Delete: index in a DELETE op */
15429 
15430 /*
15431  * Each trigger present in the database schema is stored as an instance of
15432  * struct Trigger.
15433  *
15434  * Pointers to instances of struct Trigger are stored in two ways.
15435  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
15436  * database). This allows Trigger structures to be retrieved by name.
15437  * 2. All triggers associated with a single table form a linked list, using the
15438  * pNext member of struct Trigger. A pointer to the first element of the
15439  * linked list is stored as the "pTrigger" member of the associated
15440  * struct Table.
15441  *
15442  * The "step_list" member points to the first element of a linked list
15443  * containing the SQL statements specified as the trigger program.
15444  */
15445 struct Trigger {
15446  char *zName; /* The name of the trigger */
15447  char *table; /* The table or view to which the trigger applies */
15448  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
15449  u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
15450  Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
15451  IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
15452  the <column-list> is stored here */
15453  Schema *pSchema; /* Schema containing the trigger */
15454  Schema *pTabSchema; /* Schema containing the table */
15455  TriggerStep *step_list; /* Link list of trigger program steps */
15456  Trigger *pNext; /* Next trigger associated with the table */
15457 };
15458 
15459 /*
15460 ** A trigger is either a BEFORE or an AFTER trigger. The following constants
15461 ** determine which.
15462 **
15463 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
15464 ** In that cases, the constants below can be ORed together.
15465 */
15466 #define TRIGGER_BEFORE 1
15467 #define TRIGGER_AFTER 2
15468 
15469 /*
15470  * An instance of struct TriggerStep is used to store a single SQL statement
15471  * that is a part of a trigger-program.
15472  *
15473  * Instances of struct TriggerStep are stored in a singly linked list (linked
15474  * using the "pNext" member) referenced by the "step_list" member of the
15475  * associated struct Trigger instance. The first element of the linked list is
15476  * the first step of the trigger-program.
15477  *
15478  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
15479  * "SELECT" statement. The meanings of the other members is determined by the
15480  * value of "op" as follows:
15481  *
15482  * (op == TK_INSERT)
15483  * orconf -> stores the ON CONFLICT algorithm
15484  * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
15485  * this stores a pointer to the SELECT statement. Otherwise NULL.
15486  * zTarget -> Dequoted name of the table to insert into.
15487  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
15488  * this stores values to be inserted. Otherwise NULL.
15489  * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
15490  * statement, then this stores the column-names to be
15491  * inserted into.
15492  *
15493  * (op == TK_DELETE)
15494  * zTarget -> Dequoted name of the table to delete from.
15495  * pWhere -> The WHERE clause of the DELETE statement if one is specified.
15496  * Otherwise NULL.
15497  *
15498  * (op == TK_UPDATE)
15499  * zTarget -> Dequoted name of the table to update.
15500  * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
15501  * Otherwise NULL.
15502  * pExprList -> A list of the columns to update and the expressions to update
15503  * them to. See sqlite3Update() documentation of "pChanges"
15504  * argument.
15505  *
15506  */
15507 struct TriggerStep {
15508  u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
15509  u8 orconf; /* OE_Rollback etc. */
15510  Trigger *pTrig; /* The trigger that this step is a part of */
15511  Select *pSelect; /* SELECT statement or RHS of INSERT INTO SELECT ... */
15512  char *zTarget; /* Target table for DELETE, UPDATE, INSERT */
15513  Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
15514  ExprList *pExprList; /* SET clause for UPDATE. */
15515  IdList *pIdList; /* Column names for INSERT */
15516  TriggerStep *pNext; /* Next in the link-list */
15517  TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
15518 };
15519 
15520 /*
15521 ** The following structure contains information used by the sqliteFix...
15522 ** routines as they walk the parse tree to make database references
15523 ** explicit.
15524 */
15525 typedef struct DbFixer DbFixer;
15526 struct DbFixer {
15527  Parse *pParse; /* The parsing context. Error messages written here */
15528  Schema *pSchema; /* Fix items to this schema */
15529  int bVarOnly; /* Check for variable references only */
15530  const char *zDb; /* Make sure all objects are contained in this database */
15531  const char *zType; /* Type of the container - used for error messages */
15532  const Token *pName; /* Name of the container - used for error messages */
15533 };
15534 
15535 /*
15536 ** An objected used to accumulate the text of a string where we
15537 ** do not necessarily know how big the string will be in the end.
15538 */
15539 struct StrAccum {
15540  sqlite3 *db; /* Optional database for lookaside. Can be NULL */
15541  char *zBase; /* A base allocation. Not from malloc. */
15542  char *zText; /* The string collected so far */
15543  u32 nChar; /* Length of the string so far */
15544  u32 nAlloc; /* Amount of space allocated in zText */
15545  u32 mxAlloc; /* Maximum allowed allocation. 0 for no malloc usage */
15546  u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
15547  u8 printfFlags; /* SQLITE_PRINTF flags below */
15548 };
15549 #define STRACCUM_NOMEM 1
15550 #define STRACCUM_TOOBIG 2
15551 #define SQLITE_PRINTF_INTERNAL 0x01 /* Internal-use-only converters allowed */
15552 #define SQLITE_PRINTF_SQLFUNC 0x02 /* SQL function arguments to VXPrintf */
15553 #define SQLITE_PRINTF_MALLOCED 0x04 /* True if xText is allocated space */
15554 
15555 #define isMalloced(X) (((X)->printfFlags & SQLITE_PRINTF_MALLOCED)!=0)
15556 
15557 
15558 /*
15559 ** A pointer to this structure is used to communicate information
15560 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
15561 */
15562 typedef struct {
15563  sqlite3 *db; /* The database being initialized */
15564  char **pzErrMsg; /* Error message stored here */
15565  int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
15566  int rc; /* Result code stored here */
15567 } InitData;
15568 
15569 /*
15570 ** Structure containing global configuration data for the SQLite library.
15571 **
15572 ** This structure also contains some state information.
15573 */
15575  int bMemstat; /* True to enable memory status */
15576  int bCoreMutex; /* True to enable core mutexing */
15577  int bFullMutex; /* True to enable full mutexing */
15578  int bOpenUri; /* True to interpret filenames as URIs */
15579  int bUseCis; /* Use covering indices for full-scans */
15580  int mxStrlen; /* Maximum string length */
15581  int neverCorrupt; /* Database is always well-formed */
15582  int szLookaside; /* Default lookaside buffer size */
15583  int nLookaside; /* Default lookaside buffer count */
15584  int nStmtSpill; /* Stmt-journal spill-to-disk threshold */
15585  sqlite3_mem_methods m; /* Low-level memory allocation interface */
15586  sqlite3_mutex_methods mutex; /* Low-level mutex interface */
15587  sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
15588  void *pHeap; /* Heap storage space */
15589  int nHeap; /* Size of pHeap[] */
15590  int mnReq, mxReq; /* Min and max heap requests sizes */
15591  sqlite3_int64 szMmap; /* mmap() space per open file */
15592  sqlite3_int64 mxMmap; /* Maximum value for szMmap */
15593  void *pScratch; /* Scratch memory */
15594  int szScratch; /* Size of each scratch buffer */
15595  int nScratch; /* Number of scratch buffers */
15596  void *pPage; /* Page cache memory */
15597  int szPage; /* Size of each page in pPage[] */
15598  int nPage; /* Number of pages in pPage[] */
15599  int mxParserStack; /* maximum depth of the parser stack */
15600  int sharedCacheEnabled; /* true if shared-cache mode enabled */
15601  u32 szPma; /* Maximum Sorter PMA size */
15602  /* The above might be initialized to non-zero. The following need to always
15603  ** initially be zero, however. */
15604  int isInit; /* True after initialization has finished */
15605  int inProgress; /* True while initialization in progress */
15606  int isMutexInit; /* True after mutexes are initialized */
15607  int isMallocInit; /* True after malloc is initialized */
15608  int isPCacheInit; /* True after malloc is initialized */
15609  int nRefInitMutex; /* Number of users of pInitMutex */
15610  sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
15611  void (*xLog)(void*,int,const char*); /* Function for logging */
15612  void *pLogArg; /* First argument to xLog() */
15613 #ifdef SQLITE_ENABLE_SQLLOG
15614  void(*xSqllog)(void*,sqlite3*,const char*, int);
15615  void *pSqllogArg;
15616 #endif
15617 #ifdef SQLITE_VDBE_COVERAGE
15618  /* The following callback (if not NULL) is invoked on every VDBE branch
15619  ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
15620  */
15621  void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
15622  void *pVdbeBranchArg; /* 1st argument */
15623 #endif
15624 #ifndef SQLITE_OMIT_BUILTIN_TEST
15625  int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
15626 #endif
15627  int bLocaltimeFault; /* True to fail localtime() calls */
15628 };
15629 
15630 /*
15631 ** This macro is used inside of assert() statements to indicate that
15632 ** the assert is only valid on a well-formed database. Instead of:
15633 **
15634 ** assert( X );
15635 **
15636 ** One writes:
15637 **
15638 ** assert( X || CORRUPT_DB );
15639 **
15640 ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
15641 ** that the database is definitely corrupt, only that it might be corrupt.
15642 ** For most test cases, CORRUPT_DB is set to false using a special
15643 ** sqlite3_test_control(). This enables assert() statements to prove
15644 ** things that are always true for well-formed databases.
15645 */
15646 #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
15647 
15648 /*
15649 ** Context pointer passed down through the tree-walk.
15650 */
15651 struct Walker {
15652  Parse *pParse; /* Parser context. */
15653  int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
15654  int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
15655  void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
15656  int walkerDepth; /* Number of subqueries */
15657  u8 eCode; /* A small processing code */
15658  union { /* Extra data for callback */
15659  NameContext *pNC; /* Naming context */
15660  int n; /* A counter */
15661  int iCur; /* A cursor number */
15662  SrcList *pSrcList; /* FROM clause */
15663  struct SrcCount *pSrcCount; /* Counting column references */
15664  struct CCurHint *pCCurHint; /* Used by codeCursorHint() */
15665  int *aiCol; /* array of column indexes */
15666  } u;
15667 };
15668 
15669 /* Forward declarations */
15676 
15677 /*
15678 ** Return code from the parse-tree walking primitives and their
15679 ** callbacks.
15680 */
15681 #define WRC_Continue 0 /* Continue down into children */
15682 #define WRC_Prune 1 /* Omit children but continue walking siblings */
15683 #define WRC_Abort 2 /* Abandon the tree walk */
15684 
15685 /*
15686 ** An instance of this structure represents a set of one or more CTEs
15687 ** (common table expressions) created by a single WITH clause.
15688 */
15689 struct With {
15690  int nCte; /* Number of CTEs in the WITH clause */
15691  With *pOuter; /* Containing WITH clause, or NULL */
15692  struct Cte { /* For each CTE in the WITH clause.... */
15693  char *zName; /* Name of this CTE */
15694  ExprList *pCols; /* List of explicit column names, or NULL */
15695  Select *pSelect; /* The definition of this CTE */
15696  const char *zCteErr; /* Error message for circular references */
15697  } a[1];
15698 };
15699 
15700 #ifdef SQLITE_DEBUG
15701 /*
15702 ** An instance of the TreeView object is used for printing the content of
15703 ** data structures on sqlite3DebugPrintf() using a tree-like view.
15704 */
15705 struct TreeView {
15706  int iLevel; /* Which level of the tree we are on */
15707  u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
15708 };
15709 #endif /* SQLITE_DEBUG */
15710 
15711 /*
15712 ** Assuming zIn points to the first byte of a UTF-8 character,
15713 ** advance zIn to point to the first byte of the next UTF-8 character.
15714 */
15715 #define SQLITE_SKIP_UTF8(zIn) { \
15716  if( (*(zIn++))>=0xc0 ){ \
15717  while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
15718  } \
15719 }
15720 
15721 /*
15722 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
15723 ** the same name but without the _BKPT suffix. These macros invoke
15724 ** routines that report the line-number on which the error originated
15725 ** using sqlite3_log(). The routines also provide a convenient place
15726 ** to set a debugger breakpoint.
15727 */
15731 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
15732 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
15733 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
15734 #ifdef SQLITE_DEBUG
15735 SQLITE_PRIVATE int sqlite3NomemError(int);
15736 SQLITE_PRIVATE int sqlite3IoerrnomemError(int);
15737 # define SQLITE_NOMEM_BKPT sqlite3NomemError(__LINE__)
15738 # define SQLITE_IOERR_NOMEM_BKPT sqlite3IoerrnomemError(__LINE__)
15739 #else
15740 # define SQLITE_NOMEM_BKPT SQLITE_NOMEM
15741 # define SQLITE_IOERR_NOMEM_BKPT SQLITE_IOERR_NOMEM
15742 #endif
15743 
15744 /*
15745 ** FTS3 and FTS4 both require virtual table support
15746 */
15747 #if defined(SQLITE_OMIT_VIRTUALTABLE)
15748 # undef SQLITE_ENABLE_FTS3
15749 # undef SQLITE_ENABLE_FTS4
15750 #endif
15751 
15752 /*
15753 ** FTS4 is really an extension for FTS3. It is enabled using the
15754 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
15755 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
15756 */
15757 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
15758 # define SQLITE_ENABLE_FTS3 1
15759 #endif
15760 
15761 /*
15762 ** The ctype.h header is needed for non-ASCII systems. It is also
15763 ** needed by FTS3 when FTS3 is included in the amalgamation.
15764 */
15765 #if !defined(SQLITE_ASCII) || \
15766  (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
15767 # include <ctype.h>
15768 #endif
15769 
15770 /*
15771 ** The following macros mimic the standard library functions toupper(),
15772 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
15773 ** sqlite versions only work for ASCII characters, regardless of locale.
15774 */
15775 #ifdef SQLITE_ASCII
15776 # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
15777 # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
15778 # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
15779 # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
15780 # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
15781 # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
15782 # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
15783 # define sqlite3Isquote(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x80)
15784 #else
15785 # define sqlite3Toupper(x) toupper((unsigned char)(x))
15786 # define sqlite3Isspace(x) isspace((unsigned char)(x))
15787 # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
15788 # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
15789 # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
15790 # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
15791 # define sqlite3Tolower(x) tolower((unsigned char)(x))
15792 # define sqlite3Isquote(x) ((x)=='"'||(x)=='\''||(x)=='['||(x)=='`')
15793 #endif
15794 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
15796 #endif
15797 
15798 /*
15799 ** Internal function prototypes
15800 */
15801 SQLITE_PRIVATE int sqlite3StrICmp(const char*,const char*);
15802 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
15804 #define sqlite3StrNICmp sqlite3_strnicmp
15805 
15807 SQLITE_PRIVATE void sqlite3MallocEnd(void);
15808 SQLITE_PRIVATE void *sqlite3Malloc(u64);
15813 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
15814 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
15815 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
15816 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
15817 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
15818 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
15824 SQLITE_PRIVATE void sqlite3PageFree(void*);
15826 #ifndef SQLITE_OMIT_BUILTIN_TEST
15827 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
15828 #endif
15830 
15831 /*
15832 ** On systems with ample stack space and that support alloca(), make
15833 ** use of alloca() to obtain space for large automatic objects. By default,
15834 ** obtain space from malloc().
15835 **
15836 ** The alloca() routine never returns NULL. This will cause code paths
15837 ** that deal with sqlite3StackAlloc() failures to be unreachable.
15838 */
15839 #ifdef SQLITE_USE_ALLOCA
15840 # define sqlite3StackAllocRaw(D,N) alloca(N)
15841 # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
15842 # define sqlite3StackFree(D,P)
15843 #else
15844 # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
15845 # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
15846 # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
15847 #endif
15848 
15849 #ifdef SQLITE_ENABLE_MEMSYS3
15850 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
15851 #endif
15852 #ifdef SQLITE_ENABLE_MEMSYS5
15853 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
15854 #endif
15855 
15856 
15857 #ifndef SQLITE_MUTEX_OMIT
15863 #endif
15864 #if !defined(SQLITE_MUTEX_OMIT) && !defined(SQLITE_MUTEX_NOOP)
15866 #else
15867 # define sqlite3MemoryBarrier()
15868 #endif
15869 
15870 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
15871 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
15872 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
15873 SQLITE_PRIVATE void sqlite3StatusHighwater(int, int);
15874 
15875 /* Access to mutexes used by sqlite3_status() */
15878 
15879 #ifndef SQLITE_OMIT_FLOATING_POINT
15880 SQLITE_PRIVATE int sqlite3IsNaN(double);
15881 #else
15882 # define sqlite3IsNaN(X) 0
15883 #endif
15884 
15885 /*
15886 ** An instance of the following structure holds information about SQL
15887 ** functions arguments that are the parameters to the printf() function.
15888 */
15890  int nArg; /* Total number of arguments */
15891  int nUsed; /* Number of arguments used so far */
15892  sqlite3_value **apArg; /* The argument values */
15893 };
15894 
15895 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, const char*, va_list);
15896 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
15897 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
15898 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
15899 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
15900 SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
15901 #endif
15902 #if defined(SQLITE_TEST)
15903 SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
15904 #endif
15905 
15906 #if defined(SQLITE_DEBUG)
15907 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
15908 SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
15909 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
15910 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView*, const With*, u8);
15911 #endif
15912 
15913 
15914 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*);
15915 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
15916 SQLITE_PRIVATE void sqlite3Dequote(char*);
15918 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
15919 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
15926 #ifdef SQLITE_DEBUG
15927 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse*,int,int);
15928 #endif
15930 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
15932 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
15944 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
15945 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
15958 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
15959 #if SQLITE_ENABLE_HIDDEN_COLUMNS
15961 #else
15962 # define sqlite3ColumnPropertiesFromName(T,C) /* no-op */
15963 #endif
15966 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
15971 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
15972  sqlite3_vfs**,char**,char **);
15975 
15976 #ifdef SQLITE_OMIT_BUILTIN_TEST
15977 # define sqlite3FaultSim(X) SQLITE_OK
15978 #else
15980 #endif
15981 
15986 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
15989 #ifndef SQLITE_OMIT_BUILTIN_TEST
15991 #endif
15992 
15993 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
15996 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
15998 
16000 
16001 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
16003 #else
16004 # define sqlite3ViewGetColumnNames(A,B) 0
16005 #endif
16006 
16007 #if SQLITE_MAX_ATTACHED>30
16008 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
16009 #endif
16010 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
16011 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
16013 #ifndef SQLITE_OMIT_AUTOINCREMENT
16016 #else
16017 # define sqlite3AutoincrementBegin(X)
16018 # define sqlite3AutoincrementEnd(X)
16019 #endif
16021 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
16023 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
16027  Token*, Select*, Expr*, IdList*);
16030 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
16037  Expr*, int, int);
16041  Expr*,ExprList*,u32,Expr*,Expr*);
16045 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
16046 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
16047 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
16048 #endif
16060 #define ONEPASS_OFF 0 /* Use of ONEPASS not allowed */
16061 #define ONEPASS_SINGLE 1 /* ONEPASS valid for a single row update */
16062 #define ONEPASS_MULTI 2 /* ONEPASS is valid for multiple rows */
16064 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
16067 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
16068 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
16082 #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
16083 #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
16084 #define SQLITE_ECEL_REF 0x04 /* Use ExprList.u.x.iOrderByCol */
16085 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
16086 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
16087 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse*, Expr*, int, int);
16088 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
16089 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
16090 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
16091 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
16092 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
16093 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
16104 #ifndef SQLITE_OMIT_BUILTIN_TEST
16107 #endif
16110 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
16121 #ifdef SQLITE_ENABLE_CURSOR_HINTS
16122 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr*);
16123 #endif
16127 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
16129  Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8,int);
16130 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*, int);
16131 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
16133 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
16134  u8,u8,int,int*,int*);
16135 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
16136 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, u8, int, u8*, int*, int*);
16140 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
16148 #if SELECTTRACE_ENABLED
16149 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
16150 #else
16151 # define sqlite3SelectSetName(A,B)
16152 #endif
16154 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,u8,u8);
16161 
16162 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
16164 #endif
16165 
16166 #ifndef SQLITE_OMIT_TRIGGER
16168  Expr*,int, int);
16175  int, int, int);
16176 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
16177  void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
16181  Select*,u8);
16187 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
16188 # define sqlite3IsToplevel(p) ((p)->pToplevel==0)
16189 #else
16190 # define sqlite3TriggersExist(B,C,D,E,F) 0
16191 # define sqlite3DeleteTrigger(A,B)
16192 # define sqlite3DropTriggerPtr(A,B)
16193 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
16194 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
16195 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
16196 # define sqlite3TriggerList(X, Y) 0
16197 # define sqlite3ParseToplevel(p) p
16198 # define sqlite3IsToplevel(p) 1
16199 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
16200 #endif
16201 
16205 #ifndef SQLITE_OMIT_AUTHORIZATION
16207 SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
16210 SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
16211 #else
16212 # define sqlite3AuthRead(a,b,c,d)
16213 # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
16214 # define sqlite3AuthContextPush(a,b,c)
16215 # define sqlite3AuthContextPop(a) ((void)(a))
16216 #endif
16219 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
16225 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
16226 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
16227 SQLITE_PRIVATE int sqlite3Atoi(const char*);
16228 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
16229 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
16230 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
16231 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
16232 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
16233 #ifndef SQLITE_OMIT_VIRTUALTABLE
16235 #endif
16236 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
16237  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
16238  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
16239 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
16240 #endif
16241 
16242 /*
16243 ** Routines to read and write variable-length integers. These used to
16244 ** be defined locally, but now we use the varint routines in the util.c
16245 ** file.
16246 */
16247 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
16248 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
16249 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
16251 
16252 /*
16253 ** The common case is for a varint to be a single byte. They following
16254 ** macros handle the common case without a procedure call, but then call
16255 ** the procedure for larger varints.
16256 */
16257 #define getVarint32(A,B) \
16258  (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
16259 #define putVarint32(A,B) \
16260  (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
16261  sqlite3PutVarint((A),(B)))
16262 #define getVarint sqlite3GetVarint
16263 #define putVarint sqlite3PutVarint
16264 
16265 
16268 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
16269 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
16271 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
16272 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
16273 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
16276 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
16279 
16280 #if defined(SQLITE_NEED_ERR_NAME)
16281 SQLITE_PRIVATE const char *sqlite3ErrName(int);
16282 #endif
16283 
16284 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
16286 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
16287 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
16293 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
16295 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
16296 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
16297 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
16299 #ifdef SQLITE_ENABLE_8_3_NAMES
16300 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
16301 #else
16302 # define sqlite3FileSuffix3(X,Y)
16303 #endif
16304 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
16305 
16308 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
16309  void(*)(void*));
16313 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
16316 #ifndef SQLITE_AMALGAMATION
16317 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
16318 SQLITE_PRIVATE const char sqlite3StrBINARY[];
16319 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
16320 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
16324 #ifndef SQLITE_OMIT_WSD
16326 #endif
16327 #endif
16328 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
16332 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
16333 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
16335 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
16338 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
16344 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
16347 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
16348 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
16352 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
16358 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
16365 #ifdef SQLITE_DEBUG
16366 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
16367 #endif
16368 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
16369  void (*)(sqlite3_context*,int,sqlite3_value **),
16370  void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
16371  FuncDestructor *pDestructor
16372 );
16375 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
16377 
16378 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, sqlite3*, char*, int, int);
16379 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
16381 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
16386 
16388 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
16389 
16390 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
16391 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
16392 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
16393 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
16394 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
16395 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
16396 #endif
16397 
16398 /*
16399 ** The interface to the LEMON-generated parser
16400 */
16401 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
16402 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
16403 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
16404 #ifdef YYTRACKMAXSTACKDEPTH
16405 SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
16406 #endif
16407 
16409 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16411 #else
16412 # define sqlite3CloseExtensions(X)
16413 #endif
16414 
16415 #ifndef SQLITE_OMIT_SHARED_CACHE
16416 SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
16417 #else
16418  #define sqlite3TableLock(v,w,x,y,z)
16419 #endif
16420 
16421 #ifdef SQLITE_TEST
16422 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
16423 #endif
16424 
16425 #ifdef SQLITE_OMIT_VIRTUALTABLE
16426 # define sqlite3VtabClear(Y)
16427 # define sqlite3VtabSync(X,Y) SQLITE_OK
16428 # define sqlite3VtabRollback(X)
16429 # define sqlite3VtabCommit(X)
16430 # define sqlite3VtabInSync(db) 0
16431 # define sqlite3VtabLock(X)
16432 # define sqlite3VtabUnlock(X)
16433 # define sqlite3VtabUnlockList(X)
16434 # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
16435 # define sqlite3GetVTable(X,Y) ((VTable*)0)
16436 #else
16448 # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
16449 #endif
16457 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
16459 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
16464 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
16471 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
16472 #ifndef SQLITE_OMIT_WAL
16473 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
16474 SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
16475 #endif
16476 #ifndef SQLITE_OMIT_CTE
16480 #else
16481 #define sqlite3WithPush(x,y,z)
16482 #define sqlite3WithDelete(x,y)
16483 #endif
16484 
16485 /* Declarations for functions in fkey.c. All of these are replaced by
16486 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
16487 ** key functionality is available. If OMIT_TRIGGER is defined but
16488 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
16489 ** this case foreign keys are parsed, but no other functionality is
16490 ** provided (enforcement of FK constraints requires the triggers sub-system).
16491 */
16492 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
16493 SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
16495 SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
16496 SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
16499 #else
16500  #define sqlite3FkActions(a,b,c,d,e,f)
16501  #define sqlite3FkCheck(a,b,c,d,e,f)
16502  #define sqlite3FkDropTable(a,b,c)
16503  #define sqlite3FkOldmask(a,b) 0
16504  #define sqlite3FkRequired(a,b,c,d) 0
16505 #endif
16506 #ifndef SQLITE_OMIT_FOREIGN_KEY
16509 #else
16510  #define sqlite3FkDelete(a,b)
16511  #define sqlite3FkLocateIndex(a,b,c,d,e)
16512 #endif
16513 
16514 
16515 /*
16516 ** Available fault injectors. Should be numbered beginning with 0.
16517 */
16518 #define SQLITE_FAULTINJECTOR_MALLOC 0
16519 #define SQLITE_FAULTINJECTOR_COUNT 1
16520 
16521 /*
16522 ** The interface to the code in fault.c used for identifying "benign"
16523 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
16524 ** is not defined.
16525 */
16526 #ifndef SQLITE_OMIT_BUILTIN_TEST
16529 #else
16530  #define sqlite3BeginBenignMalloc()
16531  #define sqlite3EndBenignMalloc()
16532 #endif
16533 
16534 /*
16535 ** Allowed return values from sqlite3FindInIndex()
16536 */
16537 #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
16538 #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
16539 #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
16540 #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
16541 #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
16542 /*
16543 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
16544 */
16545 #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
16546 #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
16547 #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
16548 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
16549 
16550 SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
16551 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
16552 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
16553 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
16554 #endif
16555 
16556 SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p);
16557 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
16558 
16560 #if SQLITE_MAX_EXPR_DEPTH>0
16563 #else
16564  #define sqlite3SelectExprHeight(x) 0
16565  #define sqlite3ExprCheckHeight(x,y)
16566 #endif
16567 
16568 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
16569 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
16570 
16571 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
16575 #else
16576  #define sqlite3ConnectionBlocked(x,y)
16577  #define sqlite3ConnectionUnlocked(x)
16578  #define sqlite3ConnectionClosed(x)
16579 #endif
16580 
16581 #ifdef SQLITE_DEBUG
16582 SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
16583 #endif
16584 
16585 /*
16586 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
16587 ** sqlite3IoTrace is a pointer to a printf-like routine used to
16588 ** print I/O tracing messages.
16589 */
16590 #ifdef SQLITE_ENABLE_IOTRACE
16591 # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
16593 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
16594 #else
16595 # define IOTRACE(A)
16596 # define sqlite3VdbeIOTraceSql(X)
16597 #endif
16598 
16599 /*
16600 ** These routines are available for the mem2.c debugging memory allocator
16601 ** only. They are used to verify that different "types" of memory
16602 ** allocations are properly tracked by the system.
16603 **
16604 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
16605 ** the MEMTYPE_* macros defined below. The type must be a bitmask with
16606 ** a single bit set.
16607 **
16608 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
16609 ** argument match the type set by the previous sqlite3MemdebugSetType().
16610 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
16611 **
16612 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
16613 ** argument match the type set by the previous sqlite3MemdebugSetType().
16614 **
16615 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
16616 ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
16617 ** it might have been allocated by lookaside, except the allocation was
16618 ** too large or lookaside was already full. It is important to verify
16619 ** that allocations that might have been satisfied by lookaside are not
16620 ** passed back to non-lookaside free() routines. Asserts such as the
16621 ** example above are placed on the non-lookaside free() routines to verify
16622 ** this constraint.
16623 **
16624 ** All of this is no-op for a production build. It only comes into
16625 ** play when the SQLITE_MEMDEBUG compile-time option is used.
16626 */
16627 #ifdef SQLITE_MEMDEBUG
16628 SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
16631 #else
16632 # define sqlite3MemdebugSetType(X,Y) /* no-op */
16633 # define sqlite3MemdebugHasType(X,Y) 1
16634 # define sqlite3MemdebugNoType(X,Y) 1
16635 #endif
16636 #define MEMTYPE_HEAP 0x01 /* General heap allocations */
16637 #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
16638 #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
16639 #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
16640 
16641 /*
16642 ** Threading interface
16643 */
16644 #if SQLITE_MAX_WORKER_THREADS>0
16645 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
16647 #endif
16648 
16649 #if defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)
16650 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3*);
16651 #endif
16652 
16653 #endif /* _SQLITEINT_H_ */
16654 
16655 /************** End of sqliteInt.h *******************************************/
16656 /************** Begin file global.c ******************************************/
16657 /*
16658 ** 2008 June 13
16659 **
16660 ** The author disclaims copyright to this source code. In place of
16661 ** a legal notice, here is a blessing:
16662 **
16663 ** May you do good and not evil.
16664 ** May you find forgiveness for yourself and forgive others.
16665 ** May you share freely, never taking more than you give.
16666 **
16667 *************************************************************************
16668 **
16669 ** This file contains definitions of global variables and constants.
16670 */
16671 /* #include "sqliteInt.h" */
16672 
16673 /* An array to map all upper-case characters into their corresponding
16674 ** lower-case character.
16675 **
16676 ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
16677 ** handle case conversions for the UTF character set since the tables
16678 ** involved are nearly as big or bigger than SQLite itself.
16679 */
16680 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
16681 #ifdef SQLITE_ASCII
16682  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
16683  18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
16684  36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
16685  54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
16686  104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
16687  122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
16688  108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
16689  126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
16690  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
16691  162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
16692  180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
16693  198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
16694  216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
16695  234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
16696  252,253,254,255
16697 #endif
16698 #ifdef SQLITE_EBCDIC
16699  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
16700  16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
16701  32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
16702  48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
16703  64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
16704  80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
16705  96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
16706  112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
16707  128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
16708  144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
16709  160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
16710  176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
16711  192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
16712  208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
16713  224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
16714  240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
16715 #endif
16716 };
16717 
16718 /*
16719 ** The following 256 byte lookup table is used to support SQLites built-in
16720 ** equivalents to the following standard library functions:
16721 **
16722 ** isspace() 0x01
16723 ** isalpha() 0x02
16724 ** isdigit() 0x04
16725 ** isalnum() 0x06
16726 ** isxdigit() 0x08
16727 ** toupper() 0x20
16728 ** SQLite identifier character 0x40
16729 ** Quote character 0x80
16730 **
16731 ** Bit 0x20 is set if the mapped character requires translation to upper
16732 ** case. i.e. if the character is a lower-case ASCII character.
16733 ** If x is a lower-case ASCII character, then its upper-case equivalent
16734 ** is (x - 0x20). Therefore toupper() can be implemented as:
16735 **
16736 ** (x & ~(map[x]&0x20))
16737 **
16738 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
16739 ** array. tolower() is used more often than toupper() by SQLite.
16740 **
16741 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
16742 ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
16743 ** non-ASCII UTF character. Hence the test for whether or not a character is
16744 ** part of an identifier is 0x46.
16745 **
16746 ** SQLite's versions are identical to the standard versions assuming a
16747 ** locale of "C". They are implemented as macros in sqliteInt.h.
16748 */
16749 #ifdef SQLITE_ASCII
16750 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
16751  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
16752  0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
16753  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
16754  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
16755  0x01, 0x00, 0x80, 0x00, 0x40, 0x00, 0x00, 0x80, /* 20..27 !"#$%&' */
16756  0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
16757  0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
16758  0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
16759 
16760  0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
16761  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
16762  0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
16763  0x02, 0x02, 0x02, 0x80, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
16764  0x80, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
16765  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
16766  0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
16767  0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
16768 
16769  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
16770  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
16771  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
16772  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
16773  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
16774  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
16775  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
16776  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
16777 
16778  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
16779  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
16780  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
16781  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
16782  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
16783  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
16784  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
16785  0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
16786 };
16787 #endif
16788 
16789 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
16790 ** compatibility for legacy applications, the URI filename capability is
16791 ** disabled by default.
16792 **
16793 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
16794 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
16795 **
16796 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
16797 ** disabled. The default value may be changed by compiling with the
16798 ** SQLITE_USE_URI symbol defined.
16799 */
16800 #ifndef SQLITE_USE_URI
16801 # define SQLITE_USE_URI 0
16802 #endif
16803 
16804 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
16805 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
16806 ** that compile-time option is omitted.
16807 */
16808 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
16809 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
16810 #endif
16811 
16812 /* The minimum PMA size is set to this value multiplied by the database
16813 ** page size in bytes.
16814 */
16815 #ifndef SQLITE_SORTER_PMASZ
16816 # define SQLITE_SORTER_PMASZ 250
16817 #endif
16818 
16819 /* Statement journals spill to disk when their size exceeds the following
16820 ** threashold (in bytes). 0 means that statement journals are created and
16821 ** written to disk immediately (the default behavior for SQLite versions
16822 ** before 3.12.0). -1 means always keep the entire statement journal in
16823 ** memory. (The statement journal is also always held entirely in memory
16824 ** if journal_mode=MEMORY or if temp_store=MEMORY, regardless of this
16825 ** setting.)
16826 */
16827 #ifndef SQLITE_STMTJRNL_SPILL
16828 # define SQLITE_STMTJRNL_SPILL (64*1024)
16829 #endif
16830 
16831 /*
16832 ** The following singleton contains the global configuration for
16833 ** the SQLite library.
16834 */
16836  SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
16837  1, /* bCoreMutex */
16838  SQLITE_THREADSAFE==1, /* bFullMutex */
16839  SQLITE_USE_URI, /* bOpenUri */
16840  SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
16841  0x7ffffffe, /* mxStrlen */
16842  0, /* neverCorrupt */
16843  128, /* szLookaside */
16844  500, /* nLookaside */
16845  SQLITE_STMTJRNL_SPILL, /* nStmtSpill */
16846  {0,0,0,0,0,0,0,0}, /* m */
16847  {0,0,0,0,0,0,0,0,0}, /* mutex */
16848  {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
16849  (void*)0, /* pHeap */
16850  0, /* nHeap */
16851  0, 0, /* mnHeap, mxHeap */
16852  SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
16853  SQLITE_MAX_MMAP_SIZE, /* mxMmap */
16854  (void*)0, /* pScratch */
16855  0, /* szScratch */
16856  0, /* nScratch */
16857  (void*)0, /* pPage */
16858  0, /* szPage */
16859  SQLITE_DEFAULT_PCACHE_INITSZ, /* nPage */
16860  0, /* mxParserStack */
16861  0, /* sharedCacheEnabled */
16862  SQLITE_SORTER_PMASZ, /* szPma */
16863  /* All the rest should always be initialized to zero */
16864  0, /* isInit */
16865  0, /* inProgress */
16866  0, /* isMutexInit */
16867  0, /* isMallocInit */
16868  0, /* isPCacheInit */
16869  0, /* nRefInitMutex */
16870  0, /* pInitMutex */
16871  0, /* xLog */
16872  0, /* pLogArg */
16873 #ifdef SQLITE_ENABLE_SQLLOG
16874  0, /* xSqllog */
16875  0, /* pSqllogArg */
16876 #endif
16877 #ifdef SQLITE_VDBE_COVERAGE
16878  0, /* xVdbeBranch */
16879  0, /* pVbeBranchArg */
16880 #endif
16881 #ifndef SQLITE_OMIT_BUILTIN_TEST
16882  0, /* xTestCallback */
16883 #endif
16884  0 /* bLocaltimeFault */
16885 };
16886 
16887 /*
16888 ** Hash table for global functions - functions common to all
16889 ** database connections. After initialization, this table is
16890 ** read-only.
16891 */
16893 
16894 /*
16895 ** Constant tokens for values 0 and 1.
16896 */
16897 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
16898  { "0", 1 },
16899  { "1", 1 }
16900 };
16901 
16902 
16903 /*
16904 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
16905 ** 1-gibabyte boundary) in a compatible database. SQLite never uses
16906 ** the database page that contains the pending byte. It never attempts
16907 ** to read or write that page. The pending byte page is set assign
16908 ** for use by the VFS layers as space for managing file locks.
16909 **
16910 ** During testing, it is often desirable to move the pending byte to
16911 ** a different position in the file. This allows code that has to
16912 ** deal with the pending byte to run on files that are much smaller
16913 ** than 1 GiB. The sqlite3_test_control() interface can be used to
16914 ** move the pending byte.
16915 **
16916 ** IMPORTANT: Changing the pending byte to any value other than
16917 ** 0x40000000 results in an incompatible database file format!
16918 ** Changing the pending byte during operation will result in undefined
16919 ** and incorrect behavior.
16920 */
16921 #ifndef SQLITE_OMIT_WSD
16922 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
16923 #endif
16924 
16925 /* #include "opcodes.h" */
16926 /*
16927 ** Properties of opcodes. The OPFLG_INITIALIZER macro is
16928 ** created by mkopcodeh.awk during compilation. Data is obtained
16929 ** from the comments following the "case OP_xxxx:" statements in
16930 ** the vdbe.c file.
16931 */
16932 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
16933 
16934 /*
16935 ** Name of the default collating sequence
16936 */
16937 SQLITE_PRIVATE const char sqlite3StrBINARY[] = "BINARY";
16938 
16939 /************** End of global.c **********************************************/
16940 /************** Begin file ctime.c *******************************************/
16941 /*
16942 ** 2010 February 23
16943 **
16944 ** The author disclaims copyright to this source code. In place of
16945 ** a legal notice, here is a blessing:
16946 **
16947 ** May you do good and not evil.
16948 ** May you find forgiveness for yourself and forgive others.
16949 ** May you share freely, never taking more than you give.
16950 **
16951 *************************************************************************
16952 **
16953 ** This file implements routines used to report what compile-time options
16954 ** SQLite was built with.
16955 */
16956 
16957 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
16958 
16959 /* #include "sqliteInt.h" */
16960 
16961 /*
16962 ** An array of names of all compile-time options. This array should
16963 ** be sorted A-Z.
16964 **
16965 ** This array looks large, but in a typical installation actually uses
16966 ** only a handful of compile-time options, so most times this array is usually
16967 ** rather short and uses little memory space.
16968 */
16969 static const char * const azCompileOpt[] = {
16970 
16971 /* These macros are provided to "stringify" the value of the define
16972 ** for those options in which the value is meaningful. */
16973 #define CTIMEOPT_VAL_(opt) #opt
16974 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
16975 
16976 #if SQLITE_32BIT_ROWID
16977  "32BIT_ROWID",
16978 #endif
16979 #if SQLITE_4_BYTE_ALIGNED_MALLOC
16980  "4_BYTE_ALIGNED_MALLOC",
16981 #endif
16982 #if SQLITE_CASE_SENSITIVE_LIKE
16983  "CASE_SENSITIVE_LIKE",
16984 #endif
16985 #if SQLITE_CHECK_PAGES
16986  "CHECK_PAGES",
16987 #endif
16988 #if SQLITE_COVERAGE_TEST
16989  "COVERAGE_TEST",
16990 #endif
16991 #if SQLITE_DEBUG
16992  "DEBUG",
16993 #endif
16994 #if SQLITE_DEFAULT_LOCKING_MODE
16995  "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
16996 #endif
16997 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
16998  "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
16999 #endif
17000 #if SQLITE_DISABLE_DIRSYNC
17001  "DISABLE_DIRSYNC",
17002 #endif
17003 #if SQLITE_DISABLE_LFS
17004  "DISABLE_LFS",
17005 #endif
17006 #if SQLITE_ENABLE_8_3_NAMES
17007  "ENABLE_8_3_NAMES",
17008 #endif
17009 #if SQLITE_ENABLE_API_ARMOR
17010  "ENABLE_API_ARMOR",
17011 #endif
17012 #if SQLITE_ENABLE_ATOMIC_WRITE
17013  "ENABLE_ATOMIC_WRITE",
17014 #endif
17015 #if SQLITE_ENABLE_CEROD
17016  "ENABLE_CEROD",
17017 #endif
17018 #if SQLITE_ENABLE_COLUMN_METADATA
17019  "ENABLE_COLUMN_METADATA",
17020 #endif
17021 #if SQLITE_ENABLE_DBSTAT_VTAB
17022  "ENABLE_DBSTAT_VTAB",
17023 #endif
17024 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
17025  "ENABLE_EXPENSIVE_ASSERT",
17026 #endif
17027 #if SQLITE_ENABLE_FTS1
17028  "ENABLE_FTS1",
17029 #endif
17030 #if SQLITE_ENABLE_FTS2
17031  "ENABLE_FTS2",
17032 #endif
17033 #if SQLITE_ENABLE_FTS3
17034  "ENABLE_FTS3",
17035 #endif
17036 #if SQLITE_ENABLE_FTS3_PARENTHESIS
17037  "ENABLE_FTS3_PARENTHESIS",
17038 #endif
17039 #if SQLITE_ENABLE_FTS4
17040  "ENABLE_FTS4",
17041 #endif
17042 #if SQLITE_ENABLE_FTS5
17043  "ENABLE_FTS5",
17044 #endif
17045 #if SQLITE_ENABLE_ICU
17046  "ENABLE_ICU",
17047 #endif
17048 #if SQLITE_ENABLE_IOTRACE
17049  "ENABLE_IOTRACE",
17050 #endif
17051 #if SQLITE_ENABLE_JSON1
17052  "ENABLE_JSON1",
17053 #endif
17054 #if SQLITE_ENABLE_LOAD_EXTENSION
17055  "ENABLE_LOAD_EXTENSION",
17056 #endif
17057 #if SQLITE_ENABLE_LOCKING_STYLE
17058  "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
17059 #endif
17060 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
17061  "ENABLE_MEMORY_MANAGEMENT",
17062 #endif
17063 #if SQLITE_ENABLE_MEMSYS3
17064  "ENABLE_MEMSYS3",
17065 #endif
17066 #if SQLITE_ENABLE_MEMSYS5
17067  "ENABLE_MEMSYS5",
17068 #endif
17069 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
17070  "ENABLE_OVERSIZE_CELL_CHECK",
17071 #endif
17072 #if SQLITE_ENABLE_RTREE
17073  "ENABLE_RTREE",
17074 #endif
17075 #if defined(SQLITE_ENABLE_STAT4)
17076  "ENABLE_STAT4",
17077 #elif defined(SQLITE_ENABLE_STAT3)
17078  "ENABLE_STAT3",
17079 #endif
17080 #if SQLITE_ENABLE_UNLOCK_NOTIFY
17081  "ENABLE_UNLOCK_NOTIFY",
17082 #endif
17083 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
17084  "ENABLE_UPDATE_DELETE_LIMIT",
17085 #endif
17086 #if SQLITE_HAS_CODEC
17087  "HAS_CODEC",
17088 #endif
17089 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
17090  "HAVE_ISNAN",
17091 #endif
17092 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
17093  "HOMEGROWN_RECURSIVE_MUTEX",
17094 #endif
17095 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
17096  "IGNORE_AFP_LOCK_ERRORS",
17097 #endif
17098 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
17099  "IGNORE_FLOCK_LOCK_ERRORS",
17100 #endif
17101 #ifdef SQLITE_INT64_TYPE
17102  "INT64_TYPE",
17103 #endif
17104 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
17105  "LIKE_DOESNT_MATCH_BLOBS",
17106 #endif
17107 #if SQLITE_LOCK_TRACE
17108  "LOCK_TRACE",
17109 #endif
17110 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
17111  "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
17112 #endif
17113 #ifdef SQLITE_MAX_SCHEMA_RETRY
17114  "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
17115 #endif
17116 #if SQLITE_MEMDEBUG
17117  "MEMDEBUG",
17118 #endif
17119 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
17120  "MIXED_ENDIAN_64BIT_FLOAT",
17121 #endif
17122 #if SQLITE_NO_SYNC
17123  "NO_SYNC",
17124 #endif
17125 #if SQLITE_OMIT_ALTERTABLE
17126  "OMIT_ALTERTABLE",
17127 #endif
17128 #if SQLITE_OMIT_ANALYZE
17129  "OMIT_ANALYZE",
17130 #endif
17131 #if SQLITE_OMIT_ATTACH
17132  "OMIT_ATTACH",
17133 #endif
17134 #if SQLITE_OMIT_AUTHORIZATION
17135  "OMIT_AUTHORIZATION",
17136 #endif
17137 #if SQLITE_OMIT_AUTOINCREMENT
17138  "OMIT_AUTOINCREMENT",
17139 #endif
17140 #if SQLITE_OMIT_AUTOINIT
17141  "OMIT_AUTOINIT",
17142 #endif
17143 #if SQLITE_OMIT_AUTOMATIC_INDEX
17144  "OMIT_AUTOMATIC_INDEX",
17145 #endif
17146 #if SQLITE_OMIT_AUTORESET
17147  "OMIT_AUTORESET",
17148 #endif
17149 #if SQLITE_OMIT_AUTOVACUUM
17150  "OMIT_AUTOVACUUM",
17151 #endif
17152 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
17153  "OMIT_BETWEEN_OPTIMIZATION",
17154 #endif
17155 #if SQLITE_OMIT_BLOB_LITERAL
17156  "OMIT_BLOB_LITERAL",
17157 #endif
17158 #if SQLITE_OMIT_BTREECOUNT
17159  "OMIT_BTREECOUNT",
17160 #endif
17161 #if SQLITE_OMIT_BUILTIN_TEST
17162  "OMIT_BUILTIN_TEST",
17163 #endif
17164 #if SQLITE_OMIT_CAST
17165  "OMIT_CAST",
17166 #endif
17167 #if SQLITE_OMIT_CHECK
17168  "OMIT_CHECK",
17169 #endif
17170 #if SQLITE_OMIT_COMPLETE
17171  "OMIT_COMPLETE",
17172 #endif
17173 #if SQLITE_OMIT_COMPOUND_SELECT
17174  "OMIT_COMPOUND_SELECT",
17175 #endif
17176 #if SQLITE_OMIT_CTE
17177  "OMIT_CTE",
17178 #endif
17179 #if SQLITE_OMIT_DATETIME_FUNCS
17180  "OMIT_DATETIME_FUNCS",
17181 #endif
17182 #if SQLITE_OMIT_DECLTYPE
17183  "OMIT_DECLTYPE",
17184 #endif
17185 #if SQLITE_OMIT_DEPRECATED
17186  "OMIT_DEPRECATED",
17187 #endif
17188 #if SQLITE_OMIT_DISKIO
17189  "OMIT_DISKIO",
17190 #endif
17191 #if SQLITE_OMIT_EXPLAIN
17192  "OMIT_EXPLAIN",
17193 #endif
17194 #if SQLITE_OMIT_FLAG_PRAGMAS
17195  "OMIT_FLAG_PRAGMAS",
17196 #endif
17197 #if SQLITE_OMIT_FLOATING_POINT
17198  "OMIT_FLOATING_POINT",
17199 #endif
17200 #if SQLITE_OMIT_FOREIGN_KEY
17201  "OMIT_FOREIGN_KEY",
17202 #endif
17203 #if SQLITE_OMIT_GET_TABLE
17204  "OMIT_GET_TABLE",
17205 #endif
17206 #if SQLITE_OMIT_INCRBLOB
17207  "OMIT_INCRBLOB",
17208 #endif
17209 #if SQLITE_OMIT_INTEGRITY_CHECK
17210  "OMIT_INTEGRITY_CHECK",
17211 #endif
17212 #if SQLITE_OMIT_LIKE_OPTIMIZATION
17213  "OMIT_LIKE_OPTIMIZATION",
17214 #endif
17215 #if SQLITE_OMIT_LOAD_EXTENSION
17216  "OMIT_LOAD_EXTENSION",
17217 #endif
17218 #if SQLITE_OMIT_LOCALTIME
17219  "OMIT_LOCALTIME",
17220 #endif
17221 #if SQLITE_OMIT_LOOKASIDE
17222  "OMIT_LOOKASIDE",
17223 #endif
17224 #if SQLITE_OMIT_MEMORYDB
17225  "OMIT_MEMORYDB",
17226 #endif
17227 #if SQLITE_OMIT_OR_OPTIMIZATION
17228  "OMIT_OR_OPTIMIZATION",
17229 #endif
17230 #if SQLITE_OMIT_PAGER_PRAGMAS
17231  "OMIT_PAGER_PRAGMAS",
17232 #endif
17233 #if SQLITE_OMIT_PRAGMA
17234  "OMIT_PRAGMA",
17235 #endif
17236 #if SQLITE_OMIT_PROGRESS_CALLBACK
17237  "OMIT_PROGRESS_CALLBACK",
17238 #endif
17239 #if SQLITE_OMIT_QUICKBALANCE
17240  "OMIT_QUICKBALANCE",
17241 #endif
17242 #if SQLITE_OMIT_REINDEX
17243  "OMIT_REINDEX",
17244 #endif
17245 #if SQLITE_OMIT_SCHEMA_PRAGMAS
17246  "OMIT_SCHEMA_PRAGMAS",
17247 #endif
17248 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
17249  "OMIT_SCHEMA_VERSION_PRAGMAS",
17250 #endif
17251 #if SQLITE_OMIT_SHARED_CACHE
17252  "OMIT_SHARED_CACHE",
17253 #endif
17254 #if SQLITE_OMIT_SUBQUERY
17255  "OMIT_SUBQUERY",
17256 #endif
17257 #if SQLITE_OMIT_TCL_VARIABLE
17258  "OMIT_TCL_VARIABLE",
17259 #endif
17260 #if SQLITE_OMIT_TEMPDB
17261  "OMIT_TEMPDB",
17262 #endif
17263 #if SQLITE_OMIT_TRACE
17264  "OMIT_TRACE",
17265 #endif
17266 #if SQLITE_OMIT_TRIGGER
17267  "OMIT_TRIGGER",
17268 #endif
17269 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
17270  "OMIT_TRUNCATE_OPTIMIZATION",
17271 #endif
17272 #if SQLITE_OMIT_UTF16
17273  "OMIT_UTF16",
17274 #endif
17275 #if SQLITE_OMIT_VACUUM
17276  "OMIT_VACUUM",
17277 #endif
17278 #if SQLITE_OMIT_VIEW
17279  "OMIT_VIEW",
17280 #endif
17281 #if SQLITE_OMIT_VIRTUALTABLE
17282  "OMIT_VIRTUALTABLE",
17283 #endif
17284 #if SQLITE_OMIT_WAL
17285  "OMIT_WAL",
17286 #endif
17287 #if SQLITE_OMIT_WSD
17288  "OMIT_WSD",
17289 #endif
17290 #if SQLITE_OMIT_XFER_OPT
17291  "OMIT_XFER_OPT",
17292 #endif
17293 #if SQLITE_PERFORMANCE_TRACE
17294  "PERFORMANCE_TRACE",
17295 #endif
17296 #if SQLITE_PROXY_DEBUG
17297  "PROXY_DEBUG",
17298 #endif
17299 #if SQLITE_RTREE_INT_ONLY
17300  "RTREE_INT_ONLY",
17301 #endif
17302 #if SQLITE_SECURE_DELETE
17303  "SECURE_DELETE",
17304 #endif
17305 #if SQLITE_SMALL_STACK
17306  "SMALL_STACK",
17307 #endif
17308 #if SQLITE_SOUNDEX
17309  "SOUNDEX",
17310 #endif
17311 #if SQLITE_SYSTEM_MALLOC
17312  "SYSTEM_MALLOC",
17313 #endif
17314 #if SQLITE_TCL
17315  "TCL",
17316 #endif
17317 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
17318  "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
17319 #endif
17320 #if SQLITE_TEST
17321  "TEST",
17322 #endif
17323 #if defined(SQLITE_THREADSAFE)
17324  "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
17325 #endif
17326 #if SQLITE_USE_ALLOCA
17327  "USE_ALLOCA",
17328 #endif
17329 #if SQLITE_USER_AUTHENTICATION
17330  "USER_AUTHENTICATION",
17331 #endif
17332 #if SQLITE_WIN32_MALLOC
17333  "WIN32_MALLOC",
17334 #endif
17335 #if SQLITE_ZERO_MALLOC
17336  "ZERO_MALLOC"
17337 #endif
17338 };
17339 
17340 /*
17341 ** Given the name of a compile-time option, return true if that option
17342 ** was used and false if not.
17343 **
17344 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
17345 ** is not required for a match.
17346 */
17348  int i, n;
17349 
17350 #if SQLITE_ENABLE_API_ARMOR
17351  if( zOptName==0 ){
17353  return 0;
17354  }
17355 #endif
17356  if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
17357  n = sqlite3Strlen30(zOptName);
17358 
17359  /* Since ArraySize(azCompileOpt) is normally in single digits, a
17360  ** linear search is adequate. No need for a binary search. */
17361  for(i=0; i<ArraySize(azCompileOpt); i++){
17362  if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
17363  && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
17364  ){
17365  return 1;
17366  }
17367  }
17368  return 0;
17369 }
17370 
17371 /*
17372 ** Return the N-th compile-time option string. If N is out of range,
17373 ** return a NULL pointer.
17374 */
17376  if( N>=0 && N<ArraySize(azCompileOpt) ){
17377  return azCompileOpt[N];
17378  }
17379  return 0;
17380 }
17381 
17382 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
17383 
17384 /************** End of ctime.c ***********************************************/
17385 /************** Begin file status.c ******************************************/
17386 /*
17387 ** 2008 June 18
17388 **
17389 ** The author disclaims copyright to this source code. In place of
17390 ** a legal notice, here is a blessing:
17391 **
17392 ** May you do good and not evil.
17393 ** May you find forgiveness for yourself and forgive others.
17394 ** May you share freely, never taking more than you give.
17395 **
17396 *************************************************************************
17397 **
17398 ** This module implements the sqlite3_status() interface and related
17399 ** functionality.
17400 */
17401 /* #include "sqliteInt.h" */
17402 /************** Include vdbeInt.h in the middle of status.c ******************/
17403 /************** Begin file vdbeInt.h *****************************************/
17404 /*
17405 ** 2003 September 6
17406 **
17407 ** The author disclaims copyright to this source code. In place of
17408 ** a legal notice, here is a blessing:
17409 **
17410 ** May you do good and not evil.
17411 ** May you find forgiveness for yourself and forgive others.
17412 ** May you share freely, never taking more than you give.
17413 **
17414 *************************************************************************
17415 ** This is the header file for information that is private to the
17416 ** VDBE. This information used to all be at the top of the single
17417 ** source code file "vdbe.c". When that file became too big (over
17418 ** 6000 lines long) it was split up into several smaller files and
17419 ** this header information was factored out.
17420 */
17421 #ifndef _VDBEINT_H_
17422 #define _VDBEINT_H_
17423 
17424 /*
17425 ** The maximum number of times that a statement will try to reparse
17426 ** itself before giving up and returning SQLITE_SCHEMA.
17427 */
17428 #ifndef SQLITE_MAX_SCHEMA_RETRY
17429 # define SQLITE_MAX_SCHEMA_RETRY 50
17430 #endif
17431 
17432 /*
17433 ** VDBE_DISPLAY_P4 is true or false depending on whether or not the
17434 ** "explain" P4 display logic is enabled.
17435 */
17436 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
17437  || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
17438 # define VDBE_DISPLAY_P4 1
17439 #else
17440 # define VDBE_DISPLAY_P4 0
17441 #endif
17442 
17443 /*
17444 ** SQL is translated into a sequence of instructions to be
17445 ** executed by a virtual machine. Each instruction is an instance
17446 ** of the following structure.
17447 */
17448 typedef struct VdbeOp Op;
17449 
17450 /*
17451 ** Boolean values
17452 */
17453 typedef unsigned Bool;
17454 
17455 /* Opaque type used by code in vdbesort.c */
17456 typedef struct VdbeSorter VdbeSorter;
17457 
17458 /* Opaque type used by the explainer */
17459 typedef struct Explain Explain;
17460 
17461 /* Elements of the linked list at Vdbe.pAuxData */
17462 typedef struct AuxData AuxData;
17463 
17464 /* Types of VDBE cursors */
17465 #define CURTYPE_BTREE 0
17466 #define CURTYPE_SORTER 1
17467 #define CURTYPE_VTAB 2
17468 #define CURTYPE_PSEUDO 3
17469 
17470 /*
17471 ** A VdbeCursor is an superclass (a wrapper) for various cursor objects:
17472 **
17473 ** * A b-tree cursor
17474 ** - In the main database or in an ephemeral database
17475 ** - On either an index or a table
17476 ** * A sorter
17477 ** * A virtual table
17478 ** * A one-row "pseudotable" stored in a single register
17479 */
17480 typedef struct VdbeCursor VdbeCursor;
17481 struct VdbeCursor {
17482  u8 eCurType; /* One of the CURTYPE_* values above */
17483  i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
17484  u8 nullRow; /* True if pointing to a row with no data */
17485  u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
17486  u8 isTable; /* True for rowid tables. False for indexes */
17487 #ifdef SQLITE_DEBUG
17488  u8 seekOp; /* Most recent seek operation on this cursor */
17489  u8 wrFlag; /* The wrFlag argument to sqlite3BtreeCursor() */
17490 #endif
17491  Bool isEphemeral:1; /* True for an ephemeral table */
17492  Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
17493  Bool isOrdered:1; /* True if the table is not BTREE_UNORDERED */
17494  Pgno pgnoRoot; /* Root page of the open btree cursor */
17495  i16 nField; /* Number of fields in the header */
17496  u16 nHdrParsed; /* Number of header fields parsed so far */
17497  union {
17498  BtCursor *pCursor; /* CURTYPE_BTREE. Btree cursor */
17499  sqlite3_vtab_cursor *pVCur; /* CURTYPE_VTAB. Vtab cursor */
17500  int pseudoTableReg; /* CURTYPE_PSEUDO. Reg holding content. */
17501  VdbeSorter *pSorter; /* CURTYPE_SORTER. Sorter object */
17502  } uc;
17503  Btree *pBt; /* Separate file holding temporary table */
17504  KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
17505  int seekResult; /* Result of previous sqlite3BtreeMoveto() */
17506  i64 seqCount; /* Sequence counter */
17507  i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
17508  VdbeCursor *pAltCursor; /* Associated index cursor from which to read */
17509  int *aAltMap; /* Mapping from table to index column numbers */
17510 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
17511  u64 maskUsed; /* Mask of columns used by this cursor */
17512 #endif
17513 
17514  /* Cached information about the header for the data record that the
17515  ** cursor is currently pointing to. Only valid if cacheStatus matches
17516  ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
17517  ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
17518  ** the cache is out of date.
17519  **
17520  ** aRow might point to (ephemeral) data for the current row, or it might
17521  ** be NULL.
17522  */
17523  u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
17524  u32 payloadSize; /* Total number of bytes in the record */
17525  u32 szRow; /* Byte available in aRow */
17526  u32 iHdrOffset; /* Offset to next unparsed byte of the header */
17527  const u8 *aRow; /* Data for the current row, if all on one page */
17528  u32 *aOffset; /* Pointer to aType[nField] */
17529  u32 aType[1]; /* Type values for all entries in the record */
17530  /* 2*nField extra array elements allocated for aType[], beyond the one
17531  ** static element declared in the structure. nField total array slots for
17532  ** aType[] and nField+1 array slots for aOffset[] */
17533 };
17534 
17535 /*
17536 ** When a sub-program is executed (OP_Program), a structure of this type
17537 ** is allocated to store the current value of the program counter, as
17538 ** well as the current memory cell array and various other frame specific
17539 ** values stored in the Vdbe struct. When the sub-program is finished,
17540 ** these values are copied back to the Vdbe from the VdbeFrame structure,
17541 ** restoring the state of the VM to as it was before the sub-program
17542 ** began executing.
17543 **
17544 ** The memory for a VdbeFrame object is allocated and managed by a memory
17545 ** cell in the parent (calling) frame. When the memory cell is deleted or
17546 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
17547 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
17548 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
17549 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
17550 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
17551 ** child frame are released.
17552 **
17553 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
17554 ** set to NULL if the currently executing frame is the main program.
17555 */
17556 typedef struct VdbeFrame VdbeFrame;
17557 struct VdbeFrame {
17558  Vdbe *v; /* VM this frame belongs to */
17559  VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
17560  Op *aOp; /* Program instructions for parent frame */
17561  i64 *anExec; /* Event counters from parent frame */
17562  Mem *aMem; /* Array of memory cells for parent frame */
17563  u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
17564  VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
17565  void *token; /* Copy of SubProgram.token */
17566  i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
17567  AuxData *pAuxData; /* Linked list of auxdata allocations */
17568  int nCursor; /* Number of entries in apCsr */
17569  int pc; /* Program Counter in parent (calling) frame */
17570  int nOp; /* Size of aOp array */
17571  int nMem; /* Number of entries in aMem */
17572  int nOnceFlag; /* Number of entries in aOnceFlag */
17573  int nChildMem; /* Number of memory cells for child frame */
17574  int nChildCsr; /* Number of cursors for child frame */
17575  int nChange; /* Statement changes (Vdbe.nChange) */
17576  int nDbChange; /* Value of db->nChange */
17577 };
17578 
17579 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
17580 
17581 /*
17582 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
17583 */
17584 #define CACHE_STALE 0
17585 
17586 /*
17587 ** Internally, the vdbe manipulates nearly all SQL values as Mem
17588 ** structures. Each Mem struct may cache multiple representations (string,
17589 ** integer etc.) of the same value.
17590 */
17591 struct Mem {
17592  union MemValue {
17593  double r; /* Real value used when MEM_Real is set in flags */
17594  i64 i; /* Integer value used when MEM_Int is set in flags */
17595  int nZero; /* Used when bit MEM_Zero is set in flags */
17596  FuncDef *pDef; /* Used only when flags==MEM_Agg */
17597  RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
17598  VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
17599  } u;
17600  u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
17601  u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
17602  u8 eSubtype; /* Subtype for this value */
17603  int n; /* Number of characters in string value, excluding '\0' */
17604  char *z; /* String or BLOB value */
17605  /* ShallowCopy only needs to copy the information above */
17606  char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
17607  int szMalloc; /* Size of the zMalloc allocation */
17608  u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
17609  sqlite3 *db; /* The associated database connection */
17610  void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
17611 #ifdef SQLITE_DEBUG
17612  Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
17613  void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
17614 #endif
17615 };
17616 
17617 /*
17618 ** Size of struct Mem not including the Mem.zMalloc member or anything that
17619 ** follows.
17620 */
17621 #define MEMCELLSIZE offsetof(Mem,zMalloc)
17622 
17623 /* One or more of the following flags are set to indicate the validOK
17624 ** representations of the value stored in the Mem struct.
17625 **
17626 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
17627 ** No other flags may be set in this case.
17628 **
17629 ** If the MEM_Str flag is set then Mem.z points at a string representation.
17630 ** Usually this is encoded in the same unicode encoding as the main
17631 ** database (see below for exceptions). If the MEM_Term flag is also
17632 ** set, then the string is nul terminated. The MEM_Int and MEM_Real
17633 ** flags may coexist with the MEM_Str flag.
17634 */
17635 #define MEM_Null 0x0001 /* Value is NULL */
17636 #define MEM_Str 0x0002 /* Value is a string */
17637 #define MEM_Int 0x0004 /* Value is an integer */
17638 #define MEM_Real 0x0008 /* Value is a real number */
17639 #define MEM_Blob 0x0010 /* Value is a BLOB */
17640 #define MEM_AffMask 0x001f /* Mask of affinity bits */
17641 #define MEM_RowSet 0x0020 /* Value is a RowSet object */
17642 #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
17643 #define MEM_Undefined 0x0080 /* Value is undefined */
17644 #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
17645 #define MEM_TypeMask 0x81ff /* Mask of type bits */
17646 
17647 
17648 /* Whenever Mem contains a valid string or blob representation, one of
17649 ** the following flags must be set to determine the memory management
17650 ** policy for Mem.z. The MEM_Term flag tells us whether or not the
17651 ** string is \000 or \u0000 terminated
17652 */
17653 #define MEM_Term 0x0200 /* String rep is nul terminated */
17654 #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
17655 #define MEM_Static 0x0800 /* Mem.z points to a static string */
17656 #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
17657 #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
17658 #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
17659 #define MEM_Subtype 0x8000 /* Mem.eSubtype is valid */
17660 #ifdef SQLITE_OMIT_INCRBLOB
17661  #undef MEM_Zero
17662  #define MEM_Zero 0x0000
17663 #endif
17664 
17665 /* Return TRUE if Mem X contains dynamically allocated content - anything
17666 ** that needs to be deallocated to avoid a leak.
17667 */
17668 #define VdbeMemDynamic(X) \
17669  (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
17670 
17671 /*
17672 ** Clear any existing type flags from a Mem and replace them with f
17673 */
17674 #define MemSetTypeFlag(p, f) \
17675  ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
17676 
17677 /*
17678 ** Return true if a memory cell is not marked as invalid. This macro
17679 ** is for use inside assert() statements only.
17680 */
17681 #ifdef SQLITE_DEBUG
17682 #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
17683 #endif
17684 
17685 /*
17686 ** Each auxiliary data pointer stored by a user defined function
17687 ** implementation calling sqlite3_set_auxdata() is stored in an instance
17688 ** of this structure. All such structures associated with a single VM
17689 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
17690 ** when the VM is halted (if not before).
17691 */
17692 struct AuxData {
17693  int iOp; /* Instruction number of OP_Function opcode */
17694  int iArg; /* Index of function argument. */
17695  void *pAux; /* Aux data pointer */
17696  void (*xDelete)(void *); /* Destructor for the aux data */
17697  AuxData *pNext; /* Next element in list */
17698 };
17699 
17700 /*
17701 ** The "context" argument for an installable function. A pointer to an
17702 ** instance of this structure is the first argument to the routines used
17703 ** implement the SQL functions.
17704 **
17705 ** There is a typedef for this structure in sqlite.h. So all routines,
17706 ** even the public interface to SQLite, can use a pointer to this structure.
17707 ** But this file is the only place where the internal details of this
17708 ** structure are known.
17709 **
17710 ** This structure is defined inside of vdbeInt.h because it uses substructures
17711 ** (Mem) which are only defined there.
17712 */
17714  Mem *pOut; /* The return value is stored here */
17715  FuncDef *pFunc; /* Pointer to function information */
17716  Mem *pMem; /* Memory cell used to store aggregate context */
17717  Vdbe *pVdbe; /* The VM that owns this context */
17718  int iOp; /* Instruction number of OP_Function */
17719  int isError; /* Error code returned by the function. */
17720  u8 skipFlag; /* Skip accumulator loading if true */
17721  u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
17722  u8 argc; /* Number of arguments */
17723  sqlite3_value *argv[1]; /* Argument set */
17724 };
17725 
17726 /*
17727 ** An Explain object accumulates indented output which is helpful
17728 ** in describing recursive data structures.
17729 */
17730 struct Explain {
17731  Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
17732  StrAccum str; /* The string being accumulated */
17733  int nIndent; /* Number of elements in aIndent */
17734  u16 aIndent[100]; /* Levels of indentation */
17735  char zBase[100]; /* Initial space */
17736 };
17737 
17738 /* A bitfield type for use inside of structures. Always follow with :N where
17739 ** N is the number of bits.
17740 */
17741 typedef unsigned bft; /* Bit Field Type */
17742 
17743 typedef struct ScanStatus ScanStatus;
17744 struct ScanStatus {
17745  int addrExplain; /* OP_Explain for loop */
17746  int addrLoop; /* Address of "loops" counter */
17747  int addrVisit; /* Address of "rows visited" counter */
17748  int iSelectID; /* The "Select-ID" for this loop */
17749  LogEst nEst; /* Estimated output rows per loop */
17750  char *zName; /* Name of table or index */
17751 };
17752 
17753 /*
17754 ** An instance of the virtual machine. This structure contains the complete
17755 ** state of the virtual machine.
17756 **
17757 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
17758 ** is really a pointer to an instance of this structure.
17759 */
17760 struct Vdbe {
17761  sqlite3 *db; /* The database connection that owns this statement */
17762  Op *aOp; /* Space to hold the virtual machine's program */
17763  Mem *aMem; /* The memory locations */
17764  Mem **apArg; /* Arguments to currently executing user function */
17765  Mem *aColName; /* Column names to return */
17766  Mem *pResultSet; /* Pointer to an array of results */
17767  Parse *pParse; /* Parsing context used to create this Vdbe */
17768  int nMem; /* Number of memory locations currently allocated */
17769  int nOp; /* Number of instructions in the program */
17770  int nCursor; /* Number of slots in apCsr[] */
17771  u32 magic; /* Magic number for sanity checking */
17772  char *zErrMsg; /* Error message written here */
17773  Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
17774  VdbeCursor **apCsr; /* One element of this array for each open cursor */
17775  Mem *aVar; /* Values for the OP_Variable opcode. */
17776  char **azVar; /* Name of variables */
17777  ynVar nVar; /* Number of entries in aVar[] */
17778  ynVar nzVar; /* Number of entries in azVar[] */
17779  u32 cacheCtr; /* VdbeCursor row cache generation counter */
17780  int pc; /* The program counter */
17781  int rc; /* Value to return */
17782 #ifdef SQLITE_DEBUG
17783  int rcApp; /* errcode set by sqlite3_result_error_code() */
17784 #endif
17785  u16 nResColumn; /* Number of columns in one row of the result set */
17786  u8 errorAction; /* Recovery action to do in case of an error */
17787  bft expired:1; /* True if the VM needs to be recompiled */
17788  bft doingRerun:1; /* True if rerunning after an auto-reprepare */
17789  u8 minWriteFileFormat; /* Minimum file format for writable database files */
17790  bft explain:2; /* True if EXPLAIN present on SQL command */
17791  bft changeCntOn:1; /* True to update the change-counter */
17792  bft runOnlyOnce:1; /* Automatically expire on reset */
17793  bft usesStmtJournal:1; /* True if uses a statement journal */
17794  bft readOnly:1; /* True for statements that do not write */
17795  bft bIsReader:1; /* True for statements that read */
17796  bft isPrepareV2:1; /* True if prepared with prepare_v2() */
17797  int nChange; /* Number of db changes made since last reset */
17798  yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
17799  yDbMask lockMask; /* Subset of btreeMask that requires a lock */
17800  int iStatement; /* Statement number (or 0 if has not opened stmt) */
17801  u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
17802 #ifndef SQLITE_OMIT_TRACE
17803  i64 startTime; /* Time when query started - used for profiling */
17804 #endif
17805  i64 iCurrentTime; /* Value of julianday('now') for this statement */
17806  i64 nFkConstraint; /* Number of imm. FK constraints this VM */
17807  i64 nStmtDefCons; /* Number of def. constraints when stmt started */
17808  i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
17809  char *zSql; /* Text of the SQL statement that generated this */
17810  void *pFree; /* Free this when deleting the vdbe */
17811  VdbeFrame *pFrame; /* Parent frame */
17812  VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
17813  int nFrame; /* Number of frames in pFrame list */
17814  u32 expmask; /* Binding to these vars invalidates VM */
17815  SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
17816  int nOnceFlag; /* Size of array aOnceFlag[] */
17817  u8 *aOnceFlag; /* Flags for OP_Once */
17818  AuxData *pAuxData; /* Linked list of auxdata allocations */
17819 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
17820  i64 *anExec; /* Number of times each op has been executed */
17821  int nScan; /* Entries in aScan[] */
17822  ScanStatus *aScan; /* Scan definitions for sqlite3_stmt_scanstatus() */
17823 #endif
17824 };
17825 
17826 /*
17827 ** The following are allowed values for Vdbe.magic
17828 */
17829 #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
17830 #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
17831 #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
17832 #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
17833 
17834 /*
17835 ** Structure used to store the context required by the
17836 ** sqlite3_preupdate_*() API functions.
17837 */
17838 struct PreUpdate {
17840  VdbeCursor *pCsr; /* Cursor to read old values from */
17841  int op; /* One of SQLITE_INSERT, UPDATE, DELETE */
17842  u8 *aRecord; /* old.* database record */
17844  UnpackedRecord *pUnpacked; /* Unpacked version of aRecord[] */
17845  UnpackedRecord *pNewUnpacked; /* Unpacked version of new.* record */
17846  int iNewReg; /* Register for new.* values */
17847  i64 iKey1; /* First key value passed to hook */
17848  i64 iKey2; /* Second key value passed to hook */
17849  int iPKey; /* If not negative index of IPK column */
17850  Mem *aNew; /* Array of new.* values */
17851 };
17852 
17853 /*
17854 ** Function prototypes
17855 */
17856 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe*, const char *, ...);
17858 void sqliteVdbePopStack(Vdbe*,int);
17861 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
17862 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
17863 #endif
17866 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int, u32*);
17867 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
17868 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
17870 
17871 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
17880 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
17883 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
17885 #ifdef SQLITE_OMIT_FLOATING_POINT
17886 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
17887 #else
17889 #endif
17906 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
17907 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
17912 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
17913 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(Vdbe*,VdbeCursor*,int,const char*,Table*,i64,int);
17914 #endif
17916 
17924 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
17925 
17926 #if !defined(SQLITE_OMIT_SHARED_CACHE)
17928 #else
17929 # define sqlite3VdbeEnter(X)
17930 #endif
17931 
17932 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
17934 #else
17935 # define sqlite3VdbeLeave(X)
17936 #endif
17937 
17938 #ifdef SQLITE_DEBUG
17939 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
17940 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
17941 #endif
17942 
17943 #ifndef SQLITE_OMIT_FOREIGN_KEY
17945 #else
17946 # define sqlite3VdbeCheckFk(p,i) 0
17947 #endif
17948 
17950 #ifdef SQLITE_DEBUG
17951 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
17952 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
17953 #endif
17955 
17956 #ifndef SQLITE_OMIT_INCRBLOB
17958  #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
17959 #else
17960  #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
17961  #define ExpandBlob(P) SQLITE_OK
17962 #endif
17963 
17964 #endif /* !defined(_VDBEINT_H_) */
17965 
17966 /************** End of vdbeInt.h *********************************************/
17967 /************** Continuing where we left off in status.c *********************/
17968 
17969 /*
17970 ** Variables in which to record status information.
17971 */
17972 #if SQLITE_PTRSIZE>4
17973 typedef sqlite3_int64 sqlite3StatValueType;
17974 #else
17975 typedef u32 sqlite3StatValueType;
17976 #endif
17979  sqlite3StatValueType nowValue[10]; /* Current value */
17980  sqlite3StatValueType mxValue[10]; /* Maximum value */
17981 } sqlite3Stat = { {0,}, {0,} };
17982 
17983 /*
17984 ** Elements of sqlite3Stat[] are protected by either the memory allocator
17985 ** mutex, or by the pcache1 mutex. The following array determines which.
17986 */
17987 static const char statMutex[] = {
17988  0, /* SQLITE_STATUS_MEMORY_USED */
17989  1, /* SQLITE_STATUS_PAGECACHE_USED */
17990  1, /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
17991  0, /* SQLITE_STATUS_SCRATCH_USED */
17992  0, /* SQLITE_STATUS_SCRATCH_OVERFLOW */
17993  0, /* SQLITE_STATUS_MALLOC_SIZE */
17994  0, /* SQLITE_STATUS_PARSER_STACK */
17995  1, /* SQLITE_STATUS_PAGECACHE_SIZE */
17996  0, /* SQLITE_STATUS_SCRATCH_SIZE */
17997  0, /* SQLITE_STATUS_MALLOC_COUNT */
17998 };
17999 
18000 
18001 /* The "wsdStat" macro will resolve to the status information
18002 ** state vector. If writable static data is unsupported on the target,
18003 ** we have to locate the state vector at run-time. In the more common
18004 ** case where writable static data is supported, wsdStat can refer directly
18005 ** to the "sqlite3Stat" state vector declared above.
18006 */
18007 #ifdef SQLITE_OMIT_WSD
18008 # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
18009 # define wsdStat x[0]
18010 #else
18011 # define wsdStatInit
18012 # define wsdStat sqlite3Stat
18013 #endif
18014 
18015 /*
18016 ** Return the current value of a status parameter. The caller must
18017 ** be holding the appropriate mutex.
18018 */
18019 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
18020  wsdStatInit;
18021  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18022  assert( op>=0 && op<ArraySize(statMutex) );
18023  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18024  : sqlite3MallocMutex()) );
18025  return wsdStat.nowValue[op];
18026 }
18027 
18028 /*
18029 ** Add N to the value of a status record. The caller must hold the
18030 ** appropriate mutex. (Locking is checked by assert()).
18031 **
18032 ** The StatusUp() routine can accept positive or negative values for N.
18033 ** The value of N is added to the current status value and the high-water
18034 ** mark is adjusted if necessary.
18035 **
18036 ** The StatusDown() routine lowers the current value by N. The highwater
18037 ** mark is unchanged. N must be non-negative for StatusDown().
18038 */
18039 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
18040  wsdStatInit;
18041  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18042  assert( op>=0 && op<ArraySize(statMutex) );
18043  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18044  : sqlite3MallocMutex()) );
18045  wsdStat.nowValue[op] += N;
18046  if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
18047  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18048  }
18049 }
18050 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
18051  wsdStatInit;
18052  assert( N>=0 );
18053  assert( op>=0 && op<ArraySize(statMutex) );
18054  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18055  : sqlite3MallocMutex()) );
18056  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18057  wsdStat.nowValue[op] -= N;
18058 }
18059 
18060 /*
18061 ** Adjust the highwater mark if necessary.
18062 ** The caller must hold the appropriate mutex.
18063 */
18065  sqlite3StatValueType newValue;
18066  wsdStatInit;
18067  assert( X>=0 );
18068  newValue = (sqlite3StatValueType)X;
18069  assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
18070  assert( op>=0 && op<ArraySize(statMutex) );
18071  assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
18072  : sqlite3MallocMutex()) );
18076  || op==SQLITE_STATUS_PARSER_STACK );
18077  if( newValue>wsdStat.mxValue[op] ){
18078  wsdStat.mxValue[op] = newValue;
18079  }
18080 }
18081 
18082 /*
18083 ** Query status information.
18084 */
18086  int op,
18087  sqlite3_int64 *pCurrent,
18088  sqlite3_int64 *pHighwater,
18089  int resetFlag
18090 ){
18091  sqlite3_mutex *pMutex;
18092  wsdStatInit;
18093  if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
18094  return SQLITE_MISUSE_BKPT;
18095  }
18096 #ifdef SQLITE_ENABLE_API_ARMOR
18097  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18098 #endif
18099  pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
18100  sqlite3_mutex_enter(pMutex);
18101  *pCurrent = wsdStat.nowValue[op];
18102  *pHighwater = wsdStat.mxValue[op];
18103  if( resetFlag ){
18104  wsdStat.mxValue[op] = wsdStat.nowValue[op];
18105  }
18106  sqlite3_mutex_leave(pMutex);
18107  (void)pMutex; /* Prevent warning when SQLITE_THREADSAFE=0 */
18108  return SQLITE_OK;
18109 }
18110 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
18111  sqlite3_int64 iCur, iHwtr;
18112  int rc;
18113 #ifdef SQLITE_ENABLE_API_ARMOR
18114  if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
18115 #endif
18116  rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
18117  if( rc==0 ){
18118  *pCurrent = (int)iCur;
18119  *pHighwater = (int)iHwtr;
18120  }
18121  return rc;
18122 }
18123 
18124 /*
18125 ** Query status information for a single database connection
18126 */
18128  sqlite3 *db, /* The database connection whose status is desired */
18129  int op, /* Status verb */
18130  int *pCurrent, /* Write current value here */
18131  int *pHighwater, /* Write high-water mark here */
18132  int resetFlag /* Reset high-water mark if true */
18133 ){
18134  int rc = SQLITE_OK; /* Return code */
18135 #ifdef SQLITE_ENABLE_API_ARMOR
18136  if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
18137  return SQLITE_MISUSE_BKPT;
18138  }
18139 #endif
18141  switch( op ){
18143  *pCurrent = db->lookaside.nOut;
18144  *pHighwater = db->lookaside.mxOut;
18145  if( resetFlag ){
18146  db->lookaside.mxOut = db->lookaside.nOut;
18147  }
18148  break;
18149  }
18150 
18159  *pCurrent = 0;
18160  *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
18161  if( resetFlag ){
18163  }
18164  break;
18165  }
18166 
18167  /*
18168  ** Return an approximation for the amount of memory currently used
18169  ** by all pagers associated with the given database connection. The
18170  ** highwater mark is meaningless and is returned as zero.
18171  */
18173  int totalUsed = 0;
18174  int i;
18176  for(i=0; i<db->nDb; i++){
18177  Btree *pBt = db->aDb[i].pBt;
18178  if( pBt ){
18179  Pager *pPager = sqlite3BtreePager(pBt);
18180  totalUsed += sqlite3PagerMemUsed(pPager);
18181  }
18182  }
18184  *pCurrent = totalUsed;
18185  *pHighwater = 0;
18186  break;
18187  }
18188 
18189  /*
18190  ** *pCurrent gets an accurate estimate of the amount of memory used
18191  ** to store the schema for all databases (main, temp, and any ATTACHed
18192  ** databases. *pHighwater is set to zero.
18193  */
18195  int i; /* Used to iterate through schemas */
18196  int nByte = 0; /* Used to accumulate return value */
18197 
18199  db->pnBytesFreed = &nByte;
18200  for(i=0; i<db->nDb; i++){
18201  Schema *pSchema = db->aDb[i].pSchema;
18202  if( ALWAYS(pSchema!=0) ){
18203  HashElem *p;
18204 
18205  nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
18206  pSchema->tblHash.count
18207  + pSchema->trigHash.count
18208  + pSchema->idxHash.count
18209  + pSchema->fkeyHash.count
18210  );
18211  nByte += sqlite3_msize(pSchema->tblHash.ht);
18212  nByte += sqlite3_msize(pSchema->trigHash.ht);
18213  nByte += sqlite3_msize(pSchema->idxHash.ht);
18214  nByte += sqlite3_msize(pSchema->fkeyHash.ht);
18215 
18216  for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
18218  }
18219  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
18221  }
18222  }
18223  }
18224  db->pnBytesFreed = 0;
18226 
18227  *pHighwater = 0;
18228  *pCurrent = nByte;
18229  break;
18230  }
18231 
18232  /*
18233  ** *pCurrent gets an accurate estimate of the amount of memory used
18234  ** to store all prepared statements.
18235  ** *pHighwater is set to zero.
18236  */
18238  struct Vdbe *pVdbe; /* Used to iterate through VMs */
18239  int nByte = 0; /* Used to accumulate return value */
18240 
18241  db->pnBytesFreed = &nByte;
18242  for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
18243  sqlite3VdbeClearObject(db, pVdbe);
18244  sqlite3DbFree(db, pVdbe);
18245  }
18246  db->pnBytesFreed = 0;
18247 
18248  *pHighwater = 0; /* IMP: R-64479-57858 */
18249  *pCurrent = nByte;
18250 
18251  break;
18252  }
18253 
18254  /*
18255  ** Set *pCurrent to the total cache hits or misses encountered by all
18256  ** pagers the database handle is connected to. *pHighwater is always set
18257  ** to zero.
18258  */
18262  int i;
18263  int nRet = 0;
18266 
18267  for(i=0; i<db->nDb; i++){
18268  if( db->aDb[i].pBt ){
18269  Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
18270  sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
18271  }
18272  }
18273  *pHighwater = 0; /* IMP: R-42420-56072 */
18274  /* IMP: R-54100-20147 */
18275  /* IMP: R-29431-39229 */
18276  *pCurrent = nRet;
18277  break;
18278  }
18279 
18280  /* Set *pCurrent to non-zero if there are unresolved deferred foreign
18281  ** key constraints. Set *pCurrent to zero if all foreign key constraints
18282  ** have been satisfied. The *pHighwater is always set to zero.
18283  */
18285  *pHighwater = 0; /* IMP: R-11967-56545 */
18286  *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
18287  break;
18288  }
18289 
18290  default: {
18291  rc = SQLITE_ERROR;
18292  }
18293  }
18295  return rc;
18296 }
18297 
18298 /************** End of status.c **********************************************/
18299 /************** Begin file date.c ********************************************/
18300 /*
18301 ** 2003 October 31
18302 **
18303 ** The author disclaims copyright to this source code. In place of
18304 ** a legal notice, here is a blessing:
18305 **
18306 ** May you do good and not evil.
18307 ** May you find forgiveness for yourself and forgive others.
18308 ** May you share freely, never taking more than you give.
18309 **
18310 *************************************************************************
18311 ** This file contains the C functions that implement date and time
18312 ** functions for SQLite.
18313 **
18314 ** There is only one exported symbol in this file - the function
18315 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
18316 ** All other code has file scope.
18317 **
18318 ** SQLite processes all times and dates as julian day numbers. The
18319 ** dates and times are stored as the number of days since noon
18320 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
18321 ** calendar system.
18322 **
18323 ** 1970-01-01 00:00:00 is JD 2440587.5
18324 ** 2000-01-01 00:00:00 is JD 2451544.5
18325 **
18326 ** This implementation requires years to be expressed as a 4-digit number
18327 ** which means that only dates between 0000-01-01 and 9999-12-31 can
18328 ** be represented, even though julian day numbers allow a much wider
18329 ** range of dates.
18330 **
18331 ** The Gregorian calendar system is used for all dates and times,
18332 ** even those that predate the Gregorian calendar. Historians usually
18333 ** use the julian calendar for dates prior to 1582-10-15 and for some
18334 ** dates afterwards, depending on locale. Beware of this difference.
18335 **
18336 ** The conversion algorithms are implemented based on descriptions
18337 ** in the following text:
18338 **
18339 ** Jean Meeus
18340 ** Astronomical Algorithms, 2nd Edition, 1998
18341 ** ISBM 0-943396-61-1
18342 ** Willmann-Bell, Inc
18343 ** Richmond, Virginia (USA)
18344 */
18345 /* #include "sqliteInt.h" */
18346 /* #include <stdlib.h> */
18347 /* #include <assert.h> */
18348 #include <time.h>
18349 
18350 #ifndef SQLITE_OMIT_DATETIME_FUNCS
18351 
18352 /*
18353 ** The MSVC CRT on Windows CE may not have a localtime() function.
18354 ** So declare a substitute. The substitute function itself is
18355 ** defined in "os_win.c".
18356 */
18357 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
18358  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
18359 struct tm *__cdecl localtime(const time_t *);
18360 #endif
18361 
18362 /*
18363 ** A structure for holding a single date and time.
18364 */
18365 typedef struct DateTime DateTime;
18366 struct DateTime {
18367  sqlite3_int64 iJD; /* The julian day number times 86400000 */
18368  int Y, M, D; /* Year, month, and day */
18369  int h, m; /* Hour and minutes */
18370  int tz; /* Timezone offset in minutes */
18371  double s; /* Seconds */
18372  char validYMD; /* True (1) if Y,M,D are valid */
18373  char validHMS; /* True (1) if h,m,s are valid */
18374  char validJD; /* True (1) if iJD is valid */
18375  char validTZ; /* True (1) if tz is valid */
18376  char tzSet; /* Timezone was set explicitly */
18377 };
18378 
18379 
18380 /*
18381 ** Convert zDate into one or more integers according to the conversion
18382 ** specifier zFormat.
18383 **
18384 ** zFormat[] contains 4 characters for each integer converted, except for
18385 ** the last integer which is specified by three characters. The meaning
18386 ** of a four-character format specifiers ABCD is:
18387 **
18388 ** A: number of digits to convert. Always "2" or "4".
18389 ** B: minimum value. Always "0" or "1".
18390 ** C: maximum value, decoded as:
18391 ** a: 12
18392 ** b: 14
18393 ** c: 24
18394 ** d: 31
18395 ** e: 59
18396 ** f: 9999
18397 ** D: the separator character, or \000 to indicate this is the
18398 ** last number to convert.
18399 **
18400 ** Example: To translate an ISO-8601 date YYYY-MM-DD, the format would
18401 ** be "40f-21a-20c". The "40f-" indicates the 4-digit year followed by "-".
18402 ** The "21a-" indicates the 2-digit month followed by "-". The "20c" indicates
18403 ** the 2-digit day which is the last integer in the set.
18404 **
18405 ** The function returns the number of successful conversions.
18406 */
18407 static int getDigits(const char *zDate, const char *zFormat, ...){
18408  /* The aMx[] array translates the 3rd character of each format
18409  ** spec into a max size: a b c d e f */
18410  static const u16 aMx[] = { 12, 14, 24, 31, 59, 9999 };
18411  va_list ap;
18412  int cnt = 0;
18413  char nextC;
18414  va_start(ap, zFormat);
18415  do{
18416  char N = zFormat[0] - '0';
18417  char min = zFormat[1] - '0';
18418  int val = 0;
18419  u16 max;
18420 
18421  assert( zFormat[2]>='a' && zFormat[2]<='f' );
18422  max = aMx[zFormat[2] - 'a'];
18423  nextC = zFormat[3];
18424  val = 0;
18425  while( N-- ){
18426  if( !sqlite3Isdigit(*zDate) ){
18427  goto end_getDigits;
18428  }
18429  val = val*10 + *zDate - '0';
18430  zDate++;
18431  }
18432  if( val<(int)min || val>(int)max || (nextC!=0 && nextC!=*zDate) ){
18433  goto end_getDigits;
18434  }
18435  *va_arg(ap,int*) = val;
18436  zDate++;
18437  cnt++;
18438  zFormat += 4;
18439  }while( nextC );
18440 end_getDigits:
18441  va_end(ap);
18442  return cnt;
18443 }
18444 
18445 /*
18446 ** Parse a timezone extension on the end of a date-time.
18447 ** The extension is of the form:
18448 **
18449 ** (+/-)HH:MM
18450 **
18451 ** Or the "zulu" notation:
18452 **
18453 ** Z
18454 **
18455 ** If the parse is successful, write the number of minutes
18456 ** of change in p->tz and return 0. If a parser error occurs,
18457 ** return non-zero.
18458 **
18459 ** A missing specifier is not considered an error.
18460 */
18461 static int parseTimezone(const char *zDate, DateTime *p){
18462  int sgn = 0;
18463  int nHr, nMn;
18464  int c;
18465  while( sqlite3Isspace(*zDate) ){ zDate++; }
18466  p->tz = 0;
18467  c = *zDate;
18468  if( c=='-' ){
18469  sgn = -1;
18470  }else if( c=='+' ){
18471  sgn = +1;
18472  }else if( c=='Z' || c=='z' ){
18473  zDate++;
18474  goto zulu_time;
18475  }else{
18476  return c!=0;
18477  }
18478  zDate++;
18479  if( getDigits(zDate, "20b:20e", &nHr, &nMn)!=2 ){
18480  return 1;
18481  }
18482  zDate += 5;
18483  p->tz = sgn*(nMn + nHr*60);
18484 zulu_time:
18485  while( sqlite3Isspace(*zDate) ){ zDate++; }
18486  p->tzSet = 1;
18487  return *zDate!=0;
18488 }
18489 
18490 /*
18491 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
18492 ** The HH, MM, and SS must each be exactly 2 digits. The
18493 ** fractional seconds FFFF can be one or more digits.
18494 **
18495 ** Return 1 if there is a parsing error and 0 on success.
18496 */
18497 static int parseHhMmSs(const char *zDate, DateTime *p){
18498  int h, m, s;
18499  double ms = 0.0;
18500  if( getDigits(zDate, "20c:20e", &h, &m)!=2 ){
18501  return 1;
18502  }
18503  zDate += 5;
18504  if( *zDate==':' ){
18505  zDate++;
18506  if( getDigits(zDate, "20e", &s)!=1 ){
18507  return 1;
18508  }
18509  zDate += 2;
18510  if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
18511  double rScale = 1.0;
18512  zDate++;
18513  while( sqlite3Isdigit(*zDate) ){
18514  ms = ms*10.0 + *zDate - '0';
18515  rScale *= 10.0;
18516  zDate++;
18517  }
18518  ms /= rScale;
18519  }
18520  }else{
18521  s = 0;
18522  }
18523  p->validJD = 0;
18524  p->validHMS = 1;
18525  p->h = h;
18526  p->m = m;
18527  p->s = s + ms;
18528  if( parseTimezone(zDate, p) ) return 1;
18529  p->validTZ = (p->tz!=0)?1:0;
18530  return 0;
18531 }
18532 
18533 /*
18534 ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
18535 ** that the YYYY-MM-DD is according to the Gregorian calendar.
18536 **
18537 ** Reference: Meeus page 61
18538 */
18539 static void computeJD(DateTime *p){
18540  int Y, M, D, A, B, X1, X2;
18541 
18542  if( p->validJD ) return;
18543  if( p->validYMD ){
18544  Y = p->Y;
18545  M = p->M;
18546  D = p->D;
18547  }else{
18548  Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
18549  M = 1;
18550  D = 1;
18551  }
18552  if( M<=2 ){
18553  Y--;
18554  M += 12;
18555  }
18556  A = Y/100;
18557  B = 2 - A + (A/4);
18558  X1 = 36525*(Y+4716)/100;
18559  X2 = 306001*(M+1)/10000;
18560  p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
18561  p->validJD = 1;
18562  if( p->validHMS ){
18563  p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
18564  if( p->validTZ ){
18565  p->iJD -= p->tz*60000;
18566  p->validYMD = 0;
18567  p->validHMS = 0;
18568  p->validTZ = 0;
18569  }
18570  }
18571 }
18572 
18573 /*
18574 ** Parse dates of the form
18575 **
18576 ** YYYY-MM-DD HH:MM:SS.FFF
18577 ** YYYY-MM-DD HH:MM:SS
18578 ** YYYY-MM-DD HH:MM
18579 ** YYYY-MM-DD
18580 **
18581 ** Write the result into the DateTime structure and return 0
18582 ** on success and 1 if the input string is not a well-formed
18583 ** date.
18584 */
18585 static int parseYyyyMmDd(const char *zDate, DateTime *p){
18586  int Y, M, D, neg;
18587 
18588  if( zDate[0]=='-' ){
18589  zDate++;
18590  neg = 1;
18591  }else{
18592  neg = 0;
18593  }
18594  if( getDigits(zDate, "40f-21a-21d", &Y, &M, &D)!=3 ){
18595  return 1;
18596  }
18597  zDate += 10;
18598  while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
18599  if( parseHhMmSs(zDate, p)==0 ){
18600  /* We got the time */
18601  }else if( *zDate==0 ){
18602  p->validHMS = 0;
18603  }else{
18604  return 1;
18605  }
18606  p->validJD = 0;
18607  p->validYMD = 1;
18608  p->Y = neg ? -Y : Y;
18609  p->M = M;
18610  p->D = D;
18611  if( p->validTZ ){
18612  computeJD(p);
18613  }
18614  return 0;
18615 }
18616 
18617 /*
18618 ** Set the time to the current time reported by the VFS.
18619 **
18620 ** Return the number of errors.
18621 */
18623  p->iJD = sqlite3StmtCurrentTime(context);
18624  if( p->iJD>0 ){
18625  p->validJD = 1;
18626  return 0;
18627  }else{
18628  return 1;
18629  }
18630 }
18631 
18632 /*
18633 ** Attempt to parse the given string into a julian day number. Return
18634 ** the number of errors.
18635 **
18636 ** The following are acceptable forms for the input string:
18637 **
18638 ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
18639 ** DDDD.DD
18640 ** now
18641 **
18642 ** In the first form, the +/-HH:MM is always optional. The fractional
18643 ** seconds extension (the ".FFF") is optional. The seconds portion
18644 ** (":SS.FFF") is option. The year and date can be omitted as long
18645 ** as there is a time string. The time string can be omitted as long
18646 ** as there is a year and date.
18647 */
18648 static int parseDateOrTime(
18649  sqlite3_context *context,
18650  const char *zDate,
18651  DateTime *p
18652 ){
18653  double r;
18654  if( parseYyyyMmDd(zDate,p)==0 ){
18655  return 0;
18656  }else if( parseHhMmSs(zDate, p)==0 ){
18657  return 0;
18658  }else if( sqlite3StrICmp(zDate,"now")==0){
18659  return setDateTimeToCurrent(context, p);
18660  }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
18661  p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
18662  p->validJD = 1;
18663  return 0;
18664  }
18665  return 1;
18666 }
18667 
18668 /*
18669 ** Compute the Year, Month, and Day from the julian day number.
18670 */
18671 static void computeYMD(DateTime *p){
18672  int Z, A, B, C, D, E, X1;
18673  if( p->validYMD ) return;
18674  if( !p->validJD ){
18675  p->Y = 2000;
18676  p->M = 1;
18677  p->D = 1;
18678  }else{
18679  Z = (int)((p->iJD + 43200000)/86400000);
18680  A = (int)((Z - 1867216.25)/36524.25);
18681  A = Z + 1 + A - (A/4);
18682  B = A + 1524;
18683  C = (int)((B - 122.1)/365.25);
18684  D = (36525*(C&32767))/100;
18685  E = (int)((B-D)/30.6001);
18686  X1 = (int)(30.6001*E);
18687  p->D = B - D - X1;
18688  p->M = E<14 ? E-1 : E-13;
18689  p->Y = p->M>2 ? C - 4716 : C - 4715;
18690  }
18691  p->validYMD = 1;
18692 }
18693 
18694 /*
18695 ** Compute the Hour, Minute, and Seconds from the julian day number.
18696 */
18697 static void computeHMS(DateTime *p){
18698  int s;
18699  if( p->validHMS ) return;
18700  computeJD(p);
18701  s = (int)((p->iJD + 43200000) % 86400000);
18702  p->s = s/1000.0;
18703  s = (int)p->s;
18704  p->s -= s;
18705  p->h = s/3600;
18706  s -= p->h*3600;
18707  p->m = s/60;
18708  p->s += s - p->m*60;
18709  p->validHMS = 1;
18710 }
18711 
18712 /*
18713 ** Compute both YMD and HMS
18714 */
18715 static void computeYMD_HMS(DateTime *p){
18716  computeYMD(p);
18717  computeHMS(p);
18718 }
18719 
18720 /*
18721 ** Clear the YMD and HMS and the TZ
18722 */
18723 static void clearYMD_HMS_TZ(DateTime *p){
18724  p->validYMD = 0;
18725  p->validHMS = 0;
18726  p->validTZ = 0;
18727 }
18728 
18729 #ifndef SQLITE_OMIT_LOCALTIME
18730 /*
18731 ** On recent Windows platforms, the localtime_s() function is available
18732 ** as part of the "Secure CRT". It is essentially equivalent to
18733 ** localtime_r() available under most POSIX platforms, except that the
18734 ** order of the parameters is reversed.
18735 **
18736 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
18737 **
18738 ** If the user has not indicated to use localtime_r() or localtime_s()
18739 ** already, check for an MSVC build environment that provides
18740 ** localtime_s().
18741 */
18742 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
18743  && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
18744 #undef HAVE_LOCALTIME_S
18745 #define HAVE_LOCALTIME_S 1
18746 #endif
18747 
18748 /*
18749 ** The following routine implements the rough equivalent of localtime_r()
18750 ** using whatever operating-system specific localtime facility that
18751 ** is available. This routine returns 0 on success and
18752 ** non-zero on any kind of error.
18753 **
18754 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
18755 ** routine will always fail.
18756 **
18757 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
18758 ** library function localtime_r() is used to assist in the calculation of
18759 ** local time.
18760 */
18761 static int osLocaltime(time_t *t, struct tm *pTm){
18762  int rc;
18763 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
18764  struct tm *pX;
18765 #if SQLITE_THREADSAFE>0
18767 #endif
18768  sqlite3_mutex_enter(mutex);
18769  pX = localtime(t);
18770 #ifndef SQLITE_OMIT_BUILTIN_TEST
18771  if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
18772 #endif
18773  if( pX ) *pTm = *pX;
18774  sqlite3_mutex_leave(mutex);
18775  rc = pX==0;
18776 #else
18777 #ifndef SQLITE_OMIT_BUILTIN_TEST
18778  if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
18779 #endif
18780 #if HAVE_LOCALTIME_R
18781  rc = localtime_r(t, pTm)==0;
18782 #else
18783  rc = localtime_s(pTm, t);
18784 #endif /* HAVE_LOCALTIME_R */
18785 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
18786  return rc;
18787 }
18788 #endif /* SQLITE_OMIT_LOCALTIME */
18789 
18790 
18791 #ifndef SQLITE_OMIT_LOCALTIME
18792 /*
18793 ** Compute the difference (in milliseconds) between localtime and UTC
18794 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
18795 ** return this value and set *pRc to SQLITE_OK.
18796 **
18797 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
18798 ** is undefined in this case.
18799 */
18800 static sqlite3_int64 localtimeOffset(
18801  DateTime *p, /* Date at which to calculate offset */
18802  sqlite3_context *pCtx, /* Write error here if one occurs */
18803  int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
18804 ){
18805  DateTime x, y;
18806  time_t t;
18807  struct tm sLocal;
18808 
18809  /* Initialize the contents of sLocal to avoid a compiler warning. */
18810  memset(&sLocal, 0, sizeof(sLocal));
18811 
18812  x = *p;
18813  computeYMD_HMS(&x);
18814  if( x.Y<1971 || x.Y>=2038 ){
18815  /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
18816  ** works for years between 1970 and 2037. For dates outside this range,
18817  ** SQLite attempts to map the year into an equivalent year within this
18818  ** range, do the calculation, then map the year back.
18819  */
18820  x.Y = 2000;
18821  x.M = 1;
18822  x.D = 1;
18823  x.h = 0;
18824  x.m = 0;
18825  x.s = 0.0;
18826  } else {
18827  int s = (int)(x.s + 0.5);
18828  x.s = s;
18829  }
18830  x.tz = 0;
18831  x.validJD = 0;
18832  computeJD(&x);
18833  t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
18834  if( osLocaltime(&t, &sLocal) ){
18835  sqlite3_result_error(pCtx, "local time unavailable", -1);
18836  *pRc = SQLITE_ERROR;
18837  return 0;
18838  }
18839  y.Y = sLocal.tm_year + 1900;
18840  y.M = sLocal.tm_mon + 1;
18841  y.D = sLocal.tm_mday;
18842  y.h = sLocal.tm_hour;
18843  y.m = sLocal.tm_min;
18844  y.s = sLocal.tm_sec;
18845  y.validYMD = 1;
18846  y.validHMS = 1;
18847  y.validJD = 0;
18848  y.validTZ = 0;
18849  computeJD(&y);
18850  *pRc = SQLITE_OK;
18851  return y.iJD - x.iJD;
18852 }
18853 #endif /* SQLITE_OMIT_LOCALTIME */
18854 
18855 /*
18856 ** Process a modifier to a date-time stamp. The modifiers are
18857 ** as follows:
18858 **
18859 ** NNN days
18860 ** NNN hours
18861 ** NNN minutes
18862 ** NNN.NNNN seconds
18863 ** NNN months
18864 ** NNN years
18865 ** start of month
18866 ** start of year
18867 ** start of week
18868 ** start of day
18869 ** weekday N
18870 ** unixepoch
18871 ** localtime
18872 ** utc
18873 **
18874 ** Return 0 on success and 1 if there is any kind of error. If the error
18875 ** is in a system call (i.e. localtime()), then an error message is written
18876 ** to context pCtx. If the error is an unrecognized modifier, no error is
18877 ** written to pCtx.
18878 */
18879 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
18880  int rc = 1;
18881  int n;
18882  double r;
18883  char *z, zBuf[30];
18884  z = zBuf;
18885  for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
18886  z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
18887  }
18888  z[n] = 0;
18889  switch( z[0] ){
18890 #ifndef SQLITE_OMIT_LOCALTIME
18891  case 'l': {
18892  /* localtime
18893  **
18894  ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
18895  ** show local time.
18896  */
18897  if( strcmp(z, "localtime")==0 ){
18898  computeJD(p);
18899  p->iJD += localtimeOffset(p, pCtx, &rc);
18900  clearYMD_HMS_TZ(p);
18901  }
18902  break;
18903  }
18904 #endif
18905  case 'u': {
18906  /*
18907  ** unixepoch
18908  **
18909  ** Treat the current value of p->iJD as the number of
18910  ** seconds since 1970. Convert to a real julian day number.
18911  */
18912  if( strcmp(z, "unixepoch")==0 && p->validJD ){
18913  p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
18914  clearYMD_HMS_TZ(p);
18915  rc = 0;
18916  }
18917 #ifndef SQLITE_OMIT_LOCALTIME
18918  else if( strcmp(z, "utc")==0 ){
18919  if( p->tzSet==0 ){
18920  sqlite3_int64 c1;
18921  computeJD(p);
18922  c1 = localtimeOffset(p, pCtx, &rc);
18923  if( rc==SQLITE_OK ){
18924  p->iJD -= c1;
18925  clearYMD_HMS_TZ(p);
18926  p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
18927  }
18928  p->tzSet = 1;
18929  }else{
18930  rc = SQLITE_OK;
18931  }
18932  }
18933 #endif
18934  break;
18935  }
18936  case 'w': {
18937  /*
18938  ** weekday N
18939  **
18940  ** Move the date to the same time on the next occurrence of
18941  ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
18942  ** date is already on the appropriate weekday, this is a no-op.
18943  */
18944  if( strncmp(z, "weekday ", 8)==0
18945  && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
18946  && (n=(int)r)==r && n>=0 && r<7 ){
18947  sqlite3_int64 Z;
18948  computeYMD_HMS(p);
18949  p->validTZ = 0;
18950  p->validJD = 0;
18951  computeJD(p);
18952  Z = ((p->iJD + 129600000)/86400000) % 7;
18953  if( Z>n ) Z -= 7;
18954  p->iJD += (n - Z)*86400000;
18955  clearYMD_HMS_TZ(p);
18956  rc = 0;
18957  }
18958  break;
18959  }
18960  case 's': {
18961  /*
18962  ** start of TTTTT
18963  **
18964  ** Move the date backwards to the beginning of the current day,
18965  ** or month or year.
18966  */
18967  if( strncmp(z, "start of ", 9)!=0 ) break;
18968  z += 9;
18969  computeYMD(p);
18970  p->validHMS = 1;
18971  p->h = p->m = 0;
18972  p->s = 0.0;
18973  p->validTZ = 0;
18974  p->validJD = 0;
18975  if( strcmp(z,"month")==0 ){
18976  p->D = 1;
18977  rc = 0;
18978  }else if( strcmp(z,"year")==0 ){
18979  computeYMD(p);
18980  p->M = 1;
18981  p->D = 1;
18982  rc = 0;
18983  }else if( strcmp(z,"day")==0 ){
18984  rc = 0;
18985  }
18986  break;
18987  }
18988  case '+':
18989  case '-':
18990  case '0':
18991  case '1':
18992  case '2':
18993  case '3':
18994  case '4':
18995  case '5':
18996  case '6':
18997  case '7':
18998  case '8':
18999  case '9': {
19000  double rRounder;
19001  for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
19002  if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
19003  rc = 1;
19004  break;
19005  }
19006  if( z[n]==':' ){
19007  /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
19008  ** specified number of hours, minutes, seconds, and fractional seconds
19009  ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
19010  ** omitted.
19011  */
19012  const char *z2 = z;
19013  DateTime tx;
19014  sqlite3_int64 day;
19015  if( !sqlite3Isdigit(*z2) ) z2++;
19016  memset(&tx, 0, sizeof(tx));
19017  if( parseHhMmSs(z2, &tx) ) break;
19018  computeJD(&tx);
19019  tx.iJD -= 43200000;
19020  day = tx.iJD/86400000;
19021  tx.iJD -= day*86400000;
19022  if( z[0]=='-' ) tx.iJD = -tx.iJD;
19023  computeJD(p);
19024  clearYMD_HMS_TZ(p);
19025  p->iJD += tx.iJD;
19026  rc = 0;
19027  break;
19028  }
19029  z += n;
19030  while( sqlite3Isspace(*z) ) z++;
19031  n = sqlite3Strlen30(z);
19032  if( n>10 || n<3 ) break;
19033  if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
19034  computeJD(p);
19035  rc = 0;
19036  rRounder = r<0 ? -0.5 : +0.5;
19037  if( n==3 && strcmp(z,"day")==0 ){
19038  p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
19039  }else if( n==4 && strcmp(z,"hour")==0 ){
19040  p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
19041  }else if( n==6 && strcmp(z,"minute")==0 ){
19042  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
19043  }else if( n==6 && strcmp(z,"second")==0 ){
19044  p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
19045  }else if( n==5 && strcmp(z,"month")==0 ){
19046  int x, y;
19047  computeYMD_HMS(p);
19048  p->M += (int)r;
19049  x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
19050  p->Y += x;
19051  p->M -= x*12;
19052  p->validJD = 0;
19053  computeJD(p);
19054  y = (int)r;
19055  if( y!=r ){
19056  p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
19057  }
19058  }else if( n==4 && strcmp(z,"year")==0 ){
19059  int y = (int)r;
19060  computeYMD_HMS(p);
19061  p->Y += y;
19062  p->validJD = 0;
19063  computeJD(p);
19064  if( y!=r ){
19065  p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
19066  }
19067  }else{
19068  rc = 1;
19069  }
19070  clearYMD_HMS_TZ(p);
19071  break;
19072  }
19073  default: {
19074  break;
19075  }
19076  }
19077  return rc;
19078 }
19079 
19080 /*
19081 ** Process time function arguments. argv[0] is a date-time stamp.
19082 ** argv[1] and following are modifiers. Parse them all and write
19083 ** the resulting time into the DateTime structure p. Return 0
19084 ** on success and 1 if there are any errors.
19085 **
19086 ** If there are zero parameters (if even argv[0] is undefined)
19087 ** then assume a default value of "now" for argv[0].
19088 */
19089 static int isDate(
19090  sqlite3_context *context,
19091  int argc,
19092  sqlite3_value **argv,
19093  DateTime *p
19094 ){
19095  int i;
19096  const unsigned char *z;
19097  int eType;
19098  memset(p, 0, sizeof(*p));
19099  if( argc==0 ){
19100  return setDateTimeToCurrent(context, p);
19101  }
19102  if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
19103  || eType==SQLITE_INTEGER ){
19104  p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
19105  p->validJD = 1;
19106  }else{
19107  z = sqlite3_value_text(argv[0]);
19108  if( !z || parseDateOrTime(context, (char*)z, p) ){
19109  return 1;
19110  }
19111  }
19112  for(i=1; i<argc; i++){
19113  z = sqlite3_value_text(argv[i]);
19114  if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
19115  }
19116  return 0;
19117 }
19118 
19119 
19120 /*
19121 ** The following routines implement the various date and time functions
19122 ** of SQLite.
19123 */
19124 
19125 /*
19126 ** julianday( TIMESTRING, MOD, MOD, ...)
19127 **
19128 ** Return the julian day number of the date specified in the arguments
19129 */
19130 static void juliandayFunc(
19131  sqlite3_context *context,
19132  int argc,
19133  sqlite3_value **argv
19134 ){
19135  DateTime x;
19136  if( isDate(context, argc, argv, &x)==0 ){
19137  computeJD(&x);
19138  sqlite3_result_double(context, x.iJD/86400000.0);
19139  }
19140 }
19141 
19142 /*
19143 ** datetime( TIMESTRING, MOD, MOD, ...)
19144 **
19145 ** Return YYYY-MM-DD HH:MM:SS
19146 */
19147 static void datetimeFunc(
19148  sqlite3_context *context,
19149  int argc,
19150  sqlite3_value **argv
19151 ){
19152  DateTime x;
19153  if( isDate(context, argc, argv, &x)==0 ){
19154  char zBuf[100];
19155  computeYMD_HMS(&x);
19156  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
19157  x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
19158  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19159  }
19160 }
19161 
19162 /*
19163 ** time( TIMESTRING, MOD, MOD, ...)
19164 **
19165 ** Return HH:MM:SS
19166 */
19167 static void timeFunc(
19168  sqlite3_context *context,
19169  int argc,
19170  sqlite3_value **argv
19171 ){
19172  DateTime x;
19173  if( isDate(context, argc, argv, &x)==0 ){
19174  char zBuf[100];
19175  computeHMS(&x);
19176  sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
19177  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19178  }
19179 }
19180 
19181 /*
19182 ** date( TIMESTRING, MOD, MOD, ...)
19183 **
19184 ** Return YYYY-MM-DD
19185 */
19186 static void dateFunc(
19187  sqlite3_context *context,
19188  int argc,
19189  sqlite3_value **argv
19190 ){
19191  DateTime x;
19192  if( isDate(context, argc, argv, &x)==0 ){
19193  char zBuf[100];
19194  computeYMD(&x);
19195  sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
19196  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19197  }
19198 }
19199 
19200 /*
19201 ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
19202 **
19203 ** Return a string described by FORMAT. Conversions as follows:
19204 **
19205 ** %d day of month
19206 ** %f ** fractional seconds SS.SSS
19207 ** %H hour 00-24
19208 ** %j day of year 000-366
19209 ** %J ** julian day number
19210 ** %m month 01-12
19211 ** %M minute 00-59
19212 ** %s seconds since 1970-01-01
19213 ** %S seconds 00-59
19214 ** %w day of week 0-6 sunday==0
19215 ** %W week of year 00-53
19216 ** %Y year 0000-9999
19217 ** %% %
19218 */
19219 static void strftimeFunc(
19220  sqlite3_context *context,
19221  int argc,
19222  sqlite3_value **argv
19223 ){
19224  DateTime x;
19225  u64 n;
19226  size_t i,j;
19227  char *z;
19228  sqlite3 *db;
19229  const char *zFmt;
19230  char zBuf[100];
19231  if( argc==0 ) return;
19232  zFmt = (const char*)sqlite3_value_text(argv[0]);
19233  if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
19234  db = sqlite3_context_db_handle(context);
19235  for(i=0, n=1; zFmt[i]; i++, n++){
19236  if( zFmt[i]=='%' ){
19237  switch( zFmt[i+1] ){
19238  case 'd':
19239  case 'H':
19240  case 'm':
19241  case 'M':
19242  case 'S':
19243  case 'W':
19244  n++;
19245  /* fall thru */
19246  case 'w':
19247  case '%':
19248  break;
19249  case 'f':
19250  n += 8;
19251  break;
19252  case 'j':
19253  n += 3;
19254  break;
19255  case 'Y':
19256  n += 8;
19257  break;
19258  case 's':
19259  case 'J':
19260  n += 50;
19261  break;
19262  default:
19263  return; /* ERROR. return a NULL */
19264  }
19265  i++;
19266  }
19267  }
19268  testcase( n==sizeof(zBuf)-1 );
19269  testcase( n==sizeof(zBuf) );
19270  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
19271  testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
19272  if( n<sizeof(zBuf) ){
19273  z = zBuf;
19274  }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
19275  sqlite3_result_error_toobig(context);
19276  return;
19277  }else{
19278  z = sqlite3DbMallocRawNN(db, (int)n);
19279  if( z==0 ){
19280  sqlite3_result_error_nomem(context);
19281  return;
19282  }
19283  }
19284  computeJD(&x);
19285  computeYMD_HMS(&x);
19286  for(i=j=0; zFmt[i]; i++){
19287  if( zFmt[i]!='%' ){
19288  z[j++] = zFmt[i];
19289  }else{
19290  i++;
19291  switch( zFmt[i] ){
19292  case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
19293  case 'f': {
19294  double s = x.s;
19295  if( s>59.999 ) s = 59.999;
19296  sqlite3_snprintf(7, &z[j],"%06.3f", s);
19297  j += sqlite3Strlen30(&z[j]);
19298  break;
19299  }
19300  case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
19301  case 'W': /* Fall thru */
19302  case 'j': {
19303  int nDay; /* Number of days since 1st day of year */
19304  DateTime y = x;
19305  y.validJD = 0;
19306  y.M = 1;
19307  y.D = 1;
19308  computeJD(&y);
19309  nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
19310  if( zFmt[i]=='W' ){
19311  int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
19312  wd = (int)(((x.iJD+43200000)/86400000)%7);
19313  sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
19314  j += 2;
19315  }else{
19316  sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
19317  j += 3;
19318  }
19319  break;
19320  }
19321  case 'J': {
19322  sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
19323  j+=sqlite3Strlen30(&z[j]);
19324  break;
19325  }
19326  case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
19327  case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
19328  case 's': {
19329  sqlite3_snprintf(30,&z[j],"%lld",
19330  (i64)(x.iJD/1000 - 21086676*(i64)10000));
19331  j += sqlite3Strlen30(&z[j]);
19332  break;
19333  }
19334  case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
19335  case 'w': {
19336  z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
19337  break;
19338  }
19339  case 'Y': {
19340  sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
19341  break;
19342  }
19343  default: z[j++] = '%'; break;
19344  }
19345  }
19346  }
19347  z[j] = 0;
19348  sqlite3_result_text(context, z, -1,
19349  z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
19350 }
19351 
19352 /*
19353 ** current_time()
19354 **
19355 ** This function returns the same value as time('now').
19356 */
19357 static void ctimeFunc(
19358  sqlite3_context *context,
19359  int NotUsed,
19360  sqlite3_value **NotUsed2
19361 ){
19362  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19363  timeFunc(context, 0, 0);
19364 }
19365 
19366 /*
19367 ** current_date()
19368 **
19369 ** This function returns the same value as date('now').
19370 */
19371 static void cdateFunc(
19372  sqlite3_context *context,
19373  int NotUsed,
19374  sqlite3_value **NotUsed2
19375 ){
19376  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19377  dateFunc(context, 0, 0);
19378 }
19379 
19380 /*
19381 ** current_timestamp()
19382 **
19383 ** This function returns the same value as datetime('now').
19384 */
19385 static void ctimestampFunc(
19386  sqlite3_context *context,
19387  int NotUsed,
19388  sqlite3_value **NotUsed2
19389 ){
19390  UNUSED_PARAMETER2(NotUsed, NotUsed2);
19391  datetimeFunc(context, 0, 0);
19392 }
19393 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
19394 
19395 #ifdef SQLITE_OMIT_DATETIME_FUNCS
19396 /*
19397 ** If the library is compiled to omit the full-scale date and time
19398 ** handling (to get a smaller binary), the following minimal version
19399 ** of the functions current_time(), current_date() and current_timestamp()
19400 ** are included instead. This is to support column declarations that
19401 ** include "DEFAULT CURRENT_TIME" etc.
19402 **
19403 ** This function uses the C-library functions time(), gmtime()
19404 ** and strftime(). The format string to pass to strftime() is supplied
19405 ** as the user-data for the function.
19406 */
19407 static void currentTimeFunc(
19408  sqlite3_context *context,
19409  int argc,
19410  sqlite3_value **argv
19411 ){
19412  time_t t;
19413  char *zFormat = (char *)sqlite3_user_data(context);
19414  sqlite3 *db;
19415  sqlite3_int64 iT;
19416  struct tm *pTm;
19417  struct tm sNow;
19418  char zBuf[20];
19419 
19420  UNUSED_PARAMETER(argc);
19421  UNUSED_PARAMETER(argv);
19422 
19423  iT = sqlite3StmtCurrentTime(context);
19424  if( iT<=0 ) return;
19425  t = iT/1000 - 10000*(sqlite3_int64)21086676;
19426 #if HAVE_GMTIME_R
19427  pTm = gmtime_r(&t, &sNow);
19428 #else
19430  pTm = gmtime(&t);
19431  if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
19433 #endif
19434  if( pTm ){
19435  strftime(zBuf, 20, zFormat, &sNow);
19436  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
19437  }
19438 }
19439 #endif
19440 
19441 /*
19442 ** This function registered all of the above C functions as SQL
19443 ** functions. This should be the only routine in this file with
19444 ** external linkage.
19445 */
19447  static FuncDef aDateTimeFuncs[] = {
19448 #ifndef SQLITE_OMIT_DATETIME_FUNCS
19449  DFUNCTION(julianday, -1, 0, 0, juliandayFunc ),
19450  DFUNCTION(date, -1, 0, 0, dateFunc ),
19451  DFUNCTION(time, -1, 0, 0, timeFunc ),
19452  DFUNCTION(datetime, -1, 0, 0, datetimeFunc ),
19453  DFUNCTION(strftime, -1, 0, 0, strftimeFunc ),
19454  DFUNCTION(current_time, 0, 0, 0, ctimeFunc ),
19455  DFUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
19456  DFUNCTION(current_date, 0, 0, 0, cdateFunc ),
19457 #else
19458  STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
19459  STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
19460  STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
19461 #endif
19462  };
19463  sqlite3InsertBuiltinFuncs(aDateTimeFuncs, ArraySize(aDateTimeFuncs));
19464 }
19465 
19466 /************** End of date.c ************************************************/
19467 /************** Begin file os.c **********************************************/
19468 /*
19469 ** 2005 November 29
19470 **
19471 ** The author disclaims copyright to this source code. In place of
19472 ** a legal notice, here is a blessing:
19473 **
19474 ** May you do good and not evil.
19475 ** May you find forgiveness for yourself and forgive others.
19476 ** May you share freely, never taking more than you give.
19477 **
19478 ******************************************************************************
19479 **
19480 ** This file contains OS interface code that is common to all
19481 ** architectures.
19482 */
19483 #define _SQLITE_OS_C_ 1
19484 /* #include "sqliteInt.h" */
19485 #undef _SQLITE_OS_C_
19486 
19487 /*
19488 ** If we compile with the SQLITE_TEST macro set, then the following block
19489 ** of code will give us the ability to simulate a disk I/O error. This
19490 ** is used for testing the I/O recovery logic.
19491 */
19492 #if defined(SQLITE_TEST)
19493 SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
19494 SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
19495 SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
19496 SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
19497 SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
19498 SQLITE_API int sqlite3_diskfull_pending = 0;
19499 SQLITE_API int sqlite3_diskfull = 0;
19500 #endif /* defined(SQLITE_TEST) */
19501 
19502 /*
19503 ** When testing, also keep a count of the number of open files.
19504 */
19505 #if defined(SQLITE_TEST)
19506 SQLITE_API int sqlite3_open_file_count = 0;
19507 #endif /* defined(SQLITE_TEST) */
19508 
19509 /*
19510 ** The default SQLite sqlite3_vfs implementations do not allocate
19511 ** memory (actually, os_unix.c allocates a small amount of memory
19512 ** from within OsOpen()), but some third-party implementations may.
19513 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
19514 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
19515 **
19516 ** The following functions are instrumented for malloc() failure
19517 ** testing:
19518 **
19519 ** sqlite3OsRead()
19520 ** sqlite3OsWrite()
19521 ** sqlite3OsSync()
19522 ** sqlite3OsFileSize()
19523 ** sqlite3OsLock()
19524 ** sqlite3OsCheckReservedLock()
19525 ** sqlite3OsFileControl()
19526 ** sqlite3OsShmMap()
19527 ** sqlite3OsOpen()
19528 ** sqlite3OsDelete()
19529 ** sqlite3OsAccess()
19530 ** sqlite3OsFullPathname()
19531 **
19532 */
19533 #if defined(SQLITE_TEST)
19534 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
19535  #define DO_OS_MALLOC_TEST(x) \
19536  if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3JournalIsInMemory(x))) { \
19537  void *pTstAlloc = sqlite3Malloc(10); \
19538  if (!pTstAlloc) return SQLITE_IOERR_NOMEM_BKPT; \
19539  sqlite3_free(pTstAlloc); \
19540  }
19541 #else
19542  #define DO_OS_MALLOC_TEST(x)
19543 #endif
19544 
19545 /*
19546 ** The following routines are convenience wrappers around methods
19547 ** of the sqlite3_file object. This is mostly just syntactic sugar. All
19548 ** of this would be completely automatic if SQLite were coded using
19549 ** C++ instead of plain old C.
19550 */
19551 SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *pId){
19552  if( pId->pMethods ){
19553  pId->pMethods->xClose(pId);
19554  pId->pMethods = 0;
19555  }
19556 }
19557 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
19558  DO_OS_MALLOC_TEST(id);
19559  return id->pMethods->xRead(id, pBuf, amt, offset);
19560 }
19561 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
19562  DO_OS_MALLOC_TEST(id);
19563  return id->pMethods->xWrite(id, pBuf, amt, offset);
19564 }
19565 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
19566  return id->pMethods->xTruncate(id, size);
19567 }
19568 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
19569  DO_OS_MALLOC_TEST(id);
19570  return id->pMethods->xSync(id, flags);
19571 }
19572 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
19573  DO_OS_MALLOC_TEST(id);
19574  return id->pMethods->xFileSize(id, pSize);
19575 }
19576 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
19577  DO_OS_MALLOC_TEST(id);
19578  return id->pMethods->xLock(id, lockType);
19579 }
19580 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
19581  return id->pMethods->xUnlock(id, lockType);
19582 }
19583 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
19584  DO_OS_MALLOC_TEST(id);
19585  return id->pMethods->xCheckReservedLock(id, pResOut);
19586 }
19587 
19588 /*
19589 ** Use sqlite3OsFileControl() when we are doing something that might fail
19590 ** and we need to know about the failures. Use sqlite3OsFileControlHint()
19591 ** when simply tossing information over the wall to the VFS and we do not
19592 ** really care if the VFS receives and understands the information since it
19593 ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
19594 ** routine has no return value since the return value would be meaningless.
19595 */
19596 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
19597 #ifdef SQLITE_TEST
19598  if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
19599  /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
19600  ** is using a regular VFS, it is called after the corresponding
19601  ** transaction has been committed. Injecting a fault at this point
19602  ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
19603  ** but the transaction is committed anyway.
19604  **
19605  ** The core must call OsFileControl() though, not OsFileControlHint(),
19606  ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
19607  ** means the commit really has failed and an error should be returned
19608  ** to the user. */
19609  DO_OS_MALLOC_TEST(id);
19610  }
19611 #endif
19612  return id->pMethods->xFileControl(id, op, pArg);
19613 }
19614 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
19615  (void)id->pMethods->xFileControl(id, op, pArg);
19616 }
19617 
19618 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
19619  int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
19620  return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
19621 }
19623  return id->pMethods->xDeviceCharacteristics(id);
19624 }
19625 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
19626  return id->pMethods->xShmLock(id, offset, n, flags);
19627 }
19628 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
19629  id->pMethods->xShmBarrier(id);
19630 }
19631 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
19632  return id->pMethods->xShmUnmap(id, deleteFlag);
19633 }
19635  sqlite3_file *id, /* Database file handle */
19636  int iPage,
19637  int pgsz,
19638  int bExtend, /* True to extend file if necessary */
19639  void volatile **pp /* OUT: Pointer to mapping */
19640 ){
19641  DO_OS_MALLOC_TEST(id);
19642  return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
19643 }
19644 
19645 #if SQLITE_MAX_MMAP_SIZE>0
19646 /* The real implementation of xFetch and xUnfetch */
19647 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19648  DO_OS_MALLOC_TEST(id);
19649  return id->pMethods->xFetch(id, iOff, iAmt, pp);
19650 }
19651 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19652  return id->pMethods->xUnfetch(id, iOff, p);
19653 }
19654 #else
19655 /* No-op stubs to use when memory-mapped I/O is disabled */
19656 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
19657  *pp = 0;
19658  return SQLITE_OK;
19659 }
19660 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
19661  return SQLITE_OK;
19662 }
19663 #endif
19664 
19665 /*
19666 ** The next group of routines are convenience wrappers around the
19667 ** VFS methods.
19668 */
19670  sqlite3_vfs *pVfs,
19671  const char *zPath,
19672  sqlite3_file *pFile,
19673  int flags,
19674  int *pFlagsOut
19675 ){
19676  int rc;
19677  DO_OS_MALLOC_TEST(0);
19678  /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
19679  ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
19680  ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
19681  ** reaching the VFS. */
19682  rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
19683  assert( rc==SQLITE_OK || pFile->pMethods==0 );
19684  return rc;
19685 }
19686 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
19687  DO_OS_MALLOC_TEST(0);
19688  assert( dirSync==0 || dirSync==1 );
19689  return pVfs->xDelete(pVfs, zPath, dirSync);
19690 }
19692  sqlite3_vfs *pVfs,
19693  const char *zPath,
19694  int flags,
19695  int *pResOut
19696 ){
19697  DO_OS_MALLOC_TEST(0);
19698  return pVfs->xAccess(pVfs, zPath, flags, pResOut);
19699 }
19701  sqlite3_vfs *pVfs,
19702  const char *zPath,
19703  int nPathOut,
19704  char *zPathOut
19705 ){
19706  DO_OS_MALLOC_TEST(0);
19707  zPathOut[0] = 0;
19708  return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
19709 }
19710 #ifndef SQLITE_OMIT_LOAD_EXTENSION
19711 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
19712  return pVfs->xDlOpen(pVfs, zPath);
19713 }
19714 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19715  pVfs->xDlError(pVfs, nByte, zBufOut);
19716 }
19717 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
19718  return pVfs->xDlSym(pVfs, pHdle, zSym);
19719 }
19720 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
19721  pVfs->xDlClose(pVfs, pHandle);
19722 }
19723 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
19724 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
19725  return pVfs->xRandomness(pVfs, nByte, zBufOut);
19726 }
19727 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
19728  return pVfs->xSleep(pVfs, nMicro);
19729 }
19730 SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *pVfs){
19731  return pVfs->xGetLastError ? pVfs->xGetLastError(pVfs, 0, 0) : 0;
19732 }
19733 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
19734  int rc;
19735  /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
19736  ** method to get the current date and time if that method is available
19737  ** (if iVersion is 2 or greater and the function pointer is not NULL) and
19738  ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
19739  ** unavailable.
19740  */
19741  if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
19742  rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
19743  }else{
19744  double r;
19745  rc = pVfs->xCurrentTime(pVfs, &r);
19746  *pTimeOut = (sqlite3_int64)(r*86400000.0);
19747  }
19748  return rc;
19749 }
19750 
19752  sqlite3_vfs *pVfs,
19753  const char *zFile,
19754  sqlite3_file **ppFile,
19755  int flags,
19756  int *pOutFlags
19757 ){
19758  int rc;
19759  sqlite3_file *pFile;
19760  pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
19761  if( pFile ){
19762  rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
19763  if( rc!=SQLITE_OK ){
19764  sqlite3_free(pFile);
19765  }else{
19766  *ppFile = pFile;
19767  }
19768  }else{
19769  rc = SQLITE_NOMEM_BKPT;
19770  }
19771  return rc;
19772 }
19773 SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *pFile){
19774  assert( pFile );
19775  sqlite3OsClose(pFile);
19776  sqlite3_free(pFile);
19777 }
19778 
19779 /*
19780 ** This function is a wrapper around the OS specific implementation of
19781 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
19782 ** ability to simulate a malloc failure, so that the handling of an
19783 ** error in sqlite3_os_init() by the upper layers can be tested.
19784 */
19786  void *p = sqlite3_malloc(10);
19787  if( p==0 ) return SQLITE_NOMEM_BKPT;
19788  sqlite3_free(p);
19789  return sqlite3_os_init();
19790 }
19791 
19792 /*
19793 ** The list of all registered VFS implementations.
19794 */
19795 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
19796 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
19797 
19798 /*
19799 ** Locate a VFS by name. If no name is given, simply return the
19800 ** first VFS on the list.
19801 */
19802 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
19803  sqlite3_vfs *pVfs = 0;
19804 #if SQLITE_THREADSAFE
19805  sqlite3_mutex *mutex;
19806 #endif
19807 #ifndef SQLITE_OMIT_AUTOINIT
19808  int rc = sqlite3_initialize();
19809  if( rc ) return 0;
19810 #endif
19811 #if SQLITE_THREADSAFE
19813 #endif
19814  sqlite3_mutex_enter(mutex);
19815  for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
19816  if( zVfs==0 ) break;
19817  if( strcmp(zVfs, pVfs->zName)==0 ) break;
19818  }
19819  sqlite3_mutex_leave(mutex);
19820  return pVfs;
19821 }
19822 
19823 /*
19824 ** Unlink a VFS from the linked list
19825 */
19826 static void vfsUnlink(sqlite3_vfs *pVfs){
19828  if( pVfs==0 ){
19829  /* No-op */
19830  }else if( vfsList==pVfs ){
19831  vfsList = pVfs->pNext;
19832  }else if( vfsList ){
19833  sqlite3_vfs *p = vfsList;
19834  while( p->pNext && p->pNext!=pVfs ){
19835  p = p->pNext;
19836  }
19837  if( p->pNext==pVfs ){
19838  p->pNext = pVfs->pNext;
19839  }
19840  }
19841 }
19842 
19843 /*
19844 ** Register a VFS with the system. It is harmless to register the same
19845 ** VFS multiple times. The new VFS becomes the default if makeDflt is
19846 ** true.
19847 */
19848 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
19849  MUTEX_LOGIC(sqlite3_mutex *mutex;)
19850 #ifndef SQLITE_OMIT_AUTOINIT
19851  int rc = sqlite3_initialize();
19852  if( rc ) return rc;
19853 #endif
19854 #ifdef SQLITE_ENABLE_API_ARMOR
19855  if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
19856 #endif
19857 
19859  sqlite3_mutex_enter(mutex);
19860  vfsUnlink(pVfs);
19861  if( makeDflt || vfsList==0 ){
19862  pVfs->pNext = vfsList;
19863  vfsList = pVfs;
19864  }else{
19865  pVfs->pNext = vfsList->pNext;
19866  vfsList->pNext = pVfs;
19867  }
19868  assert(vfsList);
19869  sqlite3_mutex_leave(mutex);
19870  return SQLITE_OK;
19871 }
19872 
19873 /*
19874 ** Unregister a VFS so that it is no longer accessible.
19875 */
19877 #if SQLITE_THREADSAFE
19879 #endif
19880  sqlite3_mutex_enter(mutex);
19881  vfsUnlink(pVfs);
19882  sqlite3_mutex_leave(mutex);
19883  return SQLITE_OK;
19884 }
19885 
19886 /************** End of os.c **************************************************/
19887 /************** Begin file fault.c *******************************************/
19888 /*
19889 ** 2008 Jan 22
19890 **
19891 ** The author disclaims copyright to this source code. In place of
19892 ** a legal notice, here is a blessing:
19893 **
19894 ** May you do good and not evil.
19895 ** May you find forgiveness for yourself and forgive others.
19896 ** May you share freely, never taking more than you give.
19897 **
19898 *************************************************************************
19899 **
19900 ** This file contains code to support the concept of "benign"
19901 ** malloc failures (when the xMalloc() or xRealloc() method of the
19902 ** sqlite3_mem_methods structure fails to allocate a block of memory
19903 ** and returns 0).
19904 **
19905 ** Most malloc failures are non-benign. After they occur, SQLite
19906 ** abandons the current operation and returns an error code (usually
19907 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
19908 ** fatal. For example, if a malloc fails while resizing a hash table, this
19909 ** is completely recoverable simply by not carrying out the resize. The
19910 ** hash table will continue to function normally. So a malloc failure
19911 ** during a hash table resize is a benign fault.
19912 */
19913 
19914 /* #include "sqliteInt.h" */
19915 
19916 #ifndef SQLITE_OMIT_BUILTIN_TEST
19917 
19918 /*
19919 ** Global variables.
19920 */
19923  void (*xBenignBegin)(void);
19924  void (*xBenignEnd)(void);
19925 } sqlite3Hooks = { 0, 0 };
19926 
19927 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
19928 ** structure. If writable static data is unsupported on the target,
19929 ** we have to locate the state vector at run-time. In the more common
19930 ** case where writable static data is supported, wsdHooks can refer directly
19931 ** to the "sqlite3Hooks" state vector declared above.
19932 */
19933 #ifdef SQLITE_OMIT_WSD
19934 # define wsdHooksInit \
19935  BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
19936 # define wsdHooks x[0]
19937 #else
19938 # define wsdHooksInit
19939 # define wsdHooks sqlite3Hooks
19940 #endif
19941 
19942 
19943 /*
19944 ** Register hooks to call when sqlite3BeginBenignMalloc() and
19945 ** sqlite3EndBenignMalloc() are called, respectively.
19946 */
19948  void (*xBenignBegin)(void),
19949  void (*xBenignEnd)(void)
19950 ){
19951  wsdHooksInit;
19952  wsdHooks.xBenignBegin = xBenignBegin;
19953  wsdHooks.xBenignEnd = xBenignEnd;
19954 }
19955 
19956 /*
19957 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
19958 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
19959 ** indicates that subsequent malloc failures are non-benign.
19960 */
19962  wsdHooksInit;
19963  if( wsdHooks.xBenignBegin ){
19964  wsdHooks.xBenignBegin();
19965  }
19966 }
19968  wsdHooksInit;
19969  if( wsdHooks.xBenignEnd ){
19970  wsdHooks.xBenignEnd();
19971  }
19972 }
19973 
19974 #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
19975 
19976 /************** End of fault.c ***********************************************/
19977 /************** Begin file mem0.c ********************************************/
19978 /*
19979 ** 2008 October 28
19980 **
19981 ** The author disclaims copyright to this source code. In place of
19982 ** a legal notice, here is a blessing:
19983 **
19984 ** May you do good and not evil.
19985 ** May you find forgiveness for yourself and forgive others.
19986 ** May you share freely, never taking more than you give.
19987 **
19988 *************************************************************************
19989 **
19990 ** This file contains a no-op memory allocation drivers for use when
19991 ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
19992 ** here always fail. SQLite will not operate with these drivers. These
19993 ** are merely placeholders. Real drivers must be substituted using
19994 ** sqlite3_config() before SQLite will operate.
19995 */
19996 /* #include "sqliteInt.h" */
19997 
19998 /*
19999 ** This version of the memory allocator is the default. It is
20000 ** used when no other memory allocator is specified using compile-time
20001 ** macros.
20002 */
20003 #ifdef SQLITE_ZERO_MALLOC
20004 
20005 /*
20006 ** No-op versions of all memory allocation routines
20007 */
20008 static void *sqlite3MemMalloc(int nByte){ return 0; }
20009 static void sqlite3MemFree(void *pPrior){ return; }
20010 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
20011 static int sqlite3MemSize(void *pPrior){ return 0; }
20012 static int sqlite3MemRoundup(int n){ return n; }
20013 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
20014 static void sqlite3MemShutdown(void *NotUsed){ return; }
20015 
20016 /*
20017 ** This routine is the only routine in this file with external linkage.
20018 **
20019 ** Populate the low-level memory allocation function pointers in
20020 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20021 */
20023  static const sqlite3_mem_methods defaultMethods = {
20031  0
20032  };
20033  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20034 }
20035 
20036 #endif /* SQLITE_ZERO_MALLOC */
20037 
20038 /************** End of mem0.c ************************************************/
20039 /************** Begin file mem1.c ********************************************/
20040 /*
20041 ** 2007 August 14
20042 **
20043 ** The author disclaims copyright to this source code. In place of
20044 ** a legal notice, here is a blessing:
20045 **
20046 ** May you do good and not evil.
20047 ** May you find forgiveness for yourself and forgive others.
20048 ** May you share freely, never taking more than you give.
20049 **
20050 *************************************************************************
20051 **
20052 ** This file contains low-level memory allocation drivers for when
20053 ** SQLite will use the standard C-library malloc/realloc/free interface
20054 ** to obtain the memory it needs.
20055 **
20056 ** This file contains implementations of the low-level memory allocation
20057 ** routines specified in the sqlite3_mem_methods object. The content of
20058 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
20059 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
20060 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
20061 ** default configuration is to use memory allocation routines in this
20062 ** file.
20063 **
20064 ** C-preprocessor macro summary:
20065 **
20066 ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
20067 ** the malloc_usable_size() interface exists
20068 ** on the target platform. Or, this symbol
20069 ** can be set manually, if desired.
20070 ** If an equivalent interface exists by
20071 ** a different name, using a separate -D
20072 ** option to rename it.
20073 **
20074 ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
20075 ** memory allocator. Set this symbol to enable
20076 ** building on older macs.
20077 **
20078 ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
20079 ** _msize() on windows systems. This might
20080 ** be necessary when compiling for Delphi,
20081 ** for example.
20082 */
20083 /* #include "sqliteInt.h" */
20084 
20085 /*
20086 ** This version of the memory allocator is the default. It is
20087 ** used when no other memory allocator is specified using compile-time
20088 ** macros.
20089 */
20090 #ifdef SQLITE_SYSTEM_MALLOC
20091 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20092 
20093 /*
20094 ** Use the zone allocator available on apple products unless the
20095 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
20096 */
20097 #include <sys/sysctl.h>
20098 #include <malloc/malloc.h>
20099 #include <libkern/OSAtomic.h>
20100 static malloc_zone_t* _sqliteZone_;
20101 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
20102 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
20103 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
20104 #define SQLITE_MALLOCSIZE(x) \
20105  (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
20106 
20107 #else /* if not __APPLE__ */
20108 
20109 /*
20110 ** Use standard C library malloc and free on non-Apple systems.
20111 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
20112 */
20113 #define SQLITE_MALLOC(x) malloc(x)
20114 #define SQLITE_FREE(x) free(x)
20115 #define SQLITE_REALLOC(x,y) realloc((x),(y))
20116 
20117 /*
20118 ** The malloc.h header file is needed for malloc_usable_size() function
20119 ** on some systems (e.g. Linux).
20120 */
20121 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
20122 # define SQLITE_USE_MALLOC_H 1
20123 # define SQLITE_USE_MALLOC_USABLE_SIZE 1
20124 /*
20125 ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
20126 ** use of _msize() is automatic, but can be disabled by compiling with
20127 ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
20128 ** the malloc.h header file.
20129 */
20130 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
20131 # define SQLITE_USE_MALLOC_H
20132 # define SQLITE_USE_MSIZE
20133 #endif
20134 
20135 /*
20136 ** Include the malloc.h header file, if necessary. Also set define macro
20137 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
20138 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
20139 ** The memory size function can always be overridden manually by defining
20140 ** the macro SQLITE_MALLOCSIZE to the desired function name.
20141 */
20142 #if defined(SQLITE_USE_MALLOC_H)
20143 # include <malloc.h>
20144 # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
20145 # if !defined(SQLITE_MALLOCSIZE)
20146 # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
20147 # endif
20148 # elif defined(SQLITE_USE_MSIZE)
20149 # if !defined(SQLITE_MALLOCSIZE)
20150 # define SQLITE_MALLOCSIZE _msize
20151 # endif
20152 # endif
20153 #endif /* defined(SQLITE_USE_MALLOC_H) */
20154 
20155 #endif /* __APPLE__ or not __APPLE__ */
20156 
20157 /*
20158 ** Like malloc(), but remember the size of the allocation
20159 ** so that we can find it later using sqlite3MemSize().
20160 **
20161 ** For this low-level routine, we are guaranteed that nByte>0 because
20162 ** cases of nByte<=0 will be intercepted and dealt with by higher level
20163 ** routines.
20164 */
20165 static void *sqlite3MemMalloc(int nByte){
20166 #ifdef SQLITE_MALLOCSIZE
20167  void *p = SQLITE_MALLOC( nByte );
20168  if( p==0 ){
20169  testcase( sqlite3GlobalConfig.xLog!=0 );
20170  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20171  }
20172  return p;
20173 #else
20174  sqlite3_int64 *p;
20175  assert( nByte>0 );
20176  nByte = ROUND8(nByte);
20177  p = SQLITE_MALLOC( nByte+8 );
20178  if( p ){
20179  p[0] = nByte;
20180  p++;
20181  }else{
20182  testcase( sqlite3GlobalConfig.xLog!=0 );
20183  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
20184  }
20185  return (void *)p;
20186 #endif
20187 }
20188 
20189 /*
20190 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
20191 ** or sqlite3MemRealloc().
20192 **
20193 ** For this low-level routine, we already know that pPrior!=0 since
20194 ** cases where pPrior==0 will have been intecepted and dealt with
20195 ** by higher-level routines.
20196 */
20197 static void sqlite3MemFree(void *pPrior){
20198 #ifdef SQLITE_MALLOCSIZE
20199  SQLITE_FREE(pPrior);
20200 #else
20201  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20202  assert( pPrior!=0 );
20203  p--;
20204  SQLITE_FREE(p);
20205 #endif
20206 }
20207 
20208 /*
20209 ** Report the allocated size of a prior return from xMalloc()
20210 ** or xRealloc().
20211 */
20212 static int sqlite3MemSize(void *pPrior){
20213 #ifdef SQLITE_MALLOCSIZE
20214  assert( pPrior!=0 );
20215  return (int)SQLITE_MALLOCSIZE(pPrior);
20216 #else
20217  sqlite3_int64 *p;
20218  assert( pPrior!=0 );
20219  p = (sqlite3_int64*)pPrior;
20220  p--;
20221  return (int)p[0];
20222 #endif
20223 }
20224 
20225 /*
20226 ** Like realloc(). Resize an allocation previously obtained from
20227 ** sqlite3MemMalloc().
20228 **
20229 ** For this low-level interface, we know that pPrior!=0. Cases where
20230 ** pPrior==0 while have been intercepted by higher-level routine and
20231 ** redirected to xMalloc. Similarly, we know that nByte>0 because
20232 ** cases where nByte<=0 will have been intercepted by higher-level
20233 ** routines and redirected to xFree.
20234 */
20235 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20236 #ifdef SQLITE_MALLOCSIZE
20237  void *p = SQLITE_REALLOC(pPrior, nByte);
20238  if( p==0 ){
20239  testcase( sqlite3GlobalConfig.xLog!=0 );
20241  "failed memory resize %u to %u bytes",
20242  SQLITE_MALLOCSIZE(pPrior), nByte);
20243  }
20244  return p;
20245 #else
20246  sqlite3_int64 *p = (sqlite3_int64*)pPrior;
20247  assert( pPrior!=0 && nByte>0 );
20248  assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
20249  p--;
20250  p = SQLITE_REALLOC(p, nByte+8 );
20251  if( p ){
20252  p[0] = nByte;
20253  p++;
20254  }else{
20255  testcase( sqlite3GlobalConfig.xLog!=0 );
20257  "failed memory resize %u to %u bytes",
20258  sqlite3MemSize(pPrior), nByte);
20259  }
20260  return (void*)p;
20261 #endif
20262 }
20263 
20264 /*
20265 ** Round up a request size to the next valid allocation size.
20266 */
20267 static int sqlite3MemRoundup(int n){
20268  return ROUND8(n);
20269 }
20270 
20271 /*
20272 ** Initialize this module.
20273 */
20274 static int sqlite3MemInit(void *NotUsed){
20275 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
20276  int cpuCount;
20277  size_t len;
20278  if( _sqliteZone_ ){
20279  return SQLITE_OK;
20280  }
20281  len = sizeof(cpuCount);
20282  /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
20283  sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
20284  if( cpuCount>1 ){
20285  /* defer MT decisions to system malloc */
20286  _sqliteZone_ = malloc_default_zone();
20287  }else{
20288  /* only 1 core, use our own zone to contention over global locks,
20289  ** e.g. we have our own dedicated locks */
20290  bool success;
20291  malloc_zone_t* newzone = malloc_create_zone(4096, 0);
20292  malloc_set_zone_name(newzone, "Sqlite_Heap");
20293  do{
20294  success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
20295  (void * volatile *)&_sqliteZone_);
20296  }while(!_sqliteZone_);
20297  if( !success ){
20298  /* somebody registered a zone first */
20299  malloc_destroy_zone(newzone);
20300  }
20301  }
20302 #endif
20303  UNUSED_PARAMETER(NotUsed);
20304  return SQLITE_OK;
20305 }
20306 
20307 /*
20308 ** Deinitialize this module.
20309 */
20310 static void sqlite3MemShutdown(void *NotUsed){
20311  UNUSED_PARAMETER(NotUsed);
20312  return;
20313 }
20314 
20315 /*
20316 ** This routine is the only routine in this file with external linkage.
20317 **
20318 ** Populate the low-level memory allocation function pointers in
20319 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20320 */
20322  static const sqlite3_mem_methods defaultMethods = {
20330  0
20331  };
20332  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20333 }
20334 
20335 #endif /* SQLITE_SYSTEM_MALLOC */
20336 
20337 /************** End of mem1.c ************************************************/
20338 /************** Begin file mem2.c ********************************************/
20339 /*
20340 ** 2007 August 15
20341 **
20342 ** The author disclaims copyright to this source code. In place of
20343 ** a legal notice, here is a blessing:
20344 **
20345 ** May you do good and not evil.
20346 ** May you find forgiveness for yourself and forgive others.
20347 ** May you share freely, never taking more than you give.
20348 **
20349 *************************************************************************
20350 **
20351 ** This file contains low-level memory allocation drivers for when
20352 ** SQLite will use the standard C-library malloc/realloc/free interface
20353 ** to obtain the memory it needs while adding lots of additional debugging
20354 ** information to each allocation in order to help detect and fix memory
20355 ** leaks and memory usage errors.
20356 **
20357 ** This file contains implementations of the low-level memory allocation
20358 ** routines specified in the sqlite3_mem_methods object.
20359 */
20360 /* #include "sqliteInt.h" */
20361 
20362 /*
20363 ** This version of the memory allocator is used only if the
20364 ** SQLITE_MEMDEBUG macro is defined
20365 */
20366 #ifdef SQLITE_MEMDEBUG
20367 
20368 /*
20369 ** The backtrace functionality is only available with GLIBC
20370 */
20371 #ifdef __GLIBC__
20372  extern int backtrace(void**,int);
20373  extern void backtrace_symbols_fd(void*const*,int,int);
20374 #else
20375 # define backtrace(A,B) 1
20376 # define backtrace_symbols_fd(A,B,C)
20377 #endif
20378 /* #include <stdio.h> */
20379 
20380 /*
20381 ** Each memory allocation looks like this:
20382 **
20383 ** ------------------------------------------------------------------------
20384 ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
20385 ** ------------------------------------------------------------------------
20386 **
20387 ** The application code sees only a pointer to the allocation. We have
20388 ** to back up from the allocation pointer to find the MemBlockHdr. The
20389 ** MemBlockHdr tells us the size of the allocation and the number of
20390 ** backtrace pointers. There is also a guard word at the end of the
20391 ** MemBlockHdr.
20392 */
20393 struct MemBlockHdr {
20394  i64 iSize; /* Size of this allocation */
20395  struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
20396  char nBacktrace; /* Number of backtraces on this alloc */
20397  char nBacktraceSlots; /* Available backtrace slots */
20398  u8 nTitle; /* Bytes of title; includes '\0' */
20399  u8 eType; /* Allocation type code */
20400  int iForeGuard; /* Guard word for sanity */
20401 };
20402 
20403 /*
20404 ** Guard words
20405 */
20406 #define FOREGUARD 0x80F5E153
20407 #define REARGUARD 0xE4676B53
20408 
20409 /*
20410 ** Number of malloc size increments to track.
20411 */
20412 #define NCSIZE 1000
20413 
20414 /*
20415 ** All of the static variables used by this module are collected
20416 ** into a single structure named "mem". This is to keep the
20417 ** static variables organized and to reduce namespace pollution
20418 ** when this module is combined with other in the amalgamation.
20419 */
20420 static struct {
20421 
20422  /*
20423  ** Mutex to control access to the memory allocation subsystem.
20424  */
20425  sqlite3_mutex *mutex;
20426 
20427  /*
20428  ** Head and tail of a linked list of all outstanding allocations
20429  */
20430  struct MemBlockHdr *pFirst;
20431  struct MemBlockHdr *pLast;
20432 
20433  /*
20434  ** The number of levels of backtrace to save in new allocations.
20435  */
20436  int nBacktrace;
20437  void (*xBacktrace)(int, int, void **);
20438 
20439  /*
20440  ** Title text to insert in front of each block
20441  */
20442  int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
20443  char zTitle[100]; /* The title text */
20444 
20445  /*
20446  ** sqlite3MallocDisallow() increments the following counter.
20447  ** sqlite3MallocAllow() decrements it.
20448  */
20449  int disallow; /* Do not allow memory allocation */
20450 
20451  /*
20452  ** Gather statistics on the sizes of memory allocations.
20453  ** nAlloc[i] is the number of allocation attempts of i*8
20454  ** bytes. i==NCSIZE is the number of allocation attempts for
20455  ** sizes more than NCSIZE*8 bytes.
20456  */
20457  int nAlloc[NCSIZE]; /* Total number of allocations */
20458  int nCurrent[NCSIZE]; /* Current number of allocations */
20459  int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
20460 
20461 } mem;
20462 
20463 
20464 /*
20465 ** Adjust memory usage statistics
20466 */
20467 static void adjustStats(int iSize, int increment){
20468  int i = ROUND8(iSize)/8;
20469  if( i>NCSIZE-1 ){
20470  i = NCSIZE - 1;
20471  }
20472  if( increment>0 ){
20473  mem.nAlloc[i]++;
20474  mem.nCurrent[i]++;
20475  if( mem.nCurrent[i]>mem.mxCurrent[i] ){
20476  mem.mxCurrent[i] = mem.nCurrent[i];
20477  }
20478  }else{
20479  mem.nCurrent[i]--;
20480  assert( mem.nCurrent[i]>=0 );
20481  }
20482 }
20483 
20484 /*
20485 ** Given an allocation, find the MemBlockHdr for that allocation.
20486 **
20487 ** This routine checks the guards at either end of the allocation and
20488 ** if they are incorrect it asserts.
20489 */
20490 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
20491  struct MemBlockHdr *p;
20492  int *pInt;
20493  u8 *pU8;
20494  int nReserve;
20495 
20496  p = (struct MemBlockHdr*)pAllocation;
20497  p--;
20498  assert( p->iForeGuard==(int)FOREGUARD );
20499  nReserve = ROUND8(p->iSize);
20500  pInt = (int*)pAllocation;
20501  pU8 = (u8*)pAllocation;
20502  assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
20503  /* This checks any of the "extra" bytes allocated due
20504  ** to rounding up to an 8 byte boundary to ensure
20505  ** they haven't been overwritten.
20506  */
20507  while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
20508  return p;
20509 }
20510 
20511 /*
20512 ** Return the number of bytes currently allocated at address p.
20513 */
20514 static int sqlite3MemSize(void *p){
20515  struct MemBlockHdr *pHdr;
20516  if( !p ){
20517  return 0;
20518  }
20519  pHdr = sqlite3MemsysGetHeader(p);
20520  return (int)pHdr->iSize;
20521 }
20522 
20523 /*
20524 ** Initialize the memory allocation subsystem.
20525 */
20526 static int sqlite3MemInit(void *NotUsed){
20527  UNUSED_PARAMETER(NotUsed);
20528  assert( (sizeof(struct MemBlockHdr)&7) == 0 );
20529  if( !sqlite3GlobalConfig.bMemstat ){
20530  /* If memory status is enabled, then the malloc.c wrapper will already
20531  ** hold the STATIC_MEM mutex when the routines here are invoked. */
20533  }
20534  return SQLITE_OK;
20535 }
20536 
20537 /*
20538 ** Deinitialize the memory allocation subsystem.
20539 */
20540 static void sqlite3MemShutdown(void *NotUsed){
20541  UNUSED_PARAMETER(NotUsed);
20542  mem.mutex = 0;
20543 }
20544 
20545 /*
20546 ** Round up a request size to the next valid allocation size.
20547 */
20548 static int sqlite3MemRoundup(int n){
20549  return ROUND8(n);
20550 }
20551 
20552 /*
20553 ** Fill a buffer with pseudo-random bytes. This is used to preset
20554 ** the content of a new memory allocation to unpredictable values and
20555 ** to clear the content of a freed allocation to unpredictable values.
20556 */
20557 static void randomFill(char *pBuf, int nByte){
20558  unsigned int x, y, r;
20559  x = SQLITE_PTR_TO_INT(pBuf);
20560  y = nByte | 1;
20561  while( nByte >= 4 ){
20562  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20563  y = y*1103515245 + 12345;
20564  r = x ^ y;
20565  *(int*)pBuf = r;
20566  pBuf += 4;
20567  nByte -= 4;
20568  }
20569  while( nByte-- > 0 ){
20570  x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
20571  y = y*1103515245 + 12345;
20572  r = x ^ y;
20573  *(pBuf++) = r & 0xff;
20574  }
20575 }
20576 
20577 /*
20578 ** Allocate nByte bytes of memory.
20579 */
20580 static void *sqlite3MemMalloc(int nByte){
20581  struct MemBlockHdr *pHdr;
20582  void **pBt;
20583  char *z;
20584  int *pInt;
20585  void *p = 0;
20586  int totalSize;
20587  int nReserve;
20588  sqlite3_mutex_enter(mem.mutex);
20589  assert( mem.disallow==0 );
20590  nReserve = ROUND8(nByte);
20591  totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
20592  mem.nBacktrace*sizeof(void*) + mem.nTitle;
20593  p = malloc(totalSize);
20594  if( p ){
20595  z = p;
20596  pBt = (void**)&z[mem.nTitle];
20597  pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
20598  pHdr->pNext = 0;
20599  pHdr->pPrev = mem.pLast;
20600  if( mem.pLast ){
20601  mem.pLast->pNext = pHdr;
20602  }else{
20603  mem.pFirst = pHdr;
20604  }
20605  mem.pLast = pHdr;
20606  pHdr->iForeGuard = FOREGUARD;
20607  pHdr->eType = MEMTYPE_HEAP;
20608  pHdr->nBacktraceSlots = mem.nBacktrace;
20609  pHdr->nTitle = mem.nTitle;
20610  if( mem.nBacktrace ){
20611  void *aAddr[40];
20612  pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
20613  memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
20614  assert(pBt[0]);
20615  if( mem.xBacktrace ){
20616  mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
20617  }
20618  }else{
20619  pHdr->nBacktrace = 0;
20620  }
20621  if( mem.nTitle ){
20622  memcpy(z, mem.zTitle, mem.nTitle);
20623  }
20624  pHdr->iSize = nByte;
20625  adjustStats(nByte, +1);
20626  pInt = (int*)&pHdr[1];
20627  pInt[nReserve/sizeof(int)] = REARGUARD;
20628  randomFill((char*)pInt, nByte);
20629  memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
20630  p = (void*)pInt;
20631  }
20632  sqlite3_mutex_leave(mem.mutex);
20633  return p;
20634 }
20635 
20636 /*
20637 ** Free memory.
20638 */
20639 static void sqlite3MemFree(void *pPrior){
20640  struct MemBlockHdr *pHdr;
20641  void **pBt;
20642  char *z;
20643  assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
20644  || mem.mutex!=0 );
20645  pHdr = sqlite3MemsysGetHeader(pPrior);
20646  pBt = (void**)pHdr;
20647  pBt -= pHdr->nBacktraceSlots;
20648  sqlite3_mutex_enter(mem.mutex);
20649  if( pHdr->pPrev ){
20650  assert( pHdr->pPrev->pNext==pHdr );
20651  pHdr->pPrev->pNext = pHdr->pNext;
20652  }else{
20653  assert( mem.pFirst==pHdr );
20654  mem.pFirst = pHdr->pNext;
20655  }
20656  if( pHdr->pNext ){
20657  assert( pHdr->pNext->pPrev==pHdr );
20658  pHdr->pNext->pPrev = pHdr->pPrev;
20659  }else{
20660  assert( mem.pLast==pHdr );
20661  mem.pLast = pHdr->pPrev;
20662  }
20663  z = (char*)pBt;
20664  z -= pHdr->nTitle;
20665  adjustStats((int)pHdr->iSize, -1);
20666  randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
20667  (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
20668  free(z);
20669  sqlite3_mutex_leave(mem.mutex);
20670 }
20671 
20672 /*
20673 ** Change the size of an existing memory allocation.
20674 **
20675 ** For this debugging implementation, we *always* make a copy of the
20676 ** allocation into a new place in memory. In this way, if the
20677 ** higher level code is using pointer to the old allocation, it is
20678 ** much more likely to break and we are much more liking to find
20679 ** the error.
20680 */
20681 static void *sqlite3MemRealloc(void *pPrior, int nByte){
20682  struct MemBlockHdr *pOldHdr;
20683  void *pNew;
20684  assert( mem.disallow==0 );
20685  assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
20686  pOldHdr = sqlite3MemsysGetHeader(pPrior);
20687  pNew = sqlite3MemMalloc(nByte);
20688  if( pNew ){
20689  memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
20690  if( nByte>pOldHdr->iSize ){
20691  randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
20692  }
20693  sqlite3MemFree(pPrior);
20694  }
20695  return pNew;
20696 }
20697 
20698 /*
20699 ** Populate the low-level memory allocation function pointers in
20700 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
20701 */
20703  static const sqlite3_mem_methods defaultMethods = {
20711  0
20712  };
20713  sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
20714 }
20715 
20716 /*
20717 ** Set the "type" of an allocation.
20718 */
20719 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
20720  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20721  struct MemBlockHdr *pHdr;
20722  pHdr = sqlite3MemsysGetHeader(p);
20723  assert( pHdr->iForeGuard==FOREGUARD );
20724  pHdr->eType = eType;
20725  }
20726 }
20727 
20728 /*
20729 ** Return TRUE if the mask of type in eType matches the type of the
20730 ** allocation p. Also return true if p==NULL.
20731 **
20732 ** This routine is designed for use within an assert() statement, to
20733 ** verify the type of an allocation. For example:
20734 **
20735 ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20736 */
20737 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
20738  int rc = 1;
20739  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20740  struct MemBlockHdr *pHdr;
20741  pHdr = sqlite3MemsysGetHeader(p);
20742  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
20743  if( (pHdr->eType&eType)==0 ){
20744  rc = 0;
20745  }
20746  }
20747  return rc;
20748 }
20749 
20750 /*
20751 ** Return TRUE if the mask of type in eType matches no bits of the type of the
20752 ** allocation p. Also return true if p==NULL.
20753 **
20754 ** This routine is designed for use within an assert() statement, to
20755 ** verify the type of an allocation. For example:
20756 **
20757 ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20758 */
20759 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
20760  int rc = 1;
20761  if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
20762  struct MemBlockHdr *pHdr;
20763  pHdr = sqlite3MemsysGetHeader(p);
20764  assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
20765  if( (pHdr->eType&eType)!=0 ){
20766  rc = 0;
20767  }
20768  }
20769  return rc;
20770 }
20771 
20772 /*
20773 ** Set the number of backtrace levels kept for each allocation.
20774 ** A value of zero turns off backtracing. The number is always rounded
20775 ** up to a multiple of 2.
20776 */
20777 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
20778  if( depth<0 ){ depth = 0; }
20779  if( depth>20 ){ depth = 20; }
20780  depth = (depth+1)&0xfe;
20781  mem.nBacktrace = depth;
20782 }
20783 
20784 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
20785  mem.xBacktrace = xBacktrace;
20786 }
20787 
20788 /*
20789 ** Set the title string for subsequent allocations.
20790 */
20791 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
20792  unsigned int n = sqlite3Strlen30(zTitle) + 1;
20793  sqlite3_mutex_enter(mem.mutex);
20794  if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
20795  memcpy(mem.zTitle, zTitle, n);
20796  mem.zTitle[n] = 0;
20797  mem.nTitle = ROUND8(n);
20798  sqlite3_mutex_leave(mem.mutex);
20799 }
20800 
20801 SQLITE_PRIVATE void sqlite3MemdebugSync(){
20802  struct MemBlockHdr *pHdr;
20803  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
20804  void **pBt = (void**)pHdr;
20805  pBt -= pHdr->nBacktraceSlots;
20806  mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
20807  }
20808 }
20809 
20810 /*
20811 ** Open the file indicated and write a log of all unfreed memory
20812 ** allocations into that log.
20813 */
20814 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
20815  FILE *out;
20816  struct MemBlockHdr *pHdr;
20817  void **pBt;
20818  int i;
20819  out = fopen(zFilename, "w");
20820  if( out==0 ){
20821  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
20822  zFilename);
20823  return;
20824  }
20825  for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
20826  char *z = (char*)pHdr;
20827  z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
20828  fprintf(out, "**** %lld bytes at %p from %s ****\n",
20829  pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
20830  if( pHdr->nBacktrace ){
20831  fflush(out);
20832  pBt = (void**)pHdr;
20833  pBt -= pHdr->nBacktraceSlots;
20834  backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
20835  fprintf(out, "\n");
20836  }
20837  }
20838  fprintf(out, "COUNTS:\n");
20839  for(i=0; i<NCSIZE-1; i++){
20840  if( mem.nAlloc[i] ){
20841  fprintf(out, " %5d: %10d %10d %10d\n",
20842  i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
20843  }
20844  }
20845  if( mem.nAlloc[NCSIZE-1] ){
20846  fprintf(out, " %5d: %10d %10d %10d\n",
20847  NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
20848  mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
20849  }
20850  fclose(out);
20851 }
20852 
20853 /*
20854 ** Return the number of times sqlite3MemMalloc() has been called.
20855 */
20856 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
20857  int i;
20858  int nTotal = 0;
20859  for(i=0; i<NCSIZE; i++){
20860  nTotal += mem.nAlloc[i];
20861  }
20862  return nTotal;
20863 }
20864 
20865 
20866 #endif /* SQLITE_MEMDEBUG */
20867 
20868 /************** End of mem2.c ************************************************/
20869 /************** Begin file mem3.c ********************************************/
20870 /*
20871 ** 2007 October 14
20872 **
20873 ** The author disclaims copyright to this source code. In place of
20874 ** a legal notice, here is a blessing:
20875 **
20876 ** May you do good and not evil.
20877 ** May you find forgiveness for yourself and forgive others.
20878 ** May you share freely, never taking more than you give.
20879 **
20880 *************************************************************************
20881 ** This file contains the C functions that implement a memory
20882 ** allocation subsystem for use by SQLite.
20883 **
20884 ** This version of the memory allocation subsystem omits all
20885 ** use of malloc(). The SQLite user supplies a block of memory
20886 ** before calling sqlite3_initialize() from which allocations
20887 ** are made and returned by the xMalloc() and xRealloc()
20888 ** implementations. Once sqlite3_initialize() has been called,
20889 ** the amount of memory available to SQLite is fixed and cannot
20890 ** be changed.
20891 **
20892 ** This version of the memory allocation subsystem is included
20893 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
20894 */
20895 /* #include "sqliteInt.h" */
20896 
20897 /*
20898 ** This version of the memory allocator is only built into the library
20899 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
20900 ** mean that the library will use a memory-pool by default, just that
20901 ** it is available. The mempool allocator is activated by calling
20902 ** sqlite3_config().
20903 */
20904 #ifdef SQLITE_ENABLE_MEMSYS3
20905 
20906 /*
20907 ** Maximum size (in Mem3Blocks) of a "small" chunk.
20908 */
20909 #define MX_SMALL 10
20910 
20911 
20912 /*
20913 ** Number of freelist hash slots
20914 */
20915 #define N_HASH 61
20916 
20917 /*
20918 ** A memory allocation (also called a "chunk") consists of two or
20919 ** more blocks where each block is 8 bytes. The first 8 bytes are
20920 ** a header that is not returned to the user.
20921 **
20922 ** A chunk is two or more blocks that is either checked out or
20923 ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
20924 ** size of the allocation in blocks if the allocation is free.
20925 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
20926 ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
20927 ** is true if the previous chunk is checked out and false if the
20928 ** previous chunk is free. The u.hdr.prevSize field is the size of
20929 ** the previous chunk in blocks if the previous chunk is on the
20930 ** freelist. If the previous chunk is checked out, then
20931 ** u.hdr.prevSize can be part of the data for that chunk and should
20932 ** not be read or written.
20933 **
20934 ** We often identify a chunk by its index in mem3.aPool[]. When
20935 ** this is done, the chunk index refers to the second block of
20936 ** the chunk. In this way, the first chunk has an index of 1.
20937 ** A chunk index of 0 means "no such chunk" and is the equivalent
20938 ** of a NULL pointer.
20939 **
20940 ** The second block of free chunks is of the form u.list. The
20941 ** two fields form a double-linked list of chunks of related sizes.
20942 ** Pointers to the head of the list are stored in mem3.aiSmall[]
20943 ** for smaller chunks and mem3.aiHash[] for larger chunks.
20944 **
20945 ** The second block of a chunk is user data if the chunk is checked
20946 ** out. If a chunk is checked out, the user data may extend into
20947 ** the u.hdr.prevSize value of the following chunk.
20948 */
20949 typedef struct Mem3Block Mem3Block;
20950 struct Mem3Block {
20951  union {
20952  struct {
20953  u32 prevSize; /* Size of previous chunk in Mem3Block elements */
20954  u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
20955  } hdr;
20956  struct {
20957  u32 next; /* Index in mem3.aPool[] of next free chunk */
20958  u32 prev; /* Index in mem3.aPool[] of previous free chunk */
20959  } list;
20960  } u;
20961 };
20962 
20963 /*
20964 ** All of the static variables used by this module are collected
20965 ** into a single structure named "mem3". This is to keep the
20966 ** static variables organized and to reduce namespace pollution
20967 ** when this module is combined with other in the amalgamation.
20968 */
20969 static SQLITE_WSD struct Mem3Global {
20970  /*
20971  ** Memory available for allocation. nPool is the size of the array
20972  ** (in Mem3Blocks) pointed to by aPool less 2.
20973  */
20974  u32 nPool;
20975  Mem3Block *aPool;
20976 
20977  /*
20978  ** True if we are evaluating an out-of-memory callback.
20979  */
20980  int alarmBusy;
20981 
20982  /*
20983  ** Mutex to control access to the memory allocation subsystem.
20984  */
20985  sqlite3_mutex *mutex;
20986 
20987  /*
20988  ** The minimum amount of free space that we have seen.
20989  */
20990  u32 mnMaster;
20991 
20992  /*
20993  ** iMaster is the index of the master chunk. Most new allocations
20994  ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
20995  ** of the current master. iMaster is 0 if there is not master chunk.
20996  ** The master chunk is not in either the aiHash[] or aiSmall[].
20997  */
20998  u32 iMaster;
20999  u32 szMaster;
21000 
21001  /*
21002  ** Array of lists of free blocks according to the block size
21003  ** for smaller chunks, or a hash on the block size for larger
21004  ** chunks.
21005  */
21006  u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
21007  u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
21008 } mem3 = { 97535575 };
21009 
21010 #define mem3 GLOBAL(struct Mem3Global, mem3)
21011 
21012 /*
21013 ** Unlink the chunk at mem3.aPool[i] from list it is currently
21014 ** on. *pRoot is the list that i is a member of.
21015 */
21016 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
21017  u32 next = mem3.aPool[i].u.list.next;
21018  u32 prev = mem3.aPool[i].u.list.prev;
21019  assert( sqlite3_mutex_held(mem3.mutex) );
21020  if( prev==0 ){
21021  *pRoot = next;
21022  }else{
21023  mem3.aPool[prev].u.list.next = next;
21024  }
21025  if( next ){
21026  mem3.aPool[next].u.list.prev = prev;
21027  }
21028  mem3.aPool[i].u.list.next = 0;
21029  mem3.aPool[i].u.list.prev = 0;
21030 }
21031 
21032 /*
21033 ** Unlink the chunk at index i from
21034 ** whatever list is currently a member of.
21035 */
21036 static void memsys3Unlink(u32 i){
21037  u32 size, hash;
21038  assert( sqlite3_mutex_held(mem3.mutex) );
21039  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21040  assert( i>=1 );
21041  size = mem3.aPool[i-1].u.hdr.size4x/4;
21042  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21043  assert( size>=2 );
21044  if( size <= MX_SMALL ){
21045  memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
21046  }else{
21047  hash = size % N_HASH;
21048  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21049  }
21050 }
21051 
21052 /*
21053 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
21054 ** at *pRoot.
21055 */
21056 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
21057  assert( sqlite3_mutex_held(mem3.mutex) );
21058  mem3.aPool[i].u.list.next = *pRoot;
21059  mem3.aPool[i].u.list.prev = 0;
21060  if( *pRoot ){
21061  mem3.aPool[*pRoot].u.list.prev = i;
21062  }
21063  *pRoot = i;
21064 }
21065 
21066 /*
21067 ** Link the chunk at index i into either the appropriate
21068 ** small chunk list, or into the large chunk hash table.
21069 */
21070 static void memsys3Link(u32 i){
21071  u32 size, hash;
21072  assert( sqlite3_mutex_held(mem3.mutex) );
21073  assert( i>=1 );
21074  assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
21075  size = mem3.aPool[i-1].u.hdr.size4x/4;
21076  assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
21077  assert( size>=2 );
21078  if( size <= MX_SMALL ){
21079  memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
21080  }else{
21081  hash = size % N_HASH;
21082  memsys3LinkIntoList(i, &mem3.aiHash[hash]);
21083  }
21084 }
21085 
21086 /*
21087 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
21088 ** will already be held (obtained by code in malloc.c) if
21089 ** sqlite3GlobalConfig.bMemStat is true.
21090 */
21091 static void memsys3Enter(void){
21092  if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
21094  }
21095  sqlite3_mutex_enter(mem3.mutex);
21096 }
21097 static void memsys3Leave(void){
21098  sqlite3_mutex_leave(mem3.mutex);
21099 }
21100 
21101 /*
21102 ** Called when we are unable to satisfy an allocation of nBytes.
21103 */
21104 static void memsys3OutOfMemory(int nByte){
21105  if( !mem3.alarmBusy ){
21106  mem3.alarmBusy = 1;
21107  assert( sqlite3_mutex_held(mem3.mutex) );
21108  sqlite3_mutex_leave(mem3.mutex);
21109  sqlite3_release_memory(nByte);
21110  sqlite3_mutex_enter(mem3.mutex);
21111  mem3.alarmBusy = 0;
21112  }
21113 }
21114 
21115 
21116 /*
21117 ** Chunk i is a free chunk that has been unlinked. Adjust its
21118 ** size parameters for check-out and return a pointer to the
21119 ** user portion of the chunk.
21120 */
21121 static void *memsys3Checkout(u32 i, u32 nBlock){
21122  u32 x;
21123  assert( sqlite3_mutex_held(mem3.mutex) );
21124  assert( i>=1 );
21125  assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
21126  assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
21127  x = mem3.aPool[i-1].u.hdr.size4x;
21128  mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
21129  mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
21130  mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
21131  return &mem3.aPool[i];
21132 }
21133 
21134 /*
21135 ** Carve a piece off of the end of the mem3.iMaster free chunk.
21136 ** Return a pointer to the new allocation. Or, if the master chunk
21137 ** is not large enough, return 0.
21138 */
21139 static void *memsys3FromMaster(u32 nBlock){
21140  assert( sqlite3_mutex_held(mem3.mutex) );
21141  assert( mem3.szMaster>=nBlock );
21142  if( nBlock>=mem3.szMaster-1 ){
21143  /* Use the entire master */
21144  void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
21145  mem3.iMaster = 0;
21146  mem3.szMaster = 0;
21147  mem3.mnMaster = 0;
21148  return p;
21149  }else{
21150  /* Split the master block. Return the tail. */
21151  u32 newi, x;
21152  newi = mem3.iMaster + mem3.szMaster - nBlock;
21153  assert( newi > mem3.iMaster+1 );
21154  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
21155  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
21156  mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
21157  mem3.szMaster -= nBlock;
21158  mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
21159  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21160  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21161  if( mem3.szMaster < mem3.mnMaster ){
21162  mem3.mnMaster = mem3.szMaster;
21163  }
21164  return (void*)&mem3.aPool[newi];
21165  }
21166 }
21167 
21168 /*
21169 ** *pRoot is the head of a list of free chunks of the same size
21170 ** or same size hash. In other words, *pRoot is an entry in either
21171 ** mem3.aiSmall[] or mem3.aiHash[].
21172 **
21173 ** This routine examines all entries on the given list and tries
21174 ** to coalesce each entries with adjacent free chunks.
21175 **
21176 ** If it sees a chunk that is larger than mem3.iMaster, it replaces
21177 ** the current mem3.iMaster with the new larger chunk. In order for
21178 ** this mem3.iMaster replacement to work, the master chunk must be
21179 ** linked into the hash tables. That is not the normal state of
21180 ** affairs, of course. The calling routine must link the master
21181 ** chunk before invoking this routine, then must unlink the (possibly
21182 ** changed) master chunk once this routine has finished.
21183 */
21184 static void memsys3Merge(u32 *pRoot){
21185  u32 iNext, prev, size, i, x;
21186 
21187  assert( sqlite3_mutex_held(mem3.mutex) );
21188  for(i=*pRoot; i>0; i=iNext){
21189  iNext = mem3.aPool[i].u.list.next;
21190  size = mem3.aPool[i-1].u.hdr.size4x;
21191  assert( (size&1)==0 );
21192  if( (size&2)==0 ){
21193  memsys3UnlinkFromList(i, pRoot);
21194  assert( i > mem3.aPool[i-1].u.hdr.prevSize );
21195  prev = i - mem3.aPool[i-1].u.hdr.prevSize;
21196  if( prev==iNext ){
21197  iNext = mem3.aPool[prev].u.list.next;
21198  }
21199  memsys3Unlink(prev);
21200  size = i + size/4 - prev;
21201  x = mem3.aPool[prev-1].u.hdr.size4x & 2;
21202  mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
21203  mem3.aPool[prev+size-1].u.hdr.prevSize = size;
21204  memsys3Link(prev);
21205  i = prev;
21206  }else{
21207  size /= 4;
21208  }
21209  if( size>mem3.szMaster ){
21210  mem3.iMaster = i;
21211  mem3.szMaster = size;
21212  }
21213  }
21214 }
21215 
21216 /*
21217 ** Return a block of memory of at least nBytes in size.
21218 ** Return NULL if unable.
21219 **
21220 ** This function assumes that the necessary mutexes, if any, are
21221 ** already held by the caller. Hence "Unsafe".
21222 */
21223 static void *memsys3MallocUnsafe(int nByte){
21224  u32 i;
21225  u32 nBlock;
21226  u32 toFree;
21227 
21228  assert( sqlite3_mutex_held(mem3.mutex) );
21229  assert( sizeof(Mem3Block)==8 );
21230  if( nByte<=12 ){
21231  nBlock = 2;
21232  }else{
21233  nBlock = (nByte + 11)/8;
21234  }
21235  assert( nBlock>=2 );
21236 
21237  /* STEP 1:
21238  ** Look for an entry of the correct size in either the small
21239  ** chunk table or in the large chunk hash table. This is
21240  ** successful most of the time (about 9 times out of 10).
21241  */
21242  if( nBlock <= MX_SMALL ){
21243  i = mem3.aiSmall[nBlock-2];
21244  if( i>0 ){
21245  memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
21246  return memsys3Checkout(i, nBlock);
21247  }
21248  }else{
21249  int hash = nBlock % N_HASH;
21250  for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
21251  if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
21252  memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
21253  return memsys3Checkout(i, nBlock);
21254  }
21255  }
21256  }
21257 
21258  /* STEP 2:
21259  ** Try to satisfy the allocation by carving a piece off of the end
21260  ** of the master chunk. This step usually works if step 1 fails.
21261  */
21262  if( mem3.szMaster>=nBlock ){
21263  return memsys3FromMaster(nBlock);
21264  }
21265 
21266 
21267  /* STEP 3:
21268  ** Loop through the entire memory pool. Coalesce adjacent free
21269  ** chunks. Recompute the master chunk as the largest free chunk.
21270  ** Then try again to satisfy the allocation by carving a piece off
21271  ** of the end of the master chunk. This step happens very
21272  ** rarely (we hope!)
21273  */
21274  for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
21275  memsys3OutOfMemory(toFree);
21276  if( mem3.iMaster ){
21277  memsys3Link(mem3.iMaster);
21278  mem3.iMaster = 0;
21279  mem3.szMaster = 0;
21280  }
21281  for(i=0; i<N_HASH; i++){
21282  memsys3Merge(&mem3.aiHash[i]);
21283  }
21284  for(i=0; i<MX_SMALL-1; i++){
21285  memsys3Merge(&mem3.aiSmall[i]);
21286  }
21287  if( mem3.szMaster ){
21288  memsys3Unlink(mem3.iMaster);
21289  if( mem3.szMaster>=nBlock ){
21290  return memsys3FromMaster(nBlock);
21291  }
21292  }
21293  }
21294 
21295  /* If none of the above worked, then we fail. */
21296  return 0;
21297 }
21298 
21299 /*
21300 ** Free an outstanding memory allocation.
21301 **
21302 ** This function assumes that the necessary mutexes, if any, are
21303 ** already held by the caller. Hence "Unsafe".
21304 */
21305 static void memsys3FreeUnsafe(void *pOld){
21306  Mem3Block *p = (Mem3Block*)pOld;
21307  int i;
21308  u32 size, x;
21309  assert( sqlite3_mutex_held(mem3.mutex) );
21310  assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
21311  i = p - mem3.aPool;
21312  assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
21313  size = mem3.aPool[i-1].u.hdr.size4x/4;
21314  assert( i+size<=mem3.nPool+1 );
21315  mem3.aPool[i-1].u.hdr.size4x &= ~1;
21316  mem3.aPool[i+size-1].u.hdr.prevSize = size;
21317  mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
21318  memsys3Link(i);
21319 
21320  /* Try to expand the master using the newly freed chunk */
21321  if( mem3.iMaster ){
21322  while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
21323  size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
21324  mem3.iMaster -= size;
21325  mem3.szMaster += size;
21326  memsys3Unlink(mem3.iMaster);
21327  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21328  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21329  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21330  }
21331  x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
21332  while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
21333  memsys3Unlink(mem3.iMaster+mem3.szMaster);
21334  mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
21335  mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
21336  mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
21337  }
21338  }
21339 }
21340 
21341 /*
21342 ** Return the size of an outstanding allocation, in bytes. The
21343 ** size returned omits the 8-byte header overhead. This only
21344 ** works for chunks that are currently checked out.
21345 */
21346 static int memsys3Size(void *p){
21347  Mem3Block *pBlock;
21348  assert( p!=0 );
21349  pBlock = (Mem3Block*)p;
21350  assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
21351  return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
21352 }
21353 
21354 /*
21355 ** Round up a request size to the next valid allocation size.
21356 */
21357 static int memsys3Roundup(int n){
21358  if( n<=12 ){
21359  return 12;
21360  }else{
21361  return ((n+11)&~7) - 4;
21362  }
21363 }
21364 
21365 /*
21366 ** Allocate nBytes of memory.
21367 */
21368 static void *memsys3Malloc(int nBytes){
21369  sqlite3_int64 *p;
21370  assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
21371  memsys3Enter();
21372  p = memsys3MallocUnsafe(nBytes);
21373  memsys3Leave();
21374  return (void*)p;
21375 }
21376 
21377 /*
21378 ** Free memory.
21379 */
21380 static void memsys3Free(void *pPrior){
21381  assert( pPrior );
21382  memsys3Enter();
21383  memsys3FreeUnsafe(pPrior);
21384  memsys3Leave();
21385 }
21386 
21387 /*
21388 ** Change the size of an existing memory allocation
21389 */
21390 static void *memsys3Realloc(void *pPrior, int nBytes){
21391  int nOld;
21392  void *p;
21393  if( pPrior==0 ){
21394  return sqlite3_malloc(nBytes);
21395  }
21396  if( nBytes<=0 ){
21397  sqlite3_free(pPrior);
21398  return 0;
21399  }
21400  nOld = memsys3Size(pPrior);
21401  if( nBytes<=nOld && nBytes>=nOld-128 ){
21402  return pPrior;
21403  }
21404  memsys3Enter();
21405  p = memsys3MallocUnsafe(nBytes);
21406  if( p ){
21407  if( nOld<nBytes ){
21408  memcpy(p, pPrior, nOld);
21409  }else{
21410  memcpy(p, pPrior, nBytes);
21411  }
21412  memsys3FreeUnsafe(pPrior);
21413  }
21414  memsys3Leave();
21415  return p;
21416 }
21417 
21418 /*
21419 ** Initialize this module.
21420 */
21421 static int memsys3Init(void *NotUsed){
21422  UNUSED_PARAMETER(NotUsed);
21423  if( !sqlite3GlobalConfig.pHeap ){
21424  return SQLITE_ERROR;
21425  }
21426 
21427  /* Store a pointer to the memory block in global structure mem3. */
21428  assert( sizeof(Mem3Block)==8 );
21429  mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
21430  mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
21431 
21432  /* Initialize the master block. */
21433  mem3.szMaster = mem3.nPool;
21434  mem3.mnMaster = mem3.szMaster;
21435  mem3.iMaster = 1;
21436  mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
21437  mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
21438  mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
21439 
21440  return SQLITE_OK;
21441 }
21442 
21443 /*
21444 ** Deinitialize this module.
21445 */
21446 static void memsys3Shutdown(void *NotUsed){
21447  UNUSED_PARAMETER(NotUsed);
21448  mem3.mutex = 0;
21449  return;
21450 }
21451 
21452 
21453 
21454 /*
21455 ** Open the file indicated and write a log of all unfreed memory
21456 ** allocations into that log.
21457 */
21458 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
21459 #ifdef SQLITE_DEBUG
21460  FILE *out;
21461  u32 i, j;
21462  u32 size;
21463  if( zFilename==0 || zFilename[0]==0 ){
21464  out = stdout;
21465  }else{
21466  out = fopen(zFilename, "w");
21467  if( out==0 ){
21468  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
21469  zFilename);
21470  return;
21471  }
21472  }
21473  memsys3Enter();
21474  fprintf(out, "CHUNKS:\n");
21475  for(i=1; i<=mem3.nPool; i+=size/4){
21476  size = mem3.aPool[i-1].u.hdr.size4x;
21477  if( size/4<=1 ){
21478  fprintf(out, "%p size error\n", &mem3.aPool[i]);
21479  assert( 0 );
21480  break;
21481  }
21482  if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
21483  fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
21484  assert( 0 );
21485  break;
21486  }
21487  if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
21488  fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
21489  assert( 0 );
21490  break;
21491  }
21492  if( size&1 ){
21493  fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
21494  }else{
21495  fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
21496  i==mem3.iMaster ? " **master**" : "");
21497  }
21498  }
21499  for(i=0; i<MX_SMALL-1; i++){
21500  if( mem3.aiSmall[i]==0 ) continue;
21501  fprintf(out, "small(%2d):", i);
21502  for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
21503  fprintf(out, " %p(%d)", &mem3.aPool[j],
21504  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21505  }
21506  fprintf(out, "\n");
21507  }
21508  for(i=0; i<N_HASH; i++){
21509  if( mem3.aiHash[i]==0 ) continue;
21510  fprintf(out, "hash(%2d):", i);
21511  for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
21512  fprintf(out, " %p(%d)", &mem3.aPool[j],
21513  (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
21514  }
21515  fprintf(out, "\n");
21516  }
21517  fprintf(out, "master=%d\n", mem3.iMaster);
21518  fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
21519  fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
21520  sqlite3_mutex_leave(mem3.mutex);
21521  if( out==stdout ){
21522  fflush(stdout);
21523  }else{
21524  fclose(out);
21525  }
21526 #else
21527  UNUSED_PARAMETER(zFilename);
21528 #endif
21529 }
21530 
21531 /*
21532 ** This routine is the only routine in this file with external
21533 ** linkage.
21534 **
21535 ** Populate the low-level memory allocation function pointers in
21536 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
21537 ** arguments specify the block of memory to manage.
21538 **
21539 ** This routine is only called by sqlite3_config(), and therefore
21540 ** is not required to be threadsafe (it is not).
21541 */
21542 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
21543  static const sqlite3_mem_methods mempoolMethods = {
21544  memsys3Malloc,
21545  memsys3Free,
21546  memsys3Realloc,
21547  memsys3Size,
21548  memsys3Roundup,
21549  memsys3Init,
21550  memsys3Shutdown,
21551  0
21552  };
21553  return &mempoolMethods;
21554 }
21555 
21556 #endif /* SQLITE_ENABLE_MEMSYS3 */
21557 
21558 /************** End of mem3.c ************************************************/
21559 /************** Begin file mem5.c ********************************************/
21560 /*
21561 ** 2007 October 14
21562 **
21563 ** The author disclaims copyright to this source code. In place of
21564 ** a legal notice, here is a blessing:
21565 **
21566 ** May you do good and not evil.
21567 ** May you find forgiveness for yourself and forgive others.
21568 ** May you share freely, never taking more than you give.
21569 **
21570 *************************************************************************
21571 ** This file contains the C functions that implement a memory
21572 ** allocation subsystem for use by SQLite.
21573 **
21574 ** This version of the memory allocation subsystem omits all
21575 ** use of malloc(). The application gives SQLite a block of memory
21576 ** before calling sqlite3_initialize() from which allocations
21577 ** are made and returned by the xMalloc() and xRealloc()
21578 ** implementations. Once sqlite3_initialize() has been called,
21579 ** the amount of memory available to SQLite is fixed and cannot
21580 ** be changed.
21581 **
21582 ** This version of the memory allocation subsystem is included
21583 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
21584 **
21585 ** This memory allocator uses the following algorithm:
21586 **
21587 ** 1. All memory allocation sizes are rounded up to a power of 2.
21588 **
21589 ** 2. If two adjacent free blocks are the halves of a larger block,
21590 ** then the two blocks are coalesced into the single larger block.
21591 **
21592 ** 3. New memory is allocated from the first available free block.
21593 **
21594 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
21595 ** Concerning Dynamic Storage Allocation". Journal of the Association for
21596 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
21597 **
21598 ** Let n be the size of the largest allocation divided by the minimum
21599 ** allocation size (after rounding all sizes up to a power of 2.) Let M
21600 ** be the maximum amount of memory ever outstanding at one time. Let
21601 ** N be the total amount of memory available for allocation. Robson
21602 ** proved that this memory allocator will never breakdown due to
21603 ** fragmentation as long as the following constraint holds:
21604 **
21605 ** N >= M*(1 + log2(n)/2) - n + 1
21606 **
21607 ** The sqlite3_status() logic tracks the maximum values of n and M so
21608 ** that an application can, at any time, verify this constraint.
21609 */
21610 /* #include "sqliteInt.h" */
21611 
21612 /*
21613 ** This version of the memory allocator is used only when
21614 ** SQLITE_ENABLE_MEMSYS5 is defined.
21615 */
21616 #ifdef SQLITE_ENABLE_MEMSYS5
21617 
21618 /*
21619 ** A minimum allocation is an instance of the following structure.
21620 ** Larger allocations are an array of these structures where the
21621 ** size of the array is a power of 2.
21622 **
21623 ** The size of this object must be a power of two. That fact is
21624 ** verified in memsys5Init().
21625 */
21626 typedef struct Mem5Link Mem5Link;
21627 struct Mem5Link {
21628  int next; /* Index of next free chunk */
21629  int prev; /* Index of previous free chunk */
21630 };
21631 
21632 /*
21633 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
21634 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
21635 ** it is not actually possible to reach this limit.
21636 */
21637 #define LOGMAX 30
21638 
21639 /*
21640 ** Masks used for mem5.aCtrl[] elements.
21641 */
21642 #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
21643 #define CTRL_FREE 0x20 /* True if not checked out */
21644 
21645 /*
21646 ** All of the static variables used by this module are collected
21647 ** into a single structure named "mem5". This is to keep the
21648 ** static variables organized and to reduce namespace pollution
21649 ** when this module is combined with other in the amalgamation.
21650 */
21651 static SQLITE_WSD struct Mem5Global {
21652  /*
21653  ** Memory available for allocation
21654  */
21655  int szAtom; /* Smallest possible allocation in bytes */
21656  int nBlock; /* Number of szAtom sized blocks in zPool */
21657  u8 *zPool; /* Memory available to be allocated */
21658 
21659  /*
21660  ** Mutex to control access to the memory allocation subsystem.
21661  */
21662  sqlite3_mutex *mutex;
21663 
21664 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21665  /*
21666  ** Performance statistics
21667  */
21668  u64 nAlloc; /* Total number of calls to malloc */
21669  u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
21670  u64 totalExcess; /* Total internal fragmentation */
21671  u32 currentOut; /* Current checkout, including internal fragmentation */
21672  u32 currentCount; /* Current number of distinct checkouts */
21673  u32 maxOut; /* Maximum instantaneous currentOut */
21674  u32 maxCount; /* Maximum instantaneous currentCount */
21675  u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
21676 #endif
21677 
21678  /*
21679  ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
21680  ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
21681  ** aiFreelist[2] holds free blocks of size szAtom*4. And so forth.
21682  */
21683  int aiFreelist[LOGMAX+1];
21684 
21685  /*
21686  ** Space for tracking which blocks are checked out and the size
21687  ** of each block. One byte per block.
21688  */
21689  u8 *aCtrl;
21690 
21691 } mem5;
21692 
21693 /*
21694 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
21695 */
21696 #define mem5 GLOBAL(struct Mem5Global, mem5)
21697 
21698 /*
21699 ** Assuming mem5.zPool is divided up into an array of Mem5Link
21700 ** structures, return a pointer to the idx-th such link.
21701 */
21702 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
21703 
21704 /*
21705 ** Unlink the chunk at mem5.aPool[i] from list it is currently
21706 ** on. It should be found on mem5.aiFreelist[iLogsize].
21707 */
21708 static void memsys5Unlink(int i, int iLogsize){
21709  int next, prev;
21710  assert( i>=0 && i<mem5.nBlock );
21711  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21712  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21713 
21714  next = MEM5LINK(i)->next;
21715  prev = MEM5LINK(i)->prev;
21716  if( prev<0 ){
21717  mem5.aiFreelist[iLogsize] = next;
21718  }else{
21719  MEM5LINK(prev)->next = next;
21720  }
21721  if( next>=0 ){
21722  MEM5LINK(next)->prev = prev;
21723  }
21724 }
21725 
21726 /*
21727 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
21728 ** free list.
21729 */
21730 static void memsys5Link(int i, int iLogsize){
21731  int x;
21732  assert( sqlite3_mutex_held(mem5.mutex) );
21733  assert( i>=0 && i<mem5.nBlock );
21734  assert( iLogsize>=0 && iLogsize<=LOGMAX );
21735  assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
21736 
21737  x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
21738  MEM5LINK(i)->prev = -1;
21739  if( x>=0 ){
21740  assert( x<mem5.nBlock );
21741  MEM5LINK(x)->prev = i;
21742  }
21743  mem5.aiFreelist[iLogsize] = i;
21744 }
21745 
21746 /*
21747 ** Obtain or release the mutex needed to access global data structures.
21748 */
21749 static void memsys5Enter(void){
21750  sqlite3_mutex_enter(mem5.mutex);
21751 }
21752 static void memsys5Leave(void){
21753  sqlite3_mutex_leave(mem5.mutex);
21754 }
21755 
21756 /*
21757 ** Return the size of an outstanding allocation, in bytes.
21758 ** This only works for chunks that are currently checked out.
21759 */
21760 static int memsys5Size(void *p){
21761  int iSize, i;
21762  assert( p!=0 );
21763  i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
21764  assert( i>=0 && i<mem5.nBlock );
21765  iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
21766  return iSize;
21767 }
21768 
21769 /*
21770 ** Return a block of memory of at least nBytes in size.
21771 ** Return NULL if unable. Return NULL if nBytes==0.
21772 **
21773 ** The caller guarantees that nByte is positive.
21774 **
21775 ** The caller has obtained a mutex prior to invoking this
21776 ** routine so there is never any chance that two or more
21777 ** threads can be in this routine at the same time.
21778 */
21779 static void *memsys5MallocUnsafe(int nByte){
21780  int i; /* Index of a mem5.aPool[] slot */
21781  int iBin; /* Index into mem5.aiFreelist[] */
21782  int iFullSz; /* Size of allocation rounded up to power of 2 */
21783  int iLogsize; /* Log2 of iFullSz/POW2_MIN */
21784 
21785  /* nByte must be a positive */
21786  assert( nByte>0 );
21787 
21788  /* No more than 1GiB per allocation */
21789  if( nByte > 0x40000000 ) return 0;
21790 
21791 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21792  /* Keep track of the maximum allocation request. Even unfulfilled
21793  ** requests are counted */
21794  if( (u32)nByte>mem5.maxRequest ){
21795  mem5.maxRequest = nByte;
21796  }
21797 #endif
21798 
21799 
21800  /* Round nByte up to the next valid power of two */
21801  for(iFullSz=mem5.szAtom,iLogsize=0; iFullSz<nByte; iFullSz*=2,iLogsize++){}
21802 
21803  /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
21804  ** block. If not, then split a block of the next larger power of
21805  ** two in order to create a new free block of size iLogsize.
21806  */
21807  for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
21808  if( iBin>LOGMAX ){
21809  testcase( sqlite3GlobalConfig.xLog!=0 );
21810  sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
21811  return 0;
21812  }
21813  i = mem5.aiFreelist[iBin];
21814  memsys5Unlink(i, iBin);
21815  while( iBin>iLogsize ){
21816  int newSize;
21817 
21818  iBin--;
21819  newSize = 1 << iBin;
21820  mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
21821  memsys5Link(i+newSize, iBin);
21822  }
21823  mem5.aCtrl[i] = iLogsize;
21824 
21825 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21826  /* Update allocator performance statistics. */
21827  mem5.nAlloc++;
21828  mem5.totalAlloc += iFullSz;
21829  mem5.totalExcess += iFullSz - nByte;
21830  mem5.currentCount++;
21831  mem5.currentOut += iFullSz;
21832  if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
21833  if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
21834 #endif
21835 
21836 #ifdef SQLITE_DEBUG
21837  /* Make sure the allocated memory does not assume that it is set to zero
21838  ** or retains a value from a previous allocation */
21839  memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
21840 #endif
21841 
21842  /* Return a pointer to the allocated memory. */
21843  return (void*)&mem5.zPool[i*mem5.szAtom];
21844 }
21845 
21846 /*
21847 ** Free an outstanding memory allocation.
21848 */
21849 static void memsys5FreeUnsafe(void *pOld){
21850  u32 size, iLogsize;
21851  int iBlock;
21852 
21853  /* Set iBlock to the index of the block pointed to by pOld in
21854  ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
21855  */
21856  iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
21857 
21858  /* Check that the pointer pOld points to a valid, non-free block. */
21859  assert( iBlock>=0 && iBlock<mem5.nBlock );
21860  assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
21861  assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
21862 
21863  iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
21864  size = 1<<iLogsize;
21865  assert( iBlock+size-1<(u32)mem5.nBlock );
21866 
21867  mem5.aCtrl[iBlock] |= CTRL_FREE;
21868  mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
21869 
21870 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
21871  assert( mem5.currentCount>0 );
21872  assert( mem5.currentOut>=(size*mem5.szAtom) );
21873  mem5.currentCount--;
21874  mem5.currentOut -= size*mem5.szAtom;
21875  assert( mem5.currentOut>0 || mem5.currentCount==0 );
21876  assert( mem5.currentCount>0 || mem5.currentOut==0 );
21877 #endif
21878 
21879  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
21880  while( ALWAYS(iLogsize<LOGMAX) ){
21881  int iBuddy;
21882  if( (iBlock>>iLogsize) & 1 ){
21883  iBuddy = iBlock - size;
21884  assert( iBuddy>=0 );
21885  }else{
21886  iBuddy = iBlock + size;
21887  if( iBuddy>=mem5.nBlock ) break;
21888  }
21889  if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
21890  memsys5Unlink(iBuddy, iLogsize);
21891  iLogsize++;
21892  if( iBuddy<iBlock ){
21893  mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
21894  mem5.aCtrl[iBlock] = 0;
21895  iBlock = iBuddy;
21896  }else{
21897  mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
21898  mem5.aCtrl[iBuddy] = 0;
21899  }
21900  size *= 2;
21901  }
21902 
21903 #ifdef SQLITE_DEBUG
21904  /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
21905  ** not used after being freed */
21906  memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
21907 #endif
21908 
21909  memsys5Link(iBlock, iLogsize);
21910 }
21911 
21912 /*
21913 ** Allocate nBytes of memory.
21914 */
21915 static void *memsys5Malloc(int nBytes){
21916  sqlite3_int64 *p = 0;
21917  if( nBytes>0 ){
21918  memsys5Enter();
21919  p = memsys5MallocUnsafe(nBytes);
21920  memsys5Leave();
21921  }
21922  return (void*)p;
21923 }
21924 
21925 /*
21926 ** Free memory.
21927 **
21928 ** The outer layer memory allocator prevents this routine from
21929 ** being called with pPrior==0.
21930 */
21931 static void memsys5Free(void *pPrior){
21932  assert( pPrior!=0 );
21933  memsys5Enter();
21934  memsys5FreeUnsafe(pPrior);
21935  memsys5Leave();
21936 }
21937 
21938 /*
21939 ** Change the size of an existing memory allocation.
21940 **
21941 ** The outer layer memory allocator prevents this routine from
21942 ** being called with pPrior==0.
21943 **
21944 ** nBytes is always a value obtained from a prior call to
21945 ** memsys5Round(). Hence nBytes is always a non-negative power
21946 ** of two. If nBytes==0 that means that an oversize allocation
21947 ** (an allocation larger than 0x40000000) was requested and this
21948 ** routine should return 0 without freeing pPrior.
21949 */
21950 static void *memsys5Realloc(void *pPrior, int nBytes){
21951  int nOld;
21952  void *p;
21953  assert( pPrior!=0 );
21954  assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
21955  assert( nBytes>=0 );
21956  if( nBytes==0 ){
21957  return 0;
21958  }
21959  nOld = memsys5Size(pPrior);
21960  if( nBytes<=nOld ){
21961  return pPrior;
21962  }
21963  p = memsys5Malloc(nBytes);
21964  if( p ){
21965  memcpy(p, pPrior, nOld);
21966  memsys5Free(pPrior);
21967  }
21968  return p;
21969 }
21970 
21971 /*
21972 ** Round up a request size to the next valid allocation size. If
21973 ** the allocation is too large to be handled by this allocation system,
21974 ** return 0.
21975 **
21976 ** All allocations must be a power of two and must be expressed by a
21977 ** 32-bit signed integer. Hence the largest allocation is 0x40000000
21978 ** or 1073741824 bytes.
21979 */
21980 static int memsys5Roundup(int n){
21981  int iFullSz;
21982  if( n > 0x40000000 ) return 0;
21983  for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
21984  return iFullSz;
21985 }
21986 
21987 /*
21988 ** Return the ceiling of the logarithm base 2 of iValue.
21989 **
21990 ** Examples: memsys5Log(1) -> 0
21991 ** memsys5Log(2) -> 1
21992 ** memsys5Log(4) -> 2
21993 ** memsys5Log(5) -> 3
21994 ** memsys5Log(8) -> 3
21995 ** memsys5Log(9) -> 4
21996 */
21997 static int memsys5Log(int iValue){
21998  int iLog;
21999  for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
22000  return iLog;
22001 }
22002 
22003 /*
22004 ** Initialize the memory allocator.
22005 **
22006 ** This routine is not threadsafe. The caller must be holding a mutex
22007 ** to prevent multiple threads from entering at the same time.
22008 */
22009 static int memsys5Init(void *NotUsed){
22010  int ii; /* Loop counter */
22011  int nByte; /* Number of bytes of memory available to this allocator */
22012  u8 *zByte; /* Memory usable by this allocator */
22013  int nMinLog; /* Log base 2 of minimum allocation size in bytes */
22014  int iOffset; /* An offset into mem5.aCtrl[] */
22015 
22016  UNUSED_PARAMETER(NotUsed);
22017 
22018  /* For the purposes of this routine, disable the mutex */
22019  mem5.mutex = 0;
22020 
22021  /* The size of a Mem5Link object must be a power of two. Verify that
22022  ** this is case.
22023  */
22024  assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
22025 
22026  nByte = sqlite3GlobalConfig.nHeap;
22027  zByte = (u8*)sqlite3GlobalConfig.pHeap;
22028  assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
22029 
22030  /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
22031  nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
22032  mem5.szAtom = (1<<nMinLog);
22033  while( (int)sizeof(Mem5Link)>mem5.szAtom ){
22034  mem5.szAtom = mem5.szAtom << 1;
22035  }
22036 
22037  mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
22038  mem5.zPool = zByte;
22039  mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
22040 
22041  for(ii=0; ii<=LOGMAX; ii++){
22042  mem5.aiFreelist[ii] = -1;
22043  }
22044 
22045  iOffset = 0;
22046  for(ii=LOGMAX; ii>=0; ii--){
22047  int nAlloc = (1<<ii);
22048  if( (iOffset+nAlloc)<=mem5.nBlock ){
22049  mem5.aCtrl[iOffset] = ii | CTRL_FREE;
22050  memsys5Link(iOffset, ii);
22051  iOffset += nAlloc;
22052  }
22053  assert((iOffset+nAlloc)>mem5.nBlock);
22054  }
22055 
22056  /* If a mutex is required for normal operation, allocate one */
22057  if( sqlite3GlobalConfig.bMemstat==0 ){
22059  }
22060 
22061  return SQLITE_OK;
22062 }
22063 
22064 /*
22065 ** Deinitialize this module.
22066 */
22067 static void memsys5Shutdown(void *NotUsed){
22068  UNUSED_PARAMETER(NotUsed);
22069  mem5.mutex = 0;
22070  return;
22071 }
22072 
22073 #ifdef SQLITE_TEST
22074 /*
22075 ** Open the file indicated and write a log of all unfreed memory
22076 ** allocations into that log.
22077 */
22078 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
22079  FILE *out;
22080  int i, j, n;
22081  int nMinLog;
22082 
22083  if( zFilename==0 || zFilename[0]==0 ){
22084  out = stdout;
22085  }else{
22086  out = fopen(zFilename, "w");
22087  if( out==0 ){
22088  fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
22089  zFilename);
22090  return;
22091  }
22092  }
22093  memsys5Enter();
22094  nMinLog = memsys5Log(mem5.szAtom);
22095  for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
22096  for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
22097  fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
22098  }
22099  fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
22100  fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
22101  fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
22102  fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
22103  fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
22104  fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
22105  fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
22106  fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
22107  memsys5Leave();
22108  if( out==stdout ){
22109  fflush(stdout);
22110  }else{
22111  fclose(out);
22112  }
22113 }
22114 #endif
22115 
22116 /*
22117 ** This routine is the only routine in this file with external
22118 ** linkage. It returns a pointer to a static sqlite3_mem_methods
22119 ** struct populated with the memsys5 methods.
22120 */
22121 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
22122  static const sqlite3_mem_methods memsys5Methods = {
22123  memsys5Malloc,
22124  memsys5Free,
22125  memsys5Realloc,
22126  memsys5Size,
22127  memsys5Roundup,
22128  memsys5Init,
22129  memsys5Shutdown,
22130  0
22131  };
22132  return &memsys5Methods;
22133 }
22134 
22135 #endif /* SQLITE_ENABLE_MEMSYS5 */
22136 
22137 /************** End of mem5.c ************************************************/
22138 /************** Begin file mutex.c *******************************************/
22139 /*
22140 ** 2007 August 14
22141 **
22142 ** The author disclaims copyright to this source code. In place of
22143 ** a legal notice, here is a blessing:
22144 **
22145 ** May you do good and not evil.
22146 ** May you find forgiveness for yourself and forgive others.
22147 ** May you share freely, never taking more than you give.
22148 **
22149 *************************************************************************
22150 ** This file contains the C functions that implement mutexes.
22151 **
22152 ** This file contains code that is common across all mutex implementations.
22153 */
22154 /* #include "sqliteInt.h" */
22155 
22156 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
22157 /*
22158 ** For debugging purposes, record when the mutex subsystem is initialized
22159 ** and uninitialized so that we can assert() if there is an attempt to
22160 ** allocate a mutex while the system is uninitialized.
22161 */
22162 static SQLITE_WSD int mutexIsInit = 0;
22163 #endif /* SQLITE_DEBUG && !defined(SQLITE_MUTEX_OMIT) */
22164 
22165 
22166 #ifndef SQLITE_MUTEX_OMIT
22167 /*
22168 ** Initialize the mutex system.
22169 */
22171  int rc = SQLITE_OK;
22172  if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
22173  /* If the xMutexAlloc method has not been set, then the user did not
22174  ** install a mutex implementation via sqlite3_config() prior to
22175  ** sqlite3_initialize() being called. This block copies pointers to
22176  ** the default implementation into the sqlite3GlobalConfig structure.
22177  */
22178  sqlite3_mutex_methods const *pFrom;
22180 
22181  if( sqlite3GlobalConfig.bCoreMutex ){
22182  pFrom = sqlite3DefaultMutex();
22183  }else{
22184  pFrom = sqlite3NoopMutex();
22185  }
22186  pTo->xMutexInit = pFrom->xMutexInit;
22187  pTo->xMutexEnd = pFrom->xMutexEnd;
22188  pTo->xMutexFree = pFrom->xMutexFree;
22189  pTo->xMutexEnter = pFrom->xMutexEnter;
22190  pTo->xMutexTry = pFrom->xMutexTry;
22191  pTo->xMutexLeave = pFrom->xMutexLeave;
22192  pTo->xMutexHeld = pFrom->xMutexHeld;
22193  pTo->xMutexNotheld = pFrom->xMutexNotheld;
22195  pTo->xMutexAlloc = pFrom->xMutexAlloc;
22196  }
22197  assert( sqlite3GlobalConfig.mutex.xMutexInit );
22198  rc = sqlite3GlobalConfig.mutex.xMutexInit();
22199 
22200 #ifdef SQLITE_DEBUG
22201  GLOBAL(int, mutexIsInit) = 1;
22202 #endif
22203 
22204  return rc;
22205 }
22206 
22207 /*
22208 ** Shutdown the mutex system. This call frees resources allocated by
22209 ** sqlite3MutexInit().
22210 */
22212  int rc = SQLITE_OK;
22213  if( sqlite3GlobalConfig.mutex.xMutexEnd ){
22214  rc = sqlite3GlobalConfig.mutex.xMutexEnd();
22215  }
22216 
22217 #ifdef SQLITE_DEBUG
22218  GLOBAL(int, mutexIsInit) = 0;
22219 #endif
22220 
22221  return rc;
22222 }
22223 
22224 /*
22225 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
22226 */
22228 #ifndef SQLITE_OMIT_AUTOINIT
22229  if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
22230  if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
22231 #endif
22232  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22233  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22234 }
22235 
22237  if( !sqlite3GlobalConfig.bCoreMutex ){
22238  return 0;
22239  }
22240  assert( GLOBAL(int, mutexIsInit) );
22241  assert( sqlite3GlobalConfig.mutex.xMutexAlloc );
22242  return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
22243 }
22244 
22245 /*
22246 ** Free a dynamic mutex.
22247 */
22249  if( p ){
22250  assert( sqlite3GlobalConfig.mutex.xMutexFree );
22251  sqlite3GlobalConfig.mutex.xMutexFree(p);
22252  }
22253 }
22254 
22255 /*
22256 ** Obtain the mutex p. If some other thread already has the mutex, block
22257 ** until it can be obtained.
22258 */
22260  if( p ){
22261  assert( sqlite3GlobalConfig.mutex.xMutexEnter );
22262  sqlite3GlobalConfig.mutex.xMutexEnter(p);
22263  }
22264 }
22265 
22266 /*
22267 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
22268 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
22269 */
22271  int rc = SQLITE_OK;
22272  if( p ){
22273  assert( sqlite3GlobalConfig.mutex.xMutexTry );
22274  return sqlite3GlobalConfig.mutex.xMutexTry(p);
22275  }
22276  return rc;
22277 }
22278 
22279 /*
22280 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
22281 ** entered by the same thread. The behavior is undefined if the mutex
22282 ** is not currently entered. If a NULL pointer is passed as an argument
22283 ** this function is a no-op.
22284 */
22286  if( p ){
22287  assert( sqlite3GlobalConfig.mutex.xMutexLeave );
22288  sqlite3GlobalConfig.mutex.xMutexLeave(p);
22289  }
22290 }
22291 
22292 #ifndef NDEBUG
22293 /*
22294 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22295 ** intended for use inside assert() statements.
22296 */
22298  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexHeld );
22299  return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
22300 }
22302  assert( p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld );
22303  return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
22304 }
22305 #endif
22306 
22307 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22308 
22309 /************** End of mutex.c ***********************************************/
22310 /************** Begin file mutex_noop.c **************************************/
22311 /*
22312 ** 2008 October 07
22313 **
22314 ** The author disclaims copyright to this source code. In place of
22315 ** a legal notice, here is a blessing:
22316 **
22317 ** May you do good and not evil.
22318 ** May you find forgiveness for yourself and forgive others.
22319 ** May you share freely, never taking more than you give.
22320 **
22321 *************************************************************************
22322 ** This file contains the C functions that implement mutexes.
22323 **
22324 ** This implementation in this file does not provide any mutual
22325 ** exclusion and is thus suitable for use only in applications
22326 ** that use SQLite in a single thread. The routines defined
22327 ** here are place-holders. Applications can substitute working
22328 ** mutex routines at start-time using the
22329 **
22330 ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
22331 **
22332 ** interface.
22333 **
22334 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
22335 ** that does error checking on mutexes to make sure they are being
22336 ** called correctly.
22337 */
22338 /* #include "sqliteInt.h" */
22339 
22340 #ifndef SQLITE_MUTEX_OMIT
22341 
22342 #ifndef SQLITE_DEBUG
22343 /*
22344 ** Stub routines for all mutex methods.
22345 **
22346 ** This routines provide no mutual exclusion or error checking.
22347 */
22348 static int noopMutexInit(void){ return SQLITE_OK; }
22349 static int noopMutexEnd(void){ return SQLITE_OK; }
22351  UNUSED_PARAMETER(id);
22352  return (sqlite3_mutex*)8;
22353 }
22354 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22355 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22357  UNUSED_PARAMETER(p);
22358  return SQLITE_OK;
22359 }
22360 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
22361 
22363  static const sqlite3_mutex_methods sMutex = {
22364  noopMutexInit,
22365  noopMutexEnd,
22367  noopMutexFree,
22369  noopMutexTry,
22371 
22372  0,
22373  0,
22374  };
22375 
22376  return &sMutex;
22377 }
22378 #endif /* !SQLITE_DEBUG */
22379 
22380 #ifdef SQLITE_DEBUG
22381 /*
22382 ** In this implementation, error checking is provided for testing
22383 ** and debugging purposes. The mutexes still do not provide any
22384 ** mutual exclusion.
22385 */
22386 
22387 /*
22388 ** The mutex object
22389 */
22390 typedef struct sqlite3_debug_mutex {
22391  int id; /* The mutex type */
22392  int cnt; /* Number of entries without a matching leave */
22393 } sqlite3_debug_mutex;
22394 
22395 /*
22396 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22397 ** intended for use inside assert() statements.
22398 */
22399 static int debugMutexHeld(sqlite3_mutex *pX){
22400  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22401  return p==0 || p->cnt>0;
22402 }
22403 static int debugMutexNotheld(sqlite3_mutex *pX){
22404  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22405  return p==0 || p->cnt==0;
22406 }
22407 
22408 /*
22409 ** Initialize and deinitialize the mutex subsystem.
22410 */
22411 static int debugMutexInit(void){ return SQLITE_OK; }
22412 static int debugMutexEnd(void){ return SQLITE_OK; }
22413 
22414 /*
22415 ** The sqlite3_mutex_alloc() routine allocates a new
22416 ** mutex and returns a pointer to it. If it returns NULL
22417 ** that means that a mutex could not be allocated.
22418 */
22419 static sqlite3_mutex *debugMutexAlloc(int id){
22420  static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_VFS3 - 1];
22421  sqlite3_debug_mutex *pNew = 0;
22422  switch( id ){
22423  case SQLITE_MUTEX_FAST:
22424  case SQLITE_MUTEX_RECURSIVE: {
22425  pNew = sqlite3Malloc(sizeof(*pNew));
22426  if( pNew ){
22427  pNew->id = id;
22428  pNew->cnt = 0;
22429  }
22430  break;
22431  }
22432  default: {
22433 #ifdef SQLITE_ENABLE_API_ARMOR
22434  if( id-2<0 || id-2>=ArraySize(aStatic) ){
22436  return 0;
22437  }
22438 #endif
22439  pNew = &aStatic[id-2];
22440  pNew->id = id;
22441  break;
22442  }
22443  }
22444  return (sqlite3_mutex*)pNew;
22445 }
22446 
22447 /*
22448 ** This routine deallocates a previously allocated mutex.
22449 */
22450 static void debugMutexFree(sqlite3_mutex *pX){
22451  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22452  assert( p->cnt==0 );
22453  if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
22454  sqlite3_free(p);
22455  }else{
22456 #ifdef SQLITE_ENABLE_API_ARMOR
22458 #endif
22459  }
22460 }
22461 
22462 /*
22463 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22464 ** to enter a mutex. If another thread is already within the mutex,
22465 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22466 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22467 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22468 ** be entered multiple times by the same thread. In such cases the,
22469 ** mutex must be exited an equal number of times before another thread
22470 ** can enter. If the same thread tries to enter any other kind of mutex
22471 ** more than once, the behavior is undefined.
22472 */
22473 static void debugMutexEnter(sqlite3_mutex *pX){
22474  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22475  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22476  p->cnt++;
22477 }
22478 static int debugMutexTry(sqlite3_mutex *pX){
22479  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22480  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22481  p->cnt++;
22482  return SQLITE_OK;
22483 }
22484 
22485 /*
22486 ** The sqlite3_mutex_leave() routine exits a mutex that was
22487 ** previously entered by the same thread. The behavior
22488 ** is undefined if the mutex is not currently entered or
22489 ** is not currently allocated. SQLite will never do either.
22490 */
22491 static void debugMutexLeave(sqlite3_mutex *pX){
22492  sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
22493  assert( debugMutexHeld(pX) );
22494  p->cnt--;
22495  assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
22496 }
22497 
22499  static const sqlite3_mutex_methods sMutex = {
22500  debugMutexInit,
22501  debugMutexEnd,
22502  debugMutexAlloc,
22503  debugMutexFree,
22504  debugMutexEnter,
22505  debugMutexTry,
22506  debugMutexLeave,
22507 
22508  debugMutexHeld,
22509  debugMutexNotheld
22510  };
22511 
22512  return &sMutex;
22513 }
22514 #endif /* SQLITE_DEBUG */
22515 
22516 /*
22517 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
22518 ** is used regardless of the run-time threadsafety setting.
22519 */
22520 #ifdef SQLITE_MUTEX_NOOP
22522  return sqlite3NoopMutex();
22523 }
22524 #endif /* defined(SQLITE_MUTEX_NOOP) */
22525 #endif /* !defined(SQLITE_MUTEX_OMIT) */
22526 
22527 /************** End of mutex_noop.c ******************************************/
22528 /************** Begin file mutex_unix.c **************************************/
22529 /*
22530 ** 2007 August 28
22531 **
22532 ** The author disclaims copyright to this source code. In place of
22533 ** a legal notice, here is a blessing:
22534 **
22535 ** May you do good and not evil.
22536 ** May you find forgiveness for yourself and forgive others.
22537 ** May you share freely, never taking more than you give.
22538 **
22539 *************************************************************************
22540 ** This file contains the C functions that implement mutexes for pthreads
22541 */
22542 /* #include "sqliteInt.h" */
22543 
22544 /*
22545 ** The code in this file is only used if we are compiling threadsafe
22546 ** under unix with pthreads.
22547 **
22548 ** Note that this implementation requires a version of pthreads that
22549 ** supports recursive mutexes.
22550 */
22551 #ifdef SQLITE_MUTEX_PTHREADS
22552 
22553 #include <pthread.h>
22554 
22555 /*
22556 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
22557 ** are necessary under two condidtions: (1) Debug builds and (2) using
22558 ** home-grown mutexes. Encapsulate these conditions into a single #define.
22559 */
22560 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
22561 # define SQLITE_MUTEX_NREF 1
22562 #else
22563 # define SQLITE_MUTEX_NREF 0
22564 #endif
22565 
22566 /*
22567 ** Each recursive mutex is an instance of the following structure.
22568 */
22570  pthread_mutex_t mutex; /* Mutex controlling the lock */
22571 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22572  int id; /* Mutex type */
22573 #endif
22574 #if SQLITE_MUTEX_NREF
22575  volatile int nRef; /* Number of entrances */
22576  volatile pthread_t owner; /* Thread that is within this mutex */
22577  int trace; /* True to trace changes */
22578 #endif
22579 };
22580 #if SQLITE_MUTEX_NREF
22581 #define SQLITE3_MUTEX_INITIALIZER {PTHREAD_MUTEX_INITIALIZER,0,0,(pthread_t)0,0}
22582 #elif defined(SQLITE_ENABLE_API_ARMOR)
22583 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0 }
22584 #else
22585 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
22586 #endif
22587 
22588 /*
22589 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
22590 ** intended for use only inside assert() statements. On some platforms,
22591 ** there might be race conditions that can cause these routines to
22592 ** deliver incorrect results. In particular, if pthread_equal() is
22593 ** not an atomic operation, then these routines might delivery
22594 ** incorrect results. On most platforms, pthread_equal() is a
22595 ** comparison of two integers and is therefore atomic. But we are
22596 ** told that HPUX is not such a platform. If so, then these routines
22597 ** will not always work correctly on HPUX.
22598 **
22599 ** On those platforms where pthread_equal() is not atomic, SQLite
22600 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
22601 ** make sure no assert() statements are evaluated and hence these
22602 ** routines are never called.
22603 */
22604 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
22605 static int pthreadMutexHeld(sqlite3_mutex *p){
22606  return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
22607 }
22608 static int pthreadMutexNotheld(sqlite3_mutex *p){
22609  return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
22610 }
22611 #endif
22612 
22613 /*
22614 ** Try to provide a memory barrier operation, needed for initialization
22615 ** and also for the implementation of xShmBarrier in the VFS in cases
22616 ** where SQLite is compiled without mutexes.
22617 */
22619 #if defined(SQLITE_MEMORY_BARRIER)
22620  SQLITE_MEMORY_BARRIER;
22621 #elif defined(__GNUC__) && GCC_VERSION>=4001000
22622  __sync_synchronize();
22623 #endif
22624 }
22625 
22626 /*
22627 ** Initialize and deinitialize the mutex subsystem.
22628 */
22629 static int pthreadMutexInit(void){ return SQLITE_OK; }
22630 static int pthreadMutexEnd(void){ return SQLITE_OK; }
22631 
22632 /*
22633 ** The sqlite3_mutex_alloc() routine allocates a new
22634 ** mutex and returns a pointer to it. If it returns NULL
22635 ** that means that a mutex could not be allocated. SQLite
22636 ** will unwind its stack and return an error. The argument
22637 ** to sqlite3_mutex_alloc() is one of these integer constants:
22638 **
22639 ** <ul>
22640 ** <li> SQLITE_MUTEX_FAST
22641 ** <li> SQLITE_MUTEX_RECURSIVE
22642 ** <li> SQLITE_MUTEX_STATIC_MASTER
22643 ** <li> SQLITE_MUTEX_STATIC_MEM
22644 ** <li> SQLITE_MUTEX_STATIC_OPEN
22645 ** <li> SQLITE_MUTEX_STATIC_PRNG
22646 ** <li> SQLITE_MUTEX_STATIC_LRU
22647 ** <li> SQLITE_MUTEX_STATIC_PMEM
22648 ** <li> SQLITE_MUTEX_STATIC_APP1
22649 ** <li> SQLITE_MUTEX_STATIC_APP2
22650 ** <li> SQLITE_MUTEX_STATIC_APP3
22651 ** <li> SQLITE_MUTEX_STATIC_VFS1
22652 ** <li> SQLITE_MUTEX_STATIC_VFS2
22653 ** <li> SQLITE_MUTEX_STATIC_VFS3
22654 ** </ul>
22655 **
22656 ** The first two constants cause sqlite3_mutex_alloc() to create
22657 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
22658 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
22659 ** The mutex implementation does not need to make a distinction
22660 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
22661 ** not want to. But SQLite will only request a recursive mutex in
22662 ** cases where it really needs one. If a faster non-recursive mutex
22663 ** implementation is available on the host platform, the mutex subsystem
22664 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
22665 **
22666 ** The other allowed parameters to sqlite3_mutex_alloc() each return
22667 ** a pointer to a static preexisting mutex. Six static mutexes are
22668 ** used by the current version of SQLite. Future versions of SQLite
22669 ** may add additional static mutexes. Static mutexes are for internal
22670 ** use by SQLite only. Applications that use SQLite mutexes should
22671 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
22672 ** SQLITE_MUTEX_RECURSIVE.
22673 **
22674 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
22675 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
22676 ** returns a different mutex on every call. But for the static
22677 ** mutex types, the same mutex is returned on every call that has
22678 ** the same type number.
22679 */
22681  static sqlite3_mutex staticMutexes[] = {
22693  SQLITE3_MUTEX_INITIALIZER
22694  };
22695  sqlite3_mutex *p;
22696  switch( iType ){
22697  case SQLITE_MUTEX_RECURSIVE: {
22698  p = sqlite3MallocZero( sizeof(*p) );
22699  if( p ){
22700 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22701  /* If recursive mutexes are not available, we will have to
22702  ** build our own. See below. */
22703  pthread_mutex_init(&p->mutex, 0);
22704 #else
22705  /* Use a recursive mutex if it is available */
22706  pthread_mutexattr_t recursiveAttr;
22707  pthread_mutexattr_init(&recursiveAttr);
22708  pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
22709  pthread_mutex_init(&p->mutex, &recursiveAttr);
22710  pthread_mutexattr_destroy(&recursiveAttr);
22711 #endif
22712  }
22713  break;
22714  }
22715  case SQLITE_MUTEX_FAST: {
22716  p = sqlite3MallocZero( sizeof(*p) );
22717  if( p ){
22718  pthread_mutex_init(&p->mutex, 0);
22719  }
22720  break;
22721  }
22722  default: {
22723 #ifdef SQLITE_ENABLE_API_ARMOR
22724  if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
22726  return 0;
22727  }
22728 #endif
22729  p = &staticMutexes[iType-2];
22730  break;
22731  }
22732  }
22733 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
22734  if( p ) p->id = iType;
22735 #endif
22736  return p;
22737 }
22738 
22739 
22740 /*
22741 ** This routine deallocates a previously
22742 ** allocated mutex. SQLite is careful to deallocate every
22743 ** mutex that it allocates.
22744 */
22746  assert( p->nRef==0 );
22747 #if SQLITE_ENABLE_API_ARMOR
22748  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
22749 #endif
22750  {
22751  pthread_mutex_destroy(&p->mutex);
22752  sqlite3_free(p);
22753  }
22754 #ifdef SQLITE_ENABLE_API_ARMOR
22755  else{
22757  }
22758 #endif
22759 }
22760 
22761 /*
22762 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
22763 ** to enter a mutex. If another thread is already within the mutex,
22764 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
22765 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
22766 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
22767 ** be entered multiple times by the same thread. In such cases the,
22768 ** mutex must be exited an equal number of times before another thread
22769 ** can enter. If the same thread tries to enter any other kind of mutex
22770 ** more than once, the behavior is undefined.
22771 */
22773  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
22774 
22775 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22776  /* If recursive mutexes are not available, then we have to grow
22777  ** our own. This implementation assumes that pthread_equal()
22778  ** is atomic - that it cannot be deceived into thinking self
22779  ** and p->owner are equal if p->owner changes between two values
22780  ** that are not equal to self while the comparison is taking place.
22781  ** This implementation also assumes a coherent cache - that
22782  ** separate processes cannot read different values from the same
22783  ** address at the same time. If either of these two conditions
22784  ** are not met, then the mutexes will fail and problems will result.
22785  */
22786  {
22787  pthread_t self = pthread_self();
22788  if( p->nRef>0 && pthread_equal(p->owner, self) ){
22789  p->nRef++;
22790  }else{
22791  pthread_mutex_lock(&p->mutex);
22792  assert( p->nRef==0 );
22793  p->owner = self;
22794  p->nRef = 1;
22795  }
22796  }
22797 #else
22798  /* Use the built-in recursive mutexes if they are available.
22799  */
22800  pthread_mutex_lock(&p->mutex);
22801 #if SQLITE_MUTEX_NREF
22802  assert( p->nRef>0 || p->owner==0 );
22803  p->owner = pthread_self();
22804  p->nRef++;
22805 #endif
22806 #endif
22807 
22808 #ifdef SQLITE_DEBUG
22809  if( p->trace ){
22810  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
22811  }
22812 #endif
22813 }
22815  int rc;
22816  assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
22817 
22818 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22819  /* If recursive mutexes are not available, then we have to grow
22820  ** our own. This implementation assumes that pthread_equal()
22821  ** is atomic - that it cannot be deceived into thinking self
22822  ** and p->owner are equal if p->owner changes between two values
22823  ** that are not equal to self while the comparison is taking place.
22824  ** This implementation also assumes a coherent cache - that
22825  ** separate processes cannot read different values from the same
22826  ** address at the same time. If either of these two conditions
22827  ** are not met, then the mutexes will fail and problems will result.
22828  */
22829  {
22830  pthread_t self = pthread_self();
22831  if( p->nRef>0 && pthread_equal(p->owner, self) ){
22832  p->nRef++;
22833  rc = SQLITE_OK;
22834  }else if( pthread_mutex_trylock(&p->mutex)==0 ){
22835  assert( p->nRef==0 );
22836  p->owner = self;
22837  p->nRef = 1;
22838  rc = SQLITE_OK;
22839  }else{
22840  rc = SQLITE_BUSY;
22841  }
22842  }
22843 #else
22844  /* Use the built-in recursive mutexes if they are available.
22845  */
22846  if( pthread_mutex_trylock(&p->mutex)==0 ){
22847 #if SQLITE_MUTEX_NREF
22848  p->owner = pthread_self();
22849  p->nRef++;
22850 #endif
22851  rc = SQLITE_OK;
22852  }else{
22853  rc = SQLITE_BUSY;
22854  }
22855 #endif
22856 
22857 #ifdef SQLITE_DEBUG
22858  if( rc==SQLITE_OK && p->trace ){
22859  printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
22860  }
22861 #endif
22862  return rc;
22863 }
22864 
22865 /*
22866 ** The sqlite3_mutex_leave() routine exits a mutex that was
22867 ** previously entered by the same thread. The behavior
22868 ** is undefined if the mutex is not currently entered or
22869 ** is not currently allocated. SQLite will never do either.
22870 */
22872  assert( pthreadMutexHeld(p) );
22873 #if SQLITE_MUTEX_NREF
22874  p->nRef--;
22875  if( p->nRef==0 ) p->owner = 0;
22876 #endif
22877  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
22878 
22879 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
22880  if( p->nRef==0 ){
22881  pthread_mutex_unlock(&p->mutex);
22882  }
22883 #else
22884  pthread_mutex_unlock(&p->mutex);
22885 #endif
22886 
22887 #ifdef SQLITE_DEBUG
22888  if( p->trace ){
22889  printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
22890  }
22891 #endif
22892 }
22893 
22895  static const sqlite3_mutex_methods sMutex = {
22903 #ifdef SQLITE_DEBUG
22904  pthreadMutexHeld,
22905  pthreadMutexNotheld
22906 #else
22907  0,
22908  0
22909 #endif
22910  };
22911 
22912  return &sMutex;
22913 }
22914 
22915 #endif /* SQLITE_MUTEX_PTHREADS */
22916 
22917 /************** End of mutex_unix.c ******************************************/
22918 /************** Begin file mutex_w32.c ***************************************/
22919 /*
22920 ** 2007 August 14
22921 **
22922 ** The author disclaims copyright to this source code. In place of
22923 ** a legal notice, here is a blessing:
22924 **
22925 ** May you do good and not evil.
22926 ** May you find forgiveness for yourself and forgive others.
22927 ** May you share freely, never taking more than you give.
22928 **
22929 *************************************************************************
22930 ** This file contains the C functions that implement mutexes for Win32.
22931 */
22932 /* #include "sqliteInt.h" */
22933 
22934 #if SQLITE_OS_WIN
22935 /*
22936 ** Include code that is common to all os_*.c files
22937 */
22938 /************** Include os_common.h in the middle of mutex_w32.c *************/
22939 /************** Begin file os_common.h ***************************************/
22940 /*
22941 ** 2004 May 22
22942 **
22943 ** The author disclaims copyright to this source code. In place of
22944 ** a legal notice, here is a blessing:
22945 **
22946 ** May you do good and not evil.
22947 ** May you find forgiveness for yourself and forgive others.
22948 ** May you share freely, never taking more than you give.
22949 **
22950 ******************************************************************************
22951 **
22952 ** This file contains macros and a little bit of code that is common to
22953 ** all of the platform-specific files (os_*.c) and is #included into those
22954 ** files.
22955 **
22956 ** This file should be #included by the os_*.c files only. It is not a
22957 ** general purpose header file.
22958 */
22959 #ifndef _OS_COMMON_H_
22960 #define _OS_COMMON_H_
22961 
22962 /*
22963 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22964 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22965 ** switch. The following code should catch this problem at compile-time.
22966 */
22967 #ifdef MEMORY_DEBUG
22968 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
22969 #endif
22970 
22971 /*
22972 ** Macros for performance tracing. Normally turned off. Only works
22973 ** on i486 hardware.
22974 */
22975 #ifdef SQLITE_PERFORMANCE_TRACE
22976 
22977 /*
22978 ** hwtime.h contains inline assembler code for implementing
22979 ** high-performance timing routines.
22980 */
22981 /************** Include hwtime.h in the middle of os_common.h ****************/
22982 /************** Begin file hwtime.h ******************************************/
22983 /*
22984 ** 2008 May 27
22985 **
22986 ** The author disclaims copyright to this source code. In place of
22987 ** a legal notice, here is a blessing:
22988 **
22989 ** May you do good and not evil.
22990 ** May you find forgiveness for yourself and forgive others.
22991 ** May you share freely, never taking more than you give.
22992 **
22993 ******************************************************************************
22994 **
22995 ** This file contains inline asm code for retrieving "high-performance"
22996 ** counters for x86 class CPUs.
22997 */
22998 #ifndef _HWTIME_H_
22999 #define _HWTIME_H_
23000 
23001 /*
23002 ** The following routine only works on pentium-class (or newer) processors.
23003 ** It uses the RDTSC opcode to read the cycle count value out of the
23004 ** processor and returns that value. This can be used for high-res
23005 ** profiling.
23006 */
23007 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
23008  (defined(i386) || defined(__i386__) || defined(_M_IX86))
23009 
23010  #if defined(__GNUC__)
23011 
23012  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23013  unsigned int lo, hi;
23014  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
23015  return (sqlite_uint64)hi << 32 | lo;
23016  }
23017 
23018  #elif defined(_MSC_VER)
23019 
23020  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
23021  __asm {
23022  rdtsc
23023  ret ; return value at EDX:EAX
23024  }
23025  }
23026 
23027  #endif
23028 
23029 #elif (defined(__GNUC__) && defined(__x86_64__))
23030 
23031  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23032  unsigned long val;
23033  __asm__ __volatile__ ("rdtsc" : "=A" (val));
23034  return val;
23035  }
23036 
23037 #elif (defined(__GNUC__) && defined(__ppc__))
23038 
23039  __inline__ sqlite_uint64 sqlite3Hwtime(void){
23040  unsigned long long retval;
23041  unsigned long junk;
23042  __asm__ __volatile__ ("\n\
23043  1: mftbu %1\n\
23044  mftb %L0\n\
23045  mftbu %0\n\
23046  cmpw %0,%1\n\
23047  bne 1b"
23048  : "=r" (retval), "=r" (junk));
23049  return retval;
23050  }
23051 
23052 #else
23053 
23054  #error Need implementation of sqlite3Hwtime() for your platform.
23055 
23056  /*
23057  ** To compile without implementing sqlite3Hwtime() for your platform,
23058  ** you can remove the above #error and use the following
23059  ** stub function. You will lose timing support for many
23060  ** of the debugging and testing utilities, but it should at
23061  ** least compile and run.
23062  */
23063 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
23064 
23065 #endif
23066 
23067 #endif /* !defined(_HWTIME_H_) */
23068 
23069 /************** End of hwtime.h **********************************************/
23070 /************** Continuing where we left off in os_common.h ******************/
23071 
23072 static sqlite_uint64 g_start;
23073 static sqlite_uint64 g_elapsed;
23074 #define TIMER_START g_start=sqlite3Hwtime()
23075 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
23076 #define TIMER_ELAPSED g_elapsed
23077 #else
23078 #define TIMER_START
23079 #define TIMER_END
23080 #define TIMER_ELAPSED ((sqlite_uint64)0)
23081 #endif
23082 
23083 /*
23084 ** If we compile with the SQLITE_TEST macro set, then the following block
23085 ** of code will give us the ability to simulate a disk I/O error. This
23086 ** is used for testing the I/O recovery logic.
23087 */
23088 #if defined(SQLITE_TEST)
23089 SQLITE_API extern int sqlite3_io_error_hit;
23090 SQLITE_API extern int sqlite3_io_error_hardhit;
23091 SQLITE_API extern int sqlite3_io_error_pending;
23092 SQLITE_API extern int sqlite3_io_error_persist;
23093 SQLITE_API extern int sqlite3_io_error_benign;
23094 SQLITE_API extern int sqlite3_diskfull_pending;
23095 SQLITE_API extern int sqlite3_diskfull;
23096 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
23097 #define SimulateIOError(CODE) \
23098  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
23099  || sqlite3_io_error_pending-- == 1 ) \
23100  { local_ioerr(); CODE; }
23101 static void local_ioerr(){
23102  IOTRACE(("IOERR\n"));
23103  sqlite3_io_error_hit++;
23104  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
23105 }
23106 #define SimulateDiskfullError(CODE) \
23107  if( sqlite3_diskfull_pending ){ \
23108  if( sqlite3_diskfull_pending == 1 ){ \
23109  local_ioerr(); \
23110  sqlite3_diskfull = 1; \
23111  sqlite3_io_error_hit = 1; \
23112  CODE; \
23113  }else{ \
23114  sqlite3_diskfull_pending--; \
23115  } \
23116  }
23117 #else
23118 #define SimulateIOErrorBenign(X)
23119 #define SimulateIOError(A)
23120 #define SimulateDiskfullError(A)
23121 #endif /* defined(SQLITE_TEST) */
23122 
23123 /*
23124 ** When testing, keep a count of the number of open files.
23125 */
23126 #if defined(SQLITE_TEST)
23127 SQLITE_API extern int sqlite3_open_file_count;
23128 #define OpenCounter(X) sqlite3_open_file_count+=(X)
23129 #else
23130 #define OpenCounter(X)
23131 #endif /* defined(SQLITE_TEST) */
23132 
23133 #endif /* !defined(_OS_COMMON_H_) */
23134 
23135 /************** End of os_common.h *******************************************/
23136 /************** Continuing where we left off in mutex_w32.c ******************/
23137 
23138 /*
23139 ** Include the header file for the Windows VFS.
23140 */
23141 /************** Include os_win.h in the middle of mutex_w32.c ****************/
23142 /************** Begin file os_win.h ******************************************/
23143 /*
23144 ** 2013 November 25
23145 **
23146 ** The author disclaims copyright to this source code. In place of
23147 ** a legal notice, here is a blessing:
23148 **
23149 ** May you do good and not evil.
23150 ** May you find forgiveness for yourself and forgive others.
23151 ** May you share freely, never taking more than you give.
23152 **
23153 ******************************************************************************
23154 **
23155 ** This file contains code that is specific to Windows.
23156 */
23157 #ifndef _OS_WIN_H_
23158 #define _OS_WIN_H_
23159 
23160 /*
23161 ** Include the primary Windows SDK header file.
23162 */
23163 #include "windows.h"
23164 
23165 #ifdef __CYGWIN__
23166 # include <sys/cygwin.h>
23167 # include <errno.h> /* amalgamator: dontcache */
23168 #endif
23169 
23170 /*
23171 ** Determine if we are dealing with Windows NT.
23172 **
23173 ** We ought to be able to determine if we are compiling for Windows 9x or
23174 ** Windows NT using the _WIN32_WINNT macro as follows:
23175 **
23176 ** #if defined(_WIN32_WINNT)
23177 ** # define SQLITE_OS_WINNT 1
23178 ** #else
23179 ** # define SQLITE_OS_WINNT 0
23180 ** #endif
23181 **
23182 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
23183 ** it ought to, so the above test does not work. We'll just assume that
23184 ** everything is Windows NT unless the programmer explicitly says otherwise
23185 ** by setting SQLITE_OS_WINNT to 0.
23186 */
23187 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
23188 # define SQLITE_OS_WINNT 1
23189 #endif
23190 
23191 /*
23192 ** Determine if we are dealing with Windows CE - which has a much reduced
23193 ** API.
23194 */
23195 #if defined(_WIN32_WCE)
23196 # define SQLITE_OS_WINCE 1
23197 #else
23198 # define SQLITE_OS_WINCE 0
23199 #endif
23200 
23201 /*
23202 ** Determine if we are dealing with WinRT, which provides only a subset of
23203 ** the full Win32 API.
23204 */
23205 #if !defined(SQLITE_OS_WINRT)
23206 # define SQLITE_OS_WINRT 0
23207 #endif
23208 
23209 /*
23210 ** For WinCE, some API function parameters do not appear to be declared as
23211 ** volatile.
23212 */
23213 #if SQLITE_OS_WINCE
23214 # define SQLITE_WIN32_VOLATILE
23215 #else
23216 # define SQLITE_WIN32_VOLATILE volatile
23217 #endif
23218 
23219 /*
23220 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
23221 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
23222 */
23223 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
23224  SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
23225 # define SQLITE_OS_WIN_THREADS 1
23226 #else
23227 # define SQLITE_OS_WIN_THREADS 0
23228 #endif
23229 
23230 #endif /* _OS_WIN_H_ */
23231 
23232 /************** End of os_win.h **********************************************/
23233 /************** Continuing where we left off in mutex_w32.c ******************/
23234 #endif
23235 
23236 /*
23237 ** The code in this file is only used if we are compiling multithreaded
23238 ** on a Win32 system.
23239 */
23240 #ifdef SQLITE_MUTEX_W32
23241 
23242 /*
23243 ** Each recursive mutex is an instance of the following structure.
23244 */
23245 struct sqlite3_mutex {
23246  CRITICAL_SECTION mutex; /* Mutex controlling the lock */
23247  int id; /* Mutex type */
23248 #ifdef SQLITE_DEBUG
23249  volatile int nRef; /* Number of enterances */
23250  volatile DWORD owner; /* Thread holding this mutex */
23251  volatile int trace; /* True to trace changes */
23252 #endif
23253 };
23254 
23255 /*
23256 ** These are the initializer values used when declaring a "static" mutex
23257 ** on Win32. It should be noted that all mutexes require initialization
23258 ** on the Win32 platform.
23259 */
23260 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
23261 
23262 #ifdef SQLITE_DEBUG
23263 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
23264  0L, (DWORD)0, 0 }
23265 #else
23266 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
23267 #endif
23268 
23269 #ifdef SQLITE_DEBUG
23270 /*
23271 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
23272 ** intended for use only inside assert() statements.
23273 */
23274 static int winMutexHeld(sqlite3_mutex *p){
23275  return p->nRef!=0 && p->owner==GetCurrentThreadId();
23276 }
23277 
23278 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
23279  return p->nRef==0 || p->owner!=tid;
23280 }
23281 
23282 static int winMutexNotheld(sqlite3_mutex *p){
23283  DWORD tid = GetCurrentThreadId();
23284  return winMutexNotheld2(p, tid);
23285 }
23286 #endif
23287 
23288 /*
23289 ** Try to provide a memory barrier operation, needed for initialization
23290 ** and also for the xShmBarrier method of the VFS in cases when SQLite is
23291 ** compiled without mutexes (SQLITE_THREADSAFE=0).
23292 */
23294 #if defined(SQLITE_MEMORY_BARRIER)
23295  SQLITE_MEMORY_BARRIER;
23296 #elif defined(__GNUC__)
23297  __sync_synchronize();
23298 #elif !defined(SQLITE_DISABLE_INTRINSIC) && \
23299  defined(_MSC_VER) && _MSC_VER>=1300
23300  _ReadWriteBarrier();
23301 #elif defined(MemoryBarrier)
23302  MemoryBarrier();
23303 #endif
23304 }
23305 
23306 /*
23307 ** Initialize and deinitialize the mutex subsystem.
23308 */
23309 static sqlite3_mutex winMutex_staticMutexes[] = {
23321  SQLITE3_MUTEX_INITIALIZER
23322 };
23323 
23324 static int winMutex_isInit = 0;
23325 static int winMutex_isNt = -1; /* <0 means "need to query" */
23326 
23327 /* As the winMutexInit() and winMutexEnd() functions are called as part
23328 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
23329 ** "interlocked" magic used here is probably not strictly necessary.
23330 */
23331 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
23332 
23333 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
23334 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
23335 
23336 static int winMutexInit(void){
23337  /* The first to increment to 1 does actual initialization */
23338  if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
23339  int i;
23340  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23341 #if SQLITE_OS_WINRT
23342  InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
23343 #else
23344  InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
23345 #endif
23346  }
23347  winMutex_isInit = 1;
23348  }else{
23349  /* Another thread is (in the process of) initializing the static
23350  ** mutexes */
23351  while( !winMutex_isInit ){
23352  sqlite3_win32_sleep(1);
23353  }
23354  }
23355  return SQLITE_OK;
23356 }
23357 
23358 static int winMutexEnd(void){
23359  /* The first to decrement to 0 does actual shutdown
23360  ** (which should be the last to shutdown.) */
23361  if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
23362  if( winMutex_isInit==1 ){
23363  int i;
23364  for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
23365  DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
23366  }
23367  winMutex_isInit = 0;
23368  }
23369  }
23370  return SQLITE_OK;
23371 }
23372 
23373 /*
23374 ** The sqlite3_mutex_alloc() routine allocates a new
23375 ** mutex and returns a pointer to it. If it returns NULL
23376 ** that means that a mutex could not be allocated. SQLite
23377 ** will unwind its stack and return an error. The argument
23378 ** to sqlite3_mutex_alloc() is one of these integer constants:
23379 **
23380 ** <ul>
23381 ** <li> SQLITE_MUTEX_FAST
23382 ** <li> SQLITE_MUTEX_RECURSIVE
23383 ** <li> SQLITE_MUTEX_STATIC_MASTER
23384 ** <li> SQLITE_MUTEX_STATIC_MEM
23385 ** <li> SQLITE_MUTEX_STATIC_OPEN
23386 ** <li> SQLITE_MUTEX_STATIC_PRNG
23387 ** <li> SQLITE_MUTEX_STATIC_LRU
23388 ** <li> SQLITE_MUTEX_STATIC_PMEM
23389 ** <li> SQLITE_MUTEX_STATIC_APP1
23390 ** <li> SQLITE_MUTEX_STATIC_APP2
23391 ** <li> SQLITE_MUTEX_STATIC_APP3
23392 ** <li> SQLITE_MUTEX_STATIC_VFS1
23393 ** <li> SQLITE_MUTEX_STATIC_VFS2
23394 ** <li> SQLITE_MUTEX_STATIC_VFS3
23395 ** </ul>
23396 **
23397 ** The first two constants cause sqlite3_mutex_alloc() to create
23398 ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
23399 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
23400 ** The mutex implementation does not need to make a distinction
23401 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
23402 ** not want to. But SQLite will only request a recursive mutex in
23403 ** cases where it really needs one. If a faster non-recursive mutex
23404 ** implementation is available on the host platform, the mutex subsystem
23405 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
23406 **
23407 ** The other allowed parameters to sqlite3_mutex_alloc() each return
23408 ** a pointer to a static preexisting mutex. Six static mutexes are
23409 ** used by the current version of SQLite. Future versions of SQLite
23410 ** may add additional static mutexes. Static mutexes are for internal
23411 ** use by SQLite only. Applications that use SQLite mutexes should
23412 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
23413 ** SQLITE_MUTEX_RECURSIVE.
23414 **
23415 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
23416 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
23417 ** returns a different mutex on every call. But for the static
23418 ** mutex types, the same mutex is returned on every call that has
23419 ** the same type number.
23420 */
23421 static sqlite3_mutex *winMutexAlloc(int iType){
23422  sqlite3_mutex *p;
23423 
23424  switch( iType ){
23425  case SQLITE_MUTEX_FAST:
23426  case SQLITE_MUTEX_RECURSIVE: {
23427  p = sqlite3MallocZero( sizeof(*p) );
23428  if( p ){
23429  p->id = iType;
23430 #ifdef SQLITE_DEBUG
23431 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
23432  p->trace = 1;
23433 #endif
23434 #endif
23435 #if SQLITE_OS_WINRT
23436  InitializeCriticalSectionEx(&p->mutex, 0, 0);
23437 #else
23438  InitializeCriticalSection(&p->mutex);
23439 #endif
23440  }
23441  break;
23442  }
23443  default: {
23444 #ifdef SQLITE_ENABLE_API_ARMOR
23445  if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
23447  return 0;
23448  }
23449 #endif
23450  p = &winMutex_staticMutexes[iType-2];
23451  p->id = iType;
23452 #ifdef SQLITE_DEBUG
23453 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
23454  p->trace = 1;
23455 #endif
23456 #endif
23457  break;
23458  }
23459  }
23460  return p;
23461 }
23462 
23463 
23464 /*
23465 ** This routine deallocates a previously
23466 ** allocated mutex. SQLite is careful to deallocate every
23467 ** mutex that it allocates.
23468 */
23469 static void winMutexFree(sqlite3_mutex *p){
23470  assert( p );
23471  assert( p->nRef==0 && p->owner==0 );
23472  if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
23473  DeleteCriticalSection(&p->mutex);
23474  sqlite3_free(p);
23475  }else{
23476 #ifdef SQLITE_ENABLE_API_ARMOR
23478 #endif
23479  }
23480 }
23481 
23482 /*
23483 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
23484 ** to enter a mutex. If another thread is already within the mutex,
23485 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
23486 ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
23487 ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
23488 ** be entered multiple times by the same thread. In such cases the,
23489 ** mutex must be exited an equal number of times before another thread
23490 ** can enter. If the same thread tries to enter any other kind of mutex
23491 ** more than once, the behavior is undefined.
23492 */
23493 static void winMutexEnter(sqlite3_mutex *p){
23494 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23495  DWORD tid = GetCurrentThreadId();
23496 #endif
23497 #ifdef SQLITE_DEBUG
23498  assert( p );
23499  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23500 #else
23501  assert( p );
23502 #endif
23503  assert( winMutex_isInit==1 );
23504  EnterCriticalSection(&p->mutex);
23505 #ifdef SQLITE_DEBUG
23506  assert( p->nRef>0 || p->owner==0 );
23507  p->owner = tid;
23508  p->nRef++;
23509  if( p->trace ){
23510  OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23511  tid, p, p->trace, p->nRef));
23512  }
23513 #endif
23514 }
23515 
23516 static int winMutexTry(sqlite3_mutex *p){
23517 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23518  DWORD tid = GetCurrentThreadId();
23519 #endif
23520  int rc = SQLITE_BUSY;
23521  assert( p );
23522  assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
23523  /*
23524  ** The sqlite3_mutex_try() routine is very rarely used, and when it
23525  ** is used it is merely an optimization. So it is OK for it to always
23526  ** fail.
23527  **
23528  ** The TryEnterCriticalSection() interface is only available on WinNT.
23529  ** And some windows compilers complain if you try to use it without
23530  ** first doing some #defines that prevent SQLite from building on Win98.
23531  ** For that reason, we will omit this optimization for now. See
23532  ** ticket #2685.
23533  */
23534 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
23535  assert( winMutex_isInit==1 );
23536  assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
23537  if( winMutex_isNt<0 ){
23538  winMutex_isNt = sqlite3_win32_is_nt();
23539  }
23540  assert( winMutex_isNt==0 || winMutex_isNt==1 );
23541  if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
23542 #ifdef SQLITE_DEBUG
23543  p->owner = tid;
23544  p->nRef++;
23545 #endif
23546  rc = SQLITE_OK;
23547  }
23548 #else
23549  UNUSED_PARAMETER(p);
23550 #endif
23551 #ifdef SQLITE_DEBUG
23552  if( p->trace ){
23553  OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
23554  tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
23555  }
23556 #endif
23557  return rc;
23558 }
23559 
23560 /*
23561 ** The sqlite3_mutex_leave() routine exits a mutex that was
23562 ** previously entered by the same thread. The behavior
23563 ** is undefined if the mutex is not currently entered or
23564 ** is not currently allocated. SQLite will never do either.
23565 */
23566 static void winMutexLeave(sqlite3_mutex *p){
23567 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
23568  DWORD tid = GetCurrentThreadId();
23569 #endif
23570  assert( p );
23571 #ifdef SQLITE_DEBUG
23572  assert( p->nRef>0 );
23573  assert( p->owner==tid );
23574  p->nRef--;
23575  if( p->nRef==0 ) p->owner = 0;
23576  assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
23577 #endif
23578  assert( winMutex_isInit==1 );
23579  LeaveCriticalSection(&p->mutex);
23580 #ifdef SQLITE_DEBUG
23581  if( p->trace ){
23582  OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
23583  tid, p, p->trace, p->nRef));
23584  }
23585 #endif
23586 }
23587 
23589  static const sqlite3_mutex_methods sMutex = {
23590  winMutexInit,
23591  winMutexEnd,
23592  winMutexAlloc,
23593  winMutexFree,
23594  winMutexEnter,
23595  winMutexTry,
23596  winMutexLeave,
23597 #ifdef SQLITE_DEBUG
23598  winMutexHeld,
23599  winMutexNotheld
23600 #else
23601  0,
23602  0
23603 #endif
23604  };
23605  return &sMutex;
23606 }
23607 
23608 #endif /* SQLITE_MUTEX_W32 */
23609 
23610 /************** End of mutex_w32.c *******************************************/
23611 /************** Begin file malloc.c ******************************************/
23612 /*
23613 ** 2001 September 15
23614 **
23615 ** The author disclaims copyright to this source code. In place of
23616 ** a legal notice, here is a blessing:
23617 **
23618 ** May you do good and not evil.
23619 ** May you find forgiveness for yourself and forgive others.
23620 ** May you share freely, never taking more than you give.
23621 **
23622 *************************************************************************
23623 **
23624 ** Memory allocation functions used throughout sqlite.
23625 */
23626 /* #include "sqliteInt.h" */
23627 /* #include <stdarg.h> */
23628 
23629 /*
23630 ** Attempt to release up to n bytes of non-essential memory currently
23631 ** held by SQLite. An example of non-essential memory is memory used to
23632 ** cache database pages that are not currently in use.
23633 */
23635 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23636  return sqlite3PcacheReleaseMemory(n);
23637 #else
23638  /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
23639  ** is a no-op returning zero if SQLite is not compiled with
23640  ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
23641  UNUSED_PARAMETER(n);
23642  return 0;
23643 #endif
23644 }
23645 
23646 /*
23647 ** An instance of the following object records the location of
23648 ** each unused scratch buffer.
23649 */
23650 typedef struct ScratchFreeslot {
23651  struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
23652 } ScratchFreeslot;
23653 
23654 /*
23655 ** State information local to the memory allocation subsystem.
23656 */
23657 static SQLITE_WSD struct Mem0Global {
23658  sqlite3_mutex *mutex; /* Mutex to serialize access */
23659  sqlite3_int64 alarmThreshold; /* The soft heap limit */
23660 
23661  /*
23662  ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
23663  ** (so that a range test can be used to determine if an allocation
23664  ** being freed came from pScratch) and a pointer to the list of
23665  ** unused scratch allocations.
23666  */
23670 
23671  /*
23672  ** True if heap is nearly "full" where "full" is defined by the
23673  ** sqlite3_soft_heap_limit() setting.
23674  */
23676 } mem0 = { 0, 0, 0, 0, 0, 0 };
23677 
23678 #define mem0 GLOBAL(struct Mem0Global, mem0)
23679 
23680 /*
23681 ** Return the memory allocator mutex. sqlite3_status() needs it.
23682 */
23684  return mem0.mutex;
23685 }
23686 
23687 #ifndef SQLITE_OMIT_DEPRECATED
23688 /*
23689 ** Deprecated external interface. It used to set an alarm callback
23690 ** that was invoked when memory usage grew too large. Now it is a
23691 ** no-op.
23692 */
23694  void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
23695  void *pArg,
23696  sqlite3_int64 iThreshold
23697 ){
23698  (void)xCallback;
23699  (void)pArg;
23700  (void)iThreshold;
23701  return SQLITE_OK;
23702 }
23703 #endif
23704 
23705 /*
23706 ** Set the soft heap-size limit for the library. Passing a zero or
23707 ** negative value indicates no limit.
23708 */
23709 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
23710  sqlite3_int64 priorLimit;
23711  sqlite3_int64 excess;
23712  sqlite3_int64 nUsed;
23713 #ifndef SQLITE_OMIT_AUTOINIT
23714  int rc = sqlite3_initialize();
23715  if( rc ) return -1;
23716 #endif
23717  sqlite3_mutex_enter(mem0.mutex);
23718  priorLimit = mem0.alarmThreshold;
23719  if( n<0 ){
23720  sqlite3_mutex_leave(mem0.mutex);
23721  return priorLimit;
23722  }
23723  mem0.alarmThreshold = n;
23725  mem0.nearlyFull = (n>0 && n<=nUsed);
23726  sqlite3_mutex_leave(mem0.mutex);
23727  excess = sqlite3_memory_used() - n;
23728  if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
23729  return priorLimit;
23730 }
23732  if( n<0 ) n = 0;
23734 }
23735 
23736 /*
23737 ** Initialize the memory allocation subsystem.
23738 */
23740  int rc;
23741  if( sqlite3GlobalConfig.m.xMalloc==0 ){
23743  }
23744  memset(&mem0, 0, sizeof(mem0));
23746  if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
23747  && sqlite3GlobalConfig.nScratch>0 ){
23748  int i, n, sz;
23749  ScratchFreeslot *pSlot;
23750  sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
23751  sqlite3GlobalConfig.szScratch = sz;
23752  pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
23753  n = sqlite3GlobalConfig.nScratch;
23754  mem0.pScratchFree = pSlot;
23755  mem0.nScratchFree = n;
23756  for(i=0; i<n-1; i++){
23757  pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
23758  pSlot = pSlot->pNext;
23759  }
23760  pSlot->pNext = 0;
23761  mem0.pScratchEnd = (void*)&pSlot[1];
23762  }else{
23763  mem0.pScratchEnd = 0;
23764  sqlite3GlobalConfig.pScratch = 0;
23765  sqlite3GlobalConfig.szScratch = 0;
23766  sqlite3GlobalConfig.nScratch = 0;
23767  }
23768  if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
23769  || sqlite3GlobalConfig.nPage<=0 ){
23770  sqlite3GlobalConfig.pPage = 0;
23771  sqlite3GlobalConfig.szPage = 0;
23772  }
23773  rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
23774  if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
23775  return rc;
23776 }
23777 
23778 /*
23779 ** Return true if the heap is currently under memory pressure - in other
23780 ** words if the amount of heap used is close to the limit set by
23781 ** sqlite3_soft_heap_limit().
23782 */
23784  return mem0.nearlyFull;
23785 }
23786 
23787 /*
23788 ** Deinitialize the memory allocation subsystem.
23789 */
23791  if( sqlite3GlobalConfig.m.xShutdown ){
23792  sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
23793  }
23794  memset(&mem0, 0, sizeof(mem0));
23795 }
23796 
23797 /*
23798 ** Return the amount of memory currently checked out.
23799 */
23801  sqlite3_int64 res, mx;
23803  return res;
23804 }
23805 
23806 /*
23807 ** Return the maximum amount of memory that has ever been
23808 ** checked out since either the beginning of this process
23809 ** or since the most recent reset.
23810 */
23812  sqlite3_int64 res, mx;
23813  sqlite3_status64(SQLITE_STATUS_MEMORY_USED, &res, &mx, resetFlag);
23814  return mx;
23815 }
23816 
23817 /*
23818 ** Trigger the alarm
23819 */
23820 static void sqlite3MallocAlarm(int nByte){
23821  if( mem0.alarmThreshold<=0 ) return;
23822  sqlite3_mutex_leave(mem0.mutex);
23823  sqlite3_release_memory(nByte);
23824  sqlite3_mutex_enter(mem0.mutex);
23825 }
23826 
23827 /*
23828 ** Do a memory allocation with statistics and alarms. Assume the
23829 ** lock is already held.
23830 */
23831 static int mallocWithAlarm(int n, void **pp){
23832  int nFull;
23833  void *p;
23834  assert( sqlite3_mutex_held(mem0.mutex) );
23835  nFull = sqlite3GlobalConfig.m.xRoundup(n);
23837  if( mem0.alarmThreshold>0 ){
23838  sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
23839  if( nUsed >= mem0.alarmThreshold - nFull ){
23840  mem0.nearlyFull = 1;
23841  sqlite3MallocAlarm(nFull);
23842  }else{
23843  mem0.nearlyFull = 0;
23844  }
23845  }
23846  p = sqlite3GlobalConfig.m.xMalloc(nFull);
23847 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
23848  if( p==0 && mem0.alarmThreshold>0 ){
23849  sqlite3MallocAlarm(nFull);
23850  p = sqlite3GlobalConfig.m.xMalloc(nFull);
23851  }
23852 #endif
23853  if( p ){
23854  nFull = sqlite3MallocSize(p);
23857  }
23858  *pp = p;
23859  return nFull;
23860 }
23861 
23862 /*
23863 ** Allocate memory. This routine is like sqlite3_malloc() except that it
23864 ** assumes the memory subsystem has already been initialized.
23865 */
23867  void *p;
23868  if( n==0 || n>=0x7fffff00 ){
23869  /* A memory allocation of a number of bytes which is near the maximum
23870  ** signed integer value might cause an integer overflow inside of the
23871  ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
23872  ** 255 bytes of overhead. SQLite itself will never use anything near
23873  ** this amount. The only way to reach the limit is with sqlite3_malloc() */
23874  p = 0;
23875  }else if( sqlite3GlobalConfig.bMemstat ){
23876  sqlite3_mutex_enter(mem0.mutex);
23877  mallocWithAlarm((int)n, &p);
23878  sqlite3_mutex_leave(mem0.mutex);
23879  }else{
23880  p = sqlite3GlobalConfig.m.xMalloc((int)n);
23881  }
23882  assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
23883  return p;
23884 }
23885 
23886 /*
23887 ** This version of the memory allocation is for use by the application.
23888 ** First make sure the memory subsystem is initialized, then do the
23889 ** allocation.
23890 */
23892 #ifndef SQLITE_OMIT_AUTOINIT
23893  if( sqlite3_initialize() ) return 0;
23894 #endif
23895  return n<=0 ? 0 : sqlite3Malloc(n);
23896 }
23898 #ifndef SQLITE_OMIT_AUTOINIT
23899  if( sqlite3_initialize() ) return 0;
23900 #endif
23901  return sqlite3Malloc(n);
23902 }
23903 
23904 /*
23905 ** Each thread may only have a single outstanding allocation from
23906 ** xScratchMalloc(). We verify this constraint in the single-threaded
23907 ** case by setting scratchAllocOut to 1 when an allocation
23908 ** is outstanding clearing it when the allocation is freed.
23909 */
23910 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
23911 static int scratchAllocOut = 0;
23912 #endif
23913 
23914 
23915 /*
23916 ** Allocate memory that is to be used and released right away.
23917 ** This routine is similar to alloca() in that it is not intended
23918 ** for situations where the memory might be held long-term. This
23919 ** routine is intended to get memory to old large transient data
23920 ** structures that would not normally fit on the stack of an
23921 ** embedded processor.
23922 */
23924  void *p;
23925  assert( n>0 );
23926 
23927  sqlite3_mutex_enter(mem0.mutex);
23929  if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
23930  p = mem0.pScratchFree;
23931  mem0.pScratchFree = mem0.pScratchFree->pNext;
23932  mem0.nScratchFree--;
23934  sqlite3_mutex_leave(mem0.mutex);
23935  }else{
23936  sqlite3_mutex_leave(mem0.mutex);
23937  p = sqlite3Malloc(n);
23938  if( sqlite3GlobalConfig.bMemstat && p ){
23939  sqlite3_mutex_enter(mem0.mutex);
23941  sqlite3_mutex_leave(mem0.mutex);
23942  }
23944  }
23945  assert( sqlite3_mutex_notheld(mem0.mutex) );
23946 
23947 
23948 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
23949  /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
23950  ** buffers per thread.
23951  **
23952  ** This can only be checked in single-threaded mode.
23953  */
23954  assert( scratchAllocOut==0 );
23955  if( p ) scratchAllocOut++;
23956 #endif
23957 
23958  return p;
23959 }
23961  if( p ){
23962 
23963 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
23964  /* Verify that no more than two scratch allocation per thread
23965  ** is outstanding at one time. (This is only checked in the
23966  ** single-threaded case since checking in the multi-threaded case
23967  ** would be much more complicated.) */
23968  assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
23969  scratchAllocOut--;
23970 #endif
23971 
23972  if( SQLITE_WITHIN(p, sqlite3GlobalConfig.pScratch, mem0.pScratchEnd) ){
23973  /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
23974  ScratchFreeslot *pSlot;
23975  pSlot = (ScratchFreeslot*)p;
23976  sqlite3_mutex_enter(mem0.mutex);
23977  pSlot->pNext = mem0.pScratchFree;
23978  mem0.pScratchFree = pSlot;
23979  mem0.nScratchFree++;
23980  assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
23982  sqlite3_mutex_leave(mem0.mutex);
23983  }else{
23984  /* Release memory back to the heap */
23988  if( sqlite3GlobalConfig.bMemstat ){
23989  int iSize = sqlite3MallocSize(p);
23990  sqlite3_mutex_enter(mem0.mutex);
23994  sqlite3GlobalConfig.m.xFree(p);
23995  sqlite3_mutex_leave(mem0.mutex);
23996  }else{
23997  sqlite3GlobalConfig.m.xFree(p);
23998  }
23999  }
24000  }
24001 }
24002 
24003 /*
24004 ** TRUE if p is a lookaside memory allocation from db
24005 */
24006 #ifndef SQLITE_OMIT_LOOKASIDE
24007 static int isLookaside(sqlite3 *db, void *p){
24008  return SQLITE_WITHIN(p, db->lookaside.pStart, db->lookaside.pEnd);
24009 }
24010 #else
24011 #define isLookaside(A,B) 0
24012 #endif
24013 
24014 /*
24015 ** Return the size of a memory allocation previously obtained from
24016 ** sqlite3Malloc() or sqlite3_malloc().
24017 */
24020  return sqlite3GlobalConfig.m.xSize(p);
24021 }
24023  assert( p!=0 );
24024  if( db==0 || !isLookaside(db,p) ){
24025 #if SQLITE_DEBUG
24026  if( db==0 ){
24029  }else{
24032  }
24033 #endif
24034  return sqlite3GlobalConfig.m.xSize(p);
24035  }else{
24037  return db->lookaside.sz;
24038  }
24039 }
24040 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
24043  return p ? sqlite3GlobalConfig.m.xSize(p) : 0;
24044 }
24045 
24046 /*
24047 ** Free memory previously obtained from sqlite3Malloc().
24048 */
24050  if( p==0 ) return; /* IMP: R-49053-54554 */
24053  if( sqlite3GlobalConfig.bMemstat ){
24054  sqlite3_mutex_enter(mem0.mutex);
24057  sqlite3GlobalConfig.m.xFree(p);
24058  sqlite3_mutex_leave(mem0.mutex);
24059  }else{
24060  sqlite3GlobalConfig.m.xFree(p);
24061  }
24062 }
24063 
24064 /*
24065 ** Add the size of memory allocation "p" to the count in
24066 ** *db->pnBytesFreed.
24067 */
24069  *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
24070 }
24071 
24072 /*
24073 ** Free memory that might be associated with a particular database
24074 ** connection.
24075 */
24077  assert( db==0 || sqlite3_mutex_held(db->mutex) );
24078  if( p==0 ) return;
24079  if( db ){
24080  if( db->pnBytesFreed ){
24081  measureAllocationSize(db, p);
24082  return;
24083  }
24084  if( isLookaside(db, p) ){
24085  LookasideSlot *pBuf = (LookasideSlot*)p;
24086 #if SQLITE_DEBUG
24087  /* Trash all content in the buffer being freed */
24088  memset(p, 0xaa, db->lookaside.sz);
24089 #endif
24090  pBuf->pNext = db->lookaside.pFree;
24091  db->lookaside.pFree = pBuf;
24092  db->lookaside.nOut--;
24093  return;
24094  }
24095  }
24100  sqlite3_free(p);
24101 }
24102 
24103 /*
24104 ** Change the size of an existing memory allocation
24105 */
24106 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
24107  int nOld, nNew, nDiff;
24108  void *pNew;
24110  assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
24111  if( pOld==0 ){
24112  return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
24113  }
24114  if( nBytes==0 ){
24115  sqlite3_free(pOld); /* IMP: R-26507-47431 */
24116  return 0;
24117  }
24118  if( nBytes>=0x7fffff00 ){
24119  /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
24120  return 0;
24121  }
24122  nOld = sqlite3MallocSize(pOld);
24123  /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
24124  ** argument to xRealloc is always a value returned by a prior call to
24125  ** xRoundup. */
24126  nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
24127  if( nOld==nNew ){
24128  pNew = pOld;
24129  }else if( sqlite3GlobalConfig.bMemstat ){
24130  sqlite3_mutex_enter(mem0.mutex);
24132  nDiff = nNew - nOld;
24134  mem0.alarmThreshold-nDiff ){
24135  sqlite3MallocAlarm(nDiff);
24136  }
24137  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24138  if( pNew==0 && mem0.alarmThreshold>0 ){
24139  sqlite3MallocAlarm((int)nBytes);
24140  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24141  }
24142  if( pNew ){
24143  nNew = sqlite3MallocSize(pNew);
24145  }
24146  sqlite3_mutex_leave(mem0.mutex);
24147  }else{
24148  pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
24149  }
24150  assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
24151  return pNew;
24152 }
24153 
24154 /*
24155 ** The public interface to sqlite3Realloc. Make sure that the memory
24156 ** subsystem is initialized prior to invoking sqliteRealloc.
24157 */
24158 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
24159 #ifndef SQLITE_OMIT_AUTOINIT
24160  if( sqlite3_initialize() ) return 0;
24161 #endif
24162  if( n<0 ) n = 0; /* IMP: R-26507-47431 */
24163  return sqlite3Realloc(pOld, n);
24164 }
24165 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
24166 #ifndef SQLITE_OMIT_AUTOINIT
24167  if( sqlite3_initialize() ) return 0;
24168 #endif
24169  return sqlite3Realloc(pOld, n);
24170 }
24171 
24172 
24173 /*
24174 ** Allocate and zero memory.
24175 */
24177  void *p = sqlite3Malloc(n);
24178  if( p ){
24179  memset(p, 0, (size_t)n);
24180  }
24181  return p;
24182 }
24183 
24184 /*
24185 ** Allocate and zero memory. If the allocation fails, make
24186 ** the mallocFailed flag in the connection pointer.
24187 */
24189  void *p;
24190  testcase( db==0 );
24191  p = sqlite3DbMallocRaw(db, n);
24192  if( p ) memset(p, 0, (size_t)n);
24193  return p;
24194 }
24195 
24196 
24197 /* Finish the work of sqlite3DbMallocRawNN for the unusual and
24198 ** slower case when the allocation cannot be fulfilled using lookaside.
24199 */
24200 static SQLITE_NOINLINE void *dbMallocRawFinish(sqlite3 *db, u64 n){
24201  void *p;
24202  assert( db!=0 );
24203  p = sqlite3Malloc(n);
24204  if( !p ) sqlite3OomFault(db);
24207  return p;
24208 }
24209 
24210 /*
24211 ** Allocate memory, either lookaside (if possible) or heap.
24212 ** If the allocation fails, set the mallocFailed flag in
24213 ** the connection pointer.
24214 **
24215 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
24216 ** failure on the same database connection) then always return 0.
24217 ** Hence for a particular database connection, once malloc starts
24218 ** failing, it fails consistently until mallocFailed is reset.
24219 ** This is an important assumption. There are many places in the
24220 ** code that do things like this:
24221 **
24222 ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
24223 ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
24224 ** if( b ) a[10] = 9;
24225 **
24226 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
24227 ** that all prior mallocs (ex: "a") worked too.
24228 **
24229 ** The sqlite3MallocRawNN() variant guarantees that the "db" parameter is
24230 ** not a NULL pointer.
24231 */
24233  void *p;
24234  if( db ) return sqlite3DbMallocRawNN(db, n);
24235  p = sqlite3Malloc(n);
24237  return p;
24238 }
24240 #ifndef SQLITE_OMIT_LOOKASIDE
24241  LookasideSlot *pBuf;
24242  assert( db!=0 );
24244  assert( db->pnBytesFreed==0 );
24245  if( db->lookaside.bDisable==0 ){
24246  assert( db->mallocFailed==0 );
24247  if( n>db->lookaside.sz ){
24248  db->lookaside.anStat[1]++;
24249  }else if( (pBuf = db->lookaside.pFree)==0 ){
24250  db->lookaside.anStat[2]++;
24251  }else{
24252  db->lookaside.pFree = pBuf->pNext;
24253  db->lookaside.nOut++;
24254  db->lookaside.anStat[0]++;
24255  if( db->lookaside.nOut>db->lookaside.mxOut ){
24256  db->lookaside.mxOut = db->lookaside.nOut;
24257  }
24258  return (void*)pBuf;
24259  }
24260  }else if( db->mallocFailed ){
24261  return 0;
24262  }
24263 #else
24264  assert( db!=0 );
24266  assert( db->pnBytesFreed==0 );
24267  if( db->mallocFailed ){
24268  return 0;
24269  }
24270 #endif
24271  return dbMallocRawFinish(db, n);
24272 }
24273 
24274 /* Forward declaration */
24275 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n);
24276 
24277 /*
24278 ** Resize the block of memory pointed to by p to n bytes. If the
24279 ** resize fails, set the mallocFailed flag in the connection object.
24280 */
24281 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
24282  assert( db!=0 );
24283  if( p==0 ) return sqlite3DbMallocRawNN(db, n);
24285  if( isLookaside(db,p) && n<=db->lookaside.sz ) return p;
24286  return dbReallocFinish(db, p, n);
24287 }
24288 static SQLITE_NOINLINE void *dbReallocFinish(sqlite3 *db, void *p, u64 n){
24289  void *pNew = 0;
24290  assert( db!=0 );
24291  assert( p!=0 );
24292  if( db->mallocFailed==0 ){
24293  if( isLookaside(db, p) ){
24294  pNew = sqlite3DbMallocRawNN(db, n);
24295  if( pNew ){
24296  memcpy(pNew, p, db->lookaside.sz);
24297  sqlite3DbFree(db, p);
24298  }
24299  }else{
24303  pNew = sqlite3_realloc64(p, n);
24304  if( !pNew ){
24305  sqlite3OomFault(db);
24306  }
24309  }
24310  }
24311  return pNew;
24312 }
24313 
24314 /*
24315 ** Attempt to reallocate p. If the reallocation fails, then free p
24316 ** and set the mallocFailed flag in the database connection.
24317 */
24318 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
24319  void *pNew;
24320  pNew = sqlite3DbRealloc(db, p, n);
24321  if( !pNew ){
24322  sqlite3DbFree(db, p);
24323  }
24324  return pNew;
24325 }
24326 
24327 /*
24328 ** Make a copy of a string in memory obtained from sqliteMalloc(). These
24329 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
24330 ** is because when memory debugging is turned on, these two functions are
24331 ** called via macros that record the current file and line number in the
24332 ** ThreadData structure.
24333 */
24334 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
24335  char *zNew;
24336  size_t n;
24337  if( z==0 ){
24338  return 0;
24339  }
24340  n = sqlite3Strlen30(z) + 1;
24341  assert( (n&0x7fffffff)==n );
24342  zNew = sqlite3DbMallocRaw(db, (int)n);
24343  if( zNew ){
24344  memcpy(zNew, z, n);
24345  }
24346  return zNew;
24347 }
24348 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
24349  char *zNew;
24350  assert( db!=0 );
24351  if( z==0 ){
24352  return 0;
24353  }
24354  assert( (n&0x7fffffff)==n );
24355  zNew = sqlite3DbMallocRawNN(db, n+1);
24356  if( zNew ){
24357  memcpy(zNew, z, (size_t)n);
24358  zNew[n] = 0;
24359  }
24360  return zNew;
24361 }
24362 
24363 /*
24364 ** Free any prior content in *pz and replace it with a copy of zNew.
24365 */
24366 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zNew){
24367  sqlite3DbFree(db, *pz);
24368  *pz = sqlite3DbStrDup(db, zNew);
24369 }
24370 
24371 /*
24372 ** Call this routine to record the fact that an OOM (out-of-memory) error
24373 ** has happened. This routine will set db->mallocFailed, and also
24374 ** temporarily disable the lookaside memory allocator and interrupt
24375 ** any running VDBEs.
24376 */
24378  if( db->mallocFailed==0 && db->bBenignMalloc==0 ){
24379  db->mallocFailed = 1;
24380  if( db->nVdbeExec>0 ){
24381  db->u1.isInterrupted = 1;
24382  }
24383  db->lookaside.bDisable++;
24384  }
24385 }
24386 
24387 /*
24388 ** This routine reactivates the memory allocator and clears the
24389 ** db->mallocFailed flag as necessary.
24390 **
24391 ** The memory allocator is not restarted if there are running
24392 ** VDBEs.
24393 */
24395  if( db->mallocFailed && db->nVdbeExec==0 ){
24396  db->mallocFailed = 0;
24397  db->u1.isInterrupted = 0;
24398  assert( db->lookaside.bDisable>0 );
24399  db->lookaside.bDisable--;
24400  }
24401 }
24402 
24403 /*
24404 ** Take actions at the end of an API call to indicate an OOM error
24405 */
24407  sqlite3OomClear(db);
24409  return SQLITE_NOMEM_BKPT;
24410 }
24411 
24412 /*
24413 ** This function must be called before exiting any API function (i.e.
24414 ** returning control to the user) that has called sqlite3_malloc or
24415 ** sqlite3_realloc.
24416 **
24417 ** The returned value is normally a copy of the second argument to this
24418 ** function. However, if a malloc() failure has occurred since the previous
24419 ** invocation SQLITE_NOMEM is returned instead.
24420 **
24421 ** If an OOM as occurred, then the connection error-code (the value
24422 ** returned by sqlite3_errcode()) is set to SQLITE_NOMEM.
24423 */
24425  /* If the db handle must hold the connection handle mutex here.
24426  ** Otherwise the read (and possible write) of db->mallocFailed
24427  ** is unsafe, as is the call to sqlite3Error().
24428  */
24429  assert( db!=0 );
24431  if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
24432  return apiOomError(db);
24433  }
24434  return rc & db->errMask;
24435 }
24436 
24437 /************** End of malloc.c **********************************************/
24438 /************** Begin file printf.c ******************************************/
24439 /*
24440 ** The "printf" code that follows dates from the 1980's. It is in
24441 ** the public domain.
24442 **
24443 **************************************************************************
24444 **
24445 ** This file contains code for a set of "printf"-like routines. These
24446 ** routines format strings much like the printf() from the standard C
24447 ** library, though the implementation here has enhancements to support
24448 ** SQLite.
24449 */
24450 /* #include "sqliteInt.h" */
24451 
24452 /*
24453 ** Conversion types fall into various categories as defined by the
24454 ** following enumeration.
24455 */
24456 #define etRADIX 0 /* Integer types. %d, %x, %o, and so forth */
24457 #define etFLOAT 1 /* Floating point. %f */
24458 #define etEXP 2 /* Exponentional notation. %e and %E */
24459 #define etGENERIC 3 /* Floating or exponential, depending on exponent. %g */
24460 #define etSIZE 4 /* Return number of characters processed so far. %n */
24461 #define etSTRING 5 /* Strings. %s */
24462 #define etDYNSTRING 6 /* Dynamically allocated strings. %z */
24463 #define etPERCENT 7 /* Percent symbol. %% */
24464 #define etCHARX 8 /* Characters. %c */
24465 /* The rest are extensions, not normally found in printf() */
24466 #define etSQLESCAPE 9 /* Strings with '\'' doubled. %q */
24467 #define etSQLESCAPE2 10 /* Strings with '\'' doubled and enclosed in '',
24468  NULL pointers replaced by SQL NULL. %Q */
24469 #define etTOKEN 11 /* a pointer to a Token structure */
24470 #define etSRCLIST 12 /* a pointer to a SrcList */
24471 #define etPOINTER 13 /* The %p conversion */
24472 #define etSQLESCAPE3 14 /* %w -> Strings with '\"' doubled */
24473 #define etORDINAL 15 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
24474 
24475 #define etINVALID 16 /* Any unrecognized conversion type */
24476 
24477 
24478 /*
24479 ** An "etByte" is an 8-bit unsigned value.
24480 */
24481 typedef unsigned char etByte;
24482 
24483 /*
24484 ** Each builtin conversion character (ex: the 'd' in "%d") is described
24485 ** by an instance of the following structure
24486 */
24487 typedef struct et_info { /* Information about each format field */
24488  char fmttype; /* The format field code letter */
24489  etByte base; /* The base for radix conversion */
24490  etByte flags; /* One or more of FLAG_ constants below */
24491  etByte type; /* Conversion paradigm */
24492  etByte charset; /* Offset into aDigits[] of the digits string */
24493  etByte prefix; /* Offset into aPrefix[] of the prefix string */
24494 } et_info;
24495 
24496 /*
24497 ** Allowed values for et_info.flags
24498 */
24499 #define FLAG_SIGNED 1 /* True if the value to convert is signed */
24500 #define FLAG_INTERN 2 /* True if for internal use only */
24501 #define FLAG_STRING 4 /* Allow infinity precision */
24502 
24503 
24504 /*
24505 ** The following table is searched linearly, so it is good to put the
24506 ** most frequently used conversion types first.
24507 */
24508 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
24509 static const char aPrefix[] = "-x0\000X0";
24510 static const et_info fmtinfo[] = {
24511  { 'd', 10, 1, etRADIX, 0, 0 },
24512  { 's', 0, 4, etSTRING, 0, 0 },
24513  { 'g', 0, 1, etGENERIC, 30, 0 },
24514  { 'z', 0, 4, etDYNSTRING, 0, 0 },
24515  { 'q', 0, 4, etSQLESCAPE, 0, 0 },
24516  { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
24517  { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
24518  { 'c', 0, 0, etCHARX, 0, 0 },
24519  { 'o', 8, 0, etRADIX, 0, 2 },
24520  { 'u', 10, 0, etRADIX, 0, 0 },
24521  { 'x', 16, 0, etRADIX, 16, 1 },
24522  { 'X', 16, 0, etRADIX, 0, 4 },
24523 #ifndef SQLITE_OMIT_FLOATING_POINT
24524  { 'f', 0, 1, etFLOAT, 0, 0 },
24525  { 'e', 0, 1, etEXP, 30, 0 },
24526  { 'E', 0, 1, etEXP, 14, 0 },
24527  { 'G', 0, 1, etGENERIC, 14, 0 },
24528 #endif
24529  { 'i', 10, 1, etRADIX, 0, 0 },
24530  { 'n', 0, 0, etSIZE, 0, 0 },
24531  { '%', 0, 0, etPERCENT, 0, 0 },
24532  { 'p', 16, 0, etPOINTER, 0, 1 },
24533 
24534 /* All the rest have the FLAG_INTERN bit set and are thus for internal
24535 ** use only */
24536  { 'T', 0, 2, etTOKEN, 0, 0 },
24537  { 'S', 0, 2, etSRCLIST, 0, 0 },
24538  { 'r', 10, 3, etORDINAL, 0, 0 },
24539 };
24540 
24541 /*
24542 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
24543 ** conversions will work.
24544 */
24545 #ifndef SQLITE_OMIT_FLOATING_POINT
24546 /*
24547 ** "*val" is a double such that 0.1 <= *val < 10.0
24548 ** Return the ascii code for the leading digit of *val, then
24549 ** multiply "*val" by 10.0 to renormalize.
24550 **
24551 ** Example:
24552 ** input: *val = 3.14159
24553 ** output: *val = 1.4159 function return = '3'
24554 **
24555 ** The counter *cnt is incremented each time. After counter exceeds
24556 ** 16 (the number of significant digits in a 64-bit float) '0' is
24557 ** always returned.
24558 */
24559 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
24560  int digit;
24562  if( (*cnt)<=0 ) return '0';
24563  (*cnt)--;
24564  digit = (int)*val;
24565  d = digit;
24566  digit += '0';
24567  *val = (*val - d)*10.0;
24568  return (char)digit;
24569 }
24570 #endif /* SQLITE_OMIT_FLOATING_POINT */
24571 
24572 /*
24573 ** Set the StrAccum object to an error mode.
24574 */
24575 static void setStrAccumError(StrAccum *p, u8 eError){
24576  assert( eError==STRACCUM_NOMEM || eError==STRACCUM_TOOBIG );
24577  p->accError = eError;
24578  p->nAlloc = 0;
24579 }
24580 
24581 /*
24582 ** Extra argument values from a PrintfArguments object
24583 */
24584 static sqlite3_int64 getIntArg(PrintfArguments *p){
24585  if( p->nArg<=p->nUsed ) return 0;
24586  return sqlite3_value_int64(p->apArg[p->nUsed++]);
24587 }
24588 static double getDoubleArg(PrintfArguments *p){
24589  if( p->nArg<=p->nUsed ) return 0.0;
24590  return sqlite3_value_double(p->apArg[p->nUsed++]);
24591 }
24592 static char *getTextArg(PrintfArguments *p){
24593  if( p->nArg<=p->nUsed ) return 0;
24594  return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
24595 }
24596 
24597 
24598 /*
24599 ** On machines with a small stack size, you can redefine the
24600 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
24601 */
24602 #ifndef SQLITE_PRINT_BUF_SIZE
24603 # define SQLITE_PRINT_BUF_SIZE 70
24604 #endif
24605 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
24606 
24607 /*
24608 ** Render a string given by "fmt" into the StrAccum object.
24609 */
24611  StrAccum *pAccum, /* Accumulate results here */
24612  const char *fmt, /* Format string */
24613  va_list ap /* arguments */
24614 ){
24615  int c; /* Next character in the format string */
24616  char *bufpt; /* Pointer to the conversion buffer */
24617  int precision; /* Precision of the current field */
24618  int length; /* Length of the field */
24619  int idx; /* A general purpose loop counter */
24620  int width; /* Width of the current field */
24621  etByte flag_leftjustify; /* True if "-" flag is present */
24622  etByte flag_plussign; /* True if "+" flag is present */
24623  etByte flag_blanksign; /* True if " " flag is present */
24624  etByte flag_alternateform; /* True if "#" flag is present */
24625  etByte flag_altform2; /* True if "!" flag is present */
24626  etByte flag_zeropad; /* True if field width constant starts with zero */
24627  etByte flag_long; /* True if "l" flag is present */
24628  etByte flag_longlong; /* True if the "ll" flag is present */
24629  etByte done; /* Loop termination flag */
24630  etByte xtype = etINVALID; /* Conversion paradigm */
24631  u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
24632  u8 useIntern; /* Ok to use internal conversions (ex: %T) */
24633  char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
24634  sqlite_uint64 longvalue; /* Value for integer types */
24635  LONGDOUBLE_TYPE realvalue; /* Value for real types */
24636  const et_info *infop; /* Pointer to the appropriate info structure */
24637  char *zOut; /* Rendering buffer */
24638  int nOut; /* Size of the rendering buffer */
24639  char *zExtra = 0; /* Malloced memory used by some conversion */
24640 #ifndef SQLITE_OMIT_FLOATING_POINT
24641  int exp, e2; /* exponent of real numbers */
24642  int nsd; /* Number of significant digits returned */
24643  double rounder; /* Used for rounding floating point values */
24644  etByte flag_dp; /* True if decimal point should be shown */
24645  etByte flag_rtz; /* True if trailing zeros should be removed */
24646 #endif
24647  PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
24648  char buf[etBUFSIZE]; /* Conversion buffer */
24649 
24650  bufpt = 0;
24651  if( pAccum->printfFlags ){
24652  if( (bArgList = (pAccum->printfFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
24653  pArgList = va_arg(ap, PrintfArguments*);
24654  }
24655  useIntern = pAccum->printfFlags & SQLITE_PRINTF_INTERNAL;
24656  }else{
24657  bArgList = useIntern = 0;
24658  }
24659  for(; (c=(*fmt))!=0; ++fmt){
24660  if( c!='%' ){
24661  bufpt = (char *)fmt;
24662 #if HAVE_STRCHRNUL
24663  fmt = strchrnul(fmt, '%');
24664 #else
24665  do{ fmt++; }while( *fmt && *fmt != '%' );
24666 #endif
24667  sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
24668  if( *fmt==0 ) break;
24669  }
24670  if( (c=(*++fmt))==0 ){
24671  sqlite3StrAccumAppend(pAccum, "%", 1);
24672  break;
24673  }
24674  /* Find out what flags are present */
24675  flag_leftjustify = flag_plussign = flag_blanksign =
24676  flag_alternateform = flag_altform2 = flag_zeropad = 0;
24677  done = 0;
24678  do{
24679  switch( c ){
24680  case '-': flag_leftjustify = 1; break;
24681  case '+': flag_plussign = 1; break;
24682  case ' ': flag_blanksign = 1; break;
24683  case '#': flag_alternateform = 1; break;
24684  case '!': flag_altform2 = 1; break;
24685  case '0': flag_zeropad = 1; break;
24686  default: done = 1; break;
24687  }
24688  }while( !done && (c=(*++fmt))!=0 );
24689  /* Get the field width */
24690  if( c=='*' ){
24691  if( bArgList ){
24692  width = (int)getIntArg(pArgList);
24693  }else{
24694  width = va_arg(ap,int);
24695  }
24696  if( width<0 ){
24697  flag_leftjustify = 1;
24698  width = width >= -2147483647 ? -width : 0;
24699  }
24700  c = *++fmt;
24701  }else{
24702  unsigned wx = 0;
24703  while( c>='0' && c<='9' ){
24704  wx = wx*10 + c - '0';
24705  c = *++fmt;
24706  }
24707  testcase( wx>0x7fffffff );
24708  width = wx & 0x7fffffff;
24709  }
24710  assert( width>=0 );
24711 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24712  if( width>SQLITE_PRINTF_PRECISION_LIMIT ){
24713  width = SQLITE_PRINTF_PRECISION_LIMIT;
24714  }
24715 #endif
24716 
24717  /* Get the precision */
24718  if( c=='.' ){
24719  c = *++fmt;
24720  if( c=='*' ){
24721  if( bArgList ){
24722  precision = (int)getIntArg(pArgList);
24723  }else{
24724  precision = va_arg(ap,int);
24725  }
24726  c = *++fmt;
24727  if( precision<0 ){
24728  precision = precision >= -2147483647 ? -precision : -1;
24729  }
24730  }else{
24731  unsigned px = 0;
24732  while( c>='0' && c<='9' ){
24733  px = px*10 + c - '0';
24734  c = *++fmt;
24735  }
24736  testcase( px>0x7fffffff );
24737  precision = px & 0x7fffffff;
24738  }
24739  }else{
24740  precision = -1;
24741  }
24742  assert( precision>=(-1) );
24743 #ifdef SQLITE_PRINTF_PRECISION_LIMIT
24744  if( precision>SQLITE_PRINTF_PRECISION_LIMIT ){
24745  precision = SQLITE_PRINTF_PRECISION_LIMIT;
24746  }
24747 #endif
24748 
24749 
24750  /* Get the conversion type modifier */
24751  if( c=='l' ){
24752  flag_long = 1;
24753  c = *++fmt;
24754  if( c=='l' ){
24755  flag_longlong = 1;
24756  c = *++fmt;
24757  }else{
24758  flag_longlong = 0;
24759  }
24760  }else{
24761  flag_long = flag_longlong = 0;
24762  }
24763  /* Fetch the info entry for the field */
24764  infop = &fmtinfo[0];
24765  xtype = etINVALID;
24766  for(idx=0; idx<ArraySize(fmtinfo); idx++){
24767  if( c==fmtinfo[idx].fmttype ){
24768  infop = &fmtinfo[idx];
24769  if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
24770  xtype = infop->type;
24771  }else{
24772  return;
24773  }
24774  break;
24775  }
24776  }
24777 
24778  /*
24779  ** At this point, variables are initialized as follows:
24780  **
24781  ** flag_alternateform TRUE if a '#' is present.
24782  ** flag_altform2 TRUE if a '!' is present.
24783  ** flag_plussign TRUE if a '+' is present.
24784  ** flag_leftjustify TRUE if a '-' is present or if the
24785  ** field width was negative.
24786  ** flag_zeropad TRUE if the width began with 0.
24787  ** flag_long TRUE if the letter 'l' (ell) prefixed
24788  ** the conversion character.
24789  ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
24790  ** the conversion character.
24791  ** flag_blanksign TRUE if a ' ' is present.
24792  ** width The specified field width. This is
24793  ** always non-negative. Zero is the default.
24794  ** precision The specified precision. The default
24795  ** is -1.
24796  ** xtype The class of the conversion.
24797  ** infop Pointer to the appropriate info struct.
24798  */
24799  switch( xtype ){
24800  case etPOINTER:
24801  flag_longlong = sizeof(char*)==sizeof(i64);
24802  flag_long = sizeof(char*)==sizeof(long int);
24803  /* Fall through into the next case */
24804  case etORDINAL:
24805  case etRADIX:
24806  if( infop->flags & FLAG_SIGNED ){
24807  i64 v;
24808  if( bArgList ){
24809  v = getIntArg(pArgList);
24810  }else if( flag_longlong ){
24811  v = va_arg(ap,i64);
24812  }else if( flag_long ){
24813  v = va_arg(ap,long int);
24814  }else{
24815  v = va_arg(ap,int);
24816  }
24817  if( v<0 ){
24818  if( v==SMALLEST_INT64 ){
24819  longvalue = ((u64)1)<<63;
24820  }else{
24821  longvalue = -v;
24822  }
24823  prefix = '-';
24824  }else{
24825  longvalue = v;
24826  if( flag_plussign ) prefix = '+';
24827  else if( flag_blanksign ) prefix = ' ';
24828  else prefix = 0;
24829  }
24830  }else{
24831  if( bArgList ){
24832  longvalue = (u64)getIntArg(pArgList);
24833  }else if( flag_longlong ){
24834  longvalue = va_arg(ap,u64);
24835  }else if( flag_long ){
24836  longvalue = va_arg(ap,unsigned long int);
24837  }else{
24838  longvalue = va_arg(ap,unsigned int);
24839  }
24840  prefix = 0;
24841  }
24842  if( longvalue==0 ) flag_alternateform = 0;
24843  if( flag_zeropad && precision<width-(prefix!=0) ){
24844  precision = width-(prefix!=0);
24845  }
24846  if( precision<etBUFSIZE-10 ){
24847  nOut = etBUFSIZE;
24848  zOut = buf;
24849  }else{
24850  nOut = precision + 10;
24851  zOut = zExtra = sqlite3Malloc( nOut );
24852  if( zOut==0 ){
24854  return;
24855  }
24856  }
24857  bufpt = &zOut[nOut-1];
24858  if( xtype==etORDINAL ){
24859  static const char zOrd[] = "thstndrd";
24860  int x = (int)(longvalue % 10);
24861  if( x>=4 || (longvalue/10)%10==1 ){
24862  x = 0;
24863  }
24864  *(--bufpt) = zOrd[x*2+1];
24865  *(--bufpt) = zOrd[x*2];
24866  }
24867  {
24868  const char *cset = &aDigits[infop->charset];
24869  u8 base = infop->base;
24870  do{ /* Convert to ascii */
24871  *(--bufpt) = cset[longvalue%base];
24872  longvalue = longvalue/base;
24873  }while( longvalue>0 );
24874  }
24875  length = (int)(&zOut[nOut-1]-bufpt);
24876  for(idx=precision-length; idx>0; idx--){
24877  *(--bufpt) = '0'; /* Zero pad */
24878  }
24879  if( prefix ) *(--bufpt) = prefix; /* Add sign */
24880  if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
24881  const char *pre;
24882  char x;
24883  pre = &aPrefix[infop->prefix];
24884  for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
24885  }
24886  length = (int)(&zOut[nOut-1]-bufpt);
24887  break;
24888  case etFLOAT:
24889  case etEXP:
24890  case etGENERIC:
24891  if( bArgList ){
24892  realvalue = getDoubleArg(pArgList);
24893  }else{
24894  realvalue = va_arg(ap,double);
24895  }
24896 #ifdef SQLITE_OMIT_FLOATING_POINT
24897  length = 0;
24898 #else
24899  if( precision<0 ) precision = 6; /* Set default precision */
24900  if( realvalue<0.0 ){
24901  realvalue = -realvalue;
24902  prefix = '-';
24903  }else{
24904  if( flag_plussign ) prefix = '+';
24905  else if( flag_blanksign ) prefix = ' ';
24906  else prefix = 0;
24907  }
24908  if( xtype==etGENERIC && precision>0 ) precision--;
24909  testcase( precision>0xfff );
24910  for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
24911  if( xtype==etFLOAT ) realvalue += rounder;
24912  /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
24913  exp = 0;
24914  if( sqlite3IsNaN((double)realvalue) ){
24915  bufpt = "NaN";
24916  length = 3;
24917  break;
24918  }
24919  if( realvalue>0.0 ){
24920  LONGDOUBLE_TYPE scale = 1.0;
24921  while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
24922  while( realvalue>=1e10*scale && exp<=350 ){ scale *= 1e10; exp+=10; }
24923  while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
24924  realvalue /= scale;
24925  while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
24926  while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
24927  if( exp>350 ){
24928  bufpt = buf;
24929  buf[0] = prefix;
24930  memcpy(buf+(prefix!=0),"Inf",4);
24931  length = 3+(prefix!=0);
24932  break;
24933  }
24934  }
24935  bufpt = buf;
24936  /*
24937  ** If the field type is etGENERIC, then convert to either etEXP
24938  ** or etFLOAT, as appropriate.
24939  */
24940  if( xtype!=etFLOAT ){
24941  realvalue += rounder;
24942  if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
24943  }
24944  if( xtype==etGENERIC ){
24945  flag_rtz = !flag_alternateform;
24946  if( exp<-4 || exp>precision ){
24947  xtype = etEXP;
24948  }else{
24949  precision = precision - exp;
24950  xtype = etFLOAT;
24951  }
24952  }else{
24953  flag_rtz = flag_altform2;
24954  }
24955  if( xtype==etEXP ){
24956  e2 = 0;
24957  }else{
24958  e2 = exp;
24959  }
24960  if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
24961  bufpt = zExtra
24962  = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
24963  if( bufpt==0 ){
24965  return;
24966  }
24967  }
24968  zOut = bufpt;
24969  nsd = 16 + flag_altform2*10;
24970  flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
24971  /* The sign in front of the number */
24972  if( prefix ){
24973  *(bufpt++) = prefix;
24974  }
24975  /* Digits prior to the decimal point */
24976  if( e2<0 ){
24977  *(bufpt++) = '0';
24978  }else{
24979  for(; e2>=0; e2--){
24980  *(bufpt++) = et_getdigit(&realvalue,&nsd);
24981  }
24982  }
24983  /* The decimal point */
24984  if( flag_dp ){
24985  *(bufpt++) = '.';
24986  }
24987  /* "0" digits after the decimal point but before the first
24988  ** significant digit of the number */
24989  for(e2++; e2<0; precision--, e2++){
24990  assert( precision>0 );
24991  *(bufpt++) = '0';
24992  }
24993  /* Significant digits after the decimal point */
24994  while( (precision--)>0 ){
24995  *(bufpt++) = et_getdigit(&realvalue,&nsd);
24996  }
24997  /* Remove trailing zeros and the "." if no digits follow the "." */
24998  if( flag_rtz && flag_dp ){
24999  while( bufpt[-1]=='0' ) *(--bufpt) = 0;
25000  assert( bufpt>zOut );
25001  if( bufpt[-1]=='.' ){
25002  if( flag_altform2 ){
25003  *(bufpt++) = '0';
25004  }else{
25005  *(--bufpt) = 0;
25006  }
25007  }
25008  }
25009  /* Add the "eNNN" suffix */
25010  if( xtype==etEXP ){
25011  *(bufpt++) = aDigits[infop->charset];
25012  if( exp<0 ){
25013  *(bufpt++) = '-'; exp = -exp;
25014  }else{
25015  *(bufpt++) = '+';
25016  }
25017  if( exp>=100 ){
25018  *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
25019  exp %= 100;
25020  }
25021  *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
25022  *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
25023  }
25024  *bufpt = 0;
25025 
25026  /* The converted number is in buf[] and zero terminated. Output it.
25027  ** Note that the number is in the usual order, not reversed as with
25028  ** integer conversions. */
25029  length = (int)(bufpt-zOut);
25030  bufpt = zOut;
25031 
25032  /* Special case: Add leading zeros if the flag_zeropad flag is
25033  ** set and we are not left justified */
25034  if( flag_zeropad && !flag_leftjustify && length < width){
25035  int i;
25036  int nPad = width - length;
25037  for(i=width; i>=nPad; i--){
25038  bufpt[i] = bufpt[i-nPad];
25039  }
25040  i = prefix!=0;
25041  while( nPad-- ) bufpt[i++] = '0';
25042  length = width;
25043  }
25044 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
25045  break;
25046  case etSIZE:
25047  if( !bArgList ){
25048  *(va_arg(ap,int*)) = pAccum->nChar;
25049  }
25050  length = width = 0;
25051  break;
25052  case etPERCENT:
25053  buf[0] = '%';
25054  bufpt = buf;
25055  length = 1;
25056  break;
25057  case etCHARX:
25058  if( bArgList ){
25059  bufpt = getTextArg(pArgList);
25060  c = bufpt ? bufpt[0] : 0;
25061  }else{
25062  c = va_arg(ap,int);
25063  }
25064  if( precision>1 ){
25065  width -= precision-1;
25066  if( width>1 && !flag_leftjustify ){
25067  sqlite3AppendChar(pAccum, width-1, ' ');
25068  width = 0;
25069  }
25070  sqlite3AppendChar(pAccum, precision-1, c);
25071  }
25072  length = 1;
25073  buf[0] = c;
25074  bufpt = buf;
25075  break;
25076  case etSTRING:
25077  case etDYNSTRING:
25078  if( bArgList ){
25079  bufpt = getTextArg(pArgList);
25080  xtype = etSTRING;
25081  }else{
25082  bufpt = va_arg(ap,char*);
25083  }
25084  if( bufpt==0 ){
25085  bufpt = "";
25086  }else if( xtype==etDYNSTRING ){
25087  zExtra = bufpt;
25088  }
25089  if( precision>=0 ){
25090  for(length=0; length<precision && bufpt[length]; length++){}
25091  }else{
25092  length = sqlite3Strlen30(bufpt);
25093  }
25094  break;
25095  case etSQLESCAPE: /* Escape ' characters */
25096  case etSQLESCAPE2: /* Escape ' and enclose in '...' */
25097  case etSQLESCAPE3: { /* Escape " characters */
25098  int i, j, k, n, isnull;
25099  int needQuote;
25100  char ch;
25101  char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
25102  char *escarg;
25103 
25104  if( bArgList ){
25105  escarg = getTextArg(pArgList);
25106  }else{
25107  escarg = va_arg(ap,char*);
25108  }
25109  isnull = escarg==0;
25110  if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
25111  k = precision;
25112  for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
25113  if( ch==q ) n++;
25114  }
25115  needQuote = !isnull && xtype==etSQLESCAPE2;
25116  n += i + 3;
25117  if( n>etBUFSIZE ){
25118  bufpt = zExtra = sqlite3Malloc( n );
25119  if( bufpt==0 ){
25121  return;
25122  }
25123  }else{
25124  bufpt = buf;
25125  }
25126  j = 0;
25127  if( needQuote ) bufpt[j++] = q;
25128  k = i;
25129  for(i=0; i<k; i++){
25130  bufpt[j++] = ch = escarg[i];
25131  if( ch==q ) bufpt[j++] = ch;
25132  }
25133  if( needQuote ) bufpt[j++] = q;
25134  bufpt[j] = 0;
25135  length = j;
25136  /* The precision in %q and %Q means how many input characters to
25137  ** consume, not the length of the output...
25138  ** if( precision>=0 && precision<length ) length = precision; */
25139  break;
25140  }
25141  case etTOKEN: {
25142  Token *pToken = va_arg(ap, Token*);
25143  assert( bArgList==0 );
25144  if( pToken && pToken->n ){
25145  sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
25146  }
25147  length = width = 0;
25148  break;
25149  }
25150  case etSRCLIST: {
25151  SrcList *pSrc = va_arg(ap, SrcList*);
25152  int k = va_arg(ap, int);
25153  struct SrcList_item *pItem = &pSrc->a[k];
25154  assert( bArgList==0 );
25155  assert( k>=0 && k<pSrc->nSrc );
25156  if( pItem->zDatabase ){
25157  sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
25158  sqlite3StrAccumAppend(pAccum, ".", 1);
25159  }
25160  sqlite3StrAccumAppendAll(pAccum, pItem->zName);
25161  length = width = 0;
25162  break;
25163  }
25164  default: {
25165  assert( xtype==etINVALID );
25166  return;
25167  }
25168  }/* End switch over the format type */
25169  /*
25170  ** The text of the conversion is pointed to by "bufpt" and is
25171  ** "length" characters long. The field width is "width". Do
25172  ** the output.
25173  */
25174  width -= length;
25175  if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25176  sqlite3StrAccumAppend(pAccum, bufpt, length);
25177  if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
25178 
25179  if( zExtra ){
25180  sqlite3DbFree(pAccum->db, zExtra);
25181  zExtra = 0;
25182  }
25183  }/* End for loop over the format string */
25184 } /* End of function */
25185 
25186 /*
25187 ** Enlarge the memory allocation on a StrAccum object so that it is
25188 ** able to accept at least N more bytes of text.
25189 **
25190 ** Return the number of bytes of text that StrAccum is able to accept
25191 ** after the attempted enlargement. The value returned might be zero.
25192 */
25193 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
25194  char *zNew;
25195  assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
25196  if( p->accError ){
25199  return 0;
25200  }
25201  if( p->mxAlloc==0 ){
25202  N = p->nAlloc - p->nChar - 1;
25204  return N;
25205  }else{
25206  char *zOld = isMalloced(p) ? p->zText : 0;
25207  i64 szNew = p->nChar;
25208  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25209  szNew += N + 1;
25210  if( szNew+p->nChar<=p->mxAlloc ){
25211  /* Force exponential buffer size growth as long as it does not overflow,
25212  ** to avoid having to call this routine too often */
25213  szNew += p->nChar;
25214  }
25215  if( szNew > p->mxAlloc ){
25218  return 0;
25219  }else{
25220  p->nAlloc = (int)szNew;
25221  }
25222  if( p->db ){
25223  zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
25224  }else{
25225  zNew = sqlite3_realloc64(zOld, p->nAlloc);
25226  }
25227  if( zNew ){
25228  assert( p->zText!=0 || p->nChar==0 );
25229  if( !isMalloced(p) && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
25230  p->zText = zNew;
25231  p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
25233  }else{
25236  return 0;
25237  }
25238  }
25239  return N;
25240 }
25241 
25242 /*
25243 ** Append N copies of character c to the given string buffer.
25244 */
25246  testcase( p->nChar + (i64)N > 0x7fffffff );
25247  if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
25248  return;
25249  }
25250  assert( (p->zText==p->zBase)==!isMalloced(p) );
25251  while( (N--)>0 ) p->zText[p->nChar++] = c;
25252 }
25253 
25254 /*
25255 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
25256 ** So enlarge if first, then do the append.
25257 **
25258 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
25259 ** work (enlarging the buffer) using tail recursion, so that the
25260 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
25261 */
25262 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
25263  N = sqlite3StrAccumEnlarge(p, N);
25264  if( N>0 ){
25265  memcpy(&p->zText[p->nChar], z, N);
25266  p->nChar += N;
25267  }
25268  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25269 }
25270 
25271 /*
25272 ** Append N bytes of text from z to the StrAccum object. Increase the
25273 ** size of the memory allocation for StrAccum if necessary.
25274 */
25275 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
25276  assert( z!=0 || N==0 );
25277  assert( p->zText!=0 || p->nChar==0 || p->accError );
25278  assert( N>=0 );
25279  assert( p->accError==0 || p->nAlloc==0 );
25280  if( p->nChar+N >= p->nAlloc ){
25281  enlargeAndAppend(p,z,N);
25282  }else{
25283  assert( p->zText );
25284  p->nChar += N;
25285  memcpy(&p->zText[p->nChar-N], z, N);
25286  }
25287 }
25288 
25289 /*
25290 ** Append the complete text of zero-terminated string z[] to the p string.
25291 */
25294 }
25295 
25296 
25297 /*
25298 ** Finish off a string by making sure it is zero-terminated.
25299 ** Return a pointer to the resulting string. Return a NULL
25300 ** pointer if any kind of error was encountered.
25301 */
25303  if( p->zText ){
25304  assert( (p->zText==p->zBase)==!isMalloced(p) );
25305  p->zText[p->nChar] = 0;
25306  if( p->mxAlloc>0 && !isMalloced(p) ){
25307  p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
25308  if( p->zText ){
25309  memcpy(p->zText, p->zBase, p->nChar+1);
25311  }else{
25313  }
25314  }
25315  }
25316  return p->zText;
25317 }
25318 
25319 /*
25320 ** Reset an StrAccum string. Reclaim all malloced memory.
25321 */
25323  assert( (p->zText==0 || p->zText==p->zBase)==!isMalloced(p) );
25324  if( isMalloced(p) ){
25325  sqlite3DbFree(p->db, p->zText);
25327  }
25328  p->zText = 0;
25329 }
25330 
25331 /*
25332 ** Initialize a string accumulator.
25333 **
25334 ** p: The accumulator to be initialized.
25335 ** db: Pointer to a database connection. May be NULL. Lookaside
25336 ** memory is used if not NULL. db->mallocFailed is set appropriately
25337 ** when not NULL.
25338 ** zBase: An initial buffer. May be NULL in which case the initial buffer
25339 ** is malloced.
25340 ** n: Size of zBase in bytes. If total space requirements never exceed
25341 ** n then no memory allocations ever occur.
25342 ** mx: Maximum number of bytes to accumulate. If mx==0 then no memory
25343 ** allocations will ever occur.
25344 */
25345 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, sqlite3 *db, char *zBase, int n, int mx){
25346  p->zText = p->zBase = zBase;
25347  p->db = db;
25348  p->nChar = 0;
25349  p->nAlloc = n;
25350  p->mxAlloc = mx;
25351  p->accError = 0;
25352  p->printfFlags = 0;
25353 }
25354 
25355 /*
25356 ** Print into memory obtained from sqliteMalloc(). Use the internal
25357 ** %-conversion extensions.
25358 */
25359 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
25360  char *z;
25361  char zBase[SQLITE_PRINT_BUF_SIZE];
25362  StrAccum acc;
25363  assert( db!=0 );
25364  sqlite3StrAccumInit(&acc, db, zBase, sizeof(zBase),
25367  sqlite3VXPrintf(&acc, zFormat, ap);
25368  z = sqlite3StrAccumFinish(&acc);
25369  if( acc.accError==STRACCUM_NOMEM ){
25370  sqlite3OomFault(db);
25371  }
25372  return z;
25373 }
25374 
25375 /*
25376 ** Print into memory obtained from sqliteMalloc(). Use the internal
25377 ** %-conversion extensions.
25378 */
25379 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
25380  va_list ap;
25381  char *z;
25382  va_start(ap, zFormat);
25383  z = sqlite3VMPrintf(db, zFormat, ap);
25384  va_end(ap);
25385  return z;
25386 }
25387 
25388 /*
25389 ** Print into memory obtained from sqlite3_malloc(). Omit the internal
25390 ** %-conversion extensions.
25391 */
25392 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
25393  char *z;
25394  char zBase[SQLITE_PRINT_BUF_SIZE];
25395  StrAccum acc;
25396 
25397 #ifdef SQLITE_ENABLE_API_ARMOR
25398  if( zFormat==0 ){
25400  return 0;
25401  }
25402 #endif
25403 #ifndef SQLITE_OMIT_AUTOINIT
25404  if( sqlite3_initialize() ) return 0;
25405 #endif
25406  sqlite3StrAccumInit(&acc, 0, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
25407  sqlite3VXPrintf(&acc, zFormat, ap);
25408  z = sqlite3StrAccumFinish(&acc);
25409  return z;
25410 }
25411 
25412 /*
25413 ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
25414 ** %-conversion extensions.
25415 */
25416 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
25417  va_list ap;
25418  char *z;
25419 #ifndef SQLITE_OMIT_AUTOINIT
25420  if( sqlite3_initialize() ) return 0;
25421 #endif
25422  va_start(ap, zFormat);
25423  z = sqlite3_vmprintf(zFormat, ap);
25424  va_end(ap);
25425  return z;
25426 }
25427 
25428 /*
25429 ** sqlite3_snprintf() works like snprintf() except that it ignores the
25430 ** current locale settings. This is important for SQLite because we
25431 ** are not able to use a "," as the decimal point in place of "." as
25432 ** specified by some locales.
25433 **
25434 ** Oops: The first two arguments of sqlite3_snprintf() are backwards
25435 ** from the snprintf() standard. Unfortunately, it is too late to change
25436 ** this without breaking compatibility, so we just have to live with the
25437 ** mistake.
25438 **
25439 ** sqlite3_vsnprintf() is the varargs version.
25440 */
25441 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
25442  StrAccum acc;
25443  if( n<=0 ) return zBuf;
25444 #ifdef SQLITE_ENABLE_API_ARMOR
25445  if( zBuf==0 || zFormat==0 ) {
25447  if( zBuf ) zBuf[0] = 0;
25448  return zBuf;
25449  }
25450 #endif
25451  sqlite3StrAccumInit(&acc, 0, zBuf, n, 0);
25452  sqlite3VXPrintf(&acc, zFormat, ap);
25453  return sqlite3StrAccumFinish(&acc);
25454 }
25455 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
25456  char *z;
25457  va_list ap;
25458  va_start(ap,zFormat);
25459  z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
25460  va_end(ap);
25461  return z;
25462 }
25463 
25464 /*
25465 ** This is the routine that actually formats the sqlite3_log() message.
25466 ** We house it in a separate routine from sqlite3_log() to avoid using
25467 ** stack space on small-stack systems when logging is disabled.
25468 **
25469 ** sqlite3_log() must render into a static buffer. It cannot dynamically
25470 ** allocate memory because it might be called while the memory allocator
25471 ** mutex is held.
25472 **
25473 ** sqlite3VXPrintf() might ask for *temporary* memory allocations for
25474 ** certain format characters (%q) or for very large precisions or widths.
25475 ** Care must be taken that any sqlite3_log() calls that occur while the
25476 ** memory mutex is held do not use these mechanisms.
25477 */
25478 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
25479  StrAccum acc; /* String accumulator */
25480  char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
25481 
25482  sqlite3StrAccumInit(&acc, 0, zMsg, sizeof(zMsg), 0);
25483  sqlite3VXPrintf(&acc, zFormat, ap);
25484  sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
25485  sqlite3StrAccumFinish(&acc));
25486 }
25487 
25488 /*
25489 ** Format and write a message to the log if logging is enabled.
25490 */
25491 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
25492  va_list ap; /* Vararg list */
25493  if( sqlite3GlobalConfig.xLog ){
25494  va_start(ap, zFormat);
25495  renderLogMsg(iErrCode, zFormat, ap);
25496  va_end(ap);
25497  }
25498 }
25499 
25500 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
25501 /*
25502 ** A version of printf() that understands %lld. Used for debugging.
25503 ** The printf() built into some versions of windows does not understand %lld
25504 ** and segfaults if you give it a long long int.
25505 */
25506 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
25507  va_list ap;
25508  StrAccum acc;
25509  char zBuf[500];
25510  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25511  va_start(ap,zFormat);
25512  sqlite3VXPrintf(&acc, zFormat, ap);
25513  va_end(ap);
25514  sqlite3StrAccumFinish(&acc);
25515  fprintf(stdout,"%s", zBuf);
25516  fflush(stdout);
25517 }
25518 #endif
25519 
25520 
25521 /*
25522 ** variable-argument wrapper around sqlite3VXPrintf(). The bFlags argument
25523 ** can contain the bit SQLITE_PRINTF_INTERNAL enable internal formats.
25524 */
25525 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
25526  va_list ap;
25527  va_start(ap,zFormat);
25528  sqlite3VXPrintf(p, zFormat, ap);
25529  va_end(ap);
25530 }
25531 
25532 /************** End of printf.c **********************************************/
25533 /************** Begin file treeview.c ****************************************/
25534 /*
25535 ** 2015-06-08
25536 **
25537 ** The author disclaims copyright to this source code. In place of
25538 ** a legal notice, here is a blessing:
25539 **
25540 ** May you do good and not evil.
25541 ** May you find forgiveness for yourself and forgive others.
25542 ** May you share freely, never taking more than you give.
25543 **
25544 *************************************************************************
25545 **
25546 ** This file contains C code to implement the TreeView debugging routines.
25547 ** These routines print a parse tree to standard output for debugging and
25548 ** analysis.
25549 **
25550 ** The interfaces in this file is only available when compiling
25551 ** with SQLITE_DEBUG.
25552 */
25553 /* #include "sqliteInt.h" */
25554 #ifdef SQLITE_DEBUG
25555 
25556 /*
25557 ** Add a new subitem to the tree. The moreToFollow flag indicates that this
25558 ** is not the last item in the tree.
25559 */
25560 static TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
25561  if( p==0 ){
25562  p = sqlite3_malloc64( sizeof(*p) );
25563  if( p==0 ) return 0;
25564  memset(p, 0, sizeof(*p));
25565  }else{
25566  p->iLevel++;
25567  }
25568  assert( moreToFollow==0 || moreToFollow==1 );
25569  if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
25570  return p;
25571 }
25572 
25573 /*
25574 ** Finished with one layer of the tree
25575 */
25576 static void sqlite3TreeViewPop(TreeView *p){
25577  if( p==0 ) return;
25578  p->iLevel--;
25579  if( p->iLevel<0 ) sqlite3_free(p);
25580 }
25581 
25582 /*
25583 ** Generate a single line of output for the tree, with a prefix that contains
25584 ** all the appropriate tree lines
25585 */
25586 static void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
25587  va_list ap;
25588  int i;
25589  StrAccum acc;
25590  char zBuf[500];
25591  sqlite3StrAccumInit(&acc, 0, zBuf, sizeof(zBuf), 0);
25592  if( p ){
25593  for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
25594  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
25595  }
25596  sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
25597  }
25598  va_start(ap, zFormat);
25599  sqlite3VXPrintf(&acc, zFormat, ap);
25600  va_end(ap);
25601  if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
25602  sqlite3StrAccumFinish(&acc);
25603  fprintf(stdout,"%s", zBuf);
25604  fflush(stdout);
25605 }
25606 
25607 /*
25608 ** Shorthand for starting a new tree item that consists of a single label
25609 */
25610 static void sqlite3TreeViewItem(TreeView *p, const char *zLabel,u8 moreFollows){
25611  p = sqlite3TreeViewPush(p, moreFollows);
25612  sqlite3TreeViewLine(p, "%s", zLabel);
25613 }
25614 
25615 /*
25616 ** Generate a human-readable description of a WITH clause.
25617 */
25618 SQLITE_PRIVATE void sqlite3TreeViewWith(TreeView *pView, const With *pWith, u8 moreToFollow){
25619  int i;
25620  if( pWith==0 ) return;
25621  if( pWith->nCte==0 ) return;
25622  if( pWith->pOuter ){
25623  sqlite3TreeViewLine(pView, "WITH (0x%p, pOuter=0x%p)",pWith,pWith->pOuter);
25624  }else{
25625  sqlite3TreeViewLine(pView, "WITH (0x%p)", pWith);
25626  }
25627  if( pWith->nCte>0 ){
25628  pView = sqlite3TreeViewPush(pView, 1);
25629  for(i=0; i<pWith->nCte; i++){
25630  StrAccum x;
25631  char zLine[1000];
25632  const struct Cte *pCte = &pWith->a[i];
25633  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25634  sqlite3XPrintf(&x, "%s", pCte->zName);
25635  if( pCte->pCols && pCte->pCols->nExpr>0 ){
25636  char cSep = '(';
25637  int j;
25638  for(j=0; j<pCte->pCols->nExpr; j++){
25639  sqlite3XPrintf(&x, "%c%s", cSep, pCte->pCols->a[j].zName);
25640  cSep = ',';
25641  }
25642  sqlite3XPrintf(&x, ")");
25643  }
25644  sqlite3XPrintf(&x, " AS");
25646  sqlite3TreeViewItem(pView, zLine, i<pWith->nCte-1);
25647  sqlite3TreeViewSelect(pView, pCte->pSelect, 0);
25648  sqlite3TreeViewPop(pView);
25649  }
25650  sqlite3TreeViewPop(pView);
25651  }
25652 }
25653 
25654 
25655 /*
25656 ** Generate a human-readable description of a the Select object.
25657 */
25658 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
25659  int n = 0;
25660  int cnt = 0;
25661  pView = sqlite3TreeViewPush(pView, moreToFollow);
25662  if( p->pWith ){
25663  sqlite3TreeViewWith(pView, p->pWith, 1);
25664  cnt = 1;
25665  sqlite3TreeViewPush(pView, 1);
25666  }
25667  do{
25668  sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p) selFlags=0x%x nSelectRow=%d",
25669  ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
25670  ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p, p->selFlags,
25671  (int)p->nSelectRow
25672  );
25673  if( cnt++ ) sqlite3TreeViewPop(pView);
25674  if( p->pPrior ){
25675  n = 1000;
25676  }else{
25677  n = 0;
25678  if( p->pSrc && p->pSrc->nSrc ) n++;
25679  if( p->pWhere ) n++;
25680  if( p->pGroupBy ) n++;
25681  if( p->pHaving ) n++;
25682  if( p->pOrderBy ) n++;
25683  if( p->pLimit ) n++;
25684  if( p->pOffset ) n++;
25685  }
25686  sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
25687  if( p->pSrc && p->pSrc->nSrc ){
25688  int i;
25689  pView = sqlite3TreeViewPush(pView, (n--)>0);
25690  sqlite3TreeViewLine(pView, "FROM");
25691  for(i=0; i<p->pSrc->nSrc; i++){
25692  struct SrcList_item *pItem = &p->pSrc->a[i];
25693  StrAccum x;
25694  char zLine[100];
25695  sqlite3StrAccumInit(&x, 0, zLine, sizeof(zLine), 0);
25696  sqlite3XPrintf(&x, "{%d,*}", pItem->iCursor);
25697  if( pItem->zDatabase ){
25698  sqlite3XPrintf(&x, " %s.%s", pItem->zDatabase, pItem->zName);
25699  }else if( pItem->zName ){
25700  sqlite3XPrintf(&x, " %s", pItem->zName);
25701  }
25702  if( pItem->pTab ){
25703  sqlite3XPrintf(&x, " tabname=%Q", pItem->pTab->zName);
25704  }
25705  if( pItem->zAlias ){
25706  sqlite3XPrintf(&x, " (AS %s)", pItem->zAlias);
25707  }
25708  if( pItem->fg.jointype & JT_LEFT ){
25709  sqlite3XPrintf(&x, " LEFT-JOIN");
25710  }
25712  sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
25713  if( pItem->pSelect ){
25714  sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
25715  }
25716  if( pItem->fg.isTabFunc ){
25717  sqlite3TreeViewExprList(pView, pItem->u1.pFuncArg, 0, "func-args:");
25718  }
25719  sqlite3TreeViewPop(pView);
25720  }
25721  sqlite3TreeViewPop(pView);
25722  }
25723  if( p->pWhere ){
25724  sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
25725  sqlite3TreeViewExpr(pView, p->pWhere, 0);
25726  sqlite3TreeViewPop(pView);
25727  }
25728  if( p->pGroupBy ){
25729  sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
25730  }
25731  if( p->pHaving ){
25732  sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
25733  sqlite3TreeViewExpr(pView, p->pHaving, 0);
25734  sqlite3TreeViewPop(pView);
25735  }
25736  if( p->pOrderBy ){
25737  sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
25738  }
25739  if( p->pLimit ){
25740  sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
25741  sqlite3TreeViewExpr(pView, p->pLimit, 0);
25742  sqlite3TreeViewPop(pView);
25743  }
25744  if( p->pOffset ){
25745  sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
25746  sqlite3TreeViewExpr(pView, p->pOffset, 0);
25747  sqlite3TreeViewPop(pView);
25748  }
25749  if( p->pPrior ){
25750  const char *zOp = "UNION";
25751  switch( p->op ){
25752  case TK_ALL: zOp = "UNION ALL"; break;
25753  case TK_INTERSECT: zOp = "INTERSECT"; break;
25754  case TK_EXCEPT: zOp = "EXCEPT"; break;
25755  }
25756  sqlite3TreeViewItem(pView, zOp, 1);
25757  }
25758  p = p->pPrior;
25759  }while( p!=0 );
25760  sqlite3TreeViewPop(pView);
25761 }
25762 
25763 /*
25764 ** Generate a human-readable explanation of an expression tree.
25765 */
25766 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
25767  const char *zBinOp = 0; /* Binary operator */
25768  const char *zUniOp = 0; /* Unary operator */
25769  char zFlgs[30];
25770  pView = sqlite3TreeViewPush(pView, moreToFollow);
25771  if( pExpr==0 ){
25772  sqlite3TreeViewLine(pView, "nil");
25773  sqlite3TreeViewPop(pView);
25774  return;
25775  }
25776  if( pExpr->flags ){
25777  sqlite3_snprintf(sizeof(zFlgs),zFlgs," flags=0x%x",pExpr->flags);
25778  }else{
25779  zFlgs[0] = 0;
25780  }
25781  switch( pExpr->op ){
25782  case TK_AGG_COLUMN: {
25783  sqlite3TreeViewLine(pView, "AGG{%d:%d}%s",
25784  pExpr->iTable, pExpr->iColumn, zFlgs);
25785  break;
25786  }
25787  case TK_COLUMN: {
25788  if( pExpr->iTable<0 ){
25789  /* This only happens when coding check constraints */
25790  sqlite3TreeViewLine(pView, "COLUMN(%d)%s", pExpr->iColumn, zFlgs);
25791  }else{
25792  sqlite3TreeViewLine(pView, "{%d:%d}%s",
25793  pExpr->iTable, pExpr->iColumn, zFlgs);
25794  }
25795  break;
25796  }
25797  case TK_INTEGER: {
25798  if( pExpr->flags & EP_IntValue ){
25799  sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
25800  }else{
25801  sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
25802  }
25803  break;
25804  }
25805 #ifndef SQLITE_OMIT_FLOATING_POINT
25806  case TK_FLOAT: {
25807  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
25808  break;
25809  }
25810 #endif
25811  case TK_STRING: {
25812  sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
25813  break;
25814  }
25815  case TK_NULL: {
25816  sqlite3TreeViewLine(pView,"NULL");
25817  break;
25818  }
25819 #ifndef SQLITE_OMIT_BLOB_LITERAL
25820  case TK_BLOB: {
25821  sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
25822  break;
25823  }
25824 #endif
25825  case TK_VARIABLE: {
25826  sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
25827  pExpr->u.zToken, pExpr->iColumn);
25828  break;
25829  }
25830  case TK_REGISTER: {
25831  sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
25832  break;
25833  }
25834  case TK_ID: {
25835  sqlite3TreeViewLine(pView,"ID \"%w\"", pExpr->u.zToken);
25836  break;
25837  }
25838 #ifndef SQLITE_OMIT_CAST
25839  case TK_CAST: {
25840  /* Expressions of the form: CAST(pLeft AS token) */
25841  sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
25842  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
25843  break;
25844  }
25845 #endif /* SQLITE_OMIT_CAST */
25846  case TK_LT: zBinOp = "LT"; break;
25847  case TK_LE: zBinOp = "LE"; break;
25848  case TK_GT: zBinOp = "GT"; break;
25849  case TK_GE: zBinOp = "GE"; break;
25850  case TK_NE: zBinOp = "NE"; break;
25851  case TK_EQ: zBinOp = "EQ"; break;
25852  case TK_IS: zBinOp = "IS"; break;
25853  case TK_ISNOT: zBinOp = "ISNOT"; break;
25854  case TK_AND: zBinOp = "AND"; break;
25855  case TK_OR: zBinOp = "OR"; break;
25856  case TK_PLUS: zBinOp = "ADD"; break;
25857  case TK_STAR: zBinOp = "MUL"; break;
25858  case TK_MINUS: zBinOp = "SUB"; break;
25859  case TK_REM: zBinOp = "REM"; break;
25860  case TK_BITAND: zBinOp = "BITAND"; break;
25861  case TK_BITOR: zBinOp = "BITOR"; break;
25862  case TK_SLASH: zBinOp = "DIV"; break;
25863  case TK_LSHIFT: zBinOp = "LSHIFT"; break;
25864  case TK_RSHIFT: zBinOp = "RSHIFT"; break;
25865  case TK_CONCAT: zBinOp = "CONCAT"; break;
25866  case TK_DOT: zBinOp = "DOT"; break;
25867 
25868  case TK_UMINUS: zUniOp = "UMINUS"; break;
25869  case TK_UPLUS: zUniOp = "UPLUS"; break;
25870  case TK_BITNOT: zUniOp = "BITNOT"; break;
25871  case TK_NOT: zUniOp = "NOT"; break;
25872  case TK_ISNULL: zUniOp = "ISNULL"; break;
25873  case TK_NOTNULL: zUniOp = "NOTNULL"; break;
25874 
25875  case TK_SPAN: {
25876  sqlite3TreeViewLine(pView, "SPAN %Q", pExpr->u.zToken);
25877  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
25878  break;
25879  }
25880 
25881  case TK_COLLATE: {
25882  sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
25883  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
25884  break;
25885  }
25886 
25887  case TK_AGG_FUNCTION:
25888  case TK_FUNCTION: {
25889  ExprList *pFarg; /* List of function arguments */
25890  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
25891  pFarg = 0;
25892  }else{
25893  pFarg = pExpr->x.pList;
25894  }
25895  if( pExpr->op==TK_AGG_FUNCTION ){
25896  sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
25897  pExpr->op2, pExpr->u.zToken);
25898  }else{
25899  sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
25900  }
25901  if( pFarg ){
25902  sqlite3TreeViewExprList(pView, pFarg, 0, 0);
25903  }
25904  break;
25905  }
25906 #ifndef SQLITE_OMIT_SUBQUERY
25907  case TK_EXISTS: {
25908  sqlite3TreeViewLine(pView, "EXISTS-expr");
25909  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
25910  break;
25911  }
25912  case TK_SELECT: {
25913  sqlite3TreeViewLine(pView, "SELECT-expr");
25914  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
25915  break;
25916  }
25917  case TK_IN: {
25918  sqlite3TreeViewLine(pView, "IN");
25919  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
25920  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
25921  sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
25922  }else{
25923  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
25924  }
25925  break;
25926  }
25927 #endif /* SQLITE_OMIT_SUBQUERY */
25928 
25929  /*
25930  ** x BETWEEN y AND z
25931  **
25932  ** This is equivalent to
25933  **
25934  ** x>=y AND x<=z
25935  **
25936  ** X is stored in pExpr->pLeft.
25937  ** Y is stored in pExpr->pList->a[0].pExpr.
25938  ** Z is stored in pExpr->pList->a[1].pExpr.
25939  */
25940  case TK_BETWEEN: {
25941  Expr *pX = pExpr->pLeft;
25942  Expr *pY = pExpr->x.pList->a[0].pExpr;
25943  Expr *pZ = pExpr->x.pList->a[1].pExpr;
25944  sqlite3TreeViewLine(pView, "BETWEEN");
25945  sqlite3TreeViewExpr(pView, pX, 1);
25946  sqlite3TreeViewExpr(pView, pY, 1);
25947  sqlite3TreeViewExpr(pView, pZ, 0);
25948  break;
25949  }
25950  case TK_TRIGGER: {
25951  /* If the opcode is TK_TRIGGER, then the expression is a reference
25952  ** to a column in the new.* or old.* pseudo-tables available to
25953  ** trigger programs. In this case Expr.iTable is set to 1 for the
25954  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
25955  ** is set to the column of the pseudo-table to read, or to -1 to
25956  ** read the rowid field.
25957  */
25958  sqlite3TreeViewLine(pView, "%s(%d)",
25959  pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
25960  break;
25961  }
25962  case TK_CASE: {
25963  sqlite3TreeViewLine(pView, "CASE");
25964  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
25965  sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
25966  break;
25967  }
25968 #ifndef SQLITE_OMIT_TRIGGER
25969  case TK_RAISE: {
25970  const char *zType = "unk";
25971  switch( pExpr->affinity ){
25972  case OE_Rollback: zType = "rollback"; break;
25973  case OE_Abort: zType = "abort"; break;
25974  case OE_Fail: zType = "fail"; break;
25975  case OE_Ignore: zType = "ignore"; break;
25976  }
25977  sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
25978  break;
25979  }
25980 #endif
25981  default: {
25982  sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
25983  break;
25984  }
25985  }
25986  if( zBinOp ){
25987  sqlite3TreeViewLine(pView, "%s%s", zBinOp, zFlgs);
25988  sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
25989  sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
25990  }else if( zUniOp ){
25991  sqlite3TreeViewLine(pView, "%s%s", zUniOp, zFlgs);
25992  sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
25993  }
25994  sqlite3TreeViewPop(pView);
25995 }
25996 
25997 /*
25998 ** Generate a human-readable explanation of an expression list.
25999 */
26000 SQLITE_PRIVATE void sqlite3TreeViewExprList(
26001  TreeView *pView,
26002  const ExprList *pList,
26003  u8 moreToFollow,
26004  const char *zLabel
26005 ){
26006  int i;
26007  pView = sqlite3TreeViewPush(pView, moreToFollow);
26008  if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
26009  if( pList==0 ){
26010  sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
26011  }else{
26012  sqlite3TreeViewLine(pView, "%s", zLabel);
26013  for(i=0; i<pList->nExpr; i++){
26014  int j = pList->a[i].u.x.iOrderByCol;
26015  if( j ){
26016  sqlite3TreeViewPush(pView, 0);
26017  sqlite3TreeViewLine(pView, "iOrderByCol=%d", j);
26018  }
26019  sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
26020  if( j ) sqlite3TreeViewPop(pView);
26021  }
26022  }
26023  sqlite3TreeViewPop(pView);
26024 }
26025 
26026 #endif /* SQLITE_DEBUG */
26027 
26028 /************** End of treeview.c ********************************************/
26029 /************** Begin file random.c ******************************************/
26030 /*
26031 ** 2001 September 15
26032 **
26033 ** The author disclaims copyright to this source code. In place of
26034 ** a legal notice, here is a blessing:
26035 **
26036 ** May you do good and not evil.
26037 ** May you find forgiveness for yourself and forgive others.
26038 ** May you share freely, never taking more than you give.
26039 **
26040 *************************************************************************
26041 ** This file contains code to implement a pseudo-random number
26042 ** generator (PRNG) for SQLite.
26043 **
26044 ** Random numbers are used by some of the database backends in order
26045 ** to generate random integer keys for tables or random filenames.
26046 */
26047 /* #include "sqliteInt.h" */
26048 
26049 
26050 /* All threads share a single random number generator.
26051 ** This structure is the current state of the generator.
26052 */
26054  unsigned char isInit; /* True if initialized */
26055  unsigned char i, j; /* State variables */
26056  unsigned char s[256]; /* State variables */
26057 } sqlite3Prng;
26058 
26059 /*
26060 ** Return N random bytes.
26061 */
26063  unsigned char t;
26064  unsigned char *zBuf = pBuf;
26065 
26066  /* The "wsdPrng" macro will resolve to the pseudo-random number generator
26067  ** state vector. If writable static data is unsupported on the target,
26068  ** we have to locate the state vector at run-time. In the more common
26069  ** case where writable static data is supported, wsdPrng can refer directly
26070  ** to the "sqlite3Prng" state vector declared above.
26071  */
26072 #ifdef SQLITE_OMIT_WSD
26073  struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
26074 # define wsdPrng p[0]
26075 #else
26076 # define wsdPrng sqlite3Prng
26077 #endif
26078 
26079 #if SQLITE_THREADSAFE
26080  sqlite3_mutex *mutex;
26081 #endif
26082 
26083 #ifndef SQLITE_OMIT_AUTOINIT
26084  if( sqlite3_initialize() ) return;
26085 #endif
26086 
26087 #if SQLITE_THREADSAFE
26089 #endif
26090 
26091  sqlite3_mutex_enter(mutex);
26092  if( N<=0 || pBuf==0 ){
26093  wsdPrng.isInit = 0;
26094  sqlite3_mutex_leave(mutex);
26095  return;
26096  }
26097 
26098  /* Initialize the state of the random number generator once,
26099  ** the first time this routine is called. The seed value does
26100  ** not need to contain a lot of randomness since we are not
26101  ** trying to do secure encryption or anything like that...
26102  **
26103  ** Nothing in this file or anywhere else in SQLite does any kind of
26104  ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
26105  ** number generator) not as an encryption device.
26106  */
26107  if( !wsdPrng.isInit ){
26108  int i;
26109  char k[256];
26110  wsdPrng.j = 0;
26111  wsdPrng.i = 0;
26113  for(i=0; i<256; i++){
26114  wsdPrng.s[i] = (u8)i;
26115  }
26116  for(i=0; i<256; i++){
26117  wsdPrng.j += wsdPrng.s[i] + k[i];
26118  t = wsdPrng.s[wsdPrng.j];
26119  wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
26120  wsdPrng.s[i] = t;
26121  }
26122  wsdPrng.isInit = 1;
26123  }
26124 
26125  assert( N>0 );
26126  do{
26127  wsdPrng.i++;
26128  t = wsdPrng.s[wsdPrng.i];
26129  wsdPrng.j += t;
26130  wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
26131  wsdPrng.s[wsdPrng.j] = t;
26132  t += wsdPrng.s[wsdPrng.i];
26133  *(zBuf++) = wsdPrng.s[t];
26134  }while( --N );
26135  sqlite3_mutex_leave(mutex);
26136 }
26137 
26138 #ifndef SQLITE_OMIT_BUILTIN_TEST
26139 /*
26140 ** For testing purposes, we sometimes want to preserve the state of
26141 ** PRNG and restore the PRNG to its saved state at a later time, or
26142 ** to reset the PRNG to its initial state. These routines accomplish
26143 ** those tasks.
26144 **
26145 ** The sqlite3_test_control() interface calls these routines to
26146 ** control the PRNG.
26147 */
26150  memcpy(
26153  sizeof(sqlite3Prng)
26154  );
26155 }
26157  memcpy(
26160  sizeof(sqlite3Prng)
26161  );
26162 }
26163 #endif /* SQLITE_OMIT_BUILTIN_TEST */
26164 
26165 /************** End of random.c **********************************************/
26166 /************** Begin file threads.c *****************************************/
26167 /*
26168 ** 2012 July 21
26169 **
26170 ** The author disclaims copyright to this source code. In place of
26171 ** a legal notice, here is a blessing:
26172 **
26173 ** May you do good and not evil.
26174 ** May you find forgiveness for yourself and forgive others.
26175 ** May you share freely, never taking more than you give.
26176 **
26177 ******************************************************************************
26178 **
26179 ** This file presents a simple cross-platform threading interface for
26180 ** use internally by SQLite.
26181 **
26182 ** A "thread" can be created using sqlite3ThreadCreate(). This thread
26183 ** runs independently of its creator until it is joined using
26184 ** sqlite3ThreadJoin(), at which point it terminates.
26185 **
26186 ** Threads do not have to be real. It could be that the work of the
26187 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
26188 ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
26189 ** single threaded systems. Nothing in SQLite requires multiple threads.
26190 ** This interface exists so that applications that want to take advantage
26191 ** of multiple cores can do so, while also allowing applications to stay
26192 ** single-threaded if desired.
26193 */
26194 /* #include "sqliteInt.h" */
26195 #if SQLITE_OS_WIN
26196 /* # include "os_win.h" */
26197 #endif
26198 
26199 #if SQLITE_MAX_WORKER_THREADS>0
26200 
26201 /********************************* Unix Pthreads ****************************/
26202 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
26203 
26204 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26205 /* #include <pthread.h> */
26206 
26207 /* A running thread */
26209  pthread_t tid; /* Thread ID */
26210  int done; /* Set to true when thread finishes */
26211  void *pOut; /* Result returned by the thread */
26212  void *(*xTask)(void*); /* The thread routine */
26213  void *pIn; /* Argument to the thread */
26214 };
26215 
26216 /* Create a new thread */
26218  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26219  void *(*xTask)(void*), /* Routine to run in a separate thread */
26220  void *pIn /* Argument passed into xTask() */
26221 ){
26222  SQLiteThread *p;
26223  int rc;
26224 
26225  assert( ppThread!=0 );
26226  assert( xTask!=0 );
26227  /* This routine is never used in single-threaded mode */
26228  assert( sqlite3GlobalConfig.bCoreMutex!=0 );
26229 
26230  *ppThread = 0;
26231  p = sqlite3Malloc(sizeof(*p));
26232  if( p==0 ) return SQLITE_NOMEM_BKPT;
26233  memset(p, 0, sizeof(*p));
26234  p->xTask = xTask;
26235  p->pIn = pIn;
26236  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26237  ** function that returns SQLITE_ERROR when passed the argument 200, that
26238  ** forces worker threads to run sequentially and deterministically
26239  ** for testing purposes. */
26240  if( sqlite3FaultSim(200) ){
26241  rc = 1;
26242  }else{
26243  rc = pthread_create(&p->tid, 0, xTask, pIn);
26244  }
26245  if( rc ){
26246  p->done = 1;
26247  p->pOut = xTask(pIn);
26248  }
26249  *ppThread = p;
26250  return SQLITE_OK;
26251 }
26252 
26253 /* Get the results of the thread */
26255  int rc;
26256 
26257  assert( ppOut!=0 );
26258  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26259  if( p->done ){
26260  *ppOut = p->pOut;
26261  rc = SQLITE_OK;
26262  }else{
26263  rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
26264  }
26265  sqlite3_free(p);
26266  return rc;
26267 }
26268 
26269 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
26270 /******************************** End Unix Pthreads *************************/
26271 
26272 
26273 /********************************* Win32 Threads ****************************/
26274 #if SQLITE_OS_WIN_THREADS
26275 
26276 #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
26277 #include <process.h>
26278 
26279 /* A running thread */
26280 struct SQLiteThread {
26281  void *tid; /* The thread handle */
26282  unsigned id; /* The thread identifier */
26283  void *(*xTask)(void*); /* The routine to run as a thread */
26284  void *pIn; /* Argument to xTask */
26285  void *pResult; /* Result of xTask */
26286 };
26287 
26288 /* Thread procedure Win32 compatibility shim */
26289 static unsigned __stdcall sqlite3ThreadProc(
26290  void *pArg /* IN: Pointer to the SQLiteThread structure */
26291 ){
26292  SQLiteThread *p = (SQLiteThread *)pArg;
26293 
26294  assert( p!=0 );
26295 #if 0
26296  /*
26297  ** This assert appears to trigger spuriously on certain
26298  ** versions of Windows, possibly due to _beginthreadex()
26299  ** and/or CreateThread() not fully setting their thread
26300  ** ID parameter before starting the thread.
26301  */
26302  assert( p->id==GetCurrentThreadId() );
26303 #endif
26304  assert( p->xTask!=0 );
26305  p->pResult = p->xTask(p->pIn);
26306 
26307  _endthreadex(0);
26308  return 0; /* NOT REACHED */
26309 }
26310 
26311 /* Create a new thread */
26313  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26314  void *(*xTask)(void*), /* Routine to run in a separate thread */
26315  void *pIn /* Argument passed into xTask() */
26316 ){
26317  SQLiteThread *p;
26318 
26319  assert( ppThread!=0 );
26320  assert( xTask!=0 );
26321  *ppThread = 0;
26322  p = sqlite3Malloc(sizeof(*p));
26323  if( p==0 ) return SQLITE_NOMEM_BKPT;
26324  /* If the SQLITE_TESTCTRL_FAULT_INSTALL callback is registered to a
26325  ** function that returns SQLITE_ERROR when passed the argument 200, that
26326  ** forces worker threads to run sequentially and deterministically
26327  ** (via the sqlite3FaultSim() term of the conditional) for testing
26328  ** purposes. */
26329  if( sqlite3GlobalConfig.bCoreMutex==0 || sqlite3FaultSim(200) ){
26330  memset(p, 0, sizeof(*p));
26331  }else{
26332  p->xTask = xTask;
26333  p->pIn = pIn;
26334  p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
26335  if( p->tid==0 ){
26336  memset(p, 0, sizeof(*p));
26337  }
26338  }
26339  if( p->xTask==0 ){
26340  p->id = GetCurrentThreadId();
26341  p->pResult = xTask(pIn);
26342  }
26343  *ppThread = p;
26344  return SQLITE_OK;
26345 }
26346 
26347 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
26348 
26349 /* Get the results of the thread */
26350 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26351  DWORD rc;
26352  BOOL bRc;
26353 
26354  assert( ppOut!=0 );
26355  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26356  if( p->xTask==0 ){
26357  /* assert( p->id==GetCurrentThreadId() ); */
26358  rc = WAIT_OBJECT_0;
26359  assert( p->tid==0 );
26360  }else{
26361  assert( p->id!=0 && p->id!=GetCurrentThreadId() );
26362  rc = sqlite3Win32Wait((HANDLE)p->tid);
26363  assert( rc!=WAIT_IO_COMPLETION );
26364  bRc = CloseHandle((HANDLE)p->tid);
26365  assert( bRc );
26366  }
26367  if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
26368  sqlite3_free(p);
26369  return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
26370 }
26371 
26372 #endif /* SQLITE_OS_WIN_THREADS */
26373 /******************************** End Win32 Threads *************************/
26374 
26375 
26376 /********************************* Single-Threaded **************************/
26377 #ifndef SQLITE_THREADS_IMPLEMENTED
26378 /*
26379 ** This implementation does not actually create a new thread. It does the
26380 ** work of the thread in the main thread, when either the thread is created
26381 ** or when it is joined
26382 */
26383 
26384 /* A running thread */
26385 struct SQLiteThread {
26386  void *(*xTask)(void*); /* The routine to run as a thread */
26387  void *pIn; /* Argument to xTask */
26388  void *pResult; /* Result of xTask */
26389 };
26390 
26391 /* Create a new thread */
26393  SQLiteThread **ppThread, /* OUT: Write the thread object here */
26394  void *(*xTask)(void*), /* Routine to run in a separate thread */
26395  void *pIn /* Argument passed into xTask() */
26396 ){
26397  SQLiteThread *p;
26398 
26399  assert( ppThread!=0 );
26400  assert( xTask!=0 );
26401  *ppThread = 0;
26402  p = sqlite3Malloc(sizeof(*p));
26403  if( p==0 ) return SQLITE_NOMEM_BKPT;
26404  if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
26405  p->xTask = xTask;
26406  p->pIn = pIn;
26407  }else{
26408  p->xTask = 0;
26409  p->pResult = xTask(pIn);
26410  }
26411  *ppThread = p;
26412  return SQLITE_OK;
26413 }
26414 
26415 /* Get the results of the thread */
26416 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
26417 
26418  assert( ppOut!=0 );
26419  if( NEVER(p==0) ) return SQLITE_NOMEM_BKPT;
26420  if( p->xTask ){
26421  *ppOut = p->xTask(p->pIn);
26422  }else{
26423  *ppOut = p->pResult;
26424  }
26425  sqlite3_free(p);
26426 
26427 #if defined(SQLITE_TEST)
26428  {
26429  void *pTstAlloc = sqlite3Malloc(10);
26430  if (!pTstAlloc) return SQLITE_NOMEM_BKPT;
26431  sqlite3_free(pTstAlloc);
26432  }
26433 #endif
26434 
26435  return SQLITE_OK;
26436 }
26437 
26438 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
26439 /****************************** End Single-Threaded *************************/
26440 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
26441 
26442 /************** End of threads.c *********************************************/
26443 /************** Begin file utf.c *********************************************/
26444 /*
26445 ** 2004 April 13
26446 **
26447 ** The author disclaims copyright to this source code. In place of
26448 ** a legal notice, here is a blessing:
26449 **
26450 ** May you do good and not evil.
26451 ** May you find forgiveness for yourself and forgive others.
26452 ** May you share freely, never taking more than you give.
26453 **
26454 *************************************************************************
26455 ** This file contains routines used to translate between UTF-8,
26456 ** UTF-16, UTF-16BE, and UTF-16LE.
26457 **
26458 ** Notes on UTF-8:
26459 **
26460 ** Byte-0 Byte-1 Byte-2 Byte-3 Value
26461 ** 0xxxxxxx 00000000 00000000 0xxxxxxx
26462 ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
26463 ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
26464 ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26465 **
26466 **
26467 ** Notes on UTF-16: (with wwww+1==uuuuu)
26468 **
26469 ** Word-0 Word-1 Value
26470 ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
26471 ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
26472 **
26473 **
26474 ** BOM or Byte Order Mark:
26475 ** 0xff 0xfe little-endian utf-16 follows
26476 ** 0xfe 0xff big-endian utf-16 follows
26477 **
26478 */
26479 /* #include "sqliteInt.h" */
26480 /* #include <assert.h> */
26481 /* #include "vdbeInt.h" */
26482 
26483 #if !defined(SQLITE_AMALGAMATION) && SQLITE_BYTEORDER==0
26484 /*
26485 ** The following constant value is used by the SQLITE_BIGENDIAN and
26486 ** SQLITE_LITTLEENDIAN macros.
26487 */
26488 SQLITE_PRIVATE const int sqlite3one = 1;
26489 #endif /* SQLITE_AMALGAMATION && SQLITE_BYTEORDER==0 */
26490 
26491 /*
26492 ** This lookup table is used to help decode the first byte of
26493 ** a multi-byte UTF8 character.
26494 */
26495 static const unsigned char sqlite3Utf8Trans1[] = {
26496  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26497  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26498  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
26499  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
26500  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26501  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
26502  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
26503  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
26504 };
26505 
26506 
26507 #define WRITE_UTF8(zOut, c) { \
26508  if( c<0x00080 ){ \
26509  *zOut++ = (u8)(c&0xFF); \
26510  } \
26511  else if( c<0x00800 ){ \
26512  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
26513  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26514  } \
26515  else if( c<0x10000 ){ \
26516  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
26517  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26518  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26519  }else{ \
26520  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
26521  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
26522  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
26523  *zOut++ = 0x80 + (u8)(c & 0x3F); \
26524  } \
26525 }
26526 
26527 #define WRITE_UTF16LE(zOut, c) { \
26528  if( c<=0xFFFF ){ \
26529  *zOut++ = (u8)(c&0x00FF); \
26530  *zOut++ = (u8)((c>>8)&0x00FF); \
26531  }else{ \
26532  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26533  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26534  *zOut++ = (u8)(c&0x00FF); \
26535  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26536  } \
26537 }
26538 
26539 #define WRITE_UTF16BE(zOut, c) { \
26540  if( c<=0xFFFF ){ \
26541  *zOut++ = (u8)((c>>8)&0x00FF); \
26542  *zOut++ = (u8)(c&0x00FF); \
26543  }else{ \
26544  *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
26545  *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
26546  *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
26547  *zOut++ = (u8)(c&0x00FF); \
26548  } \
26549 }
26550 
26551 #define READ_UTF16LE(zIn, TERM, c){ \
26552  c = (*zIn++); \
26553  c += ((*zIn++)<<8); \
26554  if( c>=0xD800 && c<0xE000 && TERM ){ \
26555  int c2 = (*zIn++); \
26556  c2 += ((*zIn++)<<8); \
26557  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26558  } \
26559 }
26560 
26561 #define READ_UTF16BE(zIn, TERM, c){ \
26562  c = ((*zIn++)<<8); \
26563  c += (*zIn++); \
26564  if( c>=0xD800 && c<0xE000 && TERM ){ \
26565  int c2 = ((*zIn++)<<8); \
26566  c2 += (*zIn++); \
26567  c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
26568  } \
26569 }
26570 
26571 /*
26572 ** Translate a single UTF-8 character. Return the unicode value.
26573 **
26574 ** During translation, assume that the byte that zTerm points
26575 ** is a 0x00.
26576 **
26577 ** Write a pointer to the next unread byte back into *pzNext.
26578 **
26579 ** Notes On Invalid UTF-8:
26580 **
26581 ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
26582 ** be encoded as a multi-byte character. Any multi-byte character that
26583 ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
26584 **
26585 ** * This routine never allows a UTF16 surrogate value to be encoded.
26586 ** If a multi-byte character attempts to encode a value between
26587 ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
26588 **
26589 ** * Bytes in the range of 0x80 through 0xbf which occur as the first
26590 ** byte of a character are interpreted as single-byte characters
26591 ** and rendered as themselves even though they are technically
26592 ** invalid characters.
26593 **
26594 ** * This routine accepts over-length UTF8 encodings
26595 ** for unicode values 0x80 and greater. It does not change over-length
26596 ** encodings to 0xfffd as some systems recommend.
26597 */
26598 #define READ_UTF8(zIn, zTerm, c) \
26599  c = *(zIn++); \
26600  if( c>=0xc0 ){ \
26601  c = sqlite3Utf8Trans1[c-0xc0]; \
26602  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
26603  c = (c<<6) + (0x3f & *(zIn++)); \
26604  } \
26605  if( c<0x80 \
26606  || (c&0xFFFFF800)==0xD800 \
26607  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
26608  }
26610  const unsigned char **pz /* Pointer to string from which to read char */
26611 ){
26612  unsigned int c;
26613 
26614  /* Same as READ_UTF8() above but without the zTerm parameter.
26615  ** For this routine, we assume the UTF8 string is always zero-terminated.
26616  */
26617  c = *((*pz)++);
26618  if( c>=0xc0 ){
26619  c = sqlite3Utf8Trans1[c-0xc0];
26620  while( (*(*pz) & 0xc0)==0x80 ){
26621  c = (c<<6) + (0x3f & *((*pz)++));
26622  }
26623  if( c<0x80
26624  || (c&0xFFFFF800)==0xD800
26625  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
26626  }
26627  return c;
26628 }
26629 
26630 
26631 
26632 
26633 /*
26634 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
26635 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
26636 */
26637 /* #define TRANSLATE_TRACE 1 */
26638 
26639 #ifndef SQLITE_OMIT_UTF16
26640 /*
26641 ** This routine transforms the internal text encoding used by pMem to
26642 ** desiredEnc. It is an error if the string is already of the desired
26643 ** encoding, or if *pMem does not contain a string value.
26644 */
26646  int len; /* Maximum length of output string in bytes */
26647  unsigned char *zOut; /* Output buffer */
26648  unsigned char *zIn; /* Input iterator */
26649  unsigned char *zTerm; /* End of input */
26650  unsigned char *z; /* Output iterator */
26651  unsigned int c;
26652 
26653  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
26654  assert( pMem->flags&MEM_Str );
26655  assert( pMem->enc!=desiredEnc );
26656  assert( pMem->enc!=0 );
26657  assert( pMem->n>=0 );
26658 
26659 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26660  {
26661  char zBuf[100];
26662  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26663  fprintf(stderr, "INPUT: %s\n", zBuf);
26664  }
26665 #endif
26666 
26667  /* If the translation is between UTF-16 little and big endian, then
26668  ** all that is required is to swap the byte order. This case is handled
26669  ** differently from the others.
26670  */
26671  if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
26672  u8 temp;
26673  int rc;
26674  rc = sqlite3VdbeMemMakeWriteable(pMem);
26675  if( rc!=SQLITE_OK ){
26676  assert( rc==SQLITE_NOMEM );
26677  return SQLITE_NOMEM_BKPT;
26678  }
26679  zIn = (u8*)pMem->z;
26680  zTerm = &zIn[pMem->n&~1];
26681  while( zIn<zTerm ){
26682  temp = *zIn;
26683  *zIn = *(zIn+1);
26684  zIn++;
26685  *zIn++ = temp;
26686  }
26687  pMem->enc = desiredEnc;
26688  goto translate_out;
26689  }
26690 
26691  /* Set len to the maximum number of bytes required in the output buffer. */
26692  if( desiredEnc==SQLITE_UTF8 ){
26693  /* When converting from UTF-16, the maximum growth results from
26694  ** translating a 2-byte character to a 4-byte UTF-8 character.
26695  ** A single byte is required for the output string
26696  ** nul-terminator.
26697  */
26698  pMem->n &= ~1;
26699  len = pMem->n * 2 + 1;
26700  }else{
26701  /* When converting from UTF-8 to UTF-16 the maximum growth is caused
26702  ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
26703  ** character. Two bytes are required in the output buffer for the
26704  ** nul-terminator.
26705  */
26706  len = pMem->n * 2 + 2;
26707  }
26708 
26709  /* Set zIn to point at the start of the input buffer and zTerm to point 1
26710  ** byte past the end.
26711  **
26712  ** Variable zOut is set to point at the output buffer, space obtained
26713  ** from sqlite3_malloc().
26714  */
26715  zIn = (u8*)pMem->z;
26716  zTerm = &zIn[pMem->n];
26717  zOut = sqlite3DbMallocRaw(pMem->db, len);
26718  if( !zOut ){
26719  return SQLITE_NOMEM_BKPT;
26720  }
26721  z = zOut;
26722 
26723  if( pMem->enc==SQLITE_UTF8 ){
26724  if( desiredEnc==SQLITE_UTF16LE ){
26725  /* UTF-8 -> UTF-16 Little-endian */
26726  while( zIn<zTerm ){
26727  READ_UTF8(zIn, zTerm, c);
26728  WRITE_UTF16LE(z, c);
26729  }
26730  }else{
26731  assert( desiredEnc==SQLITE_UTF16BE );
26732  /* UTF-8 -> UTF-16 Big-endian */
26733  while( zIn<zTerm ){
26734  READ_UTF8(zIn, zTerm, c);
26735  WRITE_UTF16BE(z, c);
26736  }
26737  }
26738  pMem->n = (int)(z - zOut);
26739  *z++ = 0;
26740  }else{
26741  assert( desiredEnc==SQLITE_UTF8 );
26742  if( pMem->enc==SQLITE_UTF16LE ){
26743  /* UTF-16 Little-endian -> UTF-8 */
26744  while( zIn<zTerm ){
26745  READ_UTF16LE(zIn, zIn<zTerm, c);
26746  WRITE_UTF8(z, c);
26747  }
26748  }else{
26749  /* UTF-16 Big-endian -> UTF-8 */
26750  while( zIn<zTerm ){
26751  READ_UTF16BE(zIn, zIn<zTerm, c);
26752  WRITE_UTF8(z, c);
26753  }
26754  }
26755  pMem->n = (int)(z - zOut);
26756  }
26757  *z = 0;
26758  assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
26759 
26760  c = pMem->flags;
26761  sqlite3VdbeMemRelease(pMem);
26763  pMem->enc = desiredEnc;
26764  pMem->z = (char*)zOut;
26765  pMem->zMalloc = pMem->z;
26766  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
26767 
26768 translate_out:
26769 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
26770  {
26771  char zBuf[100];
26772  sqlite3VdbeMemPrettyPrint(pMem, zBuf);
26773  fprintf(stderr, "OUTPUT: %s\n", zBuf);
26774  }
26775 #endif
26776  return SQLITE_OK;
26777 }
26778 
26779 /*
26780 ** This routine checks for a byte-order mark at the beginning of the
26781 ** UTF-16 string stored in *pMem. If one is present, it is removed and
26782 ** the encoding of the Mem adjusted. This routine does not do any
26783 ** byte-swapping, it just sets Mem.enc appropriately.
26784 **
26785 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
26786 ** changed by this function.
26787 */
26789  int rc = SQLITE_OK;
26790  u8 bom = 0;
26791 
26792  assert( pMem->n>=0 );
26793  if( pMem->n>1 ){
26794  u8 b1 = *(u8 *)pMem->z;
26795  u8 b2 = *(((u8 *)pMem->z) + 1);
26796  if( b1==0xFE && b2==0xFF ){
26797  bom = SQLITE_UTF16BE;
26798  }
26799  if( b1==0xFF && b2==0xFE ){
26800  bom = SQLITE_UTF16LE;
26801  }
26802  }
26803 
26804  if( bom ){
26805  rc = sqlite3VdbeMemMakeWriteable(pMem);
26806  if( rc==SQLITE_OK ){
26807  pMem->n -= 2;
26808  memmove(pMem->z, &pMem->z[2], pMem->n);
26809  pMem->z[pMem->n] = '\0';
26810  pMem->z[pMem->n+1] = '\0';
26811  pMem->flags |= MEM_Term;
26812  pMem->enc = bom;
26813  }
26814  }
26815  return rc;
26816 }
26817 #endif /* SQLITE_OMIT_UTF16 */
26818 
26819 /*
26820 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
26821 ** return the number of unicode characters in pZ up to (but not including)
26822 ** the first 0x00 byte. If nByte is not less than zero, return the
26823 ** number of unicode characters in the first nByte of pZ (or up to
26824 ** the first 0x00, whichever comes first).
26825 */
26826 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
26827  int r = 0;
26828  const u8 *z = (const u8*)zIn;
26829  const u8 *zTerm;
26830  if( nByte>=0 ){
26831  zTerm = &z[nByte];
26832  }else{
26833  zTerm = (const u8*)(-1);
26834  }
26835  assert( z<=zTerm );
26836  while( *z!=0 && z<zTerm ){
26837  SQLITE_SKIP_UTF8(z);
26838  r++;
26839  }
26840  return r;
26841 }
26842 
26843 /* This test function is not currently used by the automated test-suite.
26844 ** Hence it is only available in debug builds.
26845 */
26846 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
26847 /*
26848 ** Translate UTF-8 to UTF-8.
26849 **
26850 ** This has the effect of making sure that the string is well-formed
26851 ** UTF-8. Miscoded characters are removed.
26852 **
26853 ** The translation is done in-place and aborted if the output
26854 ** overruns the input.
26855 */
26856 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
26857  unsigned char *zOut = zIn;
26858  unsigned char *zStart = zIn;
26859  u32 c;
26860 
26861  while( zIn[0] && zOut<=zIn ){
26862  c = sqlite3Utf8Read((const u8**)&zIn);
26863  if( c!=0xfffd ){
26864  WRITE_UTF8(zOut, c);
26865  }
26866  }
26867  *zOut = 0;
26868  return (int)(zOut - zStart);
26869 }
26870 #endif
26871 
26872 #ifndef SQLITE_OMIT_UTF16
26873 /*
26874 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
26875 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
26876 ** be freed by the calling function.
26877 **
26878 ** NULL is returned if there is an allocation error.
26879 */
26880 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
26881  Mem m;
26882  memset(&m, 0, sizeof(m));
26883  m.db = db;
26884  sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
26886  if( db->mallocFailed ){
26888  m.z = 0;
26889  }
26890  assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
26891  assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
26892  assert( m.z || db->mallocFailed );
26893  return m.z;
26894 }
26895 
26896 /*
26897 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
26898 ** Return the number of bytes in the first nChar unicode characters
26899 ** in pZ. nChar must be non-negative.
26900 */
26901 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
26902  int c;
26903  unsigned char const *z = zIn;
26904  int n = 0;
26905 
26907  while( n<nChar ){
26908  READ_UTF16BE(z, 1, c);
26909  n++;
26910  }
26911  }else{
26912  while( n<nChar ){
26913  READ_UTF16LE(z, 1, c);
26914  n++;
26915  }
26916  }
26917  return (int)(z-(unsigned char const *)zIn);
26918 }
26919 
26920 #if defined(SQLITE_TEST)
26921 /*
26922 ** This routine is called from the TCL test function "translate_selftest".
26923 ** It checks that the primitives for serializing and deserializing
26924 ** characters in each encoding are inverses of each other.
26925 */
26926 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
26927  unsigned int i, t;
26928  unsigned char zBuf[20];
26929  unsigned char *z;
26930  int n;
26931  unsigned int c;
26932 
26933  for(i=0; i<0x00110000; i++){
26934  z = zBuf;
26935  WRITE_UTF8(z, i);
26936  n = (int)(z-zBuf);
26937  assert( n>0 && n<=4 );
26938  z[0] = 0;
26939  z = zBuf;
26940  c = sqlite3Utf8Read((const u8**)&z);
26941  t = i;
26942  if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
26943  if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
26944  assert( c==t );
26945  assert( (z-zBuf)==n );
26946  }
26947  for(i=0; i<0x00110000; i++){
26948  if( i>=0xD800 && i<0xE000 ) continue;
26949  z = zBuf;
26950  WRITE_UTF16LE(z, i);
26951  n = (int)(z-zBuf);
26952  assert( n>0 && n<=4 );
26953  z[0] = 0;
26954  z = zBuf;
26955  READ_UTF16LE(z, 1, c);
26956  assert( c==i );
26957  assert( (z-zBuf)==n );
26958  }
26959  for(i=0; i<0x00110000; i++){
26960  if( i>=0xD800 && i<0xE000 ) continue;
26961  z = zBuf;
26962  WRITE_UTF16BE(z, i);
26963  n = (int)(z-zBuf);
26964  assert( n>0 && n<=4 );
26965  z[0] = 0;
26966  z = zBuf;
26967  READ_UTF16BE(z, 1, c);
26968  assert( c==i );
26969  assert( (z-zBuf)==n );
26970  }
26971 }
26972 #endif /* SQLITE_TEST */
26973 #endif /* SQLITE_OMIT_UTF16 */
26974 
26975 /************** End of utf.c *************************************************/
26976 /************** Begin file util.c ********************************************/
26977 /*
26978 ** 2001 September 15
26979 **
26980 ** The author disclaims copyright to this source code. In place of
26981 ** a legal notice, here is a blessing:
26982 **
26983 ** May you do good and not evil.
26984 ** May you find forgiveness for yourself and forgive others.
26985 ** May you share freely, never taking more than you give.
26986 **
26987 *************************************************************************
26988 ** Utility functions used throughout sqlite.
26989 **
26990 ** This file contains functions for allocating memory, comparing
26991 ** strings, and stuff like that.
26992 **
26993 */
26994 /* #include "sqliteInt.h" */
26995 /* #include <stdarg.h> */
26996 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
26997 # include <math.h>
26998 #endif
26999 
27000 /*
27001 ** Routine needed to support the testcase() macro.
27002 */
27003 #ifdef SQLITE_COVERAGE_TEST
27004 SQLITE_PRIVATE void sqlite3Coverage(int x){
27005  static unsigned dummy = 0;
27006  dummy += (unsigned)x;
27007 }
27008 #endif
27009 
27010 /*
27011 ** Give a callback to the test harness that can be used to simulate faults
27012 ** in places where it is difficult or expensive to do so purely by means
27013 ** of inputs.
27014 **
27015 ** The intent of the integer argument is to let the fault simulator know
27016 ** which of multiple sqlite3FaultSim() calls has been hit.
27017 **
27018 ** Return whatever integer value the test callback returns, or return
27019 ** SQLITE_OK if no test callback is installed.
27020 */
27021 #ifndef SQLITE_OMIT_BUILTIN_TEST
27023  int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
27024  return xCallback ? xCallback(iTest) : SQLITE_OK;
27025 }
27026 #endif
27027 
27028 #ifndef SQLITE_OMIT_FLOATING_POINT
27029 /*
27030 ** Return true if the floating point value is Not a Number (NaN).
27031 **
27032 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
27033 ** Otherwise, we have our own implementation that works on most systems.
27034 */
27036  int rc; /* The value return */
27037 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
27038  /*
27039  ** Systems that support the isnan() library function should probably
27040  ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
27041  ** found that many systems do not have a working isnan() function so
27042  ** this implementation is provided as an alternative.
27043  **
27044  ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
27045  ** On the other hand, the use of -ffast-math comes with the following
27046  ** warning:
27047  **
27048  ** This option [-ffast-math] should never be turned on by any
27049  ** -O option since it can result in incorrect output for programs
27050  ** which depend on an exact implementation of IEEE or ISO
27051  ** rules/specifications for math functions.
27052  **
27053  ** Under MSVC, this NaN test may fail if compiled with a floating-
27054  ** point precision mode other than /fp:precise. From the MSDN
27055  ** documentation:
27056  **
27057  ** The compiler [with /fp:precise] will properly handle comparisons
27058  ** involving NaN. For example, x != x evaluates to true if x is NaN
27059  ** ...
27060  */
27061 #ifdef __FAST_MATH__
27062 # error SQLite will not work correctly with the -ffast-math option of GCC.
27063 #endif
27064  volatile double y = x;
27065  volatile double z = y;
27066  rc = (y!=z);
27067 #else /* if HAVE_ISNAN */
27068  rc = isnan(x);
27069 #endif /* HAVE_ISNAN */
27070  testcase( rc );
27071  return rc;
27072 }
27073 #endif /* SQLITE_OMIT_FLOATING_POINT */
27074 
27075 /*
27076 ** Compute a string length that is limited to what can be stored in
27077 ** lower 30 bits of a 32-bit signed integer.
27078 **
27079 ** The value returned will never be negative. Nor will it ever be greater
27080 ** than the actual length of the string. For very long strings (greater
27081 ** than 1GiB) the value returned might be less than the true string length.
27082 */
27084  if( z==0 ) return 0;
27085  return 0x3fffffff & (int)strlen(z);
27086 }
27087 
27088 /*
27089 ** Return the declared type of a column. Or return zDflt if the column
27090 ** has no declared type.
27091 **
27092 ** The column type is an extra string stored after the zero-terminator on
27093 ** the column name if and only if the COLFLAG_HASTYPE flag is set.
27094 */
27095 SQLITE_PRIVATE char *sqlite3ColumnType(Column *pCol, char *zDflt){
27096  if( (pCol->colFlags & COLFLAG_HASTYPE)==0 ) return zDflt;
27097  return pCol->zName + strlen(pCol->zName) + 1;
27098 }
27099 
27100 /*
27101 ** Helper function for sqlite3Error() - called rarely. Broken out into
27102 ** a separate routine to avoid unnecessary register saves on entry to
27103 ** sqlite3Error().
27104 */
27105 static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code){
27106  if( db->pErr ) sqlite3ValueSetNull(db->pErr);
27107  sqlite3SystemError(db, err_code);
27108 }
27109 
27110 /*
27111 ** Set the current error code to err_code and clear any prior error message.
27112 ** Also set iSysErrno (by calling sqlite3System) if the err_code indicates
27113 ** that would be appropriate.
27114 */
27115 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
27116  assert( db!=0 );
27117  db->errCode = err_code;
27118  if( err_code || db->pErr ) sqlite3ErrorFinish(db, err_code);
27119 }
27120 
27121 /*
27122 ** Load the sqlite3.iSysErrno field if that is an appropriate thing
27123 ** to do based on the SQLite error code in rc.
27124 */
27126  if( rc==SQLITE_IOERR_NOMEM ) return;
27127  rc &= 0xff;
27128  if( rc==SQLITE_CANTOPEN || rc==SQLITE_IOERR ){
27130  }
27131 }
27132 
27133 /*
27134 ** Set the most recent error code and error string for the sqlite
27135 ** handle "db". The error code is set to "err_code".
27136 **
27137 ** If it is not NULL, string zFormat specifies the format of the
27138 ** error string in the style of the printf functions: The following
27139 ** format characters are allowed:
27140 **
27141 ** %s Insert a string
27142 ** %z A string that should be freed after use
27143 ** %d Insert an integer
27144 ** %T Insert a token
27145 ** %S Insert the first element of a SrcList
27146 **
27147 ** zFormat and any string tokens that follow it are assumed to be
27148 ** encoded in UTF-8.
27149 **
27150 ** To clear the most recent error for sqlite handle "db", sqlite3Error
27151 ** should be called with err_code set to SQLITE_OK and zFormat set
27152 ** to NULL.
27153 */
27154 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
27155  assert( db!=0 );
27156  db->errCode = err_code;
27157  sqlite3SystemError(db, err_code);
27158  if( zFormat==0 ){
27159  sqlite3Error(db, err_code);
27160  }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
27161  char *z;
27162  va_list ap;
27163  va_start(ap, zFormat);
27164  z = sqlite3VMPrintf(db, zFormat, ap);
27165  va_end(ap);
27167  }
27168 }
27169 
27170 /*
27171 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
27172 ** The following formatting characters are allowed:
27173 **
27174 ** %s Insert a string
27175 ** %z A string that should be freed after use
27176 ** %d Insert an integer
27177 ** %T Insert a token
27178 ** %S Insert the first element of a SrcList
27179 **
27180 ** This function should be used to report any error that occurs while
27181 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
27182 ** last thing the sqlite3_prepare() function does is copy the error
27183 ** stored by this function into the database handle using sqlite3Error().
27184 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
27185 ** during statement execution (sqlite3_step() etc.).
27186 */
27187 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
27188  char *zMsg;
27189  va_list ap;
27190  sqlite3 *db = pParse->db;
27191  va_start(ap, zFormat);
27192  zMsg = sqlite3VMPrintf(db, zFormat, ap);
27193  va_end(ap);
27194  if( db->suppressErr ){
27195  sqlite3DbFree(db, zMsg);
27196  }else{
27197  pParse->nErr++;
27198  sqlite3DbFree(db, pParse->zErrMsg);
27199  pParse->zErrMsg = zMsg;
27200  pParse->rc = SQLITE_ERROR;
27201  }
27202 }
27203 
27204 /*
27205 ** Convert an SQL-style quoted string into a normal string by removing
27206 ** the quote characters. The conversion is done in-place. If the
27207 ** input does not begin with a quote character, then this routine
27208 ** is a no-op.
27209 **
27210 ** The input string must be zero-terminated. A new zero-terminator
27211 ** is added to the dequoted string.
27212 **
27213 ** The return value is -1 if no dequoting occurs or the length of the
27214 ** dequoted string, exclusive of the zero terminator, if dequoting does
27215 ** occur.
27216 **
27217 ** 2002-Feb-14: This routine is extended to remove MS-Access style
27218 ** brackets from around identifiers. For example: "[a-b-c]" becomes
27219 ** "a-b-c".
27220 */
27222  char quote;
27223  int i, j;
27224  if( z==0 ) return;
27225  quote = z[0];
27226  if( !sqlite3Isquote(quote) ) return;
27227  if( quote=='[' ) quote = ']';
27228  for(i=1, j=0;; i++){
27229  assert( z[i] );
27230  if( z[i]==quote ){
27231  if( z[i+1]==quote ){
27232  z[j++] = quote;
27233  i++;
27234  }else{
27235  break;
27236  }
27237  }else{
27238  z[j++] = z[i];
27239  }
27240  }
27241  z[j] = 0;
27242 }
27243 
27244 /*
27245 ** Generate a Token object from a string
27246 */
27248  p->z = z;
27249  p->n = sqlite3Strlen30(z);
27250 }
27251 
27252 /* Convenient short-hand */
27253 #define UpperToLower sqlite3UpperToLower
27254 
27255 /*
27256 ** Some systems have stricmp(). Others have strcasecmp(). Because
27257 ** there is no consistency, we will define our own.
27258 **
27259 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
27260 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
27261 ** the contents of two buffers containing UTF-8 strings in a
27262 ** case-independent fashion, using the same definition of "case
27263 ** independence" that SQLite uses internally when comparing identifiers.
27264 */
27265 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
27266  if( zLeft==0 ){
27267  return zRight ? -1 : 0;
27268  }else if( zRight==0 ){
27269  return 1;
27270  }
27271  return sqlite3StrICmp(zLeft, zRight);
27272 }
27273 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
27274  unsigned char *a, *b;
27275  int c;
27276  a = (unsigned char *)zLeft;
27277  b = (unsigned char *)zRight;
27278  for(;;){
27279  c = (int)UpperToLower[*a] - (int)UpperToLower[*b];
27280  if( c || *a==0 ) break;
27281  a++;
27282  b++;
27283  }
27284  return c;
27285 }
27286 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
27287  register unsigned char *a, *b;
27288  if( zLeft==0 ){
27289  return zRight ? -1 : 0;
27290  }else if( zRight==0 ){
27291  return 1;
27292  }
27293  a = (unsigned char *)zLeft;
27294  b = (unsigned char *)zRight;
27295  while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
27296  return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
27297 }
27298 
27299 /*
27300 ** The string z[] is an text representation of a real number.
27301 ** Convert this string to a double and write it into *pResult.
27302 **
27303 ** The string z[] is length bytes in length (bytes, not characters) and
27304 ** uses the encoding enc. The string is not necessarily zero-terminated.
27305 **
27306 ** Return TRUE if the result is a valid real number (or integer) and FALSE
27307 ** if the string is empty or contains extraneous text. Valid numbers
27308 ** are in one of these formats:
27309 **
27310 ** [+-]digits[E[+-]digits]
27311 ** [+-]digits.[digits][E[+-]digits]
27312 ** [+-].digits[E[+-]digits]
27313 **
27314 ** Leading and trailing whitespace is ignored for the purpose of determining
27315 ** validity.
27316 **
27317 ** If some prefix of the input string is a valid number, this routine
27318 ** returns FALSE but it still converts the prefix and writes the result
27319 ** into *pResult.
27320 */
27321 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
27322 #ifndef SQLITE_OMIT_FLOATING_POINT
27323  int incr;
27324  const char *zEnd = z + length;
27325  /* sign * significand * (10 ^ (esign * exponent)) */
27326  int sign = 1; /* sign of significand */
27327  i64 s = 0; /* significand */
27328  int d = 0; /* adjust exponent for shifting decimal point */
27329  int esign = 1; /* sign of exponent */
27330  int e = 0; /* exponent */
27331  int eValid = 1; /* True exponent is either not used or is well-formed */
27332  double result;
27333  int nDigits = 0;
27334  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27335 
27336  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27337  *pResult = 0.0; /* Default return value, in case of an error */
27338 
27339  if( enc==SQLITE_UTF8 ){
27340  incr = 1;
27341  }else{
27342  int i;
27343  incr = 2;
27344  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27345  for(i=3-enc; i<length && z[i]==0; i+=2){}
27346  nonNum = i<length;
27347  zEnd = &z[i^1];
27348  z += (enc&1);
27349  }
27350 
27351  /* skip leading spaces */
27352  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27353  if( z>=zEnd ) return 0;
27354 
27355  /* get sign of significand */
27356  if( *z=='-' ){
27357  sign = -1;
27358  z+=incr;
27359  }else if( *z=='+' ){
27360  z+=incr;
27361  }
27362 
27363  /* copy max significant digits to significand */
27364  while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
27365  s = s*10 + (*z - '0');
27366  z+=incr, nDigits++;
27367  }
27368 
27369  /* skip non-significant significand digits
27370  ** (increase exponent by d to shift decimal left) */
27371  while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
27372  if( z>=zEnd ) goto do_atof_calc;
27373 
27374  /* if decimal point is present */
27375  if( *z=='.' ){
27376  z+=incr;
27377  /* copy digits from after decimal to significand
27378  ** (decrease exponent by d to shift decimal right) */
27379  while( z<zEnd && sqlite3Isdigit(*z) ){
27380  if( s<((LARGEST_INT64-9)/10) ){
27381  s = s*10 + (*z - '0');
27382  d--;
27383  }
27384  z+=incr, nDigits++;
27385  }
27386  }
27387  if( z>=zEnd ) goto do_atof_calc;
27388 
27389  /* if exponent is present */
27390  if( *z=='e' || *z=='E' ){
27391  z+=incr;
27392  eValid = 0;
27393 
27394  /* This branch is needed to avoid a (harmless) buffer overread. The
27395  ** special comment alerts the mutation tester that the correct answer
27396  ** is obtained even if the branch is omitted */
27397  if( z>=zEnd ) goto do_atof_calc; /*PREVENTS-HARMLESS-OVERREAD*/
27398 
27399  /* get sign of exponent */
27400  if( *z=='-' ){
27401  esign = -1;
27402  z+=incr;
27403  }else if( *z=='+' ){
27404  z+=incr;
27405  }
27406  /* copy digits to exponent */
27407  while( z<zEnd && sqlite3Isdigit(*z) ){
27408  e = e<10000 ? (e*10 + (*z - '0')) : 10000;
27409  z+=incr;
27410  eValid = 1;
27411  }
27412  }
27413 
27414  /* skip trailing spaces */
27415  while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
27416 
27417 do_atof_calc:
27418  /* adjust exponent by d, and update sign */
27419  e = (e*esign) + d;
27420  if( e<0 ) {
27421  esign = -1;
27422  e *= -1;
27423  } else {
27424  esign = 1;
27425  }
27426 
27427  if( s==0 ) {
27428  /* In the IEEE 754 standard, zero is signed. */
27429  result = sign<0 ? -(double)0 : (double)0;
27430  } else {
27431  /* Attempt to reduce exponent.
27432  **
27433  ** Branches that are not required for the correct answer but which only
27434  ** help to obtain the correct answer faster are marked with special
27435  ** comments, as a hint to the mutation tester.
27436  */
27437  while( e>0 ){ /*OPTIMIZATION-IF-TRUE*/
27438  if( esign>0 ){
27439  if( s>=(LARGEST_INT64/10) ) break; /*OPTIMIZATION-IF-FALSE*/
27440  s *= 10;
27441  }else{
27442  if( s%10!=0 ) break; /*OPTIMIZATION-IF-FALSE*/
27443  s /= 10;
27444  }
27445  e--;
27446  }
27447 
27448  /* adjust the sign of significand */
27449  s = sign<0 ? -s : s;
27450 
27451  if( e==0 ){ /*OPTIMIZATION-IF-TRUE*/
27452  result = (double)s;
27453  }else{
27454  LONGDOUBLE_TYPE scale = 1.0;
27455  /* attempt to handle extremely small/large numbers better */
27456  if( e>307 ){ /*OPTIMIZATION-IF-TRUE*/
27457  if( e<342 ){ /*OPTIMIZATION-IF-TRUE*/
27458  while( e%308 ) { scale *= 1.0e+1; e -= 1; }
27459  if( esign<0 ){
27460  result = s / scale;
27461  result /= 1.0e+308;
27462  }else{
27463  result = s * scale;
27464  result *= 1.0e+308;
27465  }
27466  }else{ assert( e>=342 );
27467  if( esign<0 ){
27468  result = 0.0*s;
27469  }else{
27470  result = 1e308*1e308*s; /* Infinity */
27471  }
27472  }
27473  }else{
27474  /* 1.0e+22 is the largest power of 10 than can be
27475  ** represented exactly. */
27476  while( e%22 ) { scale *= 1.0e+1; e -= 1; }
27477  while( e>0 ) { scale *= 1.0e+22; e -= 22; }
27478  if( esign<0 ){
27479  result = s / scale;
27480  }else{
27481  result = s * scale;
27482  }
27483  }
27484  }
27485  }
27486 
27487  /* store the result */
27488  *pResult = result;
27489 
27490  /* return true if number and no extra non-whitespace chracters after */
27491  return z==zEnd && nDigits>0 && eValid && nonNum==0;
27492 #else
27493  return !sqlite3Atoi64(z, pResult, length, enc);
27494 #endif /* SQLITE_OMIT_FLOATING_POINT */
27495 }
27496 
27497 /*
27498 ** Compare the 19-character string zNum against the text representation
27499 ** value 2^63: 9223372036854775808. Return negative, zero, or positive
27500 ** if zNum is less than, equal to, or greater than the string.
27501 ** Note that zNum must contain exactly 19 characters.
27502 **
27503 ** Unlike memcmp() this routine is guaranteed to return the difference
27504 ** in the values of the last digit if the only difference is in the
27505 ** last digit. So, for example,
27506 **
27507 ** compare2pow63("9223372036854775800", 1)
27508 **
27509 ** will return -8.
27510 */
27511 static int compare2pow63(const char *zNum, int incr){
27512  int c = 0;
27513  int i;
27514  /* 012345678901234567 */
27515  const char *pow63 = "922337203685477580";
27516  for(i=0; c==0 && i<18; i++){
27517  c = (zNum[i*incr]-pow63[i])*10;
27518  }
27519  if( c==0 ){
27520  c = zNum[18*incr] - '8';
27521  testcase( c==(-1) );
27522  testcase( c==0 );
27523  testcase( c==(+1) );
27524  }
27525  return c;
27526 }
27527 
27528 /*
27529 ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
27530 ** routine does *not* accept hexadecimal notation.
27531 **
27532 ** If the zNum value is representable as a 64-bit twos-complement
27533 ** integer, then write that value into *pNum and return 0.
27534 **
27535 ** If zNum is exactly 9223372036854775808, return 2. This special
27536 ** case is broken out because while 9223372036854775808 cannot be a
27537 ** signed 64-bit integer, its negative -9223372036854775808 can be.
27538 **
27539 ** If zNum is too big for a 64-bit integer and is not
27540 ** 9223372036854775808 or if zNum contains any non-numeric text,
27541 ** then return 1.
27542 **
27543 ** length is the number of bytes in the string (bytes, not characters).
27544 ** The string is not necessarily zero-terminated. The encoding is
27545 ** given by enc.
27546 */
27547 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
27548  int incr;
27549  u64 u = 0;
27550  int neg = 0; /* assume positive */
27551  int i;
27552  int c = 0;
27553  int nonNum = 0; /* True if input contains UTF16 with high byte non-zero */
27554  const char *zStart;
27555  const char *zEnd = zNum + length;
27556  assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
27557  if( enc==SQLITE_UTF8 ){
27558  incr = 1;
27559  }else{
27560  incr = 2;
27561  assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
27562  for(i=3-enc; i<length && zNum[i]==0; i+=2){}
27563  nonNum = i<length;
27564  zEnd = &zNum[i^1];
27565  zNum += (enc&1);
27566  }
27567  while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
27568  if( zNum<zEnd ){
27569  if( *zNum=='-' ){
27570  neg = 1;
27571  zNum+=incr;
27572  }else if( *zNum=='+' ){
27573  zNum+=incr;
27574  }
27575  }
27576  zStart = zNum;
27577  while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
27578  for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
27579  u = u*10 + c - '0';
27580  }
27581  if( u>LARGEST_INT64 ){
27582  *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
27583  }else if( neg ){
27584  *pNum = -(i64)u;
27585  }else{
27586  *pNum = (i64)u;
27587  }
27588  testcase( i==18 );
27589  testcase( i==19 );
27590  testcase( i==20 );
27591  if( &zNum[i]<zEnd /* Extra bytes at the end */
27592  || (i==0 && zStart==zNum) /* No digits */
27593  || i>19*incr /* Too many digits */
27594  || nonNum /* UTF16 with high-order bytes non-zero */
27595  ){
27596  /* zNum is empty or contains non-numeric text or is longer
27597  ** than 19 digits (thus guaranteeing that it is too large) */
27598  return 1;
27599  }else if( i<19*incr ){
27600  /* Less than 19 digits, so we know that it fits in 64 bits */
27601  assert( u<=LARGEST_INT64 );
27602  return 0;
27603  }else{
27604  /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
27605  c = compare2pow63(zNum, incr);
27606  if( c<0 ){
27607  /* zNum is less than 9223372036854775808 so it fits */
27608  assert( u<=LARGEST_INT64 );
27609  return 0;
27610  }else if( c>0 ){
27611  /* zNum is greater than 9223372036854775808 so it overflows */
27612  return 1;
27613  }else{
27614  /* zNum is exactly 9223372036854775808. Fits if negative. The
27615  ** special case 2 overflow if positive */
27616  assert( u-1==LARGEST_INT64 );
27617  return neg ? 0 : 2;
27618  }
27619  }
27620 }
27621 
27622 /*
27623 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
27624 ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
27625 ** whereas sqlite3Atoi64() does not.
27626 **
27627 ** Returns:
27628 **
27629 ** 0 Successful transformation. Fits in a 64-bit signed integer.
27630 ** 1 Integer too large for a 64-bit signed integer or is malformed
27631 ** 2 Special case of 9223372036854775808
27632 */
27633 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
27634 #ifndef SQLITE_OMIT_HEX_INTEGER
27635  if( z[0]=='0'
27636  && (z[1]=='x' || z[1]=='X')
27637  ){
27638  u64 u = 0;
27639  int i, k;
27640  for(i=2; z[i]=='0'; i++){}
27641  for(k=i; sqlite3Isxdigit(z[k]); k++){
27642  u = u*16 + sqlite3HexToInt(z[k]);
27643  }
27644  memcpy(pOut, &u, 8);
27645  return (z[k]==0 && k-i<=16) ? 0 : 1;
27646  }else
27647 #endif /* SQLITE_OMIT_HEX_INTEGER */
27648  {
27649  return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
27650  }
27651 }
27652 
27653 /*
27654 ** If zNum represents an integer that will fit in 32-bits, then set
27655 ** *pValue to that integer and return true. Otherwise return false.
27656 **
27657 ** This routine accepts both decimal and hexadecimal notation for integers.
27658 **
27659 ** Any non-numeric characters that following zNum are ignored.
27660 ** This is different from sqlite3Atoi64() which requires the
27661 ** input number to be zero-terminated.
27662 */
27663 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
27664  sqlite_int64 v = 0;
27665  int i, c;
27666  int neg = 0;
27667  if( zNum[0]=='-' ){
27668  neg = 1;
27669  zNum++;
27670  }else if( zNum[0]=='+' ){
27671  zNum++;
27672  }
27673 #ifndef SQLITE_OMIT_HEX_INTEGER
27674  else if( zNum[0]=='0'
27675  && (zNum[1]=='x' || zNum[1]=='X')
27676  && sqlite3Isxdigit(zNum[2])
27677  ){
27678  u32 u = 0;
27679  zNum += 2;
27680  while( zNum[0]=='0' ) zNum++;
27681  for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
27682  u = u*16 + sqlite3HexToInt(zNum[i]);
27683  }
27684  if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
27685  memcpy(pValue, &u, 4);
27686  return 1;
27687  }else{
27688  return 0;
27689  }
27690  }
27691 #endif
27692  while( zNum[0]=='0' ) zNum++;
27693  for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
27694  v = v*10 + c;
27695  }
27696 
27697  /* The longest decimal representation of a 32 bit integer is 10 digits:
27698  **
27699  ** 1234567890
27700  ** 2^31 -> 2147483648
27701  */
27702  testcase( i==10 );
27703  if( i>10 ){
27704  return 0;
27705  }
27706  testcase( v-neg==2147483647 );
27707  if( v-neg>2147483647 ){
27708  return 0;
27709  }
27710  if( neg ){
27711  v = -v;
27712  }
27713  *pValue = (int)v;
27714  return 1;
27715 }
27716 
27717 /*
27718 ** Return a 32-bit integer value extracted from a string. If the
27719 ** string is not an integer, just return 0.
27720 */
27721 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
27722  int x = 0;
27723  if( z ) sqlite3GetInt32(z, &x);
27724  return x;
27725 }
27726 
27727 /*
27728 ** The variable-length integer encoding is as follows:
27729 **
27730 ** KEY:
27731 ** A = 0xxxxxxx 7 bits of data and one flag bit
27732 ** B = 1xxxxxxx 7 bits of data and one flag bit
27733 ** C = xxxxxxxx 8 bits of data
27734 **
27735 ** 7 bits - A
27736 ** 14 bits - BA
27737 ** 21 bits - BBA
27738 ** 28 bits - BBBA
27739 ** 35 bits - BBBBA
27740 ** 42 bits - BBBBBA
27741 ** 49 bits - BBBBBBA
27742 ** 56 bits - BBBBBBBA
27743 ** 64 bits - BBBBBBBBC
27744 */
27745 
27746 /*
27747 ** Write a 64-bit variable-length integer to memory starting at p[0].
27748 ** The length of data write will be between 1 and 9 bytes. The number
27749 ** of bytes written is returned.
27750 **
27751 ** A variable-length integer consists of the lower 7 bits of each byte
27752 ** for all bytes that have the 8th bit set and one byte with the 8th
27753 ** bit clear. Except, if we get to the 9th byte, it stores the full
27754 ** 8 bits and is the last byte.
27755 */
27756 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
27757  int i, j, n;
27758  u8 buf[10];
27759  if( v & (((u64)0xff000000)<<32) ){
27760  p[8] = (u8)v;
27761  v >>= 8;
27762  for(i=7; i>=0; i--){
27763  p[i] = (u8)((v & 0x7f) | 0x80);
27764  v >>= 7;
27765  }
27766  return 9;
27767  }
27768  n = 0;
27769  do{
27770  buf[n++] = (u8)((v & 0x7f) | 0x80);
27771  v >>= 7;
27772  }while( v!=0 );
27773  buf[0] &= 0x7f;
27774  assert( n<=9 );
27775  for(i=0, j=n-1; j>=0; j--, i++){
27776  p[i] = buf[j];
27777  }
27778  return n;
27779 }
27780 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
27781  if( v<=0x7f ){
27782  p[0] = v&0x7f;
27783  return 1;
27784  }
27785  if( v<=0x3fff ){
27786  p[0] = ((v>>7)&0x7f)|0x80;
27787  p[1] = v&0x7f;
27788  return 2;
27789  }
27790  return putVarint64(p,v);
27791 }
27792 
27793 /*
27794 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
27795 ** are defined here rather than simply putting the constant expressions
27796 ** inline in order to work around bugs in the RVT compiler.
27797 **
27798 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
27799 **
27800 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
27801 */
27802 #define SLOT_2_0 0x001fc07f
27803 #define SLOT_4_2_0 0xf01fc07f
27804 
27805 
27806 /*
27807 ** Read a 64-bit variable-length integer from memory starting at p[0].
27808 ** Return the number of bytes read. The value is stored in *v.
27809 */
27810 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
27811  u32 a,b,s;
27812 
27813  a = *p;
27814  /* a: p0 (unmasked) */
27815  if (!(a&0x80))
27816  {
27817  *v = a;
27818  return 1;
27819  }
27820 
27821  p++;
27822  b = *p;
27823  /* b: p1 (unmasked) */
27824  if (!(b&0x80))
27825  {
27826  a &= 0x7f;
27827  a = a<<7;
27828  a |= b;
27829  *v = a;
27830  return 2;
27831  }
27832 
27833  /* Verify that constants are precomputed correctly */
27834  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
27835  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
27836 
27837  p++;
27838  a = a<<14;
27839  a |= *p;
27840  /* a: p0<<14 | p2 (unmasked) */
27841  if (!(a&0x80))
27842  {
27843  a &= SLOT_2_0;
27844  b &= 0x7f;
27845  b = b<<7;
27846  a |= b;
27847  *v = a;
27848  return 3;
27849  }
27850 
27851  /* CSE1 from below */
27852  a &= SLOT_2_0;
27853  p++;
27854  b = b<<14;
27855  b |= *p;
27856  /* b: p1<<14 | p3 (unmasked) */
27857  if (!(b&0x80))
27858  {
27859  b &= SLOT_2_0;
27860  /* moved CSE1 up */
27861  /* a &= (0x7f<<14)|(0x7f); */
27862  a = a<<7;
27863  a |= b;
27864  *v = a;
27865  return 4;
27866  }
27867 
27868  /* a: p0<<14 | p2 (masked) */
27869  /* b: p1<<14 | p3 (unmasked) */
27870  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
27871  /* moved CSE1 up */
27872  /* a &= (0x7f<<14)|(0x7f); */
27873  b &= SLOT_2_0;
27874  s = a;
27875  /* s: p0<<14 | p2 (masked) */
27876 
27877  p++;
27878  a = a<<14;
27879  a |= *p;
27880  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
27881  if (!(a&0x80))
27882  {
27883  /* we can skip these cause they were (effectively) done above
27884  ** while calculating s */
27885  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
27886  /* b &= (0x7f<<14)|(0x7f); */
27887  b = b<<7;
27888  a |= b;
27889  s = s>>18;
27890  *v = ((u64)s)<<32 | a;
27891  return 5;
27892  }
27893 
27894  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
27895  s = s<<7;
27896  s |= b;
27897  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
27898 
27899  p++;
27900  b = b<<14;
27901  b |= *p;
27902  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
27903  if (!(b&0x80))
27904  {
27905  /* we can skip this cause it was (effectively) done above in calc'ing s */
27906  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
27907  a &= SLOT_2_0;
27908  a = a<<7;
27909  a |= b;
27910  s = s>>18;
27911  *v = ((u64)s)<<32 | a;
27912  return 6;
27913  }
27914 
27915  p++;
27916  a = a<<14;
27917  a |= *p;
27918  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
27919  if (!(a&0x80))
27920  {
27921  a &= SLOT_4_2_0;
27922  b &= SLOT_2_0;
27923  b = b<<7;
27924  a |= b;
27925  s = s>>11;
27926  *v = ((u64)s)<<32 | a;
27927  return 7;
27928  }
27929 
27930  /* CSE2 from below */
27931  a &= SLOT_2_0;
27932  p++;
27933  b = b<<14;
27934  b |= *p;
27935  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
27936  if (!(b&0x80))
27937  {
27938  b &= SLOT_4_2_0;
27939  /* moved CSE2 up */
27940  /* a &= (0x7f<<14)|(0x7f); */
27941  a = a<<7;
27942  a |= b;
27943  s = s>>4;
27944  *v = ((u64)s)<<32 | a;
27945  return 8;
27946  }
27947 
27948  p++;
27949  a = a<<15;
27950  a |= *p;
27951  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
27952 
27953  /* moved CSE2 up */
27954  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
27955  b &= SLOT_2_0;
27956  b = b<<8;
27957  a |= b;
27958 
27959  s = s<<4;
27960  b = p[-4];
27961  b &= 0x7f;
27962  b = b>>3;
27963  s |= b;
27964 
27965  *v = ((u64)s)<<32 | a;
27966 
27967  return 9;
27968 }
27969 
27970 /*
27971 ** Read a 32-bit variable-length integer from memory starting at p[0].
27972 ** Return the number of bytes read. The value is stored in *v.
27973 **
27974 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
27975 ** integer, then set *v to 0xffffffff.
27976 **
27977 ** A MACRO version, getVarint32, is provided which inlines the
27978 ** single-byte case. All code should use the MACRO version as
27979 ** this function assumes the single-byte case has already been handled.
27980 */
27981 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
27982  u32 a,b;
27983 
27984  /* The 1-byte case. Overwhelmingly the most common. Handled inline
27985  ** by the getVarin32() macro */
27986  a = *p;
27987  /* a: p0 (unmasked) */
27988 #ifndef getVarint32
27989  if (!(a&0x80))
27990  {
27991  /* Values between 0 and 127 */
27992  *v = a;
27993  return 1;
27994  }
27995 #endif
27996 
27997  /* The 2-byte case */
27998  p++;
27999  b = *p;
28000  /* b: p1 (unmasked) */
28001  if (!(b&0x80))
28002  {
28003  /* Values between 128 and 16383 */
28004  a &= 0x7f;
28005  a = a<<7;
28006  *v = a | b;
28007  return 2;
28008  }
28009 
28010  /* The 3-byte case */
28011  p++;
28012  a = a<<14;
28013  a |= *p;
28014  /* a: p0<<14 | p2 (unmasked) */
28015  if (!(a&0x80))
28016  {
28017  /* Values between 16384 and 2097151 */
28018  a &= (0x7f<<14)|(0x7f);
28019  b &= 0x7f;
28020  b = b<<7;
28021  *v = a | b;
28022  return 3;
28023  }
28024 
28025  /* A 32-bit varint is used to store size information in btrees.
28026  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
28027  ** A 3-byte varint is sufficient, for example, to record the size
28028  ** of a 1048569-byte BLOB or string.
28029  **
28030  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
28031  ** rare larger cases can be handled by the slower 64-bit varint
28032  ** routine.
28033  */
28034 #if 1
28035  {
28036  u64 v64;
28037  u8 n;
28038 
28039  p -= 2;
28040  n = sqlite3GetVarint(p, &v64);
28041  assert( n>3 && n<=9 );
28042  if( (v64 & SQLITE_MAX_U32)!=v64 ){
28043  *v = 0xffffffff;
28044  }else{
28045  *v = (u32)v64;
28046  }
28047  return n;
28048  }
28049 
28050 #else
28051  /* For following code (kept for historical record only) shows an
28052  ** unrolling for the 3- and 4-byte varint cases. This code is
28053  ** slightly faster, but it is also larger and much harder to test.
28054  */
28055  p++;
28056  b = b<<14;
28057  b |= *p;
28058  /* b: p1<<14 | p3 (unmasked) */
28059  if (!(b&0x80))
28060  {
28061  /* Values between 2097152 and 268435455 */
28062  b &= (0x7f<<14)|(0x7f);
28063  a &= (0x7f<<14)|(0x7f);
28064  a = a<<7;
28065  *v = a | b;
28066  return 4;
28067  }
28068 
28069  p++;
28070  a = a<<14;
28071  a |= *p;
28072  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
28073  if (!(a&0x80))
28074  {
28075  /* Values between 268435456 and 34359738367 */
28076  a &= SLOT_4_2_0;
28077  b &= SLOT_4_2_0;
28078  b = b<<7;
28079  *v = a | b;
28080  return 5;
28081  }
28082 
28083  /* We can only reach this point when reading a corrupt database
28084  ** file. In that case we are not in any hurry. Use the (relatively
28085  ** slow) general-purpose sqlite3GetVarint() routine to extract the
28086  ** value. */
28087  {
28088  u64 v64;
28089  u8 n;
28090 
28091  p -= 4;
28092  n = sqlite3GetVarint(p, &v64);
28093  assert( n>5 && n<=9 );
28094  *v = (u32)v64;
28095  return n;
28096  }
28097 #endif
28098 }
28099 
28100 /*
28101 ** Return the number of bytes that will be needed to store the given
28102 ** 64-bit integer.
28103 */
28105  int i;
28106  for(i=1; (v >>= 7)!=0; i++){ assert( i<10 ); }
28107  return i;
28108 }
28109 
28110 
28111 /*
28112 ** Read or write a four-byte big-endian integer value.
28113 */
28115 #if SQLITE_BYTEORDER==4321
28116  u32 x;
28117  memcpy(&x,p,4);
28118  return x;
28119 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28120  && defined(__GNUC__) && GCC_VERSION>=4003000
28121  u32 x;
28122  memcpy(&x,p,4);
28123  return __builtin_bswap32(x);
28124 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28125  && defined(_MSC_VER) && _MSC_VER>=1300
28126  u32 x;
28127  memcpy(&x,p,4);
28128  return _byteswap_ulong(x);
28129 #else
28130  testcase( p[0]&0x80 );
28131  return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
28132 #endif
28133 }
28134 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
28135 #if SQLITE_BYTEORDER==4321
28136  memcpy(p,&v,4);
28137 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28138  && defined(__GNUC__) && GCC_VERSION>=4003000
28139  u32 x = __builtin_bswap32(v);
28140  memcpy(p,&x,4);
28141 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
28142  && defined(_MSC_VER) && _MSC_VER>=1300
28143  u32 x = _byteswap_ulong(v);
28144  memcpy(p,&x,4);
28145 #else
28146  p[0] = (u8)(v>>24);
28147  p[1] = (u8)(v>>16);
28148  p[2] = (u8)(v>>8);
28149  p[3] = (u8)v;
28150 #endif
28151 }
28152 
28153 
28154 
28155 /*
28156 ** Translate a single byte of Hex into an integer.
28157 ** This routine only works if h really is a valid hexadecimal
28158 ** character: 0..9a..fA..F
28159 */
28161  assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
28162 #ifdef SQLITE_ASCII
28163  h += 9*(1&(h>>6));
28164 #endif
28165 #ifdef SQLITE_EBCDIC
28166  h += 9*(1&~(h>>4));
28167 #endif
28168  return (u8)(h & 0xf);
28169 }
28170 
28171 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
28172 /*
28173 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
28174 ** value. Return a pointer to its binary value. Space to hold the
28175 ** binary value has been obtained from malloc and must be freed by
28176 ** the calling routine.
28177 */
28178 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
28179  char *zBlob;
28180  int i;
28181 
28182  zBlob = (char *)sqlite3DbMallocRawNN(db, n/2 + 1);
28183  n--;
28184  if( zBlob ){
28185  for(i=0; i<n; i+=2){
28186  zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
28187  }
28188  zBlob[i/2] = 0;
28189  }
28190  return zBlob;
28191 }
28192 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
28193 
28194 /*
28195 ** Log an error that is an API call on a connection pointer that should
28196 ** not have been used. The "type" of connection pointer is given as the
28197 ** argument. The zType is a word like "NULL" or "closed" or "invalid".
28198 */
28199 static void logBadConnection(const char *zType){
28201  "API call with %s database connection pointer",
28202  zType
28203  );
28204 }
28205 
28206 /*
28207 ** Check to make sure we have a valid db pointer. This test is not
28208 ** foolproof but it does provide some measure of protection against
28209 ** misuse of the interface such as passing in db pointers that are
28210 ** NULL or which have been previously closed. If this routine returns
28211 ** 1 it means that the db pointer is valid and 0 if it should not be
28212 ** dereferenced for any reason. The calling function should invoke
28213 ** SQLITE_MISUSE immediately.
28214 **
28215 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
28216 ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
28217 ** open properly and is not fit for general use but which can be
28218 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
28219 */
28221  u32 magic;
28222  if( db==0 ){
28223  logBadConnection("NULL");
28224  return 0;
28225  }
28226  magic = db->magic;
28227  if( magic!=SQLITE_MAGIC_OPEN ){
28228  if( sqlite3SafetyCheckSickOrOk(db) ){
28229  testcase( sqlite3GlobalConfig.xLog!=0 );
28230  logBadConnection("unopened");
28231  }
28232  return 0;
28233  }else{
28234  return 1;
28235  }
28236 }
28238  u32 magic;
28239  magic = db->magic;
28240  if( magic!=SQLITE_MAGIC_SICK &&
28241  magic!=SQLITE_MAGIC_OPEN &&
28242  magic!=SQLITE_MAGIC_BUSY ){
28243  testcase( sqlite3GlobalConfig.xLog!=0 );
28244  logBadConnection("invalid");
28245  return 0;
28246  }else{
28247  return 1;
28248  }
28249 }
28250 
28251 /*
28252 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
28253 ** the other 64-bit signed integer at *pA and store the result in *pA.
28254 ** Return 0 on success. Or if the operation would have resulted in an
28255 ** overflow, leave *pA unchanged and return 1.
28256 */
28257 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
28258  i64 iA = *pA;
28259  testcase( iA==0 ); testcase( iA==1 );
28260  testcase( iB==-1 ); testcase( iB==0 );
28261  if( iB>=0 ){
28262  testcase( iA>0 && LARGEST_INT64 - iA == iB );
28263  testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
28264  if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
28265  }else{
28266  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
28267  testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
28268  if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
28269  }
28270  *pA += iB;
28271  return 0;
28272 }
28273 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
28274  testcase( iB==SMALLEST_INT64+1 );
28275  if( iB==SMALLEST_INT64 ){
28276  testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
28277  if( (*pA)>=0 ) return 1;
28278  *pA -= iB;
28279  return 0;
28280  }else{
28281  return sqlite3AddInt64(pA, -iB);
28282  }
28283 }
28284 #define TWOPOWER32 (((i64)1)<<32)
28285 #define TWOPOWER31 (((i64)1)<<31)
28286 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
28287  i64 iA = *pA;
28288  i64 iA1, iA0, iB1, iB0, r;
28289 
28290  iA1 = iA/TWOPOWER32;
28291  iA0 = iA % TWOPOWER32;
28292  iB1 = iB/TWOPOWER32;
28293  iB0 = iB % TWOPOWER32;
28294  if( iA1==0 ){
28295  if( iB1==0 ){
28296  *pA *= iB;
28297  return 0;
28298  }
28299  r = iA0*iB1;
28300  }else if( iB1==0 ){
28301  r = iA1*iB0;
28302  }else{
28303  /* If both iA1 and iB1 are non-zero, overflow will result */
28304  return 1;
28305  }
28306  testcase( r==(-TWOPOWER31)-1 );
28307  testcase( r==(-TWOPOWER31) );
28308  testcase( r==TWOPOWER31 );
28309  testcase( r==TWOPOWER31-1 );
28310  if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
28311  r *= TWOPOWER32;
28312  if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
28313  *pA = r;
28314  return 0;
28315 }
28316 
28317 /*
28318 ** Compute the absolute value of a 32-bit signed integer, of possible. Or
28319 ** if the integer has a value of -2147483648, return +2147483647
28320 */
28322  if( x>=0 ) return x;
28323  if( x==(int)0x80000000 ) return 0x7fffffff;
28324  return -x;
28325 }
28326 
28327 #ifdef SQLITE_ENABLE_8_3_NAMES
28328 /*
28329 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
28330 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
28331 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
28332 ** three characters, then shorten the suffix on z[] to be the last three
28333 ** characters of the original suffix.
28334 **
28335 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
28336 ** do the suffix shortening regardless of URI parameter.
28337 **
28338 ** Examples:
28339 **
28340 ** test.db-journal => test.nal
28341 ** test.db-wal => test.wal
28342 ** test.db-shm => test.shm
28343 ** test.db-mj7f3319fa => test.9fa
28344 */
28345 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
28346 #if SQLITE_ENABLE_8_3_NAMES<2
28347  if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
28348 #endif
28349  {
28350  int i, sz;
28351  sz = sqlite3Strlen30(z);
28352  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
28353  if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
28354  }
28355 }
28356 #endif
28357 
28358 /*
28359 ** Find (an approximate) sum of two LogEst values. This computation is
28360 ** not a simple "+" operator because LogEst is stored as a logarithmic
28361 ** value.
28362 **
28363 */
28364 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
28365  static const unsigned char x[] = {
28366  10, 10, /* 0,1 */
28367  9, 9, /* 2,3 */
28368  8, 8, /* 4,5 */
28369  7, 7, 7, /* 6,7,8 */
28370  6, 6, 6, /* 9,10,11 */
28371  5, 5, 5, /* 12-14 */
28372  4, 4, 4, 4, /* 15-18 */
28373  3, 3, 3, 3, 3, 3, /* 19-24 */
28374  2, 2, 2, 2, 2, 2, 2, /* 25-31 */
28375  };
28376  if( a>=b ){
28377  if( a>b+49 ) return a;
28378  if( a>b+31 ) return a+1;
28379  return a+x[a-b];
28380  }else{
28381  if( b>a+49 ) return b;
28382  if( b>a+31 ) return b+1;
28383  return b+x[b-a];
28384  }
28385 }
28386 
28387 /*
28388 ** Convert an integer into a LogEst. In other words, compute an
28389 ** approximation for 10*log2(x).
28390 */
28392  static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
28393  LogEst y = 40;
28394  if( x<8 ){
28395  if( x<2 ) return 0;
28396  while( x<8 ){ y -= 10; x <<= 1; }
28397  }else{
28398  while( x>255 ){ y += 40; x >>= 4; } /*OPTIMIZATION-IF-TRUE*/
28399  while( x>15 ){ y += 10; x >>= 1; }
28400  }
28401  return a[x&7] + y - 10;
28402 }
28403 
28404 #ifndef SQLITE_OMIT_VIRTUALTABLE
28405 /*
28406 ** Convert a double into a LogEst
28407 ** In other words, compute an approximation for 10*log2(x).
28408 */
28410  u64 a;
28411  LogEst e;
28412  assert( sizeof(x)==8 && sizeof(a)==8 );
28413  if( x<=1 ) return 0;
28414  if( x<=2000000000 ) return sqlite3LogEst((u64)x);
28415  memcpy(&a, &x, 8);
28416  e = (a>>52) - 1022;
28417  return e*10;
28418 }
28419 #endif /* SQLITE_OMIT_VIRTUALTABLE */
28420 
28421 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28422  defined(SQLITE_ENABLE_STAT3_OR_STAT4) || \
28423  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28424 /*
28425 ** Convert a LogEst into an integer.
28426 **
28427 ** Note that this routine is only used when one or more of various
28428 ** non-standard compile-time options is enabled.
28429 */
28430 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
28431  u64 n;
28432  n = x%10;
28433  x /= 10;
28434  if( n>=5 ) n -= 2;
28435  else if( n>=1 ) n -= 1;
28436 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS) || \
28437  defined(SQLITE_EXPLAIN_ESTIMATED_ROWS)
28438  if( x>60 ) return (u64)LARGEST_INT64;
28439 #else
28440  /* If only SQLITE_ENABLE_STAT3_OR_STAT4 is on, then the largest input
28441  ** possible to this routine is 310, resulting in a maximum x of 31 */
28442  assert( x<=60 );
28443 #endif
28444  return x>=3 ? (n+8)<<(x-3) : (n+8)>>(3-x);
28445 }
28446 #endif /* defined SCANSTAT or STAT4 or ESTIMATED_ROWS */
28447 
28448 /************** End of util.c ************************************************/
28449 /************** Begin file hash.c ********************************************/
28450 /*
28451 ** 2001 September 22
28452 **
28453 ** The author disclaims copyright to this source code. In place of
28454 ** a legal notice, here is a blessing:
28455 **
28456 ** May you do good and not evil.
28457 ** May you find forgiveness for yourself and forgive others.
28458 ** May you share freely, never taking more than you give.
28459 **
28460 *************************************************************************
28461 ** This is the implementation of generic hash-tables
28462 ** used in SQLite.
28463 */
28464 /* #include "sqliteInt.h" */
28465 /* #include <assert.h> */
28466 
28467 /* Turn bulk memory into a hash table object by initializing the
28468 ** fields of the Hash structure.
28469 **
28470 ** "pNew" is a pointer to the hash table that is to be initialized.
28471 */
28473  assert( pNew!=0 );
28474  pNew->first = 0;
28475  pNew->count = 0;
28476  pNew->htsize = 0;
28477  pNew->ht = 0;
28478 }
28479 
28480 /* Remove all entries from a hash table. Reclaim all memory.
28481 ** Call this routine to delete a hash table or to reset a hash table
28482 ** to the empty state.
28483 */
28485  HashElem *elem; /* For looping over all elements of the table */
28486 
28487  assert( pH!=0 );
28488  elem = pH->first;
28489  pH->first = 0;
28490  sqlite3_free(pH->ht);
28491  pH->ht = 0;
28492  pH->htsize = 0;
28493  while( elem ){
28494  HashElem *next_elem = elem->next;
28495  sqlite3_free(elem);
28496  elem = next_elem;
28497  }
28498  pH->count = 0;
28499 }
28500 
28501 /*
28502 ** The hashing function.
28503 */
28504 static unsigned int strHash(const char *z){
28505  unsigned int h = 0;
28506  unsigned char c;
28507  while( (c = (unsigned char)*z++)!=0 ){ /*OPTIMIZATION-IF-TRUE*/
28508  h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
28509  }
28510  return h;
28511 }
28512 
28513 
28514 /* Link pNew element into the hash table pH. If pEntry!=0 then also
28515 ** insert pNew into the pEntry hash bucket.
28516 */
28517 static void insertElement(
28518  Hash *pH, /* The complete hash table */
28519  struct _ht *pEntry, /* The entry into which pNew is inserted */
28520  HashElem *pNew /* The element to be inserted */
28521 ){
28522  HashElem *pHead; /* First element already in pEntry */
28523  if( pEntry ){
28524  pHead = pEntry->count ? pEntry->chain : 0;
28525  pEntry->count++;
28526  pEntry->chain = pNew;
28527  }else{
28528  pHead = 0;
28529  }
28530  if( pHead ){
28531  pNew->next = pHead;
28532  pNew->prev = pHead->prev;
28533  if( pHead->prev ){ pHead->prev->next = pNew; }
28534  else { pH->first = pNew; }
28535  pHead->prev = pNew;
28536  }else{
28537  pNew->next = pH->first;
28538  if( pH->first ){ pH->first->prev = pNew; }
28539  pNew->prev = 0;
28540  pH->first = pNew;
28541  }
28542 }
28543 
28544 
28545 /* Resize the hash table so that it cantains "new_size" buckets.
28546 **
28547 ** The hash table might fail to resize if sqlite3_malloc() fails or
28548 ** if the new size is the same as the prior size.
28549 ** Return TRUE if the resize occurs and false if not.
28550 */
28551 static int rehash(Hash *pH, unsigned int new_size){
28552  struct _ht *new_ht; /* The new hash table */
28553  HashElem *elem, *next_elem; /* For looping over existing elements */
28554 
28555 #if SQLITE_MALLOC_SOFT_LIMIT>0
28556  if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
28557  new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
28558  }
28559  if( new_size==pH->htsize ) return 0;
28560 #endif
28561 
28562  /* The inability to allocates space for a larger hash table is
28563  ** a performance hit but it is not a fatal error. So mark the
28564  ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
28565  ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
28566  ** only zeroes the requested number of bytes whereas this module will
28567  ** use the actual amount of space allocated for the hash table (which
28568  ** may be larger than the requested amount).
28569  */
28571  new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
28573 
28574  if( new_ht==0 ) return 0;
28575  sqlite3_free(pH->ht);
28576  pH->ht = new_ht;
28577  pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
28578  memset(new_ht, 0, new_size*sizeof(struct _ht));
28579  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
28580  unsigned int h = strHash(elem->pKey) % new_size;
28581  next_elem = elem->next;
28582  insertElement(pH, &new_ht[h], elem);
28583  }
28584  return 1;
28585 }
28586 
28587 /* This function (for internal use only) locates an element in an
28588 ** hash table that matches the given key. The hash for this key is
28589 ** also computed and returned in the *pH parameter.
28590 */
28592  const Hash *pH, /* The pH to be searched */
28593  const char *pKey, /* The key we are searching for */
28594  unsigned int *pHash /* Write the hash value here */
28595 ){
28596  HashElem *elem; /* Used to loop thru the element list */
28597  int count; /* Number of elements left to test */
28598  unsigned int h; /* The computed hash */
28599 
28600  if( pH->ht ){ /*OPTIMIZATION-IF-TRUE*/
28601  struct _ht *pEntry;
28602  h = strHash(pKey) % pH->htsize;
28603  pEntry = &pH->ht[h];
28604  elem = pEntry->chain;
28605  count = pEntry->count;
28606  }else{
28607  h = 0;
28608  elem = pH->first;
28609  count = pH->count;
28610  }
28611  *pHash = h;
28612  while( count-- ){
28613  assert( elem!=0 );
28614  if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
28615  return elem;
28616  }
28617  elem = elem->next;
28618  }
28619  return 0;
28620 }
28621 
28622 /* Remove a single entry from the hash table given a pointer to that
28623 ** element and a hash on the element's key.
28624 */
28626  Hash *pH, /* The pH containing "elem" */
28627  HashElem* elem, /* The element to be removed from the pH */
28628  unsigned int h /* Hash value for the element */
28629 ){
28630  struct _ht *pEntry;
28631  if( elem->prev ){
28632  elem->prev->next = elem->next;
28633  }else{
28634  pH->first = elem->next;
28635  }
28636  if( elem->next ){
28637  elem->next->prev = elem->prev;
28638  }
28639  if( pH->ht ){
28640  pEntry = &pH->ht[h];
28641  if( pEntry->chain==elem ){
28642  pEntry->chain = elem->next;
28643  }
28644  pEntry->count--;
28645  assert( pEntry->count>=0 );
28646  }
28647  sqlite3_free( elem );
28648  pH->count--;
28649  if( pH->count==0 ){
28650  assert( pH->first==0 );
28651  assert( pH->count==0 );
28652  sqlite3HashClear(pH);
28653  }
28654 }
28655 
28656 /* Attempt to locate an element of the hash table pH with a key
28657 ** that matches pKey. Return the data for this element if it is
28658 ** found, or NULL if there is no match.
28659 */
28660 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
28661  HashElem *elem; /* The element that matches key */
28662  unsigned int h; /* A hash on key */
28663 
28664  assert( pH!=0 );
28665  assert( pKey!=0 );
28666  elem = findElementWithHash(pH, pKey, &h);
28667  return elem ? elem->data : 0;
28668 }
28669 
28670 /* Insert an element into the hash table pH. The key is pKey
28671 ** and the data is "data".
28672 **
28673 ** If no element exists with a matching key, then a new
28674 ** element is created and NULL is returned.
28675 **
28676 ** If another element already exists with the same key, then the
28677 ** new data replaces the old data and the old data is returned.
28678 ** The key is not copied in this instance. If a malloc fails, then
28679 ** the new data is returned and the hash table is unchanged.
28680 **
28681 ** If the "data" parameter to this function is NULL, then the
28682 ** element corresponding to "key" is removed from the hash table.
28683 */
28684 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
28685  unsigned int h; /* the hash of the key modulo hash table size */
28686  HashElem *elem; /* Used to loop thru the element list */
28687  HashElem *new_elem; /* New element added to the pH */
28688 
28689  assert( pH!=0 );
28690  assert( pKey!=0 );
28691  elem = findElementWithHash(pH,pKey,&h);
28692  if( elem ){
28693  void *old_data = elem->data;
28694  if( data==0 ){
28695  removeElementGivenHash(pH,elem,h);
28696  }else{
28697  elem->data = data;
28698  elem->pKey = pKey;
28699  }
28700  return old_data;
28701  }
28702  if( data==0 ) return 0;
28703  new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
28704  if( new_elem==0 ) return data;
28705  new_elem->pKey = pKey;
28706  new_elem->data = data;
28707  pH->count++;
28708  if( pH->count>=10 && pH->count > 2*pH->htsize ){
28709  if( rehash(pH, pH->count*2) ){
28710  assert( pH->htsize>0 );
28711  h = strHash(pKey) % pH->htsize;
28712  }
28713  }
28714  insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
28715  return 0;
28716 }
28717 
28718 /************** End of hash.c ************************************************/
28719 /************** Begin file opcodes.c *****************************************/
28720 /* Automatically generated. Do not edit */
28721 /* See the tool/mkopcodec.tcl script for details. */
28722 #if !defined(SQLITE_OMIT_EXPLAIN) \
28723  || defined(VDBE_PROFILE) \
28724  || defined(SQLITE_DEBUG)
28725 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
28726 # define OpHelp(X) "\0" X
28727 #else
28728 # define OpHelp(X)
28729 #endif
28731  static const char *const azName[] = {
28732  /* 0 */ "Savepoint" OpHelp(""),
28733  /* 1 */ "AutoCommit" OpHelp(""),
28734  /* 2 */ "Transaction" OpHelp(""),
28735  /* 3 */ "SorterNext" OpHelp(""),
28736  /* 4 */ "PrevIfOpen" OpHelp(""),
28737  /* 5 */ "NextIfOpen" OpHelp(""),
28738  /* 6 */ "Prev" OpHelp(""),
28739  /* 7 */ "Next" OpHelp(""),
28740  /* 8 */ "Checkpoint" OpHelp(""),
28741  /* 9 */ "JournalMode" OpHelp(""),
28742  /* 10 */ "Vacuum" OpHelp(""),
28743  /* 11 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
28744  /* 12 */ "VUpdate" OpHelp("data=r[P3@P2]"),
28745  /* 13 */ "Goto" OpHelp(""),
28746  /* 14 */ "Gosub" OpHelp(""),
28747  /* 15 */ "InitCoroutine" OpHelp(""),
28748  /* 16 */ "Yield" OpHelp(""),
28749  /* 17 */ "MustBeInt" OpHelp(""),
28750  /* 18 */ "Jump" OpHelp(""),
28751  /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
28752  /* 20 */ "Once" OpHelp(""),
28753  /* 21 */ "If" OpHelp(""),
28754  /* 22 */ "IfNot" OpHelp(""),
28755  /* 23 */ "SeekLT" OpHelp("key=r[P3@P4]"),
28756  /* 24 */ "SeekLE" OpHelp("key=r[P3@P4]"),
28757  /* 25 */ "SeekGE" OpHelp("key=r[P3@P4]"),
28758  /* 26 */ "SeekGT" OpHelp("key=r[P3@P4]"),
28759  /* 27 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
28760  /* 28 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
28761  /* 29 */ "NoConflict" OpHelp("key=r[P3@P4]"),
28762  /* 30 */ "NotFound" OpHelp("key=r[P3@P4]"),
28763  /* 31 */ "Found" OpHelp("key=r[P3@P4]"),
28764  /* 32 */ "NotExists" OpHelp("intkey=r[P3]"),
28765  /* 33 */ "Last" OpHelp(""),
28766  /* 34 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
28767  /* 35 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
28768  /* 36 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
28769  /* 37 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
28770  /* 38 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
28771  /* 39 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
28772  /* 40 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
28773  /* 41 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
28774  /* 42 */ "SorterSort" OpHelp(""),
28775  /* 43 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
28776  /* 44 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
28777  /* 45 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
28778  /* 46 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
28779  /* 47 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
28780  /* 48 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
28781  /* 49 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
28782  /* 50 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
28783  /* 51 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
28784  /* 52 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
28785  /* 53 */ "Sort" OpHelp(""),
28786  /* 54 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
28787  /* 55 */ "Rewind" OpHelp(""),
28788  /* 56 */ "IdxLE" OpHelp("key=r[P3@P4]"),
28789  /* 57 */ "IdxGT" OpHelp("key=r[P3@P4]"),
28790  /* 58 */ "IdxLT" OpHelp("key=r[P3@P4]"),
28791  /* 59 */ "IdxGE" OpHelp("key=r[P3@P4]"),
28792  /* 60 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
28793  /* 61 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
28794  /* 62 */ "Program" OpHelp(""),
28795  /* 63 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
28796  /* 64 */ "IfPos" OpHelp("if r[P1]>0 then r[P1]-=P3, goto P2"),
28797  /* 65 */ "IfNotZero" OpHelp("if r[P1]!=0 then r[P1]-=P3, goto P2"),
28798  /* 66 */ "DecrJumpZero" OpHelp("if (--r[P1])==0 goto P2"),
28799  /* 67 */ "IncrVacuum" OpHelp(""),
28800  /* 68 */ "VNext" OpHelp(""),
28801  /* 69 */ "Init" OpHelp("Start at P2"),
28802  /* 70 */ "Return" OpHelp(""),
28803  /* 71 */ "EndCoroutine" OpHelp(""),
28804  /* 72 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
28805  /* 73 */ "Halt" OpHelp(""),
28806  /* 74 */ "Integer" OpHelp("r[P2]=P1"),
28807  /* 75 */ "Int64" OpHelp("r[P2]=P4"),
28808  /* 76 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
28809  /* 77 */ "Null" OpHelp("r[P2..P3]=NULL"),
28810  /* 78 */ "SoftNull" OpHelp("r[P1]=NULL"),
28811  /* 79 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
28812  /* 80 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
28813  /* 81 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
28814  /* 82 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
28815  /* 83 */ "SCopy" OpHelp("r[P2]=r[P1]"),
28816  /* 84 */ "IntCopy" OpHelp("r[P2]=r[P1]"),
28817  /* 85 */ "ResultRow" OpHelp("output=r[P1@P2]"),
28818  /* 86 */ "CollSeq" OpHelp(""),
28819  /* 87 */ "Function0" OpHelp("r[P3]=func(r[P2@P5])"),
28820  /* 88 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
28821  /* 89 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
28822  /* 90 */ "RealAffinity" OpHelp(""),
28823  /* 91 */ "Cast" OpHelp("affinity(r[P1])"),
28824  /* 92 */ "Permutation" OpHelp(""),
28825  /* 93 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
28826  /* 94 */ "Column" OpHelp("r[P3]=PX"),
28827  /* 95 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
28828  /* 96 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
28829  /* 97 */ "String8" OpHelp("r[P2]='P4'"),
28830  /* 98 */ "Count" OpHelp("r[P2]=count()"),
28831  /* 99 */ "ReadCookie" OpHelp(""),
28832  /* 100 */ "SetCookie" OpHelp(""),
28833  /* 101 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
28834  /* 102 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
28835  /* 103 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
28836  /* 104 */ "OpenAutoindex" OpHelp("nColumn=P2"),
28837  /* 105 */ "OpenEphemeral" OpHelp("nColumn=P2"),
28838  /* 106 */ "SorterOpen" OpHelp(""),
28839  /* 107 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
28840  /* 108 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
28841  /* 109 */ "Close" OpHelp(""),
28842  /* 110 */ "ColumnsUsed" OpHelp(""),
28843  /* 111 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
28844  /* 112 */ "NewRowid" OpHelp("r[P2]=rowid"),
28845  /* 113 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
28846  /* 114 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
28847  /* 115 */ "Delete" OpHelp(""),
28848  /* 116 */ "ResetCount" OpHelp(""),
28849  /* 117 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
28850  /* 118 */ "SorterData" OpHelp("r[P2]=data"),
28851  /* 119 */ "RowKey" OpHelp("r[P2]=key"),
28852  /* 120 */ "RowData" OpHelp("r[P2]=data"),
28853  /* 121 */ "Rowid" OpHelp("r[P2]=rowid"),
28854  /* 122 */ "NullRow" OpHelp(""),
28855  /* 123 */ "SorterInsert" OpHelp(""),
28856  /* 124 */ "IdxInsert" OpHelp("key=r[P2]"),
28857  /* 125 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
28858  /* 126 */ "Seek" OpHelp("Move P3 to P1.rowid"),
28859  /* 127 */ "IdxRowid" OpHelp("r[P2]=rowid"),
28860  /* 128 */ "Destroy" OpHelp(""),
28861  /* 129 */ "Clear" OpHelp(""),
28862  /* 130 */ "ResetSorter" OpHelp(""),
28863  /* 131 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
28864  /* 132 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
28865  /* 133 */ "Real" OpHelp("r[P2]=P4"),
28866  /* 134 */ "ParseSchema" OpHelp(""),
28867  /* 135 */ "LoadAnalysis" OpHelp(""),
28868  /* 136 */ "DropTable" OpHelp(""),
28869  /* 137 */ "DropIndex" OpHelp(""),
28870  /* 138 */ "DropTrigger" OpHelp(""),
28871  /* 139 */ "IntegrityCk" OpHelp(""),
28872  /* 140 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
28873  /* 141 */ "Param" OpHelp(""),
28874  /* 142 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
28875  /* 143 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
28876  /* 144 */ "OffsetLimit" OpHelp("if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)"),
28877  /* 145 */ "AggStep0" OpHelp("accum=r[P3] step(r[P2@P5])"),
28878  /* 146 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
28879  /* 147 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
28880  /* 148 */ "Expire" OpHelp(""),
28881  /* 149 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
28882  /* 150 */ "VBegin" OpHelp(""),
28883  /* 151 */ "VCreate" OpHelp(""),
28884  /* 152 */ "VDestroy" OpHelp(""),
28885  /* 153 */ "VOpen" OpHelp(""),
28886  /* 154 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
28887  /* 155 */ "VRename" OpHelp(""),
28888  /* 156 */ "Pagecount" OpHelp(""),
28889  /* 157 */ "MaxPgcnt" OpHelp(""),
28890  /* 158 */ "CursorHint" OpHelp(""),
28891  /* 159 */ "Noop" OpHelp(""),
28892  /* 160 */ "Explain" OpHelp(""),
28893  };
28894  return azName[i];
28895 }
28896 #endif
28897 
28898 /************** End of opcodes.c *********************************************/
28899 /************** Begin file os_unix.c *****************************************/
28900 /*
28901 ** 2004 May 22
28902 **
28903 ** The author disclaims copyright to this source code. In place of
28904 ** a legal notice, here is a blessing:
28905 **
28906 ** May you do good and not evil.
28907 ** May you find forgiveness for yourself and forgive others.
28908 ** May you share freely, never taking more than you give.
28909 **
28910 ******************************************************************************
28911 **
28912 ** This file contains the VFS implementation for unix-like operating systems
28913 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
28914 **
28915 ** There are actually several different VFS implementations in this file.
28916 ** The differences are in the way that file locking is done. The default
28917 ** implementation uses Posix Advisory Locks. Alternative implementations
28918 ** use flock(), dot-files, various proprietary locking schemas, or simply
28919 ** skip locking all together.
28920 **
28921 ** This source file is organized into divisions where the logic for various
28922 ** subfunctions is contained within the appropriate division. PLEASE
28923 ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
28924 ** in the correct division and should be clearly labeled.
28925 **
28926 ** The layout of divisions is as follows:
28927 **
28928 ** * General-purpose declarations and utility functions.
28929 ** * Unique file ID logic used by VxWorks.
28930 ** * Various locking primitive implementations (all except proxy locking):
28931 ** + for Posix Advisory Locks
28932 ** + for no-op locks
28933 ** + for dot-file locks
28934 ** + for flock() locking
28935 ** + for named semaphore locks (VxWorks only)
28936 ** + for AFP filesystem locks (MacOSX only)
28937 ** * sqlite3_file methods not associated with locking.
28938 ** * Definitions of sqlite3_io_methods objects for all locking
28939 ** methods plus "finder" functions for each locking method.
28940 ** * sqlite3_vfs method implementations.
28941 ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
28942 ** * Definitions of sqlite3_vfs objects for all locking methods
28943 ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
28944 */
28945 /* #include "sqliteInt.h" */
28946 #if SQLITE_OS_UNIX /* This file is used on unix only */
28947 
28948 /*
28949 ** There are various methods for file locking used for concurrency
28950 ** control:
28951 **
28952 ** 1. POSIX locking (the default),
28953 ** 2. No locking,
28954 ** 3. Dot-file locking,
28955 ** 4. flock() locking,
28956 ** 5. AFP locking (OSX only),
28957 ** 6. Named POSIX semaphores (VXWorks only),
28958 ** 7. proxy locking. (OSX only)
28959 **
28960 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
28961 ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
28962 ** selection of the appropriate locking style based on the filesystem
28963 ** where the database is located.
28964 */
28965 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
28966 # if defined(__APPLE__)
28967 # define SQLITE_ENABLE_LOCKING_STYLE 1
28968 # else
28969 # define SQLITE_ENABLE_LOCKING_STYLE 0
28970 # endif
28971 #endif
28972 
28973 /* Use pread() and pwrite() if they are available */
28974 #if defined(__APPLE__)
28975 # define HAVE_PREAD 1
28976 # define HAVE_PWRITE 1
28977 #endif
28978 #if defined(HAVE_PREAD64) && defined(HAVE_PWRITE64)
28979 # undef USE_PREAD
28980 # define USE_PREAD64 1
28981 #elif defined(HAVE_PREAD) && defined(HAVE_PWRITE)
28982 # undef USE_PREAD64
28983 # define USE_PREAD 1
28984 #endif
28985 
28986 /*
28987 ** standard include files.
28988 */
28989 #include <sys/types.h>
28990 #include <sys/stat.h>
28991 #include <fcntl.h>
28992 #include <unistd.h>
28993 /* #include <time.h> */
28994 #include <sys/time.h>
28995 #include <errno.h>
28996 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
28997 # include <sys/mman.h>
28998 #endif
28999 
29000 #if SQLITE_ENABLE_LOCKING_STYLE
29001 # include <sys/ioctl.h>
29002 # include <sys/file.h>
29003 # include <sys/param.h>
29004 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
29005 
29006 #if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
29007  (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
29008 # if (!defined(TARGET_OS_EMBEDDED) || (TARGET_OS_EMBEDDED==0)) \
29009  && (!defined(TARGET_IPHONE_SIMULATOR) || (TARGET_IPHONE_SIMULATOR==0))
29010 # define HAVE_GETHOSTUUID 1
29011 # else
29012 # warning "gethostuuid() is disabled."
29013 # endif
29014 #endif
29015 
29016 
29017 #if OS_VXWORKS
29018 /* # include <sys/ioctl.h> */
29019 # include <semaphore.h>
29020 # include <limits.h>
29021 #endif /* OS_VXWORKS */
29022 
29023 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
29024 # include <sys/mount.h>
29025 #endif
29026 
29027 #ifdef HAVE_UTIME
29028 # include <utime.h>
29029 #endif
29030 
29031 /*
29032 ** Allowed values of unixFile.fsFlags
29033 */
29034 #define SQLITE_FSFLAGS_IS_MSDOS 0x1
29035 
29036 /*
29037 ** If we are to be thread-safe, include the pthreads header and define
29038 ** the SQLITE_UNIX_THREADS macro.
29039 */
29040 #if SQLITE_THREADSAFE
29041 /* # include <pthread.h> */
29042 # define SQLITE_UNIX_THREADS 1
29043 #endif
29044 
29045 /*
29046 ** Default permissions when creating a new file
29047 */
29048 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
29049 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
29050 #endif
29051 
29052 /*
29053 ** Default permissions when creating auto proxy dir
29054 */
29055 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
29056 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
29057 #endif
29058 
29059 /*
29060 ** Maximum supported path-length.
29061 */
29062 #define MAX_PATHNAME 512
29063 
29064 /*
29065 ** Maximum supported symbolic links
29066 */
29067 #define SQLITE_MAX_SYMLINKS 100
29068 
29069 /* Always cast the getpid() return type for compatibility with
29070 ** kernel modules in VxWorks. */
29071 #define osGetpid(X) (pid_t)getpid()
29072 
29073 /*
29074 ** Only set the lastErrno if the error code is a real error and not
29075 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
29076 */
29077 #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
29078 
29079 /* Forward references */
29080 typedef struct unixShm unixShm; /* Connection shared memory */
29081 typedef struct unixShmNode unixShmNode; /* Shared memory instance */
29082 typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
29083 typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
29084 
29085 /*
29086 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
29087 ** cannot be closed immediately. In these cases, instances of the following
29088 ** structure are used to store the file descriptor while waiting for an
29089 ** opportunity to either close or reuse it.
29090 */
29092  int fd; /* File descriptor to close */
29093  int flags; /* Flags this file descriptor was opened with */
29094  UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
29095 };
29096 
29097 /*
29098 ** The unixFile structure is subclass of sqlite3_file specific to the unix
29099 ** VFS implementations.
29100 */
29101 typedef struct unixFile unixFile;
29102 struct unixFile {
29103  sqlite3_io_methods const *pMethod; /* Always the first entry */
29104  sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
29105  unixInodeInfo *pInode; /* Info about locks on this inode */
29106  int h; /* The file descriptor */
29107  unsigned char eFileLock; /* The type of lock held on this fd */
29108  unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
29109  int lastErrno; /* The unix errno from last I/O error */
29110  void *lockingContext; /* Locking style specific state */
29111  UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
29112  const char *zPath; /* Name of the file */
29113  unixShm *pShm; /* Shared memory segment information */
29114  int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
29115 #if SQLITE_MAX_MMAP_SIZE>0
29116  int nFetchOut; /* Number of outstanding xFetch refs */
29117  sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
29118  sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
29119  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
29120  void *pMapRegion; /* Memory mapped region */
29121 #endif
29122 #ifdef __QNXNTO__
29123  int sectorSize; /* Device sector size */
29124  int deviceCharacteristics; /* Precomputed device characteristics */
29125 #endif
29126 #if SQLITE_ENABLE_LOCKING_STYLE
29127  int openFlags; /* The flags specified at open() */
29128 #endif
29129 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
29130  unsigned fsFlags; /* cached details from statfs() */
29131 #endif
29132 #if OS_VXWORKS
29133  struct vxworksFileId *pId; /* Unique file ID */
29134 #endif
29135 #ifdef SQLITE_DEBUG
29136  /* The next group of variables are used to track whether or not the
29137  ** transaction counter in bytes 24-27 of database files are updated
29138  ** whenever any part of the database changes. An assertion fault will
29139  ** occur if a file is updated without also updating the transaction
29140  ** counter. This test is made to avoid new problems similar to the
29141  ** one described by ticket #3584.
29142  */
29143  unsigned char transCntrChng; /* True if the transaction counter changed */
29144  unsigned char dbUpdate; /* True if any part of database file changed */
29145  unsigned char inNormalWrite; /* True if in a normal write operation */
29146 
29147 #endif
29148 
29149 #ifdef SQLITE_TEST
29150  /* In test mode, increase the size of this structure a bit so that
29151  ** it is larger than the struct CrashFile defined in test6.c.
29152  */
29153  char aPadding[32];
29154 #endif
29155 };
29156 
29157 /* This variable holds the process id (pid) from when the xRandomness()
29158 ** method was called. If xOpen() is called from a different process id,
29159 ** indicating that a fork() has occurred, the PRNG will be reset.
29160 */
29161 static pid_t randomnessPid = 0;
29162 
29163 /*
29164 ** Allowed values for the unixFile.ctrlFlags bitmask:
29165 */
29166 #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
29167 #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
29168 #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
29169 #ifndef SQLITE_DISABLE_DIRSYNC
29170 # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
29171 #else
29172 # define UNIXFILE_DIRSYNC 0x00
29173 #endif
29174 #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
29175 #define UNIXFILE_DELETE 0x20 /* Delete on close */
29176 #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
29177 #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
29178 
29179 /*
29180 ** Include code that is common to all os_*.c files
29181 */
29182 /************** Include os_common.h in the middle of os_unix.c ***************/
29183 /************** Begin file os_common.h ***************************************/
29184 /*
29185 ** 2004 May 22
29186 **
29187 ** The author disclaims copyright to this source code. In place of
29188 ** a legal notice, here is a blessing:
29189 **
29190 ** May you do good and not evil.
29191 ** May you find forgiveness for yourself and forgive others.
29192 ** May you share freely, never taking more than you give.
29193 **
29194 ******************************************************************************
29195 **
29196 ** This file contains macros and a little bit of code that is common to
29197 ** all of the platform-specific files (os_*.c) and is #included into those
29198 ** files.
29199 **
29200 ** This file should be #included by the os_*.c files only. It is not a
29201 ** general purpose header file.
29202 */
29203 #ifndef _OS_COMMON_H_
29204 #define _OS_COMMON_H_
29205 
29206 /*
29207 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
29208 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
29209 ** switch. The following code should catch this problem at compile-time.
29210 */
29211 #ifdef MEMORY_DEBUG
29212 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
29213 #endif
29214 
29215 /*
29216 ** Macros for performance tracing. Normally turned off. Only works
29217 ** on i486 hardware.
29218 */
29219 #ifdef SQLITE_PERFORMANCE_TRACE
29220 
29221 /*
29222 ** hwtime.h contains inline assembler code for implementing
29223 ** high-performance timing routines.
29224 */
29225 /************** Include hwtime.h in the middle of os_common.h ****************/
29226 /************** Begin file hwtime.h ******************************************/
29227 /*
29228 ** 2008 May 27
29229 **
29230 ** The author disclaims copyright to this source code. In place of
29231 ** a legal notice, here is a blessing:
29232 **
29233 ** May you do good and not evil.
29234 ** May you find forgiveness for yourself and forgive others.
29235 ** May you share freely, never taking more than you give.
29236 **
29237 ******************************************************************************
29238 **
29239 ** This file contains inline asm code for retrieving "high-performance"
29240 ** counters for x86 class CPUs.
29241 */
29242 #ifndef _HWTIME_H_
29243 #define _HWTIME_H_
29244 
29245 /*
29246 ** The following routine only works on pentium-class (or newer) processors.
29247 ** It uses the RDTSC opcode to read the cycle count value out of the
29248 ** processor and returns that value. This can be used for high-res
29249 ** profiling.
29250 */
29251 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
29252  (defined(i386) || defined(__i386__) || defined(_M_IX86))
29253 
29254  #if defined(__GNUC__)
29255 
29256  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29257  unsigned int lo, hi;
29258  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
29259  return (sqlite_uint64)hi << 32 | lo;
29260  }
29261 
29262  #elif defined(_MSC_VER)
29263 
29264  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
29265  __asm {
29266  rdtsc
29267  ret ; return value at EDX:EAX
29268  }
29269  }
29270 
29271  #endif
29272 
29273 #elif (defined(__GNUC__) && defined(__x86_64__))
29274 
29275  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29276  unsigned long val;
29277  __asm__ __volatile__ ("rdtsc" : "=A" (val));
29278  return val;
29279  }
29280 
29281 #elif (defined(__GNUC__) && defined(__ppc__))
29282 
29283  __inline__ sqlite_uint64 sqlite3Hwtime(void){
29284  unsigned long long retval;
29285  unsigned long junk;
29286  __asm__ __volatile__ ("\n\
29287  1: mftbu %1\n\
29288  mftb %L0\n\
29289  mftbu %0\n\
29290  cmpw %0,%1\n\
29291  bne 1b"
29292  : "=r" (retval), "=r" (junk));
29293  return retval;
29294  }
29295 
29296 #else
29297 
29298  #error Need implementation of sqlite3Hwtime() for your platform.
29299 
29300  /*
29301  ** To compile without implementing sqlite3Hwtime() for your platform,
29302  ** you can remove the above #error and use the following
29303  ** stub function. You will lose timing support for many
29304  ** of the debugging and testing utilities, but it should at
29305  ** least compile and run.
29306  */
29307 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
29308 
29309 #endif
29310 
29311 #endif /* !defined(_HWTIME_H_) */
29312 
29313 /************** End of hwtime.h **********************************************/
29314 /************** Continuing where we left off in os_common.h ******************/
29315 
29316 static sqlite_uint64 g_start;
29317 static sqlite_uint64 g_elapsed;
29318 #define TIMER_START g_start=sqlite3Hwtime()
29319 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
29320 #define TIMER_ELAPSED g_elapsed
29321 #else
29322 #define TIMER_START
29323 #define TIMER_END
29324 #define TIMER_ELAPSED ((sqlite_uint64)0)
29325 #endif
29326 
29327 /*
29328 ** If we compile with the SQLITE_TEST macro set, then the following block
29329 ** of code will give us the ability to simulate a disk I/O error. This
29330 ** is used for testing the I/O recovery logic.
29331 */
29332 #if defined(SQLITE_TEST)
29333 SQLITE_API extern int sqlite3_io_error_hit;
29334 SQLITE_API extern int sqlite3_io_error_hardhit;
29335 SQLITE_API extern int sqlite3_io_error_pending;
29336 SQLITE_API extern int sqlite3_io_error_persist;
29337 SQLITE_API extern int sqlite3_io_error_benign;
29338 SQLITE_API extern int sqlite3_diskfull_pending;
29339 SQLITE_API extern int sqlite3_diskfull;
29340 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
29341 #define SimulateIOError(CODE) \
29342  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
29343  || sqlite3_io_error_pending-- == 1 ) \
29344  { local_ioerr(); CODE; }
29345 static void local_ioerr(){
29346  IOTRACE(("IOERR\n"));
29347  sqlite3_io_error_hit++;
29348  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
29349 }
29350 #define SimulateDiskfullError(CODE) \
29351  if( sqlite3_diskfull_pending ){ \
29352  if( sqlite3_diskfull_pending == 1 ){ \
29353  local_ioerr(); \
29354  sqlite3_diskfull = 1; \
29355  sqlite3_io_error_hit = 1; \
29356  CODE; \
29357  }else{ \
29358  sqlite3_diskfull_pending--; \
29359  } \
29360  }
29361 #else
29362 #define SimulateIOErrorBenign(X)
29363 #define SimulateIOError(A)
29364 #define SimulateDiskfullError(A)
29365 #endif /* defined(SQLITE_TEST) */
29366 
29367 /*
29368 ** When testing, keep a count of the number of open files.
29369 */
29370 #if defined(SQLITE_TEST)
29371 SQLITE_API extern int sqlite3_open_file_count;
29372 #define OpenCounter(X) sqlite3_open_file_count+=(X)
29373 #else
29374 #define OpenCounter(X)
29375 #endif /* defined(SQLITE_TEST) */
29376 
29377 #endif /* !defined(_OS_COMMON_H_) */
29378 
29379 /************** End of os_common.h *******************************************/
29380 /************** Continuing where we left off in os_unix.c ********************/
29381 
29382 /*
29383 ** Define various macros that are missing from some systems.
29384 */
29385 #ifndef O_LARGEFILE
29386 # define O_LARGEFILE 0
29387 #endif
29388 #ifdef SQLITE_DISABLE_LFS
29389 # undef O_LARGEFILE
29390 # define O_LARGEFILE 0
29391 #endif
29392 #ifndef O_NOFOLLOW
29393 # define O_NOFOLLOW 0
29394 #endif
29395 #ifndef O_BINARY
29396 # define O_BINARY 0
29397 #endif
29398 
29399 /*
29400 ** The threadid macro resolves to the thread-id or to 0. Used for
29401 ** testing and debugging only.
29402 */
29403 #if SQLITE_THREADSAFE
29404 #define threadid pthread_self()
29405 #else
29406 #define threadid 0
29407 #endif
29408 
29409 /*
29410 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
29411 */
29412 #if !defined(HAVE_MREMAP)
29413 # if defined(__linux__) && defined(_GNU_SOURCE)
29414 # define HAVE_MREMAP 1
29415 # else
29416 # define HAVE_MREMAP 0
29417 # endif
29418 #endif
29419 
29420 /*
29421 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
29422 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
29423 */
29424 #ifdef __ANDROID__
29425 # define lseek lseek64
29426 #endif
29427 
29428 /*
29429 ** Different Unix systems declare open() in different ways. Same use
29430 ** open(const char*,int,mode_t). Others use open(const char*,int,...).
29431 ** The difference is important when using a pointer to the function.
29432 **
29433 ** The safest way to deal with the problem is to always use this wrapper
29434 ** which always has the same well-defined interface.
29435 */
29436 static int posixOpen(const char *zFile, int flags, int mode){
29437  return open(zFile, flags, mode);
29438 }
29439 
29440 /* Forward reference */
29441 static int openDirectory(const char*, int*);
29442 static int unixGetpagesize(void);
29443 
29444 /*
29445 ** Many system calls are accessed through pointer-to-functions so that
29446 ** they may be overridden at runtime to facilitate fault injection during
29447 ** testing and sandboxing. The following array holds the names and pointers
29448 ** to all overrideable system calls.
29449 */
29450 static struct unix_syscall {
29451  const char *zName; /* Name of the system call */
29452  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
29453  sqlite3_syscall_ptr pDefault; /* Default value */
29454 } aSyscall[] = {
29455  { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
29456 #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
29457 
29458  { "close", (sqlite3_syscall_ptr)close, 0 },
29459 #define osClose ((int(*)(int))aSyscall[1].pCurrent)
29460 
29461  { "access", (sqlite3_syscall_ptr)access, 0 },
29462 #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
29463 
29464  { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
29465 #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
29466 
29467  { "stat", (sqlite3_syscall_ptr)stat, 0 },
29468 #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
29469 
29470 /*
29471 ** The DJGPP compiler environment looks mostly like Unix, but it
29472 ** lacks the fcntl() system call. So redefine fcntl() to be something
29473 ** that always succeeds. This means that locking does not occur under
29474 ** DJGPP. But it is DOS - what did you expect?
29475 */
29476 #ifdef __DJGPP__
29477  { "fstat", 0, 0 },
29478 #define osFstat(a,b,c) 0
29479 #else
29480  { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
29481 #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
29482 #endif
29483 
29484  { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
29485 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
29486 
29487  { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
29488 #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
29489 
29490  { "read", (sqlite3_syscall_ptr)read, 0 },
29491 #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
29492 
29493 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29494  { "pread", (sqlite3_syscall_ptr)pread, 0 },
29495 #else
29496  { "pread", (sqlite3_syscall_ptr)0, 0 },
29497 #endif
29498 #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
29499 
29500 #if defined(USE_PREAD64)
29501  { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
29502 #else
29503  { "pread64", (sqlite3_syscall_ptr)0, 0 },
29504 #endif
29505 #define osPread64 ((ssize_t(*)(int,void*,size_t,off64_t))aSyscall[10].pCurrent)
29506 
29507  { "write", (sqlite3_syscall_ptr)write, 0 },
29508 #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
29509 
29510 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
29511  { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
29512 #else
29513  { "pwrite", (sqlite3_syscall_ptr)0, 0 },
29514 #endif
29515 #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
29516  aSyscall[12].pCurrent)
29517 
29518 #if defined(USE_PREAD64)
29519  { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
29520 #else
29521  { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
29522 #endif
29523 #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off64_t))\
29524  aSyscall[13].pCurrent)
29525 
29526  { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
29527 #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
29528 
29529 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29530  { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
29531 #else
29532  { "fallocate", (sqlite3_syscall_ptr)0, 0 },
29533 #endif
29534 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
29535 
29536  { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
29537 #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
29538 
29539  { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
29540 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
29541 
29542  { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
29543 #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
29544 
29545  { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
29546 #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
29547 
29548 #if defined(HAVE_FCHOWN)
29549  { "fchown", (sqlite3_syscall_ptr)fchown, 0 },
29550 #else
29551  { "fchown", (sqlite3_syscall_ptr)0, 0 },
29552 #endif
29553 #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
29554 
29555  { "geteuid", (sqlite3_syscall_ptr)geteuid, 0 },
29556 #define osGeteuid ((uid_t(*)(void))aSyscall[21].pCurrent)
29557 
29558 #if !defined(ANDROID) && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29559  { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
29560 #else
29561  { "mmap", (sqlite3_syscall_ptr)0, 0 },
29562 #endif
29563 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[22].pCurrent)
29564 
29565 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29566  { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
29567 #else
29568  { "munmap", (sqlite3_syscall_ptr)0, 0 },
29569 #endif
29570 #define osMunmap ((void*(*)(void*,size_t))aSyscall[23].pCurrent)
29571 
29572 #if HAVE_MREMAP && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
29573  { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
29574 #else
29575  { "mremap", (sqlite3_syscall_ptr)0, 0 },
29576 #endif
29577 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[24].pCurrent)
29578 
29579 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29580  { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
29581 #else
29582  { "getpagesize", (sqlite3_syscall_ptr)0, 0 },
29583 #endif
29584 #define osGetpagesize ((int(*)(void))aSyscall[25].pCurrent)
29585 
29586 #if defined(HAVE_READLINK)
29587  { "readlink", (sqlite3_syscall_ptr)readlink, 0 },
29588 #else
29589  { "readlink", (sqlite3_syscall_ptr)0, 0 },
29590 #endif
29591 #define osReadlink ((ssize_t(*)(const char*,char*,size_t))aSyscall[26].pCurrent)
29592 
29593 #if defined(HAVE_LSTAT)
29594  { "lstat", (sqlite3_syscall_ptr)lstat, 0 },
29595 #else
29596  { "lstat", (sqlite3_syscall_ptr)0, 0 },
29597 #endif
29598 #define osLstat ((int(*)(const char*,struct stat*))aSyscall[27].pCurrent)
29599 
29600 }; /* End of the overrideable system calls */
29601 
29602 
29603 /*
29604 ** On some systems, calls to fchown() will trigger a message in a security
29605 ** log if they come from non-root processes. So avoid calling fchown() if
29606 ** we are not running as root.
29607 */
29608 static int robustFchown(int fd, uid_t uid, gid_t gid){
29609 #if defined(HAVE_FCHOWN)
29610  return osGeteuid() ? 0 : osFchown(fd,uid,gid);
29611 #else
29612  return 0;
29613 #endif
29614 }
29615 
29616 /*
29617 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
29618 ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
29619 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
29620 ** system call named zName.
29621 */
29623  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
29624  const char *zName, /* Name of system call to override */
29625  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
29626 ){
29627  unsigned int i;
29628  int rc = SQLITE_NOTFOUND;
29629 
29630  UNUSED_PARAMETER(pNotUsed);
29631  if( zName==0 ){
29632  /* If no zName is given, restore all system calls to their default
29633  ** settings and return NULL
29634  */
29635  rc = SQLITE_OK;
29636  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29637  if( aSyscall[i].pDefault ){
29639  }
29640  }
29641  }else{
29642  /* If zName is specified, operate on only the one system call
29643  ** specified.
29644  */
29645  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29646  if( strcmp(zName, aSyscall[i].zName)==0 ){
29647  if( aSyscall[i].pDefault==0 ){
29649  }
29650  rc = SQLITE_OK;
29651  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
29652  aSyscall[i].pCurrent = pNewFunc;
29653  break;
29654  }
29655  }
29656  }
29657  return rc;
29658 }
29659 
29660 /*
29661 ** Return the value of a system call. Return NULL if zName is not a
29662 ** recognized system call name. NULL is also returned if the system call
29663 ** is currently undefined.
29664 */
29666  sqlite3_vfs *pNotUsed,
29667  const char *zName
29668 ){
29669  unsigned int i;
29670 
29671  UNUSED_PARAMETER(pNotUsed);
29672  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
29673  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
29674  }
29675  return 0;
29676 }
29677 
29678 /*
29679 ** Return the name of the first system call after zName. If zName==NULL
29680 ** then return the name of the first system call. Return NULL if zName
29681 ** is the last system call or if zName is not the name of a valid
29682 ** system call.
29683 */
29684 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
29685  int i = -1;
29686 
29687  UNUSED_PARAMETER(p);
29688  if( zName ){
29689  for(i=0; i<ArraySize(aSyscall)-1; i++){
29690  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
29691  }
29692  }
29693  for(i++; i<ArraySize(aSyscall); i++){
29694  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
29695  }
29696  return 0;
29697 }
29698 
29699 /*
29700 ** Do not accept any file descriptor less than this value, in order to avoid
29701 ** opening database file using file descriptors that are commonly used for
29702 ** standard input, output, and error.
29703 */
29704 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
29705 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
29706 #endif
29707 
29708 /*
29709 ** Invoke open(). Do so multiple times, until it either succeeds or
29710 ** fails for some reason other than EINTR.
29711 **
29712 ** If the file creation mode "m" is 0 then set it to the default for
29713 ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
29714 ** 0644) as modified by the system umask. If m is not 0, then
29715 ** make the file creation mode be exactly m ignoring the umask.
29716 **
29717 ** The m parameter will be non-zero only when creating -wal, -journal,
29718 ** and -shm files. We want those files to have *exactly* the same
29719 ** permissions as their original database, unadulterated by the umask.
29720 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
29721 ** transaction crashes and leaves behind hot journals, then any
29722 ** process that is able to write to the database will also be able to
29723 ** recover the hot journals.
29724 */
29725 static int robust_open(const char *z, int f, mode_t m){
29726  int fd;
29727  mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
29728  while(1){
29729 #if defined(O_CLOEXEC)
29730  fd = osOpen(z,f|O_CLOEXEC,m2);
29731 #else
29732  fd = osOpen(z,f,m2);
29733 #endif
29734  if( fd<0 ){
29735  if( errno==EINTR ) continue;
29736  break;
29737  }
29738  if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
29739  osClose(fd);
29741  "attempt to open \"%s\" as file descriptor %d", z, fd);
29742  fd = -1;
29743  if( osOpen("/dev/null", f, m)<0 ) break;
29744  }
29745  if( fd>=0 ){
29746  if( m!=0 ){
29747  struct stat statbuf;
29748  if( osFstat(fd, &statbuf)==0
29749  && statbuf.st_size==0
29750  && (statbuf.st_mode&0777)!=m
29751  ){
29752  osFchmod(fd, m);
29753  }
29754  }
29755 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
29756  osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
29757 #endif
29758  }
29759  return fd;
29760 }
29761 
29762 /*
29763 ** Helper functions to obtain and relinquish the global mutex. The
29764 ** global mutex is used to protect the unixInodeInfo and
29765 ** vxworksFileId objects used by this file, all of which may be
29766 ** shared by multiple threads.
29767 **
29768 ** Function unixMutexHeld() is used to assert() that the global mutex
29769 ** is held when required. This function is only used as part of assert()
29770 ** statements. e.g.
29771 **
29772 ** unixEnterMutex()
29773 ** assert( unixMutexHeld() );
29774 ** unixEnterLeave()
29775 */
29776 static void unixEnterMutex(void){
29778 }
29779 static void unixLeaveMutex(void){
29781 }
29782 #ifdef SQLITE_DEBUG
29783 static int unixMutexHeld(void) {
29785 }
29786 #endif
29787 
29788 
29789 #ifdef SQLITE_HAVE_OS_TRACE
29790 /*
29791 ** Helper function for printing out trace information from debugging
29792 ** binaries. This returns the string representation of the supplied
29793 ** integer lock-type.
29794 */
29795 static const char *azFileLock(int eFileLock){
29796  switch( eFileLock ){
29797  case NO_LOCK: return "NONE";
29798  case SHARED_LOCK: return "SHARED";
29799  case RESERVED_LOCK: return "RESERVED";
29800  case PENDING_LOCK: return "PENDING";
29801  case EXCLUSIVE_LOCK: return "EXCLUSIVE";
29802  }
29803  return "ERROR";
29804 }
29805 #endif
29806 
29807 #ifdef SQLITE_LOCK_TRACE
29808 /*
29809 ** Print out information about all locking operations.
29810 **
29811 ** This routine is used for troubleshooting locks on multithreaded
29812 ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
29813 ** command-line option on the compiler. This code is normally
29814 ** turned off.
29815 */
29816 static int lockTrace(int fd, int op, struct flock *p){
29817  char *zOpName, *zType;
29818  int s;
29819  int savedErrno;
29820  if( op==F_GETLK ){
29821  zOpName = "GETLK";
29822  }else if( op==F_SETLK ){
29823  zOpName = "SETLK";
29824  }else{
29825  s = osFcntl(fd, op, p);
29826  sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
29827  return s;
29828  }
29829  if( p->l_type==F_RDLCK ){
29830  zType = "RDLCK";
29831  }else if( p->l_type==F_WRLCK ){
29832  zType = "WRLCK";
29833  }else if( p->l_type==F_UNLCK ){
29834  zType = "UNLCK";
29835  }else{
29836  assert( 0 );
29837  }
29838  assert( p->l_whence==SEEK_SET );
29839  s = osFcntl(fd, op, p);
29840  savedErrno = errno;
29841  sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
29842  threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
29843  (int)p->l_pid, s);
29844  if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
29845  struct flock l2;
29846  l2 = *p;
29847  osFcntl(fd, F_GETLK, &l2);
29848  if( l2.l_type==F_RDLCK ){
29849  zType = "RDLCK";
29850  }else if( l2.l_type==F_WRLCK ){
29851  zType = "WRLCK";
29852  }else if( l2.l_type==F_UNLCK ){
29853  zType = "UNLCK";
29854  }else{
29855  assert( 0 );
29856  }
29857  sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
29858  zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
29859  }
29860  errno = savedErrno;
29861  return s;
29862 }
29863 #undef osFcntl
29864 #define osFcntl lockTrace
29865 #endif /* SQLITE_LOCK_TRACE */
29866 
29867 /*
29868 ** Retry ftruncate() calls that fail due to EINTR
29869 **
29870 ** All calls to ftruncate() within this file should be made through
29871 ** this wrapper. On the Android platform, bypassing the logic below
29872 ** could lead to a corrupt database.
29873 */
29874 static int robust_ftruncate(int h, sqlite3_int64 sz){
29875  int rc;
29876 #ifdef __ANDROID__
29877  /* On Android, ftruncate() always uses 32-bit offsets, even if
29878  ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
29879  ** truncate a file to any size larger than 2GiB. Silently ignore any
29880  ** such attempts. */
29881  if( sz>(sqlite3_int64)0x7FFFFFFF ){
29882  rc = SQLITE_OK;
29883  }else
29884 #endif
29885  do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
29886  return rc;
29887 }
29888 
29889 /*
29890 ** This routine translates a standard POSIX errno code into something
29891 ** useful to the clients of the sqlite3 functions. Specifically, it is
29892 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
29893 ** and a variety of "please close the file descriptor NOW" errors into
29894 ** SQLITE_IOERR
29895 **
29896 ** Errors during initialization of locks, or file system support for locks,
29897 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
29898 */
29899 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
29900  assert( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
29901  (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
29902  (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
29903  (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) );
29904  switch (posixError) {
29905  case EACCES:
29906  case EAGAIN:
29907  case ETIMEDOUT:
29908  case EBUSY:
29909  case EINTR:
29910  case ENOLCK:
29911  /* random NFS retry error, unless during file system support
29912  * introspection, in which it actually means what it says */
29913  return SQLITE_BUSY;
29914 
29915  case EPERM:
29916  return SQLITE_PERM;
29917 
29918  default:
29919  return sqliteIOErr;
29920  }
29921 }
29922 
29923 
29924 /******************************************************************************
29925 ****************** Begin Unique File ID Utility Used By VxWorks ***************
29926 **
29927 ** On most versions of unix, we can get a unique ID for a file by concatenating
29928 ** the device number and the inode number. But this does not work on VxWorks.
29929 ** On VxWorks, a unique file id must be based on the canonical filename.
29930 **
29931 ** A pointer to an instance of the following structure can be used as a
29932 ** unique file ID in VxWorks. Each instance of this structure contains
29933 ** a copy of the canonical filename. There is also a reference count.
29934 ** The structure is reclaimed when the number of pointers to it drops to
29935 ** zero.
29936 **
29937 ** There are never very many files open at one time and lookups are not
29938 ** a performance-critical path, so it is sufficient to put these
29939 ** structures on a linked list.
29940 */
29942  struct vxworksFileId *pNext; /* Next in a list of them all */
29943  int nRef; /* Number of references to this one */
29944  int nName; /* Length of the zCanonicalName[] string */
29945  char *zCanonicalName; /* Canonical filename */
29946 };
29947 
29948 #if OS_VXWORKS
29949 /*
29950 ** All unique filenames are held on a linked list headed by this
29951 ** variable:
29952 */
29953 static struct vxworksFileId *vxworksFileList = 0;
29954 
29955 /*
29956 ** Simplify a filename into its canonical form
29957 ** by making the following changes:
29958 **
29959 ** * removing any trailing and duplicate /
29960 ** * convert /./ into just /
29961 ** * convert /A/../ where A is any simple name into just /
29962 **
29963 ** Changes are made in-place. Return the new name length.
29964 **
29965 ** The original filename is in z[0..n-1]. Return the number of
29966 ** characters in the simplified name.
29967 */
29968 static int vxworksSimplifyName(char *z, int n){
29969  int i, j;
29970  while( n>1 && z[n-1]=='/' ){ n--; }
29971  for(i=j=0; i<n; i++){
29972  if( z[i]=='/' ){
29973  if( z[i+1]=='/' ) continue;
29974  if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
29975  i += 1;
29976  continue;
29977  }
29978  if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
29979  while( j>0 && z[j-1]!='/' ){ j--; }
29980  if( j>0 ){ j--; }
29981  i += 2;
29982  continue;
29983  }
29984  }
29985  z[j++] = z[i];
29986  }
29987  z[j] = 0;
29988  return j;
29989 }
29990 
29991 /*
29992 ** Find a unique file ID for the given absolute pathname. Return
29993 ** a pointer to the vxworksFileId object. This pointer is the unique
29994 ** file ID.
29995 **
29996 ** The nRef field of the vxworksFileId object is incremented before
29997 ** the object is returned. A new vxworksFileId object is created
29998 ** and added to the global list if necessary.
29999 **
30000 ** If a memory allocation error occurs, return NULL.
30001 */
30002 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
30003  struct vxworksFileId *pNew; /* search key and new file ID */
30004  struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
30005  int n; /* Length of zAbsoluteName string */
30006 
30007  assert( zAbsoluteName[0]=='/' );
30008  n = (int)strlen(zAbsoluteName);
30009  pNew = sqlite3_malloc64( sizeof(*pNew) + (n+1) );
30010  if( pNew==0 ) return 0;
30011  pNew->zCanonicalName = (char*)&pNew[1];
30012  memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
30013  n = vxworksSimplifyName(pNew->zCanonicalName, n);
30014 
30015  /* Search for an existing entry that matching the canonical name.
30016  ** If found, increment the reference count and return a pointer to
30017  ** the existing file ID.
30018  */
30019  unixEnterMutex();
30020  for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
30021  if( pCandidate->nName==n
30022  && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
30023  ){
30024  sqlite3_free(pNew);
30025  pCandidate->nRef++;
30026  unixLeaveMutex();
30027  return pCandidate;
30028  }
30029  }
30030 
30031  /* No match was found. We will make a new file ID */
30032  pNew->nRef = 1;
30033  pNew->nName = n;
30034  pNew->pNext = vxworksFileList;
30035  vxworksFileList = pNew;
30036  unixLeaveMutex();
30037  return pNew;
30038 }
30039 
30040 /*
30041 ** Decrement the reference count on a vxworksFileId object. Free
30042 ** the object when the reference count reaches zero.
30043 */
30044 static void vxworksReleaseFileId(struct vxworksFileId *pId){
30045  unixEnterMutex();
30046  assert( pId->nRef>0 );
30047  pId->nRef--;
30048  if( pId->nRef==0 ){
30049  struct vxworksFileId **pp;
30050  for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
30051  assert( *pp==pId );
30052  *pp = pId->pNext;
30053  sqlite3_free(pId);
30054  }
30055  unixLeaveMutex();
30056 }
30057 #endif /* OS_VXWORKS */
30058 /*************** End of Unique File ID Utility Used By VxWorks ****************
30059 ******************************************************************************/
30060 
30061 
30062 /******************************************************************************
30063 *************************** Posix Advisory Locking ****************************
30064 **
30065 ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
30066 ** section 6.5.2.2 lines 483 through 490 specify that when a process
30067 ** sets or clears a lock, that operation overrides any prior locks set
30068 ** by the same process. It does not explicitly say so, but this implies
30069 ** that it overrides locks set by the same process using a different
30070 ** file descriptor. Consider this test case:
30071 **
30072 ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
30073 ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
30074 **
30075 ** Suppose ./file1 and ./file2 are really the same file (because
30076 ** one is a hard or symbolic link to the other) then if you set
30077 ** an exclusive lock on fd1, then try to get an exclusive lock
30078 ** on fd2, it works. I would have expected the second lock to
30079 ** fail since there was already a lock on the file due to fd1.
30080 ** But not so. Since both locks came from the same process, the
30081 ** second overrides the first, even though they were on different
30082 ** file descriptors opened on different file names.
30083 **
30084 ** This means that we cannot use POSIX locks to synchronize file access
30085 ** among competing threads of the same process. POSIX locks will work fine
30086 ** to synchronize access for threads in separate processes, but not
30087 ** threads within the same process.
30088 **
30089 ** To work around the problem, SQLite has to manage file locks internally
30090 ** on its own. Whenever a new database is opened, we have to find the
30091 ** specific inode of the database file (the inode is determined by the
30092 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
30093 ** and check for locks already existing on that inode. When locks are
30094 ** created or removed, we have to look at our own internal record of the
30095 ** locks to see if another thread has previously set a lock on that same
30096 ** inode.
30097 **
30098 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
30099 ** For VxWorks, we have to use the alternative unique ID system based on
30100 ** canonical filename and implemented in the previous division.)
30101 **
30102 ** The sqlite3_file structure for POSIX is no longer just an integer file
30103 ** descriptor. It is now a structure that holds the integer file
30104 ** descriptor and a pointer to a structure that describes the internal
30105 ** locks on the corresponding inode. There is one locking structure
30106 ** per inode, so if the same inode is opened twice, both unixFile structures
30107 ** point to the same locking structure. The locking structure keeps
30108 ** a reference count (so we will know when to delete it) and a "cnt"
30109 ** field that tells us its internal lock status. cnt==0 means the
30110 ** file is unlocked. cnt==-1 means the file has an exclusive lock.
30111 ** cnt>0 means there are cnt shared locks on the file.
30112 **
30113 ** Any attempt to lock or unlock a file first checks the locking
30114 ** structure. The fcntl() system call is only invoked to set a
30115 ** POSIX lock if the internal lock structure transitions between
30116 ** a locked and an unlocked state.
30117 **
30118 ** But wait: there are yet more problems with POSIX advisory locks.
30119 **
30120 ** If you close a file descriptor that points to a file that has locks,
30121 ** all locks on that file that are owned by the current process are
30122 ** released. To work around this problem, each unixInodeInfo object
30123 ** maintains a count of the number of pending locks on tha inode.
30124 ** When an attempt is made to close an unixFile, if there are
30125 ** other unixFile open on the same inode that are holding locks, the call
30126 ** to close() the file descriptor is deferred until all of the locks clear.
30127 ** The unixInodeInfo structure keeps a list of file descriptors that need to
30128 ** be closed and that list is walked (and cleared) when the last lock
30129 ** clears.
30130 **
30131 ** Yet another problem: LinuxThreads do not play well with posix locks.
30132 **
30133 ** Many older versions of linux use the LinuxThreads library which is
30134 ** not posix compliant. Under LinuxThreads, a lock created by thread
30135 ** A cannot be modified or overridden by a different thread B.
30136 ** Only thread A can modify the lock. Locking behavior is correct
30137 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
30138 ** on linux - with NPTL a lock created by thread A can override locks
30139 ** in thread B. But there is no way to know at compile-time which
30140 ** threading library is being used. So there is no way to know at
30141 ** compile-time whether or not thread A can override locks on thread B.
30142 ** One has to do a run-time check to discover the behavior of the
30143 ** current process.
30144 **
30145 ** SQLite used to support LinuxThreads. But support for LinuxThreads
30146 ** was dropped beginning with version 3.7.0. SQLite will still work with
30147 ** LinuxThreads provided that (1) there is no more than one connection
30148 ** per database file in the same process and (2) database connections
30149 ** do not move across threads.
30150 */
30151 
30152 /*
30153 ** An instance of the following structure serves as the key used
30154 ** to locate a particular unixInodeInfo object.
30155 */
30156 struct unixFileId {
30157  dev_t dev; /* Device number */
30158 #if OS_VXWORKS
30159  struct vxworksFileId *pId; /* Unique file ID for vxworks. */
30160 #else
30161  ino_t ino; /* Inode number */
30162 #endif
30163 };
30164 
30165 /*
30166 ** An instance of the following structure is allocated for each open
30167 ** inode. Or, on LinuxThreads, there is one of these structures for
30168 ** each inode opened by each thread.
30169 **
30170 ** A single inode can have multiple file descriptors, so each unixFile
30171 ** structure contains a pointer to an instance of this object and this
30172 ** object keeps a count of the number of unixFile pointing to it.
30173 */
30175  struct unixFileId fileId; /* The lookup key */
30176  int nShared; /* Number of SHARED locks held */
30177  unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
30178  unsigned char bProcessLock; /* An exclusive process lock is held */
30179  int nRef; /* Number of pointers to this structure */
30180  unixShmNode *pShmNode; /* Shared memory associated with this inode */
30181  int nLock; /* Number of outstanding file locks */
30182  UnixUnusedFd *pUnused; /* Unused file descriptors to close */
30183  unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
30184  unixInodeInfo *pPrev; /* .... doubly linked */
30185 #if SQLITE_ENABLE_LOCKING_STYLE
30186  unsigned long long sharedByte; /* for AFP simulated shared lock */
30187 #endif
30188 #if OS_VXWORKS
30189  sem_t *pSem; /* Named POSIX semaphore */
30190  char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
30191 #endif
30192 };
30193 
30194 /*
30195 ** A lists of all unixInodeInfo objects.
30196 */
30198 
30199 /*
30200 **
30201 ** This function - unixLogErrorAtLine(), is only ever called via the macro
30202 ** unixLogError().
30203 **
30204 ** It is invoked after an error occurs in an OS function and errno has been
30205 ** set. It logs a message using sqlite3_log() containing the current value of
30206 ** errno and, if possible, the human-readable equivalent from strerror() or
30207 ** strerror_r().
30208 **
30209 ** The first argument passed to the macro should be the error code that
30210 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
30211 ** The two subsequent arguments should be the name of the OS function that
30212 ** failed (e.g. "unlink", "open") and the associated file-system path,
30213 ** if any.
30214 */
30215 #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
30217  int errcode, /* SQLite error code */
30218  const char *zFunc, /* Name of OS function that failed */
30219  const char *zPath, /* File path associated with error */
30220  int iLine /* Source line number where error occurred */
30221 ){
30222  char *zErr; /* Message from strerror() or equivalent */
30223  int iErrno = errno; /* Saved syscall error number */
30224 
30225  /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
30226  ** the strerror() function to obtain the human-readable error message
30227  ** equivalent to errno. Otherwise, use strerror_r().
30228  */
30229 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
30230  char aErr[80];
30231  memset(aErr, 0, sizeof(aErr));
30232  zErr = aErr;
30233 
30234  /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
30235  ** assume that the system provides the GNU version of strerror_r() that
30236  ** returns a pointer to a buffer containing the error message. That pointer
30237  ** may point to aErr[], or it may point to some static storage somewhere.
30238  ** Otherwise, assume that the system provides the POSIX version of
30239  ** strerror_r(), which always writes an error message into aErr[].
30240  **
30241  ** If the code incorrectly assumes that it is the POSIX version that is
30242  ** available, the error message will often be an empty string. Not a
30243  ** huge problem. Incorrectly concluding that the GNU version is available
30244  ** could lead to a segfault though.
30245  */
30246 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
30247  zErr =
30248 # endif
30249  strerror_r(iErrno, aErr, sizeof(aErr)-1);
30250 
30251 #elif SQLITE_THREADSAFE
30252  /* This is a threadsafe build, but strerror_r() is not available. */
30253  zErr = "";
30254 #else
30255  /* Non-threadsafe build, use strerror(). */
30256  zErr = strerror(iErrno);
30257 #endif
30258 
30259  if( zPath==0 ) zPath = "";
30260  sqlite3_log(errcode,
30261  "os_unix.c:%d: (%d) %s(%s) - %s",
30262  iLine, iErrno, zFunc, zPath, zErr
30263  );
30264 
30265  return errcode;
30266 }
30267 
30268 /*
30269 ** Close a file descriptor.
30270 **
30271 ** We assume that close() almost always works, since it is only in a
30272 ** very sick application or on a very sick platform that it might fail.
30273 ** If it does fail, simply leak the file descriptor, but do log the
30274 ** error.
30275 **
30276 ** Note that it is not safe to retry close() after EINTR since the
30277 ** file descriptor might have already been reused by another thread.
30278 ** So we don't even try to recover from an EINTR. Just log the error
30279 ** and move on.
30280 */
30281 static void robust_close(unixFile *pFile, int h, int lineno){
30282  if( osClose(h) ){
30284  pFile ? pFile->zPath : 0, lineno);
30285  }
30286 }
30287 
30288 /*
30289 ** Set the pFile->lastErrno. Do this in a subroutine as that provides
30290 ** a convenient place to set a breakpoint.
30291 */
30292 static void storeLastErrno(unixFile *pFile, int error){
30293  pFile->lastErrno = error;
30294 }
30295 
30296 /*
30297 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
30298 */
30299 static void closePendingFds(unixFile *pFile){
30300  unixInodeInfo *pInode = pFile->pInode;
30301  UnixUnusedFd *p;
30302  UnixUnusedFd *pNext;
30303  for(p=pInode->pUnused; p; p=pNext){
30304  pNext = p->pNext;
30305  robust_close(pFile, p->fd, __LINE__);
30306  sqlite3_free(p);
30307  }
30308  pInode->pUnused = 0;
30309 }
30310 
30311 /*
30312 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
30313 **
30314 ** The mutex entered using the unixEnterMutex() function must be held
30315 ** when this function is called.
30316 */
30317 static void releaseInodeInfo(unixFile *pFile){
30318  unixInodeInfo *pInode = pFile->pInode;
30319  assert( unixMutexHeld() );
30320  if( ALWAYS(pInode) ){
30321  pInode->nRef--;
30322  if( pInode->nRef==0 ){
30323  assert( pInode->pShmNode==0 );
30324  closePendingFds(pFile);
30325  if( pInode->pPrev ){
30326  assert( pInode->pPrev->pNext==pInode );
30327  pInode->pPrev->pNext = pInode->pNext;
30328  }else{
30329  assert( inodeList==pInode );
30330  inodeList = pInode->pNext;
30331  }
30332  if( pInode->pNext ){
30333  assert( pInode->pNext->pPrev==pInode );
30334  pInode->pNext->pPrev = pInode->pPrev;
30335  }
30336  sqlite3_free(pInode);
30337  }
30338  }
30339 }
30340 
30341 /*
30342 ** Given a file descriptor, locate the unixInodeInfo object that
30343 ** describes that file descriptor. Create a new one if necessary. The
30344 ** return value might be uninitialized if an error occurs.
30345 **
30346 ** The mutex entered using the unixEnterMutex() function must be held
30347 ** when this function is called.
30348 **
30349 ** Return an appropriate error code.
30350 */
30351 static int findInodeInfo(
30352  unixFile *pFile, /* Unix file with file desc used in the key */
30353  unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
30354 ){
30355  int rc; /* System call return code */
30356  int fd; /* The file descriptor for pFile */
30357  struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
30358  struct stat statbuf; /* Low-level file information */
30359  unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
30360 
30361  assert( unixMutexHeld() );
30362 
30363  /* Get low-level information about the file that we can used to
30364  ** create a unique name for the file.
30365  */
30366  fd = pFile->h;
30367  rc = osFstat(fd, &statbuf);
30368  if( rc!=0 ){
30369  storeLastErrno(pFile, errno);
30370 #if defined(EOVERFLOW) && defined(SQLITE_DISABLE_LFS)
30371  if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
30372 #endif
30373  return SQLITE_IOERR;
30374  }
30375 
30376 #ifdef __APPLE__
30377  /* On OS X on an msdos filesystem, the inode number is reported
30378  ** incorrectly for zero-size files. See ticket #3260. To work
30379  ** around this problem (we consider it a bug in OS X, not SQLite)
30380  ** we always increase the file size to 1 by writing a single byte
30381  ** prior to accessing the inode number. The one byte written is
30382  ** an ASCII 'S' character which also happens to be the first byte
30383  ** in the header of every SQLite database. In this way, if there
30384  ** is a race condition such that another thread has already populated
30385  ** the first page of the database, no damage is done.
30386  */
30387  if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
30388  do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
30389  if( rc!=1 ){
30390  storeLastErrno(pFile, errno);
30391  return SQLITE_IOERR;
30392  }
30393  rc = osFstat(fd, &statbuf);
30394  if( rc!=0 ){
30395  storeLastErrno(pFile, errno);
30396  return SQLITE_IOERR;
30397  }
30398  }
30399 #endif
30400 
30401  memset(&fileId, 0, sizeof(fileId));
30402  fileId.dev = statbuf.st_dev;
30403 #if OS_VXWORKS
30404  fileId.pId = pFile->pId;
30405 #else
30406  fileId.ino = statbuf.st_ino;
30407 #endif
30408  pInode = inodeList;
30409  while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
30410  pInode = pInode->pNext;
30411  }
30412  if( pInode==0 ){
30413  pInode = sqlite3_malloc64( sizeof(*pInode) );
30414  if( pInode==0 ){
30415  return SQLITE_NOMEM_BKPT;
30416  }
30417  memset(pInode, 0, sizeof(*pInode));
30418  memcpy(&pInode->fileId, &fileId, sizeof(fileId));
30419  pInode->nRef = 1;
30420  pInode->pNext = inodeList;
30421  pInode->pPrev = 0;
30422  if( inodeList ) inodeList->pPrev = pInode;
30423  inodeList = pInode;
30424  }else{
30425  pInode->nRef++;
30426  }
30427  *ppInode = pInode;
30428  return SQLITE_OK;
30429 }
30430 
30431 /*
30432 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
30433 */
30434 static int fileHasMoved(unixFile *pFile){
30435 #if OS_VXWORKS
30436  return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
30437 #else
30438  struct stat buf;
30439  return pFile->pInode!=0 &&
30440  (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
30441 #endif
30442 }
30443 
30444 
30445 /*
30446 ** Check a unixFile that is a database. Verify the following:
30447 **
30448 ** (1) There is exactly one hard link on the file
30449 ** (2) The file is not a symbolic link
30450 ** (3) The file has not been renamed or unlinked
30451 **
30452 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
30453 */
30454 static void verifyDbFile(unixFile *pFile){
30455  struct stat buf;
30456  int rc;
30457 
30458  /* These verifications occurs for the main database only */
30459  if( pFile->ctrlFlags & UNIXFILE_NOLOCK ) return;
30460 
30461  rc = osFstat(pFile->h, &buf);
30462  if( rc!=0 ){
30463  sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
30464  return;
30465  }
30466  if( buf.st_nlink==0 ){
30467  sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
30468  return;
30469  }
30470  if( buf.st_nlink>1 ){
30471  sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
30472  return;
30473  }
30474  if( fileHasMoved(pFile) ){
30475  sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
30476  return;
30477  }
30478 }
30479 
30480 
30481 /*
30482 ** This routine checks if there is a RESERVED lock held on the specified
30483 ** file by this or any other process. If such a lock is held, set *pResOut
30484 ** to a non-zero value otherwise *pResOut is set to zero. The return value
30485 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
30486 */
30487 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
30488  int rc = SQLITE_OK;
30489  int reserved = 0;
30490  unixFile *pFile = (unixFile*)id;
30491 
30493 
30494  assert( pFile );
30495  assert( pFile->eFileLock<=SHARED_LOCK );
30496  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
30497 
30498  /* Check if a thread in this process holds such a lock */
30499  if( pFile->pInode->eFileLock>SHARED_LOCK ){
30500  reserved = 1;
30501  }
30502 
30503  /* Otherwise see if some other process holds it.
30504  */
30505 #ifndef __DJGPP__
30506  if( !reserved && !pFile->pInode->bProcessLock ){
30507  struct flock lock;
30508  lock.l_whence = SEEK_SET;
30509  lock.l_start = RESERVED_BYTE;
30510  lock.l_len = 1;
30511  lock.l_type = F_WRLCK;
30512  if( osFcntl(pFile->h, F_GETLK, &lock) ){
30514  storeLastErrno(pFile, errno);
30515  } else if( lock.l_type!=F_UNLCK ){
30516  reserved = 1;
30517  }
30518  }
30519 #endif
30520 
30521  unixLeaveMutex();
30522  OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
30523 
30524  *pResOut = reserved;
30525  return rc;
30526 }
30527 
30528 /*
30529 ** Attempt to set a system-lock on the file pFile. The lock is
30530 ** described by pLock.
30531 **
30532 ** If the pFile was opened read/write from unix-excl, then the only lock
30533 ** ever obtained is an exclusive lock, and it is obtained exactly once
30534 ** the first time any lock is attempted. All subsequent system locking
30535 ** operations become no-ops. Locking operations still happen internally,
30536 ** in order to coordinate access between separate database connections
30537 ** within this process, but all of that is handled in memory and the
30538 ** operating system does not participate.
30539 **
30540 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
30541 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
30542 ** and is read-only.
30543 **
30544 ** Zero is returned if the call completes successfully, or -1 if a call
30545 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
30546 */
30547 static int unixFileLock(unixFile *pFile, struct flock *pLock){
30548  int rc;
30549  unixInodeInfo *pInode = pFile->pInode;
30550  assert( unixMutexHeld() );
30551  assert( pInode!=0 );
30553  if( pInode->bProcessLock==0 ){
30554  struct flock lock;
30555  assert( pInode->nLock==0 );
30556  lock.l_whence = SEEK_SET;
30557  lock.l_start = SHARED_FIRST;
30558  lock.l_len = SHARED_SIZE;
30559  lock.l_type = F_WRLCK;
30560  rc = osFcntl(pFile->h, F_SETLK, &lock);
30561  if( rc<0 ) return rc;
30562  pInode->bProcessLock = 1;
30563  pInode->nLock++;
30564  }else{
30565  rc = 0;
30566  }
30567  }else{
30568  rc = osFcntl(pFile->h, F_SETLK, pLock);
30569  }
30570  return rc;
30571 }
30572 
30573 /*
30574 ** Lock the file with the lock specified by parameter eFileLock - one
30575 ** of the following:
30576 **
30577 ** (1) SHARED_LOCK
30578 ** (2) RESERVED_LOCK
30579 ** (3) PENDING_LOCK
30580 ** (4) EXCLUSIVE_LOCK
30581 **
30582 ** Sometimes when requesting one lock state, additional lock states
30583 ** are inserted in between. The locking might fail on one of the later
30584 ** transitions leaving the lock state different from what it started but
30585 ** still short of its goal. The following chart shows the allowed
30586 ** transitions and the inserted intermediate states:
30587 **
30588 ** UNLOCKED -> SHARED
30589 ** SHARED -> RESERVED
30590 ** SHARED -> (PENDING) -> EXCLUSIVE
30591 ** RESERVED -> (PENDING) -> EXCLUSIVE
30592 ** PENDING -> EXCLUSIVE
30593 **
30594 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
30595 ** routine to lower a locking level.
30596 */
30597 static int unixLock(sqlite3_file *id, int eFileLock){
30598  /* The following describes the implementation of the various locks and
30599  ** lock transitions in terms of the POSIX advisory shared and exclusive
30600  ** lock primitives (called read-locks and write-locks below, to avoid
30601  ** confusion with SQLite lock names). The algorithms are complicated
30602  ** slightly in order to be compatible with Windows95 systems simultaneously
30603  ** accessing the same database file, in case that is ever required.
30604  **
30605  ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
30606  ** byte', each single bytes at well known offsets, and the 'shared byte
30607  ** range', a range of 510 bytes at a well known offset.
30608  **
30609  ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
30610  ** byte'. If this is successful, 'shared byte range' is read-locked
30611  ** and the lock on the 'pending byte' released. (Legacy note: When
30612  ** SQLite was first developed, Windows95 systems were still very common,
30613  ** and Widnows95 lacks a shared-lock capability. So on Windows95, a
30614  ** single randomly selected by from the 'shared byte range' is locked.
30615  ** Windows95 is now pretty much extinct, but this work-around for the
30616  ** lack of shared-locks on Windows95 lives on, for backwards
30617  ** compatibility.)
30618  **
30619  ** A process may only obtain a RESERVED lock after it has a SHARED lock.
30620  ** A RESERVED lock is implemented by grabbing a write-lock on the
30621  ** 'reserved byte'.
30622  **
30623  ** A process may only obtain a PENDING lock after it has obtained a
30624  ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
30625  ** on the 'pending byte'. This ensures that no new SHARED locks can be
30626  ** obtained, but existing SHARED locks are allowed to persist. A process
30627  ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
30628  ** This property is used by the algorithm for rolling back a journal file
30629  ** after a crash.
30630  **
30631  ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
30632  ** implemented by obtaining a write-lock on the entire 'shared byte
30633  ** range'. Since all other locks require a read-lock on one of the bytes
30634  ** within this range, this ensures that no other locks are held on the
30635  ** database.
30636  */
30637  int rc = SQLITE_OK;
30638  unixFile *pFile = (unixFile*)id;
30639  unixInodeInfo *pInode;
30640  struct flock lock;
30641  int tErrno = 0;
30642 
30643  assert( pFile );
30644  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
30645  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
30646  azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
30647  osGetpid(0)));
30648 
30649  /* If there is already a lock of this type or more restrictive on the
30650  ** unixFile, do nothing. Don't use the end_lock: exit path, as
30651  ** unixEnterMutex() hasn't been called yet.
30652  */
30653  if( pFile->eFileLock>=eFileLock ){
30654  OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
30655  azFileLock(eFileLock)));
30656  return SQLITE_OK;
30657  }
30658 
30659  /* Make sure the locking sequence is correct.
30660  ** (1) We never move from unlocked to anything higher than shared lock.
30661  ** (2) SQLite never explicitly requests a pendig lock.
30662  ** (3) A shared lock is always held when a reserve lock is requested.
30663  */
30664  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
30665  assert( eFileLock!=PENDING_LOCK );
30666  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
30667 
30668  /* This mutex is needed because pFile->pInode is shared across threads
30669  */
30670  unixEnterMutex();
30671  pInode = pFile->pInode;
30672 
30673  /* If some thread using this PID has a lock via a different unixFile*
30674  ** handle that precludes the requested lock, return BUSY.
30675  */
30676  if( (pFile->eFileLock!=pInode->eFileLock &&
30677  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
30678  ){
30679  rc = SQLITE_BUSY;
30680  goto end_lock;
30681  }
30682 
30683  /* If a SHARED lock is requested, and some thread using this PID already
30684  ** has a SHARED or RESERVED lock, then increment reference counts and
30685  ** return SQLITE_OK.
30686  */
30687  if( eFileLock==SHARED_LOCK &&
30688  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
30689  assert( eFileLock==SHARED_LOCK );
30690  assert( pFile->eFileLock==0 );
30691  assert( pInode->nShared>0 );
30692  pFile->eFileLock = SHARED_LOCK;
30693  pInode->nShared++;
30694  pInode->nLock++;
30695  goto end_lock;
30696  }
30697 
30698 
30699  /* A PENDING lock is needed before acquiring a SHARED lock and before
30700  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
30701  ** be released.
30702  */
30703  lock.l_len = 1L;
30704  lock.l_whence = SEEK_SET;
30705  if( eFileLock==SHARED_LOCK
30706  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
30707  ){
30708  lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
30709  lock.l_start = PENDING_BYTE;
30710  if( unixFileLock(pFile, &lock) ){
30711  tErrno = errno;
30713  if( rc!=SQLITE_BUSY ){
30714  storeLastErrno(pFile, tErrno);
30715  }
30716  goto end_lock;
30717  }
30718  }
30719 
30720 
30721  /* If control gets to this point, then actually go ahead and make
30722  ** operating system calls for the specified lock.
30723  */
30724  if( eFileLock==SHARED_LOCK ){
30725  assert( pInode->nShared==0 );
30726  assert( pInode->eFileLock==0 );
30727  assert( rc==SQLITE_OK );
30728 
30729  /* Now get the read-lock */
30730  lock.l_start = SHARED_FIRST;
30731  lock.l_len = SHARED_SIZE;
30732  if( unixFileLock(pFile, &lock) ){
30733  tErrno = errno;
30735  }
30736 
30737  /* Drop the temporary PENDING lock */
30738  lock.l_start = PENDING_BYTE;
30739  lock.l_len = 1L;
30740  lock.l_type = F_UNLCK;
30741  if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
30742  /* This could happen with a network mount */
30743  tErrno = errno;
30744  rc = SQLITE_IOERR_UNLOCK;
30745  }
30746 
30747  if( rc ){
30748  if( rc!=SQLITE_BUSY ){
30749  storeLastErrno(pFile, tErrno);
30750  }
30751  goto end_lock;
30752  }else{
30753  pFile->eFileLock = SHARED_LOCK;
30754  pInode->nLock++;
30755  pInode->nShared = 1;
30756  }
30757  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
30758  /* We are trying for an exclusive lock but another thread in this
30759  ** same process is still holding a shared lock. */
30760  rc = SQLITE_BUSY;
30761  }else{
30762  /* The request was for a RESERVED or EXCLUSIVE lock. It is
30763  ** assumed that there is a SHARED or greater lock on the file
30764  ** already.
30765  */
30766  assert( 0!=pFile->eFileLock );
30767  lock.l_type = F_WRLCK;
30768 
30769  assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
30770  if( eFileLock==RESERVED_LOCK ){
30771  lock.l_start = RESERVED_BYTE;
30772  lock.l_len = 1L;
30773  }else{
30774  lock.l_start = SHARED_FIRST;
30775  lock.l_len = SHARED_SIZE;
30776  }
30777 
30778  if( unixFileLock(pFile, &lock) ){
30779  tErrno = errno;
30781  if( rc!=SQLITE_BUSY ){
30782  storeLastErrno(pFile, tErrno);
30783  }
30784  }
30785  }
30786 
30787 
30788 #ifdef SQLITE_DEBUG
30789  /* Set up the transaction-counter change checking flags when
30790  ** transitioning from a SHARED to a RESERVED lock. The change
30791  ** from SHARED to RESERVED marks the beginning of a normal
30792  ** write operation (not a hot journal rollback).
30793  */
30794  if( rc==SQLITE_OK
30795  && pFile->eFileLock<=SHARED_LOCK
30796  && eFileLock==RESERVED_LOCK
30797  ){
30798  pFile->transCntrChng = 0;
30799  pFile->dbUpdate = 0;
30800  pFile->inNormalWrite = 1;
30801  }
30802 #endif
30803 
30804 
30805  if( rc==SQLITE_OK ){
30806  pFile->eFileLock = eFileLock;
30807  pInode->eFileLock = eFileLock;
30808  }else if( eFileLock==EXCLUSIVE_LOCK ){
30809  pFile->eFileLock = PENDING_LOCK;
30810  pInode->eFileLock = PENDING_LOCK;
30811  }
30812 
30813 end_lock:
30814  unixLeaveMutex();
30815  OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
30816  rc==SQLITE_OK ? "ok" : "failed"));
30817  return rc;
30818 }
30819 
30820 /*
30821 ** Add the file descriptor used by file handle pFile to the corresponding
30822 ** pUnused list.
30823 */
30824 static void setPendingFd(unixFile *pFile){
30825  unixInodeInfo *pInode = pFile->pInode;
30826  UnixUnusedFd *p = pFile->pUnused;
30827  p->pNext = pInode->pUnused;
30828  pInode->pUnused = p;
30829  pFile->h = -1;
30830  pFile->pUnused = 0;
30831 }
30832 
30833 /*
30834 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
30835 ** must be either NO_LOCK or SHARED_LOCK.
30836 **
30837 ** If the locking level of the file descriptor is already at or below
30838 ** the requested locking level, this routine is a no-op.
30839 **
30840 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
30841 ** the byte range is divided into 2 parts and the first part is unlocked then
30842 ** set to a read lock, then the other part is simply unlocked. This works
30843 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
30844 ** remove the write lock on a region when a read lock is set.
30845 */
30846 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
30847  unixFile *pFile = (unixFile*)id;
30848  unixInodeInfo *pInode;
30849  struct flock lock;
30850  int rc = SQLITE_OK;
30851 
30852  assert( pFile );
30853  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
30854  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
30855  osGetpid(0)));
30856 
30857  assert( eFileLock<=SHARED_LOCK );
30858  if( pFile->eFileLock<=eFileLock ){
30859  return SQLITE_OK;
30860  }
30861  unixEnterMutex();
30862  pInode = pFile->pInode;
30863  assert( pInode->nShared!=0 );
30864  if( pFile->eFileLock>SHARED_LOCK ){
30865  assert( pInode->eFileLock==pFile->eFileLock );
30866 
30867 #ifdef SQLITE_DEBUG
30868  /* When reducing a lock such that other processes can start
30869  ** reading the database file again, make sure that the
30870  ** transaction counter was updated if any part of the database
30871  ** file changed. If the transaction counter is not updated,
30872  ** other connections to the same file might not realize that
30873  ** the file has changed and hence might not know to flush their
30874  ** cache. The use of a stale cache can lead to database corruption.
30875  */
30876  pFile->inNormalWrite = 0;
30877 #endif
30878 
30879  /* downgrading to a shared lock on NFS involves clearing the write lock
30880  ** before establishing the readlock - to avoid a race condition we downgrade
30881  ** the lock in 2 blocks, so that part of the range will be covered by a
30882  ** write lock until the rest is covered by a read lock:
30883  ** 1: [WWWWW]
30884  ** 2: [....W]
30885  ** 3: [RRRRW]
30886  ** 4: [RRRR.]
30887  */
30888  if( eFileLock==SHARED_LOCK ){
30889 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
30890  (void)handleNFSUnlock;
30891  assert( handleNFSUnlock==0 );
30892 #endif
30893 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30894  if( handleNFSUnlock ){
30895  int tErrno; /* Error code from system call errors */
30896  off_t divSize = SHARED_SIZE - 1;
30897 
30898  lock.l_type = F_UNLCK;
30899  lock.l_whence = SEEK_SET;
30900  lock.l_start = SHARED_FIRST;
30901  lock.l_len = divSize;
30902  if( unixFileLock(pFile, &lock)==(-1) ){
30903  tErrno = errno;
30904  rc = SQLITE_IOERR_UNLOCK;
30905  storeLastErrno(pFile, tErrno);
30906  goto end_unlock;
30907  }
30908  lock.l_type = F_RDLCK;
30909  lock.l_whence = SEEK_SET;
30910  lock.l_start = SHARED_FIRST;
30911  lock.l_len = divSize;
30912  if( unixFileLock(pFile, &lock)==(-1) ){
30913  tErrno = errno;
30915  if( IS_LOCK_ERROR(rc) ){
30916  storeLastErrno(pFile, tErrno);
30917  }
30918  goto end_unlock;
30919  }
30920  lock.l_type = F_UNLCK;
30921  lock.l_whence = SEEK_SET;
30922  lock.l_start = SHARED_FIRST+divSize;
30923  lock.l_len = SHARED_SIZE-divSize;
30924  if( unixFileLock(pFile, &lock)==(-1) ){
30925  tErrno = errno;
30926  rc = SQLITE_IOERR_UNLOCK;
30927  storeLastErrno(pFile, tErrno);
30928  goto end_unlock;
30929  }
30930  }else
30931 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30932  {
30933  lock.l_type = F_RDLCK;
30934  lock.l_whence = SEEK_SET;
30935  lock.l_start = SHARED_FIRST;
30936  lock.l_len = SHARED_SIZE;
30937  if( unixFileLock(pFile, &lock) ){
30938  /* In theory, the call to unixFileLock() cannot fail because another
30939  ** process is holding an incompatible lock. If it does, this
30940  ** indicates that the other process is not following the locking
30941  ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
30942  ** SQLITE_BUSY would confuse the upper layer (in practice it causes
30943  ** an assert to fail). */
30944  rc = SQLITE_IOERR_RDLOCK;
30945  storeLastErrno(pFile, errno);
30946  goto end_unlock;
30947  }
30948  }
30949  }
30950  lock.l_type = F_UNLCK;
30951  lock.l_whence = SEEK_SET;
30952  lock.l_start = PENDING_BYTE;
30953  lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
30954  if( unixFileLock(pFile, &lock)==0 ){
30955  pInode->eFileLock = SHARED_LOCK;
30956  }else{
30957  rc = SQLITE_IOERR_UNLOCK;
30958  storeLastErrno(pFile, errno);
30959  goto end_unlock;
30960  }
30961  }
30962  if( eFileLock==NO_LOCK ){
30963  /* Decrement the shared lock counter. Release the lock using an
30964  ** OS call only when all threads in this same process have released
30965  ** the lock.
30966  */
30967  pInode->nShared--;
30968  if( pInode->nShared==0 ){
30969  lock.l_type = F_UNLCK;
30970  lock.l_whence = SEEK_SET;
30971  lock.l_start = lock.l_len = 0L;
30972  if( unixFileLock(pFile, &lock)==0 ){
30973  pInode->eFileLock = NO_LOCK;
30974  }else{
30975  rc = SQLITE_IOERR_UNLOCK;
30976  storeLastErrno(pFile, errno);
30977  pInode->eFileLock = NO_LOCK;
30978  pFile->eFileLock = NO_LOCK;
30979  }
30980  }
30981 
30982  /* Decrement the count of locks against this same file. When the
30983  ** count reaches zero, close any other file descriptors whose close
30984  ** was deferred because of outstanding locks.
30985  */
30986  pInode->nLock--;
30987  assert( pInode->nLock>=0 );
30988  if( pInode->nLock==0 ){
30989  closePendingFds(pFile);
30990  }
30991  }
30992 
30993 end_unlock:
30994  unixLeaveMutex();
30995  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
30996  return rc;
30997 }
30998 
30999 /*
31000 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31001 ** must be either NO_LOCK or SHARED_LOCK.
31002 **
31003 ** If the locking level of the file descriptor is already at or below
31004 ** the requested locking level, this routine is a no-op.
31005 */
31006 static int unixUnlock(sqlite3_file *id, int eFileLock){
31007 #if SQLITE_MAX_MMAP_SIZE>0
31008  assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
31009 #endif
31010  return posixUnlock(id, eFileLock, 0);
31011 }
31012 
31013 #if SQLITE_MAX_MMAP_SIZE>0
31014 static int unixMapfile(unixFile *pFd, i64 nByte);
31015 static void unixUnmapfile(unixFile *pFd);
31016 #endif
31017 
31018 /*
31019 ** This function performs the parts of the "close file" operation
31020 ** common to all locking schemes. It closes the directory and file
31021 ** handles, if they are valid, and sets all fields of the unixFile
31022 ** structure to 0.
31023 **
31024 ** It is *not* necessary to hold the mutex when this routine is called,
31025 ** even on VxWorks. A mutex will be acquired on VxWorks by the
31026 ** vxworksReleaseFileId() routine.
31027 */
31028 static int closeUnixFile(sqlite3_file *id){
31029  unixFile *pFile = (unixFile*)id;
31030 #if SQLITE_MAX_MMAP_SIZE>0
31031  unixUnmapfile(pFile);
31032 #endif
31033  if( pFile->h>=0 ){
31034  robust_close(pFile, pFile->h, __LINE__);
31035  pFile->h = -1;
31036  }
31037 #if OS_VXWORKS
31038  if( pFile->pId ){
31039  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31040  osUnlink(pFile->pId->zCanonicalName);
31041  }
31042  vxworksReleaseFileId(pFile->pId);
31043  pFile->pId = 0;
31044  }
31045 #endif
31046 #ifdef SQLITE_UNLINK_AFTER_CLOSE
31047  if( pFile->ctrlFlags & UNIXFILE_DELETE ){
31048  osUnlink(pFile->zPath);
31049  sqlite3_free(*(char**)&pFile->zPath);
31050  pFile->zPath = 0;
31051  }
31052 #endif
31053  OSTRACE(("CLOSE %-3d\n", pFile->h));
31054  OpenCounter(-1);
31055  sqlite3_free(pFile->pUnused);
31056  memset(pFile, 0, sizeof(unixFile));
31057  return SQLITE_OK;
31058 }
31059 
31060 /*
31061 ** Close a file.
31062 */
31063 static int unixClose(sqlite3_file *id){
31064  int rc = SQLITE_OK;
31065  unixFile *pFile = (unixFile *)id;
31066  verifyDbFile(pFile);
31067  unixUnlock(id, NO_LOCK);
31068  unixEnterMutex();
31069 
31070  /* unixFile.pInode is always valid here. Otherwise, a different close
31071  ** routine (e.g. nolockClose()) would be called instead.
31072  */
31073  assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
31074  if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
31075  /* If there are outstanding locks, do not actually close the file just
31076  ** yet because that would clear those locks. Instead, add the file
31077  ** descriptor to pInode->pUnused list. It will be automatically closed
31078  ** when the last lock is cleared.
31079  */
31080  setPendingFd(pFile);
31081  }
31082  releaseInodeInfo(pFile);
31083  rc = closeUnixFile(id);
31084  unixLeaveMutex();
31085  return rc;
31086 }
31087 
31088 /************** End of the posix advisory lock implementation *****************
31089 ******************************************************************************/
31090 
31091 /******************************************************************************
31092 ****************************** No-op Locking **********************************
31093 **
31094 ** Of the various locking implementations available, this is by far the
31095 ** simplest: locking is ignored. No attempt is made to lock the database
31096 ** file for reading or writing.
31097 **
31098 ** This locking mode is appropriate for use on read-only databases
31099 ** (ex: databases that are burned into CD-ROM, for example.) It can
31100 ** also be used if the application employs some external mechanism to
31101 ** prevent simultaneous access of the same database by two or more
31102 ** database connections. But there is a serious risk of database
31103 ** corruption if this locking mode is used in situations where multiple
31104 ** database connections are accessing the same database file at the same
31105 ** time and one or more of those connections are writing.
31106 */
31107 
31108 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
31109  UNUSED_PARAMETER(NotUsed);
31110  *pResOut = 0;
31111  return SQLITE_OK;
31112 }
31113 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
31114  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31115  return SQLITE_OK;
31116 }
31117 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
31118  UNUSED_PARAMETER2(NotUsed, NotUsed2);
31119  return SQLITE_OK;
31120 }
31121 
31122 /*
31123 ** Close the file.
31124 */
31125 static int nolockClose(sqlite3_file *id) {
31126  return closeUnixFile(id);
31127 }
31128 
31129 /******************* End of the no-op lock implementation *********************
31130 ******************************************************************************/
31131 
31132 /******************************************************************************
31133 ************************* Begin dot-file Locking ******************************
31134 **
31135 ** The dotfile locking implementation uses the existence of separate lock
31136 ** files (really a directory) to control access to the database. This works
31137 ** on just about every filesystem imaginable. But there are serious downsides:
31138 **
31139 ** (1) There is zero concurrency. A single reader blocks all other
31140 ** connections from reading or writing the database.
31141 **
31142 ** (2) An application crash or power loss can leave stale lock files
31143 ** sitting around that need to be cleared manually.
31144 **
31145 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
31146 ** other locking strategy is available.
31147 **
31148 ** Dotfile locking works by creating a subdirectory in the same directory as
31149 ** the database and with the same name but with a ".lock" extension added.
31150 ** The existence of a lock directory implies an EXCLUSIVE lock. All other
31151 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
31152 */
31153 
31154 /*
31155 ** The file suffix added to the data base filename in order to create the
31156 ** lock directory.
31157 */
31158 #define DOTLOCK_SUFFIX ".lock"
31159 
31160 /*
31161 ** This routine checks if there is a RESERVED lock held on the specified
31162 ** file by this or any other process. If such a lock is held, set *pResOut
31163 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31164 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31165 **
31166 ** In dotfile locking, either a lock exists or it does not. So in this
31167 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
31168 ** is held on the file and false if the file is unlocked.
31169 */
31170 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
31171  int rc = SQLITE_OK;
31172  int reserved = 0;
31173  unixFile *pFile = (unixFile*)id;
31174 
31176 
31177  assert( pFile );
31178  reserved = osAccess((const char*)pFile->lockingContext, 0)==0;
31179  OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
31180  *pResOut = reserved;
31181  return rc;
31182 }
31183 
31184 /*
31185 ** Lock the file with the lock specified by parameter eFileLock - one
31186 ** of the following:
31187 **
31188 ** (1) SHARED_LOCK
31189 ** (2) RESERVED_LOCK
31190 ** (3) PENDING_LOCK
31191 ** (4) EXCLUSIVE_LOCK
31192 **
31193 ** Sometimes when requesting one lock state, additional lock states
31194 ** are inserted in between. The locking might fail on one of the later
31195 ** transitions leaving the lock state different from what it started but
31196 ** still short of its goal. The following chart shows the allowed
31197 ** transitions and the inserted intermediate states:
31198 **
31199 ** UNLOCKED -> SHARED
31200 ** SHARED -> RESERVED
31201 ** SHARED -> (PENDING) -> EXCLUSIVE
31202 ** RESERVED -> (PENDING) -> EXCLUSIVE
31203 ** PENDING -> EXCLUSIVE
31204 **
31205 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31206 ** routine to lower a locking level.
31207 **
31208 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
31209 ** But we track the other locking levels internally.
31210 */
31211 static int dotlockLock(sqlite3_file *id, int eFileLock) {
31212  unixFile *pFile = (unixFile*)id;
31213  char *zLockFile = (char *)pFile->lockingContext;
31214  int rc = SQLITE_OK;
31215 
31216 
31217  /* If we have any lock, then the lock file already exists. All we have
31218  ** to do is adjust our internal record of the lock level.
31219  */
31220  if( pFile->eFileLock > NO_LOCK ){
31221  pFile->eFileLock = eFileLock;
31222  /* Always update the timestamp on the old file */
31223 #ifdef HAVE_UTIME
31224  utime(zLockFile, NULL);
31225 #else
31226  utimes(zLockFile, NULL);
31227 #endif
31228  return SQLITE_OK;
31229  }
31230 
31231  /* grab an exclusive lock */
31232  rc = osMkdir(zLockFile, 0777);
31233  if( rc<0 ){
31234  /* failed to open/create the lock directory */
31235  int tErrno = errno;
31236  if( EEXIST == tErrno ){
31237  rc = SQLITE_BUSY;
31238  } else {
31240  if( rc!=SQLITE_BUSY ){
31241  storeLastErrno(pFile, tErrno);
31242  }
31243  }
31244  return rc;
31245  }
31246 
31247  /* got it, set the type and return ok */
31248  pFile->eFileLock = eFileLock;
31249  return rc;
31250 }
31251 
31252 /*
31253 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31254 ** must be either NO_LOCK or SHARED_LOCK.
31255 **
31256 ** If the locking level of the file descriptor is already at or below
31257 ** the requested locking level, this routine is a no-op.
31258 **
31259 ** When the locking level reaches NO_LOCK, delete the lock file.
31260 */
31261 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
31262  unixFile *pFile = (unixFile*)id;
31263  char *zLockFile = (char *)pFile->lockingContext;
31264  int rc;
31265 
31266  assert( pFile );
31267  OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
31268  pFile->eFileLock, osGetpid(0)));
31269  assert( eFileLock<=SHARED_LOCK );
31270 
31271  /* no-op if possible */
31272  if( pFile->eFileLock==eFileLock ){
31273  return SQLITE_OK;
31274  }
31275 
31276  /* To downgrade to shared, simply update our internal notion of the
31277  ** lock state. No need to mess with the file on disk.
31278  */
31279  if( eFileLock==SHARED_LOCK ){
31280  pFile->eFileLock = SHARED_LOCK;
31281  return SQLITE_OK;
31282  }
31283 
31284  /* To fully unlock the database, delete the lock file */
31285  assert( eFileLock==NO_LOCK );
31286  rc = osRmdir(zLockFile);
31287  if( rc<0 ){
31288  int tErrno = errno;
31289  if( tErrno==ENOENT ){
31290  rc = SQLITE_OK;
31291  }else{
31292  rc = SQLITE_IOERR_UNLOCK;
31293  storeLastErrno(pFile, tErrno);
31294  }
31295  return rc;
31296  }
31297  pFile->eFileLock = NO_LOCK;
31298  return SQLITE_OK;
31299 }
31300 
31301 /*
31302 ** Close a file. Make sure the lock has been released before closing.
31303 */
31304 static int dotlockClose(sqlite3_file *id) {
31305  unixFile *pFile = (unixFile*)id;
31306  assert( id!=0 );
31307  dotlockUnlock(id, NO_LOCK);
31308  sqlite3_free(pFile->lockingContext);
31309  return closeUnixFile(id);
31310 }
31311 /****************** End of the dot-file lock implementation *******************
31312 ******************************************************************************/
31313 
31314 /******************************************************************************
31315 ************************** Begin flock Locking ********************************
31316 **
31317 ** Use the flock() system call to do file locking.
31318 **
31319 ** flock() locking is like dot-file locking in that the various
31320 ** fine-grain locking levels supported by SQLite are collapsed into
31321 ** a single exclusive lock. In other words, SHARED, RESERVED, and
31322 ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
31323 ** still works when you do this, but concurrency is reduced since
31324 ** only a single process can be reading the database at a time.
31325 **
31326 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
31327 */
31328 #if SQLITE_ENABLE_LOCKING_STYLE
31329 
31330 /*
31331 ** Retry flock() calls that fail with EINTR
31332 */
31333 #ifdef EINTR
31334 static int robust_flock(int fd, int op){
31335  int rc;
31336  do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
31337  return rc;
31338 }
31339 #else
31340 # define robust_flock(a,b) flock(a,b)
31341 #endif
31342 
31343 
31344 /*
31345 ** This routine checks if there is a RESERVED lock held on the specified
31346 ** file by this or any other process. If such a lock is held, set *pResOut
31347 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31348 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31349 */
31350 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
31351  int rc = SQLITE_OK;
31352  int reserved = 0;
31353  unixFile *pFile = (unixFile*)id;
31354 
31356 
31357  assert( pFile );
31358 
31359  /* Check if a thread in this process holds such a lock */
31360  if( pFile->eFileLock>SHARED_LOCK ){
31361  reserved = 1;
31362  }
31363 
31364  /* Otherwise see if some other process holds it. */
31365  if( !reserved ){
31366  /* attempt to get the lock */
31367  int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
31368  if( !lrc ){
31369  /* got the lock, unlock it */
31370  lrc = robust_flock(pFile->h, LOCK_UN);
31371  if ( lrc ) {
31372  int tErrno = errno;
31373  /* unlock failed with an error */
31374  lrc = SQLITE_IOERR_UNLOCK;
31375  storeLastErrno(pFile, tErrno);
31376  rc = lrc;
31377  }
31378  } else {
31379  int tErrno = errno;
31380  reserved = 1;
31381  /* someone else might have it reserved */
31383  if( IS_LOCK_ERROR(lrc) ){
31384  storeLastErrno(pFile, tErrno);
31385  rc = lrc;
31386  }
31387  }
31388  }
31389  OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
31390 
31391 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31392  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31393  rc = SQLITE_OK;
31394  reserved=1;
31395  }
31396 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31397  *pResOut = reserved;
31398  return rc;
31399 }
31400 
31401 /*
31402 ** Lock the file with the lock specified by parameter eFileLock - one
31403 ** of the following:
31404 **
31405 ** (1) SHARED_LOCK
31406 ** (2) RESERVED_LOCK
31407 ** (3) PENDING_LOCK
31408 ** (4) EXCLUSIVE_LOCK
31409 **
31410 ** Sometimes when requesting one lock state, additional lock states
31411 ** are inserted in between. The locking might fail on one of the later
31412 ** transitions leaving the lock state different from what it started but
31413 ** still short of its goal. The following chart shows the allowed
31414 ** transitions and the inserted intermediate states:
31415 **
31416 ** UNLOCKED -> SHARED
31417 ** SHARED -> RESERVED
31418 ** SHARED -> (PENDING) -> EXCLUSIVE
31419 ** RESERVED -> (PENDING) -> EXCLUSIVE
31420 ** PENDING -> EXCLUSIVE
31421 **
31422 ** flock() only really support EXCLUSIVE locks. We track intermediate
31423 ** lock states in the sqlite3_file structure, but all locks SHARED or
31424 ** above are really EXCLUSIVE locks and exclude all other processes from
31425 ** access the file.
31426 **
31427 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31428 ** routine to lower a locking level.
31429 */
31430 static int flockLock(sqlite3_file *id, int eFileLock) {
31431  int rc = SQLITE_OK;
31432  unixFile *pFile = (unixFile*)id;
31433 
31434  assert( pFile );
31435 
31436  /* if we already have a lock, it is exclusive.
31437  ** Just adjust level and punt on outta here. */
31438  if (pFile->eFileLock > NO_LOCK) {
31439  pFile->eFileLock = eFileLock;
31440  return SQLITE_OK;
31441  }
31442 
31443  /* grab an exclusive lock */
31444 
31445  if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
31446  int tErrno = errno;
31447  /* didn't get, must be busy */
31449  if( IS_LOCK_ERROR(rc) ){
31450  storeLastErrno(pFile, tErrno);
31451  }
31452  } else {
31453  /* got it, set the type and return ok */
31454  pFile->eFileLock = eFileLock;
31455  }
31456  OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
31457  rc==SQLITE_OK ? "ok" : "failed"));
31458 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31459  if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
31460  rc = SQLITE_BUSY;
31461  }
31462 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31463  return rc;
31464 }
31465 
31466 
31467 /*
31468 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31469 ** must be either NO_LOCK or SHARED_LOCK.
31470 **
31471 ** If the locking level of the file descriptor is already at or below
31472 ** the requested locking level, this routine is a no-op.
31473 */
31474 static int flockUnlock(sqlite3_file *id, int eFileLock) {
31475  unixFile *pFile = (unixFile*)id;
31476 
31477  assert( pFile );
31478  OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
31479  pFile->eFileLock, osGetpid(0)));
31480  assert( eFileLock<=SHARED_LOCK );
31481 
31482  /* no-op if possible */
31483  if( pFile->eFileLock==eFileLock ){
31484  return SQLITE_OK;
31485  }
31486 
31487  /* shared can just be set because we always have an exclusive */
31488  if (eFileLock==SHARED_LOCK) {
31489  pFile->eFileLock = eFileLock;
31490  return SQLITE_OK;
31491  }
31492 
31493  /* no, really, unlock. */
31494  if( robust_flock(pFile->h, LOCK_UN) ){
31495 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
31496  return SQLITE_OK;
31497 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
31498  return SQLITE_IOERR_UNLOCK;
31499  }else{
31500  pFile->eFileLock = NO_LOCK;
31501  return SQLITE_OK;
31502  }
31503 }
31504 
31505 /*
31506 ** Close a file.
31507 */
31508 static int flockClose(sqlite3_file *id) {
31509  assert( id!=0 );
31510  flockUnlock(id, NO_LOCK);
31511  return closeUnixFile(id);
31512 }
31513 
31514 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
31515 
31516 /******************* End of the flock lock implementation *********************
31517 ******************************************************************************/
31518 
31519 /******************************************************************************
31520 ************************ Begin Named Semaphore Locking ************************
31521 **
31522 ** Named semaphore locking is only supported on VxWorks.
31523 **
31524 ** Semaphore locking is like dot-lock and flock in that it really only
31525 ** supports EXCLUSIVE locking. Only a single process can read or write
31526 ** the database file at a time. This reduces potential concurrency, but
31527 ** makes the lock implementation much easier.
31528 */
31529 #if OS_VXWORKS
31530 
31531 /*
31532 ** This routine checks if there is a RESERVED lock held on the specified
31533 ** file by this or any other process. If such a lock is held, set *pResOut
31534 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31535 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31536 */
31537 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
31538  int rc = SQLITE_OK;
31539  int reserved = 0;
31540  unixFile *pFile = (unixFile*)id;
31541 
31543 
31544  assert( pFile );
31545 
31546  /* Check if a thread in this process holds such a lock */
31547  if( pFile->eFileLock>SHARED_LOCK ){
31548  reserved = 1;
31549  }
31550 
31551  /* Otherwise see if some other process holds it. */
31552  if( !reserved ){
31553  sem_t *pSem = pFile->pInode->pSem;
31554 
31555  if( sem_trywait(pSem)==-1 ){
31556  int tErrno = errno;
31557  if( EAGAIN != tErrno ){
31559  storeLastErrno(pFile, tErrno);
31560  } else {
31561  /* someone else has the lock when we are in NO_LOCK */
31562  reserved = (pFile->eFileLock < SHARED_LOCK);
31563  }
31564  }else{
31565  /* we could have it if we want it */
31566  sem_post(pSem);
31567  }
31568  }
31569  OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
31570 
31571  *pResOut = reserved;
31572  return rc;
31573 }
31574 
31575 /*
31576 ** Lock the file with the lock specified by parameter eFileLock - one
31577 ** of the following:
31578 **
31579 ** (1) SHARED_LOCK
31580 ** (2) RESERVED_LOCK
31581 ** (3) PENDING_LOCK
31582 ** (4) EXCLUSIVE_LOCK
31583 **
31584 ** Sometimes when requesting one lock state, additional lock states
31585 ** are inserted in between. The locking might fail on one of the later
31586 ** transitions leaving the lock state different from what it started but
31587 ** still short of its goal. The following chart shows the allowed
31588 ** transitions and the inserted intermediate states:
31589 **
31590 ** UNLOCKED -> SHARED
31591 ** SHARED -> RESERVED
31592 ** SHARED -> (PENDING) -> EXCLUSIVE
31593 ** RESERVED -> (PENDING) -> EXCLUSIVE
31594 ** PENDING -> EXCLUSIVE
31595 **
31596 ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
31597 ** lock states in the sqlite3_file structure, but all locks SHARED or
31598 ** above are really EXCLUSIVE locks and exclude all other processes from
31599 ** access the file.
31600 **
31601 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31602 ** routine to lower a locking level.
31603 */
31604 static int semXLock(sqlite3_file *id, int eFileLock) {
31605  unixFile *pFile = (unixFile*)id;
31606  sem_t *pSem = pFile->pInode->pSem;
31607  int rc = SQLITE_OK;
31608 
31609  /* if we already have a lock, it is exclusive.
31610  ** Just adjust level and punt on outta here. */
31611  if (pFile->eFileLock > NO_LOCK) {
31612  pFile->eFileLock = eFileLock;
31613  rc = SQLITE_OK;
31614  goto sem_end_lock;
31615  }
31616 
31617  /* lock semaphore now but bail out when already locked. */
31618  if( sem_trywait(pSem)==-1 ){
31619  rc = SQLITE_BUSY;
31620  goto sem_end_lock;
31621  }
31622 
31623  /* got it, set the type and return ok */
31624  pFile->eFileLock = eFileLock;
31625 
31626  sem_end_lock:
31627  return rc;
31628 }
31629 
31630 /*
31631 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
31632 ** must be either NO_LOCK or SHARED_LOCK.
31633 **
31634 ** If the locking level of the file descriptor is already at or below
31635 ** the requested locking level, this routine is a no-op.
31636 */
31637 static int semXUnlock(sqlite3_file *id, int eFileLock) {
31638  unixFile *pFile = (unixFile*)id;
31639  sem_t *pSem = pFile->pInode->pSem;
31640 
31641  assert( pFile );
31642  assert( pSem );
31643  OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
31644  pFile->eFileLock, osGetpid(0)));
31645  assert( eFileLock<=SHARED_LOCK );
31646 
31647  /* no-op if possible */
31648  if( pFile->eFileLock==eFileLock ){
31649  return SQLITE_OK;
31650  }
31651 
31652  /* shared can just be set because we always have an exclusive */
31653  if (eFileLock==SHARED_LOCK) {
31654  pFile->eFileLock = eFileLock;
31655  return SQLITE_OK;
31656  }
31657 
31658  /* no, really unlock. */
31659  if ( sem_post(pSem)==-1 ) {
31660  int rc, tErrno = errno;
31662  if( IS_LOCK_ERROR(rc) ){
31663  storeLastErrno(pFile, tErrno);
31664  }
31665  return rc;
31666  }
31667  pFile->eFileLock = NO_LOCK;
31668  return SQLITE_OK;
31669 }
31670 
31671 /*
31672  ** Close a file.
31673  */
31674 static int semXClose(sqlite3_file *id) {
31675  if( id ){
31676  unixFile *pFile = (unixFile*)id;
31677  semXUnlock(id, NO_LOCK);
31678  assert( pFile );
31679  unixEnterMutex();
31680  releaseInodeInfo(pFile);
31681  unixLeaveMutex();
31682  closeUnixFile(id);
31683  }
31684  return SQLITE_OK;
31685 }
31686 
31687 #endif /* OS_VXWORKS */
31688 /*
31689 ** Named semaphore locking is only available on VxWorks.
31690 **
31691 *************** End of the named semaphore lock implementation ****************
31692 ******************************************************************************/
31693 
31694 
31695 /******************************************************************************
31696 *************************** Begin AFP Locking *********************************
31697 **
31698 ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
31699 ** on Apple Macintosh computers - both OS9 and OSX.
31700 **
31701 ** Third-party implementations of AFP are available. But this code here
31702 ** only works on OSX.
31703 */
31704 
31705 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31706 /*
31707 ** The afpLockingContext structure contains all afp lock specific state
31708 */
31709 typedef struct afpLockingContext afpLockingContext;
31710 struct afpLockingContext {
31711  int reserved;
31712  const char *dbPath; /* Name of the open file */
31713 };
31714 
31715 struct ByteRangeLockPB2
31716 {
31717  unsigned long long offset; /* offset to first byte to lock */
31718  unsigned long long length; /* nbr of bytes to lock */
31719  unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
31720  unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
31721  unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
31722  int fd; /* file desc to assoc this lock with */
31723 };
31724 
31725 #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
31726 
31727 /*
31728 ** This is a utility for setting or clearing a bit-range lock on an
31729 ** AFP filesystem.
31730 **
31731 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
31732 */
31733 static int afpSetLock(
31734  const char *path, /* Name of the file to be locked or unlocked */
31735  unixFile *pFile, /* Open file descriptor on path */
31736  unsigned long long offset, /* First byte to be locked */
31737  unsigned long long length, /* Number of bytes to lock */
31738  int setLockFlag /* True to set lock. False to clear lock */
31739 ){
31740  struct ByteRangeLockPB2 pb;
31741  int err;
31742 
31743  pb.unLockFlag = setLockFlag ? 0 : 1;
31744  pb.startEndFlag = 0;
31745  pb.offset = offset;
31746  pb.length = length;
31747  pb.fd = pFile->h;
31748 
31749  OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
31750  (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
31751  offset, length));
31752  err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
31753  if ( err==-1 ) {
31754  int rc;
31755  int tErrno = errno;
31756  OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
31757  path, tErrno, strerror(tErrno)));
31758 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
31759  rc = SQLITE_BUSY;
31760 #else
31761  rc = sqliteErrorFromPosixError(tErrno,
31762  setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
31763 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
31764  if( IS_LOCK_ERROR(rc) ){
31765  storeLastErrno(pFile, tErrno);
31766  }
31767  return rc;
31768  } else {
31769  return SQLITE_OK;
31770  }
31771 }
31772 
31773 /*
31774 ** This routine checks if there is a RESERVED lock held on the specified
31775 ** file by this or any other process. If such a lock is held, set *pResOut
31776 ** to a non-zero value otherwise *pResOut is set to zero. The return value
31777 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
31778 */
31779 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
31780  int rc = SQLITE_OK;
31781  int reserved = 0;
31782  unixFile *pFile = (unixFile*)id;
31783  afpLockingContext *context;
31784 
31786 
31787  assert( pFile );
31788  context = (afpLockingContext *) pFile->lockingContext;
31789  if( context->reserved ){
31790  *pResOut = 1;
31791  return SQLITE_OK;
31792  }
31793  unixEnterMutex(); /* Because pFile->pInode is shared across threads */
31794 
31795  /* Check if a thread in this process holds such a lock */
31796  if( pFile->pInode->eFileLock>SHARED_LOCK ){
31797  reserved = 1;
31798  }
31799 
31800  /* Otherwise see if some other process holds it.
31801  */
31802  if( !reserved ){
31803  /* lock the RESERVED byte */
31804  int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
31805  if( SQLITE_OK==lrc ){
31806  /* if we succeeded in taking the reserved lock, unlock it to restore
31807  ** the original state */
31808  lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
31809  } else {
31810  /* if we failed to get the lock then someone else must have it */
31811  reserved = 1;
31812  }
31813  if( IS_LOCK_ERROR(lrc) ){
31814  rc=lrc;
31815  }
31816  }
31817 
31818  unixLeaveMutex();
31819  OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
31820 
31821  *pResOut = reserved;
31822  return rc;
31823 }
31824 
31825 /*
31826 ** Lock the file with the lock specified by parameter eFileLock - one
31827 ** of the following:
31828 **
31829 ** (1) SHARED_LOCK
31830 ** (2) RESERVED_LOCK
31831 ** (3) PENDING_LOCK
31832 ** (4) EXCLUSIVE_LOCK
31833 **
31834 ** Sometimes when requesting one lock state, additional lock states
31835 ** are inserted in between. The locking might fail on one of the later
31836 ** transitions leaving the lock state different from what it started but
31837 ** still short of its goal. The following chart shows the allowed
31838 ** transitions and the inserted intermediate states:
31839 **
31840 ** UNLOCKED -> SHARED
31841 ** SHARED -> RESERVED
31842 ** SHARED -> (PENDING) -> EXCLUSIVE
31843 ** RESERVED -> (PENDING) -> EXCLUSIVE
31844 ** PENDING -> EXCLUSIVE
31845 **
31846 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
31847 ** routine to lower a locking level.
31848 */
31849 static int afpLock(sqlite3_file *id, int eFileLock){
31850  int rc = SQLITE_OK;
31851  unixFile *pFile = (unixFile*)id;
31852  unixInodeInfo *pInode = pFile->pInode;
31853  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
31854 
31855  assert( pFile );
31856  OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
31857  azFileLock(eFileLock), azFileLock(pFile->eFileLock),
31858  azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
31859 
31860  /* If there is already a lock of this type or more restrictive on the
31861  ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
31862  ** unixEnterMutex() hasn't been called yet.
31863  */
31864  if( pFile->eFileLock>=eFileLock ){
31865  OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
31866  azFileLock(eFileLock)));
31867  return SQLITE_OK;
31868  }
31869 
31870  /* Make sure the locking sequence is correct
31871  ** (1) We never move from unlocked to anything higher than shared lock.
31872  ** (2) SQLite never explicitly requests a pendig lock.
31873  ** (3) A shared lock is always held when a reserve lock is requested.
31874  */
31875  assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
31876  assert( eFileLock!=PENDING_LOCK );
31877  assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
31878 
31879  /* This mutex is needed because pFile->pInode is shared across threads
31880  */
31881  unixEnterMutex();
31882  pInode = pFile->pInode;
31883 
31884  /* If some thread using this PID has a lock via a different unixFile*
31885  ** handle that precludes the requested lock, return BUSY.
31886  */
31887  if( (pFile->eFileLock!=pInode->eFileLock &&
31888  (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
31889  ){
31890  rc = SQLITE_BUSY;
31891  goto afp_end_lock;
31892  }
31893 
31894  /* If a SHARED lock is requested, and some thread using this PID already
31895  ** has a SHARED or RESERVED lock, then increment reference counts and
31896  ** return SQLITE_OK.
31897  */
31898  if( eFileLock==SHARED_LOCK &&
31899  (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
31900  assert( eFileLock==SHARED_LOCK );
31901  assert( pFile->eFileLock==0 );
31902  assert( pInode->nShared>0 );
31903  pFile->eFileLock = SHARED_LOCK;
31904  pInode->nShared++;
31905  pInode->nLock++;
31906  goto afp_end_lock;
31907  }
31908 
31909  /* A PENDING lock is needed before acquiring a SHARED lock and before
31910  ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
31911  ** be released.
31912  */
31913  if( eFileLock==SHARED_LOCK
31914  || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
31915  ){
31916  int failed;
31917  failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
31918  if (failed) {
31919  rc = failed;
31920  goto afp_end_lock;
31921  }
31922  }
31923 
31924  /* If control gets to this point, then actually go ahead and make
31925  ** operating system calls for the specified lock.
31926  */
31927  if( eFileLock==SHARED_LOCK ){
31928  int lrc1, lrc2, lrc1Errno = 0;
31929  long lk, mask;
31930 
31931  assert( pInode->nShared==0 );
31932  assert( pInode->eFileLock==0 );
31933 
31934  mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
31935  /* Now get the read-lock SHARED_LOCK */
31936  /* note that the quality of the randomness doesn't matter that much */
31937  lk = random();
31938  pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
31939  lrc1 = afpSetLock(context->dbPath, pFile,
31940  SHARED_FIRST+pInode->sharedByte, 1, 1);
31941  if( IS_LOCK_ERROR(lrc1) ){
31942  lrc1Errno = pFile->lastErrno;
31943  }
31944  /* Drop the temporary PENDING lock */
31945  lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
31946 
31947  if( IS_LOCK_ERROR(lrc1) ) {
31948  storeLastErrno(pFile, lrc1Errno);
31949  rc = lrc1;
31950  goto afp_end_lock;
31951  } else if( IS_LOCK_ERROR(lrc2) ){
31952  rc = lrc2;
31953  goto afp_end_lock;
31954  } else if( lrc1 != SQLITE_OK ) {
31955  rc = lrc1;
31956  } else {
31957  pFile->eFileLock = SHARED_LOCK;
31958  pInode->nLock++;
31959  pInode->nShared = 1;
31960  }
31961  }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
31962  /* We are trying for an exclusive lock but another thread in this
31963  ** same process is still holding a shared lock. */
31964  rc = SQLITE_BUSY;
31965  }else{
31966  /* The request was for a RESERVED or EXCLUSIVE lock. It is
31967  ** assumed that there is a SHARED or greater lock on the file
31968  ** already.
31969  */
31970  int failed = 0;
31971  assert( 0!=pFile->eFileLock );
31972  if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
31973  /* Acquire a RESERVED lock */
31974  failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
31975  if( !failed ){
31976  context->reserved = 1;
31977  }
31978  }
31979  if (!failed && eFileLock == EXCLUSIVE_LOCK) {
31980  /* Acquire an EXCLUSIVE lock */
31981 
31982  /* Remove the shared lock before trying the range. we'll need to
31983  ** reestablish the shared lock if we can't get the afpUnlock
31984  */
31985  if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
31986  pInode->sharedByte, 1, 0)) ){
31987  int failed2 = SQLITE_OK;
31988  /* now attemmpt to get the exclusive lock range */
31989  failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
31990  SHARED_SIZE, 1);
31991  if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
31992  SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
31993  /* Can't reestablish the shared lock. Sqlite can't deal, this is
31994  ** a critical I/O error
31995  */
31996  rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
31998  goto afp_end_lock;
31999  }
32000  }else{
32001  rc = failed;
32002  }
32003  }
32004  if( failed ){
32005  rc = failed;
32006  }
32007  }
32008 
32009  if( rc==SQLITE_OK ){
32010  pFile->eFileLock = eFileLock;
32011  pInode->eFileLock = eFileLock;
32012  }else if( eFileLock==EXCLUSIVE_LOCK ){
32013  pFile->eFileLock = PENDING_LOCK;
32014  pInode->eFileLock = PENDING_LOCK;
32015  }
32016 
32017 afp_end_lock:
32018  unixLeaveMutex();
32019  OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
32020  rc==SQLITE_OK ? "ok" : "failed"));
32021  return rc;
32022 }
32023 
32024 /*
32025 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32026 ** must be either NO_LOCK or SHARED_LOCK.
32027 **
32028 ** If the locking level of the file descriptor is already at or below
32029 ** the requested locking level, this routine is a no-op.
32030 */
32031 static int afpUnlock(sqlite3_file *id, int eFileLock) {
32032  int rc = SQLITE_OK;
32033  unixFile *pFile = (unixFile*)id;
32034  unixInodeInfo *pInode;
32035  afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
32036  int skipShared = 0;
32037 #ifdef SQLITE_TEST
32038  int h = pFile->h;
32039 #endif
32040 
32041  assert( pFile );
32042  OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
32043  pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
32044  osGetpid(0)));
32045 
32046  assert( eFileLock<=SHARED_LOCK );
32047  if( pFile->eFileLock<=eFileLock ){
32048  return SQLITE_OK;
32049  }
32050  unixEnterMutex();
32051  pInode = pFile->pInode;
32052  assert( pInode->nShared!=0 );
32053  if( pFile->eFileLock>SHARED_LOCK ){
32054  assert( pInode->eFileLock==pFile->eFileLock );
32056  SimulateIOError( h=(-1) )
32058 
32059 #ifdef SQLITE_DEBUG
32060  /* When reducing a lock such that other processes can start
32061  ** reading the database file again, make sure that the
32062  ** transaction counter was updated if any part of the database
32063  ** file changed. If the transaction counter is not updated,
32064  ** other connections to the same file might not realize that
32065  ** the file has changed and hence might not know to flush their
32066  ** cache. The use of a stale cache can lead to database corruption.
32067  */
32068  assert( pFile->inNormalWrite==0
32069  || pFile->dbUpdate==0
32070  || pFile->transCntrChng==1 );
32071  pFile->inNormalWrite = 0;
32072 #endif
32073 
32074  if( pFile->eFileLock==EXCLUSIVE_LOCK ){
32075  rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
32076  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
32077  /* only re-establish the shared lock if necessary */
32078  int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32079  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
32080  } else {
32081  skipShared = 1;
32082  }
32083  }
32084  if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
32085  rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
32086  }
32087  if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
32088  rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
32089  if( !rc ){
32090  context->reserved = 0;
32091  }
32092  }
32093  if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
32094  pInode->eFileLock = SHARED_LOCK;
32095  }
32096  }
32097  if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
32098 
32099  /* Decrement the shared lock counter. Release the lock using an
32100  ** OS call only when all threads in this same process have released
32101  ** the lock.
32102  */
32103  unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
32104  pInode->nShared--;
32105  if( pInode->nShared==0 ){
32107  SimulateIOError( h=(-1) )
32109  if( !skipShared ){
32110  rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
32111  }
32112  if( !rc ){
32113  pInode->eFileLock = NO_LOCK;
32114  pFile->eFileLock = NO_LOCK;
32115  }
32116  }
32117  if( rc==SQLITE_OK ){
32118  pInode->nLock--;
32119  assert( pInode->nLock>=0 );
32120  if( pInode->nLock==0 ){
32121  closePendingFds(pFile);
32122  }
32123  }
32124  }
32125 
32126  unixLeaveMutex();
32127  if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
32128  return rc;
32129 }
32130 
32131 /*
32132 ** Close a file & cleanup AFP specific locking context
32133 */
32134 static int afpClose(sqlite3_file *id) {
32135  int rc = SQLITE_OK;
32136  unixFile *pFile = (unixFile*)id;
32137  assert( id!=0 );
32138  afpUnlock(id, NO_LOCK);
32139  unixEnterMutex();
32140  if( pFile->pInode && pFile->pInode->nLock ){
32141  /* If there are outstanding locks, do not actually close the file just
32142  ** yet because that would clear those locks. Instead, add the file
32143  ** descriptor to pInode->aPending. It will be automatically closed when
32144  ** the last lock is cleared.
32145  */
32146  setPendingFd(pFile);
32147  }
32148  releaseInodeInfo(pFile);
32149  sqlite3_free(pFile->lockingContext);
32150  rc = closeUnixFile(id);
32151  unixLeaveMutex();
32152  return rc;
32153 }
32154 
32155 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32156 /*
32157 ** The code above is the AFP lock implementation. The code is specific
32158 ** to MacOSX and does not work on other unix platforms. No alternative
32159 ** is available. If you don't compile for a mac, then the "unix-afp"
32160 ** VFS is not available.
32161 **
32162 ********************* End of the AFP lock implementation **********************
32163 ******************************************************************************/
32164 
32165 /******************************************************************************
32166 *************************** Begin NFS Locking ********************************/
32167 
32168 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
32169 /*
32170  ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
32171  ** must be either NO_LOCK or SHARED_LOCK.
32172  **
32173  ** If the locking level of the file descriptor is already at or below
32174  ** the requested locking level, this routine is a no-op.
32175  */
32176 static int nfsUnlock(sqlite3_file *id, int eFileLock){
32177  return posixUnlock(id, eFileLock, 1);
32178 }
32179 
32180 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32181 /*
32182 ** The code above is the NFS lock implementation. The code is specific
32183 ** to MacOSX and does not work on other unix platforms. No alternative
32184 ** is available.
32185 **
32186 ********************* End of the NFS lock implementation **********************
32187 ******************************************************************************/
32188 
32189 /******************************************************************************
32190 **************** Non-locking sqlite3_file methods *****************************
32191 **
32192 ** The next division contains implementations for all methods of the
32193 ** sqlite3_file object other than the locking methods. The locking
32194 ** methods were defined in divisions above (one locking method per
32195 ** division). Those methods that are common to all locking modes
32196 ** are gather together into this division.
32197 */
32198 
32199 /*
32200 ** Seek to the offset passed as the second argument, then read cnt
32201 ** bytes into pBuf. Return the number of bytes actually read.
32202 **
32203 ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
32204 ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
32205 ** one system to another. Since SQLite does not define USE_PREAD
32206 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
32207 ** See tickets #2741 and #2681.
32208 **
32209 ** To avoid stomping the errno value on a failed read the lastErrno value
32210 ** is set before returning.
32211 */
32212 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
32213  int got;
32214  int prior = 0;
32215 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
32216  i64 newOffset;
32217 #endif
32218  TIMER_START;
32219  assert( cnt==(cnt&0x1ffff) );
32220  assert( id->h>2 );
32221  do{
32222 #if defined(USE_PREAD)
32223  got = osPread(id->h, pBuf, cnt, offset);
32224  SimulateIOError( got = -1 );
32225 #elif defined(USE_PREAD64)
32226  got = osPread64(id->h, pBuf, cnt, offset);
32227  SimulateIOError( got = -1 );
32228 #else
32229  newOffset = lseek(id->h, offset, SEEK_SET);
32230  SimulateIOError( newOffset = -1 );
32231  if( newOffset<0 ){
32232  storeLastErrno((unixFile*)id, errno);
32233  return -1;
32234  }
32235  got = osRead(id->h, pBuf, cnt);
32236 #endif
32237  if( got==cnt ) break;
32238  if( got<0 ){
32239  if( errno==EINTR ){ got = 1; continue; }
32240  prior = 0;
32241  storeLastErrno((unixFile*)id, errno);
32242  break;
32243  }else if( got>0 ){
32244  cnt -= got;
32245  offset += got;
32246  prior += got;
32247  pBuf = (void*)(got + (char*)pBuf);
32248  }
32249  }while( got>0 );
32250  TIMER_END;
32251  OSTRACE(("READ %-3d %5d %7lld %llu\n",
32252  id->h, got+prior, offset-prior, TIMER_ELAPSED));
32253  return got+prior;
32254 }
32255 
32256 /*
32257 ** Read data from a file into a buffer. Return SQLITE_OK if all
32258 ** bytes were read successfully and SQLITE_IOERR if anything goes
32259 ** wrong.
32260 */
32261 static int unixRead(
32262  sqlite3_file *id,
32263  void *pBuf,
32264  int amt,
32265  sqlite3_int64 offset
32266 ){
32267  unixFile *pFile = (unixFile *)id;
32268  int got;
32269  assert( id );
32270  assert( offset>=0 );
32271  assert( amt>0 );
32272 
32273  /* If this is a database file (not a journal, master-journal or temp
32274  ** file), the bytes in the locking range should never be read or written. */
32275 #if 0
32276  assert( pFile->pUnused==0
32277  || offset>=PENDING_BYTE+512
32278  || offset+amt<=PENDING_BYTE
32279  );
32280 #endif
32281 
32282 #if SQLITE_MAX_MMAP_SIZE>0
32283  /* Deal with as much of this read request as possible by transfering
32284  ** data from the memory mapping using memcpy(). */
32285  if( offset<pFile->mmapSize ){
32286  if( offset+amt <= pFile->mmapSize ){
32287  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
32288  return SQLITE_OK;
32289  }else{
32290  int nCopy = pFile->mmapSize - offset;
32291  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
32292  pBuf = &((u8 *)pBuf)[nCopy];
32293  amt -= nCopy;
32294  offset += nCopy;
32295  }
32296  }
32297 #endif
32298 
32299  got = seekAndRead(pFile, offset, pBuf, amt);
32300  if( got==amt ){
32301  return SQLITE_OK;
32302  }else if( got<0 ){
32303  /* lastErrno set by seekAndRead */
32304  return SQLITE_IOERR_READ;
32305  }else{
32306  storeLastErrno(pFile, 0); /* not a system error */
32307  /* Unread parts of the buffer must be zero-filled */
32308  memset(&((char*)pBuf)[got], 0, amt-got);
32309  return SQLITE_IOERR_SHORT_READ;
32310  }
32311 }
32312 
32313 /*
32314 ** Attempt to seek the file-descriptor passed as the first argument to
32315 ** absolute offset iOff, then attempt to write nBuf bytes of data from
32316 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
32317 ** return the actual number of bytes written (which may be less than
32318 ** nBuf).
32319 */
32320 static int seekAndWriteFd(
32321  int fd, /* File descriptor to write to */
32322  i64 iOff, /* File offset to begin writing at */
32323  const void *pBuf, /* Copy data from this buffer to the file */
32324  int nBuf, /* Size of buffer pBuf in bytes */
32325  int *piErrno /* OUT: Error number if error occurs */
32326 ){
32327  int rc = 0; /* Value returned by system call */
32328 
32329  assert( nBuf==(nBuf&0x1ffff) );
32330  assert( fd>2 );
32331  assert( piErrno!=0 );
32332  nBuf &= 0x1ffff;
32333  TIMER_START;
32334 
32335 #if defined(USE_PREAD)
32336  do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
32337 #elif defined(USE_PREAD64)
32338  do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
32339 #else
32340  do{
32341  i64 iSeek = lseek(fd, iOff, SEEK_SET);
32342  SimulateIOError( iSeek = -1 );
32343  if( iSeek<0 ){
32344  rc = -1;
32345  break;
32346  }
32347  rc = osWrite(fd, pBuf, nBuf);
32348  }while( rc<0 && errno==EINTR );
32349 #endif
32350 
32351  TIMER_END;
32352  OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
32353 
32354  if( rc<0 ) *piErrno = errno;
32355  return rc;
32356 }
32357 
32358 
32359 /*
32360 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
32361 ** Return the number of bytes actually read. Update the offset.
32362 **
32363 ** To avoid stomping the errno value on a failed write the lastErrno value
32364 ** is set before returning.
32365 */
32366 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
32367  return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
32368 }
32369 
32370 
32371 /*
32372 ** Write data from a buffer into a file. Return SQLITE_OK on success
32373 ** or some other error code on failure.
32374 */
32375 static int unixWrite(
32376  sqlite3_file *id,
32377  const void *pBuf,
32378  int amt,
32379  sqlite3_int64 offset
32380 ){
32381  unixFile *pFile = (unixFile*)id;
32382  int wrote = 0;
32383  assert( id );
32384  assert( amt>0 );
32385 
32386  /* If this is a database file (not a journal, master-journal or temp
32387  ** file), the bytes in the locking range should never be read or written. */
32388 #if 0
32389  assert( pFile->pUnused==0
32390  || offset>=PENDING_BYTE+512
32391  || offset+amt<=PENDING_BYTE
32392  );
32393 #endif
32394 
32395 #ifdef SQLITE_DEBUG
32396  /* If we are doing a normal write to a database file (as opposed to
32397  ** doing a hot-journal rollback or a write to some file other than a
32398  ** normal database file) then record the fact that the database
32399  ** has changed. If the transaction counter is modified, record that
32400  ** fact too.
32401  */
32402  if( pFile->inNormalWrite ){
32403  pFile->dbUpdate = 1; /* The database has been modified */
32404  if( offset<=24 && offset+amt>=27 ){
32405  int rc;
32406  char oldCntr[4];
32408  rc = seekAndRead(pFile, 24, oldCntr, 4);
32410  if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
32411  pFile->transCntrChng = 1; /* The transaction counter has changed */
32412  }
32413  }
32414  }
32415 #endif
32416 
32417 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
32418  /* Deal with as much of this write request as possible by transfering
32419  ** data from the memory mapping using memcpy(). */
32420  if( offset<pFile->mmapSize ){
32421  if( offset+amt <= pFile->mmapSize ){
32422  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
32423  return SQLITE_OK;
32424  }else{
32425  int nCopy = pFile->mmapSize - offset;
32426  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
32427  pBuf = &((u8 *)pBuf)[nCopy];
32428  amt -= nCopy;
32429  offset += nCopy;
32430  }
32431  }
32432 #endif
32433 
32434  while( (wrote = seekAndWrite(pFile, offset, pBuf, amt))<amt && wrote>0 ){
32435  amt -= wrote;
32436  offset += wrote;
32437  pBuf = &((char*)pBuf)[wrote];
32438  }
32439  SimulateIOError(( wrote=(-1), amt=1 ));
32440  SimulateDiskfullError(( wrote=0, amt=1 ));
32441 
32442  if( amt>wrote ){
32443  if( wrote<0 && pFile->lastErrno!=ENOSPC ){
32444  /* lastErrno set by seekAndWrite */
32445  return SQLITE_IOERR_WRITE;
32446  }else{
32447  storeLastErrno(pFile, 0); /* not a system error */
32448  return SQLITE_FULL;
32449  }
32450  }
32451 
32452  return SQLITE_OK;
32453 }
32454 
32455 #ifdef SQLITE_TEST
32456 /*
32457 ** Count the number of fullsyncs and normal syncs. This is used to test
32458 ** that syncs and fullsyncs are occurring at the right times.
32459 */
32460 SQLITE_API int sqlite3_sync_count = 0;
32461 SQLITE_API int sqlite3_fullsync_count = 0;
32462 #endif
32463 
32464 /*
32465 ** We do not trust systems to provide a working fdatasync(). Some do.
32466 ** Others do no. To be safe, we will stick with the (slightly slower)
32467 ** fsync(). If you know that your system does support fdatasync() correctly,
32468 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
32469 */
32470 #if !defined(fdatasync) && !HAVE_FDATASYNC
32471 # define fdatasync fsync
32472 #endif
32473 
32474 /*
32475 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
32476 ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
32477 ** only available on Mac OS X. But that could change.
32478 */
32479 #ifdef F_FULLFSYNC
32480 # define HAVE_FULLFSYNC 1
32481 #else
32482 # define HAVE_FULLFSYNC 0
32483 #endif
32484 
32485 
32486 /*
32487 ** The fsync() system call does not work as advertised on many
32488 ** unix systems. The following procedure is an attempt to make
32489 ** it work better.
32490 **
32491 ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
32492 ** for testing when we want to run through the test suite quickly.
32493 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
32494 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
32495 ** or power failure will likely corrupt the database file.
32496 **
32497 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
32498 ** The idea behind dataOnly is that it should only write the file content
32499 ** to disk, not the inode. We only set dataOnly if the file size is
32500 ** unchanged since the file size is part of the inode. However,
32501 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
32502 ** file size has changed. The only real difference between fdatasync()
32503 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
32504 ** inode if the mtime or owner or other inode attributes have changed.
32505 ** We only care about the file size, not the other file attributes, so
32506 ** as far as SQLite is concerned, an fdatasync() is always adequate.
32507 ** So, we always use fdatasync() if it is available, regardless of
32508 ** the value of the dataOnly flag.
32509 */
32510 static int full_fsync(int fd, int fullSync, int dataOnly){
32511  int rc;
32512 
32513  /* The following "ifdef/elif/else/" block has the same structure as
32514  ** the one below. It is replicated here solely to avoid cluttering
32515  ** up the real code with the UNUSED_PARAMETER() macros.
32516  */
32517 #ifdef SQLITE_NO_SYNC
32518  UNUSED_PARAMETER(fd);
32519  UNUSED_PARAMETER(fullSync);
32520  UNUSED_PARAMETER(dataOnly);
32521 #elif HAVE_FULLFSYNC
32522  UNUSED_PARAMETER(dataOnly);
32523 #else
32524  UNUSED_PARAMETER(fullSync);
32525  UNUSED_PARAMETER(dataOnly);
32526 #endif
32527 
32528  /* Record the number of times that we do a normal fsync() and
32529  ** FULLSYNC. This is used during testing to verify that this procedure
32530  ** gets called with the correct arguments.
32531  */
32532 #ifdef SQLITE_TEST
32533  if( fullSync ) sqlite3_fullsync_count++;
32534  sqlite3_sync_count++;
32535 #endif
32536 
32537  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
32538  ** no-op. But go ahead and call fstat() to validate the file
32539  ** descriptor as we need a method to provoke a failure during
32540  ** coverate testing.
32541  */
32542 #ifdef SQLITE_NO_SYNC
32543  {
32544  struct stat buf;
32545  rc = osFstat(fd, &buf);
32546  }
32547 #elif HAVE_FULLFSYNC
32548  if( fullSync ){
32549  rc = osFcntl(fd, F_FULLFSYNC, 0);
32550  }else{
32551  rc = 1;
32552  }
32553  /* If the FULLFSYNC failed, fall back to attempting an fsync().
32554  ** It shouldn't be possible for fullfsync to fail on the local
32555  ** file system (on OSX), so failure indicates that FULLFSYNC
32556  ** isn't supported for this file system. So, attempt an fsync
32557  ** and (for now) ignore the overhead of a superfluous fcntl call.
32558  ** It'd be better to detect fullfsync support once and avoid
32559  ** the fcntl call every time sync is called.
32560  */
32561  if( rc ) rc = fsync(fd);
32562 
32563 #elif defined(__APPLE__)
32564  /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
32565  ** so currently we default to the macro that redefines fdatasync to fsync
32566  */
32567  rc = fsync(fd);
32568 #else
32569  rc = fdatasync(fd);
32570 #if OS_VXWORKS
32571  if( rc==-1 && errno==ENOTSUP ){
32572  rc = fsync(fd);
32573  }
32574 #endif /* OS_VXWORKS */
32575 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
32576 
32577  if( OS_VXWORKS && rc!= -1 ){
32578  rc = 0;
32579  }
32580  return rc;
32581 }
32582 
32583 /*
32584 ** Open a file descriptor to the directory containing file zFilename.
32585 ** If successful, *pFd is set to the opened file descriptor and
32586 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
32587 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
32588 ** value.
32589 **
32590 ** The directory file descriptor is used for only one thing - to
32591 ** fsync() a directory to make sure file creation and deletion events
32592 ** are flushed to disk. Such fsyncs are not needed on newer
32593 ** journaling filesystems, but are required on older filesystems.
32594 **
32595 ** This routine can be overridden using the xSetSysCall interface.
32596 ** The ability to override this routine was added in support of the
32597 ** chromium sandbox. Opening a directory is a security risk (we are
32598 ** told) so making it overrideable allows the chromium sandbox to
32599 ** replace this routine with a harmless no-op. To make this routine
32600 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
32601 ** *pFd set to a negative number.
32602 **
32603 ** If SQLITE_OK is returned, the caller is responsible for closing
32604 ** the file descriptor *pFd using close().
32605 */
32606 static int openDirectory(const char *zFilename, int *pFd){
32607  int ii;
32608  int fd = -1;
32609  char zDirname[MAX_PATHNAME+1];
32610 
32611  sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
32612  for(ii=(int)strlen(zDirname); ii>0 && zDirname[ii]!='/'; ii--);
32613  if( ii>0 ){
32614  zDirname[ii] = '\0';
32615  }else{
32616  if( zDirname[0]!='/' ) zDirname[0] = '.';
32617  zDirname[1] = 0;
32618  }
32619  fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
32620  if( fd>=0 ){
32621  OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
32622  }
32623  *pFd = fd;
32624  if( fd>=0 ) return SQLITE_OK;
32625  return unixLogError(SQLITE_CANTOPEN_BKPT, "openDirectory", zDirname);
32626 }
32627 
32628 /*
32629 ** Make sure all writes to a particular file are committed to disk.
32630 **
32631 ** If dataOnly==0 then both the file itself and its metadata (file
32632 ** size, access time, etc) are synced. If dataOnly!=0 then only the
32633 ** file data is synced.
32634 **
32635 ** Under Unix, also make sure that the directory entry for the file
32636 ** has been created by fsync-ing the directory that contains the file.
32637 ** If we do not do this and we encounter a power failure, the directory
32638 ** entry for the journal might not exist after we reboot. The next
32639 ** SQLite to access the file will not know that the journal exists (because
32640 ** the directory entry for the journal was never created) and the transaction
32641 ** will not roll back - possibly leading to database corruption.
32642 */
32643 static int unixSync(sqlite3_file *id, int flags){
32644  int rc;
32645  unixFile *pFile = (unixFile*)id;
32646 
32647  int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
32648  int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
32649 
32650  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
32651  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
32652  || (flags&0x0F)==SQLITE_SYNC_FULL
32653  );
32654 
32655  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
32656  ** line is to test that doing so does not cause any problems.
32657  */
32659 
32660  assert( pFile );
32661  OSTRACE(("SYNC %-3d\n", pFile->h));
32662  rc = full_fsync(pFile->h, isFullsync, isDataOnly);
32663  SimulateIOError( rc=1 );
32664  if( rc ){
32665  storeLastErrno(pFile, errno);
32666  return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
32667  }
32668 
32669  /* Also fsync the directory containing the file if the DIRSYNC flag
32670  ** is set. This is a one-time occurrence. Many systems (examples: AIX)
32671  ** are unable to fsync a directory, so ignore errors on the fsync.
32672  */
32673  if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
32674  int dirfd;
32675  OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
32676  HAVE_FULLFSYNC, isFullsync));
32677  rc = osOpenDirectory(pFile->zPath, &dirfd);
32678  if( rc==SQLITE_OK ){
32679  full_fsync(dirfd, 0, 0);
32680  robust_close(pFile, dirfd, __LINE__);
32681  }else{
32682  assert( rc==SQLITE_CANTOPEN );
32683  rc = SQLITE_OK;
32684  }
32685  pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
32686  }
32687  return rc;
32688 }
32689 
32690 /*
32691 ** Truncate an open file to a specified size
32692 */
32693 static int unixTruncate(sqlite3_file *id, i64 nByte){
32694  unixFile *pFile = (unixFile *)id;
32695  int rc;
32696  assert( pFile );
32698 
32699  /* If the user has configured a chunk-size for this file, truncate the
32700  ** file so that it consists of an integer number of chunks (i.e. the
32701  ** actual file size after the operation may be larger than the requested
32702  ** size).
32703  */
32704  if( pFile->szChunk>0 ){
32705  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
32706  }
32707 
32708  rc = robust_ftruncate(pFile->h, nByte);
32709  if( rc ){
32710  storeLastErrno(pFile, errno);
32711  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
32712  }else{
32713 #ifdef SQLITE_DEBUG
32714  /* If we are doing a normal write to a database file (as opposed to
32715  ** doing a hot-journal rollback or a write to some file other than a
32716  ** normal database file) and we truncate the file to zero length,
32717  ** that effectively updates the change counter. This might happen
32718  ** when restoring a database using the backup API from a zero-length
32719  ** source.
32720  */
32721  if( pFile->inNormalWrite && nByte==0 ){
32722  pFile->transCntrChng = 1;
32723  }
32724 #endif
32725 
32726 #if SQLITE_MAX_MMAP_SIZE>0
32727  /* If the file was just truncated to a size smaller than the currently
32728  ** mapped region, reduce the effective mapping size as well. SQLite will
32729  ** use read() and write() to access data beyond this point from now on.
32730  */
32731  if( nByte<pFile->mmapSize ){
32732  pFile->mmapSize = nByte;
32733  }
32734 #endif
32735 
32736  return SQLITE_OK;
32737  }
32738 }
32739 
32740 /*
32741 ** Determine the current size of a file in bytes
32742 */
32743 static int unixFileSize(sqlite3_file *id, i64 *pSize){
32744  int rc;
32745  struct stat buf;
32746  assert( id );
32747  rc = osFstat(((unixFile*)id)->h, &buf);
32748  SimulateIOError( rc=1 );
32749  if( rc!=0 ){
32750  storeLastErrno((unixFile*)id, errno);
32751  return SQLITE_IOERR_FSTAT;
32752  }
32753  *pSize = buf.st_size;
32754 
32755  /* When opening a zero-size database, the findInodeInfo() procedure
32756  ** writes a single byte into that file in order to work around a bug
32757  ** in the OS-X msdos filesystem. In order to avoid problems with upper
32758  ** layers, we need to report this file size as zero even though it is
32759  ** really 1. Ticket #3260.
32760  */
32761  if( *pSize==1 ) *pSize = 0;
32762 
32763 
32764  return SQLITE_OK;
32765 }
32766 
32767 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32768 /*
32769 ** Handler for proxy-locking file-control verbs. Defined below in the
32770 ** proxying locking division.
32771 */
32772 static int proxyFileControl(sqlite3_file*,int,void*);
32773 #endif
32774 
32775 /*
32776 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
32777 ** file-control operation. Enlarge the database to nBytes in size
32778 ** (rounded up to the next chunk-size). If the database is already
32779 ** nBytes or larger, this routine is a no-op.
32780 */
32781 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
32782  if( pFile->szChunk>0 ){
32783  i64 nSize; /* Required file size */
32784  struct stat buf; /* Used to hold return values of fstat() */
32785 
32786  if( osFstat(pFile->h, &buf) ){
32787  return SQLITE_IOERR_FSTAT;
32788  }
32789 
32790  nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
32791  if( nSize>(i64)buf.st_size ){
32792 
32793 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
32794  /* The code below is handling the return value of osFallocate()
32795  ** correctly. posix_fallocate() is defined to "returns zero on success,
32796  ** or an error number on failure". See the manpage for details. */
32797  int err;
32798  do{
32799  err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
32800  }while( err==EINTR );
32801  if( err ) return SQLITE_IOERR_WRITE;
32802 #else
32803  /* If the OS does not have posix_fallocate(), fake it. Write a
32804  ** single byte to the last byte in each block that falls entirely
32805  ** within the extended region. Then, if required, a single byte
32806  ** at offset (nSize-1), to set the size of the file correctly.
32807  ** This is a similar technique to that used by glibc on systems
32808  ** that do not have a real fallocate() call.
32809  */
32810  int nBlk = buf.st_blksize; /* File-system block size */
32811  int nWrite = 0; /* Number of bytes written by seekAndWrite */
32812  i64 iWrite; /* Next offset to write to */
32813 
32814  iWrite = (buf.st_size/nBlk)*nBlk + nBlk - 1;
32815  assert( iWrite>=buf.st_size );
32816  assert( ((iWrite+1)%nBlk)==0 );
32817  for(/*no-op*/; iWrite<nSize+nBlk-1; iWrite+=nBlk ){
32818  if( iWrite>=nSize ) iWrite = nSize - 1;
32819  nWrite = seekAndWrite(pFile, iWrite, "", 1);
32820  if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
32821  }
32822 #endif
32823  }
32824  }
32825 
32826 #if SQLITE_MAX_MMAP_SIZE>0
32827  if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
32828  int rc;
32829  if( pFile->szChunk<=0 ){
32830  if( robust_ftruncate(pFile->h, nByte) ){
32831  storeLastErrno(pFile, errno);
32832  return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
32833  }
32834  }
32835 
32836  rc = unixMapfile(pFile, nByte);
32837  return rc;
32838  }
32839 #endif
32840 
32841  return SQLITE_OK;
32842 }
32843 
32844 /*
32845 ** If *pArg is initially negative then this is a query. Set *pArg to
32846 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
32847 **
32848 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
32849 */
32850 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
32851  if( *pArg<0 ){
32852  *pArg = (pFile->ctrlFlags & mask)!=0;
32853  }else if( (*pArg)==0 ){
32854  pFile->ctrlFlags &= ~mask;
32855  }else{
32856  pFile->ctrlFlags |= mask;
32857  }
32858 }
32859 
32860 /* Forward declaration */
32861 static int unixGetTempname(int nBuf, char *zBuf);
32862 
32863 /*
32864 ** Information and control of an open file handle.
32865 */
32866 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
32867  unixFile *pFile = (unixFile*)id;
32868  switch( op ){
32869  case SQLITE_FCNTL_LOCKSTATE: {
32870  *(int*)pArg = pFile->eFileLock;
32871  return SQLITE_OK;
32872  }
32873  case SQLITE_FCNTL_LAST_ERRNO: {
32874  *(int*)pArg = pFile->lastErrno;
32875  return SQLITE_OK;
32876  }
32877  case SQLITE_FCNTL_CHUNK_SIZE: {
32878  pFile->szChunk = *(int *)pArg;
32879  return SQLITE_OK;
32880  }
32881  case SQLITE_FCNTL_SIZE_HINT: {
32882  int rc;
32884  rc = fcntlSizeHint(pFile, *(i64 *)pArg);
32886  return rc;
32887  }
32888  case SQLITE_FCNTL_PERSIST_WAL: {
32889  unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
32890  return SQLITE_OK;
32891  }
32893  unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
32894  return SQLITE_OK;
32895  }
32896  case SQLITE_FCNTL_VFSNAME: {
32897  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
32898  return SQLITE_OK;
32899  }
32901  char *zTFile = sqlite3_malloc64( pFile->pVfs->mxPathname );
32902  if( zTFile ){
32903  unixGetTempname(pFile->pVfs->mxPathname, zTFile);
32904  *(char**)pArg = zTFile;
32905  }
32906  return SQLITE_OK;
32907  }
32908  case SQLITE_FCNTL_HAS_MOVED: {
32909  *(int*)pArg = fileHasMoved(pFile);
32910  return SQLITE_OK;
32911  }
32912 #if SQLITE_MAX_MMAP_SIZE>0
32913  case SQLITE_FCNTL_MMAP_SIZE: {
32914  i64 newLimit = *(i64*)pArg;
32915  int rc = SQLITE_OK;
32916  if( newLimit>sqlite3GlobalConfig.mxMmap ){
32917  newLimit = sqlite3GlobalConfig.mxMmap;
32918  }
32919  *(i64*)pArg = pFile->mmapSizeMax;
32920  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
32921  pFile->mmapSizeMax = newLimit;
32922  if( pFile->mmapSize>0 ){
32923  unixUnmapfile(pFile);
32924  rc = unixMapfile(pFile, -1);
32925  }
32926  }
32927  return rc;
32928  }
32929 #endif
32930 #ifdef SQLITE_DEBUG
32931  /* The pager calls this method to signal that it has done
32932  ** a rollback and that the database is therefore unchanged and
32933  ** it hence it is OK for the transaction change counter to be
32934  ** unchanged.
32935  */
32937  ((unixFile*)id)->dbUpdate = 0;
32938  return SQLITE_OK;
32939  }
32940 #endif
32941 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32944  return proxyFileControl(id,op,pArg);
32945  }
32946 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
32947  }
32948  return SQLITE_NOTFOUND;
32949 }
32950 
32951 /*
32952 ** Return the sector size in bytes of the underlying block device for
32953 ** the specified file. This is almost always 512 bytes, but may be
32954 ** larger for some devices.
32955 **
32956 ** SQLite code assumes this function cannot fail. It also assumes that
32957 ** if two files are created in the same file-system directory (i.e.
32958 ** a database and its journal file) that the sector size will be the
32959 ** same for both.
32960 */
32961 #ifndef __QNXNTO__
32962 static int unixSectorSize(sqlite3_file *NotUsed){
32963  UNUSED_PARAMETER(NotUsed);
32965 }
32966 #endif
32967 
32968 /*
32969 ** The following version of unixSectorSize() is optimized for QNX.
32970 */
32971 #ifdef __QNXNTO__
32972 #include <sys/dcmd_blk.h>
32973 #include <sys/statvfs.h>
32974 static int unixSectorSize(sqlite3_file *id){
32975  unixFile *pFile = (unixFile*)id;
32976  if( pFile->sectorSize == 0 ){
32977  struct statvfs fsInfo;
32978 
32979  /* Set defaults for non-supported filesystems */
32980  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
32981  pFile->deviceCharacteristics = 0;
32982  if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
32983  return pFile->sectorSize;
32984  }
32985 
32986  if( !strcmp(fsInfo.f_basetype, "tmp") ) {
32987  pFile->sectorSize = fsInfo.f_bsize;
32988  pFile->deviceCharacteristics =
32989  SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
32990  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
32991  ** the write succeeds */
32992  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
32993  ** so it is ordered */
32994  0;
32995  }else if( strstr(fsInfo.f_basetype, "etfs") ){
32996  pFile->sectorSize = fsInfo.f_bsize;
32997  pFile->deviceCharacteristics =
32998  /* etfs cluster size writes are atomic */
32999  (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
33000  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33001  ** the write succeeds */
33002  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33003  ** so it is ordered */
33004  0;
33005  }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
33006  pFile->sectorSize = fsInfo.f_bsize;
33007  pFile->deviceCharacteristics =
33008  SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
33009  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33010  ** the write succeeds */
33011  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33012  ** so it is ordered */
33013  0;
33014  }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
33015  pFile->sectorSize = fsInfo.f_bsize;
33016  pFile->deviceCharacteristics =
33017  /* full bitset of atomics from max sector size and smaller */
33018  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33019  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33020  ** so it is ordered */
33021  0;
33022  }else if( strstr(fsInfo.f_basetype, "dos") ){
33023  pFile->sectorSize = fsInfo.f_bsize;
33024  pFile->deviceCharacteristics =
33025  /* full bitset of atomics from max sector size and smaller */
33026  ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
33027  SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
33028  ** so it is ordered */
33029  0;
33030  }else{
33031  pFile->deviceCharacteristics =
33032  SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
33033  SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
33034  ** the write succeeds */
33035  0;
33036  }
33037  }
33038  /* Last chance verification. If the sector size isn't a multiple of 512
33039  ** then it isn't valid.*/
33040  if( pFile->sectorSize % 512 != 0 ){
33041  pFile->deviceCharacteristics = 0;
33042  pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
33043  }
33044  return pFile->sectorSize;
33045 }
33046 #endif /* __QNXNTO__ */
33047 
33048 /*
33049 ** Return the device characteristics for the file.
33050 **
33051 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
33052 ** However, that choice is controversial since technically the underlying
33053 ** file system does not always provide powersafe overwrites. (In other
33054 ** words, after a power-loss event, parts of the file that were never
33055 ** written might end up being altered.) However, non-PSOW behavior is very,
33056 ** very rare. And asserting PSOW makes a large reduction in the amount
33057 ** of required I/O for journaling, since a lot of padding is eliminated.
33058 ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
33059 ** available to turn it off and URI query parameter available to turn it off.
33060 */
33061 static int unixDeviceCharacteristics(sqlite3_file *id){
33062  unixFile *p = (unixFile*)id;
33063  int rc = 0;
33064 #ifdef __QNXNTO__
33065  if( p->sectorSize==0 ) unixSectorSize(id);
33066  rc = p->deviceCharacteristics;
33067 #endif
33068  if( p->ctrlFlags & UNIXFILE_PSOW ){
33070  }
33071  return rc;
33072 }
33073 
33074 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
33075 
33076 /*
33077 ** Return the system page size.
33078 **
33079 ** This function should not be called directly by other code in this file.
33080 ** Instead, it should be called via macro osGetpagesize().
33081 */
33082 static int unixGetpagesize(void){
33083 #if OS_VXWORKS
33084  return 1024;
33085 #elif defined(_BSD_SOURCE)
33086  return getpagesize();
33087 #else
33088  return (int)sysconf(_SC_PAGESIZE);
33089 #endif
33090 }
33091 
33092 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
33093 
33094 #ifndef SQLITE_OMIT_WAL
33095 
33096 /*
33097 ** Object used to represent an shared memory buffer.
33098 **
33099 ** When multiple threads all reference the same wal-index, each thread
33100 ** has its own unixShm object, but they all point to a single instance
33101 ** of this unixShmNode object. In other words, each wal-index is opened
33102 ** only once per process.
33103 **
33104 ** Each unixShmNode object is connected to a single unixInodeInfo object.
33105 ** We could coalesce this object into unixInodeInfo, but that would mean
33106 ** every open file that does not use shared memory (in other words, most
33107 ** open files) would have to carry around this extra information. So
33108 ** the unixInodeInfo object contains a pointer to this unixShmNode object
33109 ** and the unixShmNode object is created only when needed.
33110 **
33111 ** unixMutexHeld() must be true when creating or destroying
33112 ** this object or while reading or writing the following fields:
33113 **
33114 ** nRef
33115 **
33116 ** The following fields are read-only after the object is created:
33117 **
33118 ** fid
33119 ** zFilename
33120 **
33121 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
33122 ** unixMutexHeld() is true when reading or writing any other field
33123 ** in this structure.
33124 */
33125 struct unixShmNode {
33126  unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
33127  sqlite3_mutex *mutex; /* Mutex to access this object */
33128  char *zFilename; /* Name of the mmapped file */
33129  int h; /* Open file descriptor */
33130  int szRegion; /* Size of shared-memory regions */
33131  u16 nRegion; /* Size of array apRegion */
33132  u8 isReadonly; /* True if read-only */
33133  char **apRegion; /* Array of mapped shared-memory regions */
33134  int nRef; /* Number of unixShm objects pointing to this */
33135  unixShm *pFirst; /* All unixShm objects pointing to this */
33136 #ifdef SQLITE_DEBUG
33137  u8 exclMask; /* Mask of exclusive locks held */
33138  u8 sharedMask; /* Mask of shared locks held */
33139  u8 nextShmId; /* Next available unixShm.id value */
33140 #endif
33141 };
33142 
33143 /*
33144 ** Structure used internally by this VFS to record the state of an
33145 ** open shared memory connection.
33146 **
33147 ** The following fields are initialized when this object is created and
33148 ** are read-only thereafter:
33149 **
33150 ** unixShm.pFile
33151 ** unixShm.id
33152 **
33153 ** All other fields are read/write. The unixShm.pFile->mutex must be held
33154 ** while accessing any read/write fields.
33155 */
33156 struct unixShm {
33157  unixShmNode *pShmNode; /* The underlying unixShmNode object */
33158  unixShm *pNext; /* Next unixShm with the same unixShmNode */
33159  u8 hasMutex; /* True if holding the unixShmNode mutex */
33160  u8 id; /* Id of this connection within its unixShmNode */
33161  u16 sharedMask; /* Mask of shared locks held */
33162  u16 exclMask; /* Mask of exclusive locks held */
33163 };
33164 
33165 /*
33166 ** Constants used for locking
33167 */
33168 #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
33169 #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
33170 
33171 /*
33172 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
33173 **
33174 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
33175 ** otherwise.
33176 */
33178  unixFile *pFile, /* Open connection to the WAL file */
33179  int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
33180  int ofst, /* First byte of the locking range */
33181  int n /* Number of bytes to lock */
33182 ){
33183  unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
33184  struct flock f; /* The posix advisory locking structure */
33185  int rc = SQLITE_OK; /* Result code form fcntl() */
33186 
33187  /* Access to the unixShmNode object is serialized by the caller */
33188  pShmNode = pFile->pInode->pShmNode;
33189  assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
33190 
33191  /* Shared locks never span more than one byte */
33192  assert( n==1 || lockType!=F_RDLCK );
33193 
33194  /* Locks are within range */
33195  assert( n>=1 && n<=SQLITE_SHM_NLOCK );
33196 
33197  if( pShmNode->h>=0 ){
33198  /* Initialize the locking parameters */
33199  memset(&f, 0, sizeof(f));
33200  f.l_type = lockType;
33201  f.l_whence = SEEK_SET;
33202  f.l_start = ofst;
33203  f.l_len = n;
33204 
33205  rc = osFcntl(pShmNode->h, F_SETLK, &f);
33206  rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
33207  }
33208 
33209  /* Update the global lock state and do debug tracing */
33210 #ifdef SQLITE_DEBUG
33211  { u16 mask;
33212  OSTRACE(("SHM-LOCK "));
33213  mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
33214  if( rc==SQLITE_OK ){
33215  if( lockType==F_UNLCK ){
33216  OSTRACE(("unlock %d ok", ofst));
33217  pShmNode->exclMask &= ~mask;
33218  pShmNode->sharedMask &= ~mask;
33219  }else if( lockType==F_RDLCK ){
33220  OSTRACE(("read-lock %d ok", ofst));
33221  pShmNode->exclMask &= ~mask;
33222  pShmNode->sharedMask |= mask;
33223  }else{
33224  assert( lockType==F_WRLCK );
33225  OSTRACE(("write-lock %d ok", ofst));
33226  pShmNode->exclMask |= mask;
33227  pShmNode->sharedMask &= ~mask;
33228  }
33229  }else{
33230  if( lockType==F_UNLCK ){
33231  OSTRACE(("unlock %d failed", ofst));
33232  }else if( lockType==F_RDLCK ){
33233  OSTRACE(("read-lock failed"));
33234  }else{
33235  assert( lockType==F_WRLCK );
33236  OSTRACE(("write-lock %d failed", ofst));
33237  }
33238  }
33239  OSTRACE((" - afterwards %03x,%03x\n",
33240  pShmNode->sharedMask, pShmNode->exclMask));
33241  }
33242 #endif
33243 
33244  return rc;
33245 }
33246 
33247 /*
33248 ** Return the minimum number of 32KB shm regions that should be mapped at
33249 ** a time, assuming that each mapping must be an integer multiple of the
33250 ** current system page-size.
33251 **
33252 ** Usually, this is 1. The exception seems to be systems that are configured
33253 ** to use 64KB pages - in this case each mapping must cover at least two
33254 ** shm regions.
33255 */
33256 static int unixShmRegionPerMap(void){
33257  int shmsz = 32*1024; /* SHM region size */
33258  int pgsz = osGetpagesize(); /* System page size */
33259  assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
33260  if( pgsz<shmsz ) return 1;
33261  return pgsz/shmsz;
33262 }
33263 
33264 /*
33265 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
33266 **
33267 ** This is not a VFS shared-memory method; it is a utility function called
33268 ** by VFS shared-memory methods.
33269 */
33270 static void unixShmPurge(unixFile *pFd){
33271  unixShmNode *p = pFd->pInode->pShmNode;
33272  assert( unixMutexHeld() );
33273  if( p && ALWAYS(p->nRef==0) ){
33274  int nShmPerMap = unixShmRegionPerMap();
33275  int i;
33276  assert( p->pInode==pFd->pInode );
33278  for(i=0; i<p->nRegion; i+=nShmPerMap){
33279  if( p->h>=0 ){
33280  osMunmap(p->apRegion[i], p->szRegion);
33281  }else{
33282  sqlite3_free(p->apRegion[i]);
33283  }
33284  }
33285  sqlite3_free(p->apRegion);
33286  if( p->h>=0 ){
33287  robust_close(pFd, p->h, __LINE__);
33288  p->h = -1;
33289  }
33290  p->pInode->pShmNode = 0;
33291  sqlite3_free(p);
33292  }
33293 }
33294 
33295 /*
33296 ** Open a shared-memory area associated with open database file pDbFd.
33297 ** This particular implementation uses mmapped files.
33298 **
33299 ** The file used to implement shared-memory is in the same directory
33300 ** as the open database file and has the same name as the open database
33301 ** file with the "-shm" suffix added. For example, if the database file
33302 ** is "/home/user1/config.db" then the file that is created and mmapped
33303 ** for shared memory will be called "/home/user1/config.db-shm".
33304 **
33305 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
33306 ** some other tmpfs mount. But if a file in a different directory
33307 ** from the database file is used, then differing access permissions
33308 ** or a chroot() might cause two different processes on the same
33309 ** database to end up using different files for shared memory -
33310 ** meaning that their memory would not really be shared - resulting
33311 ** in database corruption. Nevertheless, this tmpfs file usage
33312 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
33313 ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
33314 ** option results in an incompatible build of SQLite; builds of SQLite
33315 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
33316 ** same database file at the same time, database corruption will likely
33317 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
33318 ** "unsupported" and may go away in a future SQLite release.
33319 **
33320 ** When opening a new shared-memory file, if no other instances of that
33321 ** file are currently open, in this process or in other processes, then
33322 ** the file must be truncated to zero length or have its header cleared.
33323 **
33324 ** If the original database file (pDbFd) is using the "unix-excl" VFS
33325 ** that means that an exclusive lock is held on the database file and
33326 ** that no other processes are able to read or write the database. In
33327 ** that case, we do not really need shared memory. No shared memory
33328 ** file is created. The shared memory will be simulated with heap memory.
33329 */
33330 static int unixOpenSharedMemory(unixFile *pDbFd){
33331  struct unixShm *p = 0; /* The connection to be opened */
33332  struct unixShmNode *pShmNode; /* The underlying mmapped file */
33333  int rc; /* Result code */
33334  unixInodeInfo *pInode; /* The inode of fd */
33335  char *zShmFilename; /* Name of the file used for SHM */
33336  int nShmFilename; /* Size of the SHM filename in bytes */
33337 
33338  /* Allocate space for the new unixShm object. */
33339  p = sqlite3_malloc64( sizeof(*p) );
33340  if( p==0 ) return SQLITE_NOMEM_BKPT;
33341  memset(p, 0, sizeof(*p));
33342  assert( pDbFd->pShm==0 );
33343 
33344  /* Check to see if a unixShmNode object already exists. Reuse an existing
33345  ** one if present. Create a new one if necessary.
33346  */
33347  unixEnterMutex();
33348  pInode = pDbFd->pInode;
33349  pShmNode = pInode->pShmNode;
33350  if( pShmNode==0 ){
33351  struct stat sStat; /* fstat() info for database file */
33352 #ifndef SQLITE_SHM_DIRECTORY
33353  const char *zBasePath = pDbFd->zPath;
33354 #endif
33355 
33356  /* Call fstat() to figure out the permissions on the database file. If
33357  ** a new *-shm file is created, an attempt will be made to create it
33358  ** with the same permissions.
33359  */
33360  if( osFstat(pDbFd->h, &sStat) ){
33361  rc = SQLITE_IOERR_FSTAT;
33362  goto shm_open_err;
33363  }
33364 
33365 #ifdef SQLITE_SHM_DIRECTORY
33366  nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
33367 #else
33368  nShmFilename = 6 + (int)strlen(zBasePath);
33369 #endif
33370  pShmNode = sqlite3_malloc64( sizeof(*pShmNode) + nShmFilename );
33371  if( pShmNode==0 ){
33372  rc = SQLITE_NOMEM_BKPT;
33373  goto shm_open_err;
33374  }
33375  memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
33376  zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
33377 #ifdef SQLITE_SHM_DIRECTORY
33378  sqlite3_snprintf(nShmFilename, zShmFilename,
33379  SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
33380  (u32)sStat.st_ino, (u32)sStat.st_dev);
33381 #else
33382  sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
33383  sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
33384 #endif
33385  pShmNode->h = -1;
33386  pDbFd->pInode->pShmNode = pShmNode;
33387  pShmNode->pInode = pDbFd->pInode;
33388  if( sqlite3GlobalConfig.bCoreMutex ){
33390  if( pShmNode->mutex==0 ){
33391  rc = SQLITE_NOMEM_BKPT;
33392  goto shm_open_err;
33393  }
33394  }
33395 
33396  if( pInode->bProcessLock==0 ){
33397  int openFlags = O_RDWR | O_CREAT;
33398  if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
33399  openFlags = O_RDONLY;
33400  pShmNode->isReadonly = 1;
33401  }
33402  pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
33403  if( pShmNode->h<0 ){
33404  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
33405  goto shm_open_err;
33406  }
33407 
33408  /* If this process is running as root, make sure that the SHM file
33409  ** is owned by the same user that owns the original database. Otherwise,
33410  ** the original owner will not be able to connect.
33411  */
33412  robustFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
33413 
33414  /* Check to see if another process is holding the dead-man switch.
33415  ** If not, truncate the file to zero length.
33416  */
33417  rc = SQLITE_OK;
33418  if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
33419  if( robust_ftruncate(pShmNode->h, 0) ){
33420  rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
33421  }
33422  }
33423  if( rc==SQLITE_OK ){
33424  rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
33425  }
33426  if( rc ) goto shm_open_err;
33427  }
33428  }
33429 
33430  /* Make the new connection a child of the unixShmNode */
33431  p->pShmNode = pShmNode;
33432 #ifdef SQLITE_DEBUG
33433  p->id = pShmNode->nextShmId++;
33434 #endif
33435  pShmNode->nRef++;
33436  pDbFd->pShm = p;
33437  unixLeaveMutex();
33438 
33439  /* The reference count on pShmNode has already been incremented under
33440  ** the cover of the unixEnterMutex() mutex and the pointer from the
33441  ** new (struct unixShm) object to the pShmNode has been set. All that is
33442  ** left to do is to link the new object into the linked list starting
33443  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
33444  ** mutex.
33445  */
33446  sqlite3_mutex_enter(pShmNode->mutex);
33447  p->pNext = pShmNode->pFirst;
33448  pShmNode->pFirst = p;
33449  sqlite3_mutex_leave(pShmNode->mutex);
33450  return SQLITE_OK;
33451 
33452  /* Jump here on any error */
33453 shm_open_err:
33454  unixShmPurge(pDbFd); /* This call frees pShmNode if required */
33455  sqlite3_free(p);
33456  unixLeaveMutex();
33457  return rc;
33458 }
33459 
33460 /*
33461 ** This function is called to obtain a pointer to region iRegion of the
33462 ** shared-memory associated with the database file fd. Shared-memory regions
33463 ** are numbered starting from zero. Each shared-memory region is szRegion
33464 ** bytes in size.
33465 **
33466 ** If an error occurs, an error code is returned and *pp is set to NULL.
33467 **
33468 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
33469 ** region has not been allocated (by any client, including one running in a
33470 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
33471 ** bExtend is non-zero and the requested shared-memory region has not yet
33472 ** been allocated, it is allocated by this function.
33473 **
33474 ** If the shared-memory region has already been allocated or is allocated by
33475 ** this call as described above, then it is mapped into this processes
33476 ** address space (if it is not already), *pp is set to point to the mapped
33477 ** memory and SQLITE_OK returned.
33478 */
33479 static int unixShmMap(
33480  sqlite3_file *fd, /* Handle open on database file */
33481  int iRegion, /* Region to retrieve */
33482  int szRegion, /* Size of regions */
33483  int bExtend, /* True to extend file if necessary */
33484  void volatile **pp /* OUT: Mapped memory */
33485 ){
33486  unixFile *pDbFd = (unixFile*)fd;
33487  unixShm *p;
33488  unixShmNode *pShmNode;
33489  int rc = SQLITE_OK;
33490  int nShmPerMap = unixShmRegionPerMap();
33491  int nReqRegion;
33492 
33493  /* If the shared-memory file has not yet been opened, open it now. */
33494  if( pDbFd->pShm==0 ){
33495  rc = unixOpenSharedMemory(pDbFd);
33496  if( rc!=SQLITE_OK ) return rc;
33497  }
33498 
33499  p = pDbFd->pShm;
33500  pShmNode = p->pShmNode;
33501  sqlite3_mutex_enter(pShmNode->mutex);
33502  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
33503  assert( pShmNode->pInode==pDbFd->pInode );
33504  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33505  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33506 
33507  /* Minimum number of regions required to be mapped. */
33508  nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
33509 
33510  if( pShmNode->nRegion<nReqRegion ){
33511  char **apNew; /* New apRegion[] array */
33512  int nByte = nReqRegion*szRegion; /* Minimum required file size */
33513  struct stat sStat; /* Used by fstat() */
33514 
33515  pShmNode->szRegion = szRegion;
33516 
33517  if( pShmNode->h>=0 ){
33518  /* The requested region is not mapped into this processes address space.
33519  ** Check to see if it has been allocated (i.e. if the wal-index file is
33520  ** large enough to contain the requested region).
33521  */
33522  if( osFstat(pShmNode->h, &sStat) ){
33523  rc = SQLITE_IOERR_SHMSIZE;
33524  goto shmpage_out;
33525  }
33526 
33527  if( sStat.st_size<nByte ){
33528  /* The requested memory region does not exist. If bExtend is set to
33529  ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
33530  */
33531  if( !bExtend ){
33532  goto shmpage_out;
33533  }
33534 
33535  /* Alternatively, if bExtend is true, extend the file. Do this by
33536  ** writing a single byte to the end of each (OS) page being
33537  ** allocated or extended. Technically, we need only write to the
33538  ** last page in order to extend the file. But writing to all new
33539  ** pages forces the OS to allocate them immediately, which reduces
33540  ** the chances of SIGBUS while accessing the mapped region later on.
33541  */
33542  else{
33543  static const int pgsz = 4096;
33544  int iPg;
33545 
33546  /* Write to the last byte of each newly allocated or extended page */
33547  assert( (nByte % pgsz)==0 );
33548  for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
33549  int x = 0;
33550  if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, &x)!=1 ){
33551  const char *zFile = pShmNode->zFilename;
33552  rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
33553  goto shmpage_out;
33554  }
33555  }
33556  }
33557  }
33558  }
33559 
33560  /* Map the requested memory region into this processes address space. */
33561  apNew = (char **)sqlite3_realloc(
33562  pShmNode->apRegion, nReqRegion*sizeof(char *)
33563  );
33564  if( !apNew ){
33566  goto shmpage_out;
33567  }
33568  pShmNode->apRegion = apNew;
33569  while( pShmNode->nRegion<nReqRegion ){
33570  int nMap = szRegion*nShmPerMap;
33571  int i;
33572  void *pMem;
33573  if( pShmNode->h>=0 ){
33574  pMem = osMmap(0, nMap,
33575  pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
33576  MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
33577  );
33578  if( pMem==MAP_FAILED ){
33579  rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
33580  goto shmpage_out;
33581  }
33582  }else{
33583  pMem = sqlite3_malloc64(szRegion);
33584  if( pMem==0 ){
33585  rc = SQLITE_NOMEM_BKPT;
33586  goto shmpage_out;
33587  }
33588  memset(pMem, 0, szRegion);
33589  }
33590 
33591  for(i=0; i<nShmPerMap; i++){
33592  pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
33593  }
33594  pShmNode->nRegion += nShmPerMap;
33595  }
33596  }
33597 
33598 shmpage_out:
33599  if( pShmNode->nRegion>iRegion ){
33600  *pp = pShmNode->apRegion[iRegion];
33601  }else{
33602  *pp = 0;
33603  }
33604  if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
33605  sqlite3_mutex_leave(pShmNode->mutex);
33606  return rc;
33607 }
33608 
33609 /*
33610 ** Change the lock state for a shared-memory segment.
33611 **
33612 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
33613 ** different here than in posix. In xShmLock(), one can go from unlocked
33614 ** to shared and back or from unlocked to exclusive and back. But one may
33615 ** not go from shared to exclusive or from exclusive to shared.
33616 */
33617 static int unixShmLock(
33618  sqlite3_file *fd, /* Database file holding the shared memory */
33619  int ofst, /* First lock to acquire or release */
33620  int n, /* Number of locks to acquire or release */
33621  int flags /* What to do with the lock */
33622 ){
33623  unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
33624  unixShm *p = pDbFd->pShm; /* The shared memory being locked */
33625  unixShm *pX; /* For looping over all siblings */
33626  unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
33627  int rc = SQLITE_OK; /* Result code */
33628  u16 mask; /* Mask of locks to take or release */
33629 
33630  assert( pShmNode==pDbFd->pInode->pShmNode );
33631  assert( pShmNode->pInode==pDbFd->pInode );
33632  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
33633  assert( n>=1 );
33636  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
33637  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
33638  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
33639  assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
33640  assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
33641 
33642  mask = (1<<(ofst+n)) - (1<<ofst);
33643  assert( n>1 || mask==(1<<ofst) );
33644  sqlite3_mutex_enter(pShmNode->mutex);
33645  if( flags & SQLITE_SHM_UNLOCK ){
33646  u16 allMask = 0; /* Mask of locks held by siblings */
33647 
33648  /* See if any siblings hold this same lock */
33649  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33650  if( pX==p ) continue;
33651  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
33652  allMask |= pX->sharedMask;
33653  }
33654 
33655  /* Unlock the system-level locks */
33656  if( (mask & allMask)==0 ){
33657  rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
33658  }else{
33659  rc = SQLITE_OK;
33660  }
33661 
33662  /* Undo the local locks */
33663  if( rc==SQLITE_OK ){
33664  p->exclMask &= ~mask;
33665  p->sharedMask &= ~mask;
33666  }
33667  }else if( flags & SQLITE_SHM_SHARED ){
33668  u16 allShared = 0; /* Union of locks held by connections other than "p" */
33669 
33670  /* Find out which shared locks are already held by sibling connections.
33671  ** If any sibling already holds an exclusive lock, go ahead and return
33672  ** SQLITE_BUSY.
33673  */
33674  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33675  if( (pX->exclMask & mask)!=0 ){
33676  rc = SQLITE_BUSY;
33677  break;
33678  }
33679  allShared |= pX->sharedMask;
33680  }
33681 
33682  /* Get shared locks at the system level, if necessary */
33683  if( rc==SQLITE_OK ){
33684  if( (allShared & mask)==0 ){
33685  rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
33686  }else{
33687  rc = SQLITE_OK;
33688  }
33689  }
33690 
33691  /* Get the local shared locks */
33692  if( rc==SQLITE_OK ){
33693  p->sharedMask |= mask;
33694  }
33695  }else{
33696  /* Make sure no sibling connections hold locks that will block this
33697  ** lock. If any do, return SQLITE_BUSY right away.
33698  */
33699  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
33700  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
33701  rc = SQLITE_BUSY;
33702  break;
33703  }
33704  }
33705 
33706  /* Get the exclusive locks at the system level. Then if successful
33707  ** also mark the local connection as being locked.
33708  */
33709  if( rc==SQLITE_OK ){
33710  rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
33711  if( rc==SQLITE_OK ){
33712  assert( (p->sharedMask & mask)==0 );
33713  p->exclMask |= mask;
33714  }
33715  }
33716  }
33717  sqlite3_mutex_leave(pShmNode->mutex);
33718  OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
33719  p->id, osGetpid(0), p->sharedMask, p->exclMask));
33720  return rc;
33721 }
33722 
33723 /*
33724 ** Implement a memory barrier or memory fence on shared memory.
33725 **
33726 ** All loads and stores begun before the barrier must complete before
33727 ** any load or store begun after the barrier.
33728 */
33729 static void unixShmBarrier(
33730  sqlite3_file *fd /* Database file holding the shared memory */
33731 ){
33732  UNUSED_PARAMETER(fd);
33733  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
33734  unixEnterMutex(); /* Also mutex, for redundancy */
33735  unixLeaveMutex();
33736 }
33737 
33738 /*
33739 ** Close a connection to shared-memory. Delete the underlying
33740 ** storage if deleteFlag is true.
33741 **
33742 ** If there is no shared memory associated with the connection then this
33743 ** routine is a harmless no-op.
33744 */
33745 static int unixShmUnmap(
33746  sqlite3_file *fd, /* The underlying database file */
33747  int deleteFlag /* Delete shared-memory if true */
33748 ){
33749  unixShm *p; /* The connection to be closed */
33750  unixShmNode *pShmNode; /* The underlying shared-memory file */
33751  unixShm **pp; /* For looping over sibling connections */
33752  unixFile *pDbFd; /* The underlying database file */
33753 
33754  pDbFd = (unixFile*)fd;
33755  p = pDbFd->pShm;
33756  if( p==0 ) return SQLITE_OK;
33757  pShmNode = p->pShmNode;
33758 
33759  assert( pShmNode==pDbFd->pInode->pShmNode );
33760  assert( pShmNode->pInode==pDbFd->pInode );
33761 
33762  /* Remove connection p from the set of connections associated
33763  ** with pShmNode */
33764  sqlite3_mutex_enter(pShmNode->mutex);
33765  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
33766  *pp = p->pNext;
33767 
33768  /* Free the connection p */
33769  sqlite3_free(p);
33770  pDbFd->pShm = 0;
33771  sqlite3_mutex_leave(pShmNode->mutex);
33772 
33773  /* If pShmNode->nRef has reached 0, then close the underlying
33774  ** shared-memory file, too */
33775  unixEnterMutex();
33776  assert( pShmNode->nRef>0 );
33777  pShmNode->nRef--;
33778  if( pShmNode->nRef==0 ){
33779  if( deleteFlag && pShmNode->h>=0 ){
33780  osUnlink(pShmNode->zFilename);
33781  }
33782  unixShmPurge(pDbFd);
33783  }
33784  unixLeaveMutex();
33785 
33786  return SQLITE_OK;
33787 }
33788 
33789 
33790 #else
33791 # define unixShmMap 0
33792 # define unixShmLock 0
33793 # define unixShmBarrier 0
33794 # define unixShmUnmap 0
33795 #endif /* #ifndef SQLITE_OMIT_WAL */
33796 
33797 #if SQLITE_MAX_MMAP_SIZE>0
33798 /*
33799 ** If it is currently memory mapped, unmap file pFd.
33800 */
33801 static void unixUnmapfile(unixFile *pFd){
33802  assert( pFd->nFetchOut==0 );
33803  if( pFd->pMapRegion ){
33804  osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
33805  pFd->pMapRegion = 0;
33806  pFd->mmapSize = 0;
33807  pFd->mmapSizeActual = 0;
33808  }
33809 }
33810 
33811 /*
33812 ** Attempt to set the size of the memory mapping maintained by file
33813 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
33814 **
33815 ** If successful, this function sets the following variables:
33816 **
33817 ** unixFile.pMapRegion
33818 ** unixFile.mmapSize
33819 ** unixFile.mmapSizeActual
33820 **
33821 ** If unsuccessful, an error message is logged via sqlite3_log() and
33822 ** the three variables above are zeroed. In this case SQLite should
33823 ** continue accessing the database using the xRead() and xWrite()
33824 ** methods.
33825 */
33826 static void unixRemapfile(
33827  unixFile *pFd, /* File descriptor object */
33828  i64 nNew /* Required mapping size */
33829 ){
33830  const char *zErr = "mmap";
33831  int h = pFd->h; /* File descriptor open on db file */
33832  u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
33833  i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
33834  u8 *pNew = 0; /* Location of new mapping */
33835  int flags = PROT_READ; /* Flags to pass to mmap() */
33836 
33837  assert( pFd->nFetchOut==0 );
33838  assert( nNew>pFd->mmapSize );
33839  assert( nNew<=pFd->mmapSizeMax );
33840  assert( nNew>0 );
33841  assert( pFd->mmapSizeActual>=pFd->mmapSize );
33842  assert( MAP_FAILED!=0 );
33843 
33844 #ifdef SQLITE_MMAP_READWRITE
33845  if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
33846 #endif
33847 
33848  if( pOrig ){
33849 #if HAVE_MREMAP
33850  i64 nReuse = pFd->mmapSize;
33851 #else
33852  const int szSyspage = osGetpagesize();
33853  i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
33854 #endif
33855  u8 *pReq = &pOrig[nReuse];
33856 
33857  /* Unmap any pages of the existing mapping that cannot be reused. */
33858  if( nReuse!=nOrig ){
33859  osMunmap(pReq, nOrig-nReuse);
33860  }
33861 
33862 #if HAVE_MREMAP
33863  pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
33864  zErr = "mremap";
33865 #else
33866  pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
33867  if( pNew!=MAP_FAILED ){
33868  if( pNew!=pReq ){
33869  osMunmap(pNew, nNew - nReuse);
33870  pNew = 0;
33871  }else{
33872  pNew = pOrig;
33873  }
33874  }
33875 #endif
33876 
33877  /* The attempt to extend the existing mapping failed. Free it. */
33878  if( pNew==MAP_FAILED || pNew==0 ){
33879  osMunmap(pOrig, nReuse);
33880  }
33881  }
33882 
33883  /* If pNew is still NULL, try to create an entirely new mapping. */
33884  if( pNew==0 ){
33885  pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
33886  }
33887 
33888  if( pNew==MAP_FAILED ){
33889  pNew = 0;
33890  nNew = 0;
33891  unixLogError(SQLITE_OK, zErr, pFd->zPath);
33892 
33893  /* If the mmap() above failed, assume that all subsequent mmap() calls
33894  ** will probably fail too. Fall back to using xRead/xWrite exclusively
33895  ** in this case. */
33896  pFd->mmapSizeMax = 0;
33897  }
33898  pFd->pMapRegion = (void *)pNew;
33899  pFd->mmapSize = pFd->mmapSizeActual = nNew;
33900 }
33901 
33902 /*
33903 ** Memory map or remap the file opened by file-descriptor pFd (if the file
33904 ** is already mapped, the existing mapping is replaced by the new). Or, if
33905 ** there already exists a mapping for this file, and there are still
33906 ** outstanding xFetch() references to it, this function is a no-op.
33907 **
33908 ** If parameter nByte is non-negative, then it is the requested size of
33909 ** the mapping to create. Otherwise, if nByte is less than zero, then the
33910 ** requested size is the size of the file on disk. The actual size of the
33911 ** created mapping is either the requested size or the value configured
33912 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
33913 **
33914 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
33915 ** recreated as a result of outstanding references) or an SQLite error
33916 ** code otherwise.
33917 */
33918 static int unixMapfile(unixFile *pFd, i64 nMap){
33919  assert( nMap>=0 || pFd->nFetchOut==0 );
33920  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
33921  if( pFd->nFetchOut>0 ) return SQLITE_OK;
33922 
33923  if( nMap<0 ){
33924  struct stat statbuf; /* Low-level file information */
33925  if( osFstat(pFd->h, &statbuf) ){
33926  return SQLITE_IOERR_FSTAT;
33927  }
33928  nMap = statbuf.st_size;
33929  }
33930  if( nMap>pFd->mmapSizeMax ){
33931  nMap = pFd->mmapSizeMax;
33932  }
33933 
33934  assert( nMap>0 || (pFd->mmapSize==0 && pFd->pMapRegion==0) );
33935  if( nMap!=pFd->mmapSize ){
33936  unixRemapfile(pFd, nMap);
33937  }
33938 
33939  return SQLITE_OK;
33940 }
33941 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
33942 
33943 /*
33944 ** If possible, return a pointer to a mapping of file fd starting at offset
33945 ** iOff. The mapping must be valid for at least nAmt bytes.
33946 **
33947 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
33948 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
33949 ** Finally, if an error does occur, return an SQLite error code. The final
33950 ** value of *pp is undefined in this case.
33951 **
33952 ** If this function does return a pointer, the caller must eventually
33953 ** release the reference by calling unixUnfetch().
33954 */
33955 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
33956 #if SQLITE_MAX_MMAP_SIZE>0
33957  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
33958 #endif
33959  *pp = 0;
33960 
33961 #if SQLITE_MAX_MMAP_SIZE>0
33962  if( pFd->mmapSizeMax>0 ){
33963  if( pFd->pMapRegion==0 ){
33964  int rc = unixMapfile(pFd, -1);
33965  if( rc!=SQLITE_OK ) return rc;
33966  }
33967  if( pFd->mmapSize >= iOff+nAmt ){
33968  *pp = &((u8 *)pFd->pMapRegion)[iOff];
33969  pFd->nFetchOut++;
33970  }
33971  }
33972 #endif
33973  return SQLITE_OK;
33974 }
33975 
33976 /*
33977 ** If the third argument is non-NULL, then this function releases a
33978 ** reference obtained by an earlier call to unixFetch(). The second
33979 ** argument passed to this function must be the same as the corresponding
33980 ** argument that was passed to the unixFetch() invocation.
33981 **
33982 ** Or, if the third argument is NULL, then this function is being called
33983 ** to inform the VFS layer that, according to POSIX, any existing mapping
33984 ** may now be invalid and should be unmapped.
33985 */
33986 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
33987 #if SQLITE_MAX_MMAP_SIZE>0
33988  unixFile *pFd = (unixFile *)fd; /* The underlying database file */
33989  UNUSED_PARAMETER(iOff);
33990 
33991  /* If p==0 (unmap the entire file) then there must be no outstanding
33992  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
33993  ** then there must be at least one outstanding. */
33994  assert( (p==0)==(pFd->nFetchOut==0) );
33995 
33996  /* If p!=0, it must match the iOff value. */
33997  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
33998 
33999  if( p ){
34000  pFd->nFetchOut--;
34001  }else{
34002  unixUnmapfile(pFd);
34003  }
34004 
34005  assert( pFd->nFetchOut>=0 );
34006 #else
34007  UNUSED_PARAMETER(fd);
34008  UNUSED_PARAMETER(p);
34009  UNUSED_PARAMETER(iOff);
34010 #endif
34011  return SQLITE_OK;
34012 }
34013 
34014 /*
34015 ** Here ends the implementation of all sqlite3_file methods.
34016 **
34017 ********************** End sqlite3_file Methods *******************************
34018 ******************************************************************************/
34019 
34020 /*
34021 ** This division contains definitions of sqlite3_io_methods objects that
34022 ** implement various file locking strategies. It also contains definitions
34023 ** of "finder" functions. A finder-function is used to locate the appropriate
34024 ** sqlite3_io_methods object for a particular database file. The pAppData
34025 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
34026 ** the correct finder-function for that VFS.
34027 **
34028 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
34029 ** object. The only interesting finder-function is autolockIoFinder, which
34030 ** looks at the filesystem type and tries to guess the best locking
34031 ** strategy from that.
34032 **
34033 ** For finder-function F, two objects are created:
34034 **
34035 ** (1) The real finder-function named "FImpt()".
34036 **
34037 ** (2) A constant pointer to this function named just "F".
34038 **
34039 **
34040 ** A pointer to the F pointer is used as the pAppData value for VFS
34041 ** objects. We have to do this instead of letting pAppData point
34042 ** directly at the finder-function since C90 rules prevent a void*
34043 ** from be cast into a function pointer.
34044 **
34045 **
34046 ** Each instance of this macro generates two objects:
34047 **
34048 ** * A constant sqlite3_io_methods object call METHOD that has locking
34049 ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
34050 **
34051 ** * An I/O method finder function called FINDER that returns a pointer
34052 ** to the METHOD object in the previous bullet.
34053 */
34054 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP) \
34055 static const sqlite3_io_methods METHOD = { \
34056  VERSION, /* iVersion */ \
34057  CLOSE, /* xClose */ \
34058  unixRead, /* xRead */ \
34059  unixWrite, /* xWrite */ \
34060  unixTruncate, /* xTruncate */ \
34061  unixSync, /* xSync */ \
34062  unixFileSize, /* xFileSize */ \
34063  LOCK, /* xLock */ \
34064  UNLOCK, /* xUnlock */ \
34065  CKLOCK, /* xCheckReservedLock */ \
34066  unixFileControl, /* xFileControl */ \
34067  unixSectorSize, /* xSectorSize */ \
34068  unixDeviceCharacteristics, /* xDeviceCapabilities */ \
34069  SHMMAP, /* xShmMap */ \
34070  unixShmLock, /* xShmLock */ \
34071  unixShmBarrier, /* xShmBarrier */ \
34072  unixShmUnmap, /* xShmUnmap */ \
34073  unixFetch, /* xFetch */ \
34074  unixUnfetch, /* xUnfetch */ \
34075 }; \
34076 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
34077  UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
34078  return &METHOD; \
34079 } \
34080 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
34081  = FINDER##Impl;
34082 
34083 /*
34084 ** Here are all of the sqlite3_io_methods objects for each of the
34085 ** locking strategies. Functions that return pointers to these methods
34086 ** are also created.
34087 */
34089  posixIoFinder, /* Finder function name */
34090  posixIoMethods, /* sqlite3_io_methods object name */
34091  3, /* shared memory and mmap are enabled */
34092  unixClose, /* xClose method */
34093  unixLock, /* xLock method */
34094  unixUnlock, /* xUnlock method */
34095  unixCheckReservedLock, /* xCheckReservedLock method */
34096  unixShmMap /* xShmMap method */
34097 )
34098 IOMETHODS(
34099  nolockIoFinder, /* Finder function name */
34100  nolockIoMethods, /* sqlite3_io_methods object name */
34101  3, /* shared memory is disabled */
34102  nolockClose, /* xClose method */
34103  nolockLock, /* xLock method */
34104  nolockUnlock, /* xUnlock method */
34105  nolockCheckReservedLock, /* xCheckReservedLock method */
34106  0 /* xShmMap method */
34107 )
34108 IOMETHODS(
34109  dotlockIoFinder, /* Finder function name */
34110  dotlockIoMethods, /* sqlite3_io_methods object name */
34111  1, /* shared memory is disabled */
34112  dotlockClose, /* xClose method */
34113  dotlockLock, /* xLock method */
34114  dotlockUnlock, /* xUnlock method */
34115  dotlockCheckReservedLock, /* xCheckReservedLock method */
34116  0 /* xShmMap method */
34117 )
34118 
34119 #if SQLITE_ENABLE_LOCKING_STYLE
34120 IOMETHODS(
34121  flockIoFinder, /* Finder function name */
34122  flockIoMethods, /* sqlite3_io_methods object name */
34123  1, /* shared memory is disabled */
34124  flockClose, /* xClose method */
34125  flockLock, /* xLock method */
34126  flockUnlock, /* xUnlock method */
34127  flockCheckReservedLock, /* xCheckReservedLock method */
34128  0 /* xShmMap method */
34129 )
34130 #endif
34131 
34132 #if OS_VXWORKS
34133 IOMETHODS(
34134  semIoFinder, /* Finder function name */
34135  semIoMethods, /* sqlite3_io_methods object name */
34136  1, /* shared memory is disabled */
34137  semXClose, /* xClose method */
34138  semXLock, /* xLock method */
34139  semXUnlock, /* xUnlock method */
34140  semXCheckReservedLock, /* xCheckReservedLock method */
34141  0 /* xShmMap method */
34142 )
34143 #endif
34144 
34145 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34146 IOMETHODS(
34147  afpIoFinder, /* Finder function name */
34148  afpIoMethods, /* sqlite3_io_methods object name */
34149  1, /* shared memory is disabled */
34150  afpClose, /* xClose method */
34151  afpLock, /* xLock method */
34152  afpUnlock, /* xUnlock method */
34153  afpCheckReservedLock, /* xCheckReservedLock method */
34154  0 /* xShmMap method */
34155 )
34156 #endif
34157 
34158 /*
34159 ** The proxy locking method is a "super-method" in the sense that it
34160 ** opens secondary file descriptors for the conch and lock files and
34161 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
34162 ** secondary files. For this reason, the division that implements
34163 ** proxy locking is located much further down in the file. But we need
34164 ** to go ahead and define the sqlite3_io_methods and finder function
34165 ** for proxy locking here. So we forward declare the I/O methods.
34166 */
34167 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34168 static int proxyClose(sqlite3_file*);
34169 static int proxyLock(sqlite3_file*, int);
34170 static int proxyUnlock(sqlite3_file*, int);
34171 static int proxyCheckReservedLock(sqlite3_file*, int*);
34172 IOMETHODS(
34173  proxyIoFinder, /* Finder function name */
34174  proxyIoMethods, /* sqlite3_io_methods object name */
34175  1, /* shared memory is disabled */
34176  proxyClose, /* xClose method */
34177  proxyLock, /* xLock method */
34178  proxyUnlock, /* xUnlock method */
34179  proxyCheckReservedLock, /* xCheckReservedLock method */
34180  0 /* xShmMap method */
34181 )
34182 #endif
34183 
34184 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
34185 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34186 IOMETHODS(
34187  nfsIoFinder, /* Finder function name */
34188  nfsIoMethods, /* sqlite3_io_methods object name */
34189  1, /* shared memory is disabled */
34190  unixClose, /* xClose method */
34191  unixLock, /* xLock method */
34192  nfsUnlock, /* xUnlock method */
34193  unixCheckReservedLock, /* xCheckReservedLock method */
34194  0 /* xShmMap method */
34195 )
34196 #endif
34197 
34198 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34199 /*
34200 ** This "finder" function attempts to determine the best locking strategy
34201 ** for the database file "filePath". It then returns the sqlite3_io_methods
34202 ** object that implements that strategy.
34203 **
34204 ** This is for MacOSX only.
34205 */
34206 static const sqlite3_io_methods *autolockIoFinderImpl(
34207  const char *filePath, /* name of the database file */
34208  unixFile *pNew /* open file object for the database file */
34209 ){
34210  static const struct Mapping {
34211  const char *zFilesystem; /* Filesystem type name */
34212  const sqlite3_io_methods *pMethods; /* Appropriate locking method */
34213  } aMap[] = {
34214  { "hfs", &posixIoMethods },
34215  { "ufs", &posixIoMethods },
34216  { "afpfs", &afpIoMethods },
34217  { "smbfs", &afpIoMethods },
34218  { "webdav", &nolockIoMethods },
34219  { 0, 0 }
34220  };
34221  int i;
34222  struct statfs fsInfo;
34223  struct flock lockInfo;
34224 
34225  if( !filePath ){
34226  /* If filePath==NULL that means we are dealing with a transient file
34227  ** that does not need to be locked. */
34228  return &nolockIoMethods;
34229  }
34230  if( statfs(filePath, &fsInfo) != -1 ){
34231  if( fsInfo.f_flags & MNT_RDONLY ){
34232  return &nolockIoMethods;
34233  }
34234  for(i=0; aMap[i].zFilesystem; i++){
34235  if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
34236  return aMap[i].pMethods;
34237  }
34238  }
34239  }
34240 
34241  /* Default case. Handles, amongst others, "nfs".
34242  ** Test byte-range lock using fcntl(). If the call succeeds,
34243  ** assume that the file-system supports POSIX style locks.
34244  */
34245  lockInfo.l_len = 1;
34246  lockInfo.l_start = 0;
34247  lockInfo.l_whence = SEEK_SET;
34248  lockInfo.l_type = F_RDLCK;
34249  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34250  if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
34251  return &nfsIoMethods;
34252  } else {
34253  return &posixIoMethods;
34254  }
34255  }else{
34256  return &dotlockIoMethods;
34257  }
34258 }
34259 static const sqlite3_io_methods
34260  *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
34261 
34262 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
34263 
34264 #if OS_VXWORKS
34265 /*
34266 ** This "finder" function for VxWorks checks to see if posix advisory
34267 ** locking works. If it does, then that is what is used. If it does not
34268 ** work, then fallback to named semaphore locking.
34269 */
34270 static const sqlite3_io_methods *vxworksIoFinderImpl(
34271  const char *filePath, /* name of the database file */
34272  unixFile *pNew /* the open file object */
34273 ){
34274  struct flock lockInfo;
34275 
34276  if( !filePath ){
34277  /* If filePath==NULL that means we are dealing with a transient file
34278  ** that does not need to be locked. */
34279  return &nolockIoMethods;
34280  }
34281 
34282  /* Test if fcntl() is supported and use POSIX style locks.
34283  ** Otherwise fall back to the named semaphore method.
34284  */
34285  lockInfo.l_len = 1;
34286  lockInfo.l_start = 0;
34287  lockInfo.l_whence = SEEK_SET;
34288  lockInfo.l_type = F_RDLCK;
34289  if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
34290  return &posixIoMethods;
34291  }else{
34292  return &semIoMethods;
34293  }
34294 }
34295 static const sqlite3_io_methods
34296  *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
34297 
34298 #endif /* OS_VXWORKS */
34299 
34300 /*
34301 ** An abstract type for a pointer to an IO method finder function:
34302 */
34303 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
34304 
34305 
34306 /****************************************************************************
34307 **************************** sqlite3_vfs methods ****************************
34308 **
34309 ** This division contains the implementation of methods on the
34310 ** sqlite3_vfs object.
34311 */
34312 
34313 /*
34314 ** Initialize the contents of the unixFile structure pointed to by pId.
34315 */
34316 static int fillInUnixFile(
34317  sqlite3_vfs *pVfs, /* Pointer to vfs object */
34318  int h, /* Open file descriptor of file being opened */
34319  sqlite3_file *pId, /* Write to the unixFile structure here */
34320  const char *zFilename, /* Name of the file being opened */
34321  int ctrlFlags /* Zero or more UNIXFILE_* values */
34322 ){
34323  const sqlite3_io_methods *pLockingStyle;
34324  unixFile *pNew = (unixFile *)pId;
34325  int rc = SQLITE_OK;
34326 
34327  assert( pNew->pInode==NULL );
34328 
34329  /* Usually the path zFilename should not be a relative pathname. The
34330  ** exception is when opening the proxy "conch" file in builds that
34331  ** include the special Apple locking styles.
34332  */
34333 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34334  assert( zFilename==0 || zFilename[0]=='/'
34335  || pVfs->pAppData==(void*)&autolockIoFinder );
34336 #else
34337  assert( zFilename==0 || zFilename[0]=='/' );
34338 #endif
34339 
34340  /* No locking occurs in temporary files */
34341  assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
34342 
34343  OSTRACE(("OPEN %-3d %s\n", h, zFilename));
34344  pNew->h = h;
34345  pNew->pVfs = pVfs;
34346  pNew->zPath = zFilename;
34347  pNew->ctrlFlags = (u8)ctrlFlags;
34348 #if SQLITE_MAX_MMAP_SIZE>0
34349  pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
34350 #endif
34351  if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
34352  "psow", SQLITE_POWERSAFE_OVERWRITE) ){
34353  pNew->ctrlFlags |= UNIXFILE_PSOW;
34354  }
34355  if( strcmp(pVfs->zName,"unix-excl")==0 ){
34356  pNew->ctrlFlags |= UNIXFILE_EXCL;
34357  }
34358 
34359 #if OS_VXWORKS
34360  pNew->pId = vxworksFindFileId(zFilename);
34361  if( pNew->pId==0 ){
34362  ctrlFlags |= UNIXFILE_NOLOCK;
34363  rc = SQLITE_NOMEM_BKPT;
34364  }
34365 #endif
34366 
34367  if( ctrlFlags & UNIXFILE_NOLOCK ){
34368  pLockingStyle = &nolockIoMethods;
34369  }else{
34370  pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
34371 #if SQLITE_ENABLE_LOCKING_STYLE
34372  /* Cache zFilename in the locking context (AFP and dotlock override) for
34373  ** proxyLock activation is possible (remote proxy is based on db name)
34374  ** zFilename remains valid until file is closed, to support */
34375  pNew->lockingContext = (void*)zFilename;
34376 #endif
34377  }
34378 
34379  if( pLockingStyle == &posixIoMethods
34380 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
34381  || pLockingStyle == &nfsIoMethods
34382 #endif
34383  ){
34384  unixEnterMutex();
34385  rc = findInodeInfo(pNew, &pNew->pInode);
34386  if( rc!=SQLITE_OK ){
34387  /* If an error occurred in findInodeInfo(), close the file descriptor
34388  ** immediately, before releasing the mutex. findInodeInfo() may fail
34389  ** in two scenarios:
34390  **
34391  ** (a) A call to fstat() failed.
34392  ** (b) A malloc failed.
34393  **
34394  ** Scenario (b) may only occur if the process is holding no other
34395  ** file descriptors open on the same file. If there were other file
34396  ** descriptors on this file, then no malloc would be required by
34397  ** findInodeInfo(). If this is the case, it is quite safe to close
34398  ** handle h - as it is guaranteed that no posix locks will be released
34399  ** by doing so.
34400  **
34401  ** If scenario (a) caused the error then things are not so safe. The
34402  ** implicit assumption here is that if fstat() fails, things are in
34403  ** such bad shape that dropping a lock or two doesn't matter much.
34404  */
34405  robust_close(pNew, h, __LINE__);
34406  h = -1;
34407  }
34408  unixLeaveMutex();
34409  }
34410 
34411 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34412  else if( pLockingStyle == &afpIoMethods ){
34413  /* AFP locking uses the file path so it needs to be included in
34414  ** the afpLockingContext.
34415  */
34416  afpLockingContext *pCtx;
34417  pNew->lockingContext = pCtx = sqlite3_malloc64( sizeof(*pCtx) );
34418  if( pCtx==0 ){
34419  rc = SQLITE_NOMEM_BKPT;
34420  }else{
34421  /* NB: zFilename exists and remains valid until the file is closed
34422  ** according to requirement F11141. So we do not need to make a
34423  ** copy of the filename. */
34424  pCtx->dbPath = zFilename;
34425  pCtx->reserved = 0;
34426  srandomdev();
34427  unixEnterMutex();
34428  rc = findInodeInfo(pNew, &pNew->pInode);
34429  if( rc!=SQLITE_OK ){
34431  robust_close(pNew, h, __LINE__);
34432  h = -1;
34433  }
34434  unixLeaveMutex();
34435  }
34436  }
34437 #endif
34438 
34439  else if( pLockingStyle == &dotlockIoMethods ){
34440  /* Dotfile locking uses the file path so it needs to be included in
34441  ** the dotlockLockingContext
34442  */
34443  char *zLockFile;
34444  int nFilename;
34445  assert( zFilename!=0 );
34446  nFilename = (int)strlen(zFilename) + 6;
34447  zLockFile = (char *)sqlite3_malloc64(nFilename);
34448  if( zLockFile==0 ){
34449  rc = SQLITE_NOMEM_BKPT;
34450  }else{
34451  sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
34452  }
34453  pNew->lockingContext = zLockFile;
34454  }
34455 
34456 #if OS_VXWORKS
34457  else if( pLockingStyle == &semIoMethods ){
34458  /* Named semaphore locking uses the file path so it needs to be
34459  ** included in the semLockingContext
34460  */
34461  unixEnterMutex();
34462  rc = findInodeInfo(pNew, &pNew->pInode);
34463  if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
34464  char *zSemName = pNew->pInode->aSemName;
34465  int n;
34466  sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
34467  pNew->pId->zCanonicalName);
34468  for( n=1; zSemName[n]; n++ )
34469  if( zSemName[n]=='/' ) zSemName[n] = '_';
34470  pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
34471  if( pNew->pInode->pSem == SEM_FAILED ){
34472  rc = SQLITE_NOMEM_BKPT;
34473  pNew->pInode->aSemName[0] = '\0';
34474  }
34475  }
34476  unixLeaveMutex();
34477  }
34478 #endif
34479 
34480  storeLastErrno(pNew, 0);
34481 #if OS_VXWORKS
34482  if( rc!=SQLITE_OK ){
34483  if( h>=0 ) robust_close(pNew, h, __LINE__);
34484  h = -1;
34485  osUnlink(zFilename);
34486  pNew->ctrlFlags |= UNIXFILE_DELETE;
34487  }
34488 #endif
34489  if( rc!=SQLITE_OK ){
34490  if( h>=0 ) robust_close(pNew, h, __LINE__);
34491  }else{
34492  pNew->pMethod = pLockingStyle;
34493  OpenCounter(+1);
34494  verifyDbFile(pNew);
34495  }
34496  return rc;
34497 }
34498 
34499 /*
34500 ** Return the name of a directory in which to put temporary files.
34501 ** If no suitable temporary file directory can be found, return NULL.
34502 */
34503 static const char *unixTempFileDir(void){
34504  static const char *azDirs[] = {
34505  0,
34506  0,
34507  "/var/tmp",
34508  "/usr/tmp",
34509  "/tmp",
34510  "."
34511  };
34512  unsigned int i = 0;
34513  struct stat buf;
34514  const char *zDir = sqlite3_temp_directory;
34515 
34516  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
34517  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
34518  while(1){
34519  if( zDir!=0
34520  && osStat(zDir, &buf)==0
34521  && S_ISDIR(buf.st_mode)
34522  && osAccess(zDir, 03)==0
34523  ){
34524  return zDir;
34525  }
34526  if( i>=sizeof(azDirs)/sizeof(azDirs[0]) ) break;
34527  zDir = azDirs[i++];
34528  }
34529  return 0;
34530 }
34531 
34532 /*
34533 ** Create a temporary file name in zBuf. zBuf must be allocated
34534 ** by the calling process and must be big enough to hold at least
34535 ** pVfs->mxPathname bytes.
34536 */
34537 static int unixGetTempname(int nBuf, char *zBuf){
34538  const char *zDir;
34539  int iLimit = 0;
34540 
34541  /* It's odd to simulate an io-error here, but really this is just
34542  ** using the io-error infrastructure to test that SQLite handles this
34543  ** function failing.
34544  */
34545  zBuf[0] = 0;
34546  SimulateIOError( return SQLITE_IOERR );
34547 
34548  zDir = unixTempFileDir();
34549  if( zDir==0 ) return SQLITE_IOERR_GETTEMPPATH;
34550  do{
34551  u64 r;
34552  sqlite3_randomness(sizeof(r), &r);
34553  assert( nBuf>2 );
34554  zBuf[nBuf-2] = 0;
34555  sqlite3_snprintf(nBuf, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX"%llx%c",
34556  zDir, r, 0);
34557  if( zBuf[nBuf-2]!=0 || (iLimit++)>10 ) return SQLITE_ERROR;
34558  }while( osAccess(zBuf,0)==0 );
34559  return SQLITE_OK;
34560 }
34561 
34562 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
34563 /*
34564 ** Routine to transform a unixFile into a proxy-locking unixFile.
34565 ** Implementation in the proxy-lock division, but used by unixOpen()
34566 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
34567 */
34568 static int proxyTransformUnixFile(unixFile*, const char*);
34569 #endif
34570 
34571 /*
34572 ** Search for an unused file descriptor that was opened on the database
34573 ** file (not a journal or master-journal file) identified by pathname
34574 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
34575 ** argument to this function.
34576 **
34577 ** Such a file descriptor may exist if a database connection was closed
34578 ** but the associated file descriptor could not be closed because some
34579 ** other file descriptor open on the same file is holding a file-lock.
34580 ** Refer to comments in the unixClose() function and the lengthy comment
34581 ** describing "Posix Advisory Locking" at the start of this file for
34582 ** further details. Also, ticket #4018.
34583 **
34584 ** If a suitable file descriptor is found, then it is returned. If no
34585 ** such file descriptor is located, -1 is returned.
34586 */
34587 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
34588  UnixUnusedFd *pUnused = 0;
34589 
34590  /* Do not search for an unused file descriptor on vxworks. Not because
34591  ** vxworks would not benefit from the change (it might, we're not sure),
34592  ** but because no way to test it is currently available. It is better
34593  ** not to risk breaking vxworks support for the sake of such an obscure
34594  ** feature. */
34595 #if !OS_VXWORKS
34596  struct stat sStat; /* Results of stat() call */
34597 
34598  /* A stat() call may fail for various reasons. If this happens, it is
34599  ** almost certain that an open() call on the same path will also fail.
34600  ** For this reason, if an error occurs in the stat() call here, it is
34601  ** ignored and -1 is returned. The caller will try to open a new file
34602  ** descriptor on the same path, fail, and return an error to SQLite.
34603  **
34604  ** Even if a subsequent open() call does succeed, the consequences of
34605  ** not searching for a reusable file descriptor are not dire. */
34606  if( 0==osStat(zPath, &sStat) ){
34607  unixInodeInfo *pInode;
34608 
34609  unixEnterMutex();
34610  pInode = inodeList;
34611  while( pInode && (pInode->fileId.dev!=sStat.st_dev
34612  || pInode->fileId.ino!=sStat.st_ino) ){
34613  pInode = pInode->pNext;
34614  }
34615  if( pInode ){
34616  UnixUnusedFd **pp;
34617  for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
34618  pUnused = *pp;
34619  if( pUnused ){
34620  *pp = pUnused->pNext;
34621  }
34622  }
34623  unixLeaveMutex();
34624  }
34625 #endif /* if !OS_VXWORKS */
34626  return pUnused;
34627 }
34628 
34629 /*
34630 ** This function is called by unixOpen() to determine the unix permissions
34631 ** to create new files with. If no error occurs, then SQLITE_OK is returned
34632 ** and a value suitable for passing as the third argument to open(2) is
34633 ** written to *pMode. If an IO error occurs, an SQLite error code is
34634 ** returned and the value of *pMode is not modified.
34635 **
34636 ** In most cases, this routine sets *pMode to 0, which will become
34637 ** an indication to robust_open() to create the file using
34638 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
34639 ** But if the file being opened is a WAL or regular journal file, then
34640 ** this function queries the file-system for the permissions on the
34641 ** corresponding database file and sets *pMode to this value. Whenever
34642 ** possible, WAL and journal files are created using the same permissions
34643 ** as the associated database file.
34644 **
34645 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
34646 ** original filename is unavailable. But 8_3_NAMES is only used for
34647 ** FAT filesystems and permissions do not matter there, so just use
34648 ** the default permissions.
34649 */
34651  const char *zPath, /* Path of file (possibly) being created */
34652  int flags, /* Flags passed as 4th argument to xOpen() */
34653  mode_t *pMode, /* OUT: Permissions to open file with */
34654  uid_t *pUid, /* OUT: uid to set on the file */
34655  gid_t *pGid /* OUT: gid to set on the file */
34656 ){
34657  int rc = SQLITE_OK; /* Return Code */
34658  *pMode = 0;
34659  *pUid = 0;
34660  *pGid = 0;
34661  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34662  char zDb[MAX_PATHNAME+1]; /* Database file path */
34663  int nDb; /* Number of valid bytes in zDb */
34664  struct stat sStat; /* Output of stat() on database file */
34665 
34666  /* zPath is a path to a WAL or journal file. The following block derives
34667  ** the path to the associated database file from zPath. This block handles
34668  ** the following naming conventions:
34669  **
34670  ** "<path to db>-journal"
34671  ** "<path to db>-wal"
34672  ** "<path to db>-journalNN"
34673  ** "<path to db>-walNN"
34674  **
34675  ** where NN is a decimal number. The NN naming schemes are
34676  ** used by the test_multiplex.c module.
34677  */
34678  nDb = sqlite3Strlen30(zPath) - 1;
34679  while( zPath[nDb]!='-' ){
34680 #ifndef SQLITE_ENABLE_8_3_NAMES
34681  /* In the normal case (8+3 filenames disabled) the journal filename
34682  ** is guaranteed to contain a '-' character. */
34683  assert( nDb>0 );
34684  assert( sqlite3Isalnum(zPath[nDb]) );
34685 #else
34686  /* If 8+3 names are possible, then the journal file might not contain
34687  ** a '-' character. So check for that case and return early. */
34688  if( nDb==0 || zPath[nDb]=='.' ) return SQLITE_OK;
34689 #endif
34690  nDb--;
34691  }
34692  memcpy(zDb, zPath, nDb);
34693  zDb[nDb] = '\0';
34694 
34695  if( 0==osStat(zDb, &sStat) ){
34696  *pMode = sStat.st_mode & 0777;
34697  *pUid = sStat.st_uid;
34698  *pGid = sStat.st_gid;
34699  }else{
34700  rc = SQLITE_IOERR_FSTAT;
34701  }
34702  }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
34703  *pMode = 0600;
34704  }
34705  return rc;
34706 }
34707 
34708 /*
34709 ** Open the file zPath.
34710 **
34711 ** Previously, the SQLite OS layer used three functions in place of this
34712 ** one:
34713 **
34714 ** sqlite3OsOpenReadWrite();
34715 ** sqlite3OsOpenReadOnly();
34716 ** sqlite3OsOpenExclusive();
34717 **
34718 ** These calls correspond to the following combinations of flags:
34719 **
34720 ** ReadWrite() -> (READWRITE | CREATE)
34721 ** ReadOnly() -> (READONLY)
34722 ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
34723 **
34724 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
34725 ** true, the file was configured to be automatically deleted when the
34726 ** file handle closed. To achieve the same effect using this new
34727 ** interface, add the DELETEONCLOSE flag to those specified above for
34728 ** OpenExclusive().
34729 */
34730 static int unixOpen(
34731  sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
34732  const char *zPath, /* Pathname of file to be opened */
34733  sqlite3_file *pFile, /* The file descriptor to be filled in */
34734  int flags, /* Input flags to control the opening */
34735  int *pOutFlags /* Output flags returned to SQLite core */
34736 ){
34737  unixFile *p = (unixFile *)pFile;
34738  int fd = -1; /* File descriptor returned by open() */
34739  int openFlags = 0; /* Flags to pass to open() */
34740  int eType = flags&0xFFFFFF00; /* Type of file to open */
34741  int noLock; /* True to omit locking primitives */
34742  int rc = SQLITE_OK; /* Function Return Code */
34743  int ctrlFlags = 0; /* UNIXFILE_* flags */
34744 
34745  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
34746  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
34747  int isCreate = (flags & SQLITE_OPEN_CREATE);
34748  int isReadonly = (flags & SQLITE_OPEN_READONLY);
34749  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
34750 #if SQLITE_ENABLE_LOCKING_STYLE
34751  int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
34752 #endif
34753 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
34754  struct statfs fsInfo;
34755 #endif
34756 
34757  /* If creating a master or main-file journal, this function will open
34758  ** a file-descriptor on the directory too. The first time unixSync()
34759  ** is called the directory file descriptor will be fsync()ed and close()d.
34760  */
34761  int syncDir = (isCreate && (
34763  || eType==SQLITE_OPEN_MAIN_JOURNAL
34764  || eType==SQLITE_OPEN_WAL
34765  ));
34766 
34767  /* If argument zPath is a NULL pointer, this function is required to open
34768  ** a temporary file. Use this buffer to store the file name in.
34769  */
34770  char zTmpname[MAX_PATHNAME+2];
34771  const char *zName = zPath;
34772 
34773  /* Check the following statements are true:
34774  **
34775  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
34776  ** (b) if CREATE is set, then READWRITE must also be set, and
34777  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
34778  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
34779  */
34780  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
34781  assert(isCreate==0 || isReadWrite);
34782  assert(isExclusive==0 || isCreate);
34783  assert(isDelete==0 || isCreate);
34784 
34785  /* The main DB, main journal, WAL file and master journal are never
34786  ** automatically deleted. Nor are they ever temporary files. */
34787  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
34788  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
34789  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
34790  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
34791 
34792  /* Assert that the upper layer has set one of the "file-type" flags. */
34796  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
34797  );
34798 
34799  /* Detect a pid change and reset the PRNG. There is a race condition
34800  ** here such that two or more threads all trying to open databases at
34801  ** the same instant might all reset the PRNG. But multiple resets
34802  ** are harmless.
34803  */
34804  if( randomnessPid!=osGetpid(0) ){
34805  randomnessPid = osGetpid(0);
34806  sqlite3_randomness(0,0);
34807  }
34808 
34809  memset(p, 0, sizeof(unixFile));
34810 
34811  if( eType==SQLITE_OPEN_MAIN_DB ){
34812  UnixUnusedFd *pUnused;
34813  pUnused = findReusableFd(zName, flags);
34814  if( pUnused ){
34815  fd = pUnused->fd;
34816  }else{
34817  pUnused = sqlite3_malloc64(sizeof(*pUnused));
34818  if( !pUnused ){
34819  return SQLITE_NOMEM_BKPT;
34820  }
34821  }
34822  p->pUnused = pUnused;
34823 
34824  /* Database filenames are double-zero terminated if they are not
34825  ** URIs with parameters. Hence, they can always be passed into
34826  ** sqlite3_uri_parameter(). */
34827  assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
34828 
34829  }else if( !zName ){
34830  /* If zName is NULL, the upper layer is requesting a temp file. */
34831  assert(isDelete && !syncDir);
34832  rc = unixGetTempname(pVfs->mxPathname, zTmpname);
34833  if( rc!=SQLITE_OK ){
34834  return rc;
34835  }
34836  zName = zTmpname;
34837 
34838  /* Generated temporary filenames are always double-zero terminated
34839  ** for use by sqlite3_uri_parameter(). */
34840  assert( zName[strlen(zName)+1]==0 );
34841  }
34842 
34843  /* Determine the value of the flags parameter passed to POSIX function
34844  ** open(). These must be calculated even if open() is not called, as
34845  ** they may be stored as part of the file handle and used by the
34846  ** 'conch file' locking functions later on. */
34847  if( isReadonly ) openFlags |= O_RDONLY;
34848  if( isReadWrite ) openFlags |= O_RDWR;
34849  if( isCreate ) openFlags |= O_CREAT;
34850  if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
34851  openFlags |= (O_LARGEFILE|O_BINARY);
34852 
34853  if( fd<0 ){
34854  mode_t openMode; /* Permissions to create file with */
34855  uid_t uid; /* Userid for the file */
34856  gid_t gid; /* Groupid for the file */
34857  rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
34858  if( rc!=SQLITE_OK ){
34859  assert( !p->pUnused );
34860  assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
34861  return rc;
34862  }
34863  fd = robust_open(zName, openFlags, openMode);
34864  OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
34865  assert( !isExclusive || (openFlags & O_CREAT)!=0 );
34866  if( fd<0 && errno!=EISDIR && isReadWrite ){
34867  /* Failed to open the file for read/write access. Try read-only. */
34869  openFlags &= ~(O_RDWR|O_CREAT);
34870  flags |= SQLITE_OPEN_READONLY;
34871  openFlags |= O_RDONLY;
34872  isReadonly = 1;
34873  fd = robust_open(zName, openFlags, openMode);
34874  }
34875  if( fd<0 ){
34876  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
34877  goto open_finished;
34878  }
34879 
34880  /* If this process is running as root and if creating a new rollback
34881  ** journal or WAL file, set the ownership of the journal or WAL to be
34882  ** the same as the original database.
34883  */
34884  if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
34885  robustFchown(fd, uid, gid);
34886  }
34887  }
34888  assert( fd>=0 );
34889  if( pOutFlags ){
34890  *pOutFlags = flags;
34891  }
34892 
34893  if( p->pUnused ){
34894  p->pUnused->fd = fd;
34895  p->pUnused->flags = flags;
34896  }
34897 
34898  if( isDelete ){
34899 #if OS_VXWORKS
34900  zPath = zName;
34901 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
34902  zPath = sqlite3_mprintf("%s", zName);
34903  if( zPath==0 ){
34904  robust_close(p, fd, __LINE__);
34905  return SQLITE_NOMEM_BKPT;
34906  }
34907 #else
34908  osUnlink(zName);
34909 #endif
34910  }
34911 #if SQLITE_ENABLE_LOCKING_STYLE
34912  else{
34913  p->openFlags = openFlags;
34914  }
34915 #endif
34916 
34917 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
34918  if( fstatfs(fd, &fsInfo) == -1 ){
34919  storeLastErrno(p, errno);
34920  robust_close(p, fd, __LINE__);
34921  return SQLITE_IOERR_ACCESS;
34922  }
34923  if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
34924  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
34925  }
34926  if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
34927  ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
34928  }
34929 #endif
34930 
34931  /* Set up appropriate ctrlFlags */
34932  if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
34933  if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
34934  noLock = eType!=SQLITE_OPEN_MAIN_DB;
34935  if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
34936  if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
34937  if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
34938 
34939 #if SQLITE_ENABLE_LOCKING_STYLE
34940 #if SQLITE_PREFER_PROXY_LOCKING
34941  isAutoProxy = 1;
34942 #endif
34943  if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
34944  char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
34945  int useProxy = 0;
34946 
34947  /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
34948  ** never use proxy, NULL means use proxy for non-local files only. */
34949  if( envforce!=NULL ){
34950  useProxy = atoi(envforce)>0;
34951  }else{
34952  useProxy = !(fsInfo.f_flags&MNT_LOCAL);
34953  }
34954  if( useProxy ){
34955  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
34956  if( rc==SQLITE_OK ){
34957  rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
34958  if( rc!=SQLITE_OK ){
34959  /* Use unixClose to clean up the resources added in fillInUnixFile
34960  ** and clear all the structure's references. Specifically,
34961  ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
34962  */
34963  unixClose(pFile);
34964  return rc;
34965  }
34966  }
34967  goto open_finished;
34968  }
34969  }
34970 #endif
34971 
34972  rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
34973 
34974 open_finished:
34975  if( rc!=SQLITE_OK ){
34976  sqlite3_free(p->pUnused);
34977  }
34978  return rc;
34979 }
34980 
34981 
34982 /*
34983 ** Delete the file at zPath. If the dirSync argument is true, fsync()
34984 ** the directory after deleting the file.
34985 */
34986 static int unixDelete(
34987  sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
34988  const char *zPath, /* Name of file to be deleted */
34989  int dirSync /* If true, fsync() directory after deleting file */
34990 ){
34991  int rc = SQLITE_OK;
34992  UNUSED_PARAMETER(NotUsed);
34994  if( osUnlink(zPath)==(-1) ){
34995  if( errno==ENOENT
34996 #if OS_VXWORKS
34997  || osAccess(zPath,0)!=0
34998 #endif
34999  ){
35001  }else{
35002  rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
35003  }
35004  return rc;
35005  }
35006 #ifndef SQLITE_DISABLE_DIRSYNC
35007  if( (dirSync & 1)!=0 ){
35008  int fd;
35009  rc = osOpenDirectory(zPath, &fd);
35010  if( rc==SQLITE_OK ){
35011  if( full_fsync(fd,0,0) ){
35012  rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
35013  }
35014  robust_close(0, fd, __LINE__);
35015  }else{
35016  assert( rc==SQLITE_CANTOPEN );
35017  rc = SQLITE_OK;
35018  }
35019  }
35020 #endif
35021  return rc;
35022 }
35023 
35024 /*
35025 ** Test the existence of or access permissions of file zPath. The
35026 ** test performed depends on the value of flags:
35027 **
35028 ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
35029 ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
35030 ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
35031 **
35032 ** Otherwise return 0.
35033 */
35034 static int unixAccess(
35035  sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
35036  const char *zPath, /* Path of the file to examine */
35037  int flags, /* What do we want to learn about the zPath file? */
35038  int *pResOut /* Write result boolean here */
35039 ){
35040  UNUSED_PARAMETER(NotUsed);
35042  assert( pResOut!=0 );
35043 
35044  /* The spec says there are three possible values for flags. But only
35045  ** two of them are actually used */
35046  assert( flags==SQLITE_ACCESS_EXISTS || flags==SQLITE_ACCESS_READWRITE );
35047 
35048  if( flags==SQLITE_ACCESS_EXISTS ){
35049  struct stat buf;
35050  *pResOut = (0==osStat(zPath, &buf) && buf.st_size>0);
35051  }else{
35052  *pResOut = osAccess(zPath, W_OK|R_OK)==0;
35053  }
35054  return SQLITE_OK;
35055 }
35056 
35057 /*
35058 **
35059 */
35060 static int mkFullPathname(
35061  const char *zPath, /* Input path */
35062  char *zOut, /* Output buffer */
35063  int nOut /* Allocated size of buffer zOut */
35064 ){
35065  int nPath = sqlite3Strlen30(zPath);
35066  int iOff = 0;
35067  if( zPath[0]!='/' ){
35068  if( osGetcwd(zOut, nOut-2)==0 ){
35069  return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
35070  }
35071  iOff = sqlite3Strlen30(zOut);
35072  zOut[iOff++] = '/';
35073  }
35074  if( (iOff+nPath+1)>nOut ){
35075  /* SQLite assumes that xFullPathname() nul-terminates the output buffer
35076  ** even if it returns an error. */
35077  zOut[iOff] = '\0';
35078  return SQLITE_CANTOPEN_BKPT;
35079  }
35080  sqlite3_snprintf(nOut-iOff, &zOut[iOff], "%s", zPath);
35081  return SQLITE_OK;
35082 }
35083 
35084 /*
35085 ** Turn a relative pathname into a full pathname. The relative path
35086 ** is stored as a nul-terminated string in the buffer pointed to by
35087 ** zPath.
35088 **
35089 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
35090 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
35091 ** this buffer before returning.
35092 */
35093 static int unixFullPathname(
35094  sqlite3_vfs *pVfs, /* Pointer to vfs object */
35095  const char *zPath, /* Possibly relative input path */
35096  int nOut, /* Size of output buffer in bytes */
35097  char *zOut /* Output buffer */
35098 ){
35099 #if !defined(HAVE_READLINK) || !defined(HAVE_LSTAT)
35100  return mkFullPathname(zPath, zOut, nOut);
35101 #else
35102  int rc = SQLITE_OK;
35103  int nByte;
35104  int nLink = 1; /* Number of symbolic links followed so far */
35105  const char *zIn = zPath; /* Input path for each iteration of loop */
35106  char *zDel = 0;
35107 
35108  assert( pVfs->mxPathname==MAX_PATHNAME );
35109  UNUSED_PARAMETER(pVfs);
35110 
35111  /* It's odd to simulate an io-error here, but really this is just
35112  ** using the io-error infrastructure to test that SQLite handles this
35113  ** function failing. This function could fail if, for example, the
35114  ** current working directory has been unlinked.
35115  */
35116  SimulateIOError( return SQLITE_ERROR );
35117 
35118  do {
35119 
35120  /* Call stat() on path zIn. Set bLink to true if the path is a symbolic
35121  ** link, or false otherwise. */
35122  int bLink = 0;
35123  struct stat buf;
35124  if( osLstat(zIn, &buf)!=0 ){
35125  if( errno!=ENOENT ){
35126  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "lstat", zIn);
35127  }
35128  }else{
35129  bLink = S_ISLNK(buf.st_mode);
35130  }
35131 
35132  if( bLink ){
35133  if( zDel==0 ){
35134  zDel = sqlite3_malloc(nOut);
35135  if( zDel==0 ) rc = SQLITE_NOMEM_BKPT;
35136  }else if( ++nLink>SQLITE_MAX_SYMLINKS ){
35137  rc = SQLITE_CANTOPEN_BKPT;
35138  }
35139 
35140  if( rc==SQLITE_OK ){
35141  nByte = osReadlink(zIn, zDel, nOut-1);
35142  if( nByte<0 ){
35143  rc = unixLogError(SQLITE_CANTOPEN_BKPT, "readlink", zIn);
35144  }else{
35145  if( zDel[0]!='/' ){
35146  int n;
35147  for(n = sqlite3Strlen30(zIn); n>0 && zIn[n-1]!='/'; n--);
35148  if( nByte+n+1>nOut ){
35149  rc = SQLITE_CANTOPEN_BKPT;
35150  }else{
35151  memmove(&zDel[n], zDel, nByte+1);
35152  memcpy(zDel, zIn, n);
35153  nByte += n;
35154  }
35155  }
35156  zDel[nByte] = '\0';
35157  }
35158  }
35159 
35160  zIn = zDel;
35161  }
35162 
35163  assert( rc!=SQLITE_OK || zIn!=zOut || zIn[0]=='/' );
35164  if( rc==SQLITE_OK && zIn!=zOut ){
35165  rc = mkFullPathname(zIn, zOut, nOut);
35166  }
35167  if( bLink==0 ) break;
35168  zIn = zOut;
35169  }while( rc==SQLITE_OK );
35170 
35171  sqlite3_free(zDel);
35172  return rc;
35173 #endif /* HAVE_READLINK && HAVE_LSTAT */
35174 }
35175 
35176 
35177 
35178  #define unixDlOpen 0
35179  #define unixDlError 0
35180  #define unixDlSym 0
35181  #define unixDlClose 0
35182 
35183 /*
35184 ** Write nBuf bytes of random data to the supplied buffer zBuf.
35185 */
35186 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
35187  UNUSED_PARAMETER(NotUsed);
35188  assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
35189 
35190  /* We have to initialize zBuf to prevent valgrind from reporting
35191  ** errors. The reports issued by valgrind are incorrect - we would
35192  ** prefer that the randomness be increased by making use of the
35193  ** uninitialized space in zBuf - but valgrind errors tend to worry
35194  ** some users. Rather than argue, it seems easier just to initialize
35195  ** the whole array and silence valgrind, even if that means less randomness
35196  ** in the random seed.
35197  **
35198  ** When testing, initializing zBuf[] to zero is all we do. That means
35199  ** that we always use the same random number sequence. This makes the
35200  ** tests repeatable.
35201  */
35202  memset(zBuf, 0, nBuf);
35203  randomnessPid = osGetpid(0);
35204 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
35205  {
35206  int fd, got;
35207  fd = robust_open("/dev/urandom", O_RDONLY, 0);
35208  if( fd<0 ){
35209  time_t t;
35210  time(&t);
35211  memcpy(zBuf, &t, sizeof(t));
35212  memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
35213  assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
35214  nBuf = sizeof(t) + sizeof(randomnessPid);
35215  }else{
35216  do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
35217  robust_close(0, fd, __LINE__);
35218  }
35219  }
35220 #endif
35221  return nBuf;
35222 }
35223 
35224 
35225 /*
35226 ** Sleep for a little while. Return the amount of time slept.
35227 ** The argument is the number of microseconds we want to sleep.
35228 ** The return value is the number of microseconds of sleep actually
35229 ** requested from the underlying operating system, a number which
35230 ** might be greater than or equal to the argument, but not less
35231 ** than the argument.
35232 */
35233 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
35234 #if OS_VXWORKS
35235  struct timespec sp;
35236 
35237  sp.tv_sec = microseconds / 1000000;
35238  sp.tv_nsec = (microseconds % 1000000) * 1000;
35239  nanosleep(&sp, NULL);
35240  UNUSED_PARAMETER(NotUsed);
35241  return microseconds;
35242 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
35243  usleep(microseconds);
35244  UNUSED_PARAMETER(NotUsed);
35245  return microseconds;
35246 #else
35247  int seconds = (microseconds+999999)/1000000;
35248  sleep(seconds);
35249  UNUSED_PARAMETER(NotUsed);
35250  return seconds*1000000;
35251 #endif
35252 }
35253 
35254 /*
35255 ** The following variable, if set to a non-zero value, is interpreted as
35256 ** the number of seconds since 1970 and is used to set the result of
35257 ** sqlite3OsCurrentTime() during testing.
35258 */
35259 #ifdef SQLITE_TEST
35260 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
35261 #endif
35262 
35263 /*
35264 ** Find the current time (in Universal Coordinated Time). Write into *piNow
35265 ** the current time and date as a Julian Day number times 86_400_000. In
35266 ** other words, write into *piNow the number of milliseconds since the Julian
35267 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
35268 ** proleptic Gregorian calendar.
35269 **
35270 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
35271 ** cannot be found.
35272 */
35273 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
35274  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
35275  int rc = SQLITE_OK;
35276 #if defined(NO_GETTOD)
35277  time_t t;
35278  time(&t);
35279  *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
35280 #elif OS_VXWORKS
35281  struct timespec sNow;
35282  clock_gettime(CLOCK_REALTIME, &sNow);
35283  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
35284 #else
35285  struct timeval sNow;
35286  (void)gettimeofday(&sNow, 0); /* Cannot fail given valid arguments */
35287  *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
35288 #endif
35289 
35290 #ifdef SQLITE_TEST
35291  if( sqlite3_current_time ){
35292  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
35293  }
35294 #endif
35295  UNUSED_PARAMETER(NotUsed);
35296  return rc;
35297 }
35298 
35299 #ifndef SQLITE_OMIT_DEPRECATED
35300 /*
35301 ** Find the current time (in Universal Coordinated Time). Write the
35302 ** current time and date as a Julian Day number into *prNow and
35303 ** return 0. Return 1 if the time and date cannot be found.
35304 */
35305 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
35306  sqlite3_int64 i = 0;
35307  int rc;
35308  UNUSED_PARAMETER(NotUsed);
35309  rc = unixCurrentTimeInt64(0, &i);
35310  *prNow = i/86400000.0;
35311  return rc;
35312 }
35313 #else
35314 # define unixCurrentTime 0
35315 #endif
35316 
35317 /*
35318 ** The xGetLastError() method is designed to return a better
35319 ** low-level error message when operating-system problems come up
35320 ** during SQLite operation. Only the integer return code is currently
35321 ** used.
35322 */
35323 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
35324  UNUSED_PARAMETER(NotUsed);
35325  UNUSED_PARAMETER(NotUsed2);
35326  UNUSED_PARAMETER(NotUsed3);
35327  return errno;
35328 }
35329 
35330 
35331 /*
35332 ************************ End of sqlite3_vfs methods ***************************
35333 ******************************************************************************/
35334 
35335 /******************************************************************************
35336 ************************** Begin Proxy Locking ********************************
35337 **
35338 ** Proxy locking is a "uber-locking-method" in this sense: It uses the
35339 ** other locking methods on secondary lock files. Proxy locking is a
35340 ** meta-layer over top of the primitive locking implemented above. For
35341 ** this reason, the division that implements of proxy locking is deferred
35342 ** until late in the file (here) after all of the other I/O methods have
35343 ** been defined - so that the primitive locking methods are available
35344 ** as services to help with the implementation of proxy locking.
35345 **
35346 ****
35347 **
35348 ** The default locking schemes in SQLite use byte-range locks on the
35349 ** database file to coordinate safe, concurrent access by multiple readers
35350 ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
35351 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
35352 ** as POSIX read & write locks over fixed set of locations (via fsctl),
35353 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
35354 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
35355 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
35356 ** address in the shared range is taken for a SHARED lock, the entire
35357 ** shared range is taken for an EXCLUSIVE lock):
35358 **
35359 ** PENDING_BYTE 0x40000000
35360 ** RESERVED_BYTE 0x40000001
35361 ** SHARED_RANGE 0x40000002 -> 0x40000200
35362 **
35363 ** This works well on the local file system, but shows a nearly 100x
35364 ** slowdown in read performance on AFP because the AFP client disables
35365 ** the read cache when byte-range locks are present. Enabling the read
35366 ** cache exposes a cache coherency problem that is present on all OS X
35367 ** supported network file systems. NFS and AFP both observe the
35368 ** close-to-open semantics for ensuring cache coherency
35369 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
35370 ** address the requirements for concurrent database access by multiple
35371 ** readers and writers
35372 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
35373 **
35374 ** To address the performance and cache coherency issues, proxy file locking
35375 ** changes the way database access is controlled by limiting access to a
35376 ** single host at a time and moving file locks off of the database file
35377 ** and onto a proxy file on the local file system.
35378 **
35379 **
35380 ** Using proxy locks
35381 ** -----------------
35382 **
35383 ** C APIs
35384 **
35385 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
35386 ** <proxy_path> | ":auto:");
35387 ** sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
35388 ** &<proxy_path>);
35389 **
35390 **
35391 ** SQL pragmas
35392 **
35393 ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
35394 ** PRAGMA [database.]lock_proxy_file
35395 **
35396 ** Specifying ":auto:" means that if there is a conch file with a matching
35397 ** host ID in it, the proxy path in the conch file will be used, otherwise
35398 ** a proxy path based on the user's temp dir
35399 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
35400 ** actual proxy file name is generated from the name and path of the
35401 ** database file. For example:
35402 **
35403 ** For database path "/Users/me/foo.db"
35404 ** The lock path will be "<tmpdir>/sqliteplocks/_Users2_me_foo.db:auto:")
35405 **
35406 ** Once a lock proxy is configured for a database connection, it can not
35407 ** be removed, however it may be switched to a different proxy path via
35408 ** the above APIs (assuming the conch file is not being held by another
35409 ** connection or process).
35410 **
35411 **
35412 ** How proxy locking works
35413 ** -----------------------
35414 **
35415 ** Proxy file locking relies primarily on two new supporting files:
35416 **
35417 ** * conch file to limit access to the database file to a single host
35418 ** at a time
35419 **
35420 ** * proxy file to act as a proxy for the advisory locks normally
35421 ** taken on the database
35422 **
35423 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
35424 ** by taking an sqlite-style shared lock on the conch file, reading the
35425 ** contents and comparing the host's unique host ID (see below) and lock
35426 ** proxy path against the values stored in the conch. The conch file is
35427 ** stored in the same directory as the database file and the file name
35428 ** is patterned after the database file name as ".<databasename>-conch".
35429 ** If the conch file does not exist, or its contents do not match the
35430 ** host ID and/or proxy path, then the lock is escalated to an exclusive
35431 ** lock and the conch file contents is updated with the host ID and proxy
35432 ** path and the lock is downgraded to a shared lock again. If the conch
35433 ** is held by another process (with a shared lock), the exclusive lock
35434 ** will fail and SQLITE_BUSY is returned.
35435 **
35436 ** The proxy file - a single-byte file used for all advisory file locks
35437 ** normally taken on the database file. This allows for safe sharing
35438 ** of the database file for multiple readers and writers on the same
35439 ** host (the conch ensures that they all use the same local lock file).
35440 **
35441 ** Requesting the lock proxy does not immediately take the conch, it is
35442 ** only taken when the first request to lock database file is made.
35443 ** This matches the semantics of the traditional locking behavior, where
35444 ** opening a connection to a database file does not take a lock on it.
35445 ** The shared lock and an open file descriptor are maintained until
35446 ** the connection to the database is closed.
35447 **
35448 ** The proxy file and the lock file are never deleted so they only need
35449 ** to be created the first time they are used.
35450 **
35451 ** Configuration options
35452 ** ---------------------
35453 **
35454 ** SQLITE_PREFER_PROXY_LOCKING
35455 **
35456 ** Database files accessed on non-local file systems are
35457 ** automatically configured for proxy locking, lock files are
35458 ** named automatically using the same logic as
35459 ** PRAGMA lock_proxy_file=":auto:"
35460 **
35461 ** SQLITE_PROXY_DEBUG
35462 **
35463 ** Enables the logging of error messages during host id file
35464 ** retrieval and creation
35465 **
35466 ** LOCKPROXYDIR
35467 **
35468 ** Overrides the default directory used for lock proxy files that
35469 ** are named automatically via the ":auto:" setting
35470 **
35471 ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
35472 **
35473 ** Permissions to use when creating a directory for storing the
35474 ** lock proxy files, only used when LOCKPROXYDIR is not set.
35475 **
35476 **
35477 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
35478 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
35479 ** force proxy locking to be used for every database file opened, and 0
35480 ** will force automatic proxy locking to be disabled for all database
35481 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
35482 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
35483 */
35484 
35485 /*
35486 ** Proxy locking is only available on MacOSX
35487 */
35488 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
35489 
35490 /*
35491 ** The proxyLockingContext has the path and file structures for the remote
35492 ** and local proxy files in it
35493 */
35494 typedef struct proxyLockingContext proxyLockingContext;
35495 struct proxyLockingContext {
35496  unixFile *conchFile; /* Open conch file */
35497  char *conchFilePath; /* Name of the conch file */
35498  unixFile *lockProxy; /* Open proxy lock file */
35499  char *lockProxyPath; /* Name of the proxy lock file */
35500  char *dbPath; /* Name of the open file */
35501  int conchHeld; /* 1 if the conch is held, -1 if lockless */
35502  int nFails; /* Number of conch taking failures */
35503  void *oldLockingContext; /* Original lockingcontext to restore on close */
35504  sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
35505 };
35506 
35507 /*
35508 ** The proxy lock file path for the database at dbPath is written into lPath,
35509 ** which must point to valid, writable memory large enough for a maxLen length
35510 ** file path.
35511 */
35512 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
35513  int len;
35514  int dbLen;
35515  int i;
35516 
35517 #ifdef LOCKPROXYDIR
35518  len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
35519 #else
35520 # ifdef _CS_DARWIN_USER_TEMP_DIR
35521  {
35522  if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
35523  OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
35524  lPath, errno, osGetpid(0)));
35525  return SQLITE_IOERR_LOCK;
35526  }
35527  len = strlcat(lPath, "sqliteplocks", maxLen);
35528  }
35529 # else
35530  len = strlcpy(lPath, "/tmp/", maxLen);
35531 # endif
35532 #endif
35533 
35534  if( lPath[len-1]!='/' ){
35535  len = strlcat(lPath, "/", maxLen);
35536  }
35537 
35538  /* transform the db path to a unique cache name */
35539  dbLen = (int)strlen(dbPath);
35540  for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
35541  char c = dbPath[i];
35542  lPath[i+len] = (c=='/')?'_':c;
35543  }
35544  lPath[i+len]='\0';
35545  strlcat(lPath, ":auto:", maxLen);
35546  OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
35547  return SQLITE_OK;
35548 }
35549 
35550 /*
35551  ** Creates the lock file and any missing directories in lockPath
35552  */
35553 static int proxyCreateLockPath(const char *lockPath){
35554  int i, len;
35555  char buf[MAXPATHLEN];
35556  int start = 0;
35557 
35558  assert(lockPath!=NULL);
35559  /* try to create all the intermediate directories */
35560  len = (int)strlen(lockPath);
35561  buf[0] = lockPath[0];
35562  for( i=1; i<len; i++ ){
35563  if( lockPath[i] == '/' && (i - start > 0) ){
35564  /* only mkdir if leaf dir != "." or "/" or ".." */
35565  if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
35566  || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
35567  buf[i]='\0';
35569  int err=errno;
35570  if( err!=EEXIST ) {
35571  OSTRACE(("CREATELOCKPATH FAILED creating %s, "
35572  "'%s' proxy lock path=%s pid=%d\n",
35573  buf, strerror(err), lockPath, osGetpid(0)));
35574  return err;
35575  }
35576  }
35577  }
35578  start=i+1;
35579  }
35580  buf[i] = lockPath[i];
35581  }
35582  OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n",lockPath,osGetpid(0)));
35583  return 0;
35584 }
35585 
35586 /*
35587 ** Create a new VFS file descriptor (stored in memory obtained from
35588 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
35589 **
35590 ** The caller is responsible not only for closing the file descriptor
35591 ** but also for freeing the memory associated with the file descriptor.
35592 */
35593 static int proxyCreateUnixFile(
35594  const char *path, /* path for the new unixFile */
35595  unixFile **ppFile, /* unixFile created and returned by ref */
35596  int islockfile /* if non zero missing dirs will be created */
35597 ) {
35598  int fd = -1;
35599  unixFile *pNew;
35600  int rc = SQLITE_OK;
35601  int openFlags = O_RDWR | O_CREAT;
35602  sqlite3_vfs dummyVfs;
35603  int terrno = 0;
35604  UnixUnusedFd *pUnused = NULL;
35605 
35606  /* 1. first try to open/create the file
35607  ** 2. if that fails, and this is a lock file (not-conch), try creating
35608  ** the parent directories and then try again.
35609  ** 3. if that fails, try to open the file read-only
35610  ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
35611  */
35612  pUnused = findReusableFd(path, openFlags);
35613  if( pUnused ){
35614  fd = pUnused->fd;
35615  }else{
35616  pUnused = sqlite3_malloc64(sizeof(*pUnused));
35617  if( !pUnused ){
35618  return SQLITE_NOMEM_BKPT;
35619  }
35620  }
35621  if( fd<0 ){
35622  fd = robust_open(path, openFlags, 0);
35623  terrno = errno;
35624  if( fd<0 && errno==ENOENT && islockfile ){
35625  if( proxyCreateLockPath(path) == SQLITE_OK ){
35626  fd = robust_open(path, openFlags, 0);
35627  }
35628  }
35629  }
35630  if( fd<0 ){
35631  openFlags = O_RDONLY;
35632  fd = robust_open(path, openFlags, 0);
35633  terrno = errno;
35634  }
35635  if( fd<0 ){
35636  if( islockfile ){
35637  return SQLITE_BUSY;
35638  }
35639  switch (terrno) {
35640  case EACCES:
35641  return SQLITE_PERM;
35642  case EIO:
35643  return SQLITE_IOERR_LOCK; /* even though it is the conch */
35644  default:
35645  return SQLITE_CANTOPEN_BKPT;
35646  }
35647  }
35648 
35649  pNew = (unixFile *)sqlite3_malloc64(sizeof(*pNew));
35650  if( pNew==NULL ){
35651  rc = SQLITE_NOMEM_BKPT;
35652  goto end_create_proxy;
35653  }
35654  memset(pNew, 0, sizeof(unixFile));
35655  pNew->openFlags = openFlags;
35656  memset(&dummyVfs, 0, sizeof(dummyVfs));
35657  dummyVfs.pAppData = (void*)&autolockIoFinder;
35658  dummyVfs.zName = "dummy";
35659  pUnused->fd = fd;
35660  pUnused->flags = openFlags;
35661  pNew->pUnused = pUnused;
35662 
35663  rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
35664  if( rc==SQLITE_OK ){
35665  *ppFile = pNew;
35666  return SQLITE_OK;
35667  }
35668 end_create_proxy:
35669  robust_close(pNew, fd, __LINE__);
35670  sqlite3_free(pNew);
35671  sqlite3_free(pUnused);
35672  return rc;
35673 }
35674 
35675 #ifdef SQLITE_TEST
35676 /* simulate multiple hosts by creating unique hostid file paths */
35677 SQLITE_API int sqlite3_hostid_num = 0;
35678 #endif
35679 
35680 #define PROXY_HOSTIDLEN 16 /* conch file host id length */
35681 
35682 #ifdef HAVE_GETHOSTUUID
35683 /* Not always defined in the headers as it ought to be */
35684 extern int gethostuuid(uuid_t id, const struct timespec *wait);
35685 #endif
35686 
35687 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
35688 ** bytes of writable memory.
35689 */
35690 static int proxyGetHostID(unsigned char *pHostID, int *pError){
35691  assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
35692  memset(pHostID, 0, PROXY_HOSTIDLEN);
35693 #ifdef HAVE_GETHOSTUUID
35694  {
35695  struct timespec timeout = {1, 0}; /* 1 sec timeout */
35696  if( gethostuuid(pHostID, &timeout) ){
35697  int err = errno;
35698  if( pError ){
35699  *pError = err;
35700  }
35701  return SQLITE_IOERR;
35702  }
35703  }
35704 #else
35705  UNUSED_PARAMETER(pError);
35706 #endif
35707 #ifdef SQLITE_TEST
35708  /* simulate multiple hosts by creating unique hostid file paths */
35709  if( sqlite3_hostid_num != 0){
35710  pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
35711  }
35712 #endif
35713 
35714  return SQLITE_OK;
35715 }
35716 
35717 /* The conch file contains the header, host id and lock file path
35718  */
35719 #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
35720 #define PROXY_HEADERLEN 1 /* conch file header length */
35721 #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
35722 #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
35723 
35724 /*
35725 ** Takes an open conch file, copies the contents to a new path and then moves
35726 ** it back. The newly created file's file descriptor is assigned to the
35727 ** conch file structure and finally the original conch file descriptor is
35728 ** closed. Returns zero if successful.
35729 */
35730 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
35731  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
35732  unixFile *conchFile = pCtx->conchFile;
35733  char tPath[MAXPATHLEN];
35734  char buf[PROXY_MAXCONCHLEN];
35735  char *cPath = pCtx->conchFilePath;
35736  size_t readLen = 0;
35737  size_t pathLen = 0;
35738  char errmsg[64] = "";
35739  int fd = -1;
35740  int rc = -1;
35741  UNUSED_PARAMETER(myHostID);
35742 
35743  /* create a new path by replace the trailing '-conch' with '-break' */
35744  pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
35745  if( pathLen>MAXPATHLEN || pathLen<6 ||
35746  (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
35747  sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
35748  goto end_breaklock;
35749  }
35750  /* read the conch content */
35751  readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
35752  if( readLen<PROXY_PATHINDEX ){
35753  sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
35754  goto end_breaklock;
35755  }
35756  /* write it out to the temporary break file */
35757  fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
35758  if( fd<0 ){
35759  sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
35760  goto end_breaklock;
35761  }
35762  if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
35763  sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
35764  goto end_breaklock;
35765  }
35766  if( rename(tPath, cPath) ){
35767  sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
35768  goto end_breaklock;
35769  }
35770  rc = 0;
35771  fprintf(stderr, "broke stale lock on %s\n", cPath);
35772  robust_close(pFile, conchFile->h, __LINE__);
35773  conchFile->h = fd;
35774  conchFile->openFlags = O_RDWR | O_CREAT;
35775 
35776 end_breaklock:
35777  if( rc ){
35778  if( fd>=0 ){
35779  osUnlink(tPath);
35780  robust_close(pFile, fd, __LINE__);
35781  }
35782  fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
35783  }
35784  return rc;
35785 }
35786 
35787 /* Take the requested lock on the conch file and break a stale lock if the
35788 ** host id matches.
35789 */
35790 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
35791  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
35792  unixFile *conchFile = pCtx->conchFile;
35793  int rc = SQLITE_OK;
35794  int nTries = 0;
35795  struct timespec conchModTime;
35796 
35797  memset(&conchModTime, 0, sizeof(conchModTime));
35798  do {
35799  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
35800  nTries ++;
35801  if( rc==SQLITE_BUSY ){
35802  /* If the lock failed (busy):
35803  * 1st try: get the mod time of the conch, wait 0.5s and try again.
35804  * 2nd try: fail if the mod time changed or host id is different, wait
35805  * 10 sec and try again
35806  * 3rd try: break the lock unless the mod time has changed.
35807  */
35808  struct stat buf;
35809  if( osFstat(conchFile->h, &buf) ){
35810  storeLastErrno(pFile, errno);
35811  return SQLITE_IOERR_LOCK;
35812  }
35813 
35814  if( nTries==1 ){
35815  conchModTime = buf.st_mtimespec;
35816  usleep(500000); /* wait 0.5 sec and try the lock again*/
35817  continue;
35818  }
35819 
35820  assert( nTries>1 );
35821  if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
35822  conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
35823  return SQLITE_BUSY;
35824  }
35825 
35826  if( nTries==2 ){
35827  char tBuf[PROXY_MAXCONCHLEN];
35828  int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
35829  if( len<0 ){
35830  storeLastErrno(pFile, errno);
35831  return SQLITE_IOERR_LOCK;
35832  }
35833  if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
35834  /* don't break the lock if the host id doesn't match */
35835  if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
35836  return SQLITE_BUSY;
35837  }
35838  }else{
35839  /* don't break the lock on short read or a version mismatch */
35840  return SQLITE_BUSY;
35841  }
35842  usleep(10000000); /* wait 10 sec and try the lock again */
35843  continue;
35844  }
35845 
35846  assert( nTries==3 );
35847  if( 0==proxyBreakConchLock(pFile, myHostID) ){
35848  rc = SQLITE_OK;
35849  if( lockType==EXCLUSIVE_LOCK ){
35850  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
35851  }
35852  if( !rc ){
35853  rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
35854  }
35855  }
35856  }
35857  } while( rc==SQLITE_BUSY && nTries<3 );
35858 
35859  return rc;
35860 }
35861 
35862 /* Takes the conch by taking a shared lock and read the contents conch, if
35863 ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
35864 ** lockPath means that the lockPath in the conch file will be used if the
35865 ** host IDs match, or a new lock path will be generated automatically
35866 ** and written to the conch file.
35867 */
35868 static int proxyTakeConch(unixFile *pFile){
35869  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
35870 
35871  if( pCtx->conchHeld!=0 ){
35872  return SQLITE_OK;
35873  }else{
35874  unixFile *conchFile = pCtx->conchFile;
35875  uuid_t myHostID;
35876  int pError = 0;
35877  char readBuf[PROXY_MAXCONCHLEN];
35878  char lockPath[MAXPATHLEN];
35879  char *tempLockPath = NULL;
35880  int rc = SQLITE_OK;
35881  int createConch = 0;
35882  int hostIdMatch = 0;
35883  int readLen = 0;
35884  int tryOldLockPath = 0;
35885  int forceNewLockPath = 0;
35886 
35887  OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
35888  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
35889  osGetpid(0)));
35890 
35891  rc = proxyGetHostID(myHostID, &pError);
35892  if( (rc&0xff)==SQLITE_IOERR ){
35893  storeLastErrno(pFile, pError);
35894  goto end_takeconch;
35895  }
35896  rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
35897  if( rc!=SQLITE_OK ){
35898  goto end_takeconch;
35899  }
35900  /* read the existing conch file */
35901  readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
35902  if( readLen<0 ){
35903  /* I/O error: lastErrno set by seekAndRead */
35904  storeLastErrno(pFile, conchFile->lastErrno);
35905  rc = SQLITE_IOERR_READ;
35906  goto end_takeconch;
35907  }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
35908  readBuf[0]!=(char)PROXY_CONCHVERSION ){
35909  /* a short read or version format mismatch means we need to create a new
35910  ** conch file.
35911  */
35912  createConch = 1;
35913  }
35914  /* if the host id matches and the lock path already exists in the conch
35915  ** we'll try to use the path there, if we can't open that path, we'll
35916  ** retry with a new auto-generated path
35917  */
35918  do { /* in case we need to try again for an :auto: named lock file */
35919 
35920  if( !createConch && !forceNewLockPath ){
35921  hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
35922  PROXY_HOSTIDLEN);
35923  /* if the conch has data compare the contents */
35924  if( !pCtx->lockProxyPath ){
35925  /* for auto-named local lock file, just check the host ID and we'll
35926  ** use the local lock file path that's already in there
35927  */
35928  if( hostIdMatch ){
35929  size_t pathLen = (readLen - PROXY_PATHINDEX);
35930 
35931  if( pathLen>=MAXPATHLEN ){
35932  pathLen=MAXPATHLEN-1;
35933  }
35934  memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
35935  lockPath[pathLen] = 0;
35936  tempLockPath = lockPath;
35937  tryOldLockPath = 1;
35938  /* create a copy of the lock path if the conch is taken */
35939  goto end_takeconch;
35940  }
35941  }else if( hostIdMatch
35942  && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
35943  readLen-PROXY_PATHINDEX)
35944  ){
35945  /* conch host and lock path match */
35946  goto end_takeconch;
35947  }
35948  }
35949 
35950  /* if the conch isn't writable and doesn't match, we can't take it */
35951  if( (conchFile->openFlags&O_RDWR) == 0 ){
35952  rc = SQLITE_BUSY;
35953  goto end_takeconch;
35954  }
35955 
35956  /* either the conch didn't match or we need to create a new one */
35957  if( !pCtx->lockProxyPath ){
35958  proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
35959  tempLockPath = lockPath;
35960  /* create a copy of the lock path _only_ if the conch is taken */
35961  }
35962 
35963  /* update conch with host and path (this will fail if other process
35964  ** has a shared lock already), if the host id matches, use the big
35965  ** stick.
35966  */
35967  futimes(conchFile->h, NULL);
35968  if( hostIdMatch && !createConch ){
35969  if( conchFile->pInode && conchFile->pInode->nShared>1 ){
35970  /* We are trying for an exclusive lock but another thread in this
35971  ** same process is still holding a shared lock. */
35972  rc = SQLITE_BUSY;
35973  } else {
35974  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
35975  }
35976  }else{
35977  rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
35978  }
35979  if( rc==SQLITE_OK ){
35980  char writeBuffer[PROXY_MAXCONCHLEN];
35981  int writeSize = 0;
35982 
35983  writeBuffer[0] = (char)PROXY_CONCHVERSION;
35984  memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
35985  if( pCtx->lockProxyPath!=NULL ){
35986  strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
35987  MAXPATHLEN);
35988  }else{
35989  strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
35990  }
35991  writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
35992  robust_ftruncate(conchFile->h, writeSize);
35993  rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
35994  full_fsync(conchFile->h,0,0);
35995  /* If we created a new conch file (not just updated the contents of a
35996  ** valid conch file), try to match the permissions of the database
35997  */
35998  if( rc==SQLITE_OK && createConch ){
35999  struct stat buf;
36000  int err = osFstat(pFile->h, &buf);
36001  if( err==0 ){
36002  mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
36003  S_IROTH|S_IWOTH);
36004  /* try to match the database file R/W permissions, ignore failure */
36005 #ifndef SQLITE_PROXY_DEBUG
36006  osFchmod(conchFile->h, cmode);
36007 #else
36008  do{
36009  rc = osFchmod(conchFile->h, cmode);
36010  }while( rc==(-1) && errno==EINTR );
36011  if( rc!=0 ){
36012  int code = errno;
36013  fprintf(stderr, "fchmod %o FAILED with %d %s\n",
36014  cmode, code, strerror(code));
36015  } else {
36016  fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
36017  }
36018  }else{
36019  int code = errno;
36020  fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
36021  err, code, strerror(code));
36022 #endif
36023  }
36024  }
36025  }
36026  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
36027 
36028  end_takeconch:
36029  OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
36030  if( rc==SQLITE_OK && pFile->openFlags ){
36031  int fd;
36032  if( pFile->h>=0 ){
36033  robust_close(pFile, pFile->h, __LINE__);
36034  }
36035  pFile->h = -1;
36036  fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
36037  OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
36038  if( fd>=0 ){
36039  pFile->h = fd;
36040  }else{
36041  rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
36042  during locking */
36043  }
36044  }
36045  if( rc==SQLITE_OK && !pCtx->lockProxy ){
36046  char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
36047  rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
36048  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
36049  /* we couldn't create the proxy lock file with the old lock file path
36050  ** so try again via auto-naming
36051  */
36052  forceNewLockPath = 1;
36053  tryOldLockPath = 0;
36054  continue; /* go back to the do {} while start point, try again */
36055  }
36056  }
36057  if( rc==SQLITE_OK ){
36058  /* Need to make a copy of path if we extracted the value
36059  ** from the conch file or the path was allocated on the stack
36060  */
36061  if( tempLockPath ){
36062  pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
36063  if( !pCtx->lockProxyPath ){
36064  rc = SQLITE_NOMEM_BKPT;
36065  }
36066  }
36067  }
36068  if( rc==SQLITE_OK ){
36069  pCtx->conchHeld = 1;
36070 
36071  if( pCtx->lockProxy->pMethod == &afpIoMethods ){
36072  afpLockingContext *afpCtx;
36073  afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
36074  afpCtx->dbPath = pCtx->lockProxyPath;
36075  }
36076  } else {
36077  conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36078  }
36079  OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
36080  rc==SQLITE_OK?"ok":"failed"));
36081  return rc;
36082  } while (1); /* in case we need to retry the :auto: lock file -
36083  ** we should never get here except via the 'continue' call. */
36084  }
36085 }
36086 
36087 /*
36088 ** If pFile holds a lock on a conch file, then release that lock.
36089 */
36090 static int proxyReleaseConch(unixFile *pFile){
36091  int rc = SQLITE_OK; /* Subroutine return code */
36092  proxyLockingContext *pCtx; /* The locking context for the proxy lock */
36093  unixFile *conchFile; /* Name of the conch file */
36094 
36095  pCtx = (proxyLockingContext *)pFile->lockingContext;
36096  conchFile = pCtx->conchFile;
36097  OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
36098  (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
36099  osGetpid(0)));
36100  if( pCtx->conchHeld>0 ){
36101  rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
36102  }
36103  pCtx->conchHeld = 0;
36104  OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
36105  (rc==SQLITE_OK ? "ok" : "failed")));
36106  return rc;
36107 }
36108 
36109 /*
36110 ** Given the name of a database file, compute the name of its conch file.
36111 ** Store the conch filename in memory obtained from sqlite3_malloc64().
36112 ** Make *pConchPath point to the new name. Return SQLITE_OK on success
36113 ** or SQLITE_NOMEM if unable to obtain memory.
36114 **
36115 ** The caller is responsible for ensuring that the allocated memory
36116 ** space is eventually freed.
36117 **
36118 ** *pConchPath is set to NULL if a memory allocation error occurs.
36119 */
36120 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
36121  int i; /* Loop counter */
36122  int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
36123  char *conchPath; /* buffer in which to construct conch name */
36124 
36125  /* Allocate space for the conch filename and initialize the name to
36126  ** the name of the original database file. */
36127  *pConchPath = conchPath = (char *)sqlite3_malloc64(len + 8);
36128  if( conchPath==0 ){
36129  return SQLITE_NOMEM_BKPT;
36130  }
36131  memcpy(conchPath, dbPath, len+1);
36132 
36133  /* now insert a "." before the last / character */
36134  for( i=(len-1); i>=0; i-- ){
36135  if( conchPath[i]=='/' ){
36136  i++;
36137  break;
36138  }
36139  }
36140  conchPath[i]='.';
36141  while ( i<len ){
36142  conchPath[i+1]=dbPath[i];
36143  i++;
36144  }
36145 
36146  /* append the "-conch" suffix to the file */
36147  memcpy(&conchPath[i+1], "-conch", 7);
36148  assert( (int)strlen(conchPath) == len+7 );
36149 
36150  return SQLITE_OK;
36151 }
36152 
36153 
36154 /* Takes a fully configured proxy locking-style unix file and switches
36155 ** the local lock file path
36156 */
36157 static int switchLockProxyPath(unixFile *pFile, const char *path) {
36158  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36159  char *oldPath = pCtx->lockProxyPath;
36160  int rc = SQLITE_OK;
36161 
36162  if( pFile->eFileLock!=NO_LOCK ){
36163  return SQLITE_BUSY;
36164  }
36165 
36166  /* nothing to do if the path is NULL, :auto: or matches the existing path */
36167  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
36168  (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
36169  return SQLITE_OK;
36170  }else{
36171  unixFile *lockProxy = pCtx->lockProxy;
36172  pCtx->lockProxy=NULL;
36173  pCtx->conchHeld = 0;
36174  if( lockProxy!=NULL ){
36175  rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
36176  if( rc ) return rc;
36177  sqlite3_free(lockProxy);
36178  }
36179  sqlite3_free(oldPath);
36180  pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
36181  }
36182 
36183  return rc;
36184 }
36185 
36186 /*
36187 ** pFile is a file that has been opened by a prior xOpen call. dbPath
36188 ** is a string buffer at least MAXPATHLEN+1 characters in size.
36189 **
36190 ** This routine find the filename associated with pFile and writes it
36191 ** int dbPath.
36192 */
36193 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
36194 #if defined(__APPLE__)
36195  if( pFile->pMethod == &afpIoMethods ){
36196  /* afp style keeps a reference to the db path in the filePath field
36197  ** of the struct */
36198  assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36199  strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
36200  MAXPATHLEN);
36201  } else
36202 #endif
36203  if( pFile->pMethod == &dotlockIoMethods ){
36204  /* dot lock style uses the locking context to store the dot lock
36205  ** file path */
36206  int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
36207  memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
36208  }else{
36209  /* all other styles use the locking context to store the db file path */
36210  assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
36211  strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
36212  }
36213  return SQLITE_OK;
36214 }
36215 
36216 /*
36217 ** Takes an already filled in unix file and alters it so all file locking
36218 ** will be performed on the local proxy lock file. The following fields
36219 ** are preserved in the locking context so that they can be restored and
36220 ** the unix structure properly cleaned up at close time:
36221 ** ->lockingContext
36222 ** ->pMethod
36223 */
36224 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
36225  proxyLockingContext *pCtx;
36226  char dbPath[MAXPATHLEN+1]; /* Name of the database file */
36227  char *lockPath=NULL;
36228  int rc = SQLITE_OK;
36229 
36230  if( pFile->eFileLock!=NO_LOCK ){
36231  return SQLITE_BUSY;
36232  }
36233  proxyGetDbPathForUnixFile(pFile, dbPath);
36234  if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
36235  lockPath=NULL;
36236  }else{
36237  lockPath=(char *)path;
36238  }
36239 
36240  OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
36241  (lockPath ? lockPath : ":auto:"), osGetpid(0)));
36242 
36243  pCtx = sqlite3_malloc64( sizeof(*pCtx) );
36244  if( pCtx==0 ){
36245  return SQLITE_NOMEM_BKPT;
36246  }
36247  memset(pCtx, 0, sizeof(*pCtx));
36248 
36249  rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
36250  if( rc==SQLITE_OK ){
36251  rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
36252  if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
36253  /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
36254  ** (c) the file system is read-only, then enable no-locking access.
36255  ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
36256  ** that openFlags will have only one of O_RDONLY or O_RDWR.
36257  */
36258  struct statfs fsInfo;
36259  struct stat conchInfo;
36260  int goLockless = 0;
36261 
36262  if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
36263  int err = errno;
36264  if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
36265  goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
36266  }
36267  }
36268  if( goLockless ){
36269  pCtx->conchHeld = -1; /* read only FS/ lockless */
36270  rc = SQLITE_OK;
36271  }
36272  }
36273  }
36274  if( rc==SQLITE_OK && lockPath ){
36275  pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
36276  }
36277 
36278  if( rc==SQLITE_OK ){
36279  pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
36280  if( pCtx->dbPath==NULL ){
36281  rc = SQLITE_NOMEM_BKPT;
36282  }
36283  }
36284  if( rc==SQLITE_OK ){
36285  /* all memory is allocated, proxys are created and assigned,
36286  ** switch the locking context and pMethod then return.
36287  */
36288  pCtx->oldLockingContext = pFile->lockingContext;
36289  pFile->lockingContext = pCtx;
36290  pCtx->pOldMethod = pFile->pMethod;
36291  pFile->pMethod = &proxyIoMethods;
36292  }else{
36293  if( pCtx->conchFile ){
36294  pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
36295  sqlite3_free(pCtx->conchFile);
36296  }
36297  sqlite3DbFree(0, pCtx->lockProxyPath);
36298  sqlite3_free(pCtx->conchFilePath);
36299  sqlite3_free(pCtx);
36300  }
36301  OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
36302  (rc==SQLITE_OK ? "ok" : "failed")));
36303  return rc;
36304 }
36305 
36306 
36307 /*
36308 ** This routine handles sqlite3_file_control() calls that are specific
36309 ** to proxy locking.
36310 */
36311 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
36312  switch( op ){
36314  unixFile *pFile = (unixFile*)id;
36315  if( pFile->pMethod == &proxyIoMethods ){
36316  proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
36317  proxyTakeConch(pFile);
36318  if( pCtx->lockProxyPath ){
36319  *(const char **)pArg = pCtx->lockProxyPath;
36320  }else{
36321  *(const char **)pArg = ":auto: (not held)";
36322  }
36323  } else {
36324  *(const char **)pArg = NULL;
36325  }
36326  return SQLITE_OK;
36327  }
36329  unixFile *pFile = (unixFile*)id;
36330  int rc = SQLITE_OK;
36331  int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
36332  if( pArg==NULL || (const char *)pArg==0 ){
36333  if( isProxyStyle ){
36334  /* turn off proxy locking - not supported. If support is added for
36335  ** switching proxy locking mode off then it will need to fail if
36336  ** the journal mode is WAL mode.
36337  */
36338  rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
36339  }else{
36340  /* turn off proxy locking - already off - NOOP */
36341  rc = SQLITE_OK;
36342  }
36343  }else{
36344  const char *proxyPath = (const char *)pArg;
36345  if( isProxyStyle ){
36346  proxyLockingContext *pCtx =
36347  (proxyLockingContext*)pFile->lockingContext;
36348  if( !strcmp(pArg, ":auto:")
36349  || (pCtx->lockProxyPath &&
36350  !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
36351  ){
36352  rc = SQLITE_OK;
36353  }else{
36354  rc = switchLockProxyPath(pFile, proxyPath);
36355  }
36356  }else{
36357  /* turn on proxy file locking */
36358  rc = proxyTransformUnixFile(pFile, proxyPath);
36359  }
36360  }
36361  return rc;
36362  }
36363  default: {
36364  assert( 0 ); /* The call assures that only valid opcodes are sent */
36365  }
36366  }
36367  /*NOTREACHED*/
36368  return SQLITE_ERROR;
36369 }
36370 
36371 /*
36372 ** Within this division (the proxying locking implementation) the procedures
36373 ** above this point are all utilities. The lock-related methods of the
36374 ** proxy-locking sqlite3_io_method object follow.
36375 */
36376 
36377 
36378 /*
36379 ** This routine checks if there is a RESERVED lock held on the specified
36380 ** file by this or any other process. If such a lock is held, set *pResOut
36381 ** to a non-zero value otherwise *pResOut is set to zero. The return value
36382 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
36383 */
36384 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
36385  unixFile *pFile = (unixFile*)id;
36386  int rc = proxyTakeConch(pFile);
36387  if( rc==SQLITE_OK ){
36388  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36389  if( pCtx->conchHeld>0 ){
36390  unixFile *proxy = pCtx->lockProxy;
36391  return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
36392  }else{ /* conchHeld < 0 is lockless */
36393  pResOut=0;
36394  }
36395  }
36396  return rc;
36397 }
36398 
36399 /*
36400 ** Lock the file with the lock specified by parameter eFileLock - one
36401 ** of the following:
36402 **
36403 ** (1) SHARED_LOCK
36404 ** (2) RESERVED_LOCK
36405 ** (3) PENDING_LOCK
36406 ** (4) EXCLUSIVE_LOCK
36407 **
36408 ** Sometimes when requesting one lock state, additional lock states
36409 ** are inserted in between. The locking might fail on one of the later
36410 ** transitions leaving the lock state different from what it started but
36411 ** still short of its goal. The following chart shows the allowed
36412 ** transitions and the inserted intermediate states:
36413 **
36414 ** UNLOCKED -> SHARED
36415 ** SHARED -> RESERVED
36416 ** SHARED -> (PENDING) -> EXCLUSIVE
36417 ** RESERVED -> (PENDING) -> EXCLUSIVE
36418 ** PENDING -> EXCLUSIVE
36419 **
36420 ** This routine will only increase a lock. Use the sqlite3OsUnlock()
36421 ** routine to lower a locking level.
36422 */
36423 static int proxyLock(sqlite3_file *id, int eFileLock) {
36424  unixFile *pFile = (unixFile*)id;
36425  int rc = proxyTakeConch(pFile);
36426  if( rc==SQLITE_OK ){
36427  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36428  if( pCtx->conchHeld>0 ){
36429  unixFile *proxy = pCtx->lockProxy;
36430  rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
36431  pFile->eFileLock = proxy->eFileLock;
36432  }else{
36433  /* conchHeld < 0 is lockless */
36434  }
36435  }
36436  return rc;
36437 }
36438 
36439 
36440 /*
36441 ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
36442 ** must be either NO_LOCK or SHARED_LOCK.
36443 **
36444 ** If the locking level of the file descriptor is already at or below
36445 ** the requested locking level, this routine is a no-op.
36446 */
36447 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
36448  unixFile *pFile = (unixFile*)id;
36449  int rc = proxyTakeConch(pFile);
36450  if( rc==SQLITE_OK ){
36451  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36452  if( pCtx->conchHeld>0 ){
36453  unixFile *proxy = pCtx->lockProxy;
36454  rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
36455  pFile->eFileLock = proxy->eFileLock;
36456  }else{
36457  /* conchHeld < 0 is lockless */
36458  }
36459  }
36460  return rc;
36461 }
36462 
36463 /*
36464 ** Close a file that uses proxy locks.
36465 */
36466 static int proxyClose(sqlite3_file *id) {
36467  if( ALWAYS(id) ){
36468  unixFile *pFile = (unixFile*)id;
36469  proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
36470  unixFile *lockProxy = pCtx->lockProxy;
36471  unixFile *conchFile = pCtx->conchFile;
36472  int rc = SQLITE_OK;
36473 
36474  if( lockProxy ){
36475  rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
36476  if( rc ) return rc;
36477  rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
36478  if( rc ) return rc;
36479  sqlite3_free(lockProxy);
36480  pCtx->lockProxy = 0;
36481  }
36482  if( conchFile ){
36483  if( pCtx->conchHeld ){
36484  rc = proxyReleaseConch(pFile);
36485  if( rc ) return rc;
36486  }
36487  rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
36488  if( rc ) return rc;
36489  sqlite3_free(conchFile);
36490  }
36491  sqlite3DbFree(0, pCtx->lockProxyPath);
36492  sqlite3_free(pCtx->conchFilePath);
36493  sqlite3DbFree(0, pCtx->dbPath);
36494  /* restore the original locking context and pMethod then close it */
36495  pFile->lockingContext = pCtx->oldLockingContext;
36496  pFile->pMethod = pCtx->pOldMethod;
36497  sqlite3_free(pCtx);
36498  return pFile->pMethod->xClose(id);
36499  }
36500  return SQLITE_OK;
36501 }
36502 
36503 
36504 
36505 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
36506 /*
36507 ** The proxy locking style is intended for use with AFP filesystems.
36508 ** And since AFP is only supported on MacOSX, the proxy locking is also
36509 ** restricted to MacOSX.
36510 **
36511 **
36512 ******************* End of the proxy lock implementation **********************
36513 ******************************************************************************/
36514 
36515 /*
36516 ** Initialize the operating system interface.
36517 **
36518 ** This routine registers all VFS implementations for unix-like operating
36519 ** systems. This routine, and the sqlite3_os_end() routine that follows,
36520 ** should be the only routines in this file that are visible from other
36521 ** files.
36522 **
36523 ** This routine is called once during SQLite initialization and by a
36524 ** single thread. The memory allocation and mutex subsystems have not
36525 ** necessarily been initialized when this routine is called, and so they
36526 ** should not be used.
36527 */
36529  /*
36530  ** The following macro defines an initializer for an sqlite3_vfs object.
36531  ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
36532  ** to the "finder" function. (pAppData is a pointer to a pointer because
36533  ** silly C90 rules prohibit a void* from being cast to a function pointer
36534  ** and so we have to go through the intermediate pointer to avoid problems
36535  ** when compiling with -pedantic-errors on GCC.)
36536  **
36537  ** The FINDER parameter to this macro is the name of the pointer to the
36538  ** finder-function. The finder-function returns a pointer to the
36539  ** sqlite_io_methods object that implements the desired locking
36540  ** behaviors. See the division above that contains the IOMETHODS
36541  ** macro for addition information on finder-functions.
36542  **
36543  ** Most finders simply return a pointer to a fixed sqlite3_io_methods
36544  ** object. But the "autolockIoFinder" available on MacOSX does a little
36545  ** more than that; it looks at the filesystem type that hosts the
36546  ** database file and tries to choose an locking method appropriate for
36547  ** that filesystem time.
36548  */
36549  #define UNIXVFS(VFSNAME, FINDER) { \
36550  3, /* iVersion */ \
36551  sizeof(unixFile), /* szOsFile */ \
36552  MAX_PATHNAME, /* mxPathname */ \
36553  0, /* pNext */ \
36554  VFSNAME, /* zName */ \
36555  (void*)&FINDER, /* pAppData */ \
36556  unixOpen, /* xOpen */ \
36557  unixDelete, /* xDelete */ \
36558  unixAccess, /* xAccess */ \
36559  unixFullPathname, /* xFullPathname */ \
36560  unixDlOpen, /* xDlOpen */ \
36561  unixDlError, /* xDlError */ \
36562  unixDlSym, /* xDlSym */ \
36563  unixDlClose, /* xDlClose */ \
36564  unixRandomness, /* xRandomness */ \
36565  unixSleep, /* xSleep */ \
36566  unixCurrentTime, /* xCurrentTime */ \
36567  unixGetLastError, /* xGetLastError */ \
36568  unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
36569  unixSetSystemCall, /* xSetSystemCall */ \
36570  unixGetSystemCall, /* xGetSystemCall */ \
36571  unixNextSystemCall, /* xNextSystemCall */ \
36572  }
36573 
36574  /*
36575  ** All default VFSes for unix are contained in the following array.
36576  **
36577  ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
36578  ** by the SQLite core when the VFS is registered. So the following
36579  ** array cannot be const.
36580  */
36581  static sqlite3_vfs aVfs[] = {
36582 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36583  UNIXVFS("unix", autolockIoFinder ),
36584 #elif OS_VXWORKS
36585  UNIXVFS("unix", vxworksIoFinder ),
36586 #else
36587  UNIXVFS("unix", posixIoFinder ),
36588 #endif
36589  UNIXVFS("unix-none", nolockIoFinder ),
36590  UNIXVFS("unix-dotfile", dotlockIoFinder ),
36591  UNIXVFS("unix-excl", posixIoFinder ),
36592 #if OS_VXWORKS
36593  UNIXVFS("unix-namedsem", semIoFinder ),
36594 #endif
36595 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
36596  UNIXVFS("unix-posix", posixIoFinder ),
36597 #endif
36598 #if SQLITE_ENABLE_LOCKING_STYLE
36599  UNIXVFS("unix-flock", flockIoFinder ),
36600 #endif
36601 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
36602  UNIXVFS("unix-afp", afpIoFinder ),
36603  UNIXVFS("unix-nfs", nfsIoFinder ),
36604  UNIXVFS("unix-proxy", proxyIoFinder ),
36605 #endif
36606  };
36607  unsigned int i; /* Loop counter */
36608 
36609  /* Double-check that the aSyscall[] array has been constructed
36610  ** correctly. See ticket [bb3a86e890c8e96ab] */
36611  assert( ArraySize(aSyscall)==28 );
36612 
36613  /* Register all VFSes defined in the aVfs[] array */
36614  for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
36615  sqlite3_vfs_register(&aVfs[i], i==0);
36616  }
36617  return SQLITE_OK;
36618 }
36619 
36620 /*
36621 ** Shutdown the operating system interface.
36622 **
36623 ** Some operating systems might need to do some cleanup in this routine,
36624 ** to release dynamically allocated objects. But not on unix.
36625 ** This routine is a no-op for unix.
36626 */
36628  return SQLITE_OK;
36629 }
36630 
36631 #endif /* SQLITE_OS_UNIX */
36632 
36633 /************** End of os_unix.c *********************************************/
36634 /************** Begin file os_win.c ******************************************/
36635 /*
36636 ** 2004 May 22
36637 **
36638 ** The author disclaims copyright to this source code. In place of
36639 ** a legal notice, here is a blessing:
36640 **
36641 ** May you do good and not evil.
36642 ** May you find forgiveness for yourself and forgive others.
36643 ** May you share freely, never taking more than you give.
36644 **
36645 ******************************************************************************
36646 **
36647 ** This file contains code that is specific to Windows.
36648 */
36649 /* #include "sqliteInt.h" */
36650 #if SQLITE_OS_WIN /* This file is used for Windows only */
36651 
36652 /*
36653 ** Include code that is common to all os_*.c files
36654 */
36655 /************** Include os_common.h in the middle of os_win.c ****************/
36656 /************** Begin file os_common.h ***************************************/
36657 /*
36658 ** 2004 May 22
36659 **
36660 ** The author disclaims copyright to this source code. In place of
36661 ** a legal notice, here is a blessing:
36662 **
36663 ** May you do good and not evil.
36664 ** May you find forgiveness for yourself and forgive others.
36665 ** May you share freely, never taking more than you give.
36666 **
36667 ******************************************************************************
36668 **
36669 ** This file contains macros and a little bit of code that is common to
36670 ** all of the platform-specific files (os_*.c) and is #included into those
36671 ** files.
36672 **
36673 ** This file should be #included by the os_*.c files only. It is not a
36674 ** general purpose header file.
36675 */
36676 #ifndef _OS_COMMON_H_
36677 #define _OS_COMMON_H_
36678 
36679 /*
36680 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
36681 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
36682 ** switch. The following code should catch this problem at compile-time.
36683 */
36684 #ifdef MEMORY_DEBUG
36685 # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
36686 #endif
36687 
36688 /*
36689 ** Macros for performance tracing. Normally turned off. Only works
36690 ** on i486 hardware.
36691 */
36692 #ifdef SQLITE_PERFORMANCE_TRACE
36693 
36694 /*
36695 ** hwtime.h contains inline assembler code for implementing
36696 ** high-performance timing routines.
36697 */
36698 /************** Include hwtime.h in the middle of os_common.h ****************/
36699 /************** Begin file hwtime.h ******************************************/
36700 /*
36701 ** 2008 May 27
36702 **
36703 ** The author disclaims copyright to this source code. In place of
36704 ** a legal notice, here is a blessing:
36705 **
36706 ** May you do good and not evil.
36707 ** May you find forgiveness for yourself and forgive others.
36708 ** May you share freely, never taking more than you give.
36709 **
36710 ******************************************************************************
36711 **
36712 ** This file contains inline asm code for retrieving "high-performance"
36713 ** counters for x86 class CPUs.
36714 */
36715 #ifndef _HWTIME_H_
36716 #define _HWTIME_H_
36717 
36718 /*
36719 ** The following routine only works on pentium-class (or newer) processors.
36720 ** It uses the RDTSC opcode to read the cycle count value out of the
36721 ** processor and returns that value. This can be used for high-res
36722 ** profiling.
36723 */
36724 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
36725  (defined(i386) || defined(__i386__) || defined(_M_IX86))
36726 
36727  #if defined(__GNUC__)
36728 
36729  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36730  unsigned int lo, hi;
36731  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
36732  return (sqlite_uint64)hi << 32 | lo;
36733  }
36734 
36735  #elif defined(_MSC_VER)
36736 
36737  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
36738  __asm {
36739  rdtsc
36740  ret ; return value at EDX:EAX
36741  }
36742  }
36743 
36744  #endif
36745 
36746 #elif (defined(__GNUC__) && defined(__x86_64__))
36747 
36748  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36749  unsigned long val;
36750  __asm__ __volatile__ ("rdtsc" : "=A" (val));
36751  return val;
36752  }
36753 
36754 #elif (defined(__GNUC__) && defined(__ppc__))
36755 
36756  __inline__ sqlite_uint64 sqlite3Hwtime(void){
36757  unsigned long long retval;
36758  unsigned long junk;
36759  __asm__ __volatile__ ("\n\
36760  1: mftbu %1\n\
36761  mftb %L0\n\
36762  mftbu %0\n\
36763  cmpw %0,%1\n\
36764  bne 1b"
36765  : "=r" (retval), "=r" (junk));
36766  return retval;
36767  }
36768 
36769 #else
36770 
36771  #error Need implementation of sqlite3Hwtime() for your platform.
36772 
36773  /*
36774  ** To compile without implementing sqlite3Hwtime() for your platform,
36775  ** you can remove the above #error and use the following
36776  ** stub function. You will lose timing support for many
36777  ** of the debugging and testing utilities, but it should at
36778  ** least compile and run.
36779  */
36780 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
36781 
36782 #endif
36783 
36784 #endif /* !defined(_HWTIME_H_) */
36785 
36786 /************** End of hwtime.h **********************************************/
36787 /************** Continuing where we left off in os_common.h ******************/
36788 
36789 static sqlite_uint64 g_start;
36790 static sqlite_uint64 g_elapsed;
36791 #define TIMER_START g_start=sqlite3Hwtime()
36792 #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
36793 #define TIMER_ELAPSED g_elapsed
36794 #else
36795 #define TIMER_START
36796 #define TIMER_END
36797 #define TIMER_ELAPSED ((sqlite_uint64)0)
36798 #endif
36799 
36800 /*
36801 ** If we compile with the SQLITE_TEST macro set, then the following block
36802 ** of code will give us the ability to simulate a disk I/O error. This
36803 ** is used for testing the I/O recovery logic.
36804 */
36805 #if defined(SQLITE_TEST)
36806 SQLITE_API extern int sqlite3_io_error_hit;
36807 SQLITE_API extern int sqlite3_io_error_hardhit;
36808 SQLITE_API extern int sqlite3_io_error_pending;
36809 SQLITE_API extern int sqlite3_io_error_persist;
36810 SQLITE_API extern int sqlite3_io_error_benign;
36811 SQLITE_API extern int sqlite3_diskfull_pending;
36812 SQLITE_API extern int sqlite3_diskfull;
36813 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
36814 #define SimulateIOError(CODE) \
36815  if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
36816  || sqlite3_io_error_pending-- == 1 ) \
36817  { local_ioerr(); CODE; }
36818 static void local_ioerr(){
36819  IOTRACE(("IOERR\n"));
36820  sqlite3_io_error_hit++;
36821  if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
36822 }
36823 #define SimulateDiskfullError(CODE) \
36824  if( sqlite3_diskfull_pending ){ \
36825  if( sqlite3_diskfull_pending == 1 ){ \
36826  local_ioerr(); \
36827  sqlite3_diskfull = 1; \
36828  sqlite3_io_error_hit = 1; \
36829  CODE; \
36830  }else{ \
36831  sqlite3_diskfull_pending--; \
36832  } \
36833  }
36834 #else
36835 #define SimulateIOErrorBenign(X)
36836 #define SimulateIOError(A)
36837 #define SimulateDiskfullError(A)
36838 #endif /* defined(SQLITE_TEST) */
36839 
36840 /*
36841 ** When testing, keep a count of the number of open files.
36842 */
36843 #if defined(SQLITE_TEST)
36844 SQLITE_API extern int sqlite3_open_file_count;
36845 #define OpenCounter(X) sqlite3_open_file_count+=(X)
36846 #else
36847 #define OpenCounter(X)
36848 #endif /* defined(SQLITE_TEST) */
36849 
36850 #endif /* !defined(_OS_COMMON_H_) */
36851 
36852 /************** End of os_common.h *******************************************/
36853 /************** Continuing where we left off in os_win.c *********************/
36854 
36855 /*
36856 ** Include the header file for the Windows VFS.
36857 */
36858 /* #include "os_win.h" */
36859 
36860 /*
36861 ** Compiling and using WAL mode requires several APIs that are only
36862 ** available in Windows platforms based on the NT kernel.
36863 */
36864 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
36865 # error "WAL mode requires support from the Windows NT kernel, compile\
36866  with SQLITE_OMIT_WAL."
36867 #endif
36868 
36869 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
36870 # error "Memory mapped files require support from the Windows NT kernel,\
36871  compile with SQLITE_MAX_MMAP_SIZE=0."
36872 #endif
36873 
36874 /*
36875 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
36876 ** based on the sub-platform)?
36877 */
36878 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
36879 # define SQLITE_WIN32_HAS_ANSI
36880 #endif
36881 
36882 /*
36883 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
36884 ** based on the sub-platform)?
36885 */
36886 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
36887  !defined(SQLITE_WIN32_NO_WIDE)
36888 # define SQLITE_WIN32_HAS_WIDE
36889 #endif
36890 
36891 /*
36892 ** Make sure at least one set of Win32 APIs is available.
36893 */
36894 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
36895 # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
36896  must be defined."
36897 #endif
36898 
36899 /*
36900 ** Define the required Windows SDK version constants if they are not
36901 ** already available.
36902 */
36903 #ifndef NTDDI_WIN8
36904 # define NTDDI_WIN8 0x06020000
36905 #endif
36906 
36907 #ifndef NTDDI_WINBLUE
36908 # define NTDDI_WINBLUE 0x06030000
36909 #endif
36910 
36911 #ifndef NTDDI_WINTHRESHOLD
36912 # define NTDDI_WINTHRESHOLD 0x06040000
36913 #endif
36914 
36915 /*
36916 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
36917 ** target system. GetVersionEx was first deprecated in Win8.1.
36918 */
36919 #ifndef SQLITE_WIN32_GETVERSIONEX
36920 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
36921 # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
36922 # else
36923 # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
36924 # endif
36925 #endif
36926 
36927 /*
36928 ** Check to see if the CreateFileMappingA function is supported on the
36929 ** target system. It is unavailable when using "mincore.lib" on Win10.
36930 ** When compiling for Windows 10, always assume "mincore.lib" is in use.
36931 */
36932 #ifndef SQLITE_WIN32_CREATEFILEMAPPINGA
36933 # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINTHRESHOLD
36934 # define SQLITE_WIN32_CREATEFILEMAPPINGA 0
36935 # else
36936 # define SQLITE_WIN32_CREATEFILEMAPPINGA 1
36937 # endif
36938 #endif
36939 
36940 /*
36941 ** This constant should already be defined (in the "WinDef.h" SDK file).
36942 */
36943 #ifndef MAX_PATH
36944 # define MAX_PATH (260)
36945 #endif
36946 
36947 /*
36948 ** Maximum pathname length (in chars) for Win32. This should normally be
36949 ** MAX_PATH.
36950 */
36951 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
36952 # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
36953 #endif
36954 
36955 /*
36956 ** This constant should already be defined (in the "WinNT.h" SDK file).
36957 */
36958 #ifndef UNICODE_STRING_MAX_CHARS
36959 # define UNICODE_STRING_MAX_CHARS (32767)
36960 #endif
36961 
36962 /*
36963 ** Maximum pathname length (in chars) for WinNT. This should normally be
36964 ** UNICODE_STRING_MAX_CHARS.
36965 */
36966 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
36967 # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
36968 #endif
36969 
36970 /*
36971 ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
36972 ** characters, so we allocate 4 bytes per character assuming worst-case of
36973 ** 4-bytes-per-character for UTF8.
36974 */
36975 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
36976 # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
36977 #endif
36978 
36979 /*
36980 ** Maximum pathname length (in bytes) for WinNT. This should normally be
36981 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
36982 */
36983 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
36984 # define SQLITE_WINNT_MAX_PATH_BYTES \
36985  (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
36986 #endif
36987 
36988 /*
36989 ** Maximum error message length (in chars) for WinRT.
36990 */
36991 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
36992 # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
36993 #endif
36994 
36995 /*
36996 ** Returns non-zero if the character should be treated as a directory
36997 ** separator.
36998 */
36999 #ifndef winIsDirSep
37000 # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
37001 #endif
37002 
37003 /*
37004 ** This macro is used when a local variable is set to a value that is
37005 ** [sometimes] not used by the code (e.g. via conditional compilation).
37006 */
37007 #ifndef UNUSED_VARIABLE_VALUE
37008 # define UNUSED_VARIABLE_VALUE(x) (void)(x)
37009 #endif
37010 
37011 /*
37012 ** Returns the character that should be used as the directory separator.
37013 */
37014 #ifndef winGetDirSep
37015 # define winGetDirSep() '\\'
37016 #endif
37017 
37018 /*
37019 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
37020 ** mode or memory mapped files (e.g. these APIs are available in the Windows
37021 ** CE SDK; however, they are not present in the header file)?
37022 */
37023 #if SQLITE_WIN32_FILEMAPPING_API && \
37024  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37025 /*
37026 ** Two of the file mapping APIs are different under WinRT. Figure out which
37027 ** set we need.
37028 */
37029 #if SQLITE_OS_WINRT
37030 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
37031  LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
37032 
37033 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
37034 #else
37035 #if defined(SQLITE_WIN32_HAS_ANSI)
37036 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
37037  DWORD, DWORD, DWORD, LPCSTR);
37038 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
37039 
37040 #if defined(SQLITE_WIN32_HAS_WIDE)
37041 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
37042  DWORD, DWORD, DWORD, LPCWSTR);
37043 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
37044 
37045 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
37046 #endif /* SQLITE_OS_WINRT */
37047 
37048 /*
37049 ** These file mapping APIs are common to both Win32 and WinRT.
37050 */
37051 
37052 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
37053 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
37054 #endif /* SQLITE_WIN32_FILEMAPPING_API */
37055 
37056 /*
37057 ** Some Microsoft compilers lack this definition.
37058 */
37059 #ifndef INVALID_FILE_ATTRIBUTES
37060 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
37061 #endif
37062 
37063 #ifndef FILE_FLAG_MASK
37064 # define FILE_FLAG_MASK (0xFF3C0000)
37065 #endif
37066 
37067 #ifndef FILE_ATTRIBUTE_MASK
37068 # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
37069 #endif
37070 
37071 #ifndef SQLITE_OMIT_WAL
37072 /* Forward references to structures used for WAL */
37073 typedef struct winShm winShm; /* A connection to shared-memory */
37074 typedef struct winShmNode winShmNode; /* A region of shared-memory */
37075 #endif
37076 
37077 /*
37078 ** WinCE lacks native support for file locking so we have to fake it
37079 ** with some code of our own.
37080 */
37081 #if SQLITE_OS_WINCE
37082 typedef struct winceLock {
37083  int nReaders; /* Number of reader locks obtained */
37084  BOOL bPending; /* Indicates a pending lock has been obtained */
37085  BOOL bReserved; /* Indicates a reserved lock has been obtained */
37086  BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
37087 } winceLock;
37088 #endif
37089 
37090 /*
37091 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
37092 ** portability layer.
37093 */
37094 typedef struct winFile winFile;
37095 struct winFile {
37096  const sqlite3_io_methods *pMethod; /*** Must be first ***/
37097  sqlite3_vfs *pVfs; /* The VFS used to open this file */
37098  HANDLE h; /* Handle for accessing the file */
37099  u8 locktype; /* Type of lock currently held on this file */
37100  short sharedLockByte; /* Randomly chosen byte used as a shared lock */
37101  u8 ctrlFlags; /* Flags. See WINFILE_* below */
37102  DWORD lastErrno; /* The Windows errno from the last I/O error */
37103 #ifndef SQLITE_OMIT_WAL
37104  winShm *pShm; /* Instance of shared memory on this file */
37105 #endif
37106  const char *zPath; /* Full pathname of this file */
37107  int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
37108 #if SQLITE_OS_WINCE
37109  LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
37110  HANDLE hMutex; /* Mutex used to control access to shared lock */
37111  HANDLE hShared; /* Shared memory segment used for locking */
37112  winceLock local; /* Locks obtained by this instance of winFile */
37113  winceLock *shared; /* Global shared lock memory for the file */
37114 #endif
37115 #if SQLITE_MAX_MMAP_SIZE>0
37116  int nFetchOut; /* Number of outstanding xFetch references */
37117  HANDLE hMap; /* Handle for accessing memory mapping */
37118  void *pMapRegion; /* Area memory mapped */
37119  sqlite3_int64 mmapSize; /* Usable size of mapped region */
37120  sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
37121  sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
37122 #endif
37123 };
37124 
37125 /*
37126 ** Allowed values for winFile.ctrlFlags
37127 */
37128 #define WINFILE_RDONLY 0x02 /* Connection is read only */
37129 #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
37130 #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
37131 
37132 /*
37133  * The size of the buffer used by sqlite3_win32_write_debug().
37134  */
37135 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
37136 # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
37137 #endif
37138 
37139 /*
37140  * The value used with sqlite3_win32_set_directory() to specify that
37141  * the data directory should be changed.
37142  */
37143 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
37144 # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
37145 #endif
37146 
37147 /*
37148  * The value used with sqlite3_win32_set_directory() to specify that
37149  * the temporary directory should be changed.
37150  */
37151 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
37152 # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
37153 #endif
37154 
37155 /*
37156  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
37157  * various Win32 API heap functions instead of our own.
37158  */
37159 #ifdef SQLITE_WIN32_MALLOC
37160 
37161 /*
37162  * If this is non-zero, an isolated heap will be created by the native Win32
37163  * allocator subsystem; otherwise, the default process heap will be used. This
37164  * setting has no effect when compiling for WinRT. By default, this is enabled
37165  * and an isolated heap will be created to store all allocated data.
37166  *
37167  ******************************************************************************
37168  * WARNING: It is important to note that when this setting is non-zero and the
37169  * winMemShutdown function is called (e.g. by the sqlite3_shutdown
37170  * function), all data that was allocated using the isolated heap will
37171  * be freed immediately and any attempt to access any of that freed
37172  * data will almost certainly result in an immediate access violation.
37173  ******************************************************************************
37174  */
37175 #ifndef SQLITE_WIN32_HEAP_CREATE
37176 # define SQLITE_WIN32_HEAP_CREATE (TRUE)
37177 #endif
37178 
37179 /*
37180  * This is cache size used in the calculation of the initial size of the
37181  * Win32-specific heap. It cannot be negative.
37182  */
37183 #ifndef SQLITE_WIN32_CACHE_SIZE
37184 # if SQLITE_DEFAULT_CACHE_SIZE>=0
37185 # define SQLITE_WIN32_CACHE_SIZE (SQLITE_DEFAULT_CACHE_SIZE)
37186 # else
37187 # define SQLITE_WIN32_CACHE_SIZE (-(SQLITE_DEFAULT_CACHE_SIZE))
37188 # endif
37189 #endif
37190 
37191 /*
37192  * The initial size of the Win32-specific heap. This value may be zero.
37193  */
37194 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
37195 # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_WIN32_CACHE_SIZE) * \
37196  (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
37197 #endif
37198 
37199 /*
37200  * The maximum size of the Win32-specific heap. This value may be zero.
37201  */
37202 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
37203 # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
37204 #endif
37205 
37206 /*
37207  * The extra flags to use in calls to the Win32 heap APIs. This value may be
37208  * zero for the default behavior.
37209  */
37210 #ifndef SQLITE_WIN32_HEAP_FLAGS
37211 # define SQLITE_WIN32_HEAP_FLAGS (0)
37212 #endif
37213 
37214 
37215 /*
37216 ** The winMemData structure stores information required by the Win32-specific
37217 ** sqlite3_mem_methods implementation.
37218 */
37219 typedef struct winMemData winMemData;
37220 struct winMemData {
37221 #ifndef NDEBUG
37222  u32 magic1; /* Magic number to detect structure corruption. */
37223 #endif
37224  HANDLE hHeap; /* The handle to our heap. */
37225  BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
37226 #ifndef NDEBUG
37227  u32 magic2; /* Magic number to detect structure corruption. */
37228 #endif
37229 };
37230 
37231 #ifndef NDEBUG
37232 #define WINMEM_MAGIC1 0x42b2830b
37233 #define WINMEM_MAGIC2 0xbd4d7cf4
37234 #endif
37235 
37236 static struct winMemData win_mem_data = {
37237 #ifndef NDEBUG
37238  WINMEM_MAGIC1,
37239 #endif
37240  NULL, FALSE
37241 #ifndef NDEBUG
37242  ,WINMEM_MAGIC2
37243 #endif
37244 };
37245 
37246 #ifndef NDEBUG
37247 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
37248 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
37249 #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
37250 #else
37251 #define winMemAssertMagic()
37252 #endif
37253 
37254 #define winMemGetDataPtr() &win_mem_data
37255 #define winMemGetHeap() win_mem_data.hHeap
37256 #define winMemGetOwned() win_mem_data.bOwned
37257 
37258 static void *winMemMalloc(int nBytes);
37259 static void winMemFree(void *pPrior);
37260 static void *winMemRealloc(void *pPrior, int nBytes);
37261 static int winMemSize(void *p);
37262 static int winMemRoundup(int n);
37263 static int winMemInit(void *pAppData);
37264 static void winMemShutdown(void *pAppData);
37265 
37266 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
37267 #endif /* SQLITE_WIN32_MALLOC */
37268 
37269 /*
37270 ** The following variable is (normally) set once and never changes
37271 ** thereafter. It records whether the operating system is Win9x
37272 ** or WinNT.
37273 **
37274 ** 0: Operating system unknown.
37275 ** 1: Operating system is Win9x.
37276 ** 2: Operating system is WinNT.
37277 **
37278 ** In order to facilitate testing on a WinNT system, the test fixture
37279 ** can manually set this value to 1 to emulate Win98 behavior.
37280 */
37281 #ifdef SQLITE_TEST
37282 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37283 #else
37284 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
37285 #endif
37286 
37287 #ifndef SYSCALL
37288 # define SYSCALL sqlite3_syscall_ptr
37289 #endif
37290 
37291 /*
37292 ** This function is not available on Windows CE or WinRT.
37293  */
37294 
37295 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
37296 # define osAreFileApisANSI() 1
37297 #endif
37298 
37299 /*
37300 ** Many system calls are accessed through pointer-to-functions so that
37301 ** they may be overridden at runtime to facilitate fault injection during
37302 ** testing and sandboxing. The following array holds the names and pointers
37303 ** to all overrideable system calls.
37304 */
37305 static struct win_syscall {
37306  const char *zName; /* Name of the system call */
37307  sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
37308  sqlite3_syscall_ptr pDefault; /* Default value */
37309 } aSyscall[] = {
37310 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37311  { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
37312 #else
37313  { "AreFileApisANSI", (SYSCALL)0, 0 },
37314 #endif
37315 
37316 #ifndef osAreFileApisANSI
37317 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
37318 #endif
37319 
37320 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37321  { "CharLowerW", (SYSCALL)CharLowerW, 0 },
37322 #else
37323  { "CharLowerW", (SYSCALL)0, 0 },
37324 #endif
37325 
37326 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
37327 
37328 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
37329  { "CharUpperW", (SYSCALL)CharUpperW, 0 },
37330 #else
37331  { "CharUpperW", (SYSCALL)0, 0 },
37332 #endif
37333 
37334 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
37335 
37336  { "CloseHandle", (SYSCALL)CloseHandle, 0 },
37337 
37338 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
37339 
37340 #if defined(SQLITE_WIN32_HAS_ANSI)
37341  { "CreateFileA", (SYSCALL)CreateFileA, 0 },
37342 #else
37343  { "CreateFileA", (SYSCALL)0, 0 },
37344 #endif
37345 
37346 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
37347  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
37348 
37349 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37350  { "CreateFileW", (SYSCALL)CreateFileW, 0 },
37351 #else
37352  { "CreateFileW", (SYSCALL)0, 0 },
37353 #endif
37354 
37355 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
37356  LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
37357 
37358 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
37359  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0) && \
37360  SQLITE_WIN32_CREATEFILEMAPPINGA
37361  { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
37362 #else
37363  { "CreateFileMappingA", (SYSCALL)0, 0 },
37364 #endif
37365 
37366 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37367  DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
37368 
37369 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37370  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37371  { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
37372 #else
37373  { "CreateFileMappingW", (SYSCALL)0, 0 },
37374 #endif
37375 
37376 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
37377  DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
37378 
37379 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37380  { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
37381 #else
37382  { "CreateMutexW", (SYSCALL)0, 0 },
37383 #endif
37384 
37385 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
37386  LPCWSTR))aSyscall[8].pCurrent)
37387 
37388 #if defined(SQLITE_WIN32_HAS_ANSI)
37389  { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
37390 #else
37391  { "DeleteFileA", (SYSCALL)0, 0 },
37392 #endif
37393 
37394 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
37395 
37396 #if defined(SQLITE_WIN32_HAS_WIDE)
37397  { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
37398 #else
37399  { "DeleteFileW", (SYSCALL)0, 0 },
37400 #endif
37401 
37402 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
37403 
37404 #if SQLITE_OS_WINCE
37405  { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
37406 #else
37407  { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
37408 #endif
37409 
37410 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37411  LPFILETIME))aSyscall[11].pCurrent)
37412 
37413 #if SQLITE_OS_WINCE
37414  { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
37415 #else
37416  { "FileTimeToSystemTime", (SYSCALL)0, 0 },
37417 #endif
37418 
37419 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
37420  LPSYSTEMTIME))aSyscall[12].pCurrent)
37421 
37422  { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
37423 
37424 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
37425 
37426 #if defined(SQLITE_WIN32_HAS_ANSI)
37427  { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
37428 #else
37429  { "FormatMessageA", (SYSCALL)0, 0 },
37430 #endif
37431 
37432 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
37433  DWORD,va_list*))aSyscall[14].pCurrent)
37434 
37435 #if defined(SQLITE_WIN32_HAS_WIDE)
37436  { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
37437 #else
37438  { "FormatMessageW", (SYSCALL)0, 0 },
37439 #endif
37440 
37441 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
37442  DWORD,va_list*))aSyscall[15].pCurrent)
37443 
37444 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37445  { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
37446 #else
37447  { "FreeLibrary", (SYSCALL)0, 0 },
37448 #endif
37449 
37450 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
37451 
37452  { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
37453 
37454 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
37455 
37456 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37457  { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
37458 #else
37459  { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
37460 #endif
37461 
37462 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
37463  LPDWORD))aSyscall[18].pCurrent)
37464 
37465 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37466  { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
37467 #else
37468  { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
37469 #endif
37470 
37471 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
37472  LPDWORD))aSyscall[19].pCurrent)
37473 
37474 #if defined(SQLITE_WIN32_HAS_ANSI)
37475  { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
37476 #else
37477  { "GetFileAttributesA", (SYSCALL)0, 0 },
37478 #endif
37479 
37480 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
37481 
37482 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37483  { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
37484 #else
37485  { "GetFileAttributesW", (SYSCALL)0, 0 },
37486 #endif
37487 
37488 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
37489 
37490 #if defined(SQLITE_WIN32_HAS_WIDE)
37491  { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
37492 #else
37493  { "GetFileAttributesExW", (SYSCALL)0, 0 },
37494 #endif
37495 
37496 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
37497  LPVOID))aSyscall[22].pCurrent)
37498 
37499 #if !SQLITE_OS_WINRT
37500  { "GetFileSize", (SYSCALL)GetFileSize, 0 },
37501 #else
37502  { "GetFileSize", (SYSCALL)0, 0 },
37503 #endif
37504 
37505 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
37506 
37507 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
37508  { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
37509 #else
37510  { "GetFullPathNameA", (SYSCALL)0, 0 },
37511 #endif
37512 
37513 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
37514  LPSTR*))aSyscall[24].pCurrent)
37515 
37516 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37517  { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
37518 #else
37519  { "GetFullPathNameW", (SYSCALL)0, 0 },
37520 #endif
37521 
37522 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
37523  LPWSTR*))aSyscall[25].pCurrent)
37524 
37525  { "GetLastError", (SYSCALL)GetLastError, 0 },
37526 
37527 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
37528 
37529 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
37530 #if SQLITE_OS_WINCE
37531  /* The GetProcAddressA() routine is only available on Windows CE. */
37532  { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
37533 #else
37534  /* All other Windows platforms expect GetProcAddress() to take
37535  ** an ANSI string regardless of the _UNICODE setting */
37536  { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
37537 #endif
37538 #else
37539  { "GetProcAddressA", (SYSCALL)0, 0 },
37540 #endif
37541 
37542 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
37543  LPCSTR))aSyscall[27].pCurrent)
37544 
37545 #if !SQLITE_OS_WINRT
37546  { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
37547 #else
37548  { "GetSystemInfo", (SYSCALL)0, 0 },
37549 #endif
37550 
37551 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
37552 
37553  { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
37554 
37555 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
37556 
37557 #if !SQLITE_OS_WINCE
37558  { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
37559 #else
37560  { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
37561 #endif
37562 
37563 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
37564  LPFILETIME))aSyscall[30].pCurrent)
37565 
37566 #if defined(SQLITE_WIN32_HAS_ANSI)
37567  { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
37568 #else
37569  { "GetTempPathA", (SYSCALL)0, 0 },
37570 #endif
37571 
37572 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
37573 
37574 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
37575  { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
37576 #else
37577  { "GetTempPathW", (SYSCALL)0, 0 },
37578 #endif
37579 
37580 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
37581 
37582 #if !SQLITE_OS_WINRT
37583  { "GetTickCount", (SYSCALL)GetTickCount, 0 },
37584 #else
37585  { "GetTickCount", (SYSCALL)0, 0 },
37586 #endif
37587 
37588 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
37589 
37590 #if defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_GETVERSIONEX
37591  { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
37592 #else
37593  { "GetVersionExA", (SYSCALL)0, 0 },
37594 #endif
37595 
37596 #define osGetVersionExA ((BOOL(WINAPI*)( \
37597  LPOSVERSIONINFOA))aSyscall[34].pCurrent)
37598 
37599 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37600  SQLITE_WIN32_GETVERSIONEX
37601  { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
37602 #else
37603  { "GetVersionExW", (SYSCALL)0, 0 },
37604 #endif
37605 
37606 #define osGetVersionExW ((BOOL(WINAPI*)( \
37607  LPOSVERSIONINFOW))aSyscall[35].pCurrent)
37608 
37609  { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
37610 
37611 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
37612  SIZE_T))aSyscall[36].pCurrent)
37613 
37614 #if !SQLITE_OS_WINRT
37615  { "HeapCreate", (SYSCALL)HeapCreate, 0 },
37616 #else
37617  { "HeapCreate", (SYSCALL)0, 0 },
37618 #endif
37619 
37620 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
37621  SIZE_T))aSyscall[37].pCurrent)
37622 
37623 #if !SQLITE_OS_WINRT
37624  { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
37625 #else
37626  { "HeapDestroy", (SYSCALL)0, 0 },
37627 #endif
37628 
37629 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
37630 
37631  { "HeapFree", (SYSCALL)HeapFree, 0 },
37632 
37633 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
37634 
37635  { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
37636 
37637 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
37638  SIZE_T))aSyscall[40].pCurrent)
37639 
37640  { "HeapSize", (SYSCALL)HeapSize, 0 },
37641 
37642 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
37643  LPCVOID))aSyscall[41].pCurrent)
37644 
37645 #if !SQLITE_OS_WINRT
37646  { "HeapValidate", (SYSCALL)HeapValidate, 0 },
37647 #else
37648  { "HeapValidate", (SYSCALL)0, 0 },
37649 #endif
37650 
37651 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
37652  LPCVOID))aSyscall[42].pCurrent)
37653 
37654 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37655  { "HeapCompact", (SYSCALL)HeapCompact, 0 },
37656 #else
37657  { "HeapCompact", (SYSCALL)0, 0 },
37658 #endif
37659 
37660 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
37661 
37662 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
37663  { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
37664 #else
37665  { "LoadLibraryA", (SYSCALL)0, 0 },
37666 #endif
37667 
37668 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
37669 
37670 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
37671  !defined(SQLITE_OMIT_LOAD_EXTENSION)
37672  { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
37673 #else
37674  { "LoadLibraryW", (SYSCALL)0, 0 },
37675 #endif
37676 
37677 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
37678 
37679 #if !SQLITE_OS_WINRT
37680  { "LocalFree", (SYSCALL)LocalFree, 0 },
37681 #else
37682  { "LocalFree", (SYSCALL)0, 0 },
37683 #endif
37684 
37685 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
37686 
37687 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37688  { "LockFile", (SYSCALL)LockFile, 0 },
37689 #else
37690  { "LockFile", (SYSCALL)0, 0 },
37691 #endif
37692 
37693 #ifndef osLockFile
37694 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37695  DWORD))aSyscall[47].pCurrent)
37696 #endif
37697 
37698 #if !SQLITE_OS_WINCE
37699  { "LockFileEx", (SYSCALL)LockFileEx, 0 },
37700 #else
37701  { "LockFileEx", (SYSCALL)0, 0 },
37702 #endif
37703 
37704 #ifndef osLockFileEx
37705 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
37706  LPOVERLAPPED))aSyscall[48].pCurrent)
37707 #endif
37708 
37709 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
37710  (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
37711  { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
37712 #else
37713  { "MapViewOfFile", (SYSCALL)0, 0 },
37714 #endif
37715 
37716 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37717  SIZE_T))aSyscall[49].pCurrent)
37718 
37719  { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
37720 
37721 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
37722  int))aSyscall[50].pCurrent)
37723 
37724  { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
37725 
37726 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
37727  LARGE_INTEGER*))aSyscall[51].pCurrent)
37728 
37729  { "ReadFile", (SYSCALL)ReadFile, 0 },
37730 
37731 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
37732  LPOVERLAPPED))aSyscall[52].pCurrent)
37733 
37734  { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
37735 
37736 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
37737 
37738 #if !SQLITE_OS_WINRT
37739  { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
37740 #else
37741  { "SetFilePointer", (SYSCALL)0, 0 },
37742 #endif
37743 
37744 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
37745  DWORD))aSyscall[54].pCurrent)
37746 
37747 #if !SQLITE_OS_WINRT
37748  { "Sleep", (SYSCALL)Sleep, 0 },
37749 #else
37750  { "Sleep", (SYSCALL)0, 0 },
37751 #endif
37752 
37753 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
37754 
37755  { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
37756 
37757 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
37758  LPFILETIME))aSyscall[56].pCurrent)
37759 
37760 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
37761  { "UnlockFile", (SYSCALL)UnlockFile, 0 },
37762 #else
37763  { "UnlockFile", (SYSCALL)0, 0 },
37764 #endif
37765 
37766 #ifndef osUnlockFile
37767 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37768  DWORD))aSyscall[57].pCurrent)
37769 #endif
37770 
37771 #if !SQLITE_OS_WINCE
37772  { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
37773 #else
37774  { "UnlockFileEx", (SYSCALL)0, 0 },
37775 #endif
37776 
37777 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
37778  LPOVERLAPPED))aSyscall[58].pCurrent)
37779 
37780 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
37781  { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
37782 #else
37783  { "UnmapViewOfFile", (SYSCALL)0, 0 },
37784 #endif
37785 
37786 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
37787 
37788  { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
37789 
37790 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
37791  LPCSTR,LPBOOL))aSyscall[60].pCurrent)
37792 
37793  { "WriteFile", (SYSCALL)WriteFile, 0 },
37794 
37795 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
37796  LPOVERLAPPED))aSyscall[61].pCurrent)
37797 
37798 #if SQLITE_OS_WINRT
37799  { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
37800 #else
37801  { "CreateEventExW", (SYSCALL)0, 0 },
37802 #endif
37803 
37804 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
37805  DWORD,DWORD))aSyscall[62].pCurrent)
37806 
37807 #if !SQLITE_OS_WINRT
37808  { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
37809 #else
37810  { "WaitForSingleObject", (SYSCALL)0, 0 },
37811 #endif
37812 
37813 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
37814  DWORD))aSyscall[63].pCurrent)
37815 
37816 #if !SQLITE_OS_WINCE
37817  { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
37818 #else
37819  { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
37820 #endif
37821 
37822 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
37823  BOOL))aSyscall[64].pCurrent)
37824 
37825 #if SQLITE_OS_WINRT
37826  { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
37827 #else
37828  { "SetFilePointerEx", (SYSCALL)0, 0 },
37829 #endif
37830 
37831 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
37832  PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
37833 
37834 #if SQLITE_OS_WINRT
37835  { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
37836 #else
37837  { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
37838 #endif
37839 
37840 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
37841  FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
37842 
37843 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37844  { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
37845 #else
37846  { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
37847 #endif
37848 
37849 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
37850  SIZE_T))aSyscall[67].pCurrent)
37851 
37852 #if SQLITE_OS_WINRT
37853  { "CreateFile2", (SYSCALL)CreateFile2, 0 },
37854 #else
37855  { "CreateFile2", (SYSCALL)0, 0 },
37856 #endif
37857 
37858 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
37859  LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
37860 
37861 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
37862  { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
37863 #else
37864  { "LoadPackagedLibrary", (SYSCALL)0, 0 },
37865 #endif
37866 
37867 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
37868  DWORD))aSyscall[69].pCurrent)
37869 
37870 #if SQLITE_OS_WINRT
37871  { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
37872 #else
37873  { "GetTickCount64", (SYSCALL)0, 0 },
37874 #endif
37875 
37876 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
37877 
37878 #if SQLITE_OS_WINRT
37879  { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
37880 #else
37881  { "GetNativeSystemInfo", (SYSCALL)0, 0 },
37882 #endif
37883 
37884 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
37885  LPSYSTEM_INFO))aSyscall[71].pCurrent)
37886 
37887 #if defined(SQLITE_WIN32_HAS_ANSI)
37888  { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
37889 #else
37890  { "OutputDebugStringA", (SYSCALL)0, 0 },
37891 #endif
37892 
37893 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
37894 
37895 #if defined(SQLITE_WIN32_HAS_WIDE)
37896  { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
37897 #else
37898  { "OutputDebugStringW", (SYSCALL)0, 0 },
37899 #endif
37900 
37901 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
37902 
37903  { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
37904 
37905 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
37906 
37907 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
37908  { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
37909 #else
37910  { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
37911 #endif
37912 
37913 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
37914  LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
37915 
37916 /*
37917 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
37918 ** is really just a macro that uses a compiler intrinsic (e.g. x64).
37919 ** So do not try to make this is into a redefinable interface.
37920 */
37921 #if defined(InterlockedCompareExchange)
37922  { "InterlockedCompareExchange", (SYSCALL)0, 0 },
37923 
37924 #define osInterlockedCompareExchange InterlockedCompareExchange
37925 #else
37926  { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
37927 
37928 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
37929  SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
37930 #endif /* defined(InterlockedCompareExchange) */
37931 
37932 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
37933  { "UuidCreate", (SYSCALL)UuidCreate, 0 },
37934 #else
37935  { "UuidCreate", (SYSCALL)0, 0 },
37936 #endif
37937 
37938 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
37939 
37940 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
37941  { "UuidCreateSequential", (SYSCALL)UuidCreateSequential, 0 },
37942 #else
37943  { "UuidCreateSequential", (SYSCALL)0, 0 },
37944 #endif
37945 
37946 #define osUuidCreateSequential \
37947  ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
37948 
37949 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
37950  { "FlushViewOfFile", (SYSCALL)FlushViewOfFile, 0 },
37951 #else
37952  { "FlushViewOfFile", (SYSCALL)0, 0 },
37953 #endif
37954 
37955 #define osFlushViewOfFile \
37956  ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
37957 
37958 }; /* End of the overrideable system calls */
37959 
37960 /*
37961 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
37962 ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
37963 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
37964 ** system call named zName.
37965 */
37966 static int winSetSystemCall(
37967  sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
37968  const char *zName, /* Name of system call to override */
37969  sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
37970 ){
37971  unsigned int i;
37972  int rc = SQLITE_NOTFOUND;
37973 
37974  UNUSED_PARAMETER(pNotUsed);
37975  if( zName==0 ){
37976  /* If no zName is given, restore all system calls to their default
37977  ** settings and return NULL
37978  */
37979  rc = SQLITE_OK;
37980  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
37981  if( aSyscall[i].pDefault ){
37983  }
37984  }
37985  }else{
37986  /* If zName is specified, operate on only the one system call
37987  ** specified.
37988  */
37989  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
37990  if( strcmp(zName, aSyscall[i].zName)==0 ){
37991  if( aSyscall[i].pDefault==0 ){
37993  }
37994  rc = SQLITE_OK;
37995  if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
37996  aSyscall[i].pCurrent = pNewFunc;
37997  break;
37998  }
37999  }
38000  }
38001  return rc;
38002 }
38003 
38004 /*
38005 ** Return the value of a system call. Return NULL if zName is not a
38006 ** recognized system call name. NULL is also returned if the system call
38007 ** is currently undefined.
38008 */
38009 static sqlite3_syscall_ptr winGetSystemCall(
38010  sqlite3_vfs *pNotUsed,
38011  const char *zName
38012 ){
38013  unsigned int i;
38014 
38015  UNUSED_PARAMETER(pNotUsed);
38016  for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
38017  if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
38018  }
38019  return 0;
38020 }
38021 
38022 /*
38023 ** Return the name of the first system call after zName. If zName==NULL
38024 ** then return the name of the first system call. Return NULL if zName
38025 ** is the last system call or if zName is not the name of a valid
38026 ** system call.
38027 */
38028 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
38029  int i = -1;
38030 
38031  UNUSED_PARAMETER(p);
38032  if( zName ){
38033  for(i=0; i<ArraySize(aSyscall)-1; i++){
38034  if( strcmp(zName, aSyscall[i].zName)==0 ) break;
38035  }
38036  }
38037  for(i++; i<ArraySize(aSyscall); i++){
38038  if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
38039  }
38040  return 0;
38041 }
38042 
38043 #ifdef SQLITE_WIN32_MALLOC
38044 /*
38045 ** If a Win32 native heap has been configured, this function will attempt to
38046 ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
38047 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
38048 ** "pnLargest" argument, if non-zero, will be used to return the size of the
38049 ** largest committed free block in the heap, in bytes.
38050 */
38051 SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
38052  int rc = SQLITE_OK;
38053  UINT nLargest = 0;
38054  HANDLE hHeap;
38055 
38056  winMemAssertMagic();
38057  hHeap = winMemGetHeap();
38058  assert( hHeap!=0 );
38059  assert( hHeap!=INVALID_HANDLE_VALUE );
38060 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38061  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38062 #endif
38063 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
38064  if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
38065  DWORD lastErrno = osGetLastError();
38066  if( lastErrno==NO_ERROR ){
38067  sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
38068  (void*)hHeap);
38069  rc = SQLITE_NOMEM_BKPT;
38070  }else{
38071  sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
38072  osGetLastError(), (void*)hHeap);
38073  rc = SQLITE_ERROR;
38074  }
38075  }
38076 #else
38077  sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
38078  (void*)hHeap);
38079  rc = SQLITE_NOTFOUND;
38080 #endif
38081  if( pnLargest ) *pnLargest = nLargest;
38082  return rc;
38083 }
38084 
38085 /*
38086 ** If a Win32 native heap has been configured, this function will attempt to
38087 ** destroy and recreate it. If the Win32 native heap is not isolated and/or
38088 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
38089 ** be returned and no changes will be made to the Win32 native heap.
38090 */
38091 SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
38092  int rc;
38093  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
38094  MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
38097  sqlite3_mutex_enter(pMaster);
38098  sqlite3_mutex_enter(pMem);
38099  winMemAssertMagic();
38100  if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
38101  /*
38102  ** At this point, there should be no outstanding memory allocations on
38103  ** the heap. Also, since both the master and memsys locks are currently
38104  ** being held by us, no other function (i.e. from another thread) should
38105  ** be able to even access the heap. Attempt to destroy and recreate our
38106  ** isolated Win32 native heap now.
38107  */
38108  assert( winMemGetHeap()!=NULL );
38109  assert( winMemGetOwned() );
38110  assert( sqlite3_memory_used()==0 );
38111  winMemShutdown(winMemGetDataPtr());
38112  assert( winMemGetHeap()==NULL );
38113  assert( !winMemGetOwned() );
38114  assert( sqlite3_memory_used()==0 );
38115  rc = winMemInit(winMemGetDataPtr());
38116  assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
38117  assert( rc!=SQLITE_OK || winMemGetOwned() );
38118  assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
38119  }else{
38120  /*
38121  ** The Win32 native heap cannot be modified because it may be in use.
38122  */
38123  rc = SQLITE_BUSY;
38124  }
38125  sqlite3_mutex_leave(pMem);
38126  sqlite3_mutex_leave(pMaster);
38127  return rc;
38128 }
38129 #endif /* SQLITE_WIN32_MALLOC */
38130 
38131 /*
38132 ** This function outputs the specified (ANSI) string to the Win32 debugger
38133 ** (if available).
38134 */
38135 
38136 SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
38137  char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
38138  int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
38139  if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
38140  assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
38141 #ifdef SQLITE_ENABLE_API_ARMOR
38142  if( !zBuf ){
38144  return;
38145  }
38146 #endif
38147 #if defined(SQLITE_WIN32_HAS_ANSI)
38148  if( nMin>0 ){
38149  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38150  memcpy(zDbgBuf, zBuf, nMin);
38151  osOutputDebugStringA(zDbgBuf);
38152  }else{
38153  osOutputDebugStringA(zBuf);
38154  }
38155 #elif defined(SQLITE_WIN32_HAS_WIDE)
38156  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38157  if ( osMultiByteToWideChar(
38158  osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
38159  nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
38160  return;
38161  }
38162  osOutputDebugStringW((LPCWSTR)zDbgBuf);
38163 #else
38164  if( nMin>0 ){
38165  memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
38166  memcpy(zDbgBuf, zBuf, nMin);
38167  fprintf(stderr, "%s", zDbgBuf);
38168  }else{
38169  fprintf(stderr, "%s", zBuf);
38170  }
38171 #endif
38172 }
38173 
38174 /*
38175 ** The following routine suspends the current thread for at least ms
38176 ** milliseconds. This is equivalent to the Win32 Sleep() interface.
38177 */
38178 #if SQLITE_OS_WINRT
38179 static HANDLE sleepObj = NULL;
38180 #endif
38181 
38182 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
38183 #if SQLITE_OS_WINRT
38184  if ( sleepObj==NULL ){
38185  sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
38186  SYNCHRONIZE);
38187  }
38188  assert( sleepObj!=NULL );
38189  osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
38190 #else
38191  osSleep(milliseconds);
38192 #endif
38193 }
38194 
38195 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
38196  SQLITE_THREADSAFE>0
38197 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
38198  DWORD rc;
38199  while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
38200  TRUE))==WAIT_IO_COMPLETION ){}
38201  return rc;
38202 }
38203 #endif
38204 
38205 /*
38206 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
38207 ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
38208 **
38209 ** Here is an interesting observation: Win95, Win98, and WinME lack
38210 ** the LockFileEx() API. But we can still statically link against that
38211 ** API as long as we don't call it when running Win95/98/ME. A call to
38212 ** this routine is used to determine if the host is Win95/98/ME or
38213 ** WinNT/2K/XP so that we will know whether or not we can safely call
38214 ** the LockFileEx() API.
38215 */
38216 
38217 #if !SQLITE_WIN32_GETVERSIONEX
38218 # define osIsNT() (1)
38219 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
38220 # define osIsNT() (1)
38221 #elif !defined(SQLITE_WIN32_HAS_WIDE)
38222 # define osIsNT() (0)
38223 #else
38224 # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
38225 #endif
38226 
38227 /*
38228 ** This function determines if the machine is running a version of Windows
38229 ** based on the NT kernel.
38230 */
38231 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
38232 #if SQLITE_OS_WINRT
38233  /*
38234  ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
38235  ** kernel.
38236  */
38237  return 1;
38238 #elif SQLITE_WIN32_GETVERSIONEX
38239  if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
38240 #if defined(SQLITE_WIN32_HAS_ANSI)
38241  OSVERSIONINFOA sInfo;
38242  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38243  osGetVersionExA(&sInfo);
38244  osInterlockedCompareExchange(&sqlite3_os_type,
38245  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38246 #elif defined(SQLITE_WIN32_HAS_WIDE)
38247  OSVERSIONINFOW sInfo;
38248  sInfo.dwOSVersionInfoSize = sizeof(sInfo);
38249  osGetVersionExW(&sInfo);
38250  osInterlockedCompareExchange(&sqlite3_os_type,
38251  (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
38252 #endif
38253  }
38254  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38255 #elif SQLITE_TEST
38256  return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
38257 #else
38258  /*
38259  ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
38260  ** deprecated are always assumed to be based on the NT kernel.
38261  */
38262  return 1;
38263 #endif
38264 }
38265 
38266 #ifdef SQLITE_WIN32_MALLOC
38267 /*
38268 ** Allocate nBytes of memory.
38269 */
38270 static void *winMemMalloc(int nBytes){
38271  HANDLE hHeap;
38272  void *p;
38273 
38274  winMemAssertMagic();
38275  hHeap = winMemGetHeap();
38276  assert( hHeap!=0 );
38277  assert( hHeap!=INVALID_HANDLE_VALUE );
38278 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38279  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38280 #endif
38281  assert( nBytes>=0 );
38282  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38283  if( !p ){
38284  sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
38285  nBytes, osGetLastError(), (void*)hHeap);
38286  }
38287  return p;
38288 }
38289 
38290 /*
38291 ** Free memory.
38292 */
38293 static void winMemFree(void *pPrior){
38294  HANDLE hHeap;
38295 
38296  winMemAssertMagic();
38297  hHeap = winMemGetHeap();
38298  assert( hHeap!=0 );
38299  assert( hHeap!=INVALID_HANDLE_VALUE );
38300 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38301  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38302 #endif
38303  if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
38304  if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
38305  sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
38306  pPrior, osGetLastError(), (void*)hHeap);
38307  }
38308 }
38309 
38310 /*
38311 ** Change the size of an existing memory allocation
38312 */
38313 static void *winMemRealloc(void *pPrior, int nBytes){
38314  HANDLE hHeap;
38315  void *p;
38316 
38317  winMemAssertMagic();
38318  hHeap = winMemGetHeap();
38319  assert( hHeap!=0 );
38320  assert( hHeap!=INVALID_HANDLE_VALUE );
38321 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38322  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
38323 #endif
38324  assert( nBytes>=0 );
38325  if( !pPrior ){
38326  p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
38327  }else{
38328  p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
38329  }
38330  if( !p ){
38331  sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
38332  pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
38333  (void*)hHeap);
38334  }
38335  return p;
38336 }
38337 
38338 /*
38339 ** Return the size of an outstanding allocation, in bytes.
38340 */
38341 static int winMemSize(void *p){
38342  HANDLE hHeap;
38343  SIZE_T n;
38344 
38345  winMemAssertMagic();
38346  hHeap = winMemGetHeap();
38347  assert( hHeap!=0 );
38348  assert( hHeap!=INVALID_HANDLE_VALUE );
38349 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38350  assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
38351 #endif
38352  if( !p ) return 0;
38353  n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
38354  if( n==(SIZE_T)-1 ){
38355  sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
38356  p, osGetLastError(), (void*)hHeap);
38357  return 0;
38358  }
38359  return (int)n;
38360 }
38361 
38362 /*
38363 ** Round up a request size to the next valid allocation size.
38364 */
38365 static int winMemRoundup(int n){
38366  return n;
38367 }
38368 
38369 /*
38370 ** Initialize this module.
38371 */
38372 static int winMemInit(void *pAppData){
38373  winMemData *pWinMemData = (winMemData *)pAppData;
38374 
38375  if( !pWinMemData ) return SQLITE_ERROR;
38376  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38377  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38378 
38379 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
38380  if( !pWinMemData->hHeap ){
38381  DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
38382  DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
38383  if( dwMaximumSize==0 ){
38384  dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
38385  }else if( dwInitialSize>dwMaximumSize ){
38386  dwInitialSize = dwMaximumSize;
38387  }
38388  pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
38389  dwInitialSize, dwMaximumSize);
38390  if( !pWinMemData->hHeap ){
38392  "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
38393  osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
38394  dwMaximumSize);
38395  return SQLITE_NOMEM_BKPT;
38396  }
38397  pWinMemData->bOwned = TRUE;
38398  assert( pWinMemData->bOwned );
38399  }
38400 #else
38401  pWinMemData->hHeap = osGetProcessHeap();
38402  if( !pWinMemData->hHeap ){
38404  "failed to GetProcessHeap (%lu)", osGetLastError());
38405  return SQLITE_NOMEM_BKPT;
38406  }
38407  pWinMemData->bOwned = FALSE;
38408  assert( !pWinMemData->bOwned );
38409 #endif
38410  assert( pWinMemData->hHeap!=0 );
38411  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38412 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38413  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38414 #endif
38415  return SQLITE_OK;
38416 }
38417 
38418 /*
38419 ** Deinitialize this module.
38420 */
38421 static void winMemShutdown(void *pAppData){
38422  winMemData *pWinMemData = (winMemData *)pAppData;
38423 
38424  if( !pWinMemData ) return;
38425  assert( pWinMemData->magic1==WINMEM_MAGIC1 );
38426  assert( pWinMemData->magic2==WINMEM_MAGIC2 );
38427 
38428  if( pWinMemData->hHeap ){
38429  assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
38430 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
38431  assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
38432 #endif
38433  if( pWinMemData->bOwned ){
38434  if( !osHeapDestroy(pWinMemData->hHeap) ){
38435  sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
38436  osGetLastError(), (void*)pWinMemData->hHeap);
38437  }
38438  pWinMemData->bOwned = FALSE;
38439  }
38440  pWinMemData->hHeap = NULL;
38441  }
38442 }
38443 
38444 /*
38445 ** Populate the low-level memory allocation function pointers in
38446 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
38447 ** arguments specify the block of memory to manage.
38448 **
38449 ** This routine is only called by sqlite3_config(), and therefore
38450 ** is not required to be threadsafe (it is not).
38451 */
38452 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
38453  static const sqlite3_mem_methods winMemMethods = {
38454  winMemMalloc,
38455  winMemFree,
38456  winMemRealloc,
38457  winMemSize,
38458  winMemRoundup,
38459  winMemInit,
38460  winMemShutdown,
38461  &win_mem_data
38462  };
38463  return &winMemMethods;
38464 }
38465 
38467  sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
38468 }
38469 #endif /* SQLITE_WIN32_MALLOC */
38470 
38471 /*
38472 ** Convert a UTF-8 string to Microsoft Unicode.
38473 **
38474 ** Space to hold the returned string is obtained from sqlite3_malloc().
38475 */
38476 static LPWSTR winUtf8ToUnicode(const char *zText){
38477  int nChar;
38478  LPWSTR zWideText;
38479 
38480  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, NULL, 0);
38481  if( nChar==0 ){
38482  return 0;
38483  }
38484  zWideText = sqlite3MallocZero( nChar*sizeof(WCHAR) );
38485  if( zWideText==0 ){
38486  return 0;
38487  }
38488  nChar = osMultiByteToWideChar(CP_UTF8, 0, zText, -1, zWideText,
38489  nChar);
38490  if( nChar==0 ){
38491  sqlite3_free(zWideText);
38492  zWideText = 0;
38493  }
38494  return zWideText;
38495 }
38496 
38497 /*
38498 ** Convert a Microsoft Unicode string to UTF-8.
38499 **
38500 ** Space to hold the returned string is obtained from sqlite3_malloc().
38501 */
38502 static char *winUnicodeToUtf8(LPCWSTR zWideText){
38503  int nByte;
38504  char *zText;
38505 
38506  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, 0, 0, 0, 0);
38507  if( nByte == 0 ){
38508  return 0;
38509  }
38510  zText = sqlite3MallocZero( nByte );
38511  if( zText==0 ){
38512  return 0;
38513  }
38514  nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideText, -1, zText, nByte,
38515  0, 0);
38516  if( nByte == 0 ){
38517  sqlite3_free(zText);
38518  zText = 0;
38519  }
38520  return zText;
38521 }
38522 
38523 /*
38524 ** Convert an ANSI string to Microsoft Unicode, using the ANSI or OEM
38525 ** code page.
38526 **
38527 ** Space to hold the returned string is obtained from sqlite3_malloc().
38528 */
38529 static LPWSTR winMbcsToUnicode(const char *zText, int useAnsi){
38530  int nByte;
38531  LPWSTR zMbcsText;
38532  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38533 
38534  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, NULL,
38535  0)*sizeof(WCHAR);
38536  if( nByte==0 ){
38537  return 0;
38538  }
38539  zMbcsText = sqlite3MallocZero( nByte*sizeof(WCHAR) );
38540  if( zMbcsText==0 ){
38541  return 0;
38542  }
38543  nByte = osMultiByteToWideChar(codepage, 0, zText, -1, zMbcsText,
38544  nByte);
38545  if( nByte==0 ){
38546  sqlite3_free(zMbcsText);
38547  zMbcsText = 0;
38548  }
38549  return zMbcsText;
38550 }
38551 
38552 /*
38553 ** Convert a Microsoft Unicode string to a multi-byte character string,
38554 ** using the ANSI or OEM code page.
38555 **
38556 ** Space to hold the returned string is obtained from sqlite3_malloc().
38557 */
38558 static char *winUnicodeToMbcs(LPCWSTR zWideText, int useAnsi){
38559  int nByte;
38560  char *zText;
38561  int codepage = useAnsi ? CP_ACP : CP_OEMCP;
38562 
38563  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, 0, 0, 0, 0);
38564  if( nByte == 0 ){
38565  return 0;
38566  }
38567  zText = sqlite3MallocZero( nByte );
38568  if( zText==0 ){
38569  return 0;
38570  }
38571  nByte = osWideCharToMultiByte(codepage, 0, zWideText, -1, zText,
38572  nByte, 0, 0);
38573  if( nByte == 0 ){
38574  sqlite3_free(zText);
38575  zText = 0;
38576  }
38577  return zText;
38578 }
38579 
38580 /*
38581 ** Convert a multi-byte character string to UTF-8.
38582 **
38583 ** Space to hold the returned string is obtained from sqlite3_malloc().
38584 */
38585 static char *winMbcsToUtf8(const char *zText, int useAnsi){
38586  char *zTextUtf8;
38587  LPWSTR zTmpWide;
38588 
38589  zTmpWide = winMbcsToUnicode(zText, useAnsi);
38590  if( zTmpWide==0 ){
38591  return 0;
38592  }
38593  zTextUtf8 = winUnicodeToUtf8(zTmpWide);
38594  sqlite3_free(zTmpWide);
38595  return zTextUtf8;
38596 }
38597 
38598 /*
38599 ** Convert a UTF-8 string to a multi-byte character string.
38600 **
38601 ** Space to hold the returned string is obtained from sqlite3_malloc().
38602 */
38603 static char *winUtf8ToMbcs(const char *zText, int useAnsi){
38604  char *zTextMbcs;
38605  LPWSTR zTmpWide;
38606 
38607  zTmpWide = winUtf8ToUnicode(zText);
38608  if( zTmpWide==0 ){
38609  return 0;
38610  }
38611  zTextMbcs = winUnicodeToMbcs(zTmpWide, useAnsi);
38612  sqlite3_free(zTmpWide);
38613  return zTextMbcs;
38614 }
38615 
38616 /*
38617 ** This is a public wrapper for the winUtf8ToUnicode() function.
38618 */
38619 SQLITE_API LPWSTR SQLITE_STDCALL sqlite3_win32_utf8_to_unicode(const char *zText){
38620 #ifdef SQLITE_ENABLE_API_ARMOR
38621  if( !zText ){
38623  return 0;
38624  }
38625 #endif
38626 #ifndef SQLITE_OMIT_AUTOINIT
38627  if( sqlite3_initialize() ) return 0;
38628 #endif
38629  return winUtf8ToUnicode(zText);
38630 }
38631 
38632 /*
38633 ** This is a public wrapper for the winUnicodeToUtf8() function.
38634 */
38635 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_unicode_to_utf8(LPCWSTR zWideText){
38636 #ifdef SQLITE_ENABLE_API_ARMOR
38637  if( !zWideText ){
38639  return 0;
38640  }
38641 #endif
38642 #ifndef SQLITE_OMIT_AUTOINIT
38643  if( sqlite3_initialize() ) return 0;
38644 #endif
38645  return winUnicodeToUtf8(zWideText);
38646 }
38647 
38648 /*
38649 ** This is a public wrapper for the winMbcsToUtf8() function.
38650 */
38651 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zText){
38652 #ifdef SQLITE_ENABLE_API_ARMOR
38653  if( !zText ){
38655  return 0;
38656  }
38657 #endif
38658 #ifndef SQLITE_OMIT_AUTOINIT
38659  if( sqlite3_initialize() ) return 0;
38660 #endif
38661  return winMbcsToUtf8(zText, osAreFileApisANSI());
38662 }
38663 
38664 /*
38665 ** This is a public wrapper for the winMbcsToUtf8() function.
38666 */
38667 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8_v2(const char *zText, int useAnsi){
38668 #ifdef SQLITE_ENABLE_API_ARMOR
38669  if( !zText ){
38671  return 0;
38672  }
38673 #endif
38674 #ifndef SQLITE_OMIT_AUTOINIT
38675  if( sqlite3_initialize() ) return 0;
38676 #endif
38677  return winMbcsToUtf8(zText, useAnsi);
38678 }
38679 
38680 /*
38681 ** This is a public wrapper for the winUtf8ToMbcs() function.
38682 */
38683 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zText){
38684 #ifdef SQLITE_ENABLE_API_ARMOR
38685  if( !zText ){
38687  return 0;
38688  }
38689 #endif
38690 #ifndef SQLITE_OMIT_AUTOINIT
38691  if( sqlite3_initialize() ) return 0;
38692 #endif
38693  return winUtf8ToMbcs(zText, osAreFileApisANSI());
38694 }
38695 
38696 /*
38697 ** This is a public wrapper for the winUtf8ToMbcs() function.
38698 */
38699 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs_v2(const char *zText, int useAnsi){
38700 #ifdef SQLITE_ENABLE_API_ARMOR
38701  if( !zText ){
38703  return 0;
38704  }
38705 #endif
38706 #ifndef SQLITE_OMIT_AUTOINIT
38707  if( sqlite3_initialize() ) return 0;
38708 #endif
38709  return winUtf8ToMbcs(zText, useAnsi);
38710 }
38711 
38712 /*
38713 ** This function sets the data directory or the temporary directory based on
38714 ** the provided arguments. The type argument must be 1 in order to set the
38715 ** data directory or 2 in order to set the temporary directory. The zValue
38716 ** argument is the name of the directory to use. The return value will be
38717 ** SQLITE_OK if successful.
38718 */
38719 SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
38720  char **ppDirectory = 0;
38721 #ifndef SQLITE_OMIT_AUTOINIT
38722  int rc = sqlite3_initialize();
38723  if( rc ) return rc;
38724 #endif
38725  if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
38726  ppDirectory = &sqlite3_data_directory;
38727  }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
38728  ppDirectory = &sqlite3_temp_directory;
38729  }
38730  assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
38731  || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
38732  );
38733  assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
38734  if( ppDirectory ){
38735  char *zValueUtf8 = 0;
38736  if( zValue && zValue[0] ){
38737  zValueUtf8 = winUnicodeToUtf8(zValue);
38738  if ( zValueUtf8==0 ){
38739  return SQLITE_NOMEM_BKPT;
38740  }
38741  }
38742  sqlite3_free(*ppDirectory);
38743  *ppDirectory = zValueUtf8;
38744  return SQLITE_OK;
38745  }
38746  return SQLITE_ERROR;
38747 }
38748 
38749 /*
38750 ** The return value of winGetLastErrorMsg
38751 ** is zero if the error message fits in the buffer, or non-zero
38752 ** otherwise (if the message was truncated).
38753 */
38754 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
38755  /* FormatMessage returns 0 on failure. Otherwise it
38756  ** returns the number of TCHARs written to the output
38757  ** buffer, excluding the terminating null char.
38758  */
38759  DWORD dwLen = 0;
38760  char *zOut = 0;
38761 
38762  if( osIsNT() ){
38763 #if SQLITE_OS_WINRT
38764  WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
38765  dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
38766  FORMAT_MESSAGE_IGNORE_INSERTS,
38767  NULL,
38768  lastErrno,
38769  0,
38770  zTempWide,
38771  SQLITE_WIN32_MAX_ERRMSG_CHARS,
38772  0);
38773 #else
38774  LPWSTR zTempWide = NULL;
38775  dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
38776  FORMAT_MESSAGE_FROM_SYSTEM |
38777  FORMAT_MESSAGE_IGNORE_INSERTS,
38778  NULL,
38779  lastErrno,
38780  0,
38781  (LPWSTR) &zTempWide,
38782  0,
38783  0);
38784 #endif
38785  if( dwLen > 0 ){
38786  /* allocate a buffer and convert to UTF8 */
38788  zOut = winUnicodeToUtf8(zTempWide);
38790 #if !SQLITE_OS_WINRT
38791  /* free the system buffer allocated by FormatMessage */
38792  osLocalFree(zTempWide);
38793 #endif
38794  }
38795  }
38796 #ifdef SQLITE_WIN32_HAS_ANSI
38797  else{
38798  char *zTemp = NULL;
38799  dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
38800  FORMAT_MESSAGE_FROM_SYSTEM |
38801  FORMAT_MESSAGE_IGNORE_INSERTS,
38802  NULL,
38803  lastErrno,
38804  0,
38805  (LPSTR) &zTemp,
38806  0,
38807  0);
38808  if( dwLen > 0 ){
38809  /* allocate a buffer and convert to UTF8 */
38811  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
38813  /* free the system buffer allocated by FormatMessage */
38814  osLocalFree(zTemp);
38815  }
38816  }
38817 #endif
38818  if( 0 == dwLen ){
38819  sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
38820  }else{
38821  /* copy a maximum of nBuf chars to output buffer */
38822  sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
38823  /* free the UTF8 buffer */
38824  sqlite3_free(zOut);
38825  }
38826  return 0;
38827 }
38828 
38829 /*
38830 **
38831 ** This function - winLogErrorAtLine() - is only ever called via the macro
38832 ** winLogError().
38833 **
38834 ** This routine is invoked after an error occurs in an OS function.
38835 ** It logs a message using sqlite3_log() containing the current value of
38836 ** error code and, if possible, the human-readable equivalent from
38837 ** FormatMessage.
38838 **
38839 ** The first argument passed to the macro should be the error code that
38840 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
38841 ** The two subsequent arguments should be the name of the OS function that
38842 ** failed and the associated file-system path, if any.
38843 */
38844 #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
38845 static int winLogErrorAtLine(
38846  int errcode, /* SQLite error code */
38847  DWORD lastErrno, /* Win32 last error */
38848  const char *zFunc, /* Name of OS function that failed */
38849  const char *zPath, /* File path associated with error */
38850  int iLine /* Source line number where error occurred */
38851 ){
38852  char zMsg[500]; /* Human readable error text */
38853  int i; /* Loop counter */
38854 
38855  zMsg[0] = 0;
38856  winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
38857  assert( errcode!=SQLITE_OK );
38858  if( zPath==0 ) zPath = "";
38859  for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
38860  zMsg[i] = 0;
38861  sqlite3_log(errcode,
38862  "os_win.c:%d: (%lu) %s(%s) - %s",
38863  iLine, lastErrno, zFunc, zPath, zMsg
38864  );
38865 
38866  return errcode;
38867 }
38868 
38869 /*
38870 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
38871 ** will be retried following a locking error - probably caused by
38872 ** antivirus software. Also the initial delay before the first retry.
38873 ** The delay increases linearly with each retry.
38874 */
38875 #ifndef SQLITE_WIN32_IOERR_RETRY
38876 # define SQLITE_WIN32_IOERR_RETRY 10
38877 #endif
38878 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
38879 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
38880 #endif
38881 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
38882 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
38883 
38884 /*
38885 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
38886 ** error code obtained via GetLastError() is eligible to be retried. It
38887 ** must accept the error code DWORD as its only argument and should return
38888 ** non-zero if the error code is transient in nature and the operation
38889 ** responsible for generating the original error might succeed upon being
38890 ** retried. The argument to this macro should be a variable.
38891 **
38892 ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
38893 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
38894 ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
38895 ** may be used to include additional error codes in the set that should
38896 ** result in the failing I/O operation being retried by the caller. If
38897 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
38898 ** identical to those of the "winIoerrCanRetry1" macro.
38899 */
38900 #if !defined(winIoerrCanRetry1)
38901 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
38902  ((a)==ERROR_SHARING_VIOLATION) || \
38903  ((a)==ERROR_LOCK_VIOLATION) || \
38904  ((a)==ERROR_DEV_NOT_EXIST) || \
38905  ((a)==ERROR_NETNAME_DELETED) || \
38906  ((a)==ERROR_SEM_TIMEOUT) || \
38907  ((a)==ERROR_NETWORK_UNREACHABLE))
38908 #endif
38909 
38910 /*
38911 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
38912 ** to see if it should be retried. Return TRUE to retry. Return FALSE
38913 ** to give up with an error.
38914 */
38915 static int winRetryIoerr(int *pnRetry, DWORD *pError){
38916  DWORD e = osGetLastError();
38917  if( *pnRetry>=winIoerrRetry ){
38918  if( pError ){
38919  *pError = e;
38920  }
38921  return 0;
38922  }
38923  if( winIoerrCanRetry1(e) ){
38924  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
38925  ++*pnRetry;
38926  return 1;
38927  }
38928 #if defined(winIoerrCanRetry2)
38929  else if( winIoerrCanRetry2(e) ){
38930  sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
38931  ++*pnRetry;
38932  return 1;
38933  }
38934 #endif
38935  if( pError ){
38936  *pError = e;
38937  }
38938  return 0;
38939 }
38940 
38941 /*
38942 ** Log a I/O error retry episode.
38943 */
38944 static void winLogIoerr(int nRetry, int lineno){
38945  if( nRetry ){
38947  "delayed %dms for lock/sharing conflict at line %d",
38948  winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
38949  );
38950  }
38951 }
38952 
38953 /*
38954 ** This #if does not rely on the SQLITE_OS_WINCE define because the
38955 ** corresponding section in "date.c" cannot use it.
38956 */
38957 #if !defined(SQLITE_OMIT_LOCALTIME) && defined(_WIN32_WCE) && \
38958  (!defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API)
38959 /*
38960 ** The MSVC CRT on Windows CE may not have a localtime() function.
38961 ** So define a substitute.
38962 */
38963 /* # include <time.h> */
38964 struct tm *__cdecl localtime(const time_t *t)
38965 {
38966  static struct tm y;
38967  FILETIME uTm, lTm;
38968  SYSTEMTIME pTm;
38969  sqlite3_int64 t64;
38970  t64 = *t;
38971  t64 = (t64 + 11644473600)*10000000;
38972  uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
38973  uTm.dwHighDateTime= (DWORD)(t64 >> 32);
38974  osFileTimeToLocalFileTime(&uTm,&lTm);
38975  osFileTimeToSystemTime(&lTm,&pTm);
38976  y.tm_year = pTm.wYear - 1900;
38977  y.tm_mon = pTm.wMonth - 1;
38978  y.tm_wday = pTm.wDayOfWeek;
38979  y.tm_mday = pTm.wDay;
38980  y.tm_hour = pTm.wHour;
38981  y.tm_min = pTm.wMinute;
38982  y.tm_sec = pTm.wSecond;
38983  return &y;
38984 }
38985 #endif
38986 
38987 #if SQLITE_OS_WINCE
38988 /*************************************************************************
38989 ** This section contains code for WinCE only.
38990 */
38991 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
38992 
38993 /*
38994 ** Acquire a lock on the handle h
38995 */
38996 static void winceMutexAcquire(HANDLE h){
38997  DWORD dwErr;
38998  do {
38999  dwErr = osWaitForSingleObject(h, INFINITE);
39000  } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
39001 }
39002 /*
39003 ** Release a lock acquired by winceMutexAcquire()
39004 */
39005 #define winceMutexRelease(h) ReleaseMutex(h)
39006 
39007 /*
39008 ** Create the mutex and shared memory used for locking in the file
39009 ** descriptor pFile
39010 */
39011 static int winceCreateLock(const char *zFilename, winFile *pFile){
39012  LPWSTR zTok;
39013  LPWSTR zName;
39014  DWORD lastErrno;
39015  BOOL bLogged = FALSE;
39016  BOOL bInit = TRUE;
39017 
39018  zName = winUtf8ToUnicode(zFilename);
39019  if( zName==0 ){
39020  /* out of memory */
39021  return SQLITE_IOERR_NOMEM_BKPT;
39022  }
39023 
39024  /* Initialize the local lockdata */
39025  memset(&pFile->local, 0, sizeof(pFile->local));
39026 
39027  /* Replace the backslashes from the filename and lowercase it
39028  ** to derive a mutex name. */
39029  zTok = osCharLowerW(zName);
39030  for (;*zTok;zTok++){
39031  if (*zTok == '\\') *zTok = '_';
39032  }
39033 
39034  /* Create/open the named mutex */
39035  pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
39036  if (!pFile->hMutex){
39037  pFile->lastErrno = osGetLastError();
39038  sqlite3_free(zName);
39039  return winLogError(SQLITE_IOERR, pFile->lastErrno,
39040  "winceCreateLock1", zFilename);
39041  }
39042 
39043  /* Acquire the mutex before continuing */
39044  winceMutexAcquire(pFile->hMutex);
39045 
39046  /* Since the names of named mutexes, semaphores, file mappings etc are
39047  ** case-sensitive, take advantage of that by uppercasing the mutex name
39048  ** and using that as the shared filemapping name.
39049  */
39050  osCharUpperW(zName);
39051  pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
39052  PAGE_READWRITE, 0, sizeof(winceLock),
39053  zName);
39054 
39055  /* Set a flag that indicates we're the first to create the memory so it
39056  ** must be zero-initialized */
39057  lastErrno = osGetLastError();
39058  if (lastErrno == ERROR_ALREADY_EXISTS){
39059  bInit = FALSE;
39060  }
39061 
39062  sqlite3_free(zName);
39063 
39064  /* If we succeeded in making the shared memory handle, map it. */
39065  if( pFile->hShared ){
39066  pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
39067  FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
39068  /* If mapping failed, close the shared memory handle and erase it */
39069  if( !pFile->shared ){
39070  pFile->lastErrno = osGetLastError();
39071  winLogError(SQLITE_IOERR, pFile->lastErrno,
39072  "winceCreateLock2", zFilename);
39073  bLogged = TRUE;
39074  osCloseHandle(pFile->hShared);
39075  pFile->hShared = NULL;
39076  }
39077  }
39078 
39079  /* If shared memory could not be created, then close the mutex and fail */
39080  if( pFile->hShared==NULL ){
39081  if( !bLogged ){
39082  pFile->lastErrno = lastErrno;
39083  winLogError(SQLITE_IOERR, pFile->lastErrno,
39084  "winceCreateLock3", zFilename);
39085  bLogged = TRUE;
39086  }
39087  winceMutexRelease(pFile->hMutex);
39088  osCloseHandle(pFile->hMutex);
39089  pFile->hMutex = NULL;
39090  return SQLITE_IOERR;
39091  }
39092 
39093  /* Initialize the shared memory if we're supposed to */
39094  if( bInit ){
39095  memset(pFile->shared, 0, sizeof(winceLock));
39096  }
39097 
39098  winceMutexRelease(pFile->hMutex);
39099  return SQLITE_OK;
39100 }
39101 
39102 /*
39103 ** Destroy the part of winFile that deals with wince locks
39104 */
39105 static void winceDestroyLock(winFile *pFile){
39106  if (pFile->hMutex){
39107  /* Acquire the mutex */
39108  winceMutexAcquire(pFile->hMutex);
39109 
39110  /* The following blocks should probably assert in debug mode, but they
39111  are to cleanup in case any locks remained open */
39112  if (pFile->local.nReaders){
39113  pFile->shared->nReaders --;
39114  }
39115  if (pFile->local.bReserved){
39116  pFile->shared->bReserved = FALSE;
39117  }
39118  if (pFile->local.bPending){
39119  pFile->shared->bPending = FALSE;
39120  }
39121  if (pFile->local.bExclusive){
39122  pFile->shared->bExclusive = FALSE;
39123  }
39124 
39125  /* De-reference and close our copy of the shared memory handle */
39126  osUnmapViewOfFile(pFile->shared);
39127  osCloseHandle(pFile->hShared);
39128 
39129  /* Done with the mutex */
39130  winceMutexRelease(pFile->hMutex);
39131  osCloseHandle(pFile->hMutex);
39132  pFile->hMutex = NULL;
39133  }
39134 }
39135 
39136 /*
39137 ** An implementation of the LockFile() API of Windows for CE
39138 */
39139 static BOOL winceLockFile(
39140  LPHANDLE phFile,
39141  DWORD dwFileOffsetLow,
39142  DWORD dwFileOffsetHigh,
39143  DWORD nNumberOfBytesToLockLow,
39144  DWORD nNumberOfBytesToLockHigh
39145 ){
39146  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39147  BOOL bReturn = FALSE;
39148 
39149  UNUSED_PARAMETER(dwFileOffsetHigh);
39150  UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
39151 
39152  if (!pFile->hMutex) return TRUE;
39153  winceMutexAcquire(pFile->hMutex);
39154 
39155  /* Wanting an exclusive lock? */
39156  if (dwFileOffsetLow == (DWORD)SHARED_FIRST
39157  && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
39158  if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
39159  pFile->shared->bExclusive = TRUE;
39160  pFile->local.bExclusive = TRUE;
39161  bReturn = TRUE;
39162  }
39163  }
39164 
39165  /* Want a read-only lock? */
39166  else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
39167  nNumberOfBytesToLockLow == 1){
39168  if (pFile->shared->bExclusive == 0){
39169  pFile->local.nReaders ++;
39170  if (pFile->local.nReaders == 1){
39171  pFile->shared->nReaders ++;
39172  }
39173  bReturn = TRUE;
39174  }
39175  }
39176 
39177  /* Want a pending lock? */
39178  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39179  && nNumberOfBytesToLockLow == 1){
39180  /* If no pending lock has been acquired, then acquire it */
39181  if (pFile->shared->bPending == 0) {
39182  pFile->shared->bPending = TRUE;
39183  pFile->local.bPending = TRUE;
39184  bReturn = TRUE;
39185  }
39186  }
39187 
39188  /* Want a reserved lock? */
39189  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39190  && nNumberOfBytesToLockLow == 1){
39191  if (pFile->shared->bReserved == 0) {
39192  pFile->shared->bReserved = TRUE;
39193  pFile->local.bReserved = TRUE;
39194  bReturn = TRUE;
39195  }
39196  }
39197 
39198  winceMutexRelease(pFile->hMutex);
39199  return bReturn;
39200 }
39201 
39202 /*
39203 ** An implementation of the UnlockFile API of Windows for CE
39204 */
39205 static BOOL winceUnlockFile(
39206  LPHANDLE phFile,
39207  DWORD dwFileOffsetLow,
39208  DWORD dwFileOffsetHigh,
39209  DWORD nNumberOfBytesToUnlockLow,
39210  DWORD nNumberOfBytesToUnlockHigh
39211 ){
39212  winFile *pFile = HANDLE_TO_WINFILE(phFile);
39213  BOOL bReturn = FALSE;
39214 
39215  UNUSED_PARAMETER(dwFileOffsetHigh);
39216  UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
39217 
39218  if (!pFile->hMutex) return TRUE;
39219  winceMutexAcquire(pFile->hMutex);
39220 
39221  /* Releasing a reader lock or an exclusive lock */
39222  if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
39223  /* Did we have an exclusive lock? */
39224  if (pFile->local.bExclusive){
39225  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
39226  pFile->local.bExclusive = FALSE;
39227  pFile->shared->bExclusive = FALSE;
39228  bReturn = TRUE;
39229  }
39230 
39231  /* Did we just have a reader lock? */
39232  else if (pFile->local.nReaders){
39233  assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
39234  || nNumberOfBytesToUnlockLow == 1);
39235  pFile->local.nReaders --;
39236  if (pFile->local.nReaders == 0)
39237  {
39238  pFile->shared->nReaders --;
39239  }
39240  bReturn = TRUE;
39241  }
39242  }
39243 
39244  /* Releasing a pending lock */
39245  else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
39246  && nNumberOfBytesToUnlockLow == 1){
39247  if (pFile->local.bPending){
39248  pFile->local.bPending = FALSE;
39249  pFile->shared->bPending = FALSE;
39250  bReturn = TRUE;
39251  }
39252  }
39253  /* Releasing a reserved lock */
39254  else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
39255  && nNumberOfBytesToUnlockLow == 1){
39256  if (pFile->local.bReserved) {
39257  pFile->local.bReserved = FALSE;
39258  pFile->shared->bReserved = FALSE;
39259  bReturn = TRUE;
39260  }
39261  }
39262 
39263  winceMutexRelease(pFile->hMutex);
39264  return bReturn;
39265 }
39266 /*
39267 ** End of the special code for wince
39268 *****************************************************************************/
39269 #endif /* SQLITE_OS_WINCE */
39270 
39271 /*
39272 ** Lock a file region.
39273 */
39274 static BOOL winLockFile(
39275  LPHANDLE phFile,
39276  DWORD flags,
39277  DWORD offsetLow,
39278  DWORD offsetHigh,
39279  DWORD numBytesLow,
39280  DWORD numBytesHigh
39281 ){
39282 #if SQLITE_OS_WINCE
39283  /*
39284  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39285  ** API LockFile.
39286  */
39287  return winceLockFile(phFile, offsetLow, offsetHigh,
39288  numBytesLow, numBytesHigh);
39289 #else
39290  if( osIsNT() ){
39291  OVERLAPPED ovlp;
39292  memset(&ovlp, 0, sizeof(OVERLAPPED));
39293  ovlp.Offset = offsetLow;
39294  ovlp.OffsetHigh = offsetHigh;
39295  return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
39296  }else{
39297  return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39298  numBytesHigh);
39299  }
39300 #endif
39301 }
39302 
39303 /*
39304 ** Unlock a file region.
39305  */
39306 static BOOL winUnlockFile(
39307  LPHANDLE phFile,
39308  DWORD offsetLow,
39309  DWORD offsetHigh,
39310  DWORD numBytesLow,
39311  DWORD numBytesHigh
39312 ){
39313 #if SQLITE_OS_WINCE
39314  /*
39315  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39316  ** API UnlockFile.
39317  */
39318  return winceUnlockFile(phFile, offsetLow, offsetHigh,
39319  numBytesLow, numBytesHigh);
39320 #else
39321  if( osIsNT() ){
39322  OVERLAPPED ovlp;
39323  memset(&ovlp, 0, sizeof(OVERLAPPED));
39324  ovlp.Offset = offsetLow;
39325  ovlp.OffsetHigh = offsetHigh;
39326  return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
39327  }else{
39328  return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
39329  numBytesHigh);
39330  }
39331 #endif
39332 }
39333 
39334 /*****************************************************************************
39335 ** The next group of routines implement the I/O methods specified
39336 ** by the sqlite3_io_methods object.
39337 ******************************************************************************/
39338 
39339 /*
39340 ** Some Microsoft compilers lack this definition.
39341 */
39342 #ifndef INVALID_SET_FILE_POINTER
39343 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
39344 #endif
39345 
39346 /*
39347 ** Move the current position of the file handle passed as the first
39348 ** argument to offset iOffset within the file. If successful, return 0.
39349 ** Otherwise, set pFile->lastErrno and return non-zero.
39350 */
39351 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
39352 #if !SQLITE_OS_WINRT
39353  LONG upperBits; /* Most sig. 32 bits of new offset */
39354  LONG lowerBits; /* Least sig. 32 bits of new offset */
39355  DWORD dwRet; /* Value returned by SetFilePointer() */
39356  DWORD lastErrno; /* Value returned by GetLastError() */
39357 
39358  OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
39359 
39360  upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
39361  lowerBits = (LONG)(iOffset & 0xffffffff);
39362 
39363  /* API oddity: If successful, SetFilePointer() returns a dword
39364  ** containing the lower 32-bits of the new file-offset. Or, if it fails,
39365  ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
39366  ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
39367  ** whether an error has actually occurred, it is also necessary to call
39368  ** GetLastError().
39369  */
39370  dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
39371 
39372  if( (dwRet==INVALID_SET_FILE_POINTER
39373  && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
39374  pFile->lastErrno = lastErrno;
39375  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39376  "winSeekFile", pFile->zPath);
39377  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39378  return 1;
39379  }
39380 
39381  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39382  return 0;
39383 #else
39384  /*
39385  ** Same as above, except that this implementation works for WinRT.
39386  */
39387 
39388  LARGE_INTEGER x; /* The new offset */
39389  BOOL bRet; /* Value returned by SetFilePointerEx() */
39390 
39391  x.QuadPart = iOffset;
39392  bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
39393 
39394  if(!bRet){
39395  pFile->lastErrno = osGetLastError();
39396  winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
39397  "winSeekFile", pFile->zPath);
39398  OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
39399  return 1;
39400  }
39401 
39402  OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
39403  return 0;
39404 #endif
39405 }
39406 
39407 #if SQLITE_MAX_MMAP_SIZE>0
39408 /* Forward references to VFS helper methods used for memory mapped files */
39409 static int winMapfile(winFile*, sqlite3_int64);
39410 static int winUnmapfile(winFile*);
39411 #endif
39412 
39413 /*
39414 ** Close a file.
39415 **
39416 ** It is reported that an attempt to close a handle might sometimes
39417 ** fail. This is a very unreasonable result, but Windows is notorious
39418 ** for being unreasonable so I do not doubt that it might happen. If
39419 ** the close fails, we pause for 100 milliseconds and try again. As
39420 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
39421 ** giving up and returning an error.
39422 */
39423 #define MX_CLOSE_ATTEMPT 3
39424 static int winClose(sqlite3_file *id){
39425  int rc, cnt = 0;
39426  winFile *pFile = (winFile*)id;
39427 
39428  assert( id!=0 );
39429 #ifndef SQLITE_OMIT_WAL
39430  assert( pFile->pShm==0 );
39431 #endif
39432  assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
39433  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
39434  osGetCurrentProcessId(), pFile, pFile->h));
39435 
39436 #if SQLITE_MAX_MMAP_SIZE>0
39437  winUnmapfile(pFile);
39438 #endif
39439 
39440  do{
39441  rc = osCloseHandle(pFile->h);
39442  /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
39443  }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
39444 #if SQLITE_OS_WINCE
39445 #define WINCE_DELETION_ATTEMPTS 3
39446  winceDestroyLock(pFile);
39447  if( pFile->zDeleteOnClose ){
39448  int cnt = 0;
39449  while(
39450  osDeleteFileW(pFile->zDeleteOnClose)==0
39451  && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
39452  && cnt++ < WINCE_DELETION_ATTEMPTS
39453  ){
39454  sqlite3_win32_sleep(100); /* Wait a little before trying again */
39455  }
39456  sqlite3_free(pFile->zDeleteOnClose);
39457  }
39458 #endif
39459  if( rc ){
39460  pFile->h = NULL;
39461  }
39462  OpenCounter(-1);
39463  OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39464  osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
39465  return rc ? SQLITE_OK
39466  : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
39467  "winClose", pFile->zPath);
39468 }
39469 
39470 /*
39471 ** Read data from a file into a buffer. Return SQLITE_OK if all
39472 ** bytes were read successfully and SQLITE_IOERR if anything goes
39473 ** wrong.
39474 */
39475 static int winRead(
39476  sqlite3_file *id, /* File to read from */
39477  void *pBuf, /* Write content into this buffer */
39478  int amt, /* Number of bytes to read */
39479  sqlite3_int64 offset /* Begin reading at this offset */
39480 ){
39481 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39482  OVERLAPPED overlapped; /* The offset for ReadFile. */
39483 #endif
39484  winFile *pFile = (winFile*)id; /* file handle */
39485  DWORD nRead; /* Number of bytes actually read from file */
39486  int nRetry = 0; /* Number of retrys */
39487 
39488  assert( id!=0 );
39489  assert( amt>0 );
39490  assert( offset>=0 );
39492  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39493  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39494  pFile->h, pBuf, amt, offset, pFile->locktype));
39495 
39496 #if SQLITE_MAX_MMAP_SIZE>0
39497  /* Deal with as much of this read request as possible by transfering
39498  ** data from the memory mapping using memcpy(). */
39499  if( offset<pFile->mmapSize ){
39500  if( offset+amt <= pFile->mmapSize ){
39501  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
39502  OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39503  osGetCurrentProcessId(), pFile, pFile->h));
39504  return SQLITE_OK;
39505  }else{
39506  int nCopy = (int)(pFile->mmapSize - offset);
39507  memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
39508  pBuf = &((u8 *)pBuf)[nCopy];
39509  amt -= nCopy;
39510  offset += nCopy;
39511  }
39512  }
39513 #endif
39514 
39515 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39516  if( winSeekFile(pFile, offset) ){
39517  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39518  osGetCurrentProcessId(), pFile, pFile->h));
39519  return SQLITE_FULL;
39520  }
39521  while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
39522 #else
39523  memset(&overlapped, 0, sizeof(OVERLAPPED));
39524  overlapped.Offset = (LONG)(offset & 0xffffffff);
39525  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39526  while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
39527  osGetLastError()!=ERROR_HANDLE_EOF ){
39528 #endif
39529  DWORD lastErrno;
39530  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39531  pFile->lastErrno = lastErrno;
39532  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
39533  osGetCurrentProcessId(), pFile, pFile->h));
39534  return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
39535  "winRead", pFile->zPath);
39536  }
39537  winLogIoerr(nRetry, __LINE__);
39538  if( nRead<(DWORD)amt ){
39539  /* Unread parts of the buffer must be zero-filled */
39540  memset(&((char*)pBuf)[nRead], 0, amt-nRead);
39541  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
39542  osGetCurrentProcessId(), pFile, pFile->h));
39543  return SQLITE_IOERR_SHORT_READ;
39544  }
39545 
39546  OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39547  osGetCurrentProcessId(), pFile, pFile->h));
39548  return SQLITE_OK;
39549 }
39550 
39551 /*
39552 ** Write data from a buffer into a file. Return SQLITE_OK on success
39553 ** or some other error code on failure.
39554 */
39555 static int winWrite(
39556  sqlite3_file *id, /* File to write into */
39557  const void *pBuf, /* The bytes to be written */
39558  int amt, /* Number of bytes to write */
39559  sqlite3_int64 offset /* Offset into the file to begin writing at */
39560 ){
39561  int rc = 0; /* True if error has occurred, else false */
39562  winFile *pFile = (winFile*)id; /* File handle */
39563  int nRetry = 0; /* Number of retries */
39564 
39565  assert( amt>0 );
39566  assert( pFile );
39569 
39570  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
39571  "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
39572  pFile->h, pBuf, amt, offset, pFile->locktype));
39573 
39574 #if defined(SQLITE_MMAP_READWRITE) && SQLITE_MAX_MMAP_SIZE>0
39575  /* Deal with as much of this write request as possible by transfering
39576  ** data from the memory mapping using memcpy(). */
39577  if( offset<pFile->mmapSize ){
39578  if( offset+amt <= pFile->mmapSize ){
39579  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
39580  OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39581  osGetCurrentProcessId(), pFile, pFile->h));
39582  return SQLITE_OK;
39583  }else{
39584  int nCopy = (int)(pFile->mmapSize - offset);
39585  memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
39586  pBuf = &((u8 *)pBuf)[nCopy];
39587  amt -= nCopy;
39588  offset += nCopy;
39589  }
39590  }
39591 #endif
39592 
39593 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39594  rc = winSeekFile(pFile, offset);
39595  if( rc==0 ){
39596 #else
39597  {
39598 #endif
39599 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39600  OVERLAPPED overlapped; /* The offset for WriteFile. */
39601 #endif
39602  u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
39603  int nRem = amt; /* Number of bytes yet to be written */
39604  DWORD nWrite; /* Bytes written by each WriteFile() call */
39605  DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
39606 
39607 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39608  memset(&overlapped, 0, sizeof(OVERLAPPED));
39609  overlapped.Offset = (LONG)(offset & 0xffffffff);
39610  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39611 #endif
39612 
39613  while( nRem>0 ){
39614 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
39615  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
39616 #else
39617  if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
39618 #endif
39619  if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
39620  break;
39621  }
39622  assert( nWrite==0 || nWrite<=(DWORD)nRem );
39623  if( nWrite==0 || nWrite>(DWORD)nRem ){
39624  lastErrno = osGetLastError();
39625  break;
39626  }
39627 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
39628  offset += nWrite;
39629  overlapped.Offset = (LONG)(offset & 0xffffffff);
39630  overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
39631 #endif
39632  aRem += nWrite;
39633  nRem -= nWrite;
39634  }
39635  if( nRem>0 ){
39636  pFile->lastErrno = lastErrno;
39637  rc = 1;
39638  }
39639  }
39640 
39641  if( rc ){
39642  if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
39643  || ( pFile->lastErrno==ERROR_DISK_FULL )){
39644  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
39645  osGetCurrentProcessId(), pFile, pFile->h));
39646  return winLogError(SQLITE_FULL, pFile->lastErrno,
39647  "winWrite1", pFile->zPath);
39648  }
39649  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
39650  osGetCurrentProcessId(), pFile, pFile->h));
39651  return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
39652  "winWrite2", pFile->zPath);
39653  }else{
39654  winLogIoerr(nRetry, __LINE__);
39655  }
39656  OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39657  osGetCurrentProcessId(), pFile, pFile->h));
39658  return SQLITE_OK;
39659 }
39660 
39661 /*
39662 ** Truncate an open file to a specified size
39663 */
39664 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
39665  winFile *pFile = (winFile*)id; /* File handle object */
39666  int rc = SQLITE_OK; /* Return code for this function */
39667  DWORD lastErrno;
39668 
39669  assert( pFile );
39671  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
39672  osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
39673 
39674  /* If the user has configured a chunk-size for this file, truncate the
39675  ** file so that it consists of an integer number of chunks (i.e. the
39676  ** actual file size after the operation may be larger than the requested
39677  ** size).
39678  */
39679  if( pFile->szChunk>0 ){
39680  nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
39681  }
39682 
39683  /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
39684  if( winSeekFile(pFile, nByte) ){
39685  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39686  "winTruncate1", pFile->zPath);
39687  }else if( 0==osSetEndOfFile(pFile->h) &&
39688  ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
39689  pFile->lastErrno = lastErrno;
39690  rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
39691  "winTruncate2", pFile->zPath);
39692  }
39693 
39694 #if SQLITE_MAX_MMAP_SIZE>0
39695  /* If the file was truncated to a size smaller than the currently
39696  ** mapped region, reduce the effective mapping size as well. SQLite will
39697  ** use read() and write() to access data beyond this point from now on.
39698  */
39699  if( pFile->pMapRegion && nByte<pFile->mmapSize ){
39700  pFile->mmapSize = nByte;
39701  }
39702 #endif
39703 
39704  OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
39705  osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
39706  return rc;
39707 }
39708 
39709 #ifdef SQLITE_TEST
39710 /*
39711 ** Count the number of fullsyncs and normal syncs. This is used to test
39712 ** that syncs and fullsyncs are occuring at the right times.
39713 */
39714 SQLITE_API int sqlite3_sync_count = 0;
39715 SQLITE_API int sqlite3_fullsync_count = 0;
39716 #endif
39717 
39718 /*
39719 ** Make sure all writes to a particular file are committed to disk.
39720 */
39721 static int winSync(sqlite3_file *id, int flags){
39722 #ifndef SQLITE_NO_SYNC
39723  /*
39724  ** Used only when SQLITE_NO_SYNC is not defined.
39725  */
39726  BOOL rc;
39727 #endif
39728 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
39729  defined(SQLITE_HAVE_OS_TRACE)
39730  /*
39731  ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
39732  ** OSTRACE() macros.
39733  */
39734  winFile *pFile = (winFile*)id;
39735 #else
39736  UNUSED_PARAMETER(id);
39737 #endif
39738 
39739  assert( pFile );
39740  /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
39741  assert((flags&0x0F)==SQLITE_SYNC_NORMAL
39742  || (flags&0x0F)==SQLITE_SYNC_FULL
39743  );
39744 
39745  /* Unix cannot, but some systems may return SQLITE_FULL from here. This
39746  ** line is to test that doing so does not cause any problems.
39747  */
39748  SimulateDiskfullError( return SQLITE_FULL );
39749 
39750  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
39751  osGetCurrentProcessId(), pFile, pFile->h, flags,
39752  pFile->locktype));
39753 
39754 #ifndef SQLITE_TEST
39755  UNUSED_PARAMETER(flags);
39756 #else
39757  if( (flags&0x0F)==SQLITE_SYNC_FULL ){
39758  sqlite3_fullsync_count++;
39759  }
39760  sqlite3_sync_count++;
39761 #endif
39762 
39763  /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
39764  ** no-op
39765  */
39766 #ifdef SQLITE_NO_SYNC
39767  OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39768  osGetCurrentProcessId(), pFile, pFile->h));
39769  return SQLITE_OK;
39770 #else
39771 #if SQLITE_MAX_MMAP_SIZE>0
39772  if( pFile->pMapRegion ){
39773  if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
39774  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
39775  "rc=SQLITE_OK\n", osGetCurrentProcessId(),
39776  pFile, pFile->pMapRegion));
39777  }else{
39778  pFile->lastErrno = osGetLastError();
39779  OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
39780  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
39781  pFile, pFile->pMapRegion));
39782  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
39783  "winSync1", pFile->zPath);
39784  }
39785  }
39786 #endif
39787  rc = osFlushFileBuffers(pFile->h);
39788  SimulateIOError( rc=FALSE );
39789  if( rc ){
39790  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
39791  osGetCurrentProcessId(), pFile, pFile->h));
39792  return SQLITE_OK;
39793  }else{
39794  pFile->lastErrno = osGetLastError();
39795  OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
39796  osGetCurrentProcessId(), pFile, pFile->h));
39797  return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
39798  "winSync2", pFile->zPath);
39799  }
39800 #endif
39801 }
39802 
39803 /*
39804 ** Determine the current size of a file in bytes
39805 */
39806 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
39807  winFile *pFile = (winFile*)id;
39808  int rc = SQLITE_OK;
39809 
39810  assert( id!=0 );
39811  assert( pSize!=0 );
39813  OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
39814 
39815 #if SQLITE_OS_WINRT
39816  {
39817  FILE_STANDARD_INFO info;
39818  if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
39819  &info, sizeof(info)) ){
39820  *pSize = info.EndOfFile.QuadPart;
39821  }else{
39822  pFile->lastErrno = osGetLastError();
39823  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
39824  "winFileSize", pFile->zPath);
39825  }
39826  }
39827 #else
39828  {
39829  DWORD upperBits;
39830  DWORD lowerBits;
39831  DWORD lastErrno;
39832 
39833  lowerBits = osGetFileSize(pFile->h, &upperBits);
39834  *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
39835  if( (lowerBits == INVALID_FILE_SIZE)
39836  && ((lastErrno = osGetLastError())!=NO_ERROR) ){
39837  pFile->lastErrno = lastErrno;
39838  rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
39839  "winFileSize", pFile->zPath);
39840  }
39841  }
39842 #endif
39843  OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
39844  pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
39845  return rc;
39846 }
39847 
39848 /*
39849 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
39850 */
39851 #ifndef LOCKFILE_FAIL_IMMEDIATELY
39852 # define LOCKFILE_FAIL_IMMEDIATELY 1
39853 #endif
39854 
39855 #ifndef LOCKFILE_EXCLUSIVE_LOCK
39856 # define LOCKFILE_EXCLUSIVE_LOCK 2
39857 #endif
39858 
39859 /*
39860 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
39861 ** When the LockFile function was used, it was always expected to fail
39862 ** immediately if the lock could not be obtained. Also, it always expected to
39863 ** obtain an exclusive lock. These flags are used with the LockFileEx function
39864 ** and reflect those expectations; therefore, they should not be changed.
39865 */
39866 #ifndef SQLITE_LOCKFILE_FLAGS
39867 # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
39868  LOCKFILE_EXCLUSIVE_LOCK)
39869 #endif
39870 
39871 /*
39872 ** Currently, SQLite never calls the LockFileEx function without wanting the
39873 ** call to fail immediately if the lock cannot be obtained.
39874 */
39875 #ifndef SQLITE_LOCKFILEEX_FLAGS
39876 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
39877 #endif
39878 
39879 /*
39880 ** Acquire a reader lock.
39881 ** Different API routines are called depending on whether or not this
39882 ** is Win9x or WinNT.
39883 */
39884 static int winGetReadLock(winFile *pFile){
39885  int res;
39886  OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
39887  if( osIsNT() ){
39888 #if SQLITE_OS_WINCE
39889  /*
39890  ** NOTE: Windows CE is handled differently here due its lack of the Win32
39891  ** API LockFileEx.
39892  */
39893  res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
39894 #else
39895  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
39896  SHARED_SIZE, 0);
39897 #endif
39898  }
39899 #ifdef SQLITE_WIN32_HAS_ANSI
39900  else{
39901  int lk;
39902  sqlite3_randomness(sizeof(lk), &lk);
39903  pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
39904  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
39905  SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
39906  }
39907 #endif
39908  if( res == 0 ){
39909  pFile->lastErrno = osGetLastError();
39910  /* No need to log a failure to lock */
39911  }
39912  OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
39913  return res;
39914 }
39915 
39916 /*
39917 ** Undo a readlock
39918 */
39919 static int winUnlockReadLock(winFile *pFile){
39920  int res;
39921  DWORD lastErrno;
39922  OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
39923  if( osIsNT() ){
39924  res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
39925  }
39926 #ifdef SQLITE_WIN32_HAS_ANSI
39927  else{
39928  res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
39929  }
39930 #endif
39931  if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
39932  pFile->lastErrno = lastErrno;
39933  winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
39934  "winUnlockReadLock", pFile->zPath);
39935  }
39936  OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
39937  return res;
39938 }
39939 
39940 /*
39941 ** Lock the file with the lock specified by parameter locktype - one
39942 ** of the following:
39943 **
39944 ** (1) SHARED_LOCK
39945 ** (2) RESERVED_LOCK
39946 ** (3) PENDING_LOCK
39947 ** (4) EXCLUSIVE_LOCK
39948 **
39949 ** Sometimes when requesting one lock state, additional lock states
39950 ** are inserted in between. The locking might fail on one of the later
39951 ** transitions leaving the lock state different from what it started but
39952 ** still short of its goal. The following chart shows the allowed
39953 ** transitions and the inserted intermediate states:
39954 **
39955 ** UNLOCKED -> SHARED
39956 ** SHARED -> RESERVED
39957 ** SHARED -> (PENDING) -> EXCLUSIVE
39958 ** RESERVED -> (PENDING) -> EXCLUSIVE
39959 ** PENDING -> EXCLUSIVE
39960 **
39961 ** This routine will only increase a lock. The winUnlock() routine
39962 ** erases all locks at once and returns us immediately to locking level 0.
39963 ** It is not possible to lower the locking level one step at a time. You
39964 ** must go straight to locking level 0.
39965 */
39966 static int winLock(sqlite3_file *id, int locktype){
39967  int rc = SQLITE_OK; /* Return code from subroutines */
39968  int res = 1; /* Result of a Windows lock call */
39969  int newLocktype; /* Set pFile->locktype to this value before exiting */
39970  int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
39971  winFile *pFile = (winFile*)id;
39972  DWORD lastErrno = NO_ERROR;
39973 
39974  assert( id!=0 );
39975  OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
39976  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
39977 
39978  /* If there is already a lock of this type or more restrictive on the
39979  ** OsFile, do nothing. Don't use the end_lock: exit path, as
39980  ** sqlite3OsEnterMutex() hasn't been called yet.
39981  */
39982  if( pFile->locktype>=locktype ){
39983  OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
39984  return SQLITE_OK;
39985  }
39986 
39987  /* Do not allow any kind of write-lock on a read-only database
39988  */
39989  if( (pFile->ctrlFlags & WINFILE_RDONLY)!=0 && locktype>=RESERVED_LOCK ){
39990  return SQLITE_IOERR_LOCK;
39991  }
39992 
39993  /* Make sure the locking sequence is correct
39994  */
39995  assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
39996  assert( locktype!=PENDING_LOCK );
39997  assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
39998 
39999  /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
40000  ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
40001  ** the PENDING_LOCK byte is temporary.
40002  */
40003  newLocktype = pFile->locktype;
40004  if( pFile->locktype==NO_LOCK
40005  || (locktype==EXCLUSIVE_LOCK && pFile->locktype<=RESERVED_LOCK)
40006  ){
40007  int cnt = 3;
40008  while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
40009  PENDING_BYTE, 0, 1, 0))==0 ){
40010  /* Try 3 times to get the pending lock. This is needed to work
40011  ** around problems caused by indexing and/or anti-virus software on
40012  ** Windows systems.
40013  ** If you are using this code as a model for alternative VFSes, do not
40014  ** copy this retry logic. It is a hack intended for Windows only.
40015  */
40016  lastErrno = osGetLastError();
40017  OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
40018  pFile->h, cnt, res));
40019  if( lastErrno==ERROR_INVALID_HANDLE ){
40020  pFile->lastErrno = lastErrno;
40021  rc = SQLITE_IOERR_LOCK;
40022  OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
40023  pFile->h, cnt, sqlite3ErrName(rc)));
40024  return rc;
40025  }
40026  if( cnt ) sqlite3_win32_sleep(1);
40027  }
40028  gotPendingLock = res;
40029  if( !res ){
40030  lastErrno = osGetLastError();
40031  }
40032  }
40033 
40034  /* Acquire a shared lock
40035  */
40036  if( locktype==SHARED_LOCK && res ){
40037  assert( pFile->locktype==NO_LOCK );
40038  res = winGetReadLock(pFile);
40039  if( res ){
40040  newLocktype = SHARED_LOCK;
40041  }else{
40042  lastErrno = osGetLastError();
40043  }
40044  }
40045 
40046  /* Acquire a RESERVED lock
40047  */
40048  if( locktype==RESERVED_LOCK && res ){
40049  assert( pFile->locktype==SHARED_LOCK );
40050  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
40051  if( res ){
40052  newLocktype = RESERVED_LOCK;
40053  }else{
40054  lastErrno = osGetLastError();
40055  }
40056  }
40057 
40058  /* Acquire a PENDING lock
40059  */
40060  if( locktype==EXCLUSIVE_LOCK && res ){
40061  newLocktype = PENDING_LOCK;
40062  gotPendingLock = 0;
40063  }
40064 
40065  /* Acquire an EXCLUSIVE lock
40066  */
40067  if( locktype==EXCLUSIVE_LOCK && res ){
40068  assert( pFile->locktype>=SHARED_LOCK );
40069  res = winUnlockReadLock(pFile);
40070  res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
40071  SHARED_SIZE, 0);
40072  if( res ){
40073  newLocktype = EXCLUSIVE_LOCK;
40074  }else{
40075  lastErrno = osGetLastError();
40076  winGetReadLock(pFile);
40077  }
40078  }
40079 
40080  /* If we are holding a PENDING lock that ought to be released, then
40081  ** release it now.
40082  */
40083  if( gotPendingLock && locktype==SHARED_LOCK ){
40084  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40085  }
40086 
40087  /* Update the state of the lock has held in the file descriptor then
40088  ** return the appropriate result code.
40089  */
40090  if( res ){
40091  rc = SQLITE_OK;
40092  }else{
40093  pFile->lastErrno = lastErrno;
40094  rc = SQLITE_BUSY;
40095  OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
40096  pFile->h, locktype, newLocktype));
40097  }
40098  pFile->locktype = (u8)newLocktype;
40099  OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
40100  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40101  return rc;
40102 }
40103 
40104 /*
40105 ** This routine checks if there is a RESERVED lock held on the specified
40106 ** file by this or any other process. If such a lock is held, return
40107 ** non-zero, otherwise zero.
40108 */
40109 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
40110  int res;
40111  winFile *pFile = (winFile*)id;
40112 
40114  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
40115 
40116  assert( id!=0 );
40117  if( pFile->locktype>=RESERVED_LOCK ){
40118  res = 1;
40119  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
40120  }else{
40121  res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE,0,1,0);
40122  if( res ){
40123  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40124  }
40125  res = !res;
40126  OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
40127  }
40128  *pResOut = res;
40129  OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
40130  pFile->h, pResOut, *pResOut));
40131  return SQLITE_OK;
40132 }
40133 
40134 /*
40135 ** Lower the locking level on file descriptor id to locktype. locktype
40136 ** must be either NO_LOCK or SHARED_LOCK.
40137 **
40138 ** If the locking level of the file descriptor is already at or below
40139 ** the requested locking level, this routine is a no-op.
40140 **
40141 ** It is not possible for this routine to fail if the second argument
40142 ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
40143 ** might return SQLITE_IOERR;
40144 */
40145 static int winUnlock(sqlite3_file *id, int locktype){
40146  int type;
40147  winFile *pFile = (winFile*)id;
40148  int rc = SQLITE_OK;
40149  assert( pFile!=0 );
40150  assert( locktype<=SHARED_LOCK );
40151  OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
40152  pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
40153  type = pFile->locktype;
40154  if( type>=EXCLUSIVE_LOCK ){
40155  winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
40156  if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
40157  /* This should never happen. We should always be able to
40158  ** reacquire the read lock */
40159  rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
40160  "winUnlock", pFile->zPath);
40161  }
40162  }
40163  if( type>=RESERVED_LOCK ){
40164  winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
40165  }
40166  if( locktype==NO_LOCK && type>=SHARED_LOCK ){
40167  winUnlockReadLock(pFile);
40168  }
40169  if( type>=PENDING_LOCK ){
40170  winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
40171  }
40172  pFile->locktype = (u8)locktype;
40173  OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
40174  pFile->h, pFile->locktype, sqlite3ErrName(rc)));
40175  return rc;
40176 }
40177 
40178 /*
40179 ** If *pArg is initially negative then this is a query. Set *pArg to
40180 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
40181 **
40182 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
40183 */
40184 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
40185  if( *pArg<0 ){
40186  *pArg = (pFile->ctrlFlags & mask)!=0;
40187  }else if( (*pArg)==0 ){
40188  pFile->ctrlFlags &= ~mask;
40189  }else{
40190  pFile->ctrlFlags |= mask;
40191  }
40192 }
40193 
40194 /* Forward references to VFS helper methods used for temporary files */
40195 static int winGetTempname(sqlite3_vfs *, char **);
40196 static int winIsDir(const void *);
40197 static BOOL winIsDriveLetterAndColon(const char *);
40198 
40199 /*
40200 ** Control and query of the open file handle.
40201 */
40202 static int winFileControl(sqlite3_file *id, int op, void *pArg){
40203  winFile *pFile = (winFile*)id;
40204  OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
40205  switch( op ){
40206  case SQLITE_FCNTL_LOCKSTATE: {
40207  *(int*)pArg = pFile->locktype;
40208  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40209  return SQLITE_OK;
40210  }
40211  case SQLITE_FCNTL_LAST_ERRNO: {
40212  *(int*)pArg = (int)pFile->lastErrno;
40213  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40214  return SQLITE_OK;
40215  }
40216  case SQLITE_FCNTL_CHUNK_SIZE: {
40217  pFile->szChunk = *(int *)pArg;
40218  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40219  return SQLITE_OK;
40220  }
40221  case SQLITE_FCNTL_SIZE_HINT: {
40222  if( pFile->szChunk>0 ){
40223  sqlite3_int64 oldSz;
40224  int rc = winFileSize(id, &oldSz);
40225  if( rc==SQLITE_OK ){
40226  sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
40227  if( newSz>oldSz ){
40229  rc = winTruncate(id, newSz);
40231  }
40232  }
40233  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40234  return rc;
40235  }
40236  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40237  return SQLITE_OK;
40238  }
40239  case SQLITE_FCNTL_PERSIST_WAL: {
40240  winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
40241  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40242  return SQLITE_OK;
40243  }
40245  winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
40246  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40247  return SQLITE_OK;
40248  }
40249  case SQLITE_FCNTL_VFSNAME: {
40250  *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
40251  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40252  return SQLITE_OK;
40253  }
40255  int *a = (int*)pArg;
40256  if( a[0]>0 ){
40257  winIoerrRetry = a[0];
40258  }else{
40259  a[0] = winIoerrRetry;
40260  }
40261  if( a[1]>0 ){
40262  winIoerrRetryDelay = a[1];
40263  }else{
40264  a[1] = winIoerrRetryDelay;
40265  }
40266  OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
40267  return SQLITE_OK;
40268  }
40269 #ifdef SQLITE_TEST
40271  LPHANDLE phFile = (LPHANDLE)pArg;
40272  HANDLE hOldFile = pFile->h;
40273  pFile->h = *phFile;
40274  *phFile = hOldFile;
40275  OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
40276  hOldFile, pFile->h));
40277  return SQLITE_OK;
40278  }
40279 #endif
40281  char *zTFile = 0;
40282  int rc = winGetTempname(pFile->pVfs, &zTFile);
40283  if( rc==SQLITE_OK ){
40284  *(char**)pArg = zTFile;
40285  }
40286  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40287  return rc;
40288  }
40289 #if SQLITE_MAX_MMAP_SIZE>0
40290  case SQLITE_FCNTL_MMAP_SIZE: {
40291  i64 newLimit = *(i64*)pArg;
40292  int rc = SQLITE_OK;
40293  if( newLimit>sqlite3GlobalConfig.mxMmap ){
40294  newLimit = sqlite3GlobalConfig.mxMmap;
40295  }
40296  *(i64*)pArg = pFile->mmapSizeMax;
40297  if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
40298  pFile->mmapSizeMax = newLimit;
40299  if( pFile->mmapSize>0 ){
40300  winUnmapfile(pFile);
40301  rc = winMapfile(pFile, -1);
40302  }
40303  }
40304  OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
40305  return rc;
40306  }
40307 #endif
40308  }
40309  OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
40310  return SQLITE_NOTFOUND;
40311 }
40312 
40313 /*
40314 ** Return the sector size in bytes of the underlying block device for
40315 ** the specified file. This is almost always 512 bytes, but may be
40316 ** larger for some devices.
40317 **
40318 ** SQLite code assumes this function cannot fail. It also assumes that
40319 ** if two files are created in the same file-system directory (i.e.
40320 ** a database and its journal file) that the sector size will be the
40321 ** same for both.
40322 */
40323 static int winSectorSize(sqlite3_file *id){
40324  (void)id;
40326 }
40327 
40328 /*
40329 ** Return a vector of device characteristics.
40330 */
40331 static int winDeviceCharacteristics(sqlite3_file *id){
40332  winFile *p = (winFile*)id;
40334  ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
40335 }
40336 
40337 /*
40338 ** Windows will only let you create file view mappings
40339 ** on allocation size granularity boundaries.
40340 ** During sqlite3_os_init() we do a GetSystemInfo()
40341 ** to get the granularity size.
40342 */
40343 static SYSTEM_INFO winSysInfo;
40344 
40345 #ifndef SQLITE_OMIT_WAL
40346 
40347 /*
40348 ** Helper functions to obtain and relinquish the global mutex. The
40349 ** global mutex is used to protect the winLockInfo objects used by
40350 ** this file, all of which may be shared by multiple threads.
40351 **
40352 ** Function winShmMutexHeld() is used to assert() that the global mutex
40353 ** is held when required. This function is only used as part of assert()
40354 ** statements. e.g.
40355 **
40356 ** winShmEnterMutex()
40357 ** assert( winShmMutexHeld() );
40358 ** winShmLeaveMutex()
40359 */
40360 static void winShmEnterMutex(void){
40362 }
40363 static void winShmLeaveMutex(void){
40365 }
40366 #ifndef NDEBUG
40367 static int winShmMutexHeld(void) {
40369 }
40370 #endif
40371 
40372 /*
40373 ** Object used to represent a single file opened and mmapped to provide
40374 ** shared memory. When multiple threads all reference the same
40375 ** log-summary, each thread has its own winFile object, but they all
40376 ** point to a single instance of this object. In other words, each
40377 ** log-summary is opened only once per process.
40378 **
40379 ** winShmMutexHeld() must be true when creating or destroying
40380 ** this object or while reading or writing the following fields:
40381 **
40382 ** nRef
40383 ** pNext
40384 **
40385 ** The following fields are read-only after the object is created:
40386 **
40387 ** fid
40388 ** zFilename
40389 **
40390 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
40391 ** winShmMutexHeld() is true when reading or writing any other field
40392 ** in this structure.
40393 **
40394 */
40395 struct winShmNode {
40396  sqlite3_mutex *mutex; /* Mutex to access this object */
40397  char *zFilename; /* Name of the file */
40398  winFile hFile; /* File handle from winOpen */
40399 
40400  int szRegion; /* Size of shared-memory regions */
40401  int nRegion; /* Size of array apRegion */
40402  struct ShmRegion {
40403  HANDLE hMap; /* File handle from CreateFileMapping */
40404  void *pMap;
40405  } *aRegion;
40406  DWORD lastErrno; /* The Windows errno from the last I/O error */
40407 
40408  int nRef; /* Number of winShm objects pointing to this */
40409  winShm *pFirst; /* All winShm objects pointing to this */
40410  winShmNode *pNext; /* Next in list of all winShmNode objects */
40411 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40412  u8 nextShmId; /* Next available winShm.id value */
40413 #endif
40414 };
40415 
40416 /*
40417 ** A global array of all winShmNode objects.
40418 **
40419 ** The winShmMutexHeld() must be true while reading or writing this list.
40420 */
40421 static winShmNode *winShmNodeList = 0;
40422 
40423 /*
40424 ** Structure used internally by this VFS to record the state of an
40425 ** open shared memory connection.
40426 **
40427 ** The following fields are initialized when this object is created and
40428 ** are read-only thereafter:
40429 **
40430 ** winShm.pShmNode
40431 ** winShm.id
40432 **
40433 ** All other fields are read/write. The winShm.pShmNode->mutex must be held
40434 ** while accessing any read/write fields.
40435 */
40436 struct winShm {
40437  winShmNode *pShmNode; /* The underlying winShmNode object */
40438  winShm *pNext; /* Next winShm with the same winShmNode */
40439  u8 hasMutex; /* True if holding the winShmNode mutex */
40440  u16 sharedMask; /* Mask of shared locks held */
40441  u16 exclMask; /* Mask of exclusive locks held */
40442 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40443  u8 id; /* Id of this connection with its winShmNode */
40444 #endif
40445 };
40446 
40447 /*
40448 ** Constants used for locking
40449 */
40450 #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
40451 #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
40452 
40453 /*
40454 ** Apply advisory locks for all n bytes beginning at ofst.
40455 */
40456 #define _SHM_UNLCK 1
40457 #define _SHM_RDLCK 2
40458 #define _SHM_WRLCK 3
40459 static int winShmSystemLock(
40460  winShmNode *pFile, /* Apply locks to this open shared-memory segment */
40461  int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
40462  int ofst, /* Offset to first byte to be locked/unlocked */
40463  int nByte /* Number of bytes to lock or unlock */
40464 ){
40465  int rc = 0; /* Result code form Lock/UnlockFileEx() */
40466 
40467  /* Access to the winShmNode object is serialized by the caller */
40468  assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
40469 
40470  OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
40471  pFile->hFile.h, lockType, ofst, nByte));
40472 
40473  /* Release/Acquire the system-level lock */
40474  if( lockType==_SHM_UNLCK ){
40475  rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
40476  }else{
40477  /* Initialize the locking parameters */
40478  DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
40479  if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
40480  rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
40481  }
40482 
40483  if( rc!= 0 ){
40484  rc = SQLITE_OK;
40485  }else{
40486  pFile->lastErrno = osGetLastError();
40487  rc = SQLITE_BUSY;
40488  }
40489 
40490  OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
40491  pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
40492  "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
40493 
40494  return rc;
40495 }
40496 
40497 /* Forward references to VFS methods */
40498 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
40499 static int winDelete(sqlite3_vfs *,const char*,int);
40500 
40501 /*
40502 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
40503 **
40504 ** This is not a VFS shared-memory method; it is a utility function called
40505 ** by VFS shared-memory methods.
40506 */
40507 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
40508  winShmNode **pp;
40509  winShmNode *p;
40510  assert( winShmMutexHeld() );
40511  OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
40512  osGetCurrentProcessId(), deleteFlag));
40513  pp = &winShmNodeList;
40514  while( (p = *pp)!=0 ){
40515  if( p->nRef==0 ){
40516  int i;
40517  if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
40518  for(i=0; i<p->nRegion; i++){
40519  BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
40520  OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
40521  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40522  UNUSED_VARIABLE_VALUE(bRc);
40523  bRc = osCloseHandle(p->aRegion[i].hMap);
40524  OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
40525  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
40526  UNUSED_VARIABLE_VALUE(bRc);
40527  }
40528  if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
40530  winClose((sqlite3_file *)&p->hFile);
40532  }
40533  if( deleteFlag ){
40536  winDelete(pVfs, p->zFilename, 0);
40539  }
40540  *pp = p->pNext;
40541  sqlite3_free(p->aRegion);
40542  sqlite3_free(p);
40543  }else{
40544  pp = &p->pNext;
40545  }
40546  }
40547 }
40548 
40549 /*
40550 ** Open the shared-memory area associated with database file pDbFd.
40551 **
40552 ** When opening a new shared-memory file, if no other instances of that
40553 ** file are currently open, in this process or in other processes, then
40554 ** the file must be truncated to zero length or have its header cleared.
40555 */
40556 static int winOpenSharedMemory(winFile *pDbFd){
40557  struct winShm *p; /* The connection to be opened */
40558  struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
40559  int rc; /* Result code */
40560  struct winShmNode *pNew; /* Newly allocated winShmNode */
40561  int nName; /* Size of zName in bytes */
40562 
40563  assert( pDbFd->pShm==0 ); /* Not previously opened */
40564 
40565  /* Allocate space for the new sqlite3_shm object. Also speculatively
40566  ** allocate space for a new winShmNode and filename.
40567  */
40568  p = sqlite3MallocZero( sizeof(*p) );
40569  if( p==0 ) return SQLITE_IOERR_NOMEM_BKPT;
40570  nName = sqlite3Strlen30(pDbFd->zPath);
40571  pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
40572  if( pNew==0 ){
40573  sqlite3_free(p);
40574  return SQLITE_IOERR_NOMEM_BKPT;
40575  }
40576  pNew->zFilename = (char*)&pNew[1];
40577  sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
40578  sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
40579 
40580  /* Look to see if there is an existing winShmNode that can be used.
40581  ** If no matching winShmNode currently exists, create a new one.
40582  */
40583  winShmEnterMutex();
40584  for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
40585  /* TBD need to come up with better match here. Perhaps
40586  ** use FILE_ID_BOTH_DIR_INFO Structure.
40587  */
40588  if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
40589  }
40590  if( pShmNode ){
40591  sqlite3_free(pNew);
40592  }else{
40593  pShmNode = pNew;
40594  pNew = 0;
40595  ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
40596  pShmNode->pNext = winShmNodeList;
40597  winShmNodeList = pShmNode;
40598 
40599  if( sqlite3GlobalConfig.bCoreMutex ){
40600  pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
40601  if( pShmNode->mutex==0 ){
40603  goto shm_open_err;
40604  }
40605  }
40606 
40607  rc = winOpen(pDbFd->pVfs,
40608  pShmNode->zFilename, /* Name of the file (UTF-8) */
40609  (sqlite3_file*)&pShmNode->hFile, /* File handle here */
40611  0);
40612  if( SQLITE_OK!=rc ){
40613  goto shm_open_err;
40614  }
40615 
40616  /* Check to see if another process is holding the dead-man switch.
40617  ** If not, truncate the file to zero length.
40618  */
40619  if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
40620  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
40621  if( rc!=SQLITE_OK ){
40622  rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
40623  "winOpenShm", pDbFd->zPath);
40624  }
40625  }
40626  if( rc==SQLITE_OK ){
40627  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
40628  rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
40629  }
40630  if( rc ) goto shm_open_err;
40631  }
40632 
40633  /* Make the new connection a child of the winShmNode */
40634  p->pShmNode = pShmNode;
40635 #if defined(SQLITE_DEBUG) || defined(SQLITE_HAVE_OS_TRACE)
40636  p->id = pShmNode->nextShmId++;
40637 #endif
40638  pShmNode->nRef++;
40639  pDbFd->pShm = p;
40640  winShmLeaveMutex();
40641 
40642  /* The reference count on pShmNode has already been incremented under
40643  ** the cover of the winShmEnterMutex() mutex and the pointer from the
40644  ** new (struct winShm) object to the pShmNode has been set. All that is
40645  ** left to do is to link the new object into the linked list starting
40646  ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
40647  ** mutex.
40648  */
40649  sqlite3_mutex_enter(pShmNode->mutex);
40650  p->pNext = pShmNode->pFirst;
40651  pShmNode->pFirst = p;
40652  sqlite3_mutex_leave(pShmNode->mutex);
40653  return SQLITE_OK;
40654 
40655  /* Jump here on any error */
40656 shm_open_err:
40657  winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
40658  winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
40659  sqlite3_free(p);
40660  sqlite3_free(pNew);
40661  winShmLeaveMutex();
40662  return rc;
40663 }
40664 
40665 /*
40666 ** Close a connection to shared-memory. Delete the underlying
40667 ** storage if deleteFlag is true.
40668 */
40669 static int winShmUnmap(
40670  sqlite3_file *fd, /* Database holding shared memory */
40671  int deleteFlag /* Delete after closing if true */
40672 ){
40673  winFile *pDbFd; /* Database holding shared-memory */
40674  winShm *p; /* The connection to be closed */
40675  winShmNode *pShmNode; /* The underlying shared-memory file */
40676  winShm **pp; /* For looping over sibling connections */
40677 
40678  pDbFd = (winFile*)fd;
40679  p = pDbFd->pShm;
40680  if( p==0 ) return SQLITE_OK;
40681  pShmNode = p->pShmNode;
40682 
40683  /* Remove connection p from the set of connections associated
40684  ** with pShmNode */
40685  sqlite3_mutex_enter(pShmNode->mutex);
40686  for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
40687  *pp = p->pNext;
40688 
40689  /* Free the connection p */
40690  sqlite3_free(p);
40691  pDbFd->pShm = 0;
40692  sqlite3_mutex_leave(pShmNode->mutex);
40693 
40694  /* If pShmNode->nRef has reached 0, then close the underlying
40695  ** shared-memory file, too */
40696  winShmEnterMutex();
40697  assert( pShmNode->nRef>0 );
40698  pShmNode->nRef--;
40699  if( pShmNode->nRef==0 ){
40700  winShmPurge(pDbFd->pVfs, deleteFlag);
40701  }
40702  winShmLeaveMutex();
40703 
40704  return SQLITE_OK;
40705 }
40706 
40707 /*
40708 ** Change the lock state for a shared-memory segment.
40709 */
40710 static int winShmLock(
40711  sqlite3_file *fd, /* Database file holding the shared memory */
40712  int ofst, /* First lock to acquire or release */
40713  int n, /* Number of locks to acquire or release */
40714  int flags /* What to do with the lock */
40715 ){
40716  winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
40717  winShm *p = pDbFd->pShm; /* The shared memory being locked */
40718  winShm *pX; /* For looping over all siblings */
40719  winShmNode *pShmNode = p->pShmNode;
40720  int rc = SQLITE_OK; /* Result code */
40721  u16 mask; /* Mask of locks to take or release */
40722 
40723  assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
40724  assert( n>=1 );
40727  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
40728  || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
40729  assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
40730 
40731  mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
40732  assert( n>1 || mask==(1<<ofst) );
40733  sqlite3_mutex_enter(pShmNode->mutex);
40734  if( flags & SQLITE_SHM_UNLOCK ){
40735  u16 allMask = 0; /* Mask of locks held by siblings */
40736 
40737  /* See if any siblings hold this same lock */
40738  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
40739  if( pX==p ) continue;
40740  assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
40741  allMask |= pX->sharedMask;
40742  }
40743 
40744  /* Unlock the system-level locks */
40745  if( (mask & allMask)==0 ){
40746  rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
40747  }else{
40748  rc = SQLITE_OK;
40749  }
40750 
40751  /* Undo the local locks */
40752  if( rc==SQLITE_OK ){
40753  p->exclMask &= ~mask;
40754  p->sharedMask &= ~mask;
40755  }
40756  }else if( flags & SQLITE_SHM_SHARED ){
40757  u16 allShared = 0; /* Union of locks held by connections other than "p" */
40758 
40759  /* Find out which shared locks are already held by sibling connections.
40760  ** If any sibling already holds an exclusive lock, go ahead and return
40761  ** SQLITE_BUSY.
40762  */
40763  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
40764  if( (pX->exclMask & mask)!=0 ){
40765  rc = SQLITE_BUSY;
40766  break;
40767  }
40768  allShared |= pX->sharedMask;
40769  }
40770 
40771  /* Get shared locks at the system level, if necessary */
40772  if( rc==SQLITE_OK ){
40773  if( (allShared & mask)==0 ){
40774  rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
40775  }else{
40776  rc = SQLITE_OK;
40777  }
40778  }
40779 
40780  /* Get the local shared locks */
40781  if( rc==SQLITE_OK ){
40782  p->sharedMask |= mask;
40783  }
40784  }else{
40785  /* Make sure no sibling connections hold locks that will block this
40786  ** lock. If any do, return SQLITE_BUSY right away.
40787  */
40788  for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
40789  if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
40790  rc = SQLITE_BUSY;
40791  break;
40792  }
40793  }
40794 
40795  /* Get the exclusive locks at the system level. Then if successful
40796  ** also mark the local connection as being locked.
40797  */
40798  if( rc==SQLITE_OK ){
40799  rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
40800  if( rc==SQLITE_OK ){
40801  assert( (p->sharedMask & mask)==0 );
40802  p->exclMask |= mask;
40803  }
40804  }
40805  }
40806  sqlite3_mutex_leave(pShmNode->mutex);
40807  OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
40808  osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
40809  sqlite3ErrName(rc)));
40810  return rc;
40811 }
40812 
40813 /*
40814 ** Implement a memory barrier or memory fence on shared memory.
40815 **
40816 ** All loads and stores begun before the barrier must complete before
40817 ** any load or store begun after the barrier.
40818 */
40819 static void winShmBarrier(
40820  sqlite3_file *fd /* Database holding the shared memory */
40821 ){
40822  UNUSED_PARAMETER(fd);
40823  sqlite3MemoryBarrier(); /* compiler-defined memory barrier */
40824  winShmEnterMutex(); /* Also mutex, for redundancy */
40825  winShmLeaveMutex();
40826 }
40827 
40828 /*
40829 ** This function is called to obtain a pointer to region iRegion of the
40830 ** shared-memory associated with the database file fd. Shared-memory regions
40831 ** are numbered starting from zero. Each shared-memory region is szRegion
40832 ** bytes in size.
40833 **
40834 ** If an error occurs, an error code is returned and *pp is set to NULL.
40835 **
40836 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
40837 ** region has not been allocated (by any client, including one running in a
40838 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
40839 ** isWrite is non-zero and the requested shared-memory region has not yet
40840 ** been allocated, it is allocated by this function.
40841 **
40842 ** If the shared-memory region has already been allocated or is allocated by
40843 ** this call as described above, then it is mapped into this processes
40844 ** address space (if it is not already), *pp is set to point to the mapped
40845 ** memory and SQLITE_OK returned.
40846 */
40847 static int winShmMap(
40848  sqlite3_file *fd, /* Handle open on database file */
40849  int iRegion, /* Region to retrieve */
40850  int szRegion, /* Size of regions */
40851  int isWrite, /* True to extend file if necessary */
40852  void volatile **pp /* OUT: Mapped memory */
40853 ){
40854  winFile *pDbFd = (winFile*)fd;
40855  winShm *pShm = pDbFd->pShm;
40856  winShmNode *pShmNode;
40857  int rc = SQLITE_OK;
40858 
40859  if( !pShm ){
40860  rc = winOpenSharedMemory(pDbFd);
40861  if( rc!=SQLITE_OK ) return rc;
40862  pShm = pDbFd->pShm;
40863  }
40864  pShmNode = pShm->pShmNode;
40865 
40866  sqlite3_mutex_enter(pShmNode->mutex);
40867  assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
40868 
40869  if( pShmNode->nRegion<=iRegion ){
40870  struct ShmRegion *apNew; /* New aRegion[] array */
40871  int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
40872  sqlite3_int64 sz; /* Current size of wal-index file */
40873 
40874  pShmNode->szRegion = szRegion;
40875 
40876  /* The requested region is not mapped into this processes address space.
40877  ** Check to see if it has been allocated (i.e. if the wal-index file is
40878  ** large enough to contain the requested region).
40879  */
40880  rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
40881  if( rc!=SQLITE_OK ){
40882  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
40883  "winShmMap1", pDbFd->zPath);
40884  goto shmpage_out;
40885  }
40886 
40887  if( sz<nByte ){
40888  /* The requested memory region does not exist. If isWrite is set to
40889  ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
40890  **
40891  ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
40892  ** the requested memory region.
40893  */
40894  if( !isWrite ) goto shmpage_out;
40895  rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
40896  if( rc!=SQLITE_OK ){
40897  rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
40898  "winShmMap2", pDbFd->zPath);
40899  goto shmpage_out;
40900  }
40901  }
40902 
40903  /* Map the requested memory region into this processes address space. */
40904  apNew = (struct ShmRegion *)sqlite3_realloc64(
40905  pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
40906  );
40907  if( !apNew ){
40909  goto shmpage_out;
40910  }
40911  pShmNode->aRegion = apNew;
40912 
40913  while( pShmNode->nRegion<=iRegion ){
40914  HANDLE hMap = NULL; /* file-mapping handle */
40915  void *pMap = 0; /* Mapped memory region */
40916 
40917 #if SQLITE_OS_WINRT
40918  hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
40919  NULL, PAGE_READWRITE, nByte, NULL
40920  );
40921 #elif defined(SQLITE_WIN32_HAS_WIDE)
40922  hMap = osCreateFileMappingW(pShmNode->hFile.h,
40923  NULL, PAGE_READWRITE, 0, nByte, NULL
40924  );
40925 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
40926  hMap = osCreateFileMappingA(pShmNode->hFile.h,
40927  NULL, PAGE_READWRITE, 0, nByte, NULL
40928  );
40929 #endif
40930  OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
40931  osGetCurrentProcessId(), pShmNode->nRegion, nByte,
40932  hMap ? "ok" : "failed"));
40933  if( hMap ){
40934  int iOffset = pShmNode->nRegion*szRegion;
40935  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
40936 #if SQLITE_OS_WINRT
40937  pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
40938  iOffset - iOffsetShift, szRegion + iOffsetShift
40939  );
40940 #else
40941  pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
40942  0, iOffset - iOffsetShift, szRegion + iOffsetShift
40943  );
40944 #endif
40945  OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
40946  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
40947  szRegion, pMap ? "ok" : "failed"));
40948  }
40949  if( !pMap ){
40950  pShmNode->lastErrno = osGetLastError();
40951  rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
40952  "winShmMap3", pDbFd->zPath);
40953  if( hMap ) osCloseHandle(hMap);
40954  goto shmpage_out;
40955  }
40956 
40957  pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
40958  pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
40959  pShmNode->nRegion++;
40960  }
40961  }
40962 
40963 shmpage_out:
40964  if( pShmNode->nRegion>iRegion ){
40965  int iOffset = iRegion*szRegion;
40966  int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
40967  char *p = (char *)pShmNode->aRegion[iRegion].pMap;
40968  *pp = (void *)&p[iOffsetShift];
40969  }else{
40970  *pp = 0;
40971  }
40972  sqlite3_mutex_leave(pShmNode->mutex);
40973  return rc;
40974 }
40975 
40976 #else
40977 # define winShmMap 0
40978 # define winShmLock 0
40979 # define winShmBarrier 0
40980 # define winShmUnmap 0
40981 #endif /* #ifndef SQLITE_OMIT_WAL */
40982 
40983 /*
40984 ** Cleans up the mapped region of the specified file, if any.
40985 */
40986 #if SQLITE_MAX_MMAP_SIZE>0
40987 static int winUnmapfile(winFile *pFile){
40988  assert( pFile!=0 );
40989  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
40990  "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
40991  osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
40992  pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
40993  if( pFile->pMapRegion ){
40994  if( !osUnmapViewOfFile(pFile->pMapRegion) ){
40995  pFile->lastErrno = osGetLastError();
40996  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
40997  "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
40998  pFile->pMapRegion));
40999  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41000  "winUnmapfile1", pFile->zPath);
41001  }
41002  pFile->pMapRegion = 0;
41003  pFile->mmapSize = 0;
41004  pFile->mmapSizeActual = 0;
41005  }
41006  if( pFile->hMap!=NULL ){
41007  if( !osCloseHandle(pFile->hMap) ){
41008  pFile->lastErrno = osGetLastError();
41009  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
41010  osGetCurrentProcessId(), pFile, pFile->hMap));
41011  return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
41012  "winUnmapfile2", pFile->zPath);
41013  }
41014  pFile->hMap = NULL;
41015  }
41016  OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41017  osGetCurrentProcessId(), pFile));
41018  return SQLITE_OK;
41019 }
41020 
41021 /*
41022 ** Memory map or remap the file opened by file-descriptor pFd (if the file
41023 ** is already mapped, the existing mapping is replaced by the new). Or, if
41024 ** there already exists a mapping for this file, and there are still
41025 ** outstanding xFetch() references to it, this function is a no-op.
41026 **
41027 ** If parameter nByte is non-negative, then it is the requested size of
41028 ** the mapping to create. Otherwise, if nByte is less than zero, then the
41029 ** requested size is the size of the file on disk. The actual size of the
41030 ** created mapping is either the requested size or the value configured
41031 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
41032 **
41033 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
41034 ** recreated as a result of outstanding references) or an SQLite error
41035 ** code otherwise.
41036 */
41037 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
41038  sqlite3_int64 nMap = nByte;
41039  int rc;
41040 
41041  assert( nMap>=0 || pFd->nFetchOut==0 );
41042  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
41043  osGetCurrentProcessId(), pFd, nByte));
41044 
41045  if( pFd->nFetchOut>0 ) return SQLITE_OK;
41046 
41047  if( nMap<0 ){
41048  rc = winFileSize((sqlite3_file*)pFd, &nMap);
41049  if( rc ){
41050  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
41051  osGetCurrentProcessId(), pFd));
41052  return SQLITE_IOERR_FSTAT;
41053  }
41054  }
41055  if( nMap>pFd->mmapSizeMax ){
41056  nMap = pFd->mmapSizeMax;
41057  }
41058  nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
41059 
41060  if( nMap==0 && pFd->mmapSize>0 ){
41061  winUnmapfile(pFd);
41062  }
41063  if( nMap!=pFd->mmapSize ){
41064  void *pNew = 0;
41065  DWORD protect = PAGE_READONLY;
41066  DWORD flags = FILE_MAP_READ;
41067 
41068  winUnmapfile(pFd);
41069 #ifdef SQLITE_MMAP_READWRITE
41070  if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
41071  protect = PAGE_READWRITE;
41072  flags |= FILE_MAP_WRITE;
41073  }
41074 #endif
41075 #if SQLITE_OS_WINRT
41076  pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
41077 #elif defined(SQLITE_WIN32_HAS_WIDE)
41078  pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
41079  (DWORD)((nMap>>32) & 0xffffffff),
41080  (DWORD)(nMap & 0xffffffff), NULL);
41081 #elif defined(SQLITE_WIN32_HAS_ANSI) && SQLITE_WIN32_CREATEFILEMAPPINGA
41082  pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
41083  (DWORD)((nMap>>32) & 0xffffffff),
41084  (DWORD)(nMap & 0xffffffff), NULL);
41085 #endif
41086  if( pFd->hMap==NULL ){
41087  pFd->lastErrno = osGetLastError();
41088  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41089  "winMapfile1", pFd->zPath);
41090  /* Log the error, but continue normal operation using xRead/xWrite */
41091  OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
41092  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41093  return SQLITE_OK;
41094  }
41095  assert( (nMap % winSysInfo.dwPageSize)==0 );
41096  assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
41097 #if SQLITE_OS_WINRT
41098  pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
41099 #else
41100  pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
41101 #endif
41102  if( pNew==NULL ){
41103  osCloseHandle(pFd->hMap);
41104  pFd->hMap = NULL;
41105  pFd->lastErrno = osGetLastError();
41106  rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
41107  "winMapfile2", pFd->zPath);
41108  /* Log the error, but continue normal operation using xRead/xWrite */
41109  OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
41110  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41111  return SQLITE_OK;
41112  }
41113  pFd->pMapRegion = pNew;
41114  pFd->mmapSize = nMap;
41115  pFd->mmapSizeActual = nMap;
41116  }
41117 
41118  OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41119  osGetCurrentProcessId(), pFd));
41120  return SQLITE_OK;
41121 }
41122 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
41123 
41124 /*
41125 ** If possible, return a pointer to a mapping of file fd starting at offset
41126 ** iOff. The mapping must be valid for at least nAmt bytes.
41127 **
41128 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
41129 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
41130 ** Finally, if an error does occur, return an SQLite error code. The final
41131 ** value of *pp is undefined in this case.
41132 **
41133 ** If this function does return a pointer, the caller must eventually
41134 ** release the reference by calling winUnfetch().
41135 */
41136 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
41137 #if SQLITE_MAX_MMAP_SIZE>0
41138  winFile *pFd = (winFile*)fd; /* The underlying database file */
41139 #endif
41140  *pp = 0;
41141 
41142  OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
41143  osGetCurrentProcessId(), fd, iOff, nAmt, pp));
41144 
41145 #if SQLITE_MAX_MMAP_SIZE>0
41146  if( pFd->mmapSizeMax>0 ){
41147  if( pFd->pMapRegion==0 ){
41148  int rc = winMapfile(pFd, -1);
41149  if( rc!=SQLITE_OK ){
41150  OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
41151  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
41152  return rc;
41153  }
41154  }
41155  if( pFd->mmapSize >= iOff+nAmt ){
41156  *pp = &((u8 *)pFd->pMapRegion)[iOff];
41157  pFd->nFetchOut++;
41158  }
41159  }
41160 #endif
41161 
41162  OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
41163  osGetCurrentProcessId(), fd, pp, *pp));
41164  return SQLITE_OK;
41165 }
41166 
41167 /*
41168 ** If the third argument is non-NULL, then this function releases a
41169 ** reference obtained by an earlier call to winFetch(). The second
41170 ** argument passed to this function must be the same as the corresponding
41171 ** argument that was passed to the winFetch() invocation.
41172 **
41173 ** Or, if the third argument is NULL, then this function is being called
41174 ** to inform the VFS layer that, according to POSIX, any existing mapping
41175 ** may now be invalid and should be unmapped.
41176 */
41177 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
41178 #if SQLITE_MAX_MMAP_SIZE>0
41179  winFile *pFd = (winFile*)fd; /* The underlying database file */
41180 
41181  /* If p==0 (unmap the entire file) then there must be no outstanding
41182  ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
41183  ** then there must be at least one outstanding. */
41184  assert( (p==0)==(pFd->nFetchOut==0) );
41185 
41186  /* If p!=0, it must match the iOff value. */
41187  assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
41188 
41189  OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
41190  osGetCurrentProcessId(), pFd, iOff, p));
41191 
41192  if( p ){
41193  pFd->nFetchOut--;
41194  }else{
41195  /* FIXME: If Windows truly always prevents truncating or deleting a
41196  ** file while a mapping is held, then the following winUnmapfile() call
41197  ** is unnecessary can be omitted - potentially improving
41198  ** performance. */
41199  winUnmapfile(pFd);
41200  }
41201 
41202  assert( pFd->nFetchOut>=0 );
41203 #endif
41204 
41205  OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
41206  osGetCurrentProcessId(), fd));
41207  return SQLITE_OK;
41208 }
41209 
41210 /*
41211 ** Here ends the implementation of all sqlite3_file methods.
41212 **
41213 ********************** End sqlite3_file Methods *******************************
41214 ******************************************************************************/
41215 
41216 /*
41217 ** This vector defines all the methods that can operate on an
41218 ** sqlite3_file for win32.
41219 */
41220 static const sqlite3_io_methods winIoMethod = {
41221  3, /* iVersion */
41222  winClose, /* xClose */
41223  winRead, /* xRead */
41224  winWrite, /* xWrite */
41225  winTruncate, /* xTruncate */
41226  winSync, /* xSync */
41227  winFileSize, /* xFileSize */
41228  winLock, /* xLock */
41229  winUnlock, /* xUnlock */
41230  winCheckReservedLock, /* xCheckReservedLock */
41231  winFileControl, /* xFileControl */
41232  winSectorSize, /* xSectorSize */
41233  winDeviceCharacteristics, /* xDeviceCharacteristics */
41234  winShmMap, /* xShmMap */
41235  winShmLock, /* xShmLock */
41236  winShmBarrier, /* xShmBarrier */
41237  winShmUnmap, /* xShmUnmap */
41238  winFetch, /* xFetch */
41239  winUnfetch /* xUnfetch */
41240 };
41241 
41242 /****************************************************************************
41243 **************************** sqlite3_vfs methods ****************************
41244 **
41245 ** This division contains the implementation of methods on the
41246 ** sqlite3_vfs object.
41247 */
41248 
41249 #if defined(__CYGWIN__)
41250 /*
41251 ** Convert a filename from whatever the underlying operating system
41252 ** supports for filenames into UTF-8. Space to hold the result is
41253 ** obtained from malloc and must be freed by the calling function.
41254 */
41255 static char *winConvertToUtf8Filename(const void *zFilename){
41256  char *zConverted = 0;
41257  if( osIsNT() ){
41258  zConverted = winUnicodeToUtf8(zFilename);
41259  }
41260 #ifdef SQLITE_WIN32_HAS_ANSI
41261  else{
41262  zConverted = winMbcsToUtf8(zFilename, osAreFileApisANSI());
41263  }
41264 #endif
41265  /* caller will handle out of memory */
41266  return zConverted;
41267 }
41268 #endif
41269 
41270 /*
41271 ** Convert a UTF-8 filename into whatever form the underlying
41272 ** operating system wants filenames in. Space to hold the result
41273 ** is obtained from malloc and must be freed by the calling
41274 ** function.
41275 */
41276 static void *winConvertFromUtf8Filename(const char *zFilename){
41277  void *zConverted = 0;
41278  if( osIsNT() ){
41279  zConverted = winUtf8ToUnicode(zFilename);
41280  }
41281 #ifdef SQLITE_WIN32_HAS_ANSI
41282  else{
41283  zConverted = winUtf8ToMbcs(zFilename, osAreFileApisANSI());
41284  }
41285 #endif
41286  /* caller will handle out of memory */
41287  return zConverted;
41288 }
41289 
41290 /*
41291 ** This function returns non-zero if the specified UTF-8 string buffer
41292 ** ends with a directory separator character or one was successfully
41293 ** added to it.
41294 */
41295 static int winMakeEndInDirSep(int nBuf, char *zBuf){
41296  if( zBuf ){
41297  int nLen = sqlite3Strlen30(zBuf);
41298  if( nLen>0 ){
41299  if( winIsDirSep(zBuf[nLen-1]) ){
41300  return 1;
41301  }else if( nLen+1<nBuf ){
41302  zBuf[nLen] = winGetDirSep();
41303  zBuf[nLen+1] = '\0';
41304  return 1;
41305  }
41306  }
41307  }
41308  return 0;
41309 }
41310 
41311 /*
41312 ** Create a temporary file name and store the resulting pointer into pzBuf.
41313 ** The pointer returned in pzBuf must be freed via sqlite3_free().
41314 */
41315 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
41316  static char zChars[] =
41317  "abcdefghijklmnopqrstuvwxyz"
41318  "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
41319  "0123456789";
41320  size_t i, j;
41322  int nMax, nBuf, nDir, nLen;
41323  char *zBuf;
41324 
41325  /* It's odd to simulate an io-error here, but really this is just
41326  ** using the io-error infrastructure to test that SQLite handles this
41327  ** function failing.
41328  */
41329  SimulateIOError( return SQLITE_IOERR );
41330 
41331  /* Allocate a temporary buffer to store the fully qualified file
41332  ** name for the temporary file. If this fails, we cannot continue.
41333  */
41334  nMax = pVfs->mxPathname; nBuf = nMax + 2;
41335  zBuf = sqlite3MallocZero( nBuf );
41336  if( !zBuf ){
41337  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41338  return SQLITE_IOERR_NOMEM_BKPT;
41339  }
41340 
41341  /* Figure out the effective temporary directory. First, check if one
41342  ** has been explicitly set by the application; otherwise, use the one
41343  ** configured by the operating system.
41344  */
41345  nDir = nMax - (nPre + 15);
41346  assert( nDir>0 );
41347  if( sqlite3_temp_directory ){
41348  int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
41349  if( nDirLen>0 ){
41350  if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
41351  nDirLen++;
41352  }
41353  if( nDirLen>nDir ){
41354  sqlite3_free(zBuf);
41355  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41356  return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
41357  }
41358  sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
41359  }
41360  }
41361 #if defined(__CYGWIN__)
41362  else{
41363  static const char *azDirs[] = {
41364  0, /* getenv("SQLITE_TMPDIR") */
41365  0, /* getenv("TMPDIR") */
41366  0, /* getenv("TMP") */
41367  0, /* getenv("TEMP") */
41368  0, /* getenv("USERPROFILE") */
41369  "/var/tmp",
41370  "/usr/tmp",
41371  "/tmp",
41372  ".",
41373  0 /* List terminator */
41374  };
41375  unsigned int i;
41376  const char *zDir = 0;
41377 
41378  if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
41379  if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
41380  if( !azDirs[2] ) azDirs[2] = getenv("TMP");
41381  if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
41382  if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
41383  for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
41384  void *zConverted;
41385  if( zDir==0 ) continue;
41386  /* If the path starts with a drive letter followed by the colon
41387  ** character, assume it is already a native Win32 path; otherwise,
41388  ** it must be converted to a native Win32 path via the Cygwin API
41389  ** prior to using it.
41390  */
41391  if( winIsDriveLetterAndColon(zDir) ){
41392  zConverted = winConvertFromUtf8Filename(zDir);
41393  if( !zConverted ){
41394  sqlite3_free(zBuf);
41395  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41396  return SQLITE_IOERR_NOMEM_BKPT;
41397  }
41398  if( winIsDir(zConverted) ){
41399  sqlite3_snprintf(nMax, zBuf, "%s", zDir);
41400  sqlite3_free(zConverted);
41401  break;
41402  }
41403  sqlite3_free(zConverted);
41404  }else{
41405  zConverted = sqlite3MallocZero( nMax+1 );
41406  if( !zConverted ){
41407  sqlite3_free(zBuf);
41408  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41409  return SQLITE_IOERR_NOMEM_BKPT;
41410  }
41411  if( cygwin_conv_path(
41412  osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
41413  zConverted, nMax+1)<0 ){
41414  sqlite3_free(zConverted);
41415  sqlite3_free(zBuf);
41416  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
41417  return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
41418  "winGetTempname2", zDir);
41419  }
41420  if( winIsDir(zConverted) ){
41421  /* At this point, we know the candidate directory exists and should
41422  ** be used. However, we may need to convert the string containing
41423  ** its name into UTF-8 (i.e. if it is UTF-16 right now).
41424  */
41425  char *zUtf8 = winConvertToUtf8Filename(zConverted);
41426  if( !zUtf8 ){
41427  sqlite3_free(zConverted);
41428  sqlite3_free(zBuf);
41429  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41430  return SQLITE_IOERR_NOMEM_BKPT;
41431  }
41432  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41433  sqlite3_free(zUtf8);
41434  sqlite3_free(zConverted);
41435  break;
41436  }
41437  sqlite3_free(zConverted);
41438  }
41439  }
41440  }
41441 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
41442  else if( osIsNT() ){
41443  char *zMulti;
41444  LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
41445  if( !zWidePath ){
41446  sqlite3_free(zBuf);
41447  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41448  return SQLITE_IOERR_NOMEM_BKPT;
41449  }
41450  if( osGetTempPathW(nMax, zWidePath)==0 ){
41451  sqlite3_free(zWidePath);
41452  sqlite3_free(zBuf);
41453  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41454  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41455  "winGetTempname2", 0);
41456  }
41457  zMulti = winUnicodeToUtf8(zWidePath);
41458  if( zMulti ){
41459  sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
41460  sqlite3_free(zMulti);
41461  sqlite3_free(zWidePath);
41462  }else{
41463  sqlite3_free(zWidePath);
41464  sqlite3_free(zBuf);
41465  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41466  return SQLITE_IOERR_NOMEM_BKPT;
41467  }
41468  }
41469 #ifdef SQLITE_WIN32_HAS_ANSI
41470  else{
41471  char *zUtf8;
41472  char *zMbcsPath = sqlite3MallocZero( nMax );
41473  if( !zMbcsPath ){
41474  sqlite3_free(zBuf);
41475  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41476  return SQLITE_IOERR_NOMEM_BKPT;
41477  }
41478  if( osGetTempPathA(nMax, zMbcsPath)==0 ){
41479  sqlite3_free(zBuf);
41480  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
41481  return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
41482  "winGetTempname3", 0);
41483  }
41484  zUtf8 = winMbcsToUtf8(zMbcsPath, osAreFileApisANSI());
41485  if( zUtf8 ){
41486  sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
41487  sqlite3_free(zUtf8);
41488  }else{
41489  sqlite3_free(zBuf);
41490  OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
41491  return SQLITE_IOERR_NOMEM_BKPT;
41492  }
41493  }
41494 #endif /* SQLITE_WIN32_HAS_ANSI */
41495 #endif /* !SQLITE_OS_WINRT */
41496 
41497  /*
41498  ** Check to make sure the temporary directory ends with an appropriate
41499  ** separator. If it does not and there is not enough space left to add
41500  ** one, fail.
41501  */
41502  if( !winMakeEndInDirSep(nDir+1, zBuf) ){
41503  sqlite3_free(zBuf);
41504  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41505  return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
41506  }
41507 
41508  /*
41509  ** Check that the output buffer is large enough for the temporary file
41510  ** name in the following format:
41511  **
41512  ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
41513  **
41514  ** If not, return SQLITE_ERROR. The number 17 is used here in order to
41515  ** account for the space used by the 15 character random suffix and the
41516  ** two trailing NUL characters. The final directory separator character
41517  ** has already added if it was not already present.
41518  */
41519  nLen = sqlite3Strlen30(zBuf);
41520  if( (nLen + nPre + 17) > nBuf ){
41521  sqlite3_free(zBuf);
41522  OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
41523  return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
41524  }
41525 
41526  sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
41527 
41528  j = sqlite3Strlen30(zBuf);
41529  sqlite3_randomness(15, &zBuf[j]);
41530  for(i=0; i<15; i++, j++){
41531  zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
41532  }
41533  zBuf[j] = 0;
41534  zBuf[j+1] = 0;
41535  *pzBuf = zBuf;
41536 
41537  OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
41538  return SQLITE_OK;
41539 }
41540 
41541 /*
41542 ** Return TRUE if the named file is really a directory. Return false if
41543 ** it is something other than a directory, or if there is any kind of memory
41544 ** allocation failure.
41545 */
41546 static int winIsDir(const void *zConverted){
41547  DWORD attr;
41548  int rc = 0;
41549  DWORD lastErrno;
41550 
41551  if( osIsNT() ){
41552  int cnt = 0;
41553  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
41554  memset(&sAttrData, 0, sizeof(sAttrData));
41555  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
41556  GetFileExInfoStandard,
41557  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
41558  if( !rc ){
41559  return 0; /* Invalid name? */
41560  }
41561  attr = sAttrData.dwFileAttributes;
41562 #if SQLITE_OS_WINCE==0
41563  }else{
41564  attr = osGetFileAttributesA((char*)zConverted);
41565 #endif
41566  }
41567  return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
41568 }
41569 
41570 /*
41571 ** Open a file.
41572 */
41573 static int winOpen(
41574  sqlite3_vfs *pVfs, /* Used to get maximum path name length */
41575  const char *zName, /* Name of the file (UTF-8) */
41576  sqlite3_file *id, /* Write the SQLite file handle here */
41577  int flags, /* Open mode flags */
41578  int *pOutFlags /* Status return flags */
41579 ){
41580  HANDLE h;
41581  DWORD lastErrno = 0;
41582  DWORD dwDesiredAccess;
41583  DWORD dwShareMode;
41584  DWORD dwCreationDisposition;
41585  DWORD dwFlagsAndAttributes = 0;
41586 #if SQLITE_OS_WINCE
41587  int isTemp = 0;
41588 #endif
41589  winFile *pFile = (winFile*)id;
41590  void *zConverted; /* Filename in OS encoding */
41591  const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
41592  int cnt = 0;
41593 
41594  /* If argument zPath is a NULL pointer, this function is required to open
41595  ** a temporary file. Use this buffer to store the file name in.
41596  */
41597  char *zTmpname = 0; /* For temporary filename, if necessary. */
41598 
41599  int rc = SQLITE_OK; /* Function Return Code */
41600 #if !defined(NDEBUG) || SQLITE_OS_WINCE
41601  int eType = flags&0xFFFFFF00; /* Type of file to open */
41602 #endif
41603 
41604  int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
41605  int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
41606  int isCreate = (flags & SQLITE_OPEN_CREATE);
41607  int isReadonly = (flags & SQLITE_OPEN_READONLY);
41608  int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
41609 
41610 #ifndef NDEBUG
41611  int isOpenJournal = (isCreate && (
41613  || eType==SQLITE_OPEN_MAIN_JOURNAL
41614  || eType==SQLITE_OPEN_WAL
41615  ));
41616 #endif
41617 
41618  OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
41619  zUtf8Name, id, flags, pOutFlags));
41620 
41621  /* Check the following statements are true:
41622  **
41623  ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
41624  ** (b) if CREATE is set, then READWRITE must also be set, and
41625  ** (c) if EXCLUSIVE is set, then CREATE must also be set.
41626  ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
41627  */
41628  assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
41629  assert(isCreate==0 || isReadWrite);
41630  assert(isExclusive==0 || isCreate);
41631  assert(isDelete==0 || isCreate);
41632 
41633  /* The main DB, main journal, WAL file and master journal are never
41634  ** automatically deleted. Nor are they ever temporary files. */
41635  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
41636  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
41637  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
41638  assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
41639 
41640  /* Assert that the upper layer has set one of the "file-type" flags. */
41644  || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
41645  );
41646 
41647  assert( pFile!=0 );
41648  memset(pFile, 0, sizeof(winFile));
41649  pFile->h = INVALID_HANDLE_VALUE;
41650 
41651 #if SQLITE_OS_WINRT
41652  if( !zUtf8Name && !sqlite3_temp_directory ){
41654  "sqlite3_temp_directory variable should be set for WinRT");
41655  }
41656 #endif
41657 
41658  /* If the second argument to this function is NULL, generate a
41659  ** temporary file name to use
41660  */
41661  if( !zUtf8Name ){
41662  assert( isDelete && !isOpenJournal );
41663  rc = winGetTempname(pVfs, &zTmpname);
41664  if( rc!=SQLITE_OK ){
41665  OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
41666  return rc;
41667  }
41668  zUtf8Name = zTmpname;
41669  }
41670 
41671  /* Database filenames are double-zero terminated if they are not
41672  ** URIs with parameters. Hence, they can always be passed into
41673  ** sqlite3_uri_parameter().
41674  */
41675  assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
41676  zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
41677 
41678  /* Convert the filename to the system encoding. */
41679  zConverted = winConvertFromUtf8Filename(zUtf8Name);
41680  if( zConverted==0 ){
41681  sqlite3_free(zTmpname);
41682  OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
41683  return SQLITE_IOERR_NOMEM_BKPT;
41684  }
41685 
41686  if( winIsDir(zConverted) ){
41687  sqlite3_free(zConverted);
41688  sqlite3_free(zTmpname);
41689  OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
41690  return SQLITE_CANTOPEN_ISDIR;
41691  }
41692 
41693  if( isReadWrite ){
41694  dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
41695  }else{
41696  dwDesiredAccess = GENERIC_READ;
41697  }
41698 
41699  /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
41700  ** created. SQLite doesn't use it to indicate "exclusive access"
41701  ** as it is usually understood.
41702  */
41703  if( isExclusive ){
41704  /* Creates a new file, only if it does not already exist. */
41705  /* If the file exists, it fails. */
41706  dwCreationDisposition = CREATE_NEW;
41707  }else if( isCreate ){
41708  /* Open existing file, or create if it doesn't exist */
41709  dwCreationDisposition = OPEN_ALWAYS;
41710  }else{
41711  /* Opens a file, only if it exists. */
41712  dwCreationDisposition = OPEN_EXISTING;
41713  }
41714 
41715  dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
41716 
41717  if( isDelete ){
41718 #if SQLITE_OS_WINCE
41719  dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
41720  isTemp = 1;
41721 #else
41722  dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
41723  | FILE_ATTRIBUTE_HIDDEN
41724  | FILE_FLAG_DELETE_ON_CLOSE;
41725 #endif
41726  }else{
41727  dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
41728  }
41729  /* Reports from the internet are that performance is always
41730  ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
41731 #if SQLITE_OS_WINCE
41732  dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
41733 #endif
41734 
41735  if( osIsNT() ){
41736 #if SQLITE_OS_WINRT
41737  CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
41738  extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
41739  extendedParameters.dwFileAttributes =
41740  dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
41741  extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
41742  extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
41743  extendedParameters.lpSecurityAttributes = NULL;
41744  extendedParameters.hTemplateFile = NULL;
41745  while( (h = osCreateFile2((LPCWSTR)zConverted,
41746  dwDesiredAccess,
41747  dwShareMode,
41748  dwCreationDisposition,
41749  &extendedParameters))==INVALID_HANDLE_VALUE &&
41750  winRetryIoerr(&cnt, &lastErrno) ){
41751  /* Noop */
41752  }
41753 #else
41754  while( (h = osCreateFileW((LPCWSTR)zConverted,
41755  dwDesiredAccess,
41756  dwShareMode, NULL,
41757  dwCreationDisposition,
41758  dwFlagsAndAttributes,
41759  NULL))==INVALID_HANDLE_VALUE &&
41760  winRetryIoerr(&cnt, &lastErrno) ){
41761  /* Noop */
41762  }
41763 #endif
41764  }
41765 #ifdef SQLITE_WIN32_HAS_ANSI
41766  else{
41767  while( (h = osCreateFileA((LPCSTR)zConverted,
41768  dwDesiredAccess,
41769  dwShareMode, NULL,
41770  dwCreationDisposition,
41771  dwFlagsAndAttributes,
41772  NULL))==INVALID_HANDLE_VALUE &&
41773  winRetryIoerr(&cnt, &lastErrno) ){
41774  /* Noop */
41775  }
41776  }
41777 #endif
41778  winLogIoerr(cnt, __LINE__);
41779 
41780  OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
41781  dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
41782 
41783  if( h==INVALID_HANDLE_VALUE ){
41784  pFile->lastErrno = lastErrno;
41785  winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
41786  sqlite3_free(zConverted);
41787  sqlite3_free(zTmpname);
41788  if( isReadWrite && !isExclusive ){
41789  return winOpen(pVfs, zName, id,
41790  ((flags|SQLITE_OPEN_READONLY) &
41792  pOutFlags);
41793  }else{
41794  return SQLITE_CANTOPEN_BKPT;
41795  }
41796  }
41797 
41798  if( pOutFlags ){
41799  if( isReadWrite ){
41800  *pOutFlags = SQLITE_OPEN_READWRITE;
41801  }else{
41802  *pOutFlags = SQLITE_OPEN_READONLY;
41803  }
41804  }
41805 
41806  OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
41807  "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
41808  *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
41809 
41810 #if SQLITE_OS_WINCE
41811  if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
41812  && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
41813  ){
41814  osCloseHandle(h);
41815  sqlite3_free(zConverted);
41816  sqlite3_free(zTmpname);
41817  OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
41818  return rc;
41819  }
41820  if( isTemp ){
41821  pFile->zDeleteOnClose = zConverted;
41822  }else
41823 #endif
41824  {
41825  sqlite3_free(zConverted);
41826  }
41827 
41828  sqlite3_free(zTmpname);
41829  pFile->pMethod = &winIoMethod;
41830  pFile->pVfs = pVfs;
41831  pFile->h = h;
41832  if( isReadonly ){
41833  pFile->ctrlFlags |= WINFILE_RDONLY;
41834  }
41835  if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
41836  pFile->ctrlFlags |= WINFILE_PSOW;
41837  }
41838  pFile->lastErrno = NO_ERROR;
41839  pFile->zPath = zName;
41840 #if SQLITE_MAX_MMAP_SIZE>0
41841  pFile->hMap = NULL;
41842  pFile->pMapRegion = 0;
41843  pFile->mmapSize = 0;
41844  pFile->mmapSizeActual = 0;
41845  pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
41846 #endif
41847 
41848  OpenCounter(+1);
41849  return rc;
41850 }
41851 
41852 /*
41853 ** Delete the named file.
41854 **
41855 ** Note that Windows does not allow a file to be deleted if some other
41856 ** process has it open. Sometimes a virus scanner or indexing program
41857 ** will open a journal file shortly after it is created in order to do
41858 ** whatever it does. While this other process is holding the
41859 ** file open, we will be unable to delete it. To work around this
41860 ** problem, we delay 100 milliseconds and try to delete again. Up
41861 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
41862 ** up and returning an error.
41863 */
41864 static int winDelete(
41865  sqlite3_vfs *pVfs, /* Not used on win32 */
41866  const char *zFilename, /* Name of file to delete */
41867  int syncDir /* Not used on win32 */
41868 ){
41869  int cnt = 0;
41870  int rc;
41871  DWORD attr;
41872  DWORD lastErrno = 0;
41873  void *zConverted;
41874  UNUSED_PARAMETER(pVfs);
41875  UNUSED_PARAMETER(syncDir);
41876 
41878  OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
41879 
41880  zConverted = winConvertFromUtf8Filename(zFilename);
41881  if( zConverted==0 ){
41882  OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
41883  return SQLITE_IOERR_NOMEM_BKPT;
41884  }
41885  if( osIsNT() ){
41886  do {
41887 #if SQLITE_OS_WINRT
41888  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
41889  memset(&sAttrData, 0, sizeof(sAttrData));
41890  if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
41891  &sAttrData) ){
41892  attr = sAttrData.dwFileAttributes;
41893  }else{
41894  lastErrno = osGetLastError();
41895  if( lastErrno==ERROR_FILE_NOT_FOUND
41896  || lastErrno==ERROR_PATH_NOT_FOUND ){
41897  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
41898  }else{
41899  rc = SQLITE_ERROR;
41900  }
41901  break;
41902  }
41903 #else
41904  attr = osGetFileAttributesW(zConverted);
41905 #endif
41906  if ( attr==INVALID_FILE_ATTRIBUTES ){
41907  lastErrno = osGetLastError();
41908  if( lastErrno==ERROR_FILE_NOT_FOUND
41909  || lastErrno==ERROR_PATH_NOT_FOUND ){
41910  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
41911  }else{
41912  rc = SQLITE_ERROR;
41913  }
41914  break;
41915  }
41916  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
41917  rc = SQLITE_ERROR; /* Files only. */
41918  break;
41919  }
41920  if ( osDeleteFileW(zConverted) ){
41921  rc = SQLITE_OK; /* Deleted OK. */
41922  break;
41923  }
41924  if ( !winRetryIoerr(&cnt, &lastErrno) ){
41925  rc = SQLITE_ERROR; /* No more retries. */
41926  break;
41927  }
41928  } while(1);
41929  }
41930 #ifdef SQLITE_WIN32_HAS_ANSI
41931  else{
41932  do {
41933  attr = osGetFileAttributesA(zConverted);
41934  if ( attr==INVALID_FILE_ATTRIBUTES ){
41935  lastErrno = osGetLastError();
41936  if( lastErrno==ERROR_FILE_NOT_FOUND
41937  || lastErrno==ERROR_PATH_NOT_FOUND ){
41938  rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
41939  }else{
41940  rc = SQLITE_ERROR;
41941  }
41942  break;
41943  }
41944  if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
41945  rc = SQLITE_ERROR; /* Files only. */
41946  break;
41947  }
41948  if ( osDeleteFileA(zConverted) ){
41949  rc = SQLITE_OK; /* Deleted OK. */
41950  break;
41951  }
41952  if ( !winRetryIoerr(&cnt, &lastErrno) ){
41953  rc = SQLITE_ERROR; /* No more retries. */
41954  break;
41955  }
41956  } while(1);
41957  }
41958 #endif
41959  if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
41960  rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
41961  }else{
41962  winLogIoerr(cnt, __LINE__);
41963  }
41964  sqlite3_free(zConverted);
41965  OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
41966  return rc;
41967 }
41968 
41969 /*
41970 ** Check the existence and status of a file.
41971 */
41972 static int winAccess(
41973  sqlite3_vfs *pVfs, /* Not used on win32 */
41974  const char *zFilename, /* Name of file to check */
41975  int flags, /* Type of test to make on this file */
41976  int *pResOut /* OUT: Result */
41977 ){
41978  DWORD attr;
41979  int rc = 0;
41980  DWORD lastErrno = 0;
41981  void *zConverted;
41982  UNUSED_PARAMETER(pVfs);
41983 
41985  OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
41986  zFilename, flags, pResOut));
41987 
41988  zConverted = winConvertFromUtf8Filename(zFilename);
41989  if( zConverted==0 ){
41990  OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
41991  return SQLITE_IOERR_NOMEM_BKPT;
41992  }
41993  if( osIsNT() ){
41994  int cnt = 0;
41995  WIN32_FILE_ATTRIBUTE_DATA sAttrData;
41996  memset(&sAttrData, 0, sizeof(sAttrData));
41997  while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
41998  GetFileExInfoStandard,
41999  &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
42000  if( rc ){
42001  /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
42002  ** as if it does not exist.
42003  */
42004  if( flags==SQLITE_ACCESS_EXISTS
42005  && sAttrData.nFileSizeHigh==0
42006  && sAttrData.nFileSizeLow==0 ){
42007  attr = INVALID_FILE_ATTRIBUTES;
42008  }else{
42009  attr = sAttrData.dwFileAttributes;
42010  }
42011  }else{
42012  winLogIoerr(cnt, __LINE__);
42013  if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
42014  sqlite3_free(zConverted);
42015  return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
42016  zFilename);
42017  }else{
42018  attr = INVALID_FILE_ATTRIBUTES;
42019  }
42020  }
42021  }
42022 #ifdef SQLITE_WIN32_HAS_ANSI
42023  else{
42024  attr = osGetFileAttributesA((char*)zConverted);
42025  }
42026 #endif
42027  sqlite3_free(zConverted);
42028  switch( flags ){
42029  case SQLITE_ACCESS_READ:
42030  case SQLITE_ACCESS_EXISTS:
42031  rc = attr!=INVALID_FILE_ATTRIBUTES;
42032  break;
42034  rc = attr!=INVALID_FILE_ATTRIBUTES &&
42035  (attr & FILE_ATTRIBUTE_READONLY)==0;
42036  break;
42037  default:
42038  assert(!"Invalid flags argument");
42039  }
42040  *pResOut = rc;
42041  OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
42042  zFilename, pResOut, *pResOut));
42043  return SQLITE_OK;
42044 }
42045 
42046 /*
42047 ** Returns non-zero if the specified path name starts with a drive letter
42048 ** followed by a colon character.
42049 */
42050 static BOOL winIsDriveLetterAndColon(
42051  const char *zPathname
42052 ){
42053  return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
42054 }
42055 
42056 /*
42057 ** Returns non-zero if the specified path name should be used verbatim. If
42058 ** non-zero is returned from this function, the calling function must simply
42059 ** use the provided path name verbatim -OR- resolve it into a full path name
42060 ** using the GetFullPathName Win32 API function (if available).
42061 */
42062 static BOOL winIsVerbatimPathname(
42063  const char *zPathname
42064 ){
42065  /*
42066  ** If the path name starts with a forward slash or a backslash, it is either
42067  ** a legal UNC name, a volume relative path, or an absolute path name in the
42068  ** "Unix" format on Windows. There is no easy way to differentiate between
42069  ** the final two cases; therefore, we return the safer return value of TRUE
42070  ** so that callers of this function will simply use it verbatim.
42071  */
42072  if ( winIsDirSep(zPathname[0]) ){
42073  return TRUE;
42074  }
42075 
42076  /*
42077  ** If the path name starts with a letter and a colon it is either a volume
42078  ** relative path or an absolute path. Callers of this function must not
42079  ** attempt to treat it as a relative path name (i.e. they should simply use
42080  ** it verbatim).
42081  */
42082  if ( winIsDriveLetterAndColon(zPathname) ){
42083  return TRUE;
42084  }
42085 
42086  /*
42087  ** If we get to this point, the path name should almost certainly be a purely
42088  ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
42089  */
42090  return FALSE;
42091 }
42092 
42093 /*
42094 ** Turn a relative pathname into a full pathname. Write the full
42095 ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
42096 ** bytes in size.
42097 */
42098 static int winFullPathname(
42099  sqlite3_vfs *pVfs, /* Pointer to vfs object */
42100  const char *zRelative, /* Possibly relative input path */
42101  int nFull, /* Size of output buffer in bytes */
42102  char *zFull /* Output buffer */
42103 ){
42104 
42105 #if defined(__CYGWIN__)
42106  SimulateIOError( return SQLITE_ERROR );
42107  UNUSED_PARAMETER(nFull);
42108  assert( nFull>=pVfs->mxPathname );
42109  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42110  /*
42111  ** NOTE: We are dealing with a relative path name and the data
42112  ** directory has been set. Therefore, use it as the basis
42113  ** for converting the relative path name to an absolute
42114  ** one by prepending the data directory and a slash.
42115  */
42116  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42117  if( !zOut ){
42118  return SQLITE_IOERR_NOMEM_BKPT;
42119  }
42120  if( cygwin_conv_path(
42121  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
42122  CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
42123  sqlite3_free(zOut);
42124  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42125  "winFullPathname1", zRelative);
42126  }else{
42127  char *zUtf8 = winConvertToUtf8Filename(zOut);
42128  if( !zUtf8 ){
42129  sqlite3_free(zOut);
42130  return SQLITE_IOERR_NOMEM_BKPT;
42131  }
42132  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42133  sqlite3_data_directory, winGetDirSep(), zUtf8);
42134  sqlite3_free(zUtf8);
42135  sqlite3_free(zOut);
42136  }
42137  }else{
42138  char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
42139  if( !zOut ){
42140  return SQLITE_IOERR_NOMEM_BKPT;
42141  }
42142  if( cygwin_conv_path(
42143  (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
42144  zRelative, zOut, pVfs->mxPathname+1)<0 ){
42145  sqlite3_free(zOut);
42146  return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
42147  "winFullPathname2", zRelative);
42148  }else{
42149  char *zUtf8 = winConvertToUtf8Filename(zOut);
42150  if( !zUtf8 ){
42151  sqlite3_free(zOut);
42152  return SQLITE_IOERR_NOMEM_BKPT;
42153  }
42154  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
42155  sqlite3_free(zUtf8);
42156  sqlite3_free(zOut);
42157  }
42158  }
42159  return SQLITE_OK;
42160 #endif
42161 
42162 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
42163  SimulateIOError( return SQLITE_ERROR );
42164  /* WinCE has no concept of a relative pathname, or so I am told. */
42165  /* WinRT has no way to convert a relative path to an absolute one. */
42166  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42167  /*
42168  ** NOTE: We are dealing with a relative path name and the data
42169  ** directory has been set. Therefore, use it as the basis
42170  ** for converting the relative path name to an absolute
42171  ** one by prepending the data directory and a backslash.
42172  */
42173  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42174  sqlite3_data_directory, winGetDirSep(), zRelative);
42175  }else{
42176  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
42177  }
42178  return SQLITE_OK;
42179 #endif
42180 
42181 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
42182  DWORD nByte;
42183  void *zConverted;
42184  char *zOut;
42185 
42186  /* If this path name begins with "/X:", where "X" is any alphabetic
42187  ** character, discard the initial "/" from the pathname.
42188  */
42189  if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
42190  zRelative++;
42191  }
42192 
42193  /* It's odd to simulate an io-error here, but really this is just
42194  ** using the io-error infrastructure to test that SQLite handles this
42195  ** function failing. This function could fail if, for example, the
42196  ** current working directory has been unlinked.
42197  */
42198  SimulateIOError( return SQLITE_ERROR );
42199  if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
42200  /*
42201  ** NOTE: We are dealing with a relative path name and the data
42202  ** directory has been set. Therefore, use it as the basis
42203  ** for converting the relative path name to an absolute
42204  ** one by prepending the data directory and a backslash.
42205  */
42206  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
42207  sqlite3_data_directory, winGetDirSep(), zRelative);
42208  return SQLITE_OK;
42209  }
42210  zConverted = winConvertFromUtf8Filename(zRelative);
42211  if( zConverted==0 ){
42212  return SQLITE_IOERR_NOMEM_BKPT;
42213  }
42214  if( osIsNT() ){
42215  LPWSTR zTemp;
42216  nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
42217  if( nByte==0 ){
42218  sqlite3_free(zConverted);
42219  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42220  "winFullPathname1", zRelative);
42221  }
42222  nByte += 3;
42223  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42224  if( zTemp==0 ){
42225  sqlite3_free(zConverted);
42226  return SQLITE_IOERR_NOMEM_BKPT;
42227  }
42228  nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
42229  if( nByte==0 ){
42230  sqlite3_free(zConverted);
42231  sqlite3_free(zTemp);
42232  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42233  "winFullPathname2", zRelative);
42234  }
42235  sqlite3_free(zConverted);
42236  zOut = winUnicodeToUtf8(zTemp);
42237  sqlite3_free(zTemp);
42238  }
42239 #ifdef SQLITE_WIN32_HAS_ANSI
42240  else{
42241  char *zTemp;
42242  nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
42243  if( nByte==0 ){
42244  sqlite3_free(zConverted);
42245  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42246  "winFullPathname3", zRelative);
42247  }
42248  nByte += 3;
42249  zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
42250  if( zTemp==0 ){
42251  sqlite3_free(zConverted);
42252  return SQLITE_IOERR_NOMEM_BKPT;
42253  }
42254  nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
42255  if( nByte==0 ){
42256  sqlite3_free(zConverted);
42257  sqlite3_free(zTemp);
42258  return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
42259  "winFullPathname4", zRelative);
42260  }
42261  sqlite3_free(zConverted);
42262  zOut = winMbcsToUtf8(zTemp, osAreFileApisANSI());
42263  sqlite3_free(zTemp);
42264  }
42265 #endif
42266  if( zOut ){
42267  sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
42268  sqlite3_free(zOut);
42269  return SQLITE_OK;
42270  }else{
42271  return SQLITE_IOERR_NOMEM_BKPT;
42272  }
42273 #endif
42274 }
42275 
42276 #ifndef SQLITE_OMIT_LOAD_EXTENSION
42277 /*
42278 ** Interfaces for opening a shared library, finding entry points
42279 ** within the shared library, and closing the shared library.
42280 */
42281 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
42282  HANDLE h;
42283 #if defined(__CYGWIN__)
42284  int nFull = pVfs->mxPathname+1;
42285  char *zFull = sqlite3MallocZero( nFull );
42286  void *zConverted = 0;
42287  if( zFull==0 ){
42288  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42289  return 0;
42290  }
42291  if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
42292  sqlite3_free(zFull);
42293  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42294  return 0;
42295  }
42296  zConverted = winConvertFromUtf8Filename(zFull);
42297  sqlite3_free(zFull);
42298 #else
42299  void *zConverted = winConvertFromUtf8Filename(zFilename);
42300  UNUSED_PARAMETER(pVfs);
42301 #endif
42302  if( zConverted==0 ){
42303  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
42304  return 0;
42305  }
42306  if( osIsNT() ){
42307 #if SQLITE_OS_WINRT
42308  h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
42309 #else
42310  h = osLoadLibraryW((LPCWSTR)zConverted);
42311 #endif
42312  }
42313 #ifdef SQLITE_WIN32_HAS_ANSI
42314  else{
42315  h = osLoadLibraryA((char*)zConverted);
42316  }
42317 #endif
42318  OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
42319  sqlite3_free(zConverted);
42320  return (void*)h;
42321 }
42322 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
42323  UNUSED_PARAMETER(pVfs);
42324  winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
42325 }
42326 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
42327  FARPROC proc;
42328  UNUSED_PARAMETER(pVfs);
42329  proc = osGetProcAddressA((HANDLE)pH, zSym);
42330  OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
42331  (void*)pH, zSym, (void*)proc));
42332  return (void(*)(void))proc;
42333 }
42334 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
42335  UNUSED_PARAMETER(pVfs);
42336  osFreeLibrary((HANDLE)pHandle);
42337  OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
42338 }
42339 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
42340  #define winDlOpen 0
42341  #define winDlError 0
42342  #define winDlSym 0
42343  #define winDlClose 0
42344 #endif
42345 
42346 /* State information for the randomness gatherer. */
42347 typedef struct EntropyGatherer EntropyGatherer;
42348 struct EntropyGatherer {
42349  unsigned char *a; /* Gather entropy into this buffer */
42350  int na; /* Size of a[] in bytes */
42351  int i; /* XOR next input into a[i] */
42352  int nXor; /* Number of XOR operations done */
42353 };
42354 
42355 #if !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS)
42356 /* Mix sz bytes of entropy into p. */
42357 static void xorMemory(EntropyGatherer *p, unsigned char *x, int sz){
42358  int j, k;
42359  for(j=0, k=p->i; j<sz; j++){
42360  p->a[k++] ^= x[j];
42361  if( k>=p->na ) k = 0;
42362  }
42363  p->i = k;
42364  p->nXor += sz;
42365 }
42366 #endif /* !defined(SQLITE_TEST) && !defined(SQLITE_OMIT_RANDOMNESS) */
42367 
42368 /*
42369 ** Write up to nBuf bytes of randomness into zBuf.
42370 */
42371 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42372 #if defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS)
42373  UNUSED_PARAMETER(pVfs);
42374  memset(zBuf, 0, nBuf);
42375  return nBuf;
42376 #else
42377  EntropyGatherer e;
42378  UNUSED_PARAMETER(pVfs);
42379  memset(zBuf, 0, nBuf);
42380 #if defined(_MSC_VER) && _MSC_VER>=1400 && !SQLITE_OS_WINCE
42381  rand_s((unsigned int*)zBuf); /* rand_s() is not available with MinGW */
42382 #endif /* defined(_MSC_VER) && _MSC_VER>=1400 */
42383  e.a = (unsigned char*)zBuf;
42384  e.na = nBuf;
42385  e.nXor = 0;
42386  e.i = 0;
42387  {
42388  SYSTEMTIME x;
42389  osGetSystemTime(&x);
42390  xorMemory(&e, (unsigned char*)&x, sizeof(SYSTEMTIME));
42391  }
42392  {
42393  DWORD pid = osGetCurrentProcessId();
42394  xorMemory(&e, (unsigned char*)&pid, sizeof(DWORD));
42395  }
42396 #if SQLITE_OS_WINRT
42397  {
42398  ULONGLONG cnt = osGetTickCount64();
42399  xorMemory(&e, (unsigned char*)&cnt, sizeof(ULONGLONG));
42400  }
42401 #else
42402  {
42403  DWORD cnt = osGetTickCount();
42404  xorMemory(&e, (unsigned char*)&cnt, sizeof(DWORD));
42405  }
42406 #endif /* SQLITE_OS_WINRT */
42407  {
42408  LARGE_INTEGER i;
42409  osQueryPerformanceCounter(&i);
42410  xorMemory(&e, (unsigned char*)&i, sizeof(LARGE_INTEGER));
42411  }
42412 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
42413  {
42414  UUID id;
42415  memset(&id, 0, sizeof(UUID));
42416  osUuidCreate(&id);
42417  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42418  memset(&id, 0, sizeof(UUID));
42419  osUuidCreateSequential(&id);
42420  xorMemory(&e, (unsigned char*)&id, sizeof(UUID));
42421  }
42422 #endif /* !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID */
42423  return e.nXor>nBuf ? nBuf : e.nXor;
42424 #endif /* defined(SQLITE_TEST) || defined(SQLITE_OMIT_RANDOMNESS) */
42425 }
42426 
42427 
42428 /*
42429 ** Sleep for a little while. Return the amount of time slept.
42430 */
42431 static int winSleep(sqlite3_vfs *pVfs, int microsec){
42432  sqlite3_win32_sleep((microsec+999)/1000);
42433  UNUSED_PARAMETER(pVfs);
42434  return ((microsec+999)/1000)*1000;
42435 }
42436 
42437 /*
42438 ** The following variable, if set to a non-zero value, is interpreted as
42439 ** the number of seconds since 1970 and is used to set the result of
42440 ** sqlite3OsCurrentTime() during testing.
42441 */
42442 #ifdef SQLITE_TEST
42443 SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
42444 #endif
42445 
42446 /*
42447 ** Find the current time (in Universal Coordinated Time). Write into *piNow
42448 ** the current time and date as a Julian Day number times 86_400_000. In
42449 ** other words, write into *piNow the number of milliseconds since the Julian
42450 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
42451 ** proleptic Gregorian calendar.
42452 **
42453 ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
42454 ** cannot be found.
42455 */
42456 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
42457  /* FILETIME structure is a 64-bit value representing the number of
42458  100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
42459  */
42460  FILETIME ft;
42461  static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
42462 #ifdef SQLITE_TEST
42463  static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
42464 #endif
42465  /* 2^32 - to avoid use of LL and warnings in gcc */
42466  static const sqlite3_int64 max32BitValue =
42467  (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
42468  (sqlite3_int64)294967296;
42469 
42470 #if SQLITE_OS_WINCE
42471  SYSTEMTIME time;
42472  osGetSystemTime(&time);
42473  /* if SystemTimeToFileTime() fails, it returns zero. */
42474  if (!osSystemTimeToFileTime(&time,&ft)){
42475  return SQLITE_ERROR;
42476  }
42477 #else
42478  osGetSystemTimeAsFileTime( &ft );
42479 #endif
42480 
42481  *piNow = winFiletimeEpoch +
42482  ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
42483  (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
42484 
42485 #ifdef SQLITE_TEST
42486  if( sqlite3_current_time ){
42487  *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
42488  }
42489 #endif
42490  UNUSED_PARAMETER(pVfs);
42491  return SQLITE_OK;
42492 }
42493 
42494 /*
42495 ** Find the current time (in Universal Coordinated Time). Write the
42496 ** current time and date as a Julian Day number into *prNow and
42497 ** return 0. Return 1 if the time and date cannot be found.
42498 */
42499 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
42500  int rc;
42501  sqlite3_int64 i;
42502  rc = winCurrentTimeInt64(pVfs, &i);
42503  if( !rc ){
42504  *prNow = i/86400000.0;
42505  }
42506  return rc;
42507 }
42508 
42509 /*
42510 ** The idea is that this function works like a combination of
42511 ** GetLastError() and FormatMessage() on Windows (or errno and
42512 ** strerror_r() on Unix). After an error is returned by an OS
42513 ** function, SQLite calls this function with zBuf pointing to
42514 ** a buffer of nBuf bytes. The OS layer should populate the
42515 ** buffer with a nul-terminated UTF-8 encoded error message
42516 ** describing the last IO error to have occurred within the calling
42517 ** thread.
42518 **
42519 ** If the error message is too large for the supplied buffer,
42520 ** it should be truncated. The return value of xGetLastError
42521 ** is zero if the error message fits in the buffer, or non-zero
42522 ** otherwise (if the message was truncated). If non-zero is returned,
42523 ** then it is not necessary to include the nul-terminator character
42524 ** in the output buffer.
42525 **
42526 ** Not supplying an error message will have no adverse effect
42527 ** on SQLite. It is fine to have an implementation that never
42528 ** returns an error message:
42529 **
42530 ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42531 ** assert(zBuf[0]=='\0');
42532 ** return 0;
42533 ** }
42534 **
42535 ** However if an error message is supplied, it will be incorporated
42536 ** by sqlite into the error message available to the user using
42537 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
42538 */
42539 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
42540  DWORD e = osGetLastError();
42541  UNUSED_PARAMETER(pVfs);
42542  if( nBuf>0 ) winGetLastErrorMsg(e, nBuf, zBuf);
42543  return e;
42544 }
42545 
42546 /*
42547 ** Initialize and deinitialize the operating system interface.
42548 */
42550  static sqlite3_vfs winVfs = {
42551  3, /* iVersion */
42552  sizeof(winFile), /* szOsFile */
42553  SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
42554  0, /* pNext */
42555  "win32", /* zName */
42556  0, /* pAppData */
42557  winOpen, /* xOpen */
42558  winDelete, /* xDelete */
42559  winAccess, /* xAccess */
42560  winFullPathname, /* xFullPathname */
42561  winDlOpen, /* xDlOpen */
42562  winDlError, /* xDlError */
42563  winDlSym, /* xDlSym */
42564  winDlClose, /* xDlClose */
42565  winRandomness, /* xRandomness */
42566  winSleep, /* xSleep */
42567  winCurrentTime, /* xCurrentTime */
42568  winGetLastError, /* xGetLastError */
42569  winCurrentTimeInt64, /* xCurrentTimeInt64 */
42570  winSetSystemCall, /* xSetSystemCall */
42571  winGetSystemCall, /* xGetSystemCall */
42572  winNextSystemCall, /* xNextSystemCall */
42573  };
42574 #if defined(SQLITE_WIN32_HAS_WIDE)
42575  static sqlite3_vfs winLongPathVfs = {
42576  3, /* iVersion */
42577  sizeof(winFile), /* szOsFile */
42578  SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
42579  0, /* pNext */
42580  "win32-longpath", /* zName */
42581  0, /* pAppData */
42582  winOpen, /* xOpen */
42583  winDelete, /* xDelete */
42584  winAccess, /* xAccess */
42585  winFullPathname, /* xFullPathname */
42586  winDlOpen, /* xDlOpen */
42587  winDlError, /* xDlError */
42588  winDlSym, /* xDlSym */
42589  winDlClose, /* xDlClose */
42590  winRandomness, /* xRandomness */
42591  winSleep, /* xSleep */
42592  winCurrentTime, /* xCurrentTime */
42593  winGetLastError, /* xGetLastError */
42594  winCurrentTimeInt64, /* xCurrentTimeInt64 */
42595  winSetSystemCall, /* xSetSystemCall */
42596  winGetSystemCall, /* xGetSystemCall */
42597  winNextSystemCall, /* xNextSystemCall */
42598  };
42599 #endif
42600 
42601  /* Double-check that the aSyscall[] array has been constructed
42602  ** correctly. See ticket [bb3a86e890c8e96ab] */
42603  assert( ArraySize(aSyscall)==80 );
42604 
42605  /* get memory map allocation granularity */
42606  memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
42607 #if SQLITE_OS_WINRT
42608  osGetNativeSystemInfo(&winSysInfo);
42609 #else
42610  osGetSystemInfo(&winSysInfo);
42611 #endif
42612  assert( winSysInfo.dwAllocationGranularity>0 );
42613  assert( winSysInfo.dwPageSize>0 );
42614 
42615  sqlite3_vfs_register(&winVfs, 1);
42616 
42617 #if defined(SQLITE_WIN32_HAS_WIDE)
42618  sqlite3_vfs_register(&winLongPathVfs, 0);
42619 #endif
42620 
42621  return SQLITE_OK;
42622 }
42623 
42625 #if SQLITE_OS_WINRT
42626  if( sleepObj!=NULL ){
42627  osCloseHandle(sleepObj);
42628  sleepObj = NULL;
42629  }
42630 #endif
42631  return SQLITE_OK;
42632 }
42633 
42634 #endif /* SQLITE_OS_WIN */
42635 
42636 /************** End of os_win.c **********************************************/
42637 /************** Begin file bitvec.c ******************************************/
42638 /*
42639 ** 2008 February 16
42640 **
42641 ** The author disclaims copyright to this source code. In place of
42642 ** a legal notice, here is a blessing:
42643 **
42644 ** May you do good and not evil.
42645 ** May you find forgiveness for yourself and forgive others.
42646 ** May you share freely, never taking more than you give.
42647 **
42648 *************************************************************************
42649 ** This file implements an object that represents a fixed-length
42650 ** bitmap. Bits are numbered starting with 1.
42651 **
42652 ** A bitmap is used to record which pages of a database file have been
42653 ** journalled during a transaction, or which pages have the "dont-write"
42654 ** property. Usually only a few pages are meet either condition.
42655 ** So the bitmap is usually sparse and has low cardinality.
42656 ** But sometimes (for example when during a DROP of a large table) most
42657 ** or all of the pages in a database can get journalled. In those cases,
42658 ** the bitmap becomes dense with high cardinality. The algorithm needs
42659 ** to handle both cases well.
42660 **
42661 ** The size of the bitmap is fixed when the object is created.
42662 **
42663 ** All bits are clear when the bitmap is created. Individual bits
42664 ** may be set or cleared one at a time.
42665 **
42666 ** Test operations are about 100 times more common that set operations.
42667 ** Clear operations are exceedingly rare. There are usually between
42668 ** 5 and 500 set operations per Bitvec object, though the number of sets can
42669 ** sometimes grow into tens of thousands or larger. The size of the
42670 ** Bitvec object is the number of pages in the database file at the
42671 ** start of a transaction, and is thus usually less than a few thousand,
42672 ** but can be as large as 2 billion for a really big database.
42673 */
42674 /* #include "sqliteInt.h" */
42675 
42676 /* Size of the Bitvec structure in bytes. */
42677 #define BITVEC_SZ 512
42678 
42679 /* Round the union size down to the nearest pointer boundary, since that's how
42680 ** it will be aligned within the Bitvec struct. */
42681 #define BITVEC_USIZE \
42682  (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
42683 
42684 /* Type of the array "element" for the bitmap representation.
42685 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
42686 ** Setting this to the "natural word" size of your CPU may improve
42687 ** performance. */
42688 #define BITVEC_TELEM u8
42689 /* Size, in bits, of the bitmap element. */
42690 #define BITVEC_SZELEM 8
42691 /* Number of elements in a bitmap array. */
42692 #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
42693 /* Number of bits in the bitmap array. */
42694 #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
42695 
42696 /* Number of u32 values in hash table. */
42697 #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
42698 /* Maximum number of entries in hash table before
42699 ** sub-dividing and re-hashing. */
42700 #define BITVEC_MXHASH (BITVEC_NINT/2)
42701 /* Hashing function for the aHash representation.
42702 ** Empirical testing showed that the *37 multiplier
42703 ** (an arbitrary prime)in the hash function provided
42704 ** no fewer collisions than the no-op *1. */
42705 #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
42706 
42707 #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
42708 
42709 
42710 /*
42711 ** A bitmap is an instance of the following structure.
42712 **
42713 ** This bitmap records the existence of zero or more bits
42714 ** with values between 1 and iSize, inclusive.
42715 **
42716 ** There are three possible representations of the bitmap.
42717 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
42718 ** bitmap. The least significant bit is bit 1.
42719 **
42720 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
42721 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
42722 **
42723 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
42724 ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
42725 ** handles up to iDivisor separate values of i. apSub[0] holds
42726 ** values between 1 and iDivisor. apSub[1] holds values between
42727 ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
42728 ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
42729 ** to hold deal with values between 1 and iDivisor.
42730 */
42731 struct Bitvec {
42732  u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
42733  u32 nSet; /* Number of bits that are set - only valid for aHash
42734  ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
42735  ** this would be 125. */
42736  u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
42737  /* Should >=0 for apSub element. */
42738  /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
42739  /* For a BITVEC_SZ of 512, this would be 34,359,739. */
42740  union {
42741  BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
42742  u32 aHash[BITVEC_NINT]; /* Hash table representation */
42743  Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
42744  } u;
42745 };
42746 
42747 /*
42748 ** Create a new bitmap object able to handle bits between 0 and iSize,
42749 ** inclusive. Return a pointer to the new object. Return NULL if
42750 ** malloc fails.
42751 */
42753  Bitvec *p;
42754  assert( sizeof(*p)==BITVEC_SZ );
42755  p = sqlite3MallocZero( sizeof(*p) );
42756  if( p ){
42757  p->iSize = iSize;
42758  }
42759  return p;
42760 }
42761 
42762 /*
42763 ** Check to see if the i-th bit is set. Return true or false.
42764 ** If p is NULL (if the bitmap has not been created) or if
42765 ** i is out of range, then return false.
42766 */
42768  assert( p!=0 );
42769  i--;
42770  if( i>=p->iSize ) return 0;
42771  while( p->iDivisor ){
42772  u32 bin = i/p->iDivisor;
42773  i = i%p->iDivisor;
42774  p = p->u.apSub[bin];
42775  if (!p) {
42776  return 0;
42777  }
42778  }
42779  if( p->iSize<=BITVEC_NBIT ){
42780  return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
42781  } else{
42782  u32 h = BITVEC_HASH(i++);
42783  while( p->u.aHash[h] ){
42784  if( p->u.aHash[h]==i ) return 1;
42785  h = (h+1) % BITVEC_NINT;
42786  }
42787  return 0;
42788  }
42789 }
42791  return p!=0 && sqlite3BitvecTestNotNull(p,i);
42792 }
42793 
42794 /*
42795 ** Set the i-th bit. Return 0 on success and an error code if
42796 ** anything goes wrong.
42797 **
42798 ** This routine might cause sub-bitmaps to be allocated. Failing
42799 ** to get the memory needed to hold the sub-bitmap is the only
42800 ** that can go wrong with an insert, assuming p and i are valid.
42801 **
42802 ** The calling function must ensure that p is a valid Bitvec object
42803 ** and that the value for "i" is within range of the Bitvec object.
42804 ** Otherwise the behavior is undefined.
42805 */
42807  u32 h;
42808  if( p==0 ) return SQLITE_OK;
42809  assert( i>0 );
42810  assert( i<=p->iSize );
42811  i--;
42812  while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
42813  u32 bin = i/p->iDivisor;
42814  i = i%p->iDivisor;
42815  if( p->u.apSub[bin]==0 ){
42816  p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
42817  if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM_BKPT;
42818  }
42819  p = p->u.apSub[bin];
42820  }
42821  if( p->iSize<=BITVEC_NBIT ){
42822  p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
42823  return SQLITE_OK;
42824  }
42825  h = BITVEC_HASH(i++);
42826  /* if there wasn't a hash collision, and this doesn't */
42827  /* completely fill the hash, then just add it without */
42828  /* worring about sub-dividing and re-hashing. */
42829  if( !p->u.aHash[h] ){
42830  if (p->nSet<(BITVEC_NINT-1)) {
42831  goto bitvec_set_end;
42832  } else {
42833  goto bitvec_set_rehash;
42834  }
42835  }
42836  /* there was a collision, check to see if it's already */
42837  /* in hash, if not, try to find a spot for it */
42838  do {
42839  if( p->u.aHash[h]==i ) return SQLITE_OK;
42840  h++;
42841  if( h>=BITVEC_NINT ) h = 0;
42842  } while( p->u.aHash[h] );
42843  /* we didn't find it in the hash. h points to the first */
42844  /* available free spot. check to see if this is going to */
42845  /* make our hash too "full". */
42846 bitvec_set_rehash:
42847  if( p->nSet>=BITVEC_MXHASH ){
42848  unsigned int j;
42849  int rc;
42850  u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
42851  if( aiValues==0 ){
42852  return SQLITE_NOMEM_BKPT;
42853  }else{
42854  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
42855  memset(p->u.apSub, 0, sizeof(p->u.apSub));
42856  p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
42857  rc = sqlite3BitvecSet(p, i);
42858  for(j=0; j<BITVEC_NINT; j++){
42859  if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
42860  }
42861  sqlite3StackFree(0, aiValues);
42862  return rc;
42863  }
42864  }
42865 bitvec_set_end:
42866  p->nSet++;
42867  p->u.aHash[h] = i;
42868  return SQLITE_OK;
42869 }
42870 
42871 /*
42872 ** Clear the i-th bit.
42873 **
42874 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
42875 ** that BitvecClear can use to rebuilt its hash table.
42876 */
42877 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
42878  if( p==0 ) return;
42879  assert( i>0 );
42880  i--;
42881  while( p->iDivisor ){
42882  u32 bin = i/p->iDivisor;
42883  i = i%p->iDivisor;
42884  p = p->u.apSub[bin];
42885  if (!p) {
42886  return;
42887  }
42888  }
42889  if( p->iSize<=BITVEC_NBIT ){
42890  p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
42891  }else{
42892  unsigned int j;
42893  u32 *aiValues = pBuf;
42894  memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
42895  memset(p->u.aHash, 0, sizeof(p->u.aHash));
42896  p->nSet = 0;
42897  for(j=0; j<BITVEC_NINT; j++){
42898  if( aiValues[j] && aiValues[j]!=(i+1) ){
42899  u32 h = BITVEC_HASH(aiValues[j]-1);
42900  p->nSet++;
42901  while( p->u.aHash[h] ){
42902  h++;
42903  if( h>=BITVEC_NINT ) h = 0;
42904  }
42905  p->u.aHash[h] = aiValues[j];
42906  }
42907  }
42908  }
42909 }
42910 
42911 /*
42912 ** Destroy a bitmap object. Reclaim all memory used.
42913 */
42915  if( p==0 ) return;
42916  if( p->iDivisor ){
42917  unsigned int i;
42918  for(i=0; i<BITVEC_NPTR; i++){
42919  sqlite3BitvecDestroy(p->u.apSub[i]);
42920  }
42921  }
42922  sqlite3_free(p);
42923 }
42924 
42925 /*
42926 ** Return the value of the iSize parameter specified when Bitvec *p
42927 ** was created.
42928 */
42930  return p->iSize;
42931 }
42932 
42933 #ifndef SQLITE_OMIT_BUILTIN_TEST
42934 /*
42935 ** Let V[] be an array of unsigned characters sufficient to hold
42936 ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
42937 ** Then the following macros can be used to set, clear, or test
42938 ** individual bits within V.
42939 */
42940 #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
42941 #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
42942 #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
42943 
42944 /*
42945 ** This routine runs an extensive test of the Bitvec code.
42946 **
42947 ** The input is an array of integers that acts as a program
42948 ** to test the Bitvec. The integers are opcodes followed
42949 ** by 0, 1, or 3 operands, depending on the opcode. Another
42950 ** opcode follows immediately after the last operand.
42951 **
42952 ** There are 6 opcodes numbered from 0 through 5. 0 is the
42953 ** "halt" opcode and causes the test to end.
42954 **
42955 ** 0 Halt and return the number of errors
42956 ** 1 N S X Set N bits beginning with S and incrementing by X
42957 ** 2 N S X Clear N bits beginning with S and incrementing by X
42958 ** 3 N Set N randomly chosen bits
42959 ** 4 N Clear N randomly chosen bits
42960 ** 5 N S X Set N bits from S increment X in array only, not in bitvec
42961 **
42962 ** The opcodes 1 through 4 perform set and clear operations are performed
42963 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
42964 ** Opcode 5 works on the linear array only, not on the Bitvec.
42965 ** Opcode 5 is used to deliberately induce a fault in order to
42966 ** confirm that error detection works.
42967 **
42968 ** At the conclusion of the test the linear array is compared
42969 ** against the Bitvec object. If there are any differences,
42970 ** an error is returned. If they are the same, zero is returned.
42971 **
42972 ** If a memory allocation error occurs, return -1.
42973 */
42975  Bitvec *pBitvec = 0;
42976  unsigned char *pV = 0;
42977  int rc = -1;
42978  int i, nx, pc, op;
42979  void *pTmpSpace;
42980 
42981  /* Allocate the Bitvec to be tested and a linear array of
42982  ** bits to act as the reference */
42983  pBitvec = sqlite3BitvecCreate( sz );
42984  pV = sqlite3MallocZero( (sz+7)/8 + 1 );
42985  pTmpSpace = sqlite3_malloc64(BITVEC_SZ);
42986  if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
42987 
42988  /* NULL pBitvec tests */
42989  sqlite3BitvecSet(0, 1);
42990  sqlite3BitvecClear(0, 1, pTmpSpace);
42991 
42992  /* Run the program */
42993  pc = 0;
42994  while( (op = aOp[pc])!=0 ){
42995  switch( op ){
42996  case 1:
42997  case 2:
42998  case 5: {
42999  nx = 4;
43000  i = aOp[pc+2] - 1;
43001  aOp[pc+2] += aOp[pc+3];
43002  break;
43003  }
43004  case 3:
43005  case 4:
43006  default: {
43007  nx = 2;
43008  sqlite3_randomness(sizeof(i), &i);
43009  break;
43010  }
43011  }
43012  if( (--aOp[pc+1]) > 0 ) nx = 0;
43013  pc += nx;
43014  i = (i & 0x7fffffff)%sz;
43015  if( (op & 1)!=0 ){
43016  SETBIT(pV, (i+1));
43017  if( op!=5 ){
43018  if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
43019  }
43020  }else{
43021  CLEARBIT(pV, (i+1));
43022  sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
43023  }
43024  }
43025 
43026  /* Test to make sure the linear array exactly matches the
43027  ** Bitvec object. Start with the assumption that they do
43028  ** match (rc==0). Change rc to non-zero if a discrepancy
43029  ** is found.
43030  */
43031  rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
43032  + sqlite3BitvecTest(pBitvec, 0)
43033  + (sqlite3BitvecSize(pBitvec) - sz);
43034  for(i=1; i<=sz; i++){
43035  if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
43036  rc = i;
43037  break;
43038  }
43039  }
43040 
43041  /* Free allocated structure */
43042 bitvec_end:
43043  sqlite3_free(pTmpSpace);
43044  sqlite3_free(pV);
43045  sqlite3BitvecDestroy(pBitvec);
43046  return rc;
43047 }
43048 #endif /* SQLITE_OMIT_BUILTIN_TEST */
43049 
43050 /************** End of bitvec.c **********************************************/
43051 /************** Begin file pcache.c ******************************************/
43052 /*
43053 ** 2008 August 05
43054 **
43055 ** The author disclaims copyright to this source code. In place of
43056 ** a legal notice, here is a blessing:
43057 **
43058 ** May you do good and not evil.
43059 ** May you find forgiveness for yourself and forgive others.
43060 ** May you share freely, never taking more than you give.
43061 **
43062 *************************************************************************
43063 ** This file implements that page cache.
43064 */
43065 /* #include "sqliteInt.h" */
43066 
43067 /*
43068 ** A complete page cache is an instance of this structure. Every
43069 ** entry in the cache holds a single page of the database file. The
43070 ** btree layer only operates on the cached copy of the database pages.
43071 **
43072 ** A page cache entry is "clean" if it exactly matches what is currently
43073 ** on disk. A page is "dirty" if it has been modified and needs to be
43074 ** persisted to disk.
43075 **
43076 ** pDirty, pDirtyTail, pSynced:
43077 ** All dirty pages are linked into the doubly linked list using
43078 ** PgHdr.pDirtyNext and pDirtyPrev. The list is maintained in LRU order
43079 ** such that p was added to the list more recently than p->pDirtyNext.
43080 ** PCache.pDirty points to the first (newest) element in the list and
43081 ** pDirtyTail to the last (oldest).
43082 **
43083 ** The PCache.pSynced variable is used to optimize searching for a dirty
43084 ** page to eject from the cache mid-transaction. It is better to eject
43085 ** a page that does not require a journal sync than one that does.
43086 ** Therefore, pSynced is maintained to that it *almost* always points
43087 ** to either the oldest page in the pDirty/pDirtyTail list that has a
43088 ** clear PGHDR_NEED_SYNC flag or to a page that is older than this one
43089 ** (so that the right page to eject can be found by following pDirtyPrev
43090 ** pointers).
43091 */
43092 struct PCache {
43093  PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
43094  PgHdr *pSynced; /* Last synced page in dirty page list */
43095  int nRefSum; /* Sum of ref counts over all pages */
43096  int szCache; /* Configured cache size */
43097  int szSpill; /* Size before spilling occurs */
43098  int szPage; /* Size of every page in this cache */
43099  int szExtra; /* Size of extra space for each page */
43100  u8 bPurgeable; /* True if pages are on backing store */
43101  u8 eCreate; /* eCreate value for for xFetch() */
43102  int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
43103  void *pStress; /* Argument to xStress */
43104  sqlite3_pcache *pCache; /* Pluggable cache module */
43105 };
43106 
43107 /********************************** Test and Debug Logic **********************/
43108 /*
43109 ** Debug tracing macros. Enable by by changing the "0" to "1" and
43110 ** recompiling.
43111 **
43112 ** When sqlite3PcacheTrace is 1, single line trace messages are issued.
43113 ** When sqlite3PcacheTrace is 2, a dump of the pcache showing all cache entries
43114 ** is displayed for many operations, resulting in a lot of output.
43115 */
43116 #if defined(SQLITE_DEBUG) && 0
43117  int sqlite3PcacheTrace = 2; /* 0: off 1: simple 2: cache dumps */
43118  int sqlite3PcacheMxDump = 9999; /* Max cache entries for pcacheDump() */
43119 # define pcacheTrace(X) if(sqlite3PcacheTrace){sqlite3DebugPrintf X;}
43120  void pcacheDump(PCache *pCache){
43121  int N;
43122  int i, j;
43123  sqlite3_pcache_page *pLower;
43124  PgHdr *pPg;
43125  unsigned char *a;
43126 
43127  if( sqlite3PcacheTrace<2 ) return;
43128  if( pCache->pCache==0 ) return;
43129  N = sqlite3PcachePagecount(pCache);
43130  if( N>sqlite3PcacheMxDump ) N = sqlite3PcacheMxDump;
43131  for(i=1; i<=N; i++){
43132  pLower = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, i, 0);
43133  if( pLower==0 ) continue;
43134  pPg = (PgHdr*)pLower->pExtra;
43135  printf("%3d: nRef %2d flgs %02x data ", i, pPg->nRef, pPg->flags);
43136  a = (unsigned char *)pLower->pBuf;
43137  for(j=0; j<12; j++) printf("%02x", a[j]);
43138  printf("\n");
43139  if( pPg->pPage==0 ){
43140  sqlite3GlobalConfig.pcache2.xUnpin(pCache->pCache, pLower, 0);
43141  }
43142  }
43143  }
43144  #else
43145 # define pcacheTrace(X)
43146 # define pcacheDump(X)
43147 #endif
43148 
43149 /*
43150 ** Check invariants on a PgHdr entry. Return true if everything is OK.
43151 ** Return false if any invariant is violated.
43152 **
43153 ** This routine is for use inside of assert() statements only. For
43154 ** example:
43155 **
43156 ** assert( sqlite3PcachePageSanity(pPg) );
43157 */
43158 #if SQLITE_DEBUG
43159 SQLITE_PRIVATE int sqlite3PcachePageSanity(PgHdr *pPg){
43160  PCache *pCache;
43161  assert( pPg!=0 );
43162  assert( pPg->pgno>0 ); /* Page number is 1 or more */
43163  pCache = pPg->pCache;
43164  assert( pCache!=0 ); /* Every page has an associated PCache */
43165  if( pPg->flags & PGHDR_CLEAN ){
43166  assert( (pPg->flags & PGHDR_DIRTY)==0 );/* Cannot be both CLEAN and DIRTY */
43167  assert( pCache->pDirty!=pPg ); /* CLEAN pages not on dirty list */
43168  assert( pCache->pDirtyTail!=pPg );
43169  }
43170  /* WRITEABLE pages must also be DIRTY */
43171  if( pPg->flags & PGHDR_WRITEABLE ){
43172  assert( pPg->flags & PGHDR_DIRTY ); /* WRITEABLE implies DIRTY */
43173  }
43174  /* NEED_SYNC can be set independently of WRITEABLE. This can happen,
43175  ** for example, when using the sqlite3PagerDontWrite() optimization:
43176  ** (1) Page X is journalled, and gets WRITEABLE and NEED_SEEK.
43177  ** (2) Page X moved to freelist, WRITEABLE is cleared
43178  ** (3) Page X reused, WRITEABLE is set again
43179  ** If NEED_SYNC had been cleared in step 2, then it would not be reset
43180  ** in step 3, and page might be written into the database without first
43181  ** syncing the rollback journal, which might cause corruption on a power
43182  ** loss.
43183  **
43184  ** Another example is when the database page size is smaller than the
43185  ** disk sector size. When any page of a sector is journalled, all pages
43186  ** in that sector are marked NEED_SYNC even if they are still CLEAN, just
43187  ** in case they are later modified, since all pages in the same sector
43188  ** must be journalled and synced before any of those pages can be safely
43189  ** written.
43190  */
43191  return 1;
43192 }
43193 #endif /* SQLITE_DEBUG */
43194 
43195 
43196 /********************************** Linked List Management ********************/
43197 
43198 /* Allowed values for second argument to pcacheManageDirtyList() */
43199 #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
43200 #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
43201 #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
43202 
43203 /*
43204 ** Manage pPage's participation on the dirty list. Bits of the addRemove
43205 ** argument determines what operation to do. The 0x01 bit means first
43206 ** remove pPage from the dirty list. The 0x02 means add pPage back to
43207 ** the dirty list. Doing both moves pPage to the front of the dirty list.
43208 */
43209 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
43210  PCache *p = pPage->pCache;
43211 
43212  pcacheTrace(("%p.DIRTYLIST.%s %d\n", p,
43213  addRemove==1 ? "REMOVE" : addRemove==2 ? "ADD" : "FRONT",
43214  pPage->pgno));
43215  if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
43216  assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
43217  assert( pPage->pDirtyPrev || pPage==p->pDirty );
43218 
43219  /* Update the PCache1.pSynced variable if necessary. */
43220  if( p->pSynced==pPage ){
43221  p->pSynced = pPage->pDirtyPrev;
43222  }
43223 
43224  if( pPage->pDirtyNext ){
43225  pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
43226  }else{
43227  assert( pPage==p->pDirtyTail );
43228  p->pDirtyTail = pPage->pDirtyPrev;
43229  }
43230  if( pPage->pDirtyPrev ){
43231  pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
43232  }else{
43233  /* If there are now no dirty pages in the cache, set eCreate to 2.
43234  ** This is an optimization that allows sqlite3PcacheFetch() to skip
43235  ** searching for a dirty page to eject from the cache when it might
43236  ** otherwise have to. */
43237  assert( pPage==p->pDirty );
43238  p->pDirty = pPage->pDirtyNext;
43239  assert( p->bPurgeable || p->eCreate==2 );
43240  if( p->pDirty==0 ){ /*OPTIMIZATION-IF-TRUE*/
43241  assert( p->bPurgeable==0 || p->eCreate==1 );
43242  p->eCreate = 2;
43243  }
43244  }
43245  pPage->pDirtyNext = 0;
43246  pPage->pDirtyPrev = 0;
43247  }
43248  if( addRemove & PCACHE_DIRTYLIST_ADD ){
43249  assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
43250 
43251  pPage->pDirtyNext = p->pDirty;
43252  if( pPage->pDirtyNext ){
43253  assert( pPage->pDirtyNext->pDirtyPrev==0 );
43254  pPage->pDirtyNext->pDirtyPrev = pPage;
43255  }else{
43256  p->pDirtyTail = pPage;
43257  if( p->bPurgeable ){
43258  assert( p->eCreate==2 );
43259  p->eCreate = 1;
43260  }
43261  }
43262  p->pDirty = pPage;
43263 
43264  /* If pSynced is NULL and this page has a clear NEED_SYNC flag, set
43265  ** pSynced to point to it. Checking the NEED_SYNC flag is an
43266  ** optimization, as if pSynced points to a page with the NEED_SYNC
43267  ** flag set sqlite3PcacheFetchStress() searches through all newer
43268  ** entries of the dirty-list for a page with NEED_SYNC clear anyway. */
43269  if( !p->pSynced
43270  && 0==(pPage->flags&PGHDR_NEED_SYNC) /*OPTIMIZATION-IF-FALSE*/
43271  ){
43272  p->pSynced = pPage;
43273  }
43274  }
43275  pcacheDump(p);
43276 }
43277 
43278 /*
43279 ** Wrapper around the pluggable caches xUnpin method. If the cache is
43280 ** being used for an in-memory database, this function is a no-op.
43281 */
43282 static void pcacheUnpin(PgHdr *p){
43283  if( p->pCache->bPurgeable ){
43284  pcacheTrace(("%p.UNPIN %d\n", p->pCache, p->pgno));
43285  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
43286  pcacheDump(p->pCache);
43287  }
43288 }
43289 
43290 /*
43291 ** Compute the number of pages of cache requested. p->szCache is the
43292 ** cache size requested by the "PRAGMA cache_size" statement.
43293 */
43295  if( p->szCache>=0 ){
43296  /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
43297  ** suggested cache size is set to N. */
43298  return p->szCache;
43299  }else{
43300  /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
43301  ** the number of cache pages is adjusted to use approximately abs(N*1024)
43302  ** bytes of memory. */
43303  return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
43304  }
43305 }
43306 
43307 /*************************************************** General Interfaces ******
43308 **
43309 ** Initialize and shutdown the page cache subsystem. Neither of these
43310 ** functions are threadsafe.
43311 */
43313  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
43314  /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
43315  ** built-in default page cache is used instead of the application defined
43316  ** page cache. */
43318  }
43319  return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
43320 }
43322  if( sqlite3GlobalConfig.pcache2.xShutdown ){
43323  /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
43324  sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
43325  }
43326 }
43327 
43328 /*
43329 ** Return the size in bytes of a PCache object.
43330 */
43331 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
43332 
43333 /*
43334 ** Create a new PCache object. Storage space to hold the object
43335 ** has already been allocated and is passed in as the p pointer.
43336 ** The caller discovers how much space needs to be allocated by
43337 ** calling sqlite3PcacheSize().
43338 */
43340  int szPage, /* Size of every page */
43341  int szExtra, /* Extra space associated with each page */
43342  int bPurgeable, /* True if pages are on backing store */
43343  int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
43344  void *pStress, /* Argument to xStress */
43345  PCache *p /* Preallocated space for the PCache */
43346 ){
43347  memset(p, 0, sizeof(PCache));
43348  p->szPage = 1;
43349  p->szExtra = szExtra;
43350  p->bPurgeable = bPurgeable;
43351  p->eCreate = 2;
43352  p->xStress = xStress;
43353  p->pStress = pStress;
43354  p->szCache = 100;
43355  p->szSpill = 1;
43356  pcacheTrace(("%p.OPEN szPage %d bPurgeable %d\n",p,szPage,bPurgeable));
43357  return sqlite3PcacheSetPageSize(p, szPage);
43358 }
43359 
43360 /*
43361 ** Change the page size for PCache object. The caller must ensure that there
43362 ** are no outstanding page references when this function is called.
43363 */
43365  assert( pCache->nRefSum==0 && pCache->pDirty==0 );
43366  if( pCache->szPage ){
43367  sqlite3_pcache *pNew;
43368  pNew = sqlite3GlobalConfig.pcache2.xCreate(
43369  szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
43370  pCache->bPurgeable
43371  );
43372  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
43373  sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
43374  if( pCache->pCache ){
43375  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43376  }
43377  pCache->pCache = pNew;
43378  pCache->szPage = szPage;
43379  pcacheTrace(("%p.PAGESIZE %d\n",pCache,szPage));
43380  }
43381  return SQLITE_OK;
43382 }
43383 
43384 /*
43385 ** Try to obtain a page from the cache.
43386 **
43387 ** This routine returns a pointer to an sqlite3_pcache_page object if
43388 ** such an object is already in cache, or if a new one is created.
43389 ** This routine returns a NULL pointer if the object was not in cache
43390 ** and could not be created.
43391 **
43392 ** The createFlags should be 0 to check for existing pages and should
43393 ** be 3 (not 1, but 3) to try to create a new page.
43394 **
43395 ** If the createFlag is 0, then NULL is always returned if the page
43396 ** is not already in the cache. If createFlag is 1, then a new page
43397 ** is created only if that can be done without spilling dirty pages
43398 ** and without exceeding the cache size limit.
43399 **
43400 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
43401 ** initialize the sqlite3_pcache_page object and convert it into a
43402 ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
43403 ** routines are split this way for performance reasons. When separated
43404 ** they can both (usually) operate without having to push values to
43405 ** the stack on entry and pop them back off on exit, which saves a
43406 ** lot of pushing and popping.
43407 */
43409  PCache *pCache, /* Obtain the page from this cache */
43410  Pgno pgno, /* Page number to obtain */
43411  int createFlag /* If true, create page if it does not exist already */
43412 ){
43413  int eCreate;
43414  sqlite3_pcache_page *pRes;
43415 
43416  assert( pCache!=0 );
43417  assert( pCache->pCache!=0 );
43418  assert( createFlag==3 || createFlag==0 );
43419  assert( pgno>0 );
43420  assert( pCache->eCreate==((pCache->bPurgeable && pCache->pDirty) ? 1 : 2) );
43421 
43422  /* eCreate defines what to do if the page does not exist.
43423  ** 0 Do not allocate a new page. (createFlag==0)
43424  ** 1 Allocate a new page if doing so is inexpensive.
43425  ** (createFlag==1 AND bPurgeable AND pDirty)
43426  ** 2 Allocate a new page even it doing so is difficult.
43427  ** (createFlag==1 AND !(bPurgeable AND pDirty)
43428  */
43429  eCreate = createFlag & pCache->eCreate;
43430  assert( eCreate==0 || eCreate==1 || eCreate==2 );
43431  assert( createFlag==0 || pCache->eCreate==eCreate );
43432  assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
43433  pRes = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
43434  pcacheTrace(("%p.FETCH %d%s (result: %p)\n",pCache,pgno,
43435  createFlag?" create":"",pRes));
43436  return pRes;
43437 }
43438 
43439 /*
43440 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
43441 ** page because no clean pages are available for reuse and the cache
43442 ** size limit has been reached, then this routine can be invoked to
43443 ** try harder to allocate a page. This routine might invoke the stress
43444 ** callback to spill dirty pages to the journal. It will then try to
43445 ** allocate the new page and will only fail to allocate a new page on
43446 ** an OOM error.
43447 **
43448 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
43449 */
43451  PCache *pCache, /* Obtain the page from this cache */
43452  Pgno pgno, /* Page number to obtain */
43453  sqlite3_pcache_page **ppPage /* Write result here */
43454 ){
43455  PgHdr *pPg;
43456  if( pCache->eCreate==2 ) return 0;
43457 
43458  if( sqlite3PcachePagecount(pCache)>pCache->szSpill ){
43459  /* Find a dirty page to write-out and recycle. First try to find a
43460  ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
43461  ** cleared), but if that is not possible settle for any other
43462  ** unreferenced dirty page.
43463  **
43464  ** If the LRU page in the dirty list that has a clear PGHDR_NEED_SYNC
43465  ** flag is currently referenced, then the following may leave pSynced
43466  ** set incorrectly (pointing to other than the LRU page with NEED_SYNC
43467  ** cleared). This is Ok, as pSynced is just an optimization. */
43468  for(pPg=pCache->pSynced;
43469  pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
43470  pPg=pPg->pDirtyPrev
43471  );
43472  pCache->pSynced = pPg;
43473  if( !pPg ){
43474  for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
43475  }
43476  if( pPg ){
43477  int rc;
43478 #ifdef SQLITE_LOG_CACHE_SPILL
43479  sqlite3_log(SQLITE_FULL,
43480  "spill page %d making room for %d - cache used: %d/%d",
43481  pPg->pgno, pgno,
43482  sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
43483  numberOfCachePages(pCache));
43484 #endif
43485  pcacheTrace(("%p.SPILL %d\n",pCache,pPg->pgno));
43486  rc = pCache->xStress(pCache->pStress, pPg);
43487  pcacheDump(pCache);
43488  if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
43489  return rc;
43490  }
43491  }
43492  }
43493  *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
43494  return *ppPage==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
43495 }
43496 
43497 /*
43498 ** This is a helper routine for sqlite3PcacheFetchFinish()
43499 **
43500 ** In the uncommon case where the page being fetched has not been
43501 ** initialized, this routine is invoked to do the initialization.
43502 ** This routine is broken out into a separate function since it
43503 ** requires extra stack manipulation that can be avoided in the common
43504 ** case.
43505 */
43507  PCache *pCache, /* Obtain the page from this cache */
43508  Pgno pgno, /* Page number obtained */
43509  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
43510 ){
43511  PgHdr *pPgHdr;
43512  assert( pPage!=0 );
43513  pPgHdr = (PgHdr*)pPage->pExtra;
43514  assert( pPgHdr->pPage==0 );
43515  memset(pPgHdr, 0, sizeof(PgHdr));
43516  pPgHdr->pPage = pPage;
43517  pPgHdr->pData = pPage->pBuf;
43518  pPgHdr->pExtra = (void *)&pPgHdr[1];
43519  memset(pPgHdr->pExtra, 0, pCache->szExtra);
43520  pPgHdr->pCache = pCache;
43521  pPgHdr->pgno = pgno;
43522  pPgHdr->flags = PGHDR_CLEAN;
43523  return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
43524 }
43525 
43526 /*
43527 ** This routine converts the sqlite3_pcache_page object returned by
43528 ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
43529 ** must be called after sqlite3PcacheFetch() in order to get a usable
43530 ** result.
43531 */
43533  PCache *pCache, /* Obtain the page from this cache */
43534  Pgno pgno, /* Page number obtained */
43535  sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
43536 ){
43537  PgHdr *pPgHdr;
43538 
43539  assert( pPage!=0 );
43540  pPgHdr = (PgHdr *)pPage->pExtra;
43541 
43542  if( !pPgHdr->pPage ){
43543  return pcacheFetchFinishWithInit(pCache, pgno, pPage);
43544  }
43545  pCache->nRefSum++;
43546  pPgHdr->nRef++;
43547  assert( sqlite3PcachePageSanity(pPgHdr) );
43548  return pPgHdr;
43549 }
43550 
43551 /*
43552 ** Decrement the reference count on a page. If the page is clean and the
43553 ** reference count drops to 0, then it is made eligible for recycling.
43554 */
43556  assert( p->nRef>0 );
43557  p->pCache->nRefSum--;
43558  if( (--p->nRef)==0 ){
43559  if( p->flags&PGHDR_CLEAN ){
43560  pcacheUnpin(p);
43561  }else if( p->pDirtyPrev!=0 ){ /*OPTIMIZATION-IF-FALSE*/
43562  /* Move the page to the head of the dirty list. If p->pDirtyPrev==0,
43563  ** then page p is already at the head of the dirty list and the
43564  ** following call would be a no-op. Hence the OPTIMIZATION-IF-FALSE
43565  ** tag above. */
43567  }
43568  }
43569 }
43570 
43571 /*
43572 ** Increase the reference count of a supplied page by 1.
43573 */
43575  assert(p->nRef>0);
43576  assert( sqlite3PcachePageSanity(p) );
43577  p->nRef++;
43578  p->pCache->nRefSum++;
43579 }
43580 
43581 /*
43582 ** Drop a page from the cache. There must be exactly one reference to the
43583 ** page. This function deletes that reference, so after it returns the
43584 ** page pointed to by p is invalid.
43585 */
43587  assert( p->nRef==1 );
43588  assert( sqlite3PcachePageSanity(p) );
43589  if( p->flags&PGHDR_DIRTY ){
43591  }
43592  p->pCache->nRefSum--;
43593  sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
43594 }
43595 
43596 /*
43597 ** Make sure the page is marked as dirty. If it isn't dirty already,
43598 ** make it so.
43599 */
43601  assert( p->nRef>0 );
43602  assert( sqlite3PcachePageSanity(p) );
43603  if( p->flags & (PGHDR_CLEAN|PGHDR_DONT_WRITE) ){ /*OPTIMIZATION-IF-FALSE*/
43604  p->flags &= ~PGHDR_DONT_WRITE;
43605  if( p->flags & PGHDR_CLEAN ){
43606  p->flags ^= (PGHDR_DIRTY|PGHDR_CLEAN);
43607  pcacheTrace(("%p.DIRTY %d\n",p->pCache,p->pgno));
43610  }
43611  assert( sqlite3PcachePageSanity(p) );
43612  }
43613 }
43614 
43615 /*
43616 ** Make sure the page is marked as clean. If it isn't clean already,
43617 ** make it so.
43618 */
43620  assert( sqlite3PcachePageSanity(p) );
43621  if( ALWAYS((p->flags & PGHDR_DIRTY)!=0) ){
43622  assert( (p->flags & PGHDR_CLEAN)==0 );
43625  p->flags |= PGHDR_CLEAN;
43626  pcacheTrace(("%p.CLEAN %d\n",p->pCache,p->pgno));
43627  assert( sqlite3PcachePageSanity(p) );
43628  if( p->nRef==0 ){
43629  pcacheUnpin(p);
43630  }
43631  }
43632 }
43633 
43634 /*
43635 ** Make every page in the cache clean.
43636 */
43638  PgHdr *p;
43639  pcacheTrace(("%p.CLEAN-ALL\n",pCache));
43640  while( (p = pCache->pDirty)!=0 ){
43642  }
43643 }
43644 
43645 /*
43646 ** Clear the PGHDR_NEED_SYNC and PGHDR_WRITEABLE flag from all dirty pages.
43647 */
43649  PgHdr *p;
43650  pcacheTrace(("%p.CLEAR-WRITEABLE\n",pCache));
43651  for(p=pCache->pDirty; p; p=p->pDirtyNext){
43653  }
43654  pCache->pSynced = pCache->pDirtyTail;
43655 }
43656 
43657 /*
43658 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
43659 */
43661  PgHdr *p;
43662  for(p=pCache->pDirty; p; p=p->pDirtyNext){
43663  p->flags &= ~PGHDR_NEED_SYNC;
43664  }
43665  pCache->pSynced = pCache->pDirtyTail;
43666 }
43667 
43668 /*
43669 ** Change the page number of page p to newPgno.
43670 */
43671 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
43672  PCache *pCache = p->pCache;
43673  assert( p->nRef>0 );
43674  assert( newPgno>0 );
43675  assert( sqlite3PcachePageSanity(p) );
43676  pcacheTrace(("%p.MOVE %d -> %d\n",pCache,p->pgno,newPgno));
43677  sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
43678  p->pgno = newPgno;
43679  if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
43681  }
43682 }
43683 
43684 /*
43685 ** Drop every cache entry whose page number is greater than "pgno". The
43686 ** caller must ensure that there are no outstanding references to any pages
43687 ** other than page 1 with a page number greater than pgno.
43688 **
43689 ** If there is a reference to page 1 and the pgno parameter passed to this
43690 ** function is 0, then the data area associated with page 1 is zeroed, but
43691 ** the page object is not dropped.
43692 */
43694  if( pCache->pCache ){
43695  PgHdr *p;
43696  PgHdr *pNext;
43697  pcacheTrace(("%p.TRUNCATE %d\n",pCache,pgno));
43698  for(p=pCache->pDirty; p; p=pNext){
43699  pNext = p->pDirtyNext;
43700  /* This routine never gets call with a positive pgno except right
43701  ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
43702  ** it must be that pgno==0.
43703  */
43704  assert( p->pgno>0 );
43705  if( p->pgno>pgno ){
43706  assert( p->flags&PGHDR_DIRTY );
43708  }
43709  }
43710  if( pgno==0 && pCache->nRefSum ){
43711  sqlite3_pcache_page *pPage1;
43712  pPage1 = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache,1,0);
43713  if( ALWAYS(pPage1) ){ /* Page 1 is always available in cache, because
43714  ** pCache->nRefSum>0 */
43715  memset(pPage1->pBuf, 0, pCache->szPage);
43716  pgno = 1;
43717  }
43718  }
43719  sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
43720  }
43721 }
43722 
43723 /*
43724 ** Close a cache.
43725 */
43727  assert( pCache->pCache!=0 );
43728  pcacheTrace(("%p.CLOSE\n",pCache));
43729  sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
43730 }
43731 
43732 /*
43733 ** Discard the contents of the cache.
43734 */
43736  sqlite3PcacheTruncate(pCache, 0);
43737 }
43738 
43739 /*
43740 ** Merge two lists of pages connected by pDirty and in pgno order.
43741 ** Do not both fixing the pDirtyPrev pointers.
43742 */
43744  PgHdr result, *pTail;
43745  pTail = &result;
43746  while( pA && pB ){
43747  if( pA->pgno<pB->pgno ){
43748  pTail->pDirty = pA;
43749  pTail = pA;
43750  pA = pA->pDirty;
43751  }else{
43752  pTail->pDirty = pB;
43753  pTail = pB;
43754  pB = pB->pDirty;
43755  }
43756  }
43757  if( pA ){
43758  pTail->pDirty = pA;
43759  }else if( pB ){
43760  pTail->pDirty = pB;
43761  }else{
43762  pTail->pDirty = 0;
43763  }
43764  return result.pDirty;
43765 }
43766 
43767 /*
43768 ** Sort the list of pages in accending order by pgno. Pages are
43769 ** connected by pDirty pointers. The pDirtyPrev pointers are
43770 ** corrupted by this sort.
43771 **
43772 ** Since there cannot be more than 2^31 distinct pages in a database,
43773 ** there cannot be more than 31 buckets required by the merge sorter.
43774 ** One extra bucket is added to catch overflow in case something
43775 ** ever changes to make the previous sentence incorrect.
43776 */
43777 #define N_SORT_BUCKET 32
43779  PgHdr *a[N_SORT_BUCKET], *p;
43780  int i;
43781  memset(a, 0, sizeof(a));
43782  while( pIn ){
43783  p = pIn;
43784  pIn = p->pDirty;
43785  p->pDirty = 0;
43786  for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
43787  if( a[i]==0 ){
43788  a[i] = p;
43789  break;
43790  }else{
43791  p = pcacheMergeDirtyList(a[i], p);
43792  a[i] = 0;
43793  }
43794  }
43795  if( NEVER(i==N_SORT_BUCKET-1) ){
43796  /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
43797  ** the input list. But that is impossible.
43798  */
43799  a[i] = pcacheMergeDirtyList(a[i], p);
43800  }
43801  }
43802  p = a[0];
43803  for(i=1; i<N_SORT_BUCKET; i++){
43804  p = pcacheMergeDirtyList(p, a[i]);
43805  }
43806  return p;
43807 }
43808 
43809 /*
43810 ** Return a list of all dirty pages in the cache, sorted by page number.
43811 */
43813  PgHdr *p;
43814  for(p=pCache->pDirty; p; p=p->pDirtyNext){
43815  p->pDirty = p->pDirtyNext;
43816  }
43817  return pcacheSortDirtyList(pCache->pDirty);
43818 }
43819 
43820 /*
43821 ** Return the total number of references to all pages held by the cache.
43822 **
43823 ** This is not the total number of pages referenced, but the sum of the
43824 ** reference count for all pages.
43825 */
43827  return pCache->nRefSum;
43828 }
43829 
43830 /*
43831 ** Return the number of references to the page supplied as an argument.
43832 */
43834  return p->nRef;
43835 }
43836 
43837 /*
43838 ** Return the total number of pages in the cache.
43839 */
43841  assert( pCache->pCache!=0 );
43842  return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
43843 }
43844 
43845 #ifdef SQLITE_TEST
43846 /*
43847 ** Get the suggested cache-size value.
43848 */
43849 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
43850  return numberOfCachePages(pCache);
43851 }
43852 #endif
43853 
43854 /*
43855 ** Set the suggested cache-size value.
43856 */
43858  assert( pCache->pCache!=0 );
43859  pCache->szCache = mxPage;
43860  sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
43861  numberOfCachePages(pCache));
43862 }
43863 
43864 /*
43865 ** Set the suggested cache-spill value. Make no changes if if the
43866 ** argument is zero. Return the effective cache-spill size, which will
43867 ** be the larger of the szSpill and szCache.
43868 */
43870  int res;
43871  assert( p->pCache!=0 );
43872  if( mxPage ){
43873  if( mxPage<0 ){
43874  mxPage = (int)((-1024*(i64)mxPage)/(p->szPage+p->szExtra));
43875  }
43876  p->szSpill = mxPage;
43877  }
43878  res = numberOfCachePages(p);
43879  if( res<p->szSpill ) res = p->szSpill;
43880  return res;
43881 }
43882 
43883 /*
43884 ** Free up as much memory as possible from the page cache.
43885 */
43887  assert( pCache->pCache!=0 );
43888  sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
43889 }
43890 
43891 /*
43892 ** Return the size of the header added by this middleware layer
43893 ** in the page-cache hierarchy.
43894 */
43896 
43897 /*
43898 ** Return the number of dirty pages currently in the cache, as a percentage
43899 ** of the configured cache size.
43900 */
43902  PgHdr *pDirty;
43903  int nDirty = 0;
43904  int nCache = numberOfCachePages(pCache);
43905  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext) nDirty++;
43906  return nCache ? (int)(((i64)nDirty * 100) / nCache) : 0;
43907 }
43908 
43909 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
43910 /*
43911 ** For all dirty pages currently in the cache, invoke the specified
43912 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
43913 ** defined.
43914 */
43915 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
43916  PgHdr *pDirty;
43917  for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
43918  xIter(pDirty);
43919  }
43920 }
43921 #endif
43922 
43923 /************** End of pcache.c **********************************************/
43924 /************** Begin file pcache1.c *****************************************/
43925 /*
43926 ** 2008 November 05
43927 **
43928 ** The author disclaims copyright to this source code. In place of
43929 ** a legal notice, here is a blessing:
43930 **
43931 ** May you do good and not evil.
43932 ** May you find forgiveness for yourself and forgive others.
43933 ** May you share freely, never taking more than you give.
43934 **
43935 *************************************************************************
43936 **
43937 ** This file implements the default page cache implementation (the
43938 ** sqlite3_pcache interface). It also contains part of the implementation
43939 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
43940 ** If the default page cache implementation is overridden, then neither of
43941 ** these two features are available.
43942 **
43943 ** A Page cache line looks like this:
43944 **
43945 ** -------------------------------------------------------------
43946 ** | database page content | PgHdr1 | MemPage | PgHdr |
43947 ** -------------------------------------------------------------
43948 **
43949 ** The database page content is up front (so that buffer overreads tend to
43950 ** flow harmlessly into the PgHdr1, MemPage, and PgHdr extensions). MemPage
43951 ** is the extension added by the btree.c module containing information such
43952 ** as the database page number and how that database page is used. PgHdr
43953 ** is added by the pcache.c layer and contains information used to keep track
43954 ** of which pages are "dirty". PgHdr1 is an extension added by this
43955 ** module (pcache1.c). The PgHdr1 header is a subclass of sqlite3_pcache_page.
43956 ** PgHdr1 contains information needed to look up a page by its page number.
43957 ** The superclass sqlite3_pcache_page.pBuf points to the start of the
43958 ** database page content and sqlite3_pcache_page.pExtra points to PgHdr.
43959 **
43960 ** The size of the extension (MemPage+PgHdr+PgHdr1) can be determined at
43961 ** runtime using sqlite3_config(SQLITE_CONFIG_PCACHE_HDRSZ, &size). The
43962 ** sizes of the extensions sum to 272 bytes on x64 for 3.8.10, but this
43963 ** size can vary according to architecture, compile-time options, and
43964 ** SQLite library version number.
43965 **
43966 ** If SQLITE_PCACHE_SEPARATE_HEADER is defined, then the extension is obtained
43967 ** using a separate memory allocation from the database page content. This
43968 ** seeks to overcome the "clownshoe" problem (also called "internal
43969 ** fragmentation" in academic literature) of allocating a few bytes more
43970 ** than a power of two with the memory allocator rounding up to the next
43971 ** power of two, and leaving the rounded-up space unused.
43972 **
43973 ** This module tracks pointers to PgHdr1 objects. Only pcache.c communicates
43974 ** with this module. Information is passed back and forth as PgHdr1 pointers.
43975 **
43976 ** The pcache.c and pager.c modules deal pointers to PgHdr objects.
43977 ** The btree.c module deals with pointers to MemPage objects.
43978 **
43979 ** SOURCE OF PAGE CACHE MEMORY:
43980 **
43981 ** Memory for a page might come from any of three sources:
43982 **
43983 ** (1) The general-purpose memory allocator - sqlite3Malloc()
43984 ** (2) Global page-cache memory provided using sqlite3_config() with
43985 ** SQLITE_CONFIG_PAGECACHE.
43986 ** (3) PCache-local bulk allocation.
43987 **
43988 ** The third case is a chunk of heap memory (defaulting to 100 pages worth)
43989 ** that is allocated when the page cache is created. The size of the local
43990 ** bulk allocation can be adjusted using
43991 **
43992 ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, (void*)0, 0, N).
43993 **
43994 ** If N is positive, then N pages worth of memory are allocated using a single
43995 ** sqlite3Malloc() call and that memory is used for the first N pages allocated.
43996 ** Or if N is negative, then -1024*N bytes of memory are allocated and used
43997 ** for as many pages as can be accomodated.
43998 **
43999 ** Only one of (2) or (3) can be used. Once the memory available to (2) or
44000 ** (3) is exhausted, subsequent allocations fail over to the general-purpose
44001 ** memory allocator (1).
44002 **
44003 ** Earlier versions of SQLite used only methods (1) and (2). But experiments
44004 ** show that method (3) with N==100 provides about a 5% performance boost for
44005 ** common workloads.
44006 */
44007 /* #include "sqliteInt.h" */
44008 
44009 typedef struct PCache1 PCache1;
44010 typedef struct PgHdr1 PgHdr1;
44011 typedef struct PgFreeslot PgFreeslot;
44012 typedef struct PGroup PGroup;
44013 
44014 /*
44015 ** Each cache entry is represented by an instance of the following
44016 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
44017 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
44018 ** in memory.
44019 */
44020 struct PgHdr1 {
44021  sqlite3_pcache_page page; /* Base class. Must be first. pBuf & pExtra */
44022  unsigned int iKey; /* Key value (page number) */
44023  u8 isPinned; /* Page in use, not on the LRU list */
44024  u8 isBulkLocal; /* This page from bulk local storage */
44025  u8 isAnchor; /* This is the PGroup.lru element */
44026  PgHdr1 *pNext; /* Next in hash table chain */
44027  PCache1 *pCache; /* Cache that currently owns this page */
44028  PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
44029  PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
44030 };
44031 
44032 /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
44033 ** of one or more PCaches that are able to recycle each other's unpinned
44034 ** pages when they are under memory pressure. A PGroup is an instance of
44035 ** the following object.
44036 **
44037 ** This page cache implementation works in one of two modes:
44038 **
44039 ** (1) Every PCache is the sole member of its own PGroup. There is
44040 ** one PGroup per PCache.
44041 **
44042 ** (2) There is a single global PGroup that all PCaches are a member
44043 ** of.
44044 **
44045 ** Mode 1 uses more memory (since PCache instances are not able to rob
44046 ** unused pages from other PCaches) but it also operates without a mutex,
44047 ** and is therefore often faster. Mode 2 requires a mutex in order to be
44048 ** threadsafe, but recycles pages more efficiently.
44049 **
44050 ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
44051 ** PGroup which is the pcache1.grp global variable and its mutex is
44052 ** SQLITE_MUTEX_STATIC_LRU.
44053 */
44054 struct PGroup {
44055  sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
44056  unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
44057  unsigned int nMinPage; /* Sum of nMin for purgeable caches */
44058  unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
44059  unsigned int nCurrentPage; /* Number of purgeable pages allocated */
44060  PgHdr1 lru; /* The beginning and end of the LRU list */
44061 };
44062 
44063 /* Each page cache is an instance of the following object. Every
44064 ** open database file (including each in-memory database and each
44065 ** temporary or transient database) has a single page cache which
44066 ** is an instance of this object.
44067 **
44068 ** Pointers to structures of this type are cast and returned as
44069 ** opaque sqlite3_pcache* handles.
44070 */
44071 struct PCache1 {
44072  /* Cache configuration parameters. Page size (szPage) and the purgeable
44073  ** flag (bPurgeable) are set when the cache is created. nMax may be
44074  ** modified at any time by a call to the pcache1Cachesize() method.
44075  ** The PGroup mutex must be held when accessing nMax.
44076  */
44077  PGroup *pGroup; /* PGroup this cache belongs to */
44078  int szPage; /* Size of database content section */
44079  int szExtra; /* sizeof(MemPage)+sizeof(PgHdr) */
44080  int szAlloc; /* Total size of one pcache line */
44081  int bPurgeable; /* True if cache is purgeable */
44082  unsigned int nMin; /* Minimum number of pages reserved */
44083  unsigned int nMax; /* Configured "cache_size" value */
44084  unsigned int n90pct; /* nMax*9/10 */
44085  unsigned int iMaxKey; /* Largest key seen since xTruncate() */
44086 
44087  /* Hash table of all pages. The following variables may only be accessed
44088  ** when the accessor is holding the PGroup mutex.
44089  */
44090  unsigned int nRecyclable; /* Number of pages in the LRU list */
44091  unsigned int nPage; /* Total number of pages in apHash */
44092  unsigned int nHash; /* Number of slots in apHash[] */
44093  PgHdr1 **apHash; /* Hash table for fast lookup by key */
44094  PgHdr1 *pFree; /* List of unused pcache-local pages */
44095  void *pBulk; /* Bulk memory used by pcache-local */
44096 };
44097 
44098 /*
44099 ** Free slots in the allocator used to divide up the global page cache
44100 ** buffer provided using the SQLITE_CONFIG_PAGECACHE mechanism.
44101 */
44102 struct PgFreeslot {
44103  PgFreeslot *pNext; /* Next free slot */
44104 };
44105 
44106 /*
44107 ** Global data used by this cache.
44108 */
44109 static SQLITE_WSD struct PCacheGlobal {
44110  PGroup grp; /* The global PGroup for mode (2) */
44111 
44112  /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
44113  ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
44114  ** fixed at sqlite3_initialize() time and do not require mutex protection.
44115  ** The nFreeSlot and pFree values do require mutex protection.
44116  */
44117  int isInit; /* True if initialized */
44118  int separateCache; /* Use a new PGroup for each PCache */
44119  int nInitPage; /* Initial bulk allocation size */
44120  int szSlot; /* Size of each free slot */
44121  int nSlot; /* The number of pcache slots */
44122  int nReserve; /* Try to keep nFreeSlot above this */
44123  void *pStart, *pEnd; /* Bounds of global page cache memory */
44124  /* Above requires no mutex. Use mutex below for variable that follow. */
44125  sqlite3_mutex *mutex; /* Mutex for accessing the following: */
44126  PgFreeslot *pFree; /* Free page blocks */
44127  int nFreeSlot; /* Number of unused pcache slots */
44128  /* The following value requires a mutex to change. We skip the mutex on
44129  ** reading because (1) most platforms read a 32-bit integer atomically and
44130  ** (2) even if an incorrect value is read, no great harm is done since this
44131  ** is really just an optimization. */
44132  int bUnderPressure; /* True if low on PAGECACHE memory */
44133 } pcache1_g;
44134 
44135 /*
44136 ** All code in this file should access the global structure above via the
44137 ** alias "pcache1". This ensures that the WSD emulation is used when
44138 ** compiling for systems that do not support real WSD.
44139 */
44140 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
44141 
44142 /*
44143 ** Macros to enter and leave the PCache LRU mutex.
44144 */
44145 #if !defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
44146 # define pcache1EnterMutex(X) assert((X)->mutex==0)
44147 # define pcache1LeaveMutex(X) assert((X)->mutex==0)
44148 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 0
44149 #else
44150 # define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
44151 # define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
44152 # define PCACHE1_MIGHT_USE_GROUP_MUTEX 1
44153 #endif
44154 
44155 /******************************************************************************/
44156 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
44157 
44158 
44159 /*
44160 ** This function is called during initialization if a static buffer is
44161 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
44162 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
44163 ** enough to contain 'n' buffers of 'sz' bytes each.
44164 **
44165 ** This routine is called from sqlite3_initialize() and so it is guaranteed
44166 ** to be serialized already. There is no need for further mutexing.
44167 */
44168 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
44169  if( pcache1.isInit ){
44170  PgFreeslot *p;
44171  if( pBuf==0 ) sz = n = 0;
44172  sz = ROUNDDOWN8(sz);
44173  pcache1.szSlot = sz;
44174  pcache1.nSlot = pcache1.nFreeSlot = n;
44175  pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
44176  pcache1.pStart = pBuf;
44177  pcache1.pFree = 0;
44178  pcache1.bUnderPressure = 0;
44179  while( n-- ){
44180  p = (PgFreeslot*)pBuf;
44181  p->pNext = pcache1.pFree;
44182  pcache1.pFree = p;
44183  pBuf = (void*)&((char*)pBuf)[sz];
44184  }
44185  pcache1.pEnd = pBuf;
44186  }
44187 }
44188 
44189 /*
44190 ** Try to initialize the pCache->pFree and pCache->pBulk fields. Return
44191 ** true if pCache->pFree ends up containing one or more free pages.
44192 */
44193 static int pcache1InitBulk(PCache1 *pCache){
44194  i64 szBulk;
44195  char *zBulk;
44196  if( pcache1.nInitPage==0 ) return 0;
44197  /* Do not bother with a bulk allocation if the cache size very small */
44198  if( pCache->nMax<3 ) return 0;
44200  if( pcache1.nInitPage>0 ){
44201  szBulk = pCache->szAlloc * (i64)pcache1.nInitPage;
44202  }else{
44203  szBulk = -1024 * (i64)pcache1.nInitPage;
44204  }
44205  if( szBulk > pCache->szAlloc*(i64)pCache->nMax ){
44206  szBulk = pCache->szAlloc*pCache->nMax;
44207  }
44208  zBulk = pCache->pBulk = sqlite3Malloc( szBulk );
44210  if( zBulk ){
44211  int nBulk = sqlite3MallocSize(zBulk)/pCache->szAlloc;
44212  int i;
44213  for(i=0; i<nBulk; i++){
44214  PgHdr1 *pX = (PgHdr1*)&zBulk[pCache->szPage];
44215  pX->page.pBuf = zBulk;
44216  pX->page.pExtra = &pX[1];
44217  pX->isBulkLocal = 1;
44218  pX->isAnchor = 0;
44219  pX->pNext = pCache->pFree;
44220  pCache->pFree = pX;
44221  zBulk += pCache->szAlloc;
44222  }
44223  }
44224  return pCache->pFree!=0;
44225 }
44226 
44227 /*
44228 ** Malloc function used within this file to allocate space from the buffer
44229 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
44230 ** such buffer exists or there is no space left in it, this function falls
44231 ** back to sqlite3Malloc().
44232 **
44233 ** Multiple threads can run this routine at the same time. Global variables
44234 ** in pcache1 need to be protected via mutex.
44235 */
44236 static void *pcache1Alloc(int nByte){
44237  void *p = 0;
44238  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
44239  if( nByte<=pcache1.szSlot ){
44241  p = (PgHdr1 *)pcache1.pFree;
44242  if( p ){
44243  pcache1.pFree = pcache1.pFree->pNext;
44244  pcache1.nFreeSlot--;
44245  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44246  assert( pcache1.nFreeSlot>=0 );
44249  }
44251  }
44252  if( p==0 ){
44253  /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
44254  ** it from sqlite3Malloc instead.
44255  */
44256  p = sqlite3Malloc(nByte);
44257 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44258  if( p ){
44259  int sz = sqlite3MallocSize(p);
44264  }
44265 #endif
44267  }
44268  return p;
44269 }
44270 
44271 /*
44272 ** Free an allocated buffer obtained from pcache1Alloc().
44273 */
44274 static void pcache1Free(void *p){
44275  if( p==0 ) return;
44276  if( SQLITE_WITHIN(p, pcache1.pStart, pcache1.pEnd) ){
44277  PgFreeslot *pSlot;
44280  pSlot = (PgFreeslot*)p;
44281  pSlot->pNext = pcache1.pFree;
44282  pcache1.pFree = pSlot;
44283  pcache1.nFreeSlot++;
44284  pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
44285  assert( pcache1.nFreeSlot<=pcache1.nSlot );
44287  }else{
44290 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
44291  {
44292  int nFreed = 0;
44293  nFreed = sqlite3MallocSize(p);
44297  }
44298 #endif
44299  sqlite3_free(p);
44300  }
44301 }
44302 
44303 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44304 /*
44305 ** Return the size of a pcache allocation
44306 */
44307 static int pcache1MemSize(void *p){
44308  if( p>=pcache1.pStart && p<pcache1.pEnd ){
44309  return pcache1.szSlot;
44310  }else{
44311  int iSize;
44314  iSize = sqlite3MallocSize(p);
44316  return iSize;
44317  }
44318 }
44319 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
44320 
44321 /*
44322 ** Allocate a new page object initially associated with cache pCache.
44323 */
44324 static PgHdr1 *pcache1AllocPage(PCache1 *pCache, int benignMalloc){
44325  PgHdr1 *p = 0;
44326  void *pPg;
44327 
44328  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44329  if( pCache->pFree || (pCache->nPage==0 && pcache1InitBulk(pCache)) ){
44330  p = pCache->pFree;
44331  pCache->pFree = p->pNext;
44332  p->pNext = 0;
44333  }else{
44334 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44335  /* The group mutex must be released before pcache1Alloc() is called. This
44336  ** is because it might call sqlite3_release_memory(), which assumes that
44337  ** this mutex is not held. */
44338  assert( pcache1.separateCache==0 );
44339  assert( pCache->pGroup==&pcache1.grp );
44340  pcache1LeaveMutex(pCache->pGroup);
44341 #endif
44342  if( benignMalloc ){ sqlite3BeginBenignMalloc(); }
44343 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44344  pPg = pcache1Alloc(pCache->szPage);
44345  p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
44346  if( !pPg || !p ){
44347  pcache1Free(pPg);
44348  sqlite3_free(p);
44349  pPg = 0;
44350  }
44351 #else
44352  pPg = pcache1Alloc(pCache->szAlloc);
44353  p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
44354 #endif
44355  if( benignMalloc ){ sqlite3EndBenignMalloc(); }
44356 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
44357  pcache1EnterMutex(pCache->pGroup);
44358 #endif
44359  if( pPg==0 ) return 0;
44360  p->page.pBuf = pPg;
44361  p->page.pExtra = &p[1];
44362  p->isBulkLocal = 0;
44363  p->isAnchor = 0;
44364  }
44365  if( pCache->bPurgeable ){
44366  pCache->pGroup->nCurrentPage++;
44367  }
44368  return p;
44369 }
44370 
44371 /*
44372 ** Free a page object allocated by pcache1AllocPage().
44373 */
44374 static void pcache1FreePage(PgHdr1 *p){
44375  PCache1 *pCache;
44376  assert( p!=0 );
44377  pCache = p->pCache;
44379  if( p->isBulkLocal ){
44380  p->pNext = pCache->pFree;
44381  pCache->pFree = p;
44382  }else{
44383  pcache1Free(p->page.pBuf);
44384 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
44385  sqlite3_free(p);
44386 #endif
44387  }
44388  if( pCache->bPurgeable ){
44389  pCache->pGroup->nCurrentPage--;
44390  }
44391 }
44392 
44393 /*
44394 ** Malloc function used by SQLite to obtain space from the buffer configured
44395 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
44396 ** exists, this function falls back to sqlite3Malloc().
44397 */
44399  return pcache1Alloc(sz);
44400 }
44401 
44402 /*
44403 ** Free an allocated buffer obtained from sqlite3PageMalloc().
44404 */
44406  pcache1Free(p);
44407 }
44408 
44409 
44410 /*
44411 ** Return true if it desirable to avoid allocating a new page cache
44412 ** entry.
44413 **
44414 ** If memory was allocated specifically to the page cache using
44415 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
44416 ** it is desirable to avoid allocating a new page cache entry because
44417 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
44418 ** for all page cache needs and we should not need to spill the
44419 ** allocation onto the heap.
44420 **
44421 ** Or, the heap is used for all page cache memory but the heap is
44422 ** under memory pressure, then again it is desirable to avoid
44423 ** allocating a new page cache entry in order to avoid stressing
44424 ** the heap even further.
44425 */
44427  if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
44428  return pcache1.bUnderPressure;
44429  }else{
44430  return sqlite3HeapNearlyFull();
44431  }
44432 }
44433 
44434 /******************************************************************************/
44435 /******** General Implementation Functions ************************************/
44436 
44437 /*
44438 ** This function is used to resize the hash table used by the cache passed
44439 ** as the first argument.
44440 **
44441 ** The PCache mutex must be held when this function is called.
44442 */
44443 static void pcache1ResizeHash(PCache1 *p){
44444  PgHdr1 **apNew;
44445  unsigned int nNew;
44446  unsigned int i;
44447 
44449 
44450  nNew = p->nHash*2;
44451  if( nNew<256 ){
44452  nNew = 256;
44453  }
44454 
44456  if( p->nHash ){ sqlite3BeginBenignMalloc(); }
44457  apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
44458  if( p->nHash ){ sqlite3EndBenignMalloc(); }
44460  if( apNew ){
44461  for(i=0; i<p->nHash; i++){
44462  PgHdr1 *pPage;
44463  PgHdr1 *pNext = p->apHash[i];
44464  while( (pPage = pNext)!=0 ){
44465  unsigned int h = pPage->iKey % nNew;
44466  pNext = pPage->pNext;
44467  pPage->pNext = apNew[h];
44468  apNew[h] = pPage;
44469  }
44470  }
44471  sqlite3_free(p->apHash);
44472  p->apHash = apNew;
44473  p->nHash = nNew;
44474  }
44475 }
44476 
44477 /*
44478 ** This function is used internally to remove the page pPage from the
44479 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
44480 ** LRU list, then this function is a no-op.
44481 **
44482 ** The PGroup mutex must be held when this function is called.
44483 */
44484 static PgHdr1 *pcache1PinPage(PgHdr1 *pPage){
44485  PCache1 *pCache;
44486 
44487  assert( pPage!=0 );
44488  assert( pPage->isPinned==0 );
44489  pCache = pPage->pCache;
44490  assert( pPage->pLruNext );
44491  assert( pPage->pLruPrev );
44492  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44493  pPage->pLruPrev->pLruNext = pPage->pLruNext;
44494  pPage->pLruNext->pLruPrev = pPage->pLruPrev;
44495  pPage->pLruNext = 0;
44496  pPage->pLruPrev = 0;
44497  pPage->isPinned = 1;
44498  assert( pPage->isAnchor==0 );
44499  assert( pCache->pGroup->lru.isAnchor==1 );
44500  pCache->nRecyclable--;
44501  return pPage;
44502 }
44503 
44504 
44505 /*
44506 ** Remove the page supplied as an argument from the hash table
44507 ** (PCache1.apHash structure) that it is currently stored in.
44508 ** Also free the page if freePage is true.
44509 **
44510 ** The PGroup mutex must be held when this function is called.
44511 */
44512 static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag){
44513  unsigned int h;
44514  PCache1 *pCache = pPage->pCache;
44515  PgHdr1 **pp;
44516 
44517  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44518  h = pPage->iKey % pCache->nHash;
44519  for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
44520  *pp = (*pp)->pNext;
44521 
44522  pCache->nPage--;
44523  if( freeFlag ) pcache1FreePage(pPage);
44524 }
44525 
44526 /*
44527 ** If there are currently more than nMaxPage pages allocated, try
44528 ** to recycle pages to reduce the number allocated to nMaxPage.
44529 */
44530 static void pcache1EnforceMaxPage(PCache1 *pCache){
44531  PGroup *pGroup = pCache->pGroup;
44532  PgHdr1 *p;
44533  assert( sqlite3_mutex_held(pGroup->mutex) );
44534  while( pGroup->nCurrentPage>pGroup->nMaxPage
44535  && (p=pGroup->lru.pLruPrev)->isAnchor==0
44536  ){
44537  assert( p->pCache->pGroup==pGroup );
44538  assert( p->isPinned==0 );
44539  pcache1PinPage(p);
44540  pcache1RemoveFromHash(p, 1);
44541  }
44542  if( pCache->nPage==0 && pCache->pBulk ){
44543  sqlite3_free(pCache->pBulk);
44544  pCache->pBulk = pCache->pFree = 0;
44545  }
44546 }
44547 
44548 /*
44549 ** Discard all pages from cache pCache with a page number (key value)
44550 ** greater than or equal to iLimit. Any pinned pages that meet this
44551 ** criteria are unpinned before they are discarded.
44552 **
44553 ** The PCache mutex must be held when this function is called.
44554 */
44556  PCache1 *pCache, /* The cache to truncate */
44557  unsigned int iLimit /* Drop pages with this pgno or larger */
44558 ){
44559  TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
44560  unsigned int h;
44561  assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
44562  for(h=0; h<pCache->nHash; h++){
44563  PgHdr1 **pp = &pCache->apHash[h];
44564  PgHdr1 *pPage;
44565  while( (pPage = *pp)!=0 ){
44566  if( pPage->iKey>=iLimit ){
44567  pCache->nPage--;
44568  *pp = pPage->pNext;
44569  if( !pPage->isPinned ) pcache1PinPage(pPage);
44570  pcache1FreePage(pPage);
44571  }else{
44572  pp = &pPage->pNext;
44573  TESTONLY( nPage++; )
44574  }
44575  }
44576  }
44577  assert( pCache->nPage==nPage );
44578 }
44579 
44580 /******************************************************************************/
44581 /******** sqlite3_pcache Methods **********************************************/
44582 
44583 /*
44584 ** Implementation of the sqlite3_pcache.xInit method.
44585 */
44586 static int pcache1Init(void *NotUsed){
44587  UNUSED_PARAMETER(NotUsed);
44588  assert( pcache1.isInit==0 );
44589  memset(&pcache1, 0, sizeof(pcache1));
44590 
44591 
44592  /*
44593  ** The pcache1.separateCache variable is true if each PCache has its own
44594  ** private PGroup (mode-1). pcache1.separateCache is false if the single
44595  ** PGroup in pcache1.grp is used for all page caches (mode-2).
44596  **
44597  ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
44598  **
44599  ** * Use a unified cache in single-threaded applications that have
44600  ** configured a start-time buffer for use as page-cache memory using
44601  ** sqlite3_config(SQLITE_CONFIG_PAGECACHE, pBuf, sz, N) with non-NULL
44602  ** pBuf argument.
44603  **
44604  ** * Otherwise use separate caches (mode-1)
44605  */
44606 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT)
44607  pcache1.separateCache = 0;
44608 #elif SQLITE_THREADSAFE
44609  pcache1.separateCache = sqlite3GlobalConfig.pPage==0
44610  || sqlite3GlobalConfig.bCoreMutex>0;
44611 #else
44612  pcache1.separateCache = sqlite3GlobalConfig.pPage==0;
44613 #endif
44614 
44615 #if SQLITE_THREADSAFE
44616  if( sqlite3GlobalConfig.bCoreMutex ){
44619  }
44620 #endif
44621  if( pcache1.separateCache
44622  && sqlite3GlobalConfig.nPage!=0
44623  && sqlite3GlobalConfig.pPage==0
44624  ){
44625  pcache1.nInitPage = sqlite3GlobalConfig.nPage;
44626  }else{
44627  pcache1.nInitPage = 0;
44628  }
44629  pcache1.grp.mxPinned = 10;
44630  pcache1.isInit = 1;
44631  return SQLITE_OK;
44632 }
44633 
44634 /*
44635 ** Implementation of the sqlite3_pcache.xShutdown method.
44636 ** Note that the static mutex allocated in xInit does
44637 ** not need to be freed.
44638 */
44639 static void pcache1Shutdown(void *NotUsed){
44640  UNUSED_PARAMETER(NotUsed);
44641  assert( pcache1.isInit!=0 );
44642  memset(&pcache1, 0, sizeof(pcache1));
44643 }
44644 
44645 /* forward declaration */
44646 static void pcache1Destroy(sqlite3_pcache *p);
44647 
44648 /*
44649 ** Implementation of the sqlite3_pcache.xCreate method.
44650 **
44651 ** Allocate a new cache.
44652 */
44653 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
44654  PCache1 *pCache; /* The newly created page cache */
44655  PGroup *pGroup; /* The group the new page cache will belong to */
44656  int sz; /* Bytes of memory required to allocate the new cache */
44657 
44658  assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
44659  assert( szExtra < 300 );
44660 
44661  sz = sizeof(PCache1) + sizeof(PGroup)*pcache1.separateCache;
44662  pCache = (PCache1 *)sqlite3MallocZero(sz);
44663  if( pCache ){
44664  if( pcache1.separateCache ){
44665  pGroup = (PGroup*)&pCache[1];
44666  pGroup->mxPinned = 10;
44667  }else{
44668  pGroup = &pcache1.grp;
44669  }
44670  if( pGroup->lru.isAnchor==0 ){
44671  pGroup->lru.isAnchor = 1;
44672  pGroup->lru.pLruPrev = pGroup->lru.pLruNext = &pGroup->lru;
44673  }
44674  pCache->pGroup = pGroup;
44675  pCache->szPage = szPage;
44676  pCache->szExtra = szExtra;
44677  pCache->szAlloc = szPage + szExtra + ROUND8(sizeof(PgHdr1));
44678  pCache->bPurgeable = (bPurgeable ? 1 : 0);
44679  pcache1EnterMutex(pGroup);
44680  pcache1ResizeHash(pCache);
44681  if( bPurgeable ){
44682  pCache->nMin = 10;
44683  pGroup->nMinPage += pCache->nMin;
44684  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
44685  }
44686  pcache1LeaveMutex(pGroup);
44687  if( pCache->nHash==0 ){
44688  pcache1Destroy((sqlite3_pcache*)pCache);
44689  pCache = 0;
44690  }
44691  }
44692  return (sqlite3_pcache *)pCache;
44693 }
44694 
44695 /*
44696 ** Implementation of the sqlite3_pcache.xCachesize method.
44697 **
44698 ** Configure the cache_size limit for a cache.
44699 */
44700 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
44701  PCache1 *pCache = (PCache1 *)p;
44702  if( pCache->bPurgeable ){
44703  PGroup *pGroup = pCache->pGroup;
44704  pcache1EnterMutex(pGroup);
44705  pGroup->nMaxPage += (nMax - pCache->nMax);
44706  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
44707  pCache->nMax = nMax;
44708  pCache->n90pct = pCache->nMax*9/10;
44709  pcache1EnforceMaxPage(pCache);
44710  pcache1LeaveMutex(pGroup);
44711  }
44712 }
44713 
44714 /*
44715 ** Implementation of the sqlite3_pcache.xShrink method.
44716 **
44717 ** Free up as much memory as possible.
44718 */
44720  PCache1 *pCache = (PCache1*)p;
44721  if( pCache->bPurgeable ){
44722  PGroup *pGroup = pCache->pGroup;
44723  int savedMaxPage;
44724  pcache1EnterMutex(pGroup);
44725  savedMaxPage = pGroup->nMaxPage;
44726  pGroup->nMaxPage = 0;
44727  pcache1EnforceMaxPage(pCache);
44728  pGroup->nMaxPage = savedMaxPage;
44729  pcache1LeaveMutex(pGroup);
44730  }
44731 }
44732 
44733 /*
44734 ** Implementation of the sqlite3_pcache.xPagecount method.
44735 */
44737  int n;
44738  PCache1 *pCache = (PCache1*)p;
44739  pcache1EnterMutex(pCache->pGroup);
44740  n = pCache->nPage;
44741  pcache1LeaveMutex(pCache->pGroup);
44742  return n;
44743 }
44744 
44745 
44746 /*
44747 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
44748 ** in the header of the pcache1Fetch() procedure.
44749 **
44750 ** This steps are broken out into a separate procedure because they are
44751 ** usually not needed, and by avoiding the stack initialization required
44752 ** for these steps, the main pcache1Fetch() procedure can run faster.
44753 */
44755  PCache1 *pCache,
44756  unsigned int iKey,
44757  int createFlag
44758 ){
44759  unsigned int nPinned;
44760  PGroup *pGroup = pCache->pGroup;
44761  PgHdr1 *pPage = 0;
44762 
44763  /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
44764  assert( pCache->nPage >= pCache->nRecyclable );
44765  nPinned = pCache->nPage - pCache->nRecyclable;
44766  assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
44767  assert( pCache->n90pct == pCache->nMax*9/10 );
44768  if( createFlag==1 && (
44769  nPinned>=pGroup->mxPinned
44770  || nPinned>=pCache->n90pct
44771  || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
44772  )){
44773  return 0;
44774  }
44775 
44776  if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
44777  assert( pCache->nHash>0 && pCache->apHash );
44778 
44779  /* Step 4. Try to recycle a page. */
44780  if( pCache->bPurgeable
44781  && !pGroup->lru.pLruPrev->isAnchor
44782  && ((pCache->nPage+1>=pCache->nMax) || pcache1UnderMemoryPressure(pCache))
44783  ){
44784  PCache1 *pOther;
44785  pPage = pGroup->lru.pLruPrev;
44786  assert( pPage->isPinned==0 );
44787  pcache1RemoveFromHash(pPage, 0);
44788  pcache1PinPage(pPage);
44789  pOther = pPage->pCache;
44790  if( pOther->szAlloc != pCache->szAlloc ){
44791  pcache1FreePage(pPage);
44792  pPage = 0;
44793  }else{
44794  pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
44795  }
44796  }
44797 
44798  /* Step 5. If a usable page buffer has still not been found,
44799  ** attempt to allocate a new one.
44800  */
44801  if( !pPage ){
44802  pPage = pcache1AllocPage(pCache, createFlag==1);
44803  }
44804 
44805  if( pPage ){
44806  unsigned int h = iKey % pCache->nHash;
44807  pCache->nPage++;
44808  pPage->iKey = iKey;
44809  pPage->pNext = pCache->apHash[h];
44810  pPage->pCache = pCache;
44811  pPage->pLruPrev = 0;
44812  pPage->pLruNext = 0;
44813  pPage->isPinned = 1;
44814  *(void **)pPage->page.pExtra = 0;
44815  pCache->apHash[h] = pPage;
44816  if( iKey>pCache->iMaxKey ){
44817  pCache->iMaxKey = iKey;
44818  }
44819  }
44820  return pPage;
44821 }
44822 
44823 /*
44824 ** Implementation of the sqlite3_pcache.xFetch method.
44825 **
44826 ** Fetch a page by key value.
44827 **
44828 ** Whether or not a new page may be allocated by this function depends on
44829 ** the value of the createFlag argument. 0 means do not allocate a new
44830 ** page. 1 means allocate a new page if space is easily available. 2
44831 ** means to try really hard to allocate a new page.
44832 **
44833 ** For a non-purgeable cache (a cache used as the storage for an in-memory
44834 ** database) there is really no difference between createFlag 1 and 2. So
44835 ** the calling function (pcache.c) will never have a createFlag of 1 on
44836 ** a non-purgeable cache.
44837 **
44838 ** There are three different approaches to obtaining space for a page,
44839 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
44840 **
44841 ** 1. Regardless of the value of createFlag, the cache is searched for a
44842 ** copy of the requested page. If one is found, it is returned.
44843 **
44844 ** 2. If createFlag==0 and the page is not already in the cache, NULL is
44845 ** returned.
44846 **
44847 ** 3. If createFlag is 1, and the page is not already in the cache, then
44848 ** return NULL (do not allocate a new page) if any of the following
44849 ** conditions are true:
44850 **
44851 ** (a) the number of pages pinned by the cache is greater than
44852 ** PCache1.nMax, or
44853 **
44854 ** (b) the number of pages pinned by the cache is greater than
44855 ** the sum of nMax for all purgeable caches, less the sum of
44856 ** nMin for all other purgeable caches, or
44857 **
44858 ** 4. If none of the first three conditions apply and the cache is marked
44859 ** as purgeable, and if one of the following is true:
44860 **
44861 ** (a) The number of pages allocated for the cache is already
44862 ** PCache1.nMax, or
44863 **
44864 ** (b) The number of pages allocated for all purgeable caches is
44865 ** already equal to or greater than the sum of nMax for all
44866 ** purgeable caches,
44867 **
44868 ** (c) The system is under memory pressure and wants to avoid
44869 ** unnecessary pages cache entry allocations
44870 **
44871 ** then attempt to recycle a page from the LRU list. If it is the right
44872 ** size, return the recycled buffer. Otherwise, free the buffer and
44873 ** proceed to step 5.
44874 **
44875 ** 5. Otherwise, allocate and return a new page buffer.
44876 **
44877 ** There are two versions of this routine. pcache1FetchWithMutex() is
44878 ** the general case. pcache1FetchNoMutex() is a faster implementation for
44879 ** the common case where pGroup->mutex is NULL. The pcache1Fetch() wrapper
44880 ** invokes the appropriate routine.
44881 */
44883  sqlite3_pcache *p,
44884  unsigned int iKey,
44885  int createFlag
44886 ){
44887  PCache1 *pCache = (PCache1 *)p;
44888  PgHdr1 *pPage = 0;
44889 
44890  /* Step 1: Search the hash table for an existing entry. */
44891  pPage = pCache->apHash[iKey % pCache->nHash];
44892  while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
44893 
44894  /* Step 2: If the page was found in the hash table, then return it.
44895  ** If the page was not in the hash table and createFlag is 0, abort.
44896  ** Otherwise (page not in hash and createFlag!=0) continue with
44897  ** subsequent steps to try to create the page. */
44898  if( pPage ){
44899  if( !pPage->isPinned ){
44900  return pcache1PinPage(pPage);
44901  }else{
44902  return pPage;
44903  }
44904  }else if( createFlag ){
44905  /* Steps 3, 4, and 5 implemented by this subroutine */
44906  return pcache1FetchStage2(pCache, iKey, createFlag);
44907  }else{
44908  return 0;
44909  }
44910 }
44911 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
44912 static PgHdr1 *pcache1FetchWithMutex(
44913  sqlite3_pcache *p,
44914  unsigned int iKey,
44915  int createFlag
44916 ){
44917  PCache1 *pCache = (PCache1 *)p;
44918  PgHdr1 *pPage;
44919 
44920  pcache1EnterMutex(pCache->pGroup);
44921  pPage = pcache1FetchNoMutex(p, iKey, createFlag);
44922  assert( pPage==0 || pCache->iMaxKey>=iKey );
44923  pcache1LeaveMutex(pCache->pGroup);
44924  return pPage;
44925 }
44926 #endif
44928  sqlite3_pcache *p,
44929  unsigned int iKey,
44930  int createFlag
44931 ){
44932 #if PCACHE1_MIGHT_USE_GROUP_MUTEX || defined(SQLITE_DEBUG)
44933  PCache1 *pCache = (PCache1 *)p;
44934 #endif
44935 
44936  assert( offsetof(PgHdr1,page)==0 );
44937  assert( pCache->bPurgeable || createFlag!=1 );
44938  assert( pCache->bPurgeable || pCache->nMin==0 );
44939  assert( pCache->bPurgeable==0 || pCache->nMin==10 );
44940  assert( pCache->nMin==0 || pCache->bPurgeable );
44941  assert( pCache->nHash>0 );
44942 #if PCACHE1_MIGHT_USE_GROUP_MUTEX
44943  if( pCache->pGroup->mutex ){
44944  return (sqlite3_pcache_page*)pcache1FetchWithMutex(p, iKey, createFlag);
44945  }else
44946 #endif
44947  {
44948  return (sqlite3_pcache_page*)pcache1FetchNoMutex(p, iKey, createFlag);
44949  }
44950 }
44951 
44952 
44953 /*
44954 ** Implementation of the sqlite3_pcache.xUnpin method.
44955 **
44956 ** Mark a page as unpinned (eligible for asynchronous recycling).
44957 */
44958 static void pcache1Unpin(
44959  sqlite3_pcache *p,
44960  sqlite3_pcache_page *pPg,
44961  int reuseUnlikely
44962 ){
44963  PCache1 *pCache = (PCache1 *)p;
44964  PgHdr1 *pPage = (PgHdr1 *)pPg;
44965  PGroup *pGroup = pCache->pGroup;
44966 
44967  assert( pPage->pCache==pCache );
44968  pcache1EnterMutex(pGroup);
44969 
44970  /* It is an error to call this function if the page is already
44971  ** part of the PGroup LRU list.
44972  */
44973  assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
44974  assert( pPage->isPinned==1 );
44975 
44976  if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
44977  pcache1RemoveFromHash(pPage, 1);
44978  }else{
44979  /* Add the page to the PGroup LRU list. */
44980  PgHdr1 **ppFirst = &pGroup->lru.pLruNext;
44981  pPage->pLruPrev = &pGroup->lru;
44982  (pPage->pLruNext = *ppFirst)->pLruPrev = pPage;
44983  *ppFirst = pPage;
44984  pCache->nRecyclable++;
44985  pPage->isPinned = 0;
44986  }
44987 
44988  pcache1LeaveMutex(pCache->pGroup);
44989 }
44990 
44991 /*
44992 ** Implementation of the sqlite3_pcache.xRekey method.
44993 */
44994 static void pcache1Rekey(
44995  sqlite3_pcache *p,
44996  sqlite3_pcache_page *pPg,
44997  unsigned int iOld,
44998  unsigned int iNew
44999 ){
45000  PCache1 *pCache = (PCache1 *)p;
45001  PgHdr1 *pPage = (PgHdr1 *)pPg;
45002  PgHdr1 **pp;
45003  unsigned int h;
45004  assert( pPage->iKey==iOld );
45005  assert( pPage->pCache==pCache );
45006 
45007  pcache1EnterMutex(pCache->pGroup);
45008 
45009  h = iOld%pCache->nHash;
45010  pp = &pCache->apHash[h];
45011  while( (*pp)!=pPage ){
45012  pp = &(*pp)->pNext;
45013  }
45014  *pp = pPage->pNext;
45015 
45016  h = iNew%pCache->nHash;
45017  pPage->iKey = iNew;
45018  pPage->pNext = pCache->apHash[h];
45019  pCache->apHash[h] = pPage;
45020  if( iNew>pCache->iMaxKey ){
45021  pCache->iMaxKey = iNew;
45022  }
45023 
45024  pcache1LeaveMutex(pCache->pGroup);
45025 }
45026 
45027 /*
45028 ** Implementation of the sqlite3_pcache.xTruncate method.
45029 **
45030 ** Discard all unpinned pages in the cache with a page number equal to
45031 ** or greater than parameter iLimit. Any pinned pages with a page number
45032 ** equal to or greater than iLimit are implicitly unpinned.
45033 */
45034 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
45035  PCache1 *pCache = (PCache1 *)p;
45036  pcache1EnterMutex(pCache->pGroup);
45037  if( iLimit<=pCache->iMaxKey ){
45038  pcache1TruncateUnsafe(pCache, iLimit);
45039  pCache->iMaxKey = iLimit-1;
45040  }
45041  pcache1LeaveMutex(pCache->pGroup);
45042 }
45043 
45044 /*
45045 ** Implementation of the sqlite3_pcache.xDestroy method.
45046 **
45047 ** Destroy a cache allocated using pcache1Create().
45048 */
45050  PCache1 *pCache = (PCache1 *)p;
45051  PGroup *pGroup = pCache->pGroup;
45052  assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
45053  pcache1EnterMutex(pGroup);
45054  pcache1TruncateUnsafe(pCache, 0);
45055  assert( pGroup->nMaxPage >= pCache->nMax );
45056  pGroup->nMaxPage -= pCache->nMax;
45057  assert( pGroup->nMinPage >= pCache->nMin );
45058  pGroup->nMinPage -= pCache->nMin;
45059  pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
45060  pcache1EnforceMaxPage(pCache);
45061  pcache1LeaveMutex(pGroup);
45062  sqlite3_free(pCache->pBulk);
45063  sqlite3_free(pCache->apHash);
45064  sqlite3_free(pCache);
45065 }
45066 
45067 /*
45068 ** This function is called during initialization (sqlite3_initialize()) to
45069 ** install the default pluggable cache module, assuming the user has not
45070 ** already provided an alternative.
45071 */
45073  static const sqlite3_pcache_methods2 defaultMethods = {
45074  1, /* iVersion */
45075  0, /* pArg */
45076  pcache1Init, /* xInit */
45077  pcache1Shutdown, /* xShutdown */
45078  pcache1Create, /* xCreate */
45079  pcache1Cachesize, /* xCachesize */
45080  pcache1Pagecount, /* xPagecount */
45081  pcache1Fetch, /* xFetch */
45082  pcache1Unpin, /* xUnpin */
45083  pcache1Rekey, /* xRekey */
45084  pcache1Truncate, /* xTruncate */
45085  pcache1Destroy, /* xDestroy */
45086  pcache1Shrink /* xShrink */
45087  };
45088  sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
45089 }
45090 
45091 /*
45092 ** Return the size of the header on each page of this PCACHE implementation.
45093 */
45095 
45096 /*
45097 ** Return the global mutex used by this PCACHE implementation. The
45098 ** sqlite3_status() routine needs access to this mutex.
45099 */
45101  return pcache1.mutex;
45102 }
45103 
45104 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
45105 /*
45106 ** This function is called to free superfluous dynamically allocated memory
45107 ** held by the pager system. Memory in use by any SQLite pager allocated
45108 ** by the current thread may be sqlite3_free()ed.
45109 **
45110 ** nReq is the number of bytes of memory required. Once this much has
45111 ** been released, the function returns. The return value is the total number
45112 ** of bytes of memory released.
45113 */
45114 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
45115  int nFree = 0;
45116  assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
45118  if( sqlite3GlobalConfig.nPage==0 ){
45119  PgHdr1 *p;
45120  pcache1EnterMutex(&pcache1.grp);
45121  while( (nReq<0 || nFree<nReq)
45122  && (p=pcache1.grp.lru.pLruPrev)!=0
45123  && p->isAnchor==0
45124  ){
45125  nFree += pcache1MemSize(p->page.pBuf);
45126 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
45127  nFree += sqlite3MemSize(p);
45128 #endif
45129  assert( p->isPinned==0 );
45130  pcache1PinPage(p);
45131  pcache1RemoveFromHash(p, 1);
45132  }
45133  pcache1LeaveMutex(&pcache1.grp);
45134  }
45135  return nFree;
45136 }
45137 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
45138 
45139 #ifdef SQLITE_TEST
45140 /*
45141 ** This function is used by test procedures to inspect the internal state
45142 ** of the global cache.
45143 */
45144 SQLITE_PRIVATE void sqlite3PcacheStats(
45145  int *pnCurrent, /* OUT: Total number of pages cached */
45146  int *pnMax, /* OUT: Global maximum cache size */
45147  int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
45148  int *pnRecyclable /* OUT: Total number of pages available for recycling */
45149 ){
45150  PgHdr1 *p;
45151  int nRecyclable = 0;
45152  for(p=pcache1.grp.lru.pLruNext; p && !p->isAnchor; p=p->pLruNext){
45153  assert( p->isPinned==0 );
45154  nRecyclable++;
45155  }
45156  *pnCurrent = pcache1.grp.nCurrentPage;
45157  *pnMax = (int)pcache1.grp.nMaxPage;
45158  *pnMin = (int)pcache1.grp.nMinPage;
45159  *pnRecyclable = nRecyclable;
45160 }
45161 #endif
45162 
45163 /************** End of pcache1.c *********************************************/
45164 /************** Begin file rowset.c ******************************************/
45165 /*
45166 ** 2008 December 3
45167 **
45168 ** The author disclaims copyright to this source code. In place of
45169 ** a legal notice, here is a blessing:
45170 **
45171 ** May you do good and not evil.
45172 ** May you find forgiveness for yourself and forgive others.
45173 ** May you share freely, never taking more than you give.
45174 **
45175 *************************************************************************
45176 **
45177 ** This module implements an object we call a "RowSet".
45178 **
45179 ** The RowSet object is a collection of rowids. Rowids
45180 ** are inserted into the RowSet in an arbitrary order. Inserts
45181 ** can be intermixed with tests to see if a given rowid has been
45182 ** previously inserted into the RowSet.
45183 **
45184 ** After all inserts are finished, it is possible to extract the
45185 ** elements of the RowSet in sorted order. Once this extraction
45186 ** process has started, no new elements may be inserted.
45187 **
45188 ** Hence, the primitive operations for a RowSet are:
45189 **
45190 ** CREATE
45191 ** INSERT
45192 ** TEST
45193 ** SMALLEST
45194 ** DESTROY
45195 **
45196 ** The CREATE and DESTROY primitives are the constructor and destructor,
45197 ** obviously. The INSERT primitive adds a new element to the RowSet.
45198 ** TEST checks to see if an element is already in the RowSet. SMALLEST
45199 ** extracts the least value from the RowSet.
45200 **
45201 ** The INSERT primitive might allocate additional memory. Memory is
45202 ** allocated in chunks so most INSERTs do no allocation. There is an
45203 ** upper bound on the size of allocated memory. No memory is freed
45204 ** until DESTROY.
45205 **
45206 ** The TEST primitive includes a "batch" number. The TEST primitive
45207 ** will only see elements that were inserted before the last change
45208 ** in the batch number. In other words, if an INSERT occurs between
45209 ** two TESTs where the TESTs have the same batch nubmer, then the
45210 ** value added by the INSERT will not be visible to the second TEST.
45211 ** The initial batch number is zero, so if the very first TEST contains
45212 ** a non-zero batch number, it will see all prior INSERTs.
45213 **
45214 ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
45215 ** that is attempted.
45216 **
45217 ** The cost of an INSERT is roughly constant. (Sometimes new memory
45218 ** has to be allocated on an INSERT.) The cost of a TEST with a new
45219 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
45220 ** The cost of a TEST using the same batch number is O(logN). The cost
45221 ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
45222 ** primitives are constant time. The cost of DESTROY is O(N).
45223 **
45224 ** TEST and SMALLEST may not be used by the same RowSet. This used to
45225 ** be possible, but the feature was not used, so it was removed in order
45226 ** to simplify the code.
45227 */
45228 /* #include "sqliteInt.h" */
45229 
45230 
45231 /*
45232 ** Target size for allocation chunks.
45233 */
45234 #define ROWSET_ALLOCATION_SIZE 1024
45235 
45236 /*
45237 ** The number of rowset entries per allocation chunk.
45238 */
45239 #define ROWSET_ENTRY_PER_CHUNK \
45240  ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
45241 
45242 /*
45243 ** Each entry in a RowSet is an instance of the following object.
45244 **
45245 ** This same object is reused to store a linked list of trees of RowSetEntry
45246 ** objects. In that alternative use, pRight points to the next entry
45247 ** in the list, pLeft points to the tree, and v is unused. The
45248 ** RowSet.pForest value points to the head of this forest list.
45249 */
45250 struct RowSetEntry {
45251  i64 v; /* ROWID value for this entry */
45252  struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
45253  struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
45254 };
45255 
45256 /*
45257 ** RowSetEntry objects are allocated in large chunks (instances of the
45258 ** following structure) to reduce memory allocation overhead. The
45259 ** chunks are kept on a linked list so that they can be deallocated
45260 ** when the RowSet is destroyed.
45261 */
45262 struct RowSetChunk {
45263  struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
45264  struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
45265 };
45266 
45267 /*
45268 ** A RowSet in an instance of the following structure.
45269 **
45270 ** A typedef of this structure if found in sqliteInt.h.
45271 */
45272 struct RowSet {
45273  struct RowSetChunk *pChunk; /* List of all chunk allocations */
45274  sqlite3 *db; /* The database connection */
45275  struct RowSetEntry *pEntry; /* List of entries using pRight */
45276  struct RowSetEntry *pLast; /* Last entry on the pEntry list */
45277  struct RowSetEntry *pFresh; /* Source of new entry objects */
45278  struct RowSetEntry *pForest; /* List of binary trees of entries */
45279  u16 nFresh; /* Number of objects on pFresh */
45280  u16 rsFlags; /* Various flags */
45281  int iBatch; /* Current insert batch */
45282 };
45283 
45284 /*
45285 ** Allowed values for RowSet.rsFlags
45286 */
45287 #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
45288 #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
45289 
45290 /*
45291 ** Turn bulk memory into a RowSet object. N bytes of memory
45292 ** are available at pSpace. The db pointer is used as a memory context
45293 ** for any subsequent allocations that need to occur.
45294 ** Return a pointer to the new RowSet object.
45295 **
45296 ** It must be the case that N is sufficient to make a Rowset. If not
45297 ** an assertion fault occurs.
45298 **
45299 ** If N is larger than the minimum, use the surplus as an initial
45300 ** allocation of entries available to be filled.
45301 */
45302 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
45303  RowSet *p;
45304  assert( N >= ROUND8(sizeof(*p)) );
45305  p = pSpace;
45306  p->pChunk = 0;
45307  p->db = db;
45308  p->pEntry = 0;
45309  p->pLast = 0;
45310  p->pForest = 0;
45311  p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
45312  p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
45313  p->rsFlags = ROWSET_SORTED;
45314  p->iBatch = 0;
45315  return p;
45316 }
45317 
45318 /*
45319 ** Deallocate all chunks from a RowSet. This frees all memory that
45320 ** the RowSet has allocated over its lifetime. This routine is
45321 ** the destructor for the RowSet.
45322 */
45324  struct RowSetChunk *pChunk, *pNextChunk;
45325  for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
45326  pNextChunk = pChunk->pNextChunk;
45327  sqlite3DbFree(p->db, pChunk);
45328  }
45329  p->pChunk = 0;
45330  p->nFresh = 0;
45331  p->pEntry = 0;
45332  p->pLast = 0;
45333  p->pForest = 0;
45334  p->rsFlags = ROWSET_SORTED;
45335 }
45336 
45337 /*
45338 ** Allocate a new RowSetEntry object that is associated with the
45339 ** given RowSet. Return a pointer to the new and completely uninitialized
45340 ** objected.
45341 **
45342 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
45343 ** routine returns NULL.
45344 */
45346  assert( p!=0 );
45347  if( p->nFresh==0 ){ /*OPTIMIZATION-IF-FALSE*/
45348  /* We could allocate a fresh RowSetEntry each time one is needed, but it
45349  ** is more efficient to pull a preallocated entry from the pool */
45350  struct RowSetChunk *pNew;
45351  pNew = sqlite3DbMallocRawNN(p->db, sizeof(*pNew));
45352  if( pNew==0 ){
45353  return 0;
45354  }
45355  pNew->pNextChunk = p->pChunk;
45356  p->pChunk = pNew;
45357  p->pFresh = pNew->aEntry;
45359  }
45360  p->nFresh--;
45361  return p->pFresh++;
45362 }
45363 
45364 /*
45365 ** Insert a new value into a RowSet.
45366 **
45367 ** The mallocFailed flag of the database connection is set if a
45368 ** memory allocation fails.
45369 */
45371  struct RowSetEntry *pEntry; /* The new entry */
45372  struct RowSetEntry *pLast; /* The last prior entry */
45373 
45374  /* This routine is never called after sqlite3RowSetNext() */
45375  assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
45376 
45377  pEntry = rowSetEntryAlloc(p);
45378  if( pEntry==0 ) return;
45379  pEntry->v = rowid;
45380  pEntry->pRight = 0;
45381  pLast = p->pLast;
45382  if( pLast ){
45383  if( rowid<=pLast->v ){ /*OPTIMIZATION-IF-FALSE*/
45384  /* Avoid unnecessary sorts by preserving the ROWSET_SORTED flags
45385  ** where possible */
45386  p->rsFlags &= ~ROWSET_SORTED;
45387  }
45388  pLast->pRight = pEntry;
45389  }else{
45390  p->pEntry = pEntry;
45391  }
45392  p->pLast = pEntry;
45393 }
45394 
45395 /*
45396 ** Merge two lists of RowSetEntry objects. Remove duplicates.
45397 **
45398 ** The input lists are connected via pRight pointers and are
45399 ** assumed to each already be in sorted order.
45400 */
45402  struct RowSetEntry *pA, /* First sorted list to be merged */
45403  struct RowSetEntry *pB /* Second sorted list to be merged */
45404 ){
45405  struct RowSetEntry head;
45406  struct RowSetEntry *pTail;
45407 
45408  pTail = &head;
45409  while( pA && pB ){
45410  assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45411  assert( pB->pRight==0 || pB->v<=pB->pRight->v );
45412  if( pA->v<pB->v ){
45413  pTail->pRight = pA;
45414  pA = pA->pRight;
45415  pTail = pTail->pRight;
45416  }else if( pB->v<pA->v ){
45417  pTail->pRight = pB;
45418  pB = pB->pRight;
45419  pTail = pTail->pRight;
45420  }else{
45421  pA = pA->pRight;
45422  }
45423  }
45424  if( pA ){
45425  assert( pA->pRight==0 || pA->v<=pA->pRight->v );
45426  pTail->pRight = pA;
45427  }else{
45428  assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
45429  pTail->pRight = pB;
45430  }
45431  return head.pRight;
45432 }
45433 
45434 /*
45435 ** Sort all elements on the list of RowSetEntry objects into order of
45436 ** increasing v.
45437 */
45438 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
45439  unsigned int i;
45440  struct RowSetEntry *pNext, *aBucket[40];
45441 
45442  memset(aBucket, 0, sizeof(aBucket));
45443  while( pIn ){
45444  pNext = pIn->pRight;
45445  pIn->pRight = 0;
45446  for(i=0; aBucket[i]; i++){
45447  pIn = rowSetEntryMerge(aBucket[i], pIn);
45448  aBucket[i] = 0;
45449  }
45450  aBucket[i] = pIn;
45451  pIn = pNext;
45452  }
45453  pIn = 0;
45454  for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
45455  pIn = rowSetEntryMerge(pIn, aBucket[i]);
45456  }
45457  return pIn;
45458 }
45459 
45460 
45461 /*
45462 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
45463 ** Convert this tree into a linked list connected by the pRight pointers
45464 ** and return pointers to the first and last elements of the new list.
45465 */
45466 static void rowSetTreeToList(
45467  struct RowSetEntry *pIn, /* Root of the input tree */
45468  struct RowSetEntry **ppFirst, /* Write head of the output list here */
45469  struct RowSetEntry **ppLast /* Write tail of the output list here */
45470 ){
45471  assert( pIn!=0 );
45472  if( pIn->pLeft ){
45473  struct RowSetEntry *p;
45474  rowSetTreeToList(pIn->pLeft, ppFirst, &p);
45475  p->pRight = pIn;
45476  }else{
45477  *ppFirst = pIn;
45478  }
45479  if( pIn->pRight ){
45480  rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
45481  }else{
45482  *ppLast = pIn;
45483  }
45484  assert( (*ppLast)->pRight==0 );
45485 }
45486 
45487 
45488 /*
45489 ** Convert a sorted list of elements (connected by pRight) into a binary
45490 ** tree with depth of iDepth. A depth of 1 means the tree contains a single
45491 ** node taken from the head of *ppList. A depth of 2 means a tree with
45492 ** three nodes. And so forth.
45493 **
45494 ** Use as many entries from the input list as required and update the
45495 ** *ppList to point to the unused elements of the list. If the input
45496 ** list contains too few elements, then construct an incomplete tree
45497 ** and leave *ppList set to NULL.
45498 **
45499 ** Return a pointer to the root of the constructed binary tree.
45500 */
45502  struct RowSetEntry **ppList,
45503  int iDepth
45504 ){
45505  struct RowSetEntry *p; /* Root of the new tree */
45506  struct RowSetEntry *pLeft; /* Left subtree */
45507  if( *ppList==0 ){ /*OPTIMIZATION-IF-TRUE*/
45508  /* Prevent unnecessary deep recursion when we run out of entries */
45509  return 0;
45510  }
45511  if( iDepth>1 ){ /*OPTIMIZATION-IF-TRUE*/
45512  /* This branch causes a *balanced* tree to be generated. A valid tree
45513  ** is still generated without this branch, but the tree is wildly
45514  ** unbalanced and inefficient. */
45515  pLeft = rowSetNDeepTree(ppList, iDepth-1);
45516  p = *ppList;
45517  if( p==0 ){ /*OPTIMIZATION-IF-FALSE*/
45518  /* It is safe to always return here, but the resulting tree
45519  ** would be unbalanced */
45520  return pLeft;
45521  }
45522  p->pLeft = pLeft;
45523  *ppList = p->pRight;
45524  p->pRight = rowSetNDeepTree(ppList, iDepth-1);
45525  }else{
45526  p = *ppList;
45527  *ppList = p->pRight;
45528  p->pLeft = p->pRight = 0;
45529  }
45530  return p;
45531 }
45532 
45533 /*
45534 ** Convert a sorted list of elements into a binary tree. Make the tree
45535 ** as deep as it needs to be in order to contain the entire list.
45536 */
45537 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
45538  int iDepth; /* Depth of the tree so far */
45539  struct RowSetEntry *p; /* Current tree root */
45540  struct RowSetEntry *pLeft; /* Left subtree */
45541 
45542  assert( pList!=0 );
45543  p = pList;
45544  pList = p->pRight;
45545  p->pLeft = p->pRight = 0;
45546  for(iDepth=1; pList; iDepth++){
45547  pLeft = p;
45548  p = pList;
45549  pList = p->pRight;
45550  p->pLeft = pLeft;
45551  p->pRight = rowSetNDeepTree(&pList, iDepth);
45552  }
45553  return p;
45554 }
45555 
45556 /*
45557 ** Extract the smallest element from the RowSet.
45558 ** Write the element into *pRowid. Return 1 on success. Return
45559 ** 0 if the RowSet is already empty.
45560 **
45561 ** After this routine has been called, the sqlite3RowSetInsert()
45562 ** routine may not be called again.
45563 **
45564 ** This routine may not be called after sqlite3RowSetTest() has
45565 ** been used. Older versions of RowSet allowed that, but as the
45566 ** capability was not used by the code generator, it was removed
45567 ** for code economy.
45568 */
45570  assert( p!=0 );
45571  assert( p->pForest==0 ); /* Cannot be used with sqlite3RowSetText() */
45572 
45573  /* Merge the forest into a single sorted list on first call */
45574  if( (p->rsFlags & ROWSET_NEXT)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45575  if( (p->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45576  p->pEntry = rowSetEntrySort(p->pEntry);
45577  }
45579  }
45580 
45581  /* Return the next entry on the list */
45582  if( p->pEntry ){
45583  *pRowid = p->pEntry->v;
45584  p->pEntry = p->pEntry->pRight;
45585  if( p->pEntry==0 ){ /*OPTIMIZATION-IF-TRUE*/
45586  /* Free memory immediately, rather than waiting on sqlite3_finalize() */
45587  sqlite3RowSetClear(p);
45588  }
45589  return 1;
45590  }else{
45591  return 0;
45592  }
45593 }
45594 
45595 /*
45596 ** Check to see if element iRowid was inserted into the rowset as
45597 ** part of any insert batch prior to iBatch. Return 1 or 0.
45598 **
45599 ** If this is the first test of a new batch and if there exist entries
45600 ** on pRowSet->pEntry, then sort those entries into the forest at
45601 ** pRowSet->pForest so that they can be tested.
45602 */
45603 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
45604  struct RowSetEntry *p, *pTree;
45605 
45606  /* This routine is never called after sqlite3RowSetNext() */
45607  assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
45608 
45609  /* Sort entries into the forest on the first test of a new batch.
45610  ** To save unnecessary work, only do this when the batch number changes.
45611  */
45612  if( iBatch!=pRowSet->iBatch ){ /*OPTIMIZATION-IF-FALSE*/
45613  p = pRowSet->pEntry;
45614  if( p ){
45615  struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
45616  if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){ /*OPTIMIZATION-IF-FALSE*/
45617  /* Only sort the current set of entiries if they need it */
45618  p = rowSetEntrySort(p);
45619  }
45620  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
45621  ppPrevTree = &pTree->pRight;
45622  if( pTree->pLeft==0 ){
45623  pTree->pLeft = rowSetListToTree(p);
45624  break;
45625  }else{
45626  struct RowSetEntry *pAux, *pTail;
45627  rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
45628  pTree->pLeft = 0;
45629  p = rowSetEntryMerge(pAux, p);
45630  }
45631  }
45632  if( pTree==0 ){
45633  *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
45634  if( pTree ){
45635  pTree->v = 0;
45636  pTree->pRight = 0;
45637  pTree->pLeft = rowSetListToTree(p);
45638  }
45639  }
45640  pRowSet->pEntry = 0;
45641  pRowSet->pLast = 0;
45642  pRowSet->rsFlags |= ROWSET_SORTED;
45643  }
45644  pRowSet->iBatch = iBatch;
45645  }
45646 
45647  /* Test to see if the iRowid value appears anywhere in the forest.
45648  ** Return 1 if it does and 0 if not.
45649  */
45650  for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
45651  p = pTree->pLeft;
45652  while( p ){
45653  if( p->v<iRowid ){
45654  p = p->pRight;
45655  }else if( p->v>iRowid ){
45656  p = p->pLeft;
45657  }else{
45658  return 1;
45659  }
45660  }
45661  }
45662  return 0;
45663 }
45664 
45665 /************** End of rowset.c **********************************************/
45666 /************** Begin file pager.c *******************************************/
45667 /*
45668 ** 2001 September 15
45669 **
45670 ** The author disclaims copyright to this source code. In place of
45671 ** a legal notice, here is a blessing:
45672 **
45673 ** May you do good and not evil.
45674 ** May you find forgiveness for yourself and forgive others.
45675 ** May you share freely, never taking more than you give.
45676 **
45677 *************************************************************************
45678 ** This is the implementation of the page cache subsystem or "pager".
45679 **
45680 ** The pager is used to access a database disk file. It implements
45681 ** atomic commit and rollback through the use of a journal file that
45682 ** is separate from the database file. The pager also implements file
45683 ** locking to prevent two processes from writing the same database
45684 ** file simultaneously, or one process from reading the database while
45685 ** another is writing.
45686 */
45687 #ifndef SQLITE_OMIT_DISKIO
45688 /* #include "sqliteInt.h" */
45689 /************** Include wal.h in the middle of pager.c ***********************/
45690 /************** Begin file wal.h *********************************************/
45691 /*
45692 ** 2010 February 1
45693 **
45694 ** The author disclaims copyright to this source code. In place of
45695 ** a legal notice, here is a blessing:
45696 **
45697 ** May you do good and not evil.
45698 ** May you find forgiveness for yourself and forgive others.
45699 ** May you share freely, never taking more than you give.
45700 **
45701 *************************************************************************
45702 ** This header file defines the interface to the write-ahead logging
45703 ** system. Refer to the comments below and the header comment attached to
45704 ** the implementation of each function in log.c for further details.
45705 */
45706 
45707 #ifndef _WAL_H_
45708 #define _WAL_H_
45709 
45710 /* #include "sqliteInt.h" */
45711 
45712 /* Additional values that can be added to the sync_flags argument of
45713 ** sqlite3WalFrames():
45714 */
45715 #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
45716 #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
45717 
45718 #ifdef SQLITE_OMIT_WAL
45719 # define sqlite3WalOpen(x,y,z) 0
45720 # define sqlite3WalLimit(x,y)
45721 # define sqlite3WalClose(w,x,y,z) 0
45722 # define sqlite3WalBeginReadTransaction(y,z) 0
45723 # define sqlite3WalEndReadTransaction(z)
45724 # define sqlite3WalDbsize(y) 0
45725 # define sqlite3WalBeginWriteTransaction(y) 0
45726 # define sqlite3WalEndWriteTransaction(x) 0
45727 # define sqlite3WalUndo(x,y,z) 0
45728 # define sqlite3WalSavepoint(y,z)
45729 # define sqlite3WalSavepointUndo(y,z) 0
45730 # define sqlite3WalFrames(u,v,w,x,y,z) 0
45731 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
45732 # define sqlite3WalCallback(z) 0
45733 # define sqlite3WalExclusiveMode(y,z) 0
45734 # define sqlite3WalHeapMemory(z) 0
45735 # define sqlite3WalFramesize(z) 0
45736 # define sqlite3WalFindFrame(x,y,z) 0
45737 # define sqlite3WalFile(x) 0
45738 #else
45739 
45740 #define WAL_SAVEPOINT_NDATA 4
45741 
45742 /* Connection to a write-ahead log (WAL) file.
45743 ** There is one object of this type for each pager.
45744 */
45745 typedef struct Wal Wal;
45746 
45747 /* Open and close a connection to a write-ahead log. */
45748 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
45749 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
45750 
45751 /* Set the limiting size of a WAL file. */
45752 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
45753 
45754 /* Used by readers to open (lock) and close (unlock) a snapshot. A
45755 ** snapshot is like a read-transaction. It is the state of the database
45756 ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
45757 ** preserves the current state even if the other threads or processes
45758 ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
45759 ** transaction and releases the lock.
45760 */
45763 
45764 /* Read a page from the write-ahead log, if it is present. */
45765 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
45766 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
45767 
45768 /* If the WAL is not empty, return the size of the database. */
45769 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
45770 
45771 /* Obtain or release the WRITER lock. */
45774 
45775 /* Undo any frames written (but not committed) to the log */
45776 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
45777 
45778 /* Return an integer that records the current (uncommitted) write
45779 ** position in the WAL */
45780 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
45781 
45782 /* Move the write position of the WAL back to iFrame. Called in
45783 ** response to a ROLLBACK TO command. */
45784 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
45785 
45786 /* Write a frame or frames to the log. */
45787 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
45788 
45789 /* Copy pages from the log to the database file */
45791  Wal *pWal, /* Write-ahead log connection */
45792  int eMode, /* One of PASSIVE, FULL and RESTART */
45793  int (*xBusy)(void*), /* Function to call when busy */
45794  void *pBusyArg, /* Context argument for xBusyHandler */
45795  int sync_flags, /* Flags to sync db file with (or 0) */
45796  int nBuf, /* Size of buffer nBuf */
45797  u8 *zBuf, /* Temporary buffer to use */
45798  int *pnLog, /* OUT: Number of frames in WAL */
45799  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
45800 );
45801 
45802 /* Return the value to pass to a sqlite3_wal_hook callback, the
45803 ** number of frames in the WAL at the point of the last commit since
45804 ** sqlite3WalCallback() was called. If no commits have occurred since
45805 ** the last call, then return 0.
45806 */
45808 
45809 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
45810 ** by the pager layer on the database file.
45811 */
45812 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
45813 
45814 /* Return true if the argument is non-NULL and the WAL module is using
45815 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
45816 ** WAL module is using shared-memory, return false.
45817 */
45819 
45820 #ifdef SQLITE_ENABLE_SNAPSHOT
45821 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot);
45822 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot);
45823 #endif
45824 
45825 #ifdef SQLITE_ENABLE_ZIPVFS
45826 /* If the WAL file is not empty, return the number of bytes of content
45827 ** stored in each frame (i.e. the db page-size when the WAL was created).
45828 */
45829 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
45830 #endif
45831 
45832 /* Return the sqlite3_file object for the WAL file */
45833 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal);
45834 
45835 #endif /* ifndef SQLITE_OMIT_WAL */
45836 #endif /* _WAL_H_ */
45837 
45838 /************** End of wal.h *************************************************/
45839 /************** Continuing where we left off in pager.c **********************/
45840 
45841 
45842 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
45843 **
45844 ** This comment block describes invariants that hold when using a rollback
45845 ** journal. These invariants do not apply for journal_mode=WAL,
45846 ** journal_mode=MEMORY, or journal_mode=OFF.
45847 **
45848 ** Within this comment block, a page is deemed to have been synced
45849 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
45850 ** Otherwise, the page is not synced until the xSync method of the VFS
45851 ** is called successfully on the file containing the page.
45852 **
45853 ** Definition: A page of the database file is said to be "overwriteable" if
45854 ** one or more of the following are true about the page:
45855 **
45856 ** (a) The original content of the page as it was at the beginning of
45857 ** the transaction has been written into the rollback journal and
45858 ** synced.
45859 **
45860 ** (b) The page was a freelist leaf page at the start of the transaction.
45861 **
45862 ** (c) The page number is greater than the largest page that existed in
45863 ** the database file at the start of the transaction.
45864 **
45865 ** (1) A page of the database file is never overwritten unless one of the
45866 ** following are true:
45867 **
45868 ** (a) The page and all other pages on the same sector are overwriteable.
45869 **
45870 ** (b) The atomic page write optimization is enabled, and the entire
45871 ** transaction other than the update of the transaction sequence
45872 ** number consists of a single page change.
45873 **
45874 ** (2) The content of a page written into the rollback journal exactly matches
45875 ** both the content in the database when the rollback journal was written
45876 ** and the content in the database at the beginning of the current
45877 ** transaction.
45878 **
45879 ** (3) Writes to the database file are an integer multiple of the page size
45880 ** in length and are aligned on a page boundary.
45881 **
45882 ** (4) Reads from the database file are either aligned on a page boundary and
45883 ** an integer multiple of the page size in length or are taken from the
45884 ** first 100 bytes of the database file.
45885 **
45886 ** (5) All writes to the database file are synced prior to the rollback journal
45887 ** being deleted, truncated, or zeroed.
45888 **
45889 ** (6) If a master journal file is used, then all writes to the database file
45890 ** are synced prior to the master journal being deleted.
45891 **
45892 ** Definition: Two databases (or the same database at two points it time)
45893 ** are said to be "logically equivalent" if they give the same answer to
45894 ** all queries. Note in particular the content of freelist leaf
45895 ** pages can be changed arbitrarily without affecting the logical equivalence
45896 ** of the database.
45897 **
45898 ** (7) At any time, if any subset, including the empty set and the total set,
45899 ** of the unsynced changes to a rollback journal are removed and the
45900 ** journal is rolled back, the resulting database file will be logically
45901 ** equivalent to the database file at the beginning of the transaction.
45902 **
45903 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
45904 ** is called to restore the database file to the same size it was at
45905 ** the beginning of the transaction. (In some VFSes, the xTruncate
45906 ** method is a no-op, but that does not change the fact the SQLite will
45907 ** invoke it.)
45908 **
45909 ** (9) Whenever the database file is modified, at least one bit in the range
45910 ** of bytes from 24 through 39 inclusive will be changed prior to releasing
45911 ** the EXCLUSIVE lock, thus signaling other connections on the same
45912 ** database to flush their caches.
45913 **
45914 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
45915 ** than one billion transactions.
45916 **
45917 ** (11) A database file is well-formed at the beginning and at the conclusion
45918 ** of every transaction.
45919 **
45920 ** (12) An EXCLUSIVE lock is held on the database file when writing to
45921 ** the database file.
45922 **
45923 ** (13) A SHARED lock is held on the database file while reading any
45924 ** content out of the database file.
45925 **
45926 ******************************************************************************/
45927 
45928 /*
45929 ** Macros for troubleshooting. Normally turned off
45930 */
45931 #if 0
45932 int sqlite3PagerTrace=1; /* True to enable tracing */
45933 #define sqlite3DebugPrintf printf
45934 #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
45935 #else
45936 #define PAGERTRACE(X)
45937 #endif
45938 
45939 /*
45940 ** The following two macros are used within the PAGERTRACE() macros above
45941 ** to print out file-descriptors.
45942 **
45943 ** PAGERID() takes a pointer to a Pager struct as its argument. The
45944 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
45945 ** struct as its argument.
45946 */
45947 #define PAGERID(p) ((int)(p->fd))
45948 #define FILEHANDLEID(fd) ((int)fd)
45949 
45950 /*
45951 ** The Pager.eState variable stores the current 'state' of a pager. A
45952 ** pager may be in any one of the seven states shown in the following
45953 ** state diagram.
45954 **
45955 ** OPEN <------+------+
45956 ** | | |
45957 ** V | |
45958 ** +---------> READER-------+ |
45959 ** | | |
45960 ** | V |
45961 ** |<-------WRITER_LOCKED------> ERROR
45962 ** | | ^
45963 ** | V |
45964 ** |<------WRITER_CACHEMOD-------->|
45965 ** | | |
45966 ** | V |
45967 ** |<-------WRITER_DBMOD---------->|
45968 ** | | |
45969 ** | V |
45970 ** +<------WRITER_FINISHED-------->+
45971 **
45972 **
45973 ** List of state transitions and the C [function] that performs each:
45974 **
45975 ** OPEN -> READER [sqlite3PagerSharedLock]
45976 ** READER -> OPEN [pager_unlock]
45977 **
45978 ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
45979 ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
45980 ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
45981 ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
45982 ** WRITER_*** -> READER [pager_end_transaction]
45983 **
45984 ** WRITER_*** -> ERROR [pager_error]
45985 ** ERROR -> OPEN [pager_unlock]
45986 **
45987 **
45988 ** OPEN:
45989 **
45990 ** The pager starts up in this state. Nothing is guaranteed in this
45991 ** state - the file may or may not be locked and the database size is
45992 ** unknown. The database may not be read or written.
45993 **
45994 ** * No read or write transaction is active.
45995 ** * Any lock, or no lock at all, may be held on the database file.
45996 ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
45997 **
45998 ** READER:
45999 **
46000 ** In this state all the requirements for reading the database in
46001 ** rollback (non-WAL) mode are met. Unless the pager is (or recently
46002 ** was) in exclusive-locking mode, a user-level read transaction is
46003 ** open. The database size is known in this state.
46004 **
46005 ** A connection running with locking_mode=normal enters this state when
46006 ** it opens a read-transaction on the database and returns to state
46007 ** OPEN after the read-transaction is completed. However a connection
46008 ** running in locking_mode=exclusive (including temp databases) remains in
46009 ** this state even after the read-transaction is closed. The only way
46010 ** a locking_mode=exclusive connection can transition from READER to OPEN
46011 ** is via the ERROR state (see below).
46012 **
46013 ** * A read transaction may be active (but a write-transaction cannot).
46014 ** * A SHARED or greater lock is held on the database file.
46015 ** * The dbSize variable may be trusted (even if a user-level read
46016 ** transaction is not active). The dbOrigSize and dbFileSize variables
46017 ** may not be trusted at this point.
46018 ** * If the database is a WAL database, then the WAL connection is open.
46019 ** * Even if a read-transaction is not open, it is guaranteed that
46020 ** there is no hot-journal in the file-system.
46021 **
46022 ** WRITER_LOCKED:
46023 **
46024 ** The pager moves to this state from READER when a write-transaction
46025 ** is first opened on the database. In WRITER_LOCKED state, all locks
46026 ** required to start a write-transaction are held, but no actual
46027 ** modifications to the cache or database have taken place.
46028 **
46029 ** In rollback mode, a RESERVED or (if the transaction was opened with
46030 ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
46031 ** moving to this state, but the journal file is not written to or opened
46032 ** to in this state. If the transaction is committed or rolled back while
46033 ** in WRITER_LOCKED state, all that is required is to unlock the database
46034 ** file.
46035 **
46036 ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
46037 ** If the connection is running with locking_mode=exclusive, an attempt
46038 ** is made to obtain an EXCLUSIVE lock on the database file.
46039 **
46040 ** * A write transaction is active.
46041 ** * If the connection is open in rollback-mode, a RESERVED or greater
46042 ** lock is held on the database file.
46043 ** * If the connection is open in WAL-mode, a WAL write transaction
46044 ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
46045 ** called).
46046 ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
46047 ** * The contents of the pager cache have not been modified.
46048 ** * The journal file may or may not be open.
46049 ** * Nothing (not even the first header) has been written to the journal.
46050 **
46051 ** WRITER_CACHEMOD:
46052 **
46053 ** A pager moves from WRITER_LOCKED state to this state when a page is
46054 ** first modified by the upper layer. In rollback mode the journal file
46055 ** is opened (if it is not already open) and a header written to the
46056 ** start of it. The database file on disk has not been modified.
46057 **
46058 ** * A write transaction is active.
46059 ** * A RESERVED or greater lock is held on the database file.
46060 ** * The journal file is open and the first header has been written
46061 ** to it, but the header has not been synced to disk.
46062 ** * The contents of the page cache have been modified.
46063 **
46064 ** WRITER_DBMOD:
46065 **
46066 ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
46067 ** when it modifies the contents of the database file. WAL connections
46068 ** never enter this state (since they do not modify the database file,
46069 ** just the log file).
46070 **
46071 ** * A write transaction is active.
46072 ** * An EXCLUSIVE or greater lock is held on the database file.
46073 ** * The journal file is open and the first header has been written
46074 ** and synced to disk.
46075 ** * The contents of the page cache have been modified (and possibly
46076 ** written to disk).
46077 **
46078 ** WRITER_FINISHED:
46079 **
46080 ** It is not possible for a WAL connection to enter this state.
46081 **
46082 ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
46083 ** state after the entire transaction has been successfully written into the
46084 ** database file. In this state the transaction may be committed simply
46085 ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
46086 ** not possible to modify the database further. At this point, the upper
46087 ** layer must either commit or rollback the transaction.
46088 **
46089 ** * A write transaction is active.
46090 ** * An EXCLUSIVE or greater lock is held on the database file.
46091 ** * All writing and syncing of journal and database data has finished.
46092 ** If no error occurred, all that remains is to finalize the journal to
46093 ** commit the transaction. If an error did occur, the caller will need
46094 ** to rollback the transaction.
46095 **
46096 ** ERROR:
46097 **
46098 ** The ERROR state is entered when an IO or disk-full error (including
46099 ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
46100 ** difficult to be sure that the in-memory pager state (cache contents,
46101 ** db size etc.) are consistent with the contents of the file-system.
46102 **
46103 ** Temporary pager files may enter the ERROR state, but in-memory pagers
46104 ** cannot.
46105 **
46106 ** For example, if an IO error occurs while performing a rollback,
46107 ** the contents of the page-cache may be left in an inconsistent state.
46108 ** At this point it would be dangerous to change back to READER state
46109 ** (as usually happens after a rollback). Any subsequent readers might
46110 ** report database corruption (due to the inconsistent cache), and if
46111 ** they upgrade to writers, they may inadvertently corrupt the database
46112 ** file. To avoid this hazard, the pager switches into the ERROR state
46113 ** instead of READER following such an error.
46114 **
46115 ** Once it has entered the ERROR state, any attempt to use the pager
46116 ** to read or write data returns an error. Eventually, once all
46117 ** outstanding transactions have been abandoned, the pager is able to
46118 ** transition back to OPEN state, discarding the contents of the
46119 ** page-cache and any other in-memory state at the same time. Everything
46120 ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
46121 ** when a read-transaction is next opened on the pager (transitioning
46122 ** the pager into READER state). At that point the system has recovered
46123 ** from the error.
46124 **
46125 ** Specifically, the pager jumps into the ERROR state if:
46126 **
46127 ** 1. An error occurs while attempting a rollback. This happens in
46128 ** function sqlite3PagerRollback().
46129 **
46130 ** 2. An error occurs while attempting to finalize a journal file
46131 ** following a commit in function sqlite3PagerCommitPhaseTwo().
46132 **
46133 ** 3. An error occurs while attempting to write to the journal or
46134 ** database file in function pagerStress() in order to free up
46135 ** memory.
46136 **
46137 ** In other cases, the error is returned to the b-tree layer. The b-tree
46138 ** layer then attempts a rollback operation. If the error condition
46139 ** persists, the pager enters the ERROR state via condition (1) above.
46140 **
46141 ** Condition (3) is necessary because it can be triggered by a read-only
46142 ** statement executed within a transaction. In this case, if the error
46143 ** code were simply returned to the user, the b-tree layer would not
46144 ** automatically attempt a rollback, as it assumes that an error in a
46145 ** read-only statement cannot leave the pager in an internally inconsistent
46146 ** state.
46147 **
46148 ** * The Pager.errCode variable is set to something other than SQLITE_OK.
46149 ** * There are one or more outstanding references to pages (after the
46150 ** last reference is dropped the pager should move back to OPEN state).
46151 ** * The pager is not an in-memory pager.
46152 **
46153 **
46154 ** Notes:
46155 **
46156 ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
46157 ** connection is open in WAL mode. A WAL connection is always in one
46158 ** of the first four states.
46159 **
46160 ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
46161 ** state. There are two exceptions: immediately after exclusive-mode has
46162 ** been turned on (and before any read or write transactions are
46163 ** executed), and when the pager is leaving the "error state".
46164 **
46165 ** * See also: assert_pager_state().
46166 */
46167 #define PAGER_OPEN 0
46168 #define PAGER_READER 1
46169 #define PAGER_WRITER_LOCKED 2
46170 #define PAGER_WRITER_CACHEMOD 3
46171 #define PAGER_WRITER_DBMOD 4
46172 #define PAGER_WRITER_FINISHED 5
46173 #define PAGER_ERROR 6
46174 
46175 /*
46176 ** The Pager.eLock variable is almost always set to one of the
46177 ** following locking-states, according to the lock currently held on
46178 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46179 ** This variable is kept up to date as locks are taken and released by
46180 ** the pagerLockDb() and pagerUnlockDb() wrappers.
46181 **
46182 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
46183 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
46184 ** the operation was successful. In these circumstances pagerLockDb() and
46185 ** pagerUnlockDb() take a conservative approach - eLock is always updated
46186 ** when unlocking the file, and only updated when locking the file if the
46187 ** VFS call is successful. This way, the Pager.eLock variable may be set
46188 ** to a less exclusive (lower) value than the lock that is actually held
46189 ** at the system level, but it is never set to a more exclusive value.
46190 **
46191 ** This is usually safe. If an xUnlock fails or appears to fail, there may
46192 ** be a few redundant xLock() calls or a lock may be held for longer than
46193 ** required, but nothing really goes wrong.
46194 **
46195 ** The exception is when the database file is unlocked as the pager moves
46196 ** from ERROR to OPEN state. At this point there may be a hot-journal file
46197 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
46198 ** transition, by the same pager or any other). If the call to xUnlock()
46199 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
46200 ** can confuse the call to xCheckReservedLock() call made later as part
46201 ** of hot-journal detection.
46202 **
46203 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
46204 ** lock held by this process or any others". So xCheckReservedLock may
46205 ** return true because the caller itself is holding an EXCLUSIVE lock (but
46206 ** doesn't know it because of a previous error in xUnlock). If this happens
46207 ** a hot-journal may be mistaken for a journal being created by an active
46208 ** transaction in another process, causing SQLite to read from the database
46209 ** without rolling it back.
46210 **
46211 ** To work around this, if a call to xUnlock() fails when unlocking the
46212 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
46213 ** is only changed back to a real locking state after a successful call
46214 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
46215 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
46216 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
46217 ** lock on the database file before attempting to roll it back. See function
46218 ** PagerSharedLock() for more detail.
46219 **
46220 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
46221 ** PAGER_OPEN state.
46222 */
46223 #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
46224 
46225 /*
46226 ** A macro used for invoking the codec if there is one
46227 */
46228 #ifdef SQLITE_HAS_CODEC
46229 # define CODEC1(P,D,N,X,E) \
46230  if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
46231 # define CODEC2(P,D,N,X,E,O) \
46232  if( P->xCodec==0 ){ O=(char*)D; }else \
46233  if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
46234 #else
46235 # define CODEC1(P,D,N,X,E) /* NO-OP */
46236 # define CODEC2(P,D,N,X,E,O) O=(char*)D
46237 #endif
46238 
46239 /*
46240 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
46241 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
46242 ** This could conceivably cause corruption following a power failure on
46243 ** such a system. This is currently an undocumented limit.
46244 */
46245 #define MAX_SECTOR_SIZE 0x10000
46246 
46247 
46248 /*
46249 ** An instance of the following structure is allocated for each active
46250 ** savepoint and statement transaction in the system. All such structures
46251 ** are stored in the Pager.aSavepoint[] array, which is allocated and
46252 ** resized using sqlite3Realloc().
46253 **
46254 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
46255 ** set to 0. If a journal-header is written into the main journal while
46256 ** the savepoint is active, then iHdrOffset is set to the byte offset
46257 ** immediately following the last journal record written into the main
46258 ** journal before the journal-header. This is required during savepoint
46259 ** rollback (see pagerPlaybackSavepoint()).
46260 */
46263  i64 iOffset; /* Starting offset in main journal */
46264  i64 iHdrOffset; /* See above */
46265  Bitvec *pInSavepoint; /* Set of pages in this savepoint */
46266  Pgno nOrig; /* Original number of pages in file */
46267  Pgno iSubRec; /* Index of first record in sub-journal */
46268 #ifndef SQLITE_OMIT_WAL
46269  u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
46270 #endif
46271 };
46272 
46273 /*
46274 ** Bits of the Pager.doNotSpill flag. See further description below.
46275 */
46276 #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
46277 #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
46278 #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
46279 
46280 /*
46281 ** An open page cache is an instance of struct Pager. A description of
46282 ** some of the more important member variables follows:
46283 **
46284 ** eState
46285 **
46286 ** The current 'state' of the pager object. See the comment and state
46287 ** diagram above for a description of the pager state.
46288 **
46289 ** eLock
46290 **
46291 ** For a real on-disk database, the current lock held on the database file -
46292 ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
46293 **
46294 ** For a temporary or in-memory database (neither of which require any
46295 ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
46296 ** databases always have Pager.exclusiveMode==1, this tricks the pager
46297 ** logic into thinking that it already has all the locks it will ever
46298 ** need (and no reason to release them).
46299 **
46300 ** In some (obscure) circumstances, this variable may also be set to
46301 ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
46302 ** details.
46303 **
46304 ** changeCountDone
46305 **
46306 ** This boolean variable is used to make sure that the change-counter
46307 ** (the 4-byte header field at byte offset 24 of the database file) is
46308 ** not updated more often than necessary.
46309 **
46310 ** It is set to true when the change-counter field is updated, which
46311 ** can only happen if an exclusive lock is held on the database file.
46312 ** It is cleared (set to false) whenever an exclusive lock is
46313 ** relinquished on the database file. Each time a transaction is committed,
46314 ** The changeCountDone flag is inspected. If it is true, the work of
46315 ** updating the change-counter is omitted for the current transaction.
46316 **
46317 ** This mechanism means that when running in exclusive mode, a connection
46318 ** need only update the change-counter once, for the first transaction
46319 ** committed.
46320 **
46321 ** setMaster
46322 **
46323 ** When PagerCommitPhaseOne() is called to commit a transaction, it may
46324 ** (or may not) specify a master-journal name to be written into the
46325 ** journal file before it is synced to disk.
46326 **
46327 ** Whether or not a journal file contains a master-journal pointer affects
46328 ** the way in which the journal file is finalized after the transaction is
46329 ** committed or rolled back when running in "journal_mode=PERSIST" mode.
46330 ** If a journal file does not contain a master-journal pointer, it is
46331 ** finalized by overwriting the first journal header with zeroes. If
46332 ** it does contain a master-journal pointer the journal file is finalized
46333 ** by truncating it to zero bytes, just as if the connection were
46334 ** running in "journal_mode=truncate" mode.
46335 **
46336 ** Journal files that contain master journal pointers cannot be finalized
46337 ** simply by overwriting the first journal-header with zeroes, as the
46338 ** master journal pointer could interfere with hot-journal rollback of any
46339 ** subsequently interrupted transaction that reuses the journal file.
46340 **
46341 ** The flag is cleared as soon as the journal file is finalized (either
46342 ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
46343 ** journal file from being successfully finalized, the setMaster flag
46344 ** is cleared anyway (and the pager will move to ERROR state).
46345 **
46346 ** doNotSpill
46347 **
46348 ** This variables control the behavior of cache-spills (calls made by
46349 ** the pcache module to the pagerStress() routine to write cached data
46350 ** to the file-system in order to free up memory).
46351 **
46352 ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
46353 ** writing to the database from pagerStress() is disabled altogether.
46354 ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
46355 ** comes up during savepoint rollback that requires the pcache module
46356 ** to allocate a new page to prevent the journal file from being written
46357 ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
46358 ** case is a user preference.
46359 **
46360 ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from
46361 ** pagerStress() is permitted, but syncing the journal file is not.
46362 ** This flag is set by sqlite3PagerWrite() when the file-system sector-size
46363 ** is larger than the database page-size in order to prevent a journal sync
46364 ** from happening in between the journalling of two pages on the same sector.
46365 **
46366 ** subjInMemory
46367 **
46368 ** This is a boolean variable. If true, then any required sub-journal
46369 ** is opened as an in-memory journal file. If false, then in-memory
46370 ** sub-journals are only used for in-memory pager files.
46371 **
46372 ** This variable is updated by the upper layer each time a new
46373 ** write-transaction is opened.
46374 **
46375 ** dbSize, dbOrigSize, dbFileSize
46376 **
46377 ** Variable dbSize is set to the number of pages in the database file.
46378 ** It is valid in PAGER_READER and higher states (all states except for
46379 ** OPEN and ERROR).
46380 **
46381 ** dbSize is set based on the size of the database file, which may be
46382 ** larger than the size of the database (the value stored at offset
46383 ** 28 of the database header by the btree). If the size of the file
46384 ** is not an integer multiple of the page-size, the value stored in
46385 ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
46386 ** Except, any file that is greater than 0 bytes in size is considered
46387 ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
46388 ** to dbSize==1).
46389 **
46390 ** During a write-transaction, if pages with page-numbers greater than
46391 ** dbSize are modified in the cache, dbSize is updated accordingly.
46392 ** Similarly, if the database is truncated using PagerTruncateImage(),
46393 ** dbSize is updated.
46394 **
46395 ** Variables dbOrigSize and dbFileSize are valid in states
46396 ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
46397 ** variable at the start of the transaction. It is used during rollback,
46398 ** and to determine whether or not pages need to be journalled before
46399 ** being modified.
46400 **
46401 ** Throughout a write-transaction, dbFileSize contains the size of
46402 ** the file on disk in pages. It is set to a copy of dbSize when the
46403 ** write-transaction is first opened, and updated when VFS calls are made
46404 ** to write or truncate the database file on disk.
46405 **
46406 ** The only reason the dbFileSize variable is required is to suppress
46407 ** unnecessary calls to xTruncate() after committing a transaction. If,
46408 ** when a transaction is committed, the dbFileSize variable indicates
46409 ** that the database file is larger than the database image (Pager.dbSize),
46410 ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
46411 ** to measure the database file on disk, and then truncates it if required.
46412 ** dbFileSize is not used when rolling back a transaction. In this case
46413 ** pager_truncate() is called unconditionally (which means there may be
46414 ** a call to xFilesize() that is not strictly required). In either case,
46415 ** pager_truncate() may cause the file to become smaller or larger.
46416 **
46417 ** dbHintSize
46418 **
46419 ** The dbHintSize variable is used to limit the number of calls made to
46420 ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
46421 **
46422 ** dbHintSize is set to a copy of the dbSize variable when a
46423 ** write-transaction is opened (at the same time as dbFileSize and
46424 ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
46425 ** dbHintSize is increased to the number of pages that correspond to the
46426 ** size-hint passed to the method call. See pager_write_pagelist() for
46427 ** details.
46428 **
46429 ** errCode
46430 **
46431 ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
46432 ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
46433 ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
46434 ** sub-codes.
46435 */
46436 struct Pager {
46437  sqlite3_vfs *pVfs; /* OS functions to use for IO */
46438  u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
46439  u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
46440  u8 useJournal; /* Use a rollback journal on this file */
46441  u8 noSync; /* Do not sync the journal if true */
46442  u8 fullSync; /* Do extra syncs of the journal for robustness */
46443  u8 extraSync; /* sync directory after journal delete */
46444  u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
46445  u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
46446  u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
46447  u8 tempFile; /* zFilename is a temporary or immutable file */
46448  u8 noLock; /* Do not lock (except in WAL mode) */
46449  u8 readOnly; /* True for a read-only database */
46450  u8 memDb; /* True to inhibit all file I/O */
46451 
46452  /**************************************************************************
46453  ** The following block contains those class members that change during
46454  ** routine operation. Class members not in this block are either fixed
46455  ** when the pager is first created or else only change when there is a
46456  ** significant mode change (such as changing the page_size, locking_mode,
46457  ** or the journal_mode). From another view, these class members describe
46458  ** the "state" of the pager, while other class members describe the
46459  ** "configuration" of the pager.
46460  */
46461  u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
46462  u8 eLock; /* Current lock held on database file */
46463  u8 changeCountDone; /* Set after incrementing the change-counter */
46464  u8 setMaster; /* True if a m-j name has been written to jrnl */
46465  u8 doNotSpill; /* Do not spill the cache when non-zero */
46466  u8 subjInMemory; /* True to use in-memory sub-journals */
46467  u8 bUseFetch; /* True to use xFetch() */
46468  u8 hasHeldSharedLock; /* True if a shared lock has ever been held */
46469  Pgno dbSize; /* Number of pages in the database */
46470  Pgno dbOrigSize; /* dbSize before the current transaction */
46471  Pgno dbFileSize; /* Number of pages in the database file */
46472  Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
46473  int errCode; /* One of several kinds of errors */
46474  int nRec; /* Pages journalled since last j-header written */
46475  u32 cksumInit; /* Quasi-random value added to every checksum */
46476  u32 nSubRec; /* Number of records written to sub-journal */
46477  Bitvec *pInJournal; /* One bit for each page in the database file */
46478  sqlite3_file *fd; /* File descriptor for database */
46479  sqlite3_file *jfd; /* File descriptor for main journal */
46480  sqlite3_file *sjfd; /* File descriptor for sub-journal */
46481  i64 journalOff; /* Current write offset in the journal file */
46482  i64 journalHdr; /* Byte offset to previous journal header */
46483  sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
46484  PagerSavepoint *aSavepoint; /* Array of active savepoints */
46485  int nSavepoint; /* Number of elements in aSavepoint[] */
46486  u32 iDataVersion; /* Changes whenever database content changes */
46487  char dbFileVers[16]; /* Changes whenever database file changes */
46488 
46489  int nMmapOut; /* Number of mmap pages currently outstanding */
46490  sqlite3_int64 szMmap; /* Desired maximum mmap size */
46491  PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
46492  /*
46493  ** End of the routinely-changing class members
46494  ***************************************************************************/
46495 
46496  u16 nExtra; /* Add this many bytes to each in-memory page */
46497  i16 nReserve; /* Number of unused bytes at end of each page */
46498  u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
46499  u32 sectorSize; /* Assumed sector size during rollback */
46500  int pageSize; /* Number of bytes in a page */
46501  Pgno mxPgno; /* Maximum allowed size of the database */
46502  i64 journalSizeLimit; /* Size limit for persistent journal files */
46503  char *zFilename; /* Name of the database file */
46504  char *zJournal; /* Name of the journal file */
46505  int (*xBusyHandler)(void*); /* Function to call when busy */
46506  void *pBusyHandlerArg; /* Context argument for xBusyHandler */
46507  int aStat[3]; /* Total cache hits, misses and writes */
46508 #ifdef SQLITE_TEST
46509  int nRead; /* Database pages read */
46510 #endif
46511  void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
46512 #ifdef SQLITE_HAS_CODEC
46513  void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
46514  void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
46515  void (*xCodecFree)(void*); /* Destructor for the codec */
46516  void *pCodec; /* First argument to xCodec... methods */
46517 #endif
46518  char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
46519  PCache *pPCache; /* Pointer to page cache object */
46520 #ifndef SQLITE_OMIT_WAL
46521  Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
46522  char *zWal; /* File name for write-ahead log */
46523 #endif
46524 };
46525 
46526 /*
46527 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
46528 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
46529 ** or CACHE_WRITE to sqlite3_db_status().
46530 */
46531 #define PAGER_STAT_HIT 0
46532 #define PAGER_STAT_MISS 1
46533 #define PAGER_STAT_WRITE 2
46534 
46535 /*
46536 ** The following global variables hold counters used for
46537 ** testing purposes only. These variables do not exist in
46538 ** a non-testing build. These variables are not thread-safe.
46539 */
46540 #ifdef SQLITE_TEST
46541 SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
46542 SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
46543 SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
46544 # define PAGER_INCR(v) v++
46545 #else
46546 # define PAGER_INCR(v)
46547 #endif
46548 
46549 
46550 
46551 /*
46552 ** Journal files begin with the following magic string. The data
46553 ** was obtained from /dev/random. It is used only as a sanity check.
46554 **
46555 ** Since version 2.8.0, the journal format contains additional sanity
46556 ** checking information. If the power fails while the journal is being
46557 ** written, semi-random garbage data might appear in the journal
46558 ** file after power is restored. If an attempt is then made
46559 ** to roll the journal back, the database could be corrupted. The additional
46560 ** sanity checking data is an attempt to discover the garbage in the
46561 ** journal and ignore it.
46562 **
46563 ** The sanity checking information for the new journal format consists
46564 ** of a 32-bit checksum on each page of data. The checksum covers both
46565 ** the page number and the pPager->pageSize bytes of data for the page.
46566 ** This cksum is initialized to a 32-bit random value that appears in the
46567 ** journal file right after the header. The random initializer is important,
46568 ** because garbage data that appears at the end of a journal is likely
46569 ** data that was once in other files that have now been deleted. If the
46570 ** garbage data came from an obsolete journal file, the checksums might
46571 ** be correct. But by initializing the checksum to random value which
46572 ** is different for every journal, we minimize that risk.
46573 */
46574 static const unsigned char aJournalMagic[] = {
46575  0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
46576 };
46577 
46578 /*
46579 ** The size of the of each page record in the journal is given by
46580 ** the following macro.
46581 */
46582 #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
46583 
46584 /*
46585 ** The journal header size for this pager. This is usually the same
46586 ** size as a single disk sector. See also setSectorSize().
46587 */
46588 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
46589 
46590 /*
46591 ** The macro MEMDB is true if we are dealing with an in-memory database.
46592 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
46593 ** the value of MEMDB will be a constant and the compiler will optimize
46594 ** out code that would never execute.
46595 */
46596 #ifdef SQLITE_OMIT_MEMORYDB
46597 # define MEMDB 0
46598 #else
46599 # define MEMDB pPager->memDb
46600 #endif
46601 
46602 /*
46603 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
46604 ** interfaces to access the database using memory-mapped I/O.
46605 */
46606 #if SQLITE_MAX_MMAP_SIZE>0
46607 # define USEFETCH(x) ((x)->bUseFetch)
46608 #else
46609 # define USEFETCH(x) 0
46610 #endif
46611 
46612 /*
46613 ** The maximum legal page number is (2^31 - 1).
46614 */
46615 #define PAGER_MAX_PGNO 2147483647
46616 
46617 /*
46618 ** The argument to this macro is a file descriptor (type sqlite3_file*).
46619 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
46620 **
46621 ** This is so that expressions can be written as:
46622 **
46623 ** if( isOpen(pPager->jfd) ){ ...
46624 **
46625 ** instead of
46626 **
46627 ** if( pPager->jfd->pMethods ){ ...
46628 */
46629 #define isOpen(pFd) ((pFd)->pMethods!=0)
46630 
46631 /*
46632 ** Return true if this pager uses a write-ahead log instead of the usual
46633 ** rollback journal. Otherwise false.
46634 */
46635 #ifndef SQLITE_OMIT_WAL
46636 static int pagerUseWal(Pager *pPager){
46637  return (pPager->pWal!=0);
46638 }
46639 #else
46640 # define pagerUseWal(x) 0
46641 # define pagerRollbackWal(x) 0
46642 # define pagerWalFrames(v,w,x,y) 0
46643 # define pagerOpenWalIfPresent(z) SQLITE_OK
46644 # define pagerBeginReadTransaction(z) SQLITE_OK
46645 #endif
46646 
46647 #ifndef NDEBUG
46648 /*
46649 ** Usage:
46650 **
46651 ** assert( assert_pager_state(pPager) );
46652 **
46653 ** This function runs many asserts to try to find inconsistencies in
46654 ** the internal state of the Pager object.
46655 */
46656 static int assert_pager_state(Pager *p){
46657  Pager *pPager = p;
46658 
46659  /* State must be valid. */
46660  assert( p->eState==PAGER_OPEN
46661  || p->eState==PAGER_READER
46664  || p->eState==PAGER_WRITER_DBMOD
46666  || p->eState==PAGER_ERROR
46667  );
46668 
46669  /* Regardless of the current state, a temp-file connection always behaves
46670  ** as if it has an exclusive lock on the database file. It never updates
46671  ** the change-counter field, so the changeCountDone flag is always set.
46672  */
46673  assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
46674  assert( p->tempFile==0 || pPager->changeCountDone );
46675 
46676  /* If the useJournal flag is clear, the journal-mode must be "OFF".
46677  ** And if the journal-mode is "OFF", the journal file must not be open.
46678  */
46681 
46682  /* Check that MEMDB implies noSync. And an in-memory journal. Since
46683  ** this means an in-memory pager performs no IO at all, it cannot encounter
46684  ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
46685  ** a journal file. (although the in-memory journal implementation may
46686  ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
46687  ** is therefore not possible for an in-memory pager to enter the ERROR
46688  ** state.
46689  */
46690  if( MEMDB ){
46691  assert( !isOpen(p->fd) );
46692  assert( p->noSync );
46695  );
46696  assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
46697  assert( pagerUseWal(p)==0 );
46698  }
46699 
46700  /* If changeCountDone is set, a RESERVED lock or greater must be held
46701  ** on the file.
46702  */
46703  assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
46704  assert( p->eLock!=PENDING_LOCK );
46705 
46706  switch( p->eState ){
46707  case PAGER_OPEN:
46708  assert( !MEMDB );
46709  assert( pPager->errCode==SQLITE_OK );
46710  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
46711  break;
46712 
46713  case PAGER_READER:
46714  assert( pPager->errCode==SQLITE_OK );
46715  assert( p->eLock!=UNKNOWN_LOCK );
46716  assert( p->eLock>=SHARED_LOCK );
46717  break;
46718 
46719  case PAGER_WRITER_LOCKED:
46720  assert( p->eLock!=UNKNOWN_LOCK );
46721  assert( pPager->errCode==SQLITE_OK );
46722  if( !pagerUseWal(pPager) ){
46723  assert( p->eLock>=RESERVED_LOCK );
46724  }
46725  assert( pPager->dbSize==pPager->dbOrigSize );
46726  assert( pPager->dbOrigSize==pPager->dbFileSize );
46727  assert( pPager->dbOrigSize==pPager->dbHintSize );
46728  assert( pPager->setMaster==0 );
46729  break;
46730 
46731  case PAGER_WRITER_CACHEMOD:
46732  assert( p->eLock!=UNKNOWN_LOCK );
46733  assert( pPager->errCode==SQLITE_OK );
46734  if( !pagerUseWal(pPager) ){
46735  /* It is possible that if journal_mode=wal here that neither the
46736  ** journal file nor the WAL file are open. This happens during
46737  ** a rollback transaction that switches from journal_mode=off
46738  ** to journal_mode=wal.
46739  */
46740  assert( p->eLock>=RESERVED_LOCK );
46741  assert( isOpen(p->jfd)
46744  );
46745  }
46746  assert( pPager->dbOrigSize==pPager->dbFileSize );
46747  assert( pPager->dbOrigSize==pPager->dbHintSize );
46748  break;
46749 
46750  case PAGER_WRITER_DBMOD:
46751  assert( p->eLock==EXCLUSIVE_LOCK );
46752  assert( pPager->errCode==SQLITE_OK );
46753  assert( !pagerUseWal(pPager) );
46754  assert( p->eLock>=EXCLUSIVE_LOCK );
46755  assert( isOpen(p->jfd)
46758  );
46759  assert( pPager->dbOrigSize<=pPager->dbHintSize );
46760  break;
46761 
46762  case PAGER_WRITER_FINISHED:
46763  assert( p->eLock==EXCLUSIVE_LOCK );
46764  assert( pPager->errCode==SQLITE_OK );
46765  assert( !pagerUseWal(pPager) );
46766  assert( isOpen(p->jfd)
46769  );
46770  break;
46771 
46772  case PAGER_ERROR:
46773  /* There must be at least one outstanding reference to the pager if
46774  ** in ERROR state. Otherwise the pager should have already dropped
46775  ** back to OPEN state.
46776  */
46777  assert( pPager->errCode!=SQLITE_OK );
46778  assert( sqlite3PcacheRefCount(pPager->pPCache)>0 || pPager->tempFile );
46779  break;
46780  }
46781 
46782  return 1;
46783 }
46784 #endif /* ifndef NDEBUG */
46785 
46786 #ifdef SQLITE_DEBUG
46787 /*
46788 ** Return a pointer to a human readable string in a static buffer
46789 ** containing the state of the Pager object passed as an argument. This
46790 ** is intended to be used within debuggers. For example, as an alternative
46791 ** to "print *pPager" in gdb:
46792 **
46793 ** (gdb) printf "%s", print_pager_state(pPager)
46794 */
46795 static char *print_pager_state(Pager *p){
46796  static char zRet[1024];
46797 
46798  sqlite3_snprintf(1024, zRet,
46799  "Filename: %s\n"
46800  "State: %s errCode=%d\n"
46801  "Lock: %s\n"
46802  "Locking mode: locking_mode=%s\n"
46803  "Journal mode: journal_mode=%s\n"
46804  "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
46805  "Journal: journalOff=%lld journalHdr=%lld\n"
46806  "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
46807  , p->zFilename
46808  , p->eState==PAGER_OPEN ? "OPEN" :
46809  p->eState==PAGER_READER ? "READER" :
46810  p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
46811  p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
46812  p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
46813  p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
46814  p->eState==PAGER_ERROR ? "ERROR" : "?error?"
46815  , (int)p->errCode
46816  , p->eLock==NO_LOCK ? "NO_LOCK" :
46817  p->eLock==RESERVED_LOCK ? "RESERVED" :
46818  p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
46819  p->eLock==SHARED_LOCK ? "SHARED" :
46820  p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
46821  , p->exclusiveMode ? "exclusive" : "normal"
46822  , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
46823  p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
46824  p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
46825  p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
46826  p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
46827  p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
46828  , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
46829  , p->journalOff, p->journalHdr
46830  , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
46831  );
46832 
46833  return zRet;
46834 }
46835 #endif
46836 
46837 /*
46838 ** Return true if it is necessary to write page *pPg into the sub-journal.
46839 ** A page needs to be written into the sub-journal if there exists one
46840 ** or more open savepoints for which:
46841 **
46842 ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
46843 ** * The bit corresponding to the page-number is not set in
46844 ** PagerSavepoint.pInSavepoint.
46845 */
46846 static int subjRequiresPage(PgHdr *pPg){
46847  Pager *pPager = pPg->pPager;
46848  PagerSavepoint *p;
46849  Pgno pgno = pPg->pgno;
46850  int i;
46851  for(i=0; i<pPager->nSavepoint; i++){
46852  p = &pPager->aSavepoint[i];
46853  if( p->nOrig>=pgno && 0==sqlite3BitvecTestNotNull(p->pInSavepoint, pgno) ){
46854  return 1;
46855  }
46856  }
46857  return 0;
46858 }
46859 
46860 #ifdef SQLITE_DEBUG
46861 /*
46862 ** Return true if the page is already in the journal file.
46863 */
46864 static int pageInJournal(Pager *pPager, PgHdr *pPg){
46865  return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
46866 }
46867 #endif
46868 
46869 /*
46870 ** Read a 32-bit integer from the given file descriptor. Store the integer
46871 ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
46872 ** error code is something goes wrong.
46873 **
46874 ** All values are stored on disk as big-endian.
46875 */
46876 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
46877  unsigned char ac[4];
46878  int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
46879  if( rc==SQLITE_OK ){
46880  *pRes = sqlite3Get4byte(ac);
46881  }
46882  return rc;
46883 }
46884 
46885 /*
46886 ** Write a 32-bit integer into a string buffer in big-endian byte order.
46887 */
46888 #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
46889 
46890 
46891 /*
46892 ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
46893 ** on success or an error code is something goes wrong.
46894 */
46895 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
46896  char ac[4];
46897  put32bits(ac, val);
46898  return sqlite3OsWrite(fd, ac, 4, offset);
46899 }
46900 
46901 /*
46902 ** Unlock the database file to level eLock, which must be either NO_LOCK
46903 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
46904 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
46905 **
46906 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
46907 ** called, do not modify it. See the comment above the #define of
46908 ** UNKNOWN_LOCK for an explanation of this.
46909 */
46910 static int pagerUnlockDb(Pager *pPager, int eLock){
46911  int rc = SQLITE_OK;
46912 
46913  assert( !pPager->exclusiveMode || pPager->eLock==eLock );
46914  assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
46915  assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
46916  if( isOpen(pPager->fd) ){
46917  assert( pPager->eLock>=eLock );
46918  rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
46919  if( pPager->eLock!=UNKNOWN_LOCK ){
46920  pPager->eLock = (u8)eLock;
46921  }
46922  IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
46923  }
46924  return rc;
46925 }
46926 
46927 /*
46928 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
46929 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
46930 ** Pager.eLock variable to the new locking state.
46931 **
46932 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
46933 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
46934 ** See the comment above the #define of UNKNOWN_LOCK for an explanation
46935 ** of this.
46936 */
46937 static int pagerLockDb(Pager *pPager, int eLock){
46938  int rc = SQLITE_OK;
46939 
46940  assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
46941  if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
46942  rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
46943  if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
46944  pPager->eLock = (u8)eLock;
46945  IOTRACE(("LOCK %p %d\n", pPager, eLock))
46946  }
46947  }
46948  return rc;
46949 }
46950 
46951 /*
46952 ** This function determines whether or not the atomic-write optimization
46953 ** can be used with this pager. The optimization can be used if:
46954 **
46955 ** (a) the value returned by OsDeviceCharacteristics() indicates that
46956 ** a database page may be written atomically, and
46957 ** (b) the value returned by OsSectorSize() is less than or equal
46958 ** to the page size.
46959 **
46960 ** The optimization is also always enabled for temporary files. It is
46961 ** an error to call this function if pPager is opened on an in-memory
46962 ** database.
46963 **
46964 ** If the optimization cannot be used, 0 is returned. If it can be used,
46965 ** then the value returned is the size of the journal file when it
46966 ** contains rollback data for exactly one page.
46967 */
46968 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46969 static int jrnlBufferSize(Pager *pPager){
46970  assert( !MEMDB );
46971  if( !pPager->tempFile ){
46972  int dc; /* Device characteristics */
46973  int nSector; /* Sector size */
46974  int szPage; /* Page size */
46975 
46976  assert( isOpen(pPager->fd) );
46977  dc = sqlite3OsDeviceCharacteristics(pPager->fd);
46978  nSector = pPager->sectorSize;
46979  szPage = pPager->pageSize;
46980 
46981  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
46982  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
46983  if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
46984  return 0;
46985  }
46986  }
46987 
46988  return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
46989 }
46990 #else
46991 # define jrnlBufferSize(x) 0
46992 #endif
46993 
46994 /*
46995 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
46996 ** on the cache using a hash function. This is used for testing
46997 ** and debugging only.
46998 */
46999 #ifdef SQLITE_CHECK_PAGES
47000 /*
47001 ** Return a 32-bit hash of the page data for pPage.
47002 */
47003 static u32 pager_datahash(int nByte, unsigned char *pData){
47004  u32 hash = 0;
47005  int i;
47006  for(i=0; i<nByte; i++){
47007  hash = (hash*1039) + pData[i];
47008  }
47009  return hash;
47010 }
47011 static u32 pager_pagehash(PgHdr *pPage){
47012  return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
47013 }
47014 static void pager_set_pagehash(PgHdr *pPage){
47015  pPage->pageHash = pager_pagehash(pPage);
47016 }
47017 
47018 /*
47019 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
47020 ** is defined, and NDEBUG is not defined, an assert() statement checks
47021 ** that the page is either dirty or still matches the calculated page-hash.
47022 */
47023 #define CHECK_PAGE(x) checkPage(x)
47024 static void checkPage(PgHdr *pPg){
47025  Pager *pPager = pPg->pPager;
47026  assert( pPager->eState!=PAGER_ERROR );
47027  assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
47028 }
47029 
47030 #else
47031 #define pager_datahash(X,Y) 0
47032 #define pager_pagehash(X) 0
47033 #define pager_set_pagehash(X)
47034 #define CHECK_PAGE(x)
47035 #endif /* SQLITE_CHECK_PAGES */
47036 
47037 /*
47038 ** When this is called the journal file for pager pPager must be open.
47039 ** This function attempts to read a master journal file name from the
47040 ** end of the file and, if successful, copies it into memory supplied
47041 ** by the caller. See comments above writeMasterJournal() for the format
47042 ** used to store a master journal file name at the end of a journal file.
47043 **
47044 ** zMaster must point to a buffer of at least nMaster bytes allocated by
47045 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
47046 ** enough space to write the master journal name). If the master journal
47047 ** name in the journal is longer than nMaster bytes (including a
47048 ** nul-terminator), then this is handled as if no master journal name
47049 ** were present in the journal.
47050 **
47051 ** If a master journal file name is present at the end of the journal
47052 ** file, then it is copied into the buffer pointed to by zMaster. A
47053 ** nul-terminator byte is appended to the buffer following the master
47054 ** journal file name.
47055 **
47056 ** If it is determined that no master journal file name is present
47057 ** zMaster[0] is set to 0 and SQLITE_OK returned.
47058 **
47059 ** If an error occurs while reading from the journal file, an SQLite
47060 ** error code is returned.
47061 */
47062 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
47063  int rc; /* Return code */
47064  u32 len; /* Length in bytes of master journal name */
47065  i64 szJ; /* Total size in bytes of journal file pJrnl */
47066  u32 cksum; /* MJ checksum value read from journal */
47067  u32 u; /* Unsigned loop counter */
47068  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47069  zMaster[0] = '\0';
47070 
47071  if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
47072  || szJ<16
47073  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
47074  || len>=nMaster
47075  || len==0
47076  || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
47077  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
47078  || memcmp(aMagic, aJournalMagic, 8)
47079  || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
47080  ){
47081  return rc;
47082  }
47083 
47084  /* See if the checksum matches the master journal name */
47085  for(u=0; u<len; u++){
47086  cksum -= zMaster[u];
47087  }
47088  if( cksum ){
47089  /* If the checksum doesn't add up, then one or more of the disk sectors
47090  ** containing the master journal filename is corrupted. This means
47091  ** definitely roll back, so just return SQLITE_OK and report a (nul)
47092  ** master-journal filename.
47093  */
47094  len = 0;
47095  }
47096  zMaster[len] = '\0';
47097 
47098  return SQLITE_OK;
47099 }
47100 
47101 /*
47102 ** Return the offset of the sector boundary at or immediately
47103 ** following the value in pPager->journalOff, assuming a sector
47104 ** size of pPager->sectorSize bytes.
47105 **
47106 ** i.e for a sector size of 512:
47107 **
47108 ** Pager.journalOff Return value
47109 ** ---------------------------------------
47110 ** 0 0
47111 ** 512 512
47112 ** 100 512
47113 ** 2000 2048
47114 **
47115 */
47116 static i64 journalHdrOffset(Pager *pPager){
47117  i64 offset = 0;
47118  i64 c = pPager->journalOff;
47119  if( c ){
47120  offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
47121  }
47122  assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
47123  assert( offset>=c );
47124  assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
47125  return offset;
47126 }
47127 
47128 /*
47129 ** The journal file must be open when this function is called.
47130 **
47131 ** This function is a no-op if the journal file has not been written to
47132 ** within the current transaction (i.e. if Pager.journalOff==0).
47133 **
47134 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
47135 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
47136 ** zero the 28-byte header at the start of the journal file. In either case,
47137 ** if the pager is not in no-sync mode, sync the journal file immediately
47138 ** after writing or truncating it.
47139 **
47140 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
47141 ** following the truncation or zeroing described above the size of the
47142 ** journal file in bytes is larger than this value, then truncate the
47143 ** journal file to Pager.journalSizeLimit bytes. The journal file does
47144 ** not need to be synced following this operation.
47145 **
47146 ** If an IO error occurs, abandon processing and return the IO error code.
47147 ** Otherwise, return SQLITE_OK.
47148 */
47149 static int zeroJournalHdr(Pager *pPager, int doTruncate){
47150  int rc = SQLITE_OK; /* Return code */
47151  assert( isOpen(pPager->jfd) );
47152  assert( !sqlite3JournalIsInMemory(pPager->jfd) );
47153  if( pPager->journalOff ){
47154  const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
47155 
47156  IOTRACE(("JZEROHDR %p\n", pPager))
47157  if( doTruncate || iLimit==0 ){
47158  rc = sqlite3OsTruncate(pPager->jfd, 0);
47159  }else{
47160  static const char zeroHdr[28] = {0};
47161  rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
47162  }
47163  if( rc==SQLITE_OK && !pPager->noSync ){
47164  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
47165  }
47166 
47167  /* At this point the transaction is committed but the write lock
47168  ** is still held on the file. If there is a size limit configured for
47169  ** the persistent journal and the journal file currently consumes more
47170  ** space than that limit allows for, truncate it now. There is no need
47171  ** to sync the file following this operation.
47172  */
47173  if( rc==SQLITE_OK && iLimit>0 ){
47174  i64 sz;
47175  rc = sqlite3OsFileSize(pPager->jfd, &sz);
47176  if( rc==SQLITE_OK && sz>iLimit ){
47177  rc = sqlite3OsTruncate(pPager->jfd, iLimit);
47178  }
47179  }
47180  }
47181  return rc;
47182 }
47183 
47184 /*
47185 ** The journal file must be open when this routine is called. A journal
47186 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
47187 ** current location.
47188 **
47189 ** The format for the journal header is as follows:
47190 ** - 8 bytes: Magic identifying journal format.
47191 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
47192 ** - 4 bytes: Random number used for page hash.
47193 ** - 4 bytes: Initial database page count.
47194 ** - 4 bytes: Sector size used by the process that wrote this journal.
47195 ** - 4 bytes: Database page size.
47196 **
47197 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
47198 */
47199 static int writeJournalHdr(Pager *pPager){
47200  int rc = SQLITE_OK; /* Return code */
47201  char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
47202  u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
47203  u32 nWrite; /* Bytes of header sector written */
47204  int ii; /* Loop counter */
47205 
47206  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47207 
47208  if( nHeader>JOURNAL_HDR_SZ(pPager) ){
47209  nHeader = JOURNAL_HDR_SZ(pPager);
47210  }
47211 
47212  /* If there are active savepoints and any of them were created
47213  ** since the most recent journal header was written, update the
47214  ** PagerSavepoint.iHdrOffset fields now.
47215  */
47216  for(ii=0; ii<pPager->nSavepoint; ii++){
47217  if( pPager->aSavepoint[ii].iHdrOffset==0 ){
47218  pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
47219  }
47220  }
47221 
47222  pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
47223 
47224  /*
47225  ** Write the nRec Field - the number of page records that follow this
47226  ** journal header. Normally, zero is written to this value at this time.
47227  ** After the records are added to the journal (and the journal synced,
47228  ** if in full-sync mode), the zero is overwritten with the true number
47229  ** of records (see syncJournal()).
47230  **
47231  ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
47232  ** reading the journal this value tells SQLite to assume that the
47233  ** rest of the journal file contains valid page records. This assumption
47234  ** is dangerous, as if a failure occurred whilst writing to the journal
47235  ** file it may contain some garbage data. There are two scenarios
47236  ** where this risk can be ignored:
47237  **
47238  ** * When the pager is in no-sync mode. Corruption can follow a
47239  ** power failure in this case anyway.
47240  **
47241  ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
47242  ** that garbage data is never appended to the journal file.
47243  */
47244  assert( isOpen(pPager->fd) || pPager->noSync );
47245  if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
47247  ){
47248  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
47249  put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
47250  }else{
47251  memset(zHeader, 0, sizeof(aJournalMagic)+4);
47252  }
47253 
47254  /* The random check-hash initializer */
47255  sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
47256  put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
47257  /* The initial database size */
47258  put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
47259  /* The assumed sector size for this process */
47260  put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
47261 
47262  /* The page size */
47263  put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
47264 
47265  /* Initializing the tail of the buffer is not necessary. Everything
47266  ** works find if the following memset() is omitted. But initializing
47267  ** the memory prevents valgrind from complaining, so we are willing to
47268  ** take the performance hit.
47269  */
47270  memset(&zHeader[sizeof(aJournalMagic)+20], 0,
47271  nHeader-(sizeof(aJournalMagic)+20));
47272 
47273  /* In theory, it is only necessary to write the 28 bytes that the
47274  ** journal header consumes to the journal file here. Then increment the
47275  ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
47276  ** record is written to the following sector (leaving a gap in the file
47277  ** that will be implicitly filled in by the OS).
47278  **
47279  ** However it has been discovered that on some systems this pattern can
47280  ** be significantly slower than contiguously writing data to the file,
47281  ** even if that means explicitly writing data to the block of
47282  ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
47283  ** is done.
47284  **
47285  ** The loop is required here in case the sector-size is larger than the
47286  ** database page size. Since the zHeader buffer is only Pager.pageSize
47287  ** bytes in size, more than one call to sqlite3OsWrite() may be required
47288  ** to populate the entire journal header sector.
47289  */
47290  for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
47291  IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
47292  rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
47293  assert( pPager->journalHdr <= pPager->journalOff );
47294  pPager->journalOff += nHeader;
47295  }
47296 
47297  return rc;
47298 }
47299 
47300 /*
47301 ** The journal file must be open when this is called. A journal header file
47302 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
47303 ** file. The current location in the journal file is given by
47304 ** pPager->journalOff. See comments above function writeJournalHdr() for
47305 ** a description of the journal header format.
47306 **
47307 ** If the header is read successfully, *pNRec is set to the number of
47308 ** page records following this header and *pDbSize is set to the size of the
47309 ** database before the transaction began, in pages. Also, pPager->cksumInit
47310 ** is set to the value read from the journal header. SQLITE_OK is returned
47311 ** in this case.
47312 **
47313 ** If the journal header file appears to be corrupted, SQLITE_DONE is
47314 ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
47315 ** cannot be read from the journal file an error code is returned.
47316 */
47317 static int readJournalHdr(
47318  Pager *pPager, /* Pager object */
47319  int isHot,
47320  i64 journalSize, /* Size of the open journal file in bytes */
47321  u32 *pNRec, /* OUT: Value read from the nRec field */
47322  u32 *pDbSize /* OUT: Value of original database size field */
47323 ){
47324  int rc; /* Return code */
47325  unsigned char aMagic[8]; /* A buffer to hold the magic header */
47326  i64 iHdrOff; /* Offset of journal header being read */
47327 
47328  assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
47329 
47330  /* Advance Pager.journalOff to the start of the next sector. If the
47331  ** journal file is too small for there to be a header stored at this
47332  ** point, return SQLITE_DONE.
47333  */
47334  pPager->journalOff = journalHdrOffset(pPager);
47335  if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
47336  return SQLITE_DONE;
47337  }
47338  iHdrOff = pPager->journalOff;
47339 
47340  /* Read in the first 8 bytes of the journal header. If they do not match
47341  ** the magic string found at the start of each journal header, return
47342  ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
47343  ** proceed.
47344  */
47345  if( isHot || iHdrOff!=pPager->journalHdr ){
47346  rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
47347  if( rc ){
47348  return rc;
47349  }
47350  if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
47351  return SQLITE_DONE;
47352  }
47353  }
47354 
47355  /* Read the first three 32-bit fields of the journal header: The nRec
47356  ** field, the checksum-initializer and the database size at the start
47357  ** of the transaction. Return an error code if anything goes wrong.
47358  */
47359  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
47360  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
47361  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
47362  ){
47363  return rc;
47364  }
47365 
47366  if( pPager->journalOff==0 ){
47367  u32 iPageSize; /* Page-size field of journal header */
47368  u32 iSectorSize; /* Sector-size field of journal header */
47369 
47370  /* Read the page-size and sector-size journal header fields. */
47371  if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
47372  || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
47373  ){
47374  return rc;
47375  }
47376 
47377  /* Versions of SQLite prior to 3.5.8 set the page-size field of the
47378  ** journal header to zero. In this case, assume that the Pager.pageSize
47379  ** variable is already set to the correct page size.
47380  */
47381  if( iPageSize==0 ){
47382  iPageSize = pPager->pageSize;
47383  }
47384 
47385  /* Check that the values read from the page-size and sector-size fields
47386  ** are within range. To be 'in range', both values need to be a power
47387  ** of two greater than or equal to 512 or 32, and not greater than their
47388  ** respective compile time maximum limits.
47389  */
47390  if( iPageSize<512 || iSectorSize<32
47391  || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
47392  || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
47393  ){
47394  /* If the either the page-size or sector-size in the journal-header is
47395  ** invalid, then the process that wrote the journal-header must have
47396  ** crashed before the header was synced. In this case stop reading
47397  ** the journal file here.
47398  */
47399  return SQLITE_DONE;
47400  }
47401 
47402  /* Update the page-size to match the value read from the journal.
47403  ** Use a testcase() macro to make sure that malloc failure within
47404  ** PagerSetPagesize() is tested.
47405  */
47406  rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
47407  testcase( rc!=SQLITE_OK );
47408 
47409  /* Update the assumed sector-size to match the value used by
47410  ** the process that created this journal. If this journal was
47411  ** created by a process other than this one, then this routine
47412  ** is being called from within pager_playback(). The local value
47413  ** of Pager.sectorSize is restored at the end of that routine.
47414  */
47415  pPager->sectorSize = iSectorSize;
47416  }
47417 
47418  pPager->journalOff += JOURNAL_HDR_SZ(pPager);
47419  return rc;
47420 }
47421 
47422 
47423 /*
47424 ** Write the supplied master journal name into the journal file for pager
47425 ** pPager at the current location. The master journal name must be the last
47426 ** thing written to a journal file. If the pager is in full-sync mode, the
47427 ** journal file descriptor is advanced to the next sector boundary before
47428 ** anything is written. The format is:
47429 **
47430 ** + 4 bytes: PAGER_MJ_PGNO.
47431 ** + N bytes: Master journal filename in utf-8.
47432 ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
47433 ** + 4 bytes: Master journal name checksum.
47434 ** + 8 bytes: aJournalMagic[].
47435 **
47436 ** The master journal page checksum is the sum of the bytes in the master
47437 ** journal name, where each byte is interpreted as a signed 8-bit integer.
47438 **
47439 ** If zMaster is a NULL pointer (occurs for a single database transaction),
47440 ** this call is a no-op.
47441 */
47442 static int writeMasterJournal(Pager *pPager, const char *zMaster){
47443  int rc; /* Return code */
47444  int nMaster; /* Length of string zMaster */
47445  i64 iHdrOff; /* Offset of header in journal file */
47446  i64 jrnlSize; /* Size of journal file on disk */
47447  u32 cksum = 0; /* Checksum of string zMaster */
47448 
47449  assert( pPager->setMaster==0 );
47450  assert( !pagerUseWal(pPager) );
47451 
47452  if( !zMaster
47454  || !isOpen(pPager->jfd)
47455  ){
47456  return SQLITE_OK;
47457  }
47458  pPager->setMaster = 1;
47459  assert( pPager->journalHdr <= pPager->journalOff );
47460 
47461  /* Calculate the length in bytes and the checksum of zMaster */
47462  for(nMaster=0; zMaster[nMaster]; nMaster++){
47463  cksum += zMaster[nMaster];
47464  }
47465 
47466  /* If in full-sync mode, advance to the next disk sector before writing
47467  ** the master journal name. This is in case the previous page written to
47468  ** the journal has already been synced.
47469  */
47470  if( pPager->fullSync ){
47471  pPager->journalOff = journalHdrOffset(pPager);
47472  }
47473  iHdrOff = pPager->journalOff;
47474 
47475  /* Write the master journal data to the end of the journal file. If
47476  ** an error occurs, return the error code to the caller.
47477  */
47478  if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
47479  || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
47480  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
47481  || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
47482  || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8,
47483  iHdrOff+4+nMaster+8)))
47484  ){
47485  return rc;
47486  }
47487  pPager->journalOff += (nMaster+20);
47488 
47489  /* If the pager is in peristent-journal mode, then the physical
47490  ** journal-file may extend past the end of the master-journal name
47491  ** and 8 bytes of magic data just written to the file. This is
47492  ** dangerous because the code to rollback a hot-journal file
47493  ** will not be able to find the master-journal name to determine
47494  ** whether or not the journal is hot.
47495  **
47496  ** Easiest thing to do in this scenario is to truncate the journal
47497  ** file to the required size.
47498  */
47499  if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
47500  && jrnlSize>pPager->journalOff
47501  ){
47502  rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
47503  }
47504  return rc;
47505 }
47506 
47507 /*
47508 ** Discard the entire contents of the in-memory page-cache.
47509 */
47510 static void pager_reset(Pager *pPager){
47511  pPager->iDataVersion++;
47512  sqlite3BackupRestart(pPager->pBackup);
47513  sqlite3PcacheClear(pPager->pPCache);
47514 }
47515 
47516 /*
47517 ** Return the pPager->iDataVersion value
47518 */
47520  assert( pPager->eState>PAGER_OPEN );
47521  return pPager->iDataVersion;
47522 }
47523 
47524 /*
47525 ** Free all structures in the Pager.aSavepoint[] array and set both
47526 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
47527 ** if it is open and the pager is not in exclusive mode.
47528 */
47529 static void releaseAllSavepoints(Pager *pPager){
47530  int ii; /* Iterator for looping through Pager.aSavepoint */
47531  for(ii=0; ii<pPager->nSavepoint; ii++){
47533  }
47534  if( !pPager->exclusiveMode || sqlite3JournalIsInMemory(pPager->sjfd) ){
47535  sqlite3OsClose(pPager->sjfd);
47536  }
47537  sqlite3_free(pPager->aSavepoint);
47538  pPager->aSavepoint = 0;
47539  pPager->nSavepoint = 0;
47540  pPager->nSubRec = 0;
47541 }
47542 
47543 /*
47544 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
47545 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
47546 ** or SQLITE_NOMEM if a malloc failure occurs.
47547 */
47548 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
47549  int ii; /* Loop counter */
47550  int rc = SQLITE_OK; /* Result code */
47551 
47552  for(ii=0; ii<pPager->nSavepoint; ii++){
47553  PagerSavepoint *p = &pPager->aSavepoint[ii];
47554  if( pgno<=p->nOrig ){
47555  rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
47556  testcase( rc==SQLITE_NOMEM );
47557  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
47558  }
47559  }
47560  return rc;
47561 }
47562 
47563 /*
47564 ** This function is a no-op if the pager is in exclusive mode and not
47565 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
47566 ** state.
47567 **
47568 ** If the pager is not in exclusive-access mode, the database file is
47569 ** completely unlocked. If the file is unlocked and the file-system does
47570 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
47571 ** closed (if it is open).
47572 **
47573 ** If the pager is in ERROR state when this function is called, the
47574 ** contents of the pager cache are discarded before switching back to
47575 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
47576 ** or not, any journal file left in the file-system will be treated
47577 ** as a hot-journal and rolled back the next time a read-transaction
47578 ** is opened (by this or by any other connection).
47579 */
47580 static void pager_unlock(Pager *pPager){
47581 
47582  assert( pPager->eState==PAGER_READER
47583  || pPager->eState==PAGER_OPEN
47584  || pPager->eState==PAGER_ERROR
47585  );
47586 
47588  pPager->pInJournal = 0;
47589  releaseAllSavepoints(pPager);
47590 
47591  if( pagerUseWal(pPager) ){
47592  assert( !isOpen(pPager->jfd) );
47594  pPager->eState = PAGER_OPEN;
47595  }else if( !pPager->exclusiveMode ){
47596  int rc; /* Error code returned by pagerUnlockDb() */
47597  int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
47598 
47599  /* If the operating system support deletion of open files, then
47600  ** close the journal file when dropping the database lock. Otherwise
47601  ** another connection with journal_mode=delete might delete the file
47602  ** out from under us.
47603  */
47604  assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
47605  assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
47606  assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
47607  assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
47608  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
47609  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
47610  if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
47611  || 1!=(pPager->journalMode & 5)
47612  ){
47613  sqlite3OsClose(pPager->jfd);
47614  }
47615 
47616  /* If the pager is in the ERROR state and the call to unlock the database
47617  ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
47618  ** above the #define for UNKNOWN_LOCK for an explanation of why this
47619  ** is necessary.
47620  */
47621  rc = pagerUnlockDb(pPager, NO_LOCK);
47622  if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
47623  pPager->eLock = UNKNOWN_LOCK;
47624  }
47625 
47626  /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
47627  ** without clearing the error code. This is intentional - the error
47628  ** code is cleared and the cache reset in the block below.
47629  */
47630  assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
47631  pPager->changeCountDone = 0;
47632  pPager->eState = PAGER_OPEN;
47633  }
47634 
47635  /* If Pager.errCode is set, the contents of the pager cache cannot be
47636  ** trusted. Now that there are no outstanding references to the pager,
47637  ** it can safely move back to PAGER_OPEN state. This happens in both
47638  ** normal and exclusive-locking mode.
47639  */
47640  assert( pPager->errCode==SQLITE_OK || !MEMDB );
47641  if( pPager->errCode ){
47642  if( pPager->tempFile==0 ){
47643  pager_reset(pPager);
47644  pPager->changeCountDone = 0;
47645  pPager->eState = PAGER_OPEN;
47646  }else{
47647  pPager->eState = (isOpen(pPager->jfd) ? PAGER_OPEN : PAGER_READER);
47648  }
47649  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
47650  pPager->errCode = SQLITE_OK;
47651  }
47652 
47653  pPager->journalOff = 0;
47654  pPager->journalHdr = 0;
47655  pPager->setMaster = 0;
47656 }
47657 
47658 /*
47659 ** This function is called whenever an IOERR or FULL error that requires
47660 ** the pager to transition into the ERROR state may ahve occurred.
47661 ** The first argument is a pointer to the pager structure, the second
47662 ** the error-code about to be returned by a pager API function. The
47663 ** value returned is a copy of the second argument to this function.
47664 **
47665 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
47666 ** IOERR sub-codes, the pager enters the ERROR state and the error code
47667 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
47668 ** all major API calls on the Pager will immediately return Pager.errCode.
47669 **
47670 ** The ERROR state indicates that the contents of the pager-cache
47671 ** cannot be trusted. This state can be cleared by completely discarding
47672 ** the contents of the pager-cache. If a transaction was active when
47673 ** the persistent error occurred, then the rollback journal may need
47674 ** to be replayed to restore the contents of the database file (as if
47675 ** it were a hot-journal).
47676 */
47677 static int pager_error(Pager *pPager, int rc){
47678  int rc2 = rc & 0xff;
47679  assert( rc==SQLITE_OK || !MEMDB );
47680  assert(
47681  pPager->errCode==SQLITE_FULL ||
47682  pPager->errCode==SQLITE_OK ||
47683  (pPager->errCode & 0xff)==SQLITE_IOERR
47684  );
47685  if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
47686  pPager->errCode = rc;
47687  pPager->eState = PAGER_ERROR;
47688  }
47689  return rc;
47690 }
47691 
47692 static int pager_truncate(Pager *pPager, Pgno nPage);
47693 
47694 /*
47695 ** The write transaction open on pPager is being committed (bCommit==1)
47696 ** or rolled back (bCommit==0).
47697 **
47698 ** Return TRUE if and only if all dirty pages should be flushed to disk.
47699 **
47700 ** Rules:
47701 **
47702 ** * For non-TEMP databases, always sync to disk. This is necessary
47703 ** for transactions to be durable.
47704 **
47705 ** * Sync TEMP database only on a COMMIT (not a ROLLBACK) when the backing
47706 ** file has been created already (via a spill on pagerStress()) and
47707 ** when the number of dirty pages in memory exceeds 25% of the total
47708 ** cache size.
47709 */
47710 static int pagerFlushOnCommit(Pager *pPager, int bCommit){
47711  if( pPager->tempFile==0 ) return 1;
47712  if( !bCommit ) return 0;
47713  if( !isOpen(pPager->fd) ) return 0;
47714  return (sqlite3PCachePercentDirty(pPager->pPCache)>=25);
47715 }
47716 
47717 /*
47718 ** This routine ends a transaction. A transaction is usually ended by
47719 ** either a COMMIT or a ROLLBACK operation. This routine may be called
47720 ** after rollback of a hot-journal, or if an error occurs while opening
47721 ** the journal file or writing the very first journal-header of a
47722 ** database transaction.
47723 **
47724 ** This routine is never called in PAGER_ERROR state. If it is called
47725 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
47726 ** exclusive than a RESERVED lock, it is a no-op.
47727 **
47728 ** Otherwise, any active savepoints are released.
47729 **
47730 ** If the journal file is open, then it is "finalized". Once a journal
47731 ** file has been finalized it is not possible to use it to roll back a
47732 ** transaction. Nor will it be considered to be a hot-journal by this
47733 ** or any other database connection. Exactly how a journal is finalized
47734 ** depends on whether or not the pager is running in exclusive mode and
47735 ** the current journal-mode (Pager.journalMode value), as follows:
47736 **
47737 ** journalMode==MEMORY
47738 ** Journal file descriptor is simply closed. This destroys an
47739 ** in-memory journal.
47740 **
47741 ** journalMode==TRUNCATE
47742 ** Journal file is truncated to zero bytes in size.
47743 **
47744 ** journalMode==PERSIST
47745 ** The first 28 bytes of the journal file are zeroed. This invalidates
47746 ** the first journal header in the file, and hence the entire journal
47747 ** file. An invalid journal file cannot be rolled back.
47748 **
47749 ** journalMode==DELETE
47750 ** The journal file is closed and deleted using sqlite3OsDelete().
47751 **
47752 ** If the pager is running in exclusive mode, this method of finalizing
47753 ** the journal file is never used. Instead, if the journalMode is
47754 ** DELETE and the pager is in exclusive mode, the method described under
47755 ** journalMode==PERSIST is used instead.
47756 **
47757 ** After the journal is finalized, the pager moves to PAGER_READER state.
47758 ** If running in non-exclusive rollback mode, the lock on the file is
47759 ** downgraded to a SHARED_LOCK.
47760 **
47761 ** SQLITE_OK is returned if no error occurs. If an error occurs during
47762 ** any of the IO operations to finalize the journal file or unlock the
47763 ** database then the IO error code is returned to the user. If the
47764 ** operation to finalize the journal file fails, then the code still
47765 ** tries to unlock the database file if not in exclusive mode. If the
47766 ** unlock operation fails as well, then the first error code related
47767 ** to the first error encountered (the journal finalization one) is
47768 ** returned.
47769 */
47770 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
47771  int rc = SQLITE_OK; /* Error code from journal finalization operation */
47772  int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
47773 
47774  /* Do nothing if the pager does not have an open write transaction
47775  ** or at least a RESERVED lock. This function may be called when there
47776  ** is no write-transaction active but a RESERVED or greater lock is
47777  ** held under two circumstances:
47778  **
47779  ** 1. After a successful hot-journal rollback, it is called with
47780  ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
47781  **
47782  ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
47783  ** lock switches back to locking_mode=normal and then executes a
47784  ** read-transaction, this function is called with eState==PAGER_READER
47785  ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
47786  */
47787  assert( assert_pager_state(pPager) );
47788  assert( pPager->eState!=PAGER_ERROR );
47789  if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
47790  return SQLITE_OK;
47791  }
47792 
47793  releaseAllSavepoints(pPager);
47794  assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
47795  if( isOpen(pPager->jfd) ){
47796  assert( !pagerUseWal(pPager) );
47797 
47798  /* Finalize the journal file. */
47799  if( sqlite3JournalIsInMemory(pPager->jfd) ){
47800  /* assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ); */
47801  sqlite3OsClose(pPager->jfd);
47802  }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
47803  if( pPager->journalOff==0 ){
47804  rc = SQLITE_OK;
47805  }else{
47806  rc = sqlite3OsTruncate(pPager->jfd, 0);
47807  if( rc==SQLITE_OK && pPager->fullSync ){
47808  /* Make sure the new file size is written into the inode right away.
47809  ** Otherwise the journal might resurrect following a power loss and
47810  ** cause the last transaction to roll back. See
47811  ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
47812  */
47813  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
47814  }
47815  }
47816  pPager->journalOff = 0;
47817  }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47818  || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
47819  ){
47820  rc = zeroJournalHdr(pPager, hasMaster||pPager->tempFile);
47821  pPager->journalOff = 0;
47822  }else{
47823  /* This branch may be executed with Pager.journalMode==MEMORY if
47824  ** a hot-journal was just rolled back. In this case the journal
47825  ** file should be closed and deleted. If this connection writes to
47826  ** the database file, it will do so using an in-memory journal.
47827  */
47828  int bDelete = !pPager->tempFile;
47829  assert( sqlite3JournalIsInMemory(pPager->jfd)==0 );
47832  || pPager->journalMode==PAGER_JOURNALMODE_WAL
47833  );
47834  sqlite3OsClose(pPager->jfd);
47835  if( bDelete ){
47836  rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, pPager->extraSync);
47837  }
47838  }
47839  }
47840 
47841 #ifdef SQLITE_CHECK_PAGES
47842  sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
47843  if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
47844  PgHdr *p = sqlite3PagerLookup(pPager, 1);
47845  if( p ){
47846  p->pageHash = 0;
47848  }
47849  }
47850 #endif
47851 
47853  pPager->pInJournal = 0;
47854  pPager->nRec = 0;
47855  if( rc==SQLITE_OK ){
47856  if( pagerFlushOnCommit(pPager, bCommit) ){
47857  sqlite3PcacheCleanAll(pPager->pPCache);
47858  }else{
47860  }
47861  sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
47862  }
47863 
47864  if( pagerUseWal(pPager) ){
47865  /* Drop the WAL write-lock, if any. Also, if the connection was in
47866  ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
47867  ** lock held on the database file.
47868  */
47869  rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
47870  assert( rc2==SQLITE_OK );
47871  }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
47872  /* This branch is taken when committing a transaction in rollback-journal
47873  ** mode if the database file on disk is larger than the database image.
47874  ** At this point the journal has been finalized and the transaction
47875  ** successfully committed, but the EXCLUSIVE lock is still held on the
47876  ** file. So it is safe to truncate the database file to its minimum
47877  ** required size. */
47878  assert( pPager->eLock==EXCLUSIVE_LOCK );
47879  rc = pager_truncate(pPager, pPager->dbSize);
47880  }
47881 
47882  if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
47884  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
47885  }
47886 
47887  if( !pPager->exclusiveMode
47888  && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
47889  ){
47890  rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
47891  pPager->changeCountDone = 0;
47892  }
47893  pPager->eState = PAGER_READER;
47894  pPager->setMaster = 0;
47895 
47896  return (rc==SQLITE_OK?rc2:rc);
47897 }
47898 
47899 /*
47900 ** Execute a rollback if a transaction is active and unlock the
47901 ** database file.
47902 **
47903 ** If the pager has already entered the ERROR state, do not attempt
47904 ** the rollback at this time. Instead, pager_unlock() is called. The
47905 ** call to pager_unlock() will discard all in-memory pages, unlock
47906 ** the database file and move the pager back to OPEN state. If this
47907 ** means that there is a hot-journal left in the file-system, the next
47908 ** connection to obtain a shared lock on the pager (which may be this one)
47909 ** will roll it back.
47910 **
47911 ** If the pager has not already entered the ERROR state, but an IO or
47912 ** malloc error occurs during a rollback, then this will itself cause
47913 ** the pager to enter the ERROR state. Which will be cleared by the
47914 ** call to pager_unlock(), as described above.
47915 */
47916 static void pagerUnlockAndRollback(Pager *pPager){
47917  if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
47918  assert( assert_pager_state(pPager) );
47919  if( pPager->eState>=PAGER_WRITER_LOCKED ){
47921  sqlite3PagerRollback(pPager);
47923  }else if( !pPager->exclusiveMode ){
47924  assert( pPager->eState==PAGER_READER );
47925  pager_end_transaction(pPager, 0, 0);
47926  }
47927  }
47928  pager_unlock(pPager);
47929 }
47930 
47931 /*
47932 ** Parameter aData must point to a buffer of pPager->pageSize bytes
47933 ** of data. Compute and return a checksum based ont the contents of the
47934 ** page of data and the current value of pPager->cksumInit.
47935 **
47936 ** This is not a real checksum. It is really just the sum of the
47937 ** random initial value (pPager->cksumInit) and every 200th byte
47938 ** of the page data, starting with byte offset (pPager->pageSize%200).
47939 ** Each byte is interpreted as an 8-bit unsigned integer.
47940 **
47941 ** Changing the formula used to compute this checksum results in an
47942 ** incompatible journal file format.
47943 **
47944 ** If journal corruption occurs due to a power failure, the most likely
47945 ** scenario is that one end or the other of the record will be changed.
47946 ** It is much less likely that the two ends of the journal record will be
47947 ** correct and the middle be corrupt. Thus, this "checksum" scheme,
47948 ** though fast and simple, catches the mostly likely kind of corruption.
47949 */
47950 static u32 pager_cksum(Pager *pPager, const u8 *aData){
47951  u32 cksum = pPager->cksumInit; /* Checksum value to return */
47952  int i = pPager->pageSize-200; /* Loop counter */
47953  while( i>0 ){
47954  cksum += aData[i];
47955  i -= 200;
47956  }
47957  return cksum;
47958 }
47959 
47960 /*
47961 ** Report the current page size and number of reserved bytes back
47962 ** to the codec.
47963 */
47964 #ifdef SQLITE_HAS_CODEC
47965 static void pagerReportSize(Pager *pPager){
47966  if( pPager->xCodecSizeChng ){
47967  pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
47968  (int)pPager->nReserve);
47969  }
47970 }
47971 #else
47972 # define pagerReportSize(X) /* No-op if we do not support a codec */
47973 #endif
47974 
47975 #ifdef SQLITE_HAS_CODEC
47976 /*
47977 ** Make sure the number of reserved bits is the same in the destination
47978 ** pager as it is in the source. This comes up when a VACUUM changes the
47979 ** number of reserved bits to the "optimal" amount.
47980 */
47981 SQLITE_PRIVATE void sqlite3PagerAlignReserve(Pager *pDest, Pager *pSrc){
47982  if( pDest->nReserve!=pSrc->nReserve ){
47983  pDest->nReserve = pSrc->nReserve;
47984  pagerReportSize(pDest);
47985  }
47986 }
47987 #endif
47988 
47989 /*
47990 ** Read a single page from either the journal file (if isMainJrnl==1) or
47991 ** from the sub-journal (if isMainJrnl==0) and playback that page.
47992 ** The page begins at offset *pOffset into the file. The *pOffset
47993 ** value is increased to the start of the next page in the journal.
47994 **
47995 ** The main rollback journal uses checksums - the statement journal does
47996 ** not.
47997 **
47998 ** If the page number of the page record read from the (sub-)journal file
47999 ** is greater than the current value of Pager.dbSize, then playback is
48000 ** skipped and SQLITE_OK is returned.
48001 **
48002 ** If pDone is not NULL, then it is a record of pages that have already
48003 ** been played back. If the page at *pOffset has already been played back
48004 ** (if the corresponding pDone bit is set) then skip the playback.
48005 ** Make sure the pDone bit corresponding to the *pOffset page is set
48006 ** prior to returning.
48007 **
48008 ** If the page record is successfully read from the (sub-)journal file
48009 ** and played back, then SQLITE_OK is returned. If an IO error occurs
48010 ** while reading the record from the (sub-)journal file or while writing
48011 ** to the database file, then the IO error code is returned. If data
48012 ** is successfully read from the (sub-)journal file but appears to be
48013 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
48014 ** two circumstances:
48015 **
48016 ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
48017 ** * If the record is being rolled back from the main journal file
48018 ** and the checksum field does not match the record content.
48019 **
48020 ** Neither of these two scenarios are possible during a savepoint rollback.
48021 **
48022 ** If this is a savepoint rollback, then memory may have to be dynamically
48023 ** allocated by this function. If this is the case and an allocation fails,
48024 ** SQLITE_NOMEM is returned.
48025 */
48027  Pager *pPager, /* The pager being played back */
48028  i64 *pOffset, /* Offset of record to playback */
48029  Bitvec *pDone, /* Bitvec of pages already played back */
48030  int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
48031  int isSavepnt /* True for a savepoint rollback */
48032 ){
48033  int rc;
48034  PgHdr *pPg; /* An existing page in the cache */
48035  Pgno pgno; /* The page number of a page in journal */
48036  u32 cksum; /* Checksum used for sanity checking */
48037  char *aData; /* Temporary storage for the page */
48038  sqlite3_file *jfd; /* The file descriptor for the journal file */
48039  int isSynced; /* True if journal page is synced */
48040 
48041  assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
48042  assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
48043  assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
48044  assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
48045 
48046  aData = pPager->pTmpSpace;
48047  assert( aData ); /* Temp storage must have already been allocated */
48048  assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
48049 
48050  /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
48051  ** or savepoint rollback done at the request of the caller) or this is
48052  ** a hot-journal rollback. If it is a hot-journal rollback, the pager
48053  ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
48054  ** only reads from the main journal, not the sub-journal.
48055  */
48057  || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
48058  );
48059  assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
48060 
48061  /* Read the page number and page data from the journal or sub-journal
48062  ** file. Return an error code to the caller if an IO error occurs.
48063  */
48064  jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
48065  rc = read32bits(jfd, *pOffset, &pgno);
48066  if( rc!=SQLITE_OK ) return rc;
48067  rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
48068  if( rc!=SQLITE_OK ) return rc;
48069  *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
48070 
48071  /* Sanity checking on the page. This is more important that I originally
48072  ** thought. If a power failure occurs while the journal is being written,
48073  ** it could cause invalid data to be written into the journal. We need to
48074  ** detect this invalid data (with high probability) and ignore it.
48075  */
48076  if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
48077  assert( !isSavepnt );
48078  return SQLITE_DONE;
48079  }
48080  if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
48081  return SQLITE_OK;
48082  }
48083  if( isMainJrnl ){
48084  rc = read32bits(jfd, (*pOffset)-4, &cksum);
48085  if( rc ) return rc;
48086  if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
48087  return SQLITE_DONE;
48088  }
48089  }
48090 
48091  /* If this page has already been played back before during the current
48092  ** rollback, then don't bother to play it back again.
48093  */
48094  if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
48095  return rc;
48096  }
48097 
48098  /* When playing back page 1, restore the nReserve setting
48099  */
48100  if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
48101  pPager->nReserve = ((u8*)aData)[20];
48102  pagerReportSize(pPager);
48103  }
48104 
48105  /* If the pager is in CACHEMOD state, then there must be a copy of this
48106  ** page in the pager cache. In this case just update the pager cache,
48107  ** not the database file. The page is left marked dirty in this case.
48108  **
48109  ** An exception to the above rule: If the database is in no-sync mode
48110  ** and a page is moved during an incremental vacuum then the page may
48111  ** not be in the pager cache. Later: if a malloc() or IO error occurs
48112  ** during a Movepage() call, then the page may not be in the cache
48113  ** either. So the condition described in the above paragraph is not
48114  ** assert()able.
48115  **
48116  ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
48117  ** pager cache if it exists and the main file. The page is then marked
48118  ** not dirty. Since this code is only executed in PAGER_OPEN state for
48119  ** a hot-journal rollback, it is guaranteed that the page-cache is empty
48120  ** if the pager is in OPEN state.
48121  **
48122  ** Ticket #1171: The statement journal might contain page content that is
48123  ** different from the page content at the start of the transaction.
48124  ** This occurs when a page is changed prior to the start of a statement
48125  ** then changed again within the statement. When rolling back such a
48126  ** statement we must not write to the original database unless we know
48127  ** for certain that original page contents are synced into the main rollback
48128  ** journal. Otherwise, a power loss might leave modified data in the
48129  ** database file without an entry in the rollback journal that can
48130  ** restore the database to its original form. Two conditions must be
48131  ** met before writing to the database files. (1) the database must be
48132  ** locked. (2) we know that the original page content is fully synced
48133  ** in the main journal either because the page is not in cache or else
48134  ** the page is marked as needSync==0.
48135  **
48136  ** 2008-04-14: When attempting to vacuum a corrupt database file, it
48137  ** is possible to fail a statement on a database that does not yet exist.
48138  ** Do not attempt to write if database file has never been opened.
48139  */
48140  if( pagerUseWal(pPager) ){
48141  pPg = 0;
48142  }else{
48143  pPg = sqlite3PagerLookup(pPager, pgno);
48144  }
48145  assert( pPg || !MEMDB );
48146  assert( pPager->eState!=PAGER_OPEN || pPg==0 || pPager->tempFile );
48147  PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
48148  PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
48149  (isMainJrnl?"main-journal":"sub-journal")
48150  ));
48151  if( isMainJrnl ){
48152  isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
48153  }else{
48154  isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
48155  }
48156  if( isOpen(pPager->fd)
48157  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48158  && isSynced
48159  ){
48160  i64 ofst = (pgno-1)*(i64)pPager->pageSize;
48161  testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
48162  assert( !pagerUseWal(pPager) );
48163  rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
48164  if( pgno>pPager->dbFileSize ){
48165  pPager->dbFileSize = pgno;
48166  }
48167  if( pPager->pBackup ){
48168  CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM_BKPT);
48169  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
48170  CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM_BKPT, aData);
48171  }
48172  }else if( !isMainJrnl && pPg==0 ){
48173  /* If this is a rollback of a savepoint and data was not written to
48174  ** the database and the page is not in-memory, there is a potential
48175  ** problem. When the page is next fetched by the b-tree layer, it
48176  ** will be read from the database file, which may or may not be
48177  ** current.
48178  **
48179  ** There are a couple of different ways this can happen. All are quite
48180  ** obscure. When running in synchronous mode, this can only happen
48181  ** if the page is on the free-list at the start of the transaction, then
48182  ** populated, then moved using sqlite3PagerMovepage().
48183  **
48184  ** The solution is to add an in-memory page to the cache containing
48185  ** the data just read from the sub-journal. Mark the page as dirty
48186  ** and if the pager requires a journal-sync, then mark the page as
48187  ** requiring a journal-sync before it is written.
48188  */
48189  assert( isSavepnt );
48190  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
48191  pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
48192  rc = sqlite3PagerGet(pPager, pgno, &pPg, 1);
48193  assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
48194  pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
48195  if( rc!=SQLITE_OK ) return rc;
48197  }
48198  if( pPg ){
48199  /* No page should ever be explicitly rolled back that is in use, except
48200  ** for page 1 which is held in use in order to keep the lock on the
48201  ** database active. However such a page may be rolled back as a result
48202  ** of an internal error resulting in an automatic call to
48203  ** sqlite3PagerRollback().
48204  */
48205  void *pData;
48206  pData = pPg->pData;
48207  memcpy(pData, (u8*)aData, pPager->pageSize);
48208  pPager->xReiniter(pPg);
48209  /* It used to be that sqlite3PcacheMakeClean(pPg) was called here. But
48210  ** that call was dangerous and had no detectable benefit since the cache
48211  ** is normally cleaned by sqlite3PcacheCleanAll() after rollback and so
48212  ** has been removed. */
48213  pager_set_pagehash(pPg);
48214 
48215  /* If this was page 1, then restore the value of Pager.dbFileVers.
48216  ** Do this before any decoding. */
48217  if( pgno==1 ){
48218  memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
48219  }
48220 
48221  /* Decode the page just read from disk */
48222  CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM_BKPT);
48223  sqlite3PcacheRelease(pPg);
48224  }
48225  return rc;
48226 }
48227 
48228 /*
48229 ** Parameter zMaster is the name of a master journal file. A single journal
48230 ** file that referred to the master journal file has just been rolled back.
48231 ** This routine checks if it is possible to delete the master journal file,
48232 ** and does so if it is.
48233 **
48234 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
48235 ** available for use within this function.
48236 **
48237 ** When a master journal file is created, it is populated with the names
48238 ** of all of its child journals, one after another, formatted as utf-8
48239 ** encoded text. The end of each child journal file is marked with a
48240 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
48241 ** file for a transaction involving two databases might be:
48242 **
48243 ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
48244 **
48245 ** A master journal file may only be deleted once all of its child
48246 ** journals have been rolled back.
48247 **
48248 ** This function reads the contents of the master-journal file into
48249 ** memory and loops through each of the child journal names. For
48250 ** each child journal, it checks if:
48251 **
48252 ** * if the child journal exists, and if so
48253 ** * if the child journal contains a reference to master journal
48254 ** file zMaster
48255 **
48256 ** If a child journal can be found that matches both of the criteria
48257 ** above, this function returns without doing anything. Otherwise, if
48258 ** no such child journal can be found, file zMaster is deleted from
48259 ** the file-system using sqlite3OsDelete().
48260 **
48261 ** If an IO error within this function, an error code is returned. This
48262 ** function allocates memory by calling sqlite3Malloc(). If an allocation
48263 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
48264 ** occur, SQLITE_OK is returned.
48265 **
48266 ** TODO: This function allocates a single block of memory to load
48267 ** the entire contents of the master journal file. This could be
48268 ** a couple of kilobytes or so - potentially larger than the page
48269 ** size.
48270 */
48271 static int pager_delmaster(Pager *pPager, const char *zMaster){
48272  sqlite3_vfs *pVfs = pPager->pVfs;
48273  int rc; /* Return code */
48274  sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
48275  sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
48276  char *zMasterJournal = 0; /* Contents of master journal file */
48277  i64 nMasterJournal; /* Size of master journal file */
48278  char *zJournal; /* Pointer to one journal within MJ file */
48279  char *zMasterPtr; /* Space to hold MJ filename from a journal file */
48280  int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
48281 
48282  /* Allocate space for both the pJournal and pMaster file descriptors.
48283  ** If successful, open the master journal file for reading.
48284  */
48285  pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
48286  pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
48287  if( !pMaster ){
48288  rc = SQLITE_NOMEM_BKPT;
48289  }else{
48291  rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
48292  }
48293  if( rc!=SQLITE_OK ) goto delmaster_out;
48294 
48295  /* Load the entire master journal file into space obtained from
48296  ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
48297  ** sufficient space (in zMasterPtr) to hold the names of master
48298  ** journal files extracted from regular rollback-journals.
48299  */
48300  rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
48301  if( rc!=SQLITE_OK ) goto delmaster_out;
48302  nMasterPtr = pVfs->mxPathname+1;
48303  zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
48304  if( !zMasterJournal ){
48305  rc = SQLITE_NOMEM_BKPT;
48306  goto delmaster_out;
48307  }
48308  zMasterPtr = &zMasterJournal[nMasterJournal+1];
48309  rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
48310  if( rc!=SQLITE_OK ) goto delmaster_out;
48311  zMasterJournal[nMasterJournal] = 0;
48312 
48313  zJournal = zMasterJournal;
48314  while( (zJournal-zMasterJournal)<nMasterJournal ){
48315  int exists;
48316  rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
48317  if( rc!=SQLITE_OK ){
48318  goto delmaster_out;
48319  }
48320  if( exists ){
48321  /* One of the journals pointed to by the master journal exists.
48322  ** Open it and check if it points at the master journal. If
48323  ** so, return without deleting the master journal file.
48324  */
48325  int c;
48327  rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
48328  if( rc!=SQLITE_OK ){
48329  goto delmaster_out;
48330  }
48331 
48332  rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
48333  sqlite3OsClose(pJournal);
48334  if( rc!=SQLITE_OK ){
48335  goto delmaster_out;
48336  }
48337 
48338  c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
48339  if( c ){
48340  /* We have a match. Do not delete the master journal file. */
48341  goto delmaster_out;
48342  }
48343  }
48344  zJournal += (sqlite3Strlen30(zJournal)+1);
48345  }
48346 
48347  sqlite3OsClose(pMaster);
48348  rc = sqlite3OsDelete(pVfs, zMaster, 0);
48349 
48350 delmaster_out:
48351  sqlite3_free(zMasterJournal);
48352  if( pMaster ){
48353  sqlite3OsClose(pMaster);
48354  assert( !isOpen(pJournal) );
48355  sqlite3_free(pMaster);
48356  }
48357  return rc;
48358 }
48359 
48360 
48361 /*
48362 ** This function is used to change the actual size of the database
48363 ** file in the file-system. This only happens when committing a transaction,
48364 ** or rolling back a transaction (including rolling back a hot-journal).
48365 **
48366 ** If the main database file is not open, or the pager is not in either
48367 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
48368 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
48369 ** If the file on disk is currently larger than nPage pages, then use the VFS
48370 ** xTruncate() method to truncate it.
48371 **
48372 ** Or, it might be the case that the file on disk is smaller than
48373 ** nPage pages. Some operating system implementations can get confused if
48374 ** you try to truncate a file to some size that is larger than it
48375 ** currently is, so detect this case and write a single zero byte to
48376 ** the end of the new file instead.
48377 **
48378 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
48379 ** the database file, return the error code to the caller.
48380 */
48381 static int pager_truncate(Pager *pPager, Pgno nPage){
48382  int rc = SQLITE_OK;
48383  assert( pPager->eState!=PAGER_ERROR );
48384  assert( pPager->eState!=PAGER_READER );
48385 
48386  if( isOpen(pPager->fd)
48387  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48388  ){
48389  i64 currentSize, newSize;
48390  int szPage = pPager->pageSize;
48391  assert( pPager->eLock==EXCLUSIVE_LOCK );
48392  /* TODO: Is it safe to use Pager.dbFileSize here? */
48393  rc = sqlite3OsFileSize(pPager->fd, &currentSize);
48394  newSize = szPage*(i64)nPage;
48395  if( rc==SQLITE_OK && currentSize!=newSize ){
48396  if( currentSize>newSize ){
48397  rc = sqlite3OsTruncate(pPager->fd, newSize);
48398  }else if( (currentSize+szPage)<=newSize ){
48399  char *pTmp = pPager->pTmpSpace;
48400  memset(pTmp, 0, szPage);
48401  testcase( (newSize-szPage) == currentSize );
48402  testcase( (newSize-szPage) > currentSize );
48403  rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
48404  }
48405  if( rc==SQLITE_OK ){
48406  pPager->dbFileSize = nPage;
48407  }
48408  }
48409  }
48410  return rc;
48411 }
48412 
48413 /*
48414 ** Return a sanitized version of the sector-size of OS file pFile. The
48415 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
48416 */
48417 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
48418  int iRet = sqlite3OsSectorSize(pFile);
48419  if( iRet<32 ){
48420  iRet = 512;
48421  }else if( iRet>MAX_SECTOR_SIZE ){
48422  assert( MAX_SECTOR_SIZE>=512 );
48423  iRet = MAX_SECTOR_SIZE;
48424  }
48425  return iRet;
48426 }
48427 
48428 /*
48429 ** Set the value of the Pager.sectorSize variable for the given
48430 ** pager based on the value returned by the xSectorSize method
48431 ** of the open database file. The sector size will be used
48432 ** to determine the size and alignment of journal header and
48433 ** master journal pointers within created journal files.
48434 **
48435 ** For temporary files the effective sector size is always 512 bytes.
48436 **
48437 ** Otherwise, for non-temporary files, the effective sector size is
48438 ** the value returned by the xSectorSize() method rounded up to 32 if
48439 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
48440 ** is greater than MAX_SECTOR_SIZE.
48441 **
48442 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
48443 ** the effective sector size to its minimum value (512). The purpose of
48444 ** pPager->sectorSize is to define the "blast radius" of bytes that
48445 ** might change if a crash occurs while writing to a single byte in
48446 ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
48447 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
48448 ** size. For backwards compatibility of the rollback journal file format,
48449 ** we cannot reduce the effective sector size below 512.
48450 */
48451 static void setSectorSize(Pager *pPager){
48452  assert( isOpen(pPager->fd) || pPager->tempFile );
48453 
48454  if( pPager->tempFile
48455  || (sqlite3OsDeviceCharacteristics(pPager->fd) &
48457  ){
48458  /* Sector size doesn't matter for temporary files. Also, the file
48459  ** may not have been opened yet, in which case the OsSectorSize()
48460  ** call will segfault. */
48461  pPager->sectorSize = 512;
48462  }else{
48463  pPager->sectorSize = sqlite3SectorSize(pPager->fd);
48464  }
48465 }
48466 
48467 /*
48468 ** Playback the journal and thus restore the database file to
48469 ** the state it was in before we started making changes.
48470 **
48471 ** The journal file format is as follows:
48472 **
48473 ** (1) 8 byte prefix. A copy of aJournalMagic[].
48474 ** (2) 4 byte big-endian integer which is the number of valid page records
48475 ** in the journal. If this value is 0xffffffff, then compute the
48476 ** number of page records from the journal size.
48477 ** (3) 4 byte big-endian integer which is the initial value for the
48478 ** sanity checksum.
48479 ** (4) 4 byte integer which is the number of pages to truncate the
48480 ** database to during a rollback.
48481 ** (5) 4 byte big-endian integer which is the sector size. The header
48482 ** is this many bytes in size.
48483 ** (6) 4 byte big-endian integer which is the page size.
48484 ** (7) zero padding out to the next sector size.
48485 ** (8) Zero or more pages instances, each as follows:
48486 ** + 4 byte page number.
48487 ** + pPager->pageSize bytes of data.
48488 ** + 4 byte checksum
48489 **
48490 ** When we speak of the journal header, we mean the first 7 items above.
48491 ** Each entry in the journal is an instance of the 8th item.
48492 **
48493 ** Call the value from the second bullet "nRec". nRec is the number of
48494 ** valid page entries in the journal. In most cases, you can compute the
48495 ** value of nRec from the size of the journal file. But if a power
48496 ** failure occurred while the journal was being written, it could be the
48497 ** case that the size of the journal file had already been increased but
48498 ** the extra entries had not yet made it safely to disk. In such a case,
48499 ** the value of nRec computed from the file size would be too large. For
48500 ** that reason, we always use the nRec value in the header.
48501 **
48502 ** If the nRec value is 0xffffffff it means that nRec should be computed
48503 ** from the file size. This value is used when the user selects the
48504 ** no-sync option for the journal. A power failure could lead to corruption
48505 ** in this case. But for things like temporary table (which will be
48506 ** deleted when the power is restored) we don't care.
48507 **
48508 ** If the file opened as the journal file is not a well-formed
48509 ** journal file then all pages up to the first corrupted page are rolled
48510 ** back (or no pages if the journal header is corrupted). The journal file
48511 ** is then deleted and SQLITE_OK returned, just as if no corruption had
48512 ** been encountered.
48513 **
48514 ** If an I/O or malloc() error occurs, the journal-file is not deleted
48515 ** and an error code is returned.
48516 **
48517 ** The isHot parameter indicates that we are trying to rollback a journal
48518 ** that might be a hot journal. Or, it could be that the journal is
48519 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
48520 ** If the journal really is hot, reset the pager cache prior rolling
48521 ** back any content. If the journal is merely persistent, no reset is
48522 ** needed.
48523 */
48524 static int pager_playback(Pager *pPager, int isHot){
48525  sqlite3_vfs *pVfs = pPager->pVfs;
48526  i64 szJ; /* Size of the journal file in bytes */
48527  u32 nRec; /* Number of Records in the journal */
48528  u32 u; /* Unsigned loop counter */
48529  Pgno mxPg = 0; /* Size of the original file in pages */
48530  int rc; /* Result code of a subroutine */
48531  int res = 1; /* Value returned by sqlite3OsAccess() */
48532  char *zMaster = 0; /* Name of master journal file if any */
48533  int needPagerReset; /* True to reset page prior to first page rollback */
48534  int nPlayback = 0; /* Total number of pages restored from journal */
48535 
48536  /* Figure out how many records are in the journal. Abort early if
48537  ** the journal is empty.
48538  */
48539  assert( isOpen(pPager->jfd) );
48540  rc = sqlite3OsFileSize(pPager->jfd, &szJ);
48541  if( rc!=SQLITE_OK ){
48542  goto end_playback;
48543  }
48544 
48545  /* Read the master journal name from the journal, if it is present.
48546  ** If a master journal file name is specified, but the file is not
48547  ** present on disk, then the journal is not hot and does not need to be
48548  ** played back.
48549  **
48550  ** TODO: Technically the following is an error because it assumes that
48551  ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
48552  ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
48553  ** mxPathname is 512, which is the same as the minimum allowable value
48554  ** for pageSize.
48555  */
48556  zMaster = pPager->pTmpSpace;
48557  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
48558  if( rc==SQLITE_OK && zMaster[0] ){
48559  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
48560  }
48561  zMaster = 0;
48562  if( rc!=SQLITE_OK || !res ){
48563  goto end_playback;
48564  }
48565  pPager->journalOff = 0;
48566  needPagerReset = isHot;
48567 
48568  /* This loop terminates either when a readJournalHdr() or
48569  ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
48570  ** occurs.
48571  */
48572  while( 1 ){
48573  /* Read the next journal header from the journal file. If there are
48574  ** not enough bytes left in the journal file for a complete header, or
48575  ** it is corrupted, then a process must have failed while writing it.
48576  ** This indicates nothing more needs to be rolled back.
48577  */
48578  rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
48579  if( rc!=SQLITE_OK ){
48580  if( rc==SQLITE_DONE ){
48581  rc = SQLITE_OK;
48582  }
48583  goto end_playback;
48584  }
48585 
48586  /* If nRec is 0xffffffff, then this journal was created by a process
48587  ** working in no-sync mode. This means that the rest of the journal
48588  ** file consists of pages, there are no more journal headers. Compute
48589  ** the value of nRec based on this assumption.
48590  */
48591  if( nRec==0xffffffff ){
48592  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
48593  nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
48594  }
48595 
48596  /* If nRec is 0 and this rollback is of a transaction created by this
48597  ** process and if this is the final header in the journal, then it means
48598  ** that this part of the journal was being filled but has not yet been
48599  ** synced to disk. Compute the number of pages based on the remaining
48600  ** size of the file.
48601  **
48602  ** The third term of the test was added to fix ticket #2565.
48603  ** When rolling back a hot journal, nRec==0 always means that the next
48604  ** chunk of the journal contains zero pages to be rolled back. But
48605  ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
48606  ** the journal, it means that the journal might contain additional
48607  ** pages that need to be rolled back and that the number of pages
48608  ** should be computed based on the journal file size.
48609  */
48610  if( nRec==0 && !isHot &&
48611  pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
48612  nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
48613  }
48614 
48615  /* If this is the first header read from the journal, truncate the
48616  ** database file back to its original size.
48617  */
48618  if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
48619  rc = pager_truncate(pPager, mxPg);
48620  if( rc!=SQLITE_OK ){
48621  goto end_playback;
48622  }
48623  pPager->dbSize = mxPg;
48624  }
48625 
48626  /* Copy original pages out of the journal and back into the
48627  ** database file and/or page cache.
48628  */
48629  for(u=0; u<nRec; u++){
48630  if( needPagerReset ){
48631  pager_reset(pPager);
48632  needPagerReset = 0;
48633  }
48634  rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
48635  if( rc==SQLITE_OK ){
48636  nPlayback++;
48637  }else{
48638  if( rc==SQLITE_DONE ){
48639  pPager->journalOff = szJ;
48640  break;
48641  }else if( rc==SQLITE_IOERR_SHORT_READ ){
48642  /* If the journal has been truncated, simply stop reading and
48643  ** processing the journal. This might happen if the journal was
48644  ** not completely written and synced prior to a crash. In that
48645  ** case, the database should have never been written in the
48646  ** first place so it is OK to simply abandon the rollback. */
48647  rc = SQLITE_OK;
48648  goto end_playback;
48649  }else{
48650  /* If we are unable to rollback, quit and return the error
48651  ** code. This will cause the pager to enter the error state
48652  ** so that no further harm will be done. Perhaps the next
48653  ** process to come along will be able to rollback the database.
48654  */
48655  goto end_playback;
48656  }
48657  }
48658  }
48659  }
48660  /*NOTREACHED*/
48661  assert( 0 );
48662 
48663 end_playback:
48664  /* Following a rollback, the database file should be back in its original
48665  ** state prior to the start of the transaction, so invoke the
48666  ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
48667  ** assertion that the transaction counter was modified.
48668  */
48669 #ifdef SQLITE_DEBUG
48670  if( pPager->fd->pMethods ){
48672  }
48673 #endif
48674 
48675  /* If this playback is happening automatically as a result of an IO or
48676  ** malloc error that occurred after the change-counter was updated but
48677  ** before the transaction was committed, then the change-counter
48678  ** modification may just have been reverted. If this happens in exclusive
48679  ** mode, then subsequent transactions performed by the connection will not
48680  ** update the change-counter at all. This may lead to cache inconsistency
48681  ** problems for other processes at some point in the future. So, just
48682  ** in case this has happened, clear the changeCountDone flag now.
48683  */
48684  pPager->changeCountDone = pPager->tempFile;
48685 
48686  if( rc==SQLITE_OK ){
48687  zMaster = pPager->pTmpSpace;
48688  rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
48689  testcase( rc!=SQLITE_OK );
48690  }
48691  if( rc==SQLITE_OK
48692  && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
48693  ){
48694  rc = sqlite3PagerSync(pPager, 0);
48695  }
48696  if( rc==SQLITE_OK ){
48697  rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
48698  testcase( rc!=SQLITE_OK );
48699  }
48700  if( rc==SQLITE_OK && zMaster[0] && res ){
48701  /* If there was a master journal and this routine will return success,
48702  ** see if it is possible to delete the master journal.
48703  */
48704  rc = pager_delmaster(pPager, zMaster);
48705  testcase( rc!=SQLITE_OK );
48706  }
48707  if( isHot && nPlayback ){
48708  sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
48709  nPlayback, pPager->zJournal);
48710  }
48711 
48712  /* The Pager.sectorSize variable may have been updated while rolling
48713  ** back a journal created by a process with a different sector size
48714  ** value. Reset it to the correct value for this process.
48715  */
48716  setSectorSize(pPager);
48717  return rc;
48718 }
48719 
48720 
48721 /*
48722 ** Read the content for page pPg out of the database file and into
48723 ** pPg->pData. A shared lock or greater must be held on the database
48724 ** file before this function is called.
48725 **
48726 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
48727 ** the value read from the database file.
48728 **
48729 ** If an IO error occurs, then the IO error is returned to the caller.
48730 ** Otherwise, SQLITE_OK is returned.
48731 */
48732 static int readDbPage(PgHdr *pPg, u32 iFrame){
48733  Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
48734  Pgno pgno = pPg->pgno; /* Page number to read */
48735  int rc = SQLITE_OK; /* Return code */
48736  int pgsz = pPager->pageSize; /* Number of bytes to read */
48737 
48738  assert( pPager->eState>=PAGER_READER && !MEMDB );
48739  assert( isOpen(pPager->fd) );
48740 
48741 #ifndef SQLITE_OMIT_WAL
48742  if( iFrame ){
48743  /* Try to pull the page from the write-ahead log. */
48744  rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
48745  }else
48746 #endif
48747  {
48748  i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
48749  rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
48750  if( rc==SQLITE_IOERR_SHORT_READ ){
48751  rc = SQLITE_OK;
48752  }
48753  }
48754 
48755  if( pgno==1 ){
48756  if( rc ){
48757  /* If the read is unsuccessful, set the dbFileVers[] to something
48758  ** that will never be a valid file version. dbFileVers[] is a copy
48759  ** of bytes 24..39 of the database. Bytes 28..31 should always be
48760  ** zero or the size of the database in page. Bytes 32..35 and 35..39
48761  ** should be page numbers which are never 0xffffffff. So filling
48762  ** pPager->dbFileVers[] with all 0xff bytes should suffice.
48763  **
48764  ** For an encrypted database, the situation is more complex: bytes
48765  ** 24..39 of the database are white noise. But the probability of
48766  ** white noise equaling 16 bytes of 0xff is vanishingly small so
48767  ** we should still be ok.
48768  */
48769  memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
48770  }else{
48771  u8 *dbFileVers = &((u8*)pPg->pData)[24];
48772  memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
48773  }
48774  }
48775  CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM_BKPT);
48776 
48777  PAGER_INCR(sqlite3_pager_readdb_count);
48778  PAGER_INCR(pPager->nRead);
48779  IOTRACE(("PGIN %p %d\n", pPager, pgno));
48780  PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
48781  PAGERID(pPager), pgno, pager_pagehash(pPg)));
48782 
48783  return rc;
48784 }
48785 
48786 /*
48787 ** Update the value of the change-counter at offsets 24 and 92 in
48788 ** the header and the sqlite version number at offset 96.
48789 **
48790 ** This is an unconditional update. See also the pager_incr_changecounter()
48791 ** routine which only updates the change-counter if the update is actually
48792 ** needed, as determined by the pPager->changeCountDone state variable.
48793 */
48795  u32 change_counter;
48796 
48797  /* Increment the value just read and write it back to byte 24. */
48798  change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
48799  put32bits(((char*)pPg->pData)+24, change_counter);
48800 
48801  /* Also store the SQLite version number in bytes 96..99 and in
48802  ** bytes 92..95 store the change counter for which the version number
48803  ** is valid. */
48804  put32bits(((char*)pPg->pData)+92, change_counter);
48805  put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
48806 }
48807 
48808 #ifndef SQLITE_OMIT_WAL
48809 /*
48810 ** This function is invoked once for each page that has already been
48811 ** written into the log file when a WAL transaction is rolled back.
48812 ** Parameter iPg is the page number of said page. The pCtx argument
48813 ** is actually a pointer to the Pager structure.
48814 **
48815 ** If page iPg is present in the cache, and has no outstanding references,
48816 ** it is discarded. Otherwise, if there are one or more outstanding
48817 ** references, the page content is reloaded from the database. If the
48818 ** attempt to reload content from the database is required and fails,
48819 ** return an SQLite error code. Otherwise, SQLITE_OK.
48820 */
48821 static int pagerUndoCallback(void *pCtx, Pgno iPg){
48822  int rc = SQLITE_OK;
48823  Pager *pPager = (Pager *)pCtx;
48824  PgHdr *pPg;
48825 
48826  assert( pagerUseWal(pPager) );
48827  pPg = sqlite3PagerLookup(pPager, iPg);
48828  if( pPg ){
48829  if( sqlite3PcachePageRefcount(pPg)==1 ){
48830  sqlite3PcacheDrop(pPg);
48831  }else{
48832  u32 iFrame = 0;
48833  rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
48834  if( rc==SQLITE_OK ){
48835  rc = readDbPage(pPg, iFrame);
48836  }
48837  if( rc==SQLITE_OK ){
48838  pPager->xReiniter(pPg);
48839  }
48841  }
48842  }
48843 
48844  /* Normally, if a transaction is rolled back, any backup processes are
48845  ** updated as data is copied out of the rollback journal and into the
48846  ** database. This is not generally possible with a WAL database, as
48847  ** rollback involves simply truncating the log file. Therefore, if one
48848  ** or more frames have already been written to the log (and therefore
48849  ** also copied into the backup databases) as part of this transaction,
48850  ** the backups must be restarted.
48851  */
48852  sqlite3BackupRestart(pPager->pBackup);
48853 
48854  return rc;
48855 }
48856 
48857 /*
48858 ** This function is called to rollback a transaction on a WAL database.
48859 */
48860 static int pagerRollbackWal(Pager *pPager){
48861  int rc; /* Return Code */
48862  PgHdr *pList; /* List of dirty pages to revert */
48863 
48864  /* For all pages in the cache that are currently dirty or have already
48865  ** been written (but not committed) to the log file, do one of the
48866  ** following:
48867  **
48868  ** + Discard the cached page (if refcount==0), or
48869  ** + Reload page content from the database (if refcount>0).
48870  */
48871  pPager->dbSize = pPager->dbOrigSize;
48872  rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
48873  pList = sqlite3PcacheDirtyList(pPager->pPCache);
48874  while( pList && rc==SQLITE_OK ){
48875  PgHdr *pNext = pList->pDirty;
48876  rc = pagerUndoCallback((void *)pPager, pList->pgno);
48877  pList = pNext;
48878  }
48879 
48880  return rc;
48881 }
48882 
48883 /*
48884 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
48885 ** the contents of the list of pages headed by pList (connected by pDirty),
48886 ** this function notifies any active backup processes that the pages have
48887 ** changed.
48888 **
48889 ** The list of pages passed into this routine is always sorted by page number.
48890 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
48891 */
48892 static int pagerWalFrames(
48893  Pager *pPager, /* Pager object */
48894  PgHdr *pList, /* List of frames to log */
48895  Pgno nTruncate, /* Database size after this commit */
48896  int isCommit /* True if this is a commit */
48897 ){
48898  int rc; /* Return code */
48899  int nList; /* Number of pages in pList */
48900  PgHdr *p; /* For looping over pages */
48901 
48902  assert( pPager->pWal );
48903  assert( pList );
48904 #ifdef SQLITE_DEBUG
48905  /* Verify that the page list is in accending order */
48906  for(p=pList; p && p->pDirty; p=p->pDirty){
48907  assert( p->pgno < p->pDirty->pgno );
48908  }
48909 #endif
48910 
48911  assert( pList->pDirty==0 || isCommit );
48912  if( isCommit ){
48913  /* If a WAL transaction is being committed, there is no point in writing
48914  ** any pages with page numbers greater than nTruncate into the WAL file.
48915  ** They will never be read by any client. So remove them from the pDirty
48916  ** list here. */
48917  PgHdr **ppNext = &pList;
48918  nList = 0;
48919  for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
48920  if( p->pgno<=nTruncate ){
48921  ppNext = &p->pDirty;
48922  nList++;
48923  }
48924  }
48925  assert( pList );
48926  }else{
48927  nList = 1;
48928  }
48929  pPager->aStat[PAGER_STAT_WRITE] += nList;
48930 
48931  if( pList->pgno==1 ) pager_write_changecounter(pList);
48932  rc = sqlite3WalFrames(pPager->pWal,
48933  pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
48934  );
48935  if( rc==SQLITE_OK && pPager->pBackup ){
48936  for(p=pList; p; p=p->pDirty){
48937  sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
48938  }
48939  }
48940 
48941 #ifdef SQLITE_CHECK_PAGES
48942  pList = sqlite3PcacheDirtyList(pPager->pPCache);
48943  for(p=pList; p; p=p->pDirty){
48944  pager_set_pagehash(p);
48945  }
48946 #endif
48947 
48948  return rc;
48949 }
48950 
48951 /*
48952 ** Begin a read transaction on the WAL.
48953 **
48954 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
48955 ** makes a snapshot of the database at the current point in time and preserves
48956 ** that snapshot for use by the reader in spite of concurrently changes by
48957 ** other writers or checkpointers.
48958 */
48959 static int pagerBeginReadTransaction(Pager *pPager){
48960  int rc; /* Return code */
48961  int changed = 0; /* True if cache must be reset */
48962 
48963  assert( pagerUseWal(pPager) );
48964  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
48965 
48966  /* sqlite3WalEndReadTransaction() was not called for the previous
48967  ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
48968  ** are in locking_mode=NORMAL and EndRead() was previously called,
48969  ** the duplicate call is harmless.
48970  */
48972 
48973  rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
48974  if( rc!=SQLITE_OK || changed ){
48975  pager_reset(pPager);
48976  if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
48977  }
48978 
48979  return rc;
48980 }
48981 #endif
48982 
48983 /*
48984 ** This function is called as part of the transition from PAGER_OPEN
48985 ** to PAGER_READER state to determine the size of the database file
48986 ** in pages (assuming the page size currently stored in Pager.pageSize).
48987 **
48988 ** If no error occurs, SQLITE_OK is returned and the size of the database
48989 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
48990 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
48991 */
48992 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
48993  Pgno nPage; /* Value to return via *pnPage */
48994 
48995  /* Query the WAL sub-system for the database size. The WalDbsize()
48996  ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
48997  ** if the database size is not available. The database size is not
48998  ** available from the WAL sub-system if the log file is empty or
48999  ** contains no valid committed transactions.
49000  */
49001  assert( pPager->eState==PAGER_OPEN );
49002  assert( pPager->eLock>=SHARED_LOCK );
49003  assert( isOpen(pPager->fd) );
49004  assert( pPager->tempFile==0 );
49005  nPage = sqlite3WalDbsize(pPager->pWal);
49006 
49007  /* If the number of pages in the database is not available from the
49008  ** WAL sub-system, determine the page counte based on the size of
49009  ** the database file. If the size of the database file is not an
49010  ** integer multiple of the page-size, round up the result.
49011  */
49012  if( nPage==0 && ALWAYS(isOpen(pPager->fd)) ){
49013  i64 n = 0; /* Size of db file in bytes */
49014  int rc = sqlite3OsFileSize(pPager->fd, &n);
49015  if( rc!=SQLITE_OK ){
49016  return rc;
49017  }
49018  nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
49019  }
49020 
49021  /* If the current number of pages in the file is greater than the
49022  ** configured maximum pager number, increase the allowed limit so
49023  ** that the file can be read.
49024  */
49025  if( nPage>pPager->mxPgno ){
49026  pPager->mxPgno = (Pgno)nPage;
49027  }
49028 
49029  *pnPage = nPage;
49030  return SQLITE_OK;
49031 }
49032 
49033 #ifndef SQLITE_OMIT_WAL
49034 /*
49035 ** Check if the *-wal file that corresponds to the database opened by pPager
49036 ** exists if the database is not empy, or verify that the *-wal file does
49037 ** not exist (by deleting it) if the database file is empty.
49038 **
49039 ** If the database is not empty and the *-wal file exists, open the pager
49040 ** in WAL mode. If the database is empty or if no *-wal file exists and
49041 ** if no error occurs, make sure Pager.journalMode is not set to
49042 ** PAGER_JOURNALMODE_WAL.
49043 **
49044 ** Return SQLITE_OK or an error code.
49045 **
49046 ** The caller must hold a SHARED lock on the database file to call this
49047 ** function. Because an EXCLUSIVE lock on the db file is required to delete
49048 ** a WAL on a none-empty database, this ensures there is no race condition
49049 ** between the xAccess() below and an xDelete() being executed by some
49050 ** other connection.
49051 */
49052 static int pagerOpenWalIfPresent(Pager *pPager){
49053  int rc = SQLITE_OK;
49054  assert( pPager->eState==PAGER_OPEN );
49055  assert( pPager->eLock>=SHARED_LOCK );
49056 
49057  if( !pPager->tempFile ){
49058  int isWal; /* True if WAL file exists */
49059  Pgno nPage; /* Size of the database file */
49060 
49061  rc = pagerPagecount(pPager, &nPage);
49062  if( rc ) return rc;
49063  if( nPage==0 ){
49064  rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
49065  if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
49066  isWal = 0;
49067  }else{
49068  rc = sqlite3OsAccess(
49069  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
49070  );
49071  }
49072  if( rc==SQLITE_OK ){
49073  if( isWal ){
49074  testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
49075  rc = sqlite3PagerOpenWal(pPager, 0);
49076  }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
49078  }
49079  }
49080  }
49081  return rc;
49082 }
49083 #endif
49084 
49085 /*
49086 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
49087 ** the entire master journal file. The case pSavepoint==NULL occurs when
49088 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
49089 ** savepoint.
49090 **
49091 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
49092 ** being rolled back), then the rollback consists of up to three stages,
49093 ** performed in the order specified:
49094 **
49095 ** * Pages are played back from the main journal starting at byte
49096 ** offset PagerSavepoint.iOffset and continuing to
49097 ** PagerSavepoint.iHdrOffset, or to the end of the main journal
49098 ** file if PagerSavepoint.iHdrOffset is zero.
49099 **
49100 ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
49101 ** back starting from the journal header immediately following
49102 ** PagerSavepoint.iHdrOffset to the end of the main journal file.
49103 **
49104 ** * Pages are then played back from the sub-journal file, starting
49105 ** with the PagerSavepoint.iSubRec and continuing to the end of
49106 ** the journal file.
49107 **
49108 ** Throughout the rollback process, each time a page is rolled back, the
49109 ** corresponding bit is set in a bitvec structure (variable pDone in the
49110 ** implementation below). This is used to ensure that a page is only
49111 ** rolled back the first time it is encountered in either journal.
49112 **
49113 ** If pSavepoint is NULL, then pages are only played back from the main
49114 ** journal file. There is no need for a bitvec in this case.
49115 **
49116 ** In either case, before playback commences the Pager.dbSize variable
49117 ** is reset to the value that it held at the start of the savepoint
49118 ** (or transaction). No page with a page-number greater than this value
49119 ** is played back. If one is encountered it is simply skipped.
49120 */
49121 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
49122  i64 szJ; /* Effective size of the main journal */
49123  i64 iHdrOff; /* End of first segment of main-journal records */
49124  int rc = SQLITE_OK; /* Return code */
49125  Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
49126 
49127  assert( pPager->eState!=PAGER_ERROR );
49128  assert( pPager->eState>=PAGER_WRITER_LOCKED );
49129 
49130  /* Allocate a bitvec to use to store the set of pages rolled back */
49131  if( pSavepoint ){
49132  pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
49133  if( !pDone ){
49134  return SQLITE_NOMEM_BKPT;
49135  }
49136  }
49137 
49138  /* Set the database size back to the value it was before the savepoint
49139  ** being reverted was opened.
49140  */
49141  pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
49142  pPager->changeCountDone = pPager->tempFile;
49143 
49144  if( !pSavepoint && pagerUseWal(pPager) ){
49145  return pagerRollbackWal(pPager);
49146  }
49147 
49148  /* Use pPager->journalOff as the effective size of the main rollback
49149  ** journal. The actual file might be larger than this in
49150  ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
49151  ** past pPager->journalOff is off-limits to us.
49152  */
49153  szJ = pPager->journalOff;
49154  assert( pagerUseWal(pPager)==0 || szJ==0 );
49155 
49156  /* Begin by rolling back records from the main journal starting at
49157  ** PagerSavepoint.iOffset and continuing to the next journal header.
49158  ** There might be records in the main journal that have a page number
49159  ** greater than the current database size (pPager->dbSize) but those
49160  ** will be skipped automatically. Pages are added to pDone as they
49161  ** are played back.
49162  */
49163  if( pSavepoint && !pagerUseWal(pPager) ){
49164  iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
49165  pPager->journalOff = pSavepoint->iOffset;
49166  while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
49167  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49168  }
49169  assert( rc!=SQLITE_DONE );
49170  }else{
49171  pPager->journalOff = 0;
49172  }
49173 
49174  /* Continue rolling back records out of the main journal starting at
49175  ** the first journal header seen and continuing until the effective end
49176  ** of the main journal file. Continue to skip out-of-range pages and
49177  ** continue adding pages rolled back to pDone.
49178  */
49179  while( rc==SQLITE_OK && pPager->journalOff<szJ ){
49180  u32 ii; /* Loop counter */
49181  u32 nJRec = 0; /* Number of Journal Records */
49182  u32 dummy;
49183  rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
49184  assert( rc!=SQLITE_DONE );
49185 
49186  /*
49187  ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
49188  ** test is related to ticket #2565. See the discussion in the
49189  ** pager_playback() function for additional information.
49190  */
49191  if( nJRec==0
49192  && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
49193  ){
49194  nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
49195  }
49196  for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
49197  rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
49198  }
49199  assert( rc!=SQLITE_DONE );
49200  }
49201  assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
49202 
49203  /* Finally, rollback pages from the sub-journal. Page that were
49204  ** previously rolled back out of the main journal (and are hence in pDone)
49205  ** will be skipped. Out-of-range pages are also skipped.
49206  */
49207  if( pSavepoint ){
49208  u32 ii; /* Loop counter */
49209  i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
49210 
49211  if( pagerUseWal(pPager) ){
49212  rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
49213  }
49214  for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
49215  assert( offset==(i64)ii*(4+pPager->pageSize) );
49216  rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
49217  }
49218  assert( rc!=SQLITE_DONE );
49219  }
49220 
49221  sqlite3BitvecDestroy(pDone);
49222  if( rc==SQLITE_OK ){
49223  pPager->journalOff = szJ;
49224  }
49225 
49226  return rc;
49227 }
49228 
49229 /*
49230 ** Change the maximum number of in-memory pages that are allowed
49231 ** before attempting to recycle clean and unused pages.
49232 */
49234  sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
49235 }
49236 
49237 /*
49238 ** Change the maximum number of in-memory pages that are allowed
49239 ** before attempting to spill pages to journal.
49240 */
49242  return sqlite3PcacheSetSpillsize(pPager->pPCache, mxPage);
49243 }
49244 
49245 /*
49246 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
49247 */
49248 static void pagerFixMaplimit(Pager *pPager){
49249 #if SQLITE_MAX_MMAP_SIZE>0
49250  sqlite3_file *fd = pPager->fd;
49251  if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
49252  sqlite3_int64 sz;
49253  sz = pPager->szMmap;
49254  pPager->bUseFetch = (sz>0);
49256  }
49257 #endif
49258 }
49259 
49260 /*
49261 ** Change the maximum size of any memory mapping made of the database file.
49262 */
49263 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
49264  pPager->szMmap = szMmap;
49265  pagerFixMaplimit(pPager);
49266 }
49267 
49268 /*
49269 ** Free as much memory as possible from the pager.
49270 */
49272  sqlite3PcacheShrink(pPager->pPCache);
49273 }
49274 
49275 /*
49276 ** Adjust settings of the pager to those specified in the pgFlags parameter.
49277 **
49278 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
49279 ** of the database to damage due to OS crashes or power failures by
49280 ** changing the number of syncs()s when writing the journals.
49281 ** There are four levels:
49282 **
49283 ** OFF sqlite3OsSync() is never called. This is the default
49284 ** for temporary and transient files.
49285 **
49286 ** NORMAL The journal is synced once before writes begin on the
49287 ** database. This is normally adequate protection, but
49288 ** it is theoretically possible, though very unlikely,
49289 ** that an inopertune power failure could leave the journal
49290 ** in a state which would cause damage to the database
49291 ** when it is rolled back.
49292 **
49293 ** FULL The journal is synced twice before writes begin on the
49294 ** database (with some additional information - the nRec field
49295 ** of the journal header - being written in between the two
49296 ** syncs). If we assume that writing a
49297 ** single disk sector is atomic, then this mode provides
49298 ** assurance that the journal will not be corrupted to the
49299 ** point of causing damage to the database during rollback.
49300 **
49301 ** EXTRA This is like FULL except that is also syncs the directory
49302 ** that contains the rollback journal after the rollback
49303 ** journal is unlinked.
49304 **
49305 ** The above is for a rollback-journal mode. For WAL mode, OFF continues
49306 ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
49307 ** prior to the start of checkpoint and that the database file is synced
49308 ** at the conclusion of the checkpoint if the entire content of the WAL
49309 ** was written back into the database. But no sync operations occur for
49310 ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
49311 ** file is synced following each commit operation, in addition to the
49312 ** syncs associated with NORMAL. There is no difference between FULL
49313 ** and EXTRA for WAL mode.
49314 **
49315 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
49316 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
49317 ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
49318 ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
49319 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
49320 ** synchronous=FULL versus synchronous=NORMAL setting determines when
49321 ** the xSync primitive is called and is relevant to all platforms.
49322 **
49323 ** Numeric values associated with these states are OFF==1, NORMAL=2,
49324 ** and FULL=3.
49325 */
49326 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
49328  Pager *pPager, /* The pager to set safety level for */
49329  unsigned pgFlags /* Various flags */
49330 ){
49331  unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
49332  if( pPager->tempFile ){
49333  pPager->noSync = 1;
49334  pPager->fullSync = 0;
49335  pPager->extraSync = 0;
49336  }else{
49337  pPager->noSync = level==PAGER_SYNCHRONOUS_OFF ?1:0;
49338  pPager->fullSync = level>=PAGER_SYNCHRONOUS_FULL ?1:0;
49339  pPager->extraSync = level==PAGER_SYNCHRONOUS_EXTRA ?1:0;
49340  }
49341  if( pPager->noSync ){
49342  pPager->syncFlags = 0;
49343  pPager->ckptSyncFlags = 0;
49344  }else if( pgFlags & PAGER_FULLFSYNC ){
49345  pPager->syncFlags = SQLITE_SYNC_FULL;
49346  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49347  }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
49348  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49349  pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
49350  }else{
49351  pPager->syncFlags = SQLITE_SYNC_NORMAL;
49353  }
49354  pPager->walSyncFlags = pPager->syncFlags;
49355  if( pPager->fullSync ){
49357  }
49358  if( pgFlags & PAGER_CACHESPILL ){
49359  pPager->doNotSpill &= ~SPILLFLAG_OFF;
49360  }else{
49361  pPager->doNotSpill |= SPILLFLAG_OFF;
49362  }
49363 }
49364 #endif
49365 
49366 /*
49367 ** The following global variable is incremented whenever the library
49368 ** attempts to open a temporary file. This information is used for
49369 ** testing and analysis only.
49370 */
49371 #ifdef SQLITE_TEST
49372 SQLITE_API int sqlite3_opentemp_count = 0;
49373 #endif
49374 
49375 /*
49376 ** Open a temporary file.
49377 **
49378 ** Write the file descriptor into *pFile. Return SQLITE_OK on success
49379 ** or some other error code if we fail. The OS will automatically
49380 ** delete the temporary file when it is closed.
49381 **
49382 ** The flags passed to the VFS layer xOpen() call are those specified
49383 ** by parameter vfsFlags ORed with the following:
49384 **
49385 ** SQLITE_OPEN_READWRITE
49386 ** SQLITE_OPEN_CREATE
49387 ** SQLITE_OPEN_EXCLUSIVE
49388 ** SQLITE_OPEN_DELETEONCLOSE
49389 */
49390 static int pagerOpentemp(
49391  Pager *pPager, /* The pager object */
49392  sqlite3_file *pFile, /* Write the file descriptor here */
49393  int vfsFlags /* Flags passed through to the VFS */
49394 ){
49395  int rc; /* Return code */
49396 
49397 #ifdef SQLITE_TEST
49398  sqlite3_opentemp_count++; /* Used for testing and analysis only */
49399 #endif
49400 
49403  rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
49404  assert( rc!=SQLITE_OK || isOpen(pFile) );
49405  return rc;
49406 }
49407 
49408 /*
49409 ** Set the busy handler function.
49410 **
49411 ** The pager invokes the busy-handler if sqlite3OsLock() returns
49412 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
49413 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
49414 ** lock. It does *not* invoke the busy handler when upgrading from
49415 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
49416 ** (which occurs during hot-journal rollback). Summary:
49417 **
49418 ** Transition | Invokes xBusyHandler
49419 ** --------------------------------------------------------
49420 ** NO_LOCK -> SHARED_LOCK | Yes
49421 ** SHARED_LOCK -> RESERVED_LOCK | No
49422 ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
49423 ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
49424 **
49425 ** If the busy-handler callback returns non-zero, the lock is
49426 ** retried. If it returns zero, then the SQLITE_BUSY error is
49427 ** returned to the caller of the pager API function.
49428 */
49430  Pager *pPager, /* Pager object */
49431  int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
49432  void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
49433 ){
49434  pPager->xBusyHandler = xBusyHandler;
49435  pPager->pBusyHandlerArg = pBusyHandlerArg;
49436 
49437  if( isOpen(pPager->fd) ){
49438  void **ap = (void **)&pPager->xBusyHandler;
49439  assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
49440  assert( ap[1]==pBusyHandlerArg );
49442  }
49443 }
49444 
49445 /*
49446 ** Change the page size used by the Pager object. The new page size
49447 ** is passed in *pPageSize.
49448 **
49449 ** If the pager is in the error state when this function is called, it
49450 ** is a no-op. The value returned is the error state error code (i.e.
49451 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
49452 **
49453 ** Otherwise, if all of the following are true:
49454 **
49455 ** * the new page size (value of *pPageSize) is valid (a power
49456 ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
49457 **
49458 ** * there are no outstanding page references, and
49459 **
49460 ** * the database is either not an in-memory database or it is
49461 ** an in-memory database that currently consists of zero pages.
49462 **
49463 ** then the pager object page size is set to *pPageSize.
49464 **
49465 ** If the page size is changed, then this function uses sqlite3PagerMalloc()
49466 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
49467 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
49468 ** In all other cases, SQLITE_OK is returned.
49469 **
49470 ** If the page size is not changed, either because one of the enumerated
49471 ** conditions above is not true, the pager was in error state when this
49472 ** function was called, or because the memory allocation attempt failed,
49473 ** then *pPageSize is set to the old, retained page size before returning.
49474 */
49475 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
49476  int rc = SQLITE_OK;
49477 
49478  /* It is not possible to do a full assert_pager_state() here, as this
49479  ** function may be called from within PagerOpen(), before the state
49480  ** of the Pager object is internally consistent.
49481  **
49482  ** At one point this function returned an error if the pager was in
49483  ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
49484  ** there is at least one outstanding page reference, this function
49485  ** is a no-op for that case anyhow.
49486  */
49487 
49488  u32 pageSize = *pPageSize;
49489  assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
49490  if( (pPager->memDb==0 || pPager->dbSize==0)
49491  && sqlite3PcacheRefCount(pPager->pPCache)==0
49492  && pageSize && pageSize!=(u32)pPager->pageSize
49493  ){
49494  char *pNew = NULL; /* New temp space */
49495  i64 nByte = 0;
49496 
49497  if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
49498  rc = sqlite3OsFileSize(pPager->fd, &nByte);
49499  }
49500  if( rc==SQLITE_OK ){
49501  pNew = (char *)sqlite3PageMalloc(pageSize);
49502  if( !pNew ) rc = SQLITE_NOMEM_BKPT;
49503  }
49504 
49505  if( rc==SQLITE_OK ){
49506  pager_reset(pPager);
49507  rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
49508  }
49509  if( rc==SQLITE_OK ){
49510  sqlite3PageFree(pPager->pTmpSpace);
49511  pPager->pTmpSpace = pNew;
49512  pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
49513  pPager->pageSize = pageSize;
49514  }else{
49515  sqlite3PageFree(pNew);
49516  }
49517  }
49518 
49519  *pPageSize = pPager->pageSize;
49520  if( rc==SQLITE_OK ){
49521  if( nReserve<0 ) nReserve = pPager->nReserve;
49522  assert( nReserve>=0 && nReserve<1000 );
49523  pPager->nReserve = (i16)nReserve;
49524  pagerReportSize(pPager);
49525  pagerFixMaplimit(pPager);
49526  }
49527  return rc;
49528 }
49529 
49530 /*
49531 ** Return a pointer to the "temporary page" buffer held internally
49532 ** by the pager. This is a buffer that is big enough to hold the
49533 ** entire content of a database page. This buffer is used internally
49534 ** during rollback and will be overwritten whenever a rollback
49535 ** occurs. But other modules are free to use it too, as long as
49536 ** no rollbacks are happening.
49537 */
49539  return pPager->pTmpSpace;
49540 }
49541 
49542 /*
49543 ** Attempt to set the maximum database page count if mxPage is positive.
49544 ** Make no changes if mxPage is zero or negative. And never reduce the
49545 ** maximum page count below the current size of the database.
49546 **
49547 ** Regardless of mxPage, return the current maximum page count.
49548 */
49550  if( mxPage>0 ){
49551  pPager->mxPgno = mxPage;
49552  }
49553  assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
49554  assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
49555  return pPager->mxPgno;
49556 }
49557 
49558 /*
49559 ** The following set of routines are used to disable the simulated
49560 ** I/O error mechanism. These routines are used to avoid simulated
49561 ** errors in places where we do not care about errors.
49562 **
49563 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
49564 ** and generate no code.
49565 */
49566 #ifdef SQLITE_TEST
49567 SQLITE_API extern int sqlite3_io_error_pending;
49568 SQLITE_API extern int sqlite3_io_error_hit;
49569 static int saved_cnt;
49570 void disable_simulated_io_errors(void){
49571  saved_cnt = sqlite3_io_error_pending;
49572  sqlite3_io_error_pending = -1;
49573 }
49574 void enable_simulated_io_errors(void){
49575  sqlite3_io_error_pending = saved_cnt;
49576 }
49577 #else
49578 # define disable_simulated_io_errors()
49579 # define enable_simulated_io_errors()
49580 #endif
49581 
49582 /*
49583 ** Read the first N bytes from the beginning of the file into memory
49584 ** that pDest points to.
49585 **
49586 ** If the pager was opened on a transient file (zFilename==""), or
49587 ** opened on a file less than N bytes in size, the output buffer is
49588 ** zeroed and SQLITE_OK returned. The rationale for this is that this
49589 ** function is used to read database headers, and a new transient or
49590 ** zero sized database has a header than consists entirely of zeroes.
49591 **
49592 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
49593 ** the error code is returned to the caller and the contents of the
49594 ** output buffer undefined.
49595 */
49596 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
49597  int rc = SQLITE_OK;
49598  memset(pDest, 0, N);
49599  assert( isOpen(pPager->fd) || pPager->tempFile );
49600 
49601  /* This routine is only called by btree immediately after creating
49602  ** the Pager object. There has not been an opportunity to transition
49603  ** to WAL mode yet.
49604  */
49605  assert( !pagerUseWal(pPager) );
49606 
49607  if( isOpen(pPager->fd) ){
49608  IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
49609  rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
49610  if( rc==SQLITE_IOERR_SHORT_READ ){
49611  rc = SQLITE_OK;
49612  }
49613  }
49614  return rc;
49615 }
49616 
49617 /*
49618 ** This function may only be called when a read-transaction is open on
49619 ** the pager. It returns the total number of pages in the database.
49620 **
49621 ** However, if the file is between 1 and <page-size> bytes in size, then
49622 ** this is considered a 1 page file.
49623 */
49624 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
49625  assert( pPager->eState>=PAGER_READER );
49626  assert( pPager->eState!=PAGER_WRITER_FINISHED );
49627  *pnPage = (int)pPager->dbSize;
49628 }
49629 
49630 
49631 /*
49632 ** Try to obtain a lock of type locktype on the database file. If
49633 ** a similar or greater lock is already held, this function is a no-op
49634 ** (returning SQLITE_OK immediately).
49635 **
49636 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
49637 ** the busy callback if the lock is currently not available. Repeat
49638 ** until the busy callback returns false or until the attempt to
49639 ** obtain the lock succeeds.
49640 **
49641 ** Return SQLITE_OK on success and an error code if we cannot obtain
49642 ** the lock. If the lock is obtained successfully, set the Pager.state
49643 ** variable to locktype before returning.
49644 */
49645 static int pager_wait_on_lock(Pager *pPager, int locktype){
49646  int rc; /* Return code */
49647 
49648  /* Check that this is either a no-op (because the requested lock is
49649  ** already held), or one of the transitions that the busy-handler
49650  ** may be invoked during, according to the comment above
49651  ** sqlite3PagerSetBusyhandler().
49652  */
49653  assert( (pPager->eLock>=locktype)
49654  || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
49655  || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
49656  );
49657 
49658  do {
49659  rc = pagerLockDb(pPager, locktype);
49660  }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
49661  return rc;
49662 }
49663 
49664 /*
49665 ** Function assertTruncateConstraint(pPager) checks that one of the
49666 ** following is true for all dirty pages currently in the page-cache:
49667 **
49668 ** a) The page number is less than or equal to the size of the
49669 ** current database image, in pages, OR
49670 **
49671 ** b) if the page content were written at this time, it would not
49672 ** be necessary to write the current content out to the sub-journal
49673 ** (as determined by function subjRequiresPage()).
49674 **
49675 ** If the condition asserted by this function were not true, and the
49676 ** dirty page were to be discarded from the cache via the pagerStress()
49677 ** routine, pagerStress() would not write the current page content to
49678 ** the database file. If a savepoint transaction were rolled back after
49679 ** this happened, the correct behavior would be to restore the current
49680 ** content of the page. However, since this content is not present in either
49681 ** the database file or the portion of the rollback journal and
49682 ** sub-journal rolled back the content could not be restored and the
49683 ** database image would become corrupt. It is therefore fortunate that
49684 ** this circumstance cannot arise.
49685 */
49686 #if defined(SQLITE_DEBUG)
49687 static void assertTruncateConstraintCb(PgHdr *pPg){
49688  assert( pPg->flags&PGHDR_DIRTY );
49689  assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
49690 }
49691 static void assertTruncateConstraint(Pager *pPager){
49692  sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
49693 }
49694 #else
49695 # define assertTruncateConstraint(pPager)
49696 #endif
49697 
49698 /*
49699 ** Truncate the in-memory database file image to nPage pages. This
49700 ** function does not actually modify the database file on disk. It
49701 ** just sets the internal state of the pager object so that the
49702 ** truncation will be done when the current transaction is committed.
49703 **
49704 ** This function is only called right before committing a transaction.
49705 ** Once this function has been called, the transaction must either be
49706 ** rolled back or committed. It is not safe to call this function and
49707 ** then continue writing to the database.
49708 */
49710  assert( pPager->dbSize>=nPage );
49711  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
49712  pPager->dbSize = nPage;
49713 
49714  /* At one point the code here called assertTruncateConstraint() to
49715  ** ensure that all pages being truncated away by this operation are,
49716  ** if one or more savepoints are open, present in the savepoint
49717  ** journal so that they can be restored if the savepoint is rolled
49718  ** back. This is no longer necessary as this function is now only
49719  ** called right before committing a transaction. So although the
49720  ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
49721  ** they cannot be rolled back. So the assertTruncateConstraint() call
49722  ** is no longer correct. */
49723 }
49724 
49725 
49726 /*
49727 ** This function is called before attempting a hot-journal rollback. It
49728 ** syncs the journal file to disk, then sets pPager->journalHdr to the
49729 ** size of the journal file so that the pager_playback() routine knows
49730 ** that the entire journal file has been synced.
49731 **
49732 ** Syncing a hot-journal to disk before attempting to roll it back ensures
49733 ** that if a power-failure occurs during the rollback, the process that
49734 ** attempts rollback following system recovery sees the same journal
49735 ** content as this process.
49736 **
49737 ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
49738 ** an SQLite error code.
49739 */
49740 static int pagerSyncHotJournal(Pager *pPager){
49741  int rc = SQLITE_OK;
49742  if( !pPager->noSync ){
49743  rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
49744  }
49745  if( rc==SQLITE_OK ){
49746  rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
49747  }
49748  return rc;
49749 }
49750 
49751 /*
49752 ** Obtain a reference to a memory mapped page object for page number pgno.
49753 ** The new object will use the pointer pData, obtained from xFetch().
49754 ** If successful, set *ppPage to point to the new page reference
49755 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
49756 ** *ppPage to zero.
49757 **
49758 ** Page references obtained by calling this function should be released
49759 ** by calling pagerReleaseMapPage().
49760 */
49762  Pager *pPager, /* Pager object */
49763  Pgno pgno, /* Page number */
49764  void *pData, /* xFetch()'d data for this page */
49765  PgHdr **ppPage /* OUT: Acquired page object */
49766 ){
49767  PgHdr *p; /* Memory mapped page to return */
49768 
49769  if( pPager->pMmapFreelist ){
49770  *ppPage = p = pPager->pMmapFreelist;
49771  pPager->pMmapFreelist = p->pDirty;
49772  p->pDirty = 0;
49773  memset(p->pExtra, 0, pPager->nExtra);
49774  }else{
49775  *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
49776  if( p==0 ){
49777  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
49778  return SQLITE_NOMEM_BKPT;
49779  }
49780  p->pExtra = (void *)&p[1];
49781  p->flags = PGHDR_MMAP;
49782  p->nRef = 1;
49783  p->pPager = pPager;
49784  }
49785 
49786  assert( p->pExtra==(void *)&p[1] );
49787  assert( p->pPage==0 );
49788  assert( p->flags==PGHDR_MMAP );
49789  assert( p->pPager==pPager );
49790  assert( p->nRef==1 );
49791 
49792  p->pgno = pgno;
49793  p->pData = pData;
49794  pPager->nMmapOut++;
49795 
49796  return SQLITE_OK;
49797 }
49798 
49799 /*
49800 ** Release a reference to page pPg. pPg must have been returned by an
49801 ** earlier call to pagerAcquireMapPage().
49802 */
49803 static void pagerReleaseMapPage(PgHdr *pPg){
49804  Pager *pPager = pPg->pPager;
49805  pPager->nMmapOut--;
49806  pPg->pDirty = pPager->pMmapFreelist;
49807  pPager->pMmapFreelist = pPg;
49808 
49809  assert( pPager->fd->pMethods->iVersion>=3 );
49810  sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
49811 }
49812 
49813 /*
49814 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
49815 */
49816 static void pagerFreeMapHdrs(Pager *pPager){
49817  PgHdr *p;
49818  PgHdr *pNext;
49819  for(p=pPager->pMmapFreelist; p; p=pNext){
49820  pNext = p->pDirty;
49821  sqlite3_free(p);
49822  }
49823 }
49824 
49825 
49826 /*
49827 ** Shutdown the page cache. Free all memory and close all files.
49828 **
49829 ** If a transaction was in progress when this routine is called, that
49830 ** transaction is rolled back. All outstanding pages are invalidated
49831 ** and their memory is freed. Any attempt to use a page associated
49832 ** with this page cache after this function returns will likely
49833 ** result in a coredump.
49834 **
49835 ** This function always succeeds. If a transaction is active an attempt
49836 ** is made to roll it back. If an error occurs during the rollback
49837 ** a hot journal may be left in the filesystem but no error is returned
49838 ** to the caller.
49839 */
49841  u8 *pTmp = (u8 *)pPager->pTmpSpace;
49842 
49843  assert( assert_pager_state(pPager) );
49846  pagerFreeMapHdrs(pPager);
49847  /* pPager->errCode = 0; */
49848  pPager->exclusiveMode = 0;
49849 #ifndef SQLITE_OMIT_WAL
49850  sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
49851  pPager->pWal = 0;
49852 #endif
49853  pager_reset(pPager);
49854  if( MEMDB ){
49855  pager_unlock(pPager);
49856  }else{
49857  /* If it is open, sync the journal file before calling UnlockAndRollback.
49858  ** If this is not done, then an unsynced portion of the open journal
49859  ** file may be played back into the database. If a power failure occurs
49860  ** while this is happening, the database could become corrupt.
49861  **
49862  ** If an error occurs while trying to sync the journal, shift the pager
49863  ** into the ERROR state. This causes UnlockAndRollback to unlock the
49864  ** database and close the journal file without attempting to roll it
49865  ** back or finalize it. The next database user will have to do hot-journal
49866  ** rollback before accessing the database file.
49867  */
49868  if( isOpen(pPager->jfd) ){
49869  pager_error(pPager, pagerSyncHotJournal(pPager));
49870  }
49871  pagerUnlockAndRollback(pPager);
49872  }
49875  PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
49876  IOTRACE(("CLOSE %p\n", pPager))
49877  sqlite3OsClose(pPager->jfd);
49878  sqlite3OsClose(pPager->fd);
49879  sqlite3PageFree(pTmp);
49880  sqlite3PcacheClose(pPager->pPCache);
49881 
49882 #ifdef SQLITE_HAS_CODEC
49883  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
49884 #endif
49885 
49886  assert( !pPager->aSavepoint && !pPager->pInJournal );
49887  assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
49888 
49889  sqlite3_free(pPager);
49890  return SQLITE_OK;
49891 }
49892 
49893 #if !defined(NDEBUG) || defined(SQLITE_TEST)
49894 /*
49895 ** Return the page number for page pPg.
49896 */
49897 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
49898  return pPg->pgno;
49899 }
49900 #endif
49901 
49902 /*
49903 ** Increment the reference count for page pPg.
49904 */
49906  sqlite3PcacheRef(pPg);
49907 }
49908 
49909 /*
49910 ** Sync the journal. In other words, make sure all the pages that have
49911 ** been written to the journal have actually reached the surface of the
49912 ** disk and can be restored in the event of a hot-journal rollback.
49913 **
49914 ** If the Pager.noSync flag is set, then this function is a no-op.
49915 ** Otherwise, the actions required depend on the journal-mode and the
49916 ** device characteristics of the file-system, as follows:
49917 **
49918 ** * If the journal file is an in-memory journal file, no action need
49919 ** be taken.
49920 **
49921 ** * Otherwise, if the device does not support the SAFE_APPEND property,
49922 ** then the nRec field of the most recently written journal header
49923 ** is updated to contain the number of journal records that have
49924 ** been written following it. If the pager is operating in full-sync
49925 ** mode, then the journal file is synced before this field is updated.
49926 **
49927 ** * If the device does not support the SEQUENTIAL property, then
49928 ** journal file is synced.
49929 **
49930 ** Or, in pseudo-code:
49931 **
49932 ** if( NOT <in-memory journal> ){
49933 ** if( NOT SAFE_APPEND ){
49934 ** if( <full-sync mode> ) xSync(<journal file>);
49935 ** <update nRec field>
49936 ** }
49937 ** if( NOT SEQUENTIAL ) xSync(<journal file>);
49938 ** }
49939 **
49940 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
49941 ** page currently held in memory before returning SQLITE_OK. If an IO
49942 ** error is encountered, then the IO error code is returned to the caller.
49943 */
49944 static int syncJournal(Pager *pPager, int newHdr){
49945  int rc; /* Return code */
49946 
49948  || pPager->eState==PAGER_WRITER_DBMOD
49949  );
49950  assert( assert_pager_state(pPager) );
49951  assert( !pagerUseWal(pPager) );
49952 
49953  rc = sqlite3PagerExclusiveLock(pPager);
49954  if( rc!=SQLITE_OK ) return rc;
49955 
49956  if( !pPager->noSync ){
49957  assert( !pPager->tempFile );
49958  if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
49959  const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
49960  assert( isOpen(pPager->jfd) );
49961 
49962  if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
49963  /* This block deals with an obscure problem. If the last connection
49964  ** that wrote to this database was operating in persistent-journal
49965  ** mode, then the journal file may at this point actually be larger
49966  ** than Pager.journalOff bytes. If the next thing in the journal
49967  ** file happens to be a journal-header (written as part of the
49968  ** previous connection's transaction), and a crash or power-failure
49969  ** occurs after nRec is updated but before this connection writes
49970  ** anything else to the journal file (or commits/rolls back its
49971  ** transaction), then SQLite may become confused when doing the
49972  ** hot-journal rollback following recovery. It may roll back all
49973  ** of this connections data, then proceed to rolling back the old,
49974  ** out-of-date data that follows it. Database corruption.
49975  **
49976  ** To work around this, if the journal file does appear to contain
49977  ** a valid header following Pager.journalOff, then write a 0x00
49978  ** byte to the start of it to prevent it from being recognized.
49979  **
49980  ** Variable iNextHdrOffset is set to the offset at which this
49981  ** problematic header will occur, if it exists. aMagic is used
49982  ** as a temporary buffer to inspect the first couple of bytes of
49983  ** the potential journal header.
49984  */
49985  i64 iNextHdrOffset;
49986  u8 aMagic[8];
49987  u8 zHeader[sizeof(aJournalMagic)+4];
49988 
49989  memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
49990  put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
49991 
49992  iNextHdrOffset = journalHdrOffset(pPager);
49993  rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
49994  if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
49995  static const u8 zerobyte = 0;
49996  rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
49997  }
49998  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
49999  return rc;
50000  }
50001 
50002  /* Write the nRec value into the journal file header. If in
50003  ** full-synchronous mode, sync the journal first. This ensures that
50004  ** all data has really hit the disk before nRec is updated to mark
50005  ** it as a candidate for rollback.
50006  **
50007  ** This is not required if the persistent media supports the
50008  ** SAFE_APPEND property. Because in this case it is not possible
50009  ** for garbage data to be appended to the file, the nRec field
50010  ** is populated with 0xFFFFFFFF when the journal header is written
50011  ** and never needs to be updated.
50012  */
50013  if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50014  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50015  IOTRACE(("JSYNC %p\n", pPager))
50016  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
50017  if( rc!=SQLITE_OK ) return rc;
50018  }
50019  IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
50020  rc = sqlite3OsWrite(
50021  pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
50022  );
50023  if( rc!=SQLITE_OK ) return rc;
50024  }
50025  if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
50026  PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
50027  IOTRACE(("JSYNC %p\n", pPager))
50028  rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
50030  );
50031  if( rc!=SQLITE_OK ) return rc;
50032  }
50033 
50034  pPager->journalHdr = pPager->journalOff;
50035  if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
50036  pPager->nRec = 0;
50037  rc = writeJournalHdr(pPager);
50038  if( rc!=SQLITE_OK ) return rc;
50039  }
50040  }else{
50041  pPager->journalHdr = pPager->journalOff;
50042  }
50043  }
50044 
50045  /* Unless the pager is in noSync mode, the journal file was just
50046  ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
50047  ** all pages.
50048  */
50050  pPager->eState = PAGER_WRITER_DBMOD;
50051  assert( assert_pager_state(pPager) );
50052  return SQLITE_OK;
50053 }
50054 
50055 /*
50056 ** The argument is the first in a linked list of dirty pages connected
50057 ** by the PgHdr.pDirty pointer. This function writes each one of the
50058 ** in-memory pages in the list to the database file. The argument may
50059 ** be NULL, representing an empty list. In this case this function is
50060 ** a no-op.
50061 **
50062 ** The pager must hold at least a RESERVED lock when this function
50063 ** is called. Before writing anything to the database file, this lock
50064 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
50065 ** SQLITE_BUSY is returned and no data is written to the database file.
50066 **
50067 ** If the pager is a temp-file pager and the actual file-system file
50068 ** is not yet open, it is created and opened before any data is
50069 ** written out.
50070 **
50071 ** Once the lock has been upgraded and, if necessary, the file opened,
50072 ** the pages are written out to the database file in list order. Writing
50073 ** a page is skipped if it meets either of the following criteria:
50074 **
50075 ** * The page number is greater than Pager.dbSize, or
50076 ** * The PGHDR_DONT_WRITE flag is set on the page.
50077 **
50078 ** If writing out a page causes the database file to grow, Pager.dbFileSize
50079 ** is updated accordingly. If page 1 is written out, then the value cached
50080 ** in Pager.dbFileVers[] is updated to match the new value stored in
50081 ** the database file.
50082 **
50083 ** If everything is successful, SQLITE_OK is returned. If an IO error
50084 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
50085 ** be obtained, SQLITE_BUSY is returned.
50086 */
50087 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
50088  int rc = SQLITE_OK; /* Return code */
50089 
50090  /* This function is only called for rollback pagers in WRITER_DBMOD state. */
50091  assert( !pagerUseWal(pPager) );
50092  assert( pPager->tempFile || pPager->eState==PAGER_WRITER_DBMOD );
50093  assert( pPager->eLock==EXCLUSIVE_LOCK );
50094  assert( isOpen(pPager->fd) || pList->pDirty==0 );
50095 
50096  /* If the file is a temp-file has not yet been opened, open it now. It
50097  ** is not possible for rc to be other than SQLITE_OK if this branch
50098  ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
50099  */
50100  if( !isOpen(pPager->fd) ){
50101  assert( pPager->tempFile && rc==SQLITE_OK );
50102  rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
50103  }
50104 
50105  /* Before the first write, give the VFS a hint of what the final
50106  ** file size will be.
50107  */
50108  assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
50109  if( rc==SQLITE_OK
50110  && pPager->dbHintSize<pPager->dbSize
50111  && (pList->pDirty || pList->pgno>pPager->dbHintSize)
50112  ){
50113  sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
50115  pPager->dbHintSize = pPager->dbSize;
50116  }
50117 
50118  while( rc==SQLITE_OK && pList ){
50119  Pgno pgno = pList->pgno;
50120 
50121  /* If there are dirty pages in the page cache with page numbers greater
50122  ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
50123  ** make the file smaller (presumably by auto-vacuum code). Do not write
50124  ** any such pages to the file.
50125  **
50126  ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
50127  ** set (set by sqlite3PagerDontWrite()).
50128  */
50129  if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
50130  i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
50131  char *pData; /* Data to write */
50132 
50133  assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
50134  if( pList->pgno==1 ) pager_write_changecounter(pList);
50135 
50136  /* Encode the database */
50137  CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM_BKPT, pData);
50138 
50139  /* Write out the page data. */
50140  rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
50141 
50142  /* If page 1 was just written, update Pager.dbFileVers to match
50143  ** the value now stored in the database file. If writing this
50144  ** page caused the database file to grow, update dbFileSize.
50145  */
50146  if( pgno==1 ){
50147  memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
50148  }
50149  if( pgno>pPager->dbFileSize ){
50150  pPager->dbFileSize = pgno;
50151  }
50152  pPager->aStat[PAGER_STAT_WRITE]++;
50153 
50154  /* Update any backup objects copying the contents of this pager. */
50155  sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
50156 
50157  PAGERTRACE(("STORE %d page %d hash(%08x)\n",
50158  PAGERID(pPager), pgno, pager_pagehash(pList)));
50159  IOTRACE(("PGOUT %p %d\n", pPager, pgno));
50160  PAGER_INCR(sqlite3_pager_writedb_count);
50161  }else{
50162  PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
50163  }
50164  pager_set_pagehash(pList);
50165  pList = pList->pDirty;
50166  }
50167 
50168  return rc;
50169 }
50170 
50171 /*
50172 ** Ensure that the sub-journal file is open. If it is already open, this
50173 ** function is a no-op.
50174 **
50175 ** SQLITE_OK is returned if everything goes according to plan. An
50176 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
50177 ** fails.
50178 */
50179 static int openSubJournal(Pager *pPager){
50180  int rc = SQLITE_OK;
50181  if( !isOpen(pPager->sjfd) ){
50182  const int flags = SQLITE_OPEN_SUBJOURNAL | SQLITE_OPEN_READWRITE
50185  int nStmtSpill = sqlite3Config.nStmtSpill;
50186  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
50187  nStmtSpill = -1;
50188  }
50189  rc = sqlite3JournalOpen(pPager->pVfs, 0, pPager->sjfd, flags, nStmtSpill);
50190  }
50191  return rc;
50192 }
50193 
50194 /*
50195 ** Append a record of the current state of page pPg to the sub-journal.
50196 **
50197 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
50198 ** for all open savepoints before returning.
50199 **
50200 ** This function returns SQLITE_OK if everything is successful, an IO
50201 ** error code if the attempt to write to the sub-journal fails, or
50202 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
50203 ** bitvec.
50204 */
50205 static int subjournalPage(PgHdr *pPg){
50206  int rc = SQLITE_OK;
50207  Pager *pPager = pPg->pPager;
50208  if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
50209 
50210  /* Open the sub-journal, if it has not already been opened */
50211  assert( pPager->useJournal );
50212  assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
50213  assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
50214  assert( pagerUseWal(pPager)
50215  || pageInJournal(pPager, pPg)
50216  || pPg->pgno>pPager->dbOrigSize
50217  );
50218  rc = openSubJournal(pPager);
50219 
50220  /* If the sub-journal was opened successfully (or was already open),
50221  ** write the journal record into the file. */
50222  if( rc==SQLITE_OK ){
50223  void *pData = pPg->pData;
50224  i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
50225  char *pData2;
50226 
50227  CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
50228  PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
50229  rc = write32bits(pPager->sjfd, offset, pPg->pgno);
50230  if( rc==SQLITE_OK ){
50231  rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
50232  }
50233  }
50234  }
50235  if( rc==SQLITE_OK ){
50236  pPager->nSubRec++;
50237  assert( pPager->nSavepoint>0 );
50238  rc = addToSavepointBitvecs(pPager, pPg->pgno);
50239  }
50240  return rc;
50241 }
50243  if( subjRequiresPage(pPg) ){
50244  return subjournalPage(pPg);
50245  }else{
50246  return SQLITE_OK;
50247  }
50248 }
50249 
50250 /*
50251 ** This function is called by the pcache layer when it has reached some
50252 ** soft memory limit. The first argument is a pointer to a Pager object
50253 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
50254 ** database). The second argument is a reference to a page that is
50255 ** currently dirty but has no outstanding references. The page
50256 ** is always associated with the Pager object passed as the first
50257 ** argument.
50258 **
50259 ** The job of this function is to make pPg clean by writing its contents
50260 ** out to the database file, if possible. This may involve syncing the
50261 ** journal file.
50262 **
50263 ** If successful, sqlite3PcacheMakeClean() is called on the page and
50264 ** SQLITE_OK returned. If an IO error occurs while trying to make the
50265 ** page clean, the IO error code is returned. If the page cannot be
50266 ** made clean for some other reason, but no error occurs, then SQLITE_OK
50267 ** is returned by sqlite3PcacheMakeClean() is not called.
50268 */
50269 static int pagerStress(void *p, PgHdr *pPg){
50270  Pager *pPager = (Pager *)p;
50271  int rc = SQLITE_OK;
50272 
50273  assert( pPg->pPager==pPager );
50274  assert( pPg->flags&PGHDR_DIRTY );
50275 
50276  /* The doNotSpill NOSYNC bit is set during times when doing a sync of
50277  ** journal (and adding a new header) is not allowed. This occurs
50278  ** during calls to sqlite3PagerWrite() while trying to journal multiple
50279  ** pages belonging to the same sector.
50280  **
50281  ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
50282  ** regardless of whether or not a sync is required. This is set during
50283  ** a rollback or by user request, respectively.
50284  **
50285  ** Spilling is also prohibited when in an error state since that could
50286  ** lead to database corruption. In the current implementation it
50287  ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
50288  ** while in the error state, hence it is impossible for this routine to
50289  ** be called in the error state. Nevertheless, we include a NEVER()
50290  ** test for the error state as a safeguard against future changes.
50291  */
50292  if( NEVER(pPager->errCode) ) return SQLITE_OK;
50293  testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
50294  testcase( pPager->doNotSpill & SPILLFLAG_OFF );
50295  testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
50296  if( pPager->doNotSpill
50297  && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
50298  || (pPg->flags & PGHDR_NEED_SYNC)!=0)
50299  ){
50300  return SQLITE_OK;
50301  }
50302 
50303  pPg->pDirty = 0;
50304  if( pagerUseWal(pPager) ){
50305  /* Write a single frame for this page to the log. */
50306  rc = subjournalPageIfRequired(pPg);
50307  if( rc==SQLITE_OK ){
50308  rc = pagerWalFrames(pPager, pPg, 0, 0);
50309  }
50310  }else{
50311 
50312  /* Sync the journal file if required. */
50313  if( pPg->flags&PGHDR_NEED_SYNC
50314  || pPager->eState==PAGER_WRITER_CACHEMOD
50315  ){
50316  rc = syncJournal(pPager, 1);
50317  }
50318 
50319  /* Write the contents of the page out to the database file. */
50320  if( rc==SQLITE_OK ){
50321  assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
50322  rc = pager_write_pagelist(pPager, pPg);
50323  }
50324  }
50325 
50326  /* Mark the page as clean. */
50327  if( rc==SQLITE_OK ){
50328  PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
50330  }
50331 
50332  return pager_error(pPager, rc);
50333 }
50334 
50335 /*
50336 ** Flush all unreferenced dirty pages to disk.
50337 */
50339  int rc = pPager->errCode;
50340  if( !MEMDB ){
50341  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
50342  assert( assert_pager_state(pPager) );
50343  while( rc==SQLITE_OK && pList ){
50344  PgHdr *pNext = pList->pDirty;
50345  if( pList->nRef==0 ){
50346  rc = pagerStress((void*)pPager, pList);
50347  }
50348  pList = pNext;
50349  }
50350  }
50351 
50352  return rc;
50353 }
50354 
50355 /*
50356 ** Allocate and initialize a new Pager object and put a pointer to it
50357 ** in *ppPager. The pager should eventually be freed by passing it
50358 ** to sqlite3PagerClose().
50359 **
50360 ** The zFilename argument is the path to the database file to open.
50361 ** If zFilename is NULL then a randomly-named temporary file is created
50362 ** and used as the file to be cached. Temporary files are be deleted
50363 ** automatically when they are closed. If zFilename is ":memory:" then
50364 ** all information is held in cache. It is never written to disk.
50365 ** This can be used to implement an in-memory database.
50366 **
50367 ** The nExtra parameter specifies the number of bytes of space allocated
50368 ** along with each page reference. This space is available to the user
50369 ** via the sqlite3PagerGetExtra() API.
50370 **
50371 ** The flags argument is used to specify properties that affect the
50372 ** operation of the pager. It should be passed some bitwise combination
50373 ** of the PAGER_* flags.
50374 **
50375 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
50376 ** of the xOpen() method of the supplied VFS when opening files.
50377 **
50378 ** If the pager object is allocated and the specified file opened
50379 ** successfully, SQLITE_OK is returned and *ppPager set to point to
50380 ** the new pager object. If an error occurs, *ppPager is set to NULL
50381 ** and error code returned. This function may return SQLITE_NOMEM
50382 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
50383 ** various SQLITE_IO_XXX errors.
50384 */
50386  sqlite3_vfs *pVfs, /* The virtual file system to use */
50387  Pager **ppPager, /* OUT: Return the Pager structure here */
50388  const char *zFilename, /* Name of the database file to open */
50389  int nExtra, /* Extra bytes append to each in-memory page */
50390  int flags, /* flags controlling this file */
50391  int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
50392  void (*xReinit)(DbPage*) /* Function to reinitialize pages */
50393 ){
50394  u8 *pPtr;
50395  Pager *pPager = 0; /* Pager object to allocate and return */
50396  int rc = SQLITE_OK; /* Return code */
50397  int tempFile = 0; /* True for temp files (incl. in-memory files) */
50398  int memDb = 0; /* True if this is an in-memory file */
50399  int readOnly = 0; /* True if this is a read-only file */
50400  int journalFileSize; /* Bytes to allocate for each journal fd */
50401  char *zPathname = 0; /* Full path to database file */
50402  int nPathname = 0; /* Number of bytes in zPathname */
50403  int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
50404  int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
50405  u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
50406  const char *zUri = 0; /* URI args to copy */
50407  int nUri = 0; /* Number of bytes of URI args at *zUri */
50408 
50409  /* Figure out how much space is required for each journal file-handle
50410  ** (there are two of them, the main journal and the sub-journal). */
50411  journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
50412 
50413  /* Set the output variable to NULL in case an error occurs. */
50414  *ppPager = 0;
50415 
50416 #ifndef SQLITE_OMIT_MEMORYDB
50417  if( flags & PAGER_MEMORY ){
50418  memDb = 1;
50419  if( zFilename && zFilename[0] ){
50420  zPathname = sqlite3DbStrDup(0, zFilename);
50421  if( zPathname==0 ) return SQLITE_NOMEM_BKPT;
50422  nPathname = sqlite3Strlen30(zPathname);
50423  zFilename = 0;
50424  }
50425  }
50426 #endif
50427 
50428  /* Compute and store the full pathname in an allocated buffer pointed
50429  ** to by zPathname, length nPathname. Or, if this is a temporary file,
50430  ** leave both nPathname and zPathname set to 0.
50431  */
50432  if( zFilename && zFilename[0] ){
50433  const char *z;
50434  nPathname = pVfs->mxPathname+1;
50435  zPathname = sqlite3DbMallocRaw(0, nPathname*2);
50436  if( zPathname==0 ){
50437  return SQLITE_NOMEM_BKPT;
50438  }
50439  zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
50440  rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
50441  nPathname = sqlite3Strlen30(zPathname);
50442  z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
50443  while( *z ){
50444  z += sqlite3Strlen30(z)+1;
50445  z += sqlite3Strlen30(z)+1;
50446  }
50447  nUri = (int)(&z[1] - zUri);
50448  assert( nUri>=0 );
50449  if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
50450  /* This branch is taken when the journal path required by
50451  ** the database being opened will be more than pVfs->mxPathname
50452  ** bytes in length. This means the database cannot be opened,
50453  ** as it will not be possible to open the journal file or even
50454  ** check for a hot-journal before reading.
50455  */
50456  rc = SQLITE_CANTOPEN_BKPT;
50457  }
50458  if( rc!=SQLITE_OK ){
50459  sqlite3DbFree(0, zPathname);
50460  return rc;
50461  }
50462  }
50463 
50464  /* Allocate memory for the Pager structure, PCache object, the
50465  ** three file descriptors, the database file name and the journal
50466  ** file name. The layout in memory is as follows:
50467  **
50468  ** Pager object (sizeof(Pager) bytes)
50469  ** PCache object (sqlite3PcacheSize() bytes)
50470  ** Database file handle (pVfs->szOsFile bytes)
50471  ** Sub-journal file handle (journalFileSize bytes)
50472  ** Main journal file handle (journalFileSize bytes)
50473  ** Database file name (nPathname+1 bytes)
50474  ** Journal file name (nPathname+8+1 bytes)
50475  */
50476  pPtr = (u8 *)sqlite3MallocZero(
50477  ROUND8(sizeof(*pPager)) + /* Pager structure */
50478  ROUND8(pcacheSize) + /* PCache object */
50479  ROUND8(pVfs->szOsFile) + /* The main db file */
50480  journalFileSize * 2 + /* The two journal files */
50481  nPathname + 1 + nUri + /* zFilename */
50482  nPathname + 8 + 2 /* zJournal */
50483 #ifndef SQLITE_OMIT_WAL
50484  + nPathname + 4 + 2 /* zWal */
50485 #endif
50486  );
50487  assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
50488  if( !pPtr ){
50489  sqlite3DbFree(0, zPathname);
50490  return SQLITE_NOMEM_BKPT;
50491  }
50492  pPager = (Pager*)(pPtr);
50493  pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
50494  pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
50495  pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
50496  pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
50497  pPager->zFilename = (char*)(pPtr += journalFileSize);
50498  assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
50499 
50500  /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
50501  if( zPathname ){
50502  assert( nPathname>0 );
50503  pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
50504  memcpy(pPager->zFilename, zPathname, nPathname);
50505  if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
50506  memcpy(pPager->zJournal, zPathname, nPathname);
50507  memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
50508  sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
50509 #ifndef SQLITE_OMIT_WAL
50510  pPager->zWal = &pPager->zJournal[nPathname+8+1];
50511  memcpy(pPager->zWal, zPathname, nPathname);
50512  memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
50513  sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
50514 #endif
50515  sqlite3DbFree(0, zPathname);
50516  }
50517  pPager->pVfs = pVfs;
50518  pPager->vfsFlags = vfsFlags;
50519 
50520  /* Open the pager file.
50521  */
50522  if( zFilename && zFilename[0] ){
50523  int fout = 0; /* VFS flags returned by xOpen() */
50524  rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
50525  assert( !memDb );
50526  readOnly = (fout&SQLITE_OPEN_READONLY);
50527 
50528  /* If the file was successfully opened for read/write access,
50529  ** choose a default page size in case we have to create the
50530  ** database file. The default page size is the maximum of:
50531  **
50532  ** + SQLITE_DEFAULT_PAGE_SIZE,
50533  ** + The value returned by sqlite3OsSectorSize()
50534  ** + The largest page size that can be written atomically.
50535  */
50536  if( rc==SQLITE_OK ){
50537  int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
50538  if( !readOnly ){
50539  setSectorSize(pPager);
50541  if( szPageDflt<pPager->sectorSize ){
50543  szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
50544  }else{
50545  szPageDflt = (u32)pPager->sectorSize;
50546  }
50547  }
50548 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
50549  {
50550  int ii;
50551  assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
50552  assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
50554  for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
50555  if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
50556  szPageDflt = ii;
50557  }
50558  }
50559  }
50560 #endif
50561  }
50562  pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
50563  if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
50564  || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
50565  vfsFlags |= SQLITE_OPEN_READONLY;
50566  goto act_like_temp_file;
50567  }
50568  }
50569  }else{
50570  /* If a temporary file is requested, it is not opened immediately.
50571  ** In this case we accept the default page size and delay actually
50572  ** opening the file until the first call to OsWrite().
50573  **
50574  ** This branch is also run for an in-memory database. An in-memory
50575  ** database is the same as a temp-file that is never written out to
50576  ** disk and uses an in-memory rollback journal.
50577  **
50578  ** This branch also runs for files marked as immutable.
50579  */
50580 act_like_temp_file:
50581  tempFile = 1;
50582  pPager->eState = PAGER_READER; /* Pretend we already have a lock */
50583  pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE mode */
50584  pPager->noLock = 1; /* Do no locking */
50585  readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
50586  }
50587 
50588  /* The following call to PagerSetPagesize() serves to set the value of
50589  ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
50590  */
50591  if( rc==SQLITE_OK ){
50592  assert( pPager->memDb==0 );
50593  rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
50594  testcase( rc!=SQLITE_OK );
50595  }
50596 
50597  /* Initialize the PCache object. */
50598  if( rc==SQLITE_OK ){
50599  assert( nExtra<1000 );
50600  nExtra = ROUND8(nExtra);
50601  rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
50602  !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
50603  }
50604 
50605  /* If an error occurred above, free the Pager structure and close the file.
50606  */
50607  if( rc!=SQLITE_OK ){
50608  sqlite3OsClose(pPager->fd);
50609  sqlite3PageFree(pPager->pTmpSpace);
50610  sqlite3_free(pPager);
50611  return rc;
50612  }
50613 
50614  PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
50615  IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
50616 
50617  pPager->useJournal = (u8)useJournal;
50618  /* pPager->stmtOpen = 0; */
50619  /* pPager->stmtInUse = 0; */
50620  /* pPager->nRef = 0; */
50621  /* pPager->stmtSize = 0; */
50622  /* pPager->stmtJSize = 0; */
50623  /* pPager->nPage = 0; */
50624  pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
50625  /* pPager->state = PAGER_UNLOCK; */
50626  /* pPager->errMask = 0; */
50627  pPager->tempFile = (u8)tempFile;
50628  assert( tempFile==PAGER_LOCKINGMODE_NORMAL
50629  || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
50631  pPager->exclusiveMode = (u8)tempFile;
50632  pPager->changeCountDone = pPager->tempFile;
50633  pPager->memDb = (u8)memDb;
50634  pPager->readOnly = (u8)readOnly;
50635  assert( useJournal || pPager->tempFile );
50636  pPager->noSync = pPager->tempFile;
50637  if( pPager->noSync ){
50638  assert( pPager->fullSync==0 );
50639  assert( pPager->extraSync==0 );
50640  assert( pPager->syncFlags==0 );
50641  assert( pPager->walSyncFlags==0 );
50642  assert( pPager->ckptSyncFlags==0 );
50643  }else{
50644  pPager->fullSync = 1;
50645  pPager->extraSync = 0;
50646  pPager->syncFlags = SQLITE_SYNC_NORMAL;
50649  }
50650  /* pPager->pFirst = 0; */
50651  /* pPager->pFirstSynced = 0; */
50652  /* pPager->pLast = 0; */
50653  pPager->nExtra = (u16)nExtra;
50655  assert( isOpen(pPager->fd) || tempFile );
50656  setSectorSize(pPager);
50657  if( !useJournal ){
50659  }else if( memDb ){
50661  }
50662  /* pPager->xBusyHandler = 0; */
50663  /* pPager->pBusyHandlerArg = 0; */
50664  pPager->xReiniter = xReinit;
50665  /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
50666  /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
50667 
50668  *ppPager = pPager;
50669  return SQLITE_OK;
50670 }
50671 
50672 
50673 /* Verify that the database file has not be deleted or renamed out from
50674 ** under the pager. Return SQLITE_OK if the database is still were it ought
50675 ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
50676 ** code from sqlite3OsAccess()) if the database has gone missing.
50677 */
50678 static int databaseIsUnmoved(Pager *pPager){
50679  int bHasMoved = 0;
50680  int rc;
50681 
50682  if( pPager->tempFile ) return SQLITE_OK;
50683  if( pPager->dbSize==0 ) return SQLITE_OK;
50684  assert( pPager->zFilename && pPager->zFilename[0] );
50685  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
50686  if( rc==SQLITE_NOTFOUND ){
50687  /* If the HAS_MOVED file-control is unimplemented, assume that the file
50688  ** has not been moved. That is the historical behavior of SQLite: prior to
50689  ** version 3.8.3, it never checked */
50690  rc = SQLITE_OK;
50691  }else if( rc==SQLITE_OK && bHasMoved ){
50693  }
50694  return rc;
50695 }
50696 
50697 
50698 /*
50699 ** This function is called after transitioning from PAGER_UNLOCK to
50700 ** PAGER_SHARED state. It tests if there is a hot journal present in
50701 ** the file-system for the given pager. A hot journal is one that
50702 ** needs to be played back. According to this function, a hot-journal
50703 ** file exists if the following criteria are met:
50704 **
50705 ** * The journal file exists in the file system, and
50706 ** * No process holds a RESERVED or greater lock on the database file, and
50707 ** * The database file itself is greater than 0 bytes in size, and
50708 ** * The first byte of the journal file exists and is not 0x00.
50709 **
50710 ** If the current size of the database file is 0 but a journal file
50711 ** exists, that is probably an old journal left over from a prior
50712 ** database with the same name. In this case the journal file is
50713 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
50714 ** is returned.
50715 **
50716 ** This routine does not check if there is a master journal filename
50717 ** at the end of the file. If there is, and that master journal file
50718 ** does not exist, then the journal file is not really hot. In this
50719 ** case this routine will return a false-positive. The pager_playback()
50720 ** routine will discover that the journal file is not really hot and
50721 ** will not roll it back.
50722 **
50723 ** If a hot-journal file is found to exist, *pExists is set to 1 and
50724 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
50725 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
50726 ** to determine whether or not a hot-journal file exists, the IO error
50727 ** code is returned and the value of *pExists is undefined.
50728 */
50729 static int hasHotJournal(Pager *pPager, int *pExists){
50730  sqlite3_vfs * const pVfs = pPager->pVfs;
50731  int rc = SQLITE_OK; /* Return code */
50732  int exists = 1; /* True if a journal file is present */
50733  int jrnlOpen = !!isOpen(pPager->jfd);
50734 
50735  assert( pPager->useJournal );
50736  assert( isOpen(pPager->fd) );
50737  assert( pPager->eState==PAGER_OPEN );
50738 
50739  assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
50741  ));
50742 
50743  *pExists = 0;
50744  if( !jrnlOpen ){
50745  rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
50746  }
50747  if( rc==SQLITE_OK && exists ){
50748  int locked = 0; /* True if some process holds a RESERVED lock */
50749 
50750  /* Race condition here: Another process might have been holding the
50751  ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
50752  ** call above, but then delete the journal and drop the lock before
50753  ** we get to the following sqlite3OsCheckReservedLock() call. If that
50754  ** is the case, this routine might think there is a hot journal when
50755  ** in fact there is none. This results in a false-positive which will
50756  ** be dealt with by the playback routine. Ticket #3883.
50757  */
50758  rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
50759  if( rc==SQLITE_OK && !locked ){
50760  Pgno nPage; /* Number of pages in database file */
50761 
50762  assert( pPager->tempFile==0 );
50763  rc = pagerPagecount(pPager, &nPage);
50764  if( rc==SQLITE_OK ){
50765  /* If the database is zero pages in size, that means that either (1) the
50766  ** journal is a remnant from a prior database with the same name where
50767  ** the database file but not the journal was deleted, or (2) the initial
50768  ** transaction that populates a new database is being rolled back.
50769  ** In either case, the journal file can be deleted. However, take care
50770  ** not to delete the journal file if it is already open due to
50771  ** journal_mode=PERSIST.
50772  */
50773  if( nPage==0 && !jrnlOpen ){
50775  if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
50776  sqlite3OsDelete(pVfs, pPager->zJournal, 0);
50777  if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
50778  }
50780  }else{
50781  /* The journal file exists and no other connection has a reserved
50782  ** or greater lock on the database file. Now check that there is
50783  ** at least one non-zero bytes at the start of the journal file.
50784  ** If there is, then we consider this journal to be hot. If not,
50785  ** it can be ignored.
50786  */
50787  if( !jrnlOpen ){
50789  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
50790  }
50791  if( rc==SQLITE_OK ){
50792  u8 first = 0;
50793  rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
50794  if( rc==SQLITE_IOERR_SHORT_READ ){
50795  rc = SQLITE_OK;
50796  }
50797  if( !jrnlOpen ){
50798  sqlite3OsClose(pPager->jfd);
50799  }
50800  *pExists = (first!=0);
50801  }else if( rc==SQLITE_CANTOPEN ){
50802  /* If we cannot open the rollback journal file in order to see if
50803  ** it has a zero header, that might be due to an I/O error, or
50804  ** it might be due to the race condition described above and in
50805  ** ticket #3883. Either way, assume that the journal is hot.
50806  ** This might be a false positive. But if it is, then the
50807  ** automatic journal playback and recovery mechanism will deal
50808  ** with it under an EXCLUSIVE lock where we do not need to
50809  ** worry so much with race conditions.
50810  */
50811  *pExists = 1;
50812  rc = SQLITE_OK;
50813  }
50814  }
50815  }
50816  }
50817  }
50818 
50819  return rc;
50820 }
50821 
50822 /*
50823 ** This function is called to obtain a shared lock on the database file.
50824 ** It is illegal to call sqlite3PagerGet() until after this function
50825 ** has been successfully called. If a shared-lock is already held when
50826 ** this function is called, it is a no-op.
50827 **
50828 ** The following operations are also performed by this function.
50829 **
50830 ** 1) If the pager is currently in PAGER_OPEN state (no lock held
50831 ** on the database file), then an attempt is made to obtain a
50832 ** SHARED lock on the database file. Immediately after obtaining
50833 ** the SHARED lock, the file-system is checked for a hot-journal,
50834 ** which is played back if present. Following any hot-journal
50835 ** rollback, the contents of the cache are validated by checking
50836 ** the 'change-counter' field of the database file header and
50837 ** discarded if they are found to be invalid.
50838 **
50839 ** 2) If the pager is running in exclusive-mode, and there are currently
50840 ** no outstanding references to any pages, and is in the error state,
50841 ** then an attempt is made to clear the error state by discarding
50842 ** the contents of the page cache and rolling back any open journal
50843 ** file.
50844 **
50845 ** If everything is successful, SQLITE_OK is returned. If an IO error
50846 ** occurs while locking the database, checking for a hot-journal file or
50847 ** rolling back a journal file, the IO error code is returned.
50848 */
50850  int rc = SQLITE_OK; /* Return code */
50851 
50852  /* This routine is only called from b-tree and only when there are no
50853  ** outstanding pages. This implies that the pager state should either
50854  ** be OPEN or READER. READER is only possible if the pager is or was in
50855  ** exclusive access mode. */
50856  assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
50857  assert( assert_pager_state(pPager) );
50858  assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
50859  assert( pPager->errCode==SQLITE_OK );
50860 
50861  if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
50862  int bHotJournal = 1; /* True if there exists a hot journal-file */
50863 
50864  assert( !MEMDB );
50865  assert( pPager->tempFile==0 || pPager->eLock==EXCLUSIVE_LOCK );
50866 
50867  rc = pager_wait_on_lock(pPager, SHARED_LOCK);
50868  if( rc!=SQLITE_OK ){
50869  assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
50870  goto failed;
50871  }
50872 
50873  /* If a journal file exists, and there is no RESERVED lock on the
50874  ** database file, then it either needs to be played back or deleted.
50875  */
50876  if( pPager->eLock<=SHARED_LOCK ){
50877  rc = hasHotJournal(pPager, &bHotJournal);
50878  }
50879  if( rc!=SQLITE_OK ){
50880  goto failed;
50881  }
50882  if( bHotJournal ){
50883  if( pPager->readOnly ){
50885  goto failed;
50886  }
50887 
50888  /* Get an EXCLUSIVE lock on the database file. At this point it is
50889  ** important that a RESERVED lock is not obtained on the way to the
50890  ** EXCLUSIVE lock. If it were, another process might open the
50891  ** database file, detect the RESERVED lock, and conclude that the
50892  ** database is safe to read while this process is still rolling the
50893  ** hot-journal back.
50894  **
50895  ** Because the intermediate RESERVED lock is not requested, any
50896  ** other process attempting to access the database file will get to
50897  ** this point in the code and fail to obtain its own EXCLUSIVE lock
50898  ** on the database file.
50899  **
50900  ** Unless the pager is in locking_mode=exclusive mode, the lock is
50901  ** downgraded to SHARED_LOCK before this function returns.
50902  */
50903  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
50904  if( rc!=SQLITE_OK ){
50905  goto failed;
50906  }
50907 
50908  /* If it is not already open and the file exists on disk, open the
50909  ** journal for read/write access. Write access is required because
50910  ** in exclusive-access mode the file descriptor will be kept open
50911  ** and possibly used for a transaction later on. Also, write-access
50912  ** is usually required to finalize the journal in journal_mode=persist
50913  ** mode (and also for journal_mode=truncate on some systems).
50914  **
50915  ** If the journal does not exist, it usually means that some
50916  ** other connection managed to get in and roll it back before
50917  ** this connection obtained the exclusive lock above. Or, it
50918  ** may mean that the pager was in the error-state when this
50919  ** function was called and the journal file does not exist.
50920  */
50921  if( !isOpen(pPager->jfd) ){
50922  sqlite3_vfs * const pVfs = pPager->pVfs;
50923  int bExists; /* True if journal file exists */
50924  rc = sqlite3OsAccess(
50925  pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
50926  if( rc==SQLITE_OK && bExists ){
50927  int fout = 0;
50929  assert( !pPager->tempFile );
50930  rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
50931  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
50932  if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
50933  rc = SQLITE_CANTOPEN_BKPT;
50934  sqlite3OsClose(pPager->jfd);
50935  }
50936  }
50937  }
50938 
50939  /* Playback and delete the journal. Drop the database write
50940  ** lock and reacquire the read lock. Purge the cache before
50941  ** playing back the hot-journal so that we don't end up with
50942  ** an inconsistent cache. Sync the hot journal before playing
50943  ** it back since the process that crashed and left the hot journal
50944  ** probably did not sync it and we are required to always sync
50945  ** the journal before playing it back.
50946  */
50947  if( isOpen(pPager->jfd) ){
50948  assert( rc==SQLITE_OK );
50949  rc = pagerSyncHotJournal(pPager);
50950  if( rc==SQLITE_OK ){
50951  rc = pager_playback(pPager, !pPager->tempFile);
50952  pPager->eState = PAGER_OPEN;
50953  }
50954  }else if( !pPager->exclusiveMode ){
50955  pagerUnlockDb(pPager, SHARED_LOCK);
50956  }
50957 
50958  if( rc!=SQLITE_OK ){
50959  /* This branch is taken if an error occurs while trying to open
50960  ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
50961  ** pager_unlock() routine will be called before returning to unlock
50962  ** the file. If the unlock attempt fails, then Pager.eLock must be
50963  ** set to UNKNOWN_LOCK (see the comment above the #define for
50964  ** UNKNOWN_LOCK above for an explanation).
50965  **
50966  ** In order to get pager_unlock() to do this, set Pager.eState to
50967  ** PAGER_ERROR now. This is not actually counted as a transition
50968  ** to ERROR state in the state diagram at the top of this file,
50969  ** since we know that the same call to pager_unlock() will very
50970  ** shortly transition the pager object to the OPEN state. Calling
50971  ** assert_pager_state() would fail now, as it should not be possible
50972  ** to be in ERROR state when there are zero outstanding page
50973  ** references.
50974  */
50975  pager_error(pPager, rc);
50976  goto failed;
50977  }
50978 
50979  assert( pPager->eState==PAGER_OPEN );
50980  assert( (pPager->eLock==SHARED_LOCK)
50981  || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
50982  );
50983  }
50984 
50985  if( !pPager->tempFile && pPager->hasHeldSharedLock ){
50986  /* The shared-lock has just been acquired then check to
50987  ** see if the database has been modified. If the database has changed,
50988  ** flush the cache. The hasHeldSharedLock flag prevents this from
50989  ** occurring on the very first access to a file, in order to save a
50990  ** single unnecessary sqlite3OsRead() call at the start-up.
50991  **
50992  ** Database changes are detected by looking at 15 bytes beginning
50993  ** at offset 24 into the file. The first 4 of these 16 bytes are
50994  ** a 32-bit counter that is incremented with each change. The
50995  ** other bytes change randomly with each file change when
50996  ** a codec is in use.
50997  **
50998  ** There is a vanishingly small chance that a change will not be
50999  ** detected. The chance of an undetected change is so small that
51000  ** it can be neglected.
51001  */
51002  Pgno nPage = 0;
51003  char dbFileVers[sizeof(pPager->dbFileVers)];
51004 
51005  rc = pagerPagecount(pPager, &nPage);
51006  if( rc ) goto failed;
51007 
51008  if( nPage>0 ){
51009  IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
51010  rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
51011  if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
51012  goto failed;
51013  }
51014  }else{
51015  memset(dbFileVers, 0, sizeof(dbFileVers));
51016  }
51017 
51018  if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
51019  pager_reset(pPager);
51020 
51021  /* Unmap the database file. It is possible that external processes
51022  ** may have truncated the database file and then extended it back
51023  ** to its original size while this process was not holding a lock.
51024  ** In this case there may exist a Pager.pMap mapping that appears
51025  ** to be the right size but is not actually valid. Avoid this
51026  ** possibility by unmapping the db here. */
51027  if( USEFETCH(pPager) ){
51028  sqlite3OsUnfetch(pPager->fd, 0, 0);
51029  }
51030  }
51031  }
51032 
51033  /* If there is a WAL file in the file-system, open this database in WAL
51034  ** mode. Otherwise, the following function call is a no-op.
51035  */
51036  rc = pagerOpenWalIfPresent(pPager);
51037 #ifndef SQLITE_OMIT_WAL
51038  assert( pPager->pWal==0 || rc==SQLITE_OK );
51039 #endif
51040  }
51041 
51042  if( pagerUseWal(pPager) ){
51043  assert( rc==SQLITE_OK );
51044  rc = pagerBeginReadTransaction(pPager);
51045  }
51046 
51047  if( pPager->tempFile==0 && pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
51048  rc = pagerPagecount(pPager, &pPager->dbSize);
51049  }
51050 
51051  failed:
51052  if( rc!=SQLITE_OK ){
51053  assert( !MEMDB );
51054  pager_unlock(pPager);
51055  assert( pPager->eState==PAGER_OPEN );
51056  }else{
51057  pPager->eState = PAGER_READER;
51058  pPager->hasHeldSharedLock = 1;
51059  }
51060  return rc;
51061 }
51062 
51063 /*
51064 ** If the reference count has reached zero, rollback any active
51065 ** transaction and unlock the pager.
51066 **
51067 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
51068 ** the rollback journal, the unlock is not performed and there is
51069 ** nothing to rollback, so this routine is a no-op.
51070 */
51071 static void pagerUnlockIfUnused(Pager *pPager){
51072  if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
51073  pagerUnlockAndRollback(pPager);
51074  }
51075 }
51076 
51077 /*
51078 ** Acquire a reference to page number pgno in pager pPager (a page
51079 ** reference has type DbPage*). If the requested reference is
51080 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
51081 **
51082 ** If the requested page is already in the cache, it is returned.
51083 ** Otherwise, a new page object is allocated and populated with data
51084 ** read from the database file. In some cases, the pcache module may
51085 ** choose not to allocate a new page object and may reuse an existing
51086 ** object with no outstanding references.
51087 **
51088 ** The extra data appended to a page is always initialized to zeros the
51089 ** first time a page is loaded into memory. If the page requested is
51090 ** already in the cache when this function is called, then the extra
51091 ** data is left as it was when the page object was last used.
51092 **
51093 ** If the database image is smaller than the requested page or if a
51094 ** non-zero value is passed as the noContent parameter and the
51095 ** requested page is not already stored in the cache, then no
51096 ** actual disk read occurs. In this case the memory image of the
51097 ** page is initialized to all zeros.
51098 **
51099 ** If noContent is true, it means that we do not care about the contents
51100 ** of the page. This occurs in two scenarios:
51101 **
51102 ** a) When reading a free-list leaf page from the database, and
51103 **
51104 ** b) When a savepoint is being rolled back and we need to load
51105 ** a new page into the cache to be filled with the data read
51106 ** from the savepoint journal.
51107 **
51108 ** If noContent is true, then the data returned is zeroed instead of
51109 ** being read from the database. Additionally, the bits corresponding
51110 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
51111 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
51112 ** savepoints are set. This means if the page is made writable at any
51113 ** point in the future, using a call to sqlite3PagerWrite(), its contents
51114 ** will not be journaled. This saves IO.
51115 **
51116 ** The acquisition might fail for several reasons. In all cases,
51117 ** an appropriate error code is returned and *ppPage is set to NULL.
51118 **
51119 ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
51120 ** to find a page in the in-memory cache first. If the page is not already
51121 ** in memory, this routine goes to disk to read it in whereas Lookup()
51122 ** just returns 0. This routine acquires a read-lock the first time it
51123 ** has to go to disk, and could also playback an old journal if necessary.
51124 ** Since Lookup() never goes to disk, it never has to deal with locks
51125 ** or journal files.
51126 */
51128  Pager *pPager, /* The pager open on the database file */
51129  Pgno pgno, /* Page number to fetch */
51130  DbPage **ppPage, /* Write a pointer to the page here */
51131  int flags /* PAGER_GET_XXX flags */
51132 ){
51133  int rc = SQLITE_OK;
51134  PgHdr *pPg = 0;
51135  u32 iFrame = 0; /* Frame to read from WAL file */
51136  const int noContent = (flags & PAGER_GET_NOCONTENT);
51137 
51138  /* It is acceptable to use a read-only (mmap) page for any page except
51139  ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
51140  ** flag was specified by the caller. And so long as the db is not a
51141  ** temporary or in-memory database. */
51142  const int bMmapOk = (pgno>1 && USEFETCH(pPager)
51143  && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
51144 #ifdef SQLITE_HAS_CODEC
51145  && pPager->xCodec==0
51146 #endif
51147  );
51148 
51149  /* Optimization note: Adding the "pgno<=1" term before "pgno==0" here
51150  ** allows the compiler optimizer to reuse the results of the "pgno>1"
51151  ** test in the previous statement, and avoid testing pgno==0 in the
51152  ** common case where pgno is large. */
51153  if( pgno<=1 && pgno==0 ){
51154  return SQLITE_CORRUPT_BKPT;
51155  }
51156  assert( pPager->eState>=PAGER_READER );
51157  assert( assert_pager_state(pPager) );
51158  assert( noContent==0 || bMmapOk==0 );
51159 
51160  assert( pPager->hasHeldSharedLock==1 );
51161 
51162  /* If the pager is in the error state, return an error immediately.
51163  ** Otherwise, request the page from the PCache layer. */
51164  if( pPager->errCode!=SQLITE_OK ){
51165  rc = pPager->errCode;
51166  }else{
51167  if( bMmapOk && pagerUseWal(pPager) ){
51168  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51169  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51170  }
51171 
51172  if( bMmapOk && iFrame==0 ){
51173  void *pData = 0;
51174 
51175  rc = sqlite3OsFetch(pPager->fd,
51176  (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
51177  );
51178 
51179  if( rc==SQLITE_OK && pData ){
51180  if( pPager->eState>PAGER_READER || pPager->tempFile ){
51181  pPg = sqlite3PagerLookup(pPager, pgno);
51182  }
51183  if( pPg==0 ){
51184  rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
51185  }else{
51186  sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
51187  }
51188  if( pPg ){
51189  assert( rc==SQLITE_OK );
51190  *ppPage = pPg;
51191  return SQLITE_OK;
51192  }
51193  }
51194  if( rc!=SQLITE_OK ){
51195  goto pager_acquire_err;
51196  }
51197  }
51198 
51199  {
51200  sqlite3_pcache_page *pBase;
51201  pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
51202  if( pBase==0 ){
51203  rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
51204  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51205  if( pBase==0 ){
51206  pPg = *ppPage = 0;
51207  rc = SQLITE_NOMEM_BKPT;
51208  goto pager_acquire_err;
51209  }
51210  }
51211  pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
51212  assert( pPg!=0 );
51213  }
51214  }
51215 
51216  if( rc!=SQLITE_OK ){
51217  /* Either the call to sqlite3PcacheFetch() returned an error or the
51218  ** pager was already in the error-state when this function was called.
51219  ** Set pPg to 0 and jump to the exception handler. */
51220  pPg = 0;
51221  goto pager_acquire_err;
51222  }
51223  assert( pPg==(*ppPage) );
51224  assert( pPg->pgno==pgno );
51225  assert( pPg->pPager==pPager || pPg->pPager==0 );
51226 
51227  if( pPg->pPager && !noContent ){
51228  /* In this case the pcache already contains an initialized copy of
51229  ** the page. Return without further ado. */
51230  assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
51231  pPager->aStat[PAGER_STAT_HIT]++;
51232  return SQLITE_OK;
51233 
51234  }else{
51235  /* The pager cache has created a new page. Its content needs to
51236  ** be initialized. */
51237 
51238  pPg->pPager = pPager;
51239 
51240  /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
51241  ** number greater than this, or the unused locking-page, is requested. */
51242  if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
51243  rc = SQLITE_CORRUPT_BKPT;
51244  goto pager_acquire_err;
51245  }
51246 
51247  assert( !isOpen(pPager->fd) || !MEMDB );
51248  if( !isOpen(pPager->fd) || pPager->dbSize<pgno || noContent ){
51249  if( pgno>pPager->mxPgno ){
51250  rc = SQLITE_FULL;
51251  goto pager_acquire_err;
51252  }
51253  if( noContent ){
51254  /* Failure to set the bits in the InJournal bit-vectors is benign.
51255  ** It merely means that we might do some extra work to journal a
51256  ** page that does not need to be journaled. Nevertheless, be sure
51257  ** to test the case where a malloc error occurs while trying to set
51258  ** a bit in a bit vector.
51259  */
51261  if( pgno<=pPager->dbOrigSize ){
51262  TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
51263  testcase( rc==SQLITE_NOMEM );
51264  }
51265  TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
51266  testcase( rc==SQLITE_NOMEM );
51268  }
51269  memset(pPg->pData, 0, pPager->pageSize);
51270  IOTRACE(("ZERO %p %d\n", pPager, pgno));
51271  }else{
51272  if( pagerUseWal(pPager) && bMmapOk==0 ){
51273  rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
51274  if( rc!=SQLITE_OK ) goto pager_acquire_err;
51275  }
51276  assert( pPg->pPager==pPager );
51277  pPager->aStat[PAGER_STAT_MISS]++;
51278  rc = readDbPage(pPg, iFrame);
51279  if( rc!=SQLITE_OK ){
51280  goto pager_acquire_err;
51281  }
51282  }
51283  pager_set_pagehash(pPg);
51284  }
51285 
51286  return SQLITE_OK;
51287 
51288 pager_acquire_err:
51289  assert( rc!=SQLITE_OK );
51290  if( pPg ){
51291  sqlite3PcacheDrop(pPg);
51292  }
51293  pagerUnlockIfUnused(pPager);
51294 
51295  *ppPage = 0;
51296  return rc;
51297 }
51298 
51299 /*
51300 ** Acquire a page if it is already in the in-memory cache. Do
51301 ** not read the page from disk. Return a pointer to the page,
51302 ** or 0 if the page is not in cache.
51303 **
51304 ** See also sqlite3PagerGet(). The difference between this routine
51305 ** and sqlite3PagerGet() is that _get() will go to the disk and read
51306 ** in the page if the page is not already in cache. This routine
51307 ** returns NULL if the page is not in cache or if a disk I/O error
51308 ** has ever happened.
51309 */
51311  sqlite3_pcache_page *pPage;
51312  assert( pPager!=0 );
51313  assert( pgno!=0 );
51314  assert( pPager->pPCache!=0 );
51315  pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
51316  assert( pPage==0 || pPager->hasHeldSharedLock );
51317  if( pPage==0 ) return 0;
51318  return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
51319 }
51320 
51321 /*
51322 ** Release a page reference.
51323 **
51324 ** If the number of references to the page drop to zero, then the
51325 ** page is added to the LRU list. When all references to all pages
51326 ** are released, a rollback occurs and the lock on the database is
51327 ** removed.
51328 */
51330  Pager *pPager;
51331  assert( pPg!=0 );
51332  pPager = pPg->pPager;
51333  if( pPg->flags & PGHDR_MMAP ){
51334  pagerReleaseMapPage(pPg);
51335  }else{
51336  sqlite3PcacheRelease(pPg);
51337  }
51338  pagerUnlockIfUnused(pPager);
51339 }
51341  if( pPg ) sqlite3PagerUnrefNotNull(pPg);
51342 }
51343 
51344 /*
51345 ** This function is called at the start of every write transaction.
51346 ** There must already be a RESERVED or EXCLUSIVE lock on the database
51347 ** file when this routine is called.
51348 **
51349 ** Open the journal file for pager pPager and write a journal header
51350 ** to the start of it. If there are active savepoints, open the sub-journal
51351 ** as well. This function is only used when the journal file is being
51352 ** opened to write a rollback log for a transaction. It is not used
51353 ** when opening a hot journal file to roll it back.
51354 **
51355 ** If the journal file is already open (as it may be in exclusive mode),
51356 ** then this function just writes a journal header to the start of the
51357 ** already open file.
51358 **
51359 ** Whether or not the journal file is opened by this function, the
51360 ** Pager.pInJournal bitvec structure is allocated.
51361 **
51362 ** Return SQLITE_OK if everything is successful. Otherwise, return
51363 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
51364 ** an IO error code if opening or writing the journal file fails.
51365 */
51366 static int pager_open_journal(Pager *pPager){
51367  int rc = SQLITE_OK; /* Return code */
51368  sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
51369 
51370  assert( pPager->eState==PAGER_WRITER_LOCKED );
51371  assert( assert_pager_state(pPager) );
51372  assert( pPager->pInJournal==0 );
51373 
51374  /* If already in the error state, this function is a no-op. But on
51375  ** the other hand, this routine is never called if we are already in
51376  ** an error state. */
51377  if( NEVER(pPager->errCode) ) return pPager->errCode;
51378 
51379  if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
51380  pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
51381  if( pPager->pInJournal==0 ){
51382  return SQLITE_NOMEM_BKPT;
51383  }
51384 
51385  /* Open the journal file if it is not already open. */
51386  if( !isOpen(pPager->jfd) ){
51387  if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
51388  sqlite3MemJournalOpen(pPager->jfd);
51389  }else{
51391  int nSpill;
51392 
51393  if( pPager->tempFile ){
51395  nSpill = sqlite3Config.nStmtSpill;
51396  }else{
51397  flags |= SQLITE_OPEN_MAIN_JOURNAL;
51398  nSpill = jrnlBufferSize(pPager);
51399  }
51400 
51401  /* Verify that the database still has the same name as it did when
51402  ** it was originally opened. */
51403  rc = databaseIsUnmoved(pPager);
51404  if( rc==SQLITE_OK ){
51405  rc = sqlite3JournalOpen (
51406  pVfs, pPager->zJournal, pPager->jfd, flags, nSpill
51407  );
51408  }
51409  }
51410  assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
51411  }
51412 
51413 
51414  /* Write the first journal header to the journal file and open
51415  ** the sub-journal if necessary.
51416  */
51417  if( rc==SQLITE_OK ){
51418  /* TODO: Check if all of these are really required. */
51419  pPager->nRec = 0;
51420  pPager->journalOff = 0;
51421  pPager->setMaster = 0;
51422  pPager->journalHdr = 0;
51423  rc = writeJournalHdr(pPager);
51424  }
51425  }
51426 
51427  if( rc!=SQLITE_OK ){
51429  pPager->pInJournal = 0;
51430  }else{
51431  assert( pPager->eState==PAGER_WRITER_LOCKED );
51432  pPager->eState = PAGER_WRITER_CACHEMOD;
51433  }
51434 
51435  return rc;
51436 }
51437 
51438 /*
51439 ** Begin a write-transaction on the specified pager object. If a
51440 ** write-transaction has already been opened, this function is a no-op.
51441 **
51442 ** If the exFlag argument is false, then acquire at least a RESERVED
51443 ** lock on the database file. If exFlag is true, then acquire at least
51444 ** an EXCLUSIVE lock. If such a lock is already held, no locking
51445 ** functions need be called.
51446 **
51447 ** If the subjInMemory argument is non-zero, then any sub-journal opened
51448 ** within this transaction will be opened as an in-memory file. This
51449 ** has no effect if the sub-journal is already opened (as it may be when
51450 ** running in exclusive mode) or if the transaction does not require a
51451 ** sub-journal. If the subjInMemory argument is zero, then any required
51452 ** sub-journal is implemented in-memory if pPager is an in-memory database,
51453 ** or using a temporary file otherwise.
51454 */
51455 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
51456  int rc = SQLITE_OK;
51457 
51458  if( pPager->errCode ) return pPager->errCode;
51459  assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
51460  pPager->subjInMemory = (u8)subjInMemory;
51461 
51462  if( ALWAYS(pPager->eState==PAGER_READER) ){
51463  assert( pPager->pInJournal==0 );
51464 
51465  if( pagerUseWal(pPager) ){
51466  /* If the pager is configured to use locking_mode=exclusive, and an
51467  ** exclusive lock on the database is not already held, obtain it now.
51468  */
51469  if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
51470  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
51471  if( rc!=SQLITE_OK ){
51472  return rc;
51473  }
51474  (void)sqlite3WalExclusiveMode(pPager->pWal, 1);
51475  }
51476 
51477  /* Grab the write lock on the log file. If successful, upgrade to
51478  ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
51479  ** The busy-handler is not invoked if another connection already
51480  ** holds the write-lock. If possible, the upper layer will call it.
51481  */
51482  rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
51483  }else{
51484  /* Obtain a RESERVED lock on the database file. If the exFlag parameter
51485  ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
51486  ** busy-handler callback can be used when upgrading to the EXCLUSIVE
51487  ** lock, but not when obtaining the RESERVED lock.
51488  */
51489  rc = pagerLockDb(pPager, RESERVED_LOCK);
51490  if( rc==SQLITE_OK && exFlag ){
51491  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
51492  }
51493  }
51494 
51495  if( rc==SQLITE_OK ){
51496  /* Change to WRITER_LOCKED state.
51497  **
51498  ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
51499  ** when it has an open transaction, but never to DBMOD or FINISHED.
51500  ** This is because in those states the code to roll back savepoint
51501  ** transactions may copy data from the sub-journal into the database
51502  ** file as well as into the page cache. Which would be incorrect in
51503  ** WAL mode.
51504  */
51505  pPager->eState = PAGER_WRITER_LOCKED;
51506  pPager->dbHintSize = pPager->dbSize;
51507  pPager->dbFileSize = pPager->dbSize;
51508  pPager->dbOrigSize = pPager->dbSize;
51509  pPager->journalOff = 0;
51510  }
51511 
51512  assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
51513  assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
51514  assert( assert_pager_state(pPager) );
51515  }
51516 
51517  PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
51518  return rc;
51519 }
51520 
51521 /*
51522 ** Write page pPg onto the end of the rollback journal.
51523 */
51525  Pager *pPager = pPg->pPager;
51526  int rc;
51527  u32 cksum;
51528  char *pData2;
51529  i64 iOff = pPager->journalOff;
51530 
51531  /* We should never write to the journal file the page that
51532  ** contains the database locks. The following assert verifies
51533  ** that we do not. */
51534  assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
51535 
51536  assert( pPager->journalHdr<=pPager->journalOff );
51537  CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM_BKPT, pData2);
51538  cksum = pager_cksum(pPager, (u8*)pData2);
51539 
51540  /* Even if an IO or diskfull error occurs while journalling the
51541  ** page in the block above, set the need-sync flag for the page.
51542  ** Otherwise, when the transaction is rolled back, the logic in
51543  ** playback_one_page() will think that the page needs to be restored
51544  ** in the database file. And if an IO error occurs while doing so,
51545  ** then corruption may follow.
51546  */
51547  pPg->flags |= PGHDR_NEED_SYNC;
51548 
51549  rc = write32bits(pPager->jfd, iOff, pPg->pgno);
51550  if( rc!=SQLITE_OK ) return rc;
51551  rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
51552  if( rc!=SQLITE_OK ) return rc;
51553  rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
51554  if( rc!=SQLITE_OK ) return rc;
51555 
51556  IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
51557  pPager->journalOff, pPager->pageSize));
51558  PAGER_INCR(sqlite3_pager_writej_count);
51559  PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
51560  PAGERID(pPager), pPg->pgno,
51561  ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
51562 
51563  pPager->journalOff += 8 + pPager->pageSize;
51564  pPager->nRec++;
51565  assert( pPager->pInJournal!=0 );
51566  rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
51567  testcase( rc==SQLITE_NOMEM );
51568  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
51569  rc |= addToSavepointBitvecs(pPager, pPg->pgno);
51570  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
51571  return rc;
51572 }
51573 
51574 /*
51575 ** Mark a single data page as writeable. The page is written into the
51576 ** main journal or sub-journal as required. If the page is written into
51577 ** one of the journals, the corresponding bit is set in the
51578 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
51579 ** of any open savepoints as appropriate.
51580 */
51581 static int pager_write(PgHdr *pPg){
51582  Pager *pPager = pPg->pPager;
51583  int rc = SQLITE_OK;
51584 
51585  /* This routine is not called unless a write-transaction has already
51586  ** been started. The journal file may or may not be open at this point.
51587  ** It is never called in the ERROR state.
51588  */
51590  || pPager->eState==PAGER_WRITER_CACHEMOD
51591  || pPager->eState==PAGER_WRITER_DBMOD
51592  );
51593  assert( assert_pager_state(pPager) );
51594  assert( pPager->errCode==0 );
51595  assert( pPager->readOnly==0 );
51596  CHECK_PAGE(pPg);
51597 
51598  /* The journal file needs to be opened. Higher level routines have already
51599  ** obtained the necessary locks to begin the write-transaction, but the
51600  ** rollback journal might not yet be open. Open it now if this is the case.
51601  **
51602  ** This is done before calling sqlite3PcacheMakeDirty() on the page.
51603  ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
51604  ** an error might occur and the pager would end up in WRITER_LOCKED state
51605  ** with pages marked as dirty in the cache.
51606  */
51607  if( pPager->eState==PAGER_WRITER_LOCKED ){
51608  rc = pager_open_journal(pPager);
51609  if( rc!=SQLITE_OK ) return rc;
51610  }
51611  assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
51612  assert( assert_pager_state(pPager) );
51613 
51614  /* Mark the page that is about to be modified as dirty. */
51616 
51617  /* If a rollback journal is in use, them make sure the page that is about
51618  ** to change is in the rollback journal, or if the page is a new page off
51619  ** then end of the file, make sure it is marked as PGHDR_NEED_SYNC.
51620  */
51621  assert( (pPager->pInJournal!=0) == isOpen(pPager->jfd) );
51622  if( pPager->pInJournal!=0
51623  && sqlite3BitvecTestNotNull(pPager->pInJournal, pPg->pgno)==0
51624  ){
51625  assert( pagerUseWal(pPager)==0 );
51626  if( pPg->pgno<=pPager->dbOrigSize ){
51628  if( rc!=SQLITE_OK ){
51629  return rc;
51630  }
51631  }else{
51632  if( pPager->eState!=PAGER_WRITER_DBMOD ){
51633  pPg->flags |= PGHDR_NEED_SYNC;
51634  }
51635  PAGERTRACE(("APPEND %d page %d needSync=%d\n",
51636  PAGERID(pPager), pPg->pgno,
51637  ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
51638  }
51639  }
51640 
51641  /* The PGHDR_DIRTY bit is set above when the page was added to the dirty-list
51642  ** and before writing the page into the rollback journal. Wait until now,
51643  ** after the page has been successfully journalled, before setting the
51644  ** PGHDR_WRITEABLE bit that indicates that the page can be safely modified.
51645  */
51646  pPg->flags |= PGHDR_WRITEABLE;
51647 
51648  /* If the statement journal is open and the page is not in it,
51649  ** then write the page into the statement journal.
51650  */
51651  if( pPager->nSavepoint>0 ){
51652  rc = subjournalPageIfRequired(pPg);
51653  }
51654 
51655  /* Update the database size and return. */
51656  if( pPager->dbSize<pPg->pgno ){
51657  pPager->dbSize = pPg->pgno;
51658  }
51659  return rc;
51660 }
51661 
51662 /*
51663 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
51664 ** is larger than the page size. SQLite makes the (reasonable) assumption that
51665 ** all bytes of a sector are written together by hardware. Hence, all bytes of
51666 ** a sector need to be journalled in case of a power loss in the middle of
51667 ** a write.
51668 **
51669 ** Usually, the sector size is less than or equal to the page size, in which
51670 ** case pages can be individually written. This routine only runs in the
51671 ** exceptional case where the page size is smaller than the sector size.
51672 */
51674  int rc = SQLITE_OK; /* Return code */
51675  Pgno nPageCount; /* Total number of pages in database file */
51676  Pgno pg1; /* First page of the sector pPg is located on. */
51677  int nPage = 0; /* Number of pages starting at pg1 to journal */
51678  int ii; /* Loop counter */
51679  int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
51680  Pager *pPager = pPg->pPager; /* The pager that owns pPg */
51681  Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
51682 
51683  /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
51684  ** a journal header to be written between the pages journaled by
51685  ** this function.
51686  */
51687  assert( !MEMDB );
51688  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
51689  pPager->doNotSpill |= SPILLFLAG_NOSYNC;
51690 
51691  /* This trick assumes that both the page-size and sector-size are
51692  ** an integer power of 2. It sets variable pg1 to the identifier
51693  ** of the first page of the sector pPg is located on.
51694  */
51695  pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
51696 
51697  nPageCount = pPager->dbSize;
51698  if( pPg->pgno>nPageCount ){
51699  nPage = (pPg->pgno - pg1)+1;
51700  }else if( (pg1+nPagePerSector-1)>nPageCount ){
51701  nPage = nPageCount+1-pg1;
51702  }else{
51703  nPage = nPagePerSector;
51704  }
51705  assert(nPage>0);
51706  assert(pg1<=pPg->pgno);
51707  assert((pg1+nPage)>pPg->pgno);
51708 
51709  for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
51710  Pgno pg = pg1+ii;
51711  PgHdr *pPage;
51712  if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
51713  if( pg!=PAGER_MJ_PGNO(pPager) ){
51714  rc = sqlite3PagerGet(pPager, pg, &pPage, 0);
51715  if( rc==SQLITE_OK ){
51716  rc = pager_write(pPage);
51717  if( pPage->flags&PGHDR_NEED_SYNC ){
51718  needSync = 1;
51719  }
51720  sqlite3PagerUnrefNotNull(pPage);
51721  }
51722  }
51723  }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
51724  if( pPage->flags&PGHDR_NEED_SYNC ){
51725  needSync = 1;
51726  }
51727  sqlite3PagerUnrefNotNull(pPage);
51728  }
51729  }
51730 
51731  /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
51732  ** starting at pg1, then it needs to be set for all of them. Because
51733  ** writing to any of these nPage pages may damage the others, the
51734  ** journal file must contain sync()ed copies of all of them
51735  ** before any of them can be written out to the database file.
51736  */
51737  if( rc==SQLITE_OK && needSync ){
51738  assert( !MEMDB );
51739  for(ii=0; ii<nPage; ii++){
51740  PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
51741  if( pPage ){
51742  pPage->flags |= PGHDR_NEED_SYNC;
51743  sqlite3PagerUnrefNotNull(pPage);
51744  }
51745  }
51746  }
51747 
51748  assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
51749  pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
51750  return rc;
51751 }
51752 
51753 /*
51754 ** Mark a data page as writeable. This routine must be called before
51755 ** making changes to a page. The caller must check the return value
51756 ** of this function and be careful not to change any page data unless
51757 ** this routine returns SQLITE_OK.
51758 **
51759 ** The difference between this function and pager_write() is that this
51760 ** function also deals with the special case where 2 or more pages
51761 ** fit on a single disk sector. In this case all co-resident pages
51762 ** must have been written to the journal file before returning.
51763 **
51764 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
51765 ** as appropriate. Otherwise, SQLITE_OK.
51766 */
51768  Pager *pPager = pPg->pPager;
51769  assert( (pPg->flags & PGHDR_MMAP)==0 );
51770  assert( pPager->eState>=PAGER_WRITER_LOCKED );
51771  assert( assert_pager_state(pPager) );
51772  if( pPager->errCode ){
51773  return pPager->errCode;
51774  }else if( (pPg->flags & PGHDR_WRITEABLE)!=0 && pPager->dbSize>=pPg->pgno ){
51775  if( pPager->nSavepoint ) return subjournalPageIfRequired(pPg);
51776  return SQLITE_OK;
51777  }else if( pPager->sectorSize > (u32)pPager->pageSize ){
51778  assert( pPager->tempFile==0 );
51779  return pagerWriteLargeSector(pPg);
51780  }else{
51781  return pager_write(pPg);
51782  }
51783 }
51784 
51785 /*
51786 ** Return TRUE if the page given in the argument was previously passed
51787 ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
51788 ** to change the content of the page.
51789 */
51790 #ifndef NDEBUG
51791 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
51792  return pPg->flags & PGHDR_WRITEABLE;
51793 }
51794 #endif
51795 
51796 /*
51797 ** A call to this routine tells the pager that it is not necessary to
51798 ** write the information on page pPg back to the disk, even though
51799 ** that page might be marked as dirty. This happens, for example, when
51800 ** the page has been added as a leaf of the freelist and so its
51801 ** content no longer matters.
51802 **
51803 ** The overlying software layer calls this routine when all of the data
51804 ** on the given page is unused. The pager marks the page as clean so
51805 ** that it does not get written to disk.
51806 **
51807 ** Tests show that this optimization can quadruple the speed of large
51808 ** DELETE operations.
51809 **
51810 ** This optimization cannot be used with a temp-file, as the page may
51811 ** have been dirty at the start of the transaction. In that case, if
51812 ** memory pressure forces page pPg out of the cache, the data does need
51813 ** to be written out to disk so that it may be read back in if the
51814 ** current transaction is rolled back.
51815 */
51817  Pager *pPager = pPg->pPager;
51818  if( !pPager->tempFile && (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
51819  PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
51820  IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
51821  pPg->flags |= PGHDR_DONT_WRITE;
51822  pPg->flags &= ~PGHDR_WRITEABLE;
51823  testcase( pPg->flags & PGHDR_NEED_SYNC );
51824  pager_set_pagehash(pPg);
51825  }
51826 }
51827 
51828 /*
51829 ** This routine is called to increment the value of the database file
51830 ** change-counter, stored as a 4-byte big-endian integer starting at
51831 ** byte offset 24 of the pager file. The secondary change counter at
51832 ** 92 is also updated, as is the SQLite version number at offset 96.
51833 **
51834 ** But this only happens if the pPager->changeCountDone flag is false.
51835 ** To avoid excess churning of page 1, the update only happens once.
51836 ** See also the pager_write_changecounter() routine that does an
51837 ** unconditional update of the change counters.
51838 **
51839 ** If the isDirectMode flag is zero, then this is done by calling
51840 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
51841 ** page data. In this case the file will be updated when the current
51842 ** transaction is committed.
51843 **
51844 ** The isDirectMode flag may only be non-zero if the library was compiled
51845 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
51846 ** if isDirect is non-zero, then the database file is updated directly
51847 ** by writing an updated version of page 1 using a call to the
51848 ** sqlite3OsWrite() function.
51849 */
51850 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
51851  int rc = SQLITE_OK;
51852 
51854  || pPager->eState==PAGER_WRITER_DBMOD
51855  );
51856  assert( assert_pager_state(pPager) );
51857 
51858  /* Declare and initialize constant integer 'isDirect'. If the
51859  ** atomic-write optimization is enabled in this build, then isDirect
51860  ** is initialized to the value passed as the isDirectMode parameter
51861  ** to this function. Otherwise, it is always set to zero.
51862  **
51863  ** The idea is that if the atomic-write optimization is not
51864  ** enabled at compile time, the compiler can omit the tests of
51865  ** 'isDirect' below, as well as the block enclosed in the
51866  ** "if( isDirect )" condition.
51867  */
51868 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
51869 # define DIRECT_MODE 0
51870  assert( isDirectMode==0 );
51871  UNUSED_PARAMETER(isDirectMode);
51872 #else
51873 # define DIRECT_MODE isDirectMode
51874 #endif
51875 
51876  if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
51877  PgHdr *pPgHdr; /* Reference to page 1 */
51878 
51879  assert( !pPager->tempFile && isOpen(pPager->fd) );
51880 
51881  /* Open page 1 of the file for writing. */
51882  rc = sqlite3PagerGet(pPager, 1, &pPgHdr, 0);
51883  assert( pPgHdr==0 || rc==SQLITE_OK );
51884 
51885  /* If page one was fetched successfully, and this function is not
51886  ** operating in direct-mode, make page 1 writable. When not in
51887  ** direct mode, page 1 is always held in cache and hence the PagerGet()
51888  ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
51889  */
51890  if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
51891  rc = sqlite3PagerWrite(pPgHdr);
51892  }
51893 
51894  if( rc==SQLITE_OK ){
51895  /* Actually do the update of the change counter */
51896  pager_write_changecounter(pPgHdr);
51897 
51898  /* If running in direct mode, write the contents of page 1 to the file. */
51899  if( DIRECT_MODE ){
51900  const void *zBuf;
51901  assert( pPager->dbFileSize>0 );
51902  CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM_BKPT, zBuf);
51903  if( rc==SQLITE_OK ){
51904  rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
51905  pPager->aStat[PAGER_STAT_WRITE]++;
51906  }
51907  if( rc==SQLITE_OK ){
51908  /* Update the pager's copy of the change-counter. Otherwise, the
51909  ** next time a read transaction is opened the cache will be
51910  ** flushed (as the change-counter values will not match). */
51911  const void *pCopy = (const void *)&((const char *)zBuf)[24];
51912  memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
51913  pPager->changeCountDone = 1;
51914  }
51915  }else{
51916  pPager->changeCountDone = 1;
51917  }
51918  }
51919 
51920  /* Release the page reference. */
51921  sqlite3PagerUnref(pPgHdr);
51922  }
51923  return rc;
51924 }
51925 
51926 /*
51927 ** Sync the database file to disk. This is a no-op for in-memory databases
51928 ** or pages with the Pager.noSync flag set.
51929 **
51930 ** If successful, or if called on a pager for which it is a no-op, this
51931 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
51932 */
51933 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
51934  int rc = SQLITE_OK;
51935 
51936  if( isOpen(pPager->fd) ){
51937  void *pArg = (void*)zMaster;
51938  rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
51939  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
51940  }
51941  if( rc==SQLITE_OK && !pPager->noSync ){
51942  assert( !MEMDB );
51943  rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
51944  }
51945  return rc;
51946 }
51947 
51948 /*
51949 ** This function may only be called while a write-transaction is active in
51950 ** rollback. If the connection is in WAL mode, this call is a no-op.
51951 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
51952 ** the database file, an attempt is made to obtain one.
51953 **
51954 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
51955 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
51956 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
51957 ** returned.
51958 */
51960  int rc = pPager->errCode;
51961  assert( assert_pager_state(pPager) );
51962  if( rc==SQLITE_OK ){
51964  || pPager->eState==PAGER_WRITER_DBMOD
51965  || pPager->eState==PAGER_WRITER_LOCKED
51966  );
51967  assert( assert_pager_state(pPager) );
51968  if( 0==pagerUseWal(pPager) ){
51969  rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
51970  }
51971  }
51972  return rc;
51973 }
51974 
51975 /*
51976 ** Sync the database file for the pager pPager. zMaster points to the name
51977 ** of a master journal file that should be written into the individual
51978 ** journal file. zMaster may be NULL, which is interpreted as no master
51979 ** journal (a single database transaction).
51980 **
51981 ** This routine ensures that:
51982 **
51983 ** * The database file change-counter is updated,
51984 ** * the journal is synced (unless the atomic-write optimization is used),
51985 ** * all dirty pages are written to the database file,
51986 ** * the database file is truncated (if required), and
51987 ** * the database file synced.
51988 **
51989 ** The only thing that remains to commit the transaction is to finalize
51990 ** (delete, truncate or zero the first part of) the journal file (or
51991 ** delete the master journal file if specified).
51992 **
51993 ** Note that if zMaster==NULL, this does not overwrite a previous value
51994 ** passed to an sqlite3PagerCommitPhaseOne() call.
51995 **
51996 ** If the final parameter - noSync - is true, then the database file itself
51997 ** is not synced. The caller must call sqlite3PagerSync() directly to
51998 ** sync the database file before calling CommitPhaseTwo() to delete the
51999 ** journal file in this case.
52000 */
52002  Pager *pPager, /* Pager object */
52003  const char *zMaster, /* If not NULL, the master journal name */
52004  int noSync /* True to omit the xSync on the db file */
52005 ){
52006  int rc = SQLITE_OK; /* Return code */
52007 
52009  || pPager->eState==PAGER_WRITER_CACHEMOD
52010  || pPager->eState==PAGER_WRITER_DBMOD
52011  || pPager->eState==PAGER_ERROR
52012  );
52013  assert( assert_pager_state(pPager) );
52014 
52015  /* If a prior error occurred, report that error again. */
52016  if( NEVER(pPager->errCode) ) return pPager->errCode;
52017 
52018  /* Provide the ability to easily simulate an I/O error during testing */
52019  if( sqlite3FaultSim(400) ) return SQLITE_IOERR;
52020 
52021  PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
52022  pPager->zFilename, zMaster, pPager->dbSize));
52023 
52024  /* If no database changes have been made, return early. */
52025  if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
52026 
52027  assert( MEMDB==0 || pPager->tempFile );
52028  assert( isOpen(pPager->fd) || pPager->tempFile );
52029  if( 0==pagerFlushOnCommit(pPager, 1) ){
52030  /* If this is an in-memory db, or no pages have been written to, or this
52031  ** function has already been called, it is mostly a no-op. However, any
52032  ** backup in progress needs to be restarted. */
52033  sqlite3BackupRestart(pPager->pBackup);
52034  }else{
52035  if( pagerUseWal(pPager) ){
52036  PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
52037  PgHdr *pPageOne = 0;
52038  if( pList==0 ){
52039  /* Must have at least one page for the WAL commit flag.
52040  ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
52041  rc = sqlite3PagerGet(pPager, 1, &pPageOne, 0);
52042  pList = pPageOne;
52043  pList->pDirty = 0;
52044  }
52045  assert( rc==SQLITE_OK );
52046  if( ALWAYS(pList) ){
52047  rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
52048  }
52049  sqlite3PagerUnref(pPageOne);
52050  if( rc==SQLITE_OK ){
52051  sqlite3PcacheCleanAll(pPager->pPCache);
52052  }
52053  }else{
52054  /* The following block updates the change-counter. Exactly how it
52055  ** does this depends on whether or not the atomic-update optimization
52056  ** was enabled at compile time, and if this transaction meets the
52057  ** runtime criteria to use the operation:
52058  **
52059  ** * The file-system supports the atomic-write property for
52060  ** blocks of size page-size, and
52061  ** * This commit is not part of a multi-file transaction, and
52062  ** * Exactly one page has been modified and store in the journal file.
52063  **
52064  ** If the optimization was not enabled at compile time, then the
52065  ** pager_incr_changecounter() function is called to update the change
52066  ** counter in 'indirect-mode'. If the optimization is compiled in but
52067  ** is not applicable to this transaction, call sqlite3JournalCreate()
52068  ** to make sure the journal file has actually been created, then call
52069  ** pager_incr_changecounter() to update the change-counter in indirect
52070  ** mode.
52071  **
52072  ** Otherwise, if the optimization is both enabled and applicable,
52073  ** then call pager_incr_changecounter() to update the change-counter
52074  ** in 'direct' mode. In this case the journal file will never be
52075  ** created for this transaction.
52076  */
52077  #ifdef SQLITE_ENABLE_ATOMIC_WRITE
52078  PgHdr *pPg;
52079  assert( isOpen(pPager->jfd)
52080  || pPager->journalMode==PAGER_JOURNALMODE_OFF
52081  || pPager->journalMode==PAGER_JOURNALMODE_WAL
52082  );
52083  if( !zMaster && isOpen(pPager->jfd)
52084  && pPager->journalOff==jrnlBufferSize(pPager)
52085  && pPager->dbSize>=pPager->dbOrigSize
52086  && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
52087  ){
52088  /* Update the db file change counter via the direct-write method. The
52089  ** following call will modify the in-memory representation of page 1
52090  ** to include the updated change counter and then write page 1
52091  ** directly to the database file. Because of the atomic-write
52092  ** property of the host file-system, this is safe.
52093  */
52094  rc = pager_incr_changecounter(pPager, 1);
52095  }else{
52096  rc = sqlite3JournalCreate(pPager->jfd);
52097  if( rc==SQLITE_OK ){
52098  rc = pager_incr_changecounter(pPager, 0);
52099  }
52100  }
52101  #else
52102  rc = pager_incr_changecounter(pPager, 0);
52103  #endif
52104  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52105 
52106  /* Write the master journal name into the journal file. If a master
52107  ** journal file name has already been written to the journal file,
52108  ** or if zMaster is NULL (no master journal), then this call is a no-op.
52109  */
52110  rc = writeMasterJournal(pPager, zMaster);
52111  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52112 
52113  /* Sync the journal file and write all dirty pages to the database.
52114  ** If the atomic-update optimization is being used, this sync will not
52115  ** create the journal file or perform any real IO.
52116  **
52117  ** Because the change-counter page was just modified, unless the
52118  ** atomic-update optimization is used it is almost certain that the
52119  ** journal requires a sync here. However, in locking_mode=exclusive
52120  ** on a system under memory pressure it is just possible that this is
52121  ** not the case. In this case it is likely enough that the redundant
52122  ** xSync() call will be changed to a no-op by the OS anyhow.
52123  */
52124  rc = syncJournal(pPager, 0);
52125  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52126 
52127  rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
52128  if( rc!=SQLITE_OK ){
52130  goto commit_phase_one_exit;
52131  }
52132  sqlite3PcacheCleanAll(pPager->pPCache);
52133 
52134  /* If the file on disk is smaller than the database image, use
52135  ** pager_truncate to grow the file here. This can happen if the database
52136  ** image was extended as part of the current transaction and then the
52137  ** last page in the db image moved to the free-list. In this case the
52138  ** last page is never written out to disk, leaving the database file
52139  ** undersized. Fix this now if it is the case. */
52140  if( pPager->dbSize>pPager->dbFileSize ){
52141  Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
52142  assert( pPager->eState==PAGER_WRITER_DBMOD );
52143  rc = pager_truncate(pPager, nNew);
52144  if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
52145  }
52146 
52147  /* Finally, sync the database file. */
52148  if( !noSync ){
52149  rc = sqlite3PagerSync(pPager, zMaster);
52150  }
52151  IOTRACE(("DBSYNC %p\n", pPager))
52152  }
52153  }
52154 
52155 commit_phase_one_exit:
52156  if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
52157  pPager->eState = PAGER_WRITER_FINISHED;
52158  }
52159  return rc;
52160 }
52161 
52162 
52163 /*
52164 ** When this function is called, the database file has been completely
52165 ** updated to reflect the changes made by the current transaction and
52166 ** synced to disk. The journal file still exists in the file-system
52167 ** though, and if a failure occurs at this point it will eventually
52168 ** be used as a hot-journal and the current transaction rolled back.
52169 **
52170 ** This function finalizes the journal file, either by deleting,
52171 ** truncating or partially zeroing it, so that it cannot be used
52172 ** for hot-journal rollback. Once this is done the transaction is
52173 ** irrevocably committed.
52174 **
52175 ** If an error occurs, an IO error code is returned and the pager
52176 ** moves into the error state. Otherwise, SQLITE_OK is returned.
52177 */
52179  int rc = SQLITE_OK; /* Return code */
52180 
52181  /* This routine should not be called if a prior error has occurred.
52182  ** But if (due to a coding error elsewhere in the system) it does get
52183  ** called, just return the same error code without doing anything. */
52184  if( NEVER(pPager->errCode) ) return pPager->errCode;
52185 
52187  || pPager->eState==PAGER_WRITER_FINISHED
52188  || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
52189  );
52190  assert( assert_pager_state(pPager) );
52191 
52192  /* An optimization. If the database was not actually modified during
52193  ** this transaction, the pager is running in exclusive-mode and is
52194  ** using persistent journals, then this function is a no-op.
52195  **
52196  ** The start of the journal file currently contains a single journal
52197  ** header with the nRec field set to 0. If such a journal is used as
52198  ** a hot-journal during hot-journal rollback, 0 changes will be made
52199  ** to the database file. So there is no need to zero the journal
52200  ** header. Since the pager is in exclusive mode, there is no need
52201  ** to drop any locks either.
52202  */
52203  if( pPager->eState==PAGER_WRITER_LOCKED
52204  && pPager->exclusiveMode
52206  ){
52207  assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
52208  pPager->eState = PAGER_READER;
52209  return SQLITE_OK;
52210  }
52211 
52212  PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
52213  pPager->iDataVersion++;
52214  rc = pager_end_transaction(pPager, pPager->setMaster, 1);
52215  return pager_error(pPager, rc);
52216 }
52217 
52218 /*
52219 ** If a write transaction is open, then all changes made within the
52220 ** transaction are reverted and the current write-transaction is closed.
52221 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
52222 ** state if an error occurs.
52223 **
52224 ** If the pager is already in PAGER_ERROR state when this function is called,
52225 ** it returns Pager.errCode immediately. No work is performed in this case.
52226 **
52227 ** Otherwise, in rollback mode, this function performs two functions:
52228 **
52229 ** 1) It rolls back the journal file, restoring all database file and
52230 ** in-memory cache pages to the state they were in when the transaction
52231 ** was opened, and
52232 **
52233 ** 2) It finalizes the journal file, so that it is not used for hot
52234 ** rollback at any point in the future.
52235 **
52236 ** Finalization of the journal file (task 2) is only performed if the
52237 ** rollback is successful.
52238 **
52239 ** In WAL mode, all cache-entries containing data modified within the
52240 ** current transaction are either expelled from the cache or reverted to
52241 ** their pre-transaction state by re-reading data from the database or
52242 ** WAL files. The WAL transaction is then closed.
52243 */
52245  int rc = SQLITE_OK; /* Return code */
52246  PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
52247 
52248  /* PagerRollback() is a no-op if called in READER or OPEN state. If
52249  ** the pager is already in the ERROR state, the rollback is not
52250  ** attempted here. Instead, the error code is returned to the caller.
52251  */
52252  assert( assert_pager_state(pPager) );
52253  if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
52254  if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
52255 
52256  if( pagerUseWal(pPager) ){
52257  int rc2;
52258  rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
52259  rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
52260  if( rc==SQLITE_OK ) rc = rc2;
52261  }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
52262  int eState = pPager->eState;
52263  rc = pager_end_transaction(pPager, 0, 0);
52264  if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
52265  /* This can happen using journal_mode=off. Move the pager to the error
52266  ** state to indicate that the contents of the cache may not be trusted.
52267  ** Any active readers will get SQLITE_ABORT.
52268  */
52269  pPager->errCode = SQLITE_ABORT;
52270  pPager->eState = PAGER_ERROR;
52271  return rc;
52272  }
52273  }else{
52274  rc = pager_playback(pPager, 0);
52275  }
52276 
52277  assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
52278  assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
52279  || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
52280  || rc==SQLITE_CANTOPEN
52281  );
52282 
52283  /* If an error occurs during a ROLLBACK, we can no longer trust the pager
52284  ** cache. So call pager_error() on the way out to make any error persistent.
52285  */
52286  return pager_error(pPager, rc);
52287 }
52288 
52289 /*
52290 ** Return TRUE if the database file is opened read-only. Return FALSE
52291 ** if the database is (in theory) writable.
52292 */
52294  return pPager->readOnly;
52295 }
52296 
52297 #ifdef SQLITE_DEBUG
52298 /*
52299 ** Return the sum of the reference counts for all pages held by pPager.
52300 */
52301 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
52302  return sqlite3PcacheRefCount(pPager->pPCache);
52303 }
52304 #endif
52305 
52306 /*
52307 ** Return the approximate number of bytes of memory currently
52308 ** used by the pager and its associated cache.
52309 */
52311  int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
52312  + 5*sizeof(void*);
52313  return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
52314  + sqlite3MallocSize(pPager)
52315  + pPager->pageSize;
52316 }
52317 
52318 /*
52319 ** Return the number of references to the specified page.
52320 */
52322  return sqlite3PcachePageRefcount(pPage);
52323 }
52324 
52325 #ifdef SQLITE_TEST
52326 /*
52327 ** This routine is used for testing and analysis only.
52328 */
52329 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
52330  static int a[11];
52331  a[0] = sqlite3PcacheRefCount(pPager->pPCache);
52332  a[1] = sqlite3PcachePagecount(pPager->pPCache);
52333  a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
52334  a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
52335  a[4] = pPager->eState;
52336  a[5] = pPager->errCode;
52337  a[6] = pPager->aStat[PAGER_STAT_HIT];
52338  a[7] = pPager->aStat[PAGER_STAT_MISS];
52339  a[8] = 0; /* Used to be pPager->nOvfl */
52340  a[9] = pPager->nRead;
52341  a[10] = pPager->aStat[PAGER_STAT_WRITE];
52342  return a;
52343 }
52344 #endif
52345 
52346 /*
52347 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
52348 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
52349 ** current cache hit or miss count, according to the value of eStat. If the
52350 ** reset parameter is non-zero, the cache hit or miss count is zeroed before
52351 ** returning.
52352 */
52353 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
52354 
52356  || eStat==SQLITE_DBSTATUS_CACHE_MISS
52357  || eStat==SQLITE_DBSTATUS_CACHE_WRITE
52358  );
52359 
52363 
52364  *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
52365  if( reset ){
52366  pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
52367  }
52368 }
52369 
52370 /*
52371 ** Return true if this is an in-memory or temp-file backed pager.
52372 */
52374  return pPager->tempFile;
52375 }
52376 
52377 /*
52378 ** Check that there are at least nSavepoint savepoints open. If there are
52379 ** currently less than nSavepoints open, then open one or more savepoints
52380 ** to make up the difference. If the number of savepoints is already
52381 ** equal to nSavepoint, then this function is a no-op.
52382 **
52383 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
52384 ** occurs while opening the sub-journal file, then an IO error code is
52385 ** returned. Otherwise, SQLITE_OK.
52386 */
52387 static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint){
52388  int rc = SQLITE_OK; /* Return code */
52389  int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
52390  int ii; /* Iterator variable */
52391  PagerSavepoint *aNew; /* New Pager.aSavepoint array */
52392 
52393  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52394  assert( assert_pager_state(pPager) );
52395  assert( nSavepoint>nCurrent && pPager->useJournal );
52396 
52397  /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
52398  ** if the allocation fails. Otherwise, zero the new portion in case a
52399  ** malloc failure occurs while populating it in the for(...) loop below.
52400  */
52401  aNew = (PagerSavepoint *)sqlite3Realloc(
52402  pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
52403  );
52404  if( !aNew ){
52405  return SQLITE_NOMEM_BKPT;
52406  }
52407  memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
52408  pPager->aSavepoint = aNew;
52409 
52410  /* Populate the PagerSavepoint structures just allocated. */
52411  for(ii=nCurrent; ii<nSavepoint; ii++){
52412  aNew[ii].nOrig = pPager->dbSize;
52413  if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
52414  aNew[ii].iOffset = pPager->journalOff;
52415  }else{
52416  aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
52417  }
52418  aNew[ii].iSubRec = pPager->nSubRec;
52419  aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
52420  if( !aNew[ii].pInSavepoint ){
52421  return SQLITE_NOMEM_BKPT;
52422  }
52423  if( pagerUseWal(pPager) ){
52424  sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
52425  }
52426  pPager->nSavepoint = ii+1;
52427  }
52428  assert( pPager->nSavepoint==nSavepoint );
52429  assertTruncateConstraint(pPager);
52430  return rc;
52431 }
52432 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
52433  assert( pPager->eState>=PAGER_WRITER_LOCKED );
52434  assert( assert_pager_state(pPager) );
52435 
52436  if( nSavepoint>pPager->nSavepoint && pPager->useJournal ){
52437  return pagerOpenSavepoint(pPager, nSavepoint);
52438  }else{
52439  return SQLITE_OK;
52440  }
52441 }
52442 
52443 
52444 /*
52445 ** This function is called to rollback or release (commit) a savepoint.
52446 ** The savepoint to release or rollback need not be the most recently
52447 ** created savepoint.
52448 **
52449 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
52450 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
52451 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
52452 ** that have occurred since the specified savepoint was created.
52453 **
52454 ** The savepoint to rollback or release is identified by parameter
52455 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
52456 ** (the first created). A value of (Pager.nSavepoint-1) means operate
52457 ** on the most recently created savepoint. If iSavepoint is greater than
52458 ** (Pager.nSavepoint-1), then this function is a no-op.
52459 **
52460 ** If a negative value is passed to this function, then the current
52461 ** transaction is rolled back. This is different to calling
52462 ** sqlite3PagerRollback() because this function does not terminate
52463 ** the transaction or unlock the database, it just restores the
52464 ** contents of the database to its original state.
52465 **
52466 ** In any case, all savepoints with an index greater than iSavepoint
52467 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
52468 ** then savepoint iSavepoint is also destroyed.
52469 **
52470 ** This function may return SQLITE_NOMEM if a memory allocation fails,
52471 ** or an IO error code if an IO error occurs while rolling back a
52472 ** savepoint. If no errors occur, SQLITE_OK is returned.
52473 */
52474 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
52475  int rc = pPager->errCode; /* Return code */
52476 
52478  assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
52479 
52480  if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
52481  int ii; /* Iterator variable */
52482  int nNew; /* Number of remaining savepoints after this op. */
52483 
52484  /* Figure out how many savepoints will still be active after this
52485  ** operation. Store this value in nNew. Then free resources associated
52486  ** with any savepoints that are destroyed by this operation.
52487  */
52488  nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
52489  for(ii=nNew; ii<pPager->nSavepoint; ii++){
52491  }
52492  pPager->nSavepoint = nNew;
52493 
52494  /* If this is a release of the outermost savepoint, truncate
52495  ** the sub-journal to zero bytes in size. */
52496  if( op==SAVEPOINT_RELEASE ){
52497  if( nNew==0 && isOpen(pPager->sjfd) ){
52498  /* Only truncate if it is an in-memory sub-journal. */
52499  if( sqlite3JournalIsInMemory(pPager->sjfd) ){
52500  rc = sqlite3OsTruncate(pPager->sjfd, 0);
52501  assert( rc==SQLITE_OK );
52502  }
52503  pPager->nSubRec = 0;
52504  }
52505  }
52506  /* Else this is a rollback operation, playback the specified savepoint.
52507  ** If this is a temp-file, it is possible that the journal file has
52508  ** not yet been opened. In this case there have been no changes to
52509  ** the database file, so the playback operation can be skipped.
52510  */
52511  else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
52512  PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
52513  rc = pagerPlaybackSavepoint(pPager, pSavepoint);
52514  assert(rc!=SQLITE_DONE);
52515  }
52516  }
52517 
52518  return rc;
52519 }
52520 
52521 /*
52522 ** Return the full pathname of the database file.
52523 **
52524 ** Except, if the pager is in-memory only, then return an empty string if
52525 ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
52526 ** used to report the filename to the user, for compatibility with legacy
52527 ** behavior. But when the Btree needs to know the filename for matching to
52528 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
52529 ** participate in shared-cache.
52530 */
52531 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
52532  return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
52533 }
52534 
52535 /*
52536 ** Return the VFS structure for the pager.
52537 */
52538 SQLITE_PRIVATE sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
52539  return pPager->pVfs;
52540 }
52541 
52542 /*
52543 ** Return the file handle for the database file associated
52544 ** with the pager. This might return NULL if the file has
52545 ** not yet been opened.
52546 */
52547 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
52548  return pPager->fd;
52549 }
52550 
52551 /*
52552 ** Return the file handle for the journal file (if it exists).
52553 ** This will be either the rollback journal or the WAL file.
52554 */
52556 #if SQLITE_OMIT_WAL
52557  return pPager->jfd;
52558 #else
52559  return pPager->pWal ? sqlite3WalFile(pPager->pWal) : pPager->jfd;
52560 #endif
52561 }
52562 
52563 /*
52564 ** Return the full pathname of the journal file.
52565 */
52567  return pPager->zJournal;
52568 }
52569 
52570 #ifdef SQLITE_HAS_CODEC
52571 /*
52572 ** Set or retrieve the codec for this pager
52573 */
52574 SQLITE_PRIVATE void sqlite3PagerSetCodec(
52575  Pager *pPager,
52576  void *(*xCodec)(void*,void*,Pgno,int),
52577  void (*xCodecSizeChng)(void*,int,int),
52578  void (*xCodecFree)(void*),
52579  void *pCodec
52580 ){
52581  if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
52582  pPager->xCodec = pPager->memDb ? 0 : xCodec;
52583  pPager->xCodecSizeChng = xCodecSizeChng;
52584  pPager->xCodecFree = xCodecFree;
52585  pPager->pCodec = pCodec;
52586  pagerReportSize(pPager);
52587 }
52588 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
52589  return pPager->pCodec;
52590 }
52591 
52592 /*
52593 ** This function is called by the wal module when writing page content
52594 ** into the log file.
52595 **
52596 ** This function returns a pointer to a buffer containing the encrypted
52597 ** page content. If a malloc fails, this function may return NULL.
52598 */
52599 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
52600  void *aData = 0;
52601  CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
52602  return aData;
52603 }
52604 
52605 /*
52606 ** Return the current pager state
52607 */
52608 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
52609  return pPager->eState;
52610 }
52611 #endif /* SQLITE_HAS_CODEC */
52612 
52613 #ifndef SQLITE_OMIT_AUTOVACUUM
52614 /*
52615 ** Move the page pPg to location pgno in the file.
52616 **
52617 ** There must be no references to the page previously located at
52618 ** pgno (which we call pPgOld) though that page is allowed to be
52619 ** in cache. If the page previously located at pgno is not already
52620 ** in the rollback journal, it is not put there by by this routine.
52621 **
52622 ** References to the page pPg remain valid. Updating any
52623 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
52624 ** allocated along with the page) is the responsibility of the caller.
52625 **
52626 ** A transaction must be active when this routine is called. It used to be
52627 ** required that a statement transaction was not active, but this restriction
52628 ** has been removed (CREATE INDEX needs to move a page when a statement
52629 ** transaction is active).
52630 **
52631 ** If the fourth argument, isCommit, is non-zero, then this page is being
52632 ** moved as part of a database reorganization just before the transaction
52633 ** is being committed. In this case, it is guaranteed that the database page
52634 ** pPg refers to will not be written to again within this transaction.
52635 **
52636 ** This function may return SQLITE_NOMEM or an IO error code if an error
52637 ** occurs. Otherwise, it returns SQLITE_OK.
52638 */
52639 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
52640  PgHdr *pPgOld; /* The page being overwritten. */
52641  Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
52642  int rc; /* Return code */
52643  Pgno origPgno; /* The original page number */
52644 
52645  assert( pPg->nRef>0 );
52647  || pPager->eState==PAGER_WRITER_DBMOD
52648  );
52649  assert( assert_pager_state(pPager) );
52650 
52651  /* In order to be able to rollback, an in-memory database must journal
52652  ** the page we are moving from.
52653  */
52654  assert( pPager->tempFile || !MEMDB );
52655  if( pPager->tempFile ){
52656  rc = sqlite3PagerWrite(pPg);
52657  if( rc ) return rc;
52658  }
52659 
52660  /* If the page being moved is dirty and has not been saved by the latest
52661  ** savepoint, then save the current contents of the page into the
52662  ** sub-journal now. This is required to handle the following scenario:
52663  **
52664  ** BEGIN;
52665  ** <journal page X, then modify it in memory>
52666  ** SAVEPOINT one;
52667  ** <Move page X to location Y>
52668  ** ROLLBACK TO one;
52669  **
52670  ** If page X were not written to the sub-journal here, it would not
52671  ** be possible to restore its contents when the "ROLLBACK TO one"
52672  ** statement were is processed.
52673  **
52674  ** subjournalPage() may need to allocate space to store pPg->pgno into
52675  ** one or more savepoint bitvecs. This is the reason this function
52676  ** may return SQLITE_NOMEM.
52677  */
52678  if( (pPg->flags & PGHDR_DIRTY)!=0
52679  && SQLITE_OK!=(rc = subjournalPageIfRequired(pPg))
52680  ){
52681  return rc;
52682  }
52683 
52684  PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
52685  PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
52686  IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
52687 
52688  /* If the journal needs to be sync()ed before page pPg->pgno can
52689  ** be written to, store pPg->pgno in local variable needSyncPgno.
52690  **
52691  ** If the isCommit flag is set, there is no need to remember that
52692  ** the journal needs to be sync()ed before database page pPg->pgno
52693  ** can be written to. The caller has already promised not to write to it.
52694  */
52695  if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
52696  needSyncPgno = pPg->pgno;
52698  pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
52699  assert( pPg->flags&PGHDR_DIRTY );
52700  }
52701 
52702  /* If the cache contains a page with page-number pgno, remove it
52703  ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
52704  ** page pgno before the 'move' operation, it needs to be retained
52705  ** for the page moved there.
52706  */
52707  pPg->flags &= ~PGHDR_NEED_SYNC;
52708  pPgOld = sqlite3PagerLookup(pPager, pgno);
52709  assert( !pPgOld || pPgOld->nRef==1 );
52710  if( pPgOld ){
52711  pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
52712  if( pPager->tempFile ){
52713  /* Do not discard pages from an in-memory database since we might
52714  ** need to rollback later. Just move the page out of the way. */
52715  sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
52716  }else{
52717  sqlite3PcacheDrop(pPgOld);
52718  }
52719  }
52720 
52721  origPgno = pPg->pgno;
52722  sqlite3PcacheMove(pPg, pgno);
52724 
52725  /* For an in-memory database, make sure the original page continues
52726  ** to exist, in case the transaction needs to roll back. Use pPgOld
52727  ** as the original page since it has already been allocated.
52728  */
52729  if( pPager->tempFile && pPgOld ){
52730  sqlite3PcacheMove(pPgOld, origPgno);
52731  sqlite3PagerUnrefNotNull(pPgOld);
52732  }
52733 
52734  if( needSyncPgno ){
52735  /* If needSyncPgno is non-zero, then the journal file needs to be
52736  ** sync()ed before any data is written to database file page needSyncPgno.
52737  ** Currently, no such page exists in the page-cache and the
52738  ** "is journaled" bitvec flag has been set. This needs to be remedied by
52739  ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
52740  ** flag.
52741  **
52742  ** If the attempt to load the page into the page-cache fails, (due
52743  ** to a malloc() or IO failure), clear the bit in the pInJournal[]
52744  ** array. Otherwise, if the page is loaded and written again in
52745  ** this transaction, it may be written to the database file before
52746  ** it is synced into the journal file. This way, it may end up in
52747  ** the journal file twice, but that is not a problem.
52748  */
52749  PgHdr *pPgHdr;
52750  rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr, 0);
52751  if( rc!=SQLITE_OK ){
52752  if( needSyncPgno<=pPager->dbOrigSize ){
52753  assert( pPager->pTmpSpace!=0 );
52754  sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
52755  }
52756  return rc;
52757  }
52758  pPgHdr->flags |= PGHDR_NEED_SYNC;
52759  sqlite3PcacheMakeDirty(pPgHdr);
52760  sqlite3PagerUnrefNotNull(pPgHdr);
52761  }
52762 
52763  return SQLITE_OK;
52764 }
52765 #endif
52766 
52767 /*
52768 ** The page handle passed as the first argument refers to a dirty page
52769 ** with a page number other than iNew. This function changes the page's
52770 ** page number to iNew and sets the value of the PgHdr.flags field to
52771 ** the value passed as the third parameter.
52772 */
52773 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
52774  assert( pPg->pgno!=iNew );
52775  pPg->flags = flags;
52776  sqlite3PcacheMove(pPg, iNew);
52777 }
52778 
52779 /*
52780 ** Return a pointer to the data for the specified page.
52781 */
52783  assert( pPg->nRef>0 || pPg->pPager->memDb );
52784  return pPg->pData;
52785 }
52786 
52787 /*
52788 ** Return a pointer to the Pager.nExtra bytes of "extra" space
52789 ** allocated along with the specified page.
52790 */
52792  return pPg->pExtra;
52793 }
52794 
52795 /*
52796 ** Get/set the locking-mode for this pager. Parameter eMode must be one
52797 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
52798 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
52799 ** the locking-mode is set to the value specified.
52800 **
52801 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
52802 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
52803 ** locking-mode.
52804 */
52807  || eMode==PAGER_LOCKINGMODE_NORMAL
52808  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
52811  assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
52812  if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
52813  pPager->exclusiveMode = (u8)eMode;
52814  }
52815  return (int)pPager->exclusiveMode;
52816 }
52817 
52818 /*
52819 ** Set the journal-mode for this pager. Parameter eMode must be one of:
52820 **
52821 ** PAGER_JOURNALMODE_DELETE
52822 ** PAGER_JOURNALMODE_TRUNCATE
52823 ** PAGER_JOURNALMODE_PERSIST
52824 ** PAGER_JOURNALMODE_OFF
52825 ** PAGER_JOURNALMODE_MEMORY
52826 ** PAGER_JOURNALMODE_WAL
52827 **
52828 ** The journalmode is set to the value specified if the change is allowed.
52829 ** The change may be disallowed for the following reasons:
52830 **
52831 ** * An in-memory database can only have its journal_mode set to _OFF
52832 ** or _MEMORY.
52833 **
52834 ** * Temporary databases cannot have _WAL journalmode.
52835 **
52836 ** The returned indicate the current (possibly updated) journal-mode.
52837 */
52839  u8 eOld = pPager->journalMode; /* Prior journalmode */
52840 
52841 #ifdef SQLITE_DEBUG
52842  /* The print_pager_state() routine is intended to be used by the debugger
52843  ** only. We invoke it once here to suppress a compiler warning. */
52844  print_pager_state(pPager);
52845 #endif
52846 
52847 
52848  /* The eMode parameter is always valid */
52850  || eMode==PAGER_JOURNALMODE_TRUNCATE
52851  || eMode==PAGER_JOURNALMODE_PERSIST
52852  || eMode==PAGER_JOURNALMODE_OFF
52853  || eMode==PAGER_JOURNALMODE_WAL
52854  || eMode==PAGER_JOURNALMODE_MEMORY );
52855 
52856  /* This routine is only called from the OP_JournalMode opcode, and
52857  ** the logic there will never allow a temporary file to be changed
52858  ** to WAL mode.
52859  */
52860  assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
52861 
52862  /* Do allow the journalmode of an in-memory database to be set to
52863  ** anything other than MEMORY or OFF
52864  */
52865  if( MEMDB ){
52867  if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
52868  eMode = eOld;
52869  }
52870  }
52871 
52872  if( eMode!=eOld ){
52873 
52874  /* Change the journal mode. */
52875  assert( pPager->eState!=PAGER_ERROR );
52876  pPager->journalMode = (u8)eMode;
52877 
52878  /* When transistioning from TRUNCATE or PERSIST to any other journal
52879  ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
52880  ** delete the journal file.
52881  */
52882  assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
52883  assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
52884  assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
52885  assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
52886  assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
52887  assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
52888 
52889  assert( isOpen(pPager->fd) || pPager->exclusiveMode );
52890  if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
52891 
52892  /* In this case we would like to delete the journal file. If it is
52893  ** not possible, then that is not a problem. Deleting the journal file
52894  ** here is an optimization only.
52895  **
52896  ** Before deleting the journal file, obtain a RESERVED lock on the
52897  ** database file. This ensures that the journal file is not deleted
52898  ** while it is in use by some other client.
52899  */
52900  sqlite3OsClose(pPager->jfd);
52901  if( pPager->eLock>=RESERVED_LOCK ){
52902  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
52903  }else{
52904  int rc = SQLITE_OK;
52905  int state = pPager->eState;
52906  assert( state==PAGER_OPEN || state==PAGER_READER );
52907  if( state==PAGER_OPEN ){
52908  rc = sqlite3PagerSharedLock(pPager);
52909  }
52910  if( pPager->eState==PAGER_READER ){
52911  assert( rc==SQLITE_OK );
52912  rc = pagerLockDb(pPager, RESERVED_LOCK);
52913  }
52914  if( rc==SQLITE_OK ){
52915  sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
52916  }
52917  if( rc==SQLITE_OK && state==PAGER_READER ){
52918  pagerUnlockDb(pPager, SHARED_LOCK);
52919  }else if( state==PAGER_OPEN ){
52920  pager_unlock(pPager);
52921  }
52922  assert( state==pPager->eState );
52923  }
52924  }else if( eMode==PAGER_JOURNALMODE_OFF ){
52925  sqlite3OsClose(pPager->jfd);
52926  }
52927  }
52928 
52929  /* Return the new journal mode */
52930  return (int)pPager->journalMode;
52931 }
52932 
52933 /*
52934 ** Return the current journal mode.
52935 */
52937  return (int)pPager->journalMode;
52938 }
52939 
52940 /*
52941 ** Return TRUE if the pager is in a state where it is OK to change the
52942 ** journalmode. Journalmode changes can only happen when the database
52943 ** is unmodified.
52944 */
52946  assert( assert_pager_state(pPager) );
52947  if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
52948  if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
52949  return 1;
52950 }
52951 
52952 /*
52953 ** Get/set the size-limit used for persistent journal files.
52954 **
52955 ** Setting the size limit to -1 means no limit is enforced.
52956 ** An attempt to set a limit smaller than -1 is a no-op.
52957 */
52959  if( iLimit>=-1 ){
52960  pPager->journalSizeLimit = iLimit;
52961  sqlite3WalLimit(pPager->pWal, iLimit);
52962  }
52963  return pPager->journalSizeLimit;
52964 }
52965 
52966 /*
52967 ** Return a pointer to the pPager->pBackup variable. The backup module
52968 ** in backup.c maintains the content of this variable. This module
52969 ** uses it opaquely as an argument to sqlite3BackupRestart() and
52970 ** sqlite3BackupUpdate() only.
52971 */
52973  return &pPager->pBackup;
52974 }
52975 
52976 #ifndef SQLITE_OMIT_VACUUM
52977 /*
52978 ** Unless this is an in-memory or temporary database, clear the pager cache.
52979 */
52981  assert( MEMDB==0 || pPager->tempFile );
52982  if( pPager->tempFile==0 ) pager_reset(pPager);
52983 }
52984 #endif
52985 
52986 #ifndef SQLITE_OMIT_WAL
52987 /*
52988 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
52989 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
52990 ** or wal_blocking_checkpoint() API functions.
52991 **
52992 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
52993 */
52994 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
52995  int rc = SQLITE_OK;
52996  if( pPager->pWal ){
52997  rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
52998  (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
52999  pPager->pBusyHandlerArg,
53000  pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
53001  pnLog, pnCkpt
53002  );
53003  }
53004  return rc;
53005 }
53006 
53008  return sqlite3WalCallback(pPager->pWal);
53009 }
53010 
53011 /*
53012 ** Return true if the underlying VFS for the given pager supports the
53013 ** primitives necessary for write-ahead logging.
53014 */
53016  const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
53017  if( pPager->noLock ) return 0;
53018  return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
53019 }
53020 
53021 /*
53022 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
53023 ** is obtained instead, immediately release it.
53024 */
53025 static int pagerExclusiveLock(Pager *pPager){
53026  int rc; /* Return code */
53027 
53028  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53029  rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
53030  if( rc!=SQLITE_OK ){
53031  /* If the attempt to grab the exclusive lock failed, release the
53032  ** pending lock that may have been obtained instead. */
53033  pagerUnlockDb(pPager, SHARED_LOCK);
53034  }
53035 
53036  return rc;
53037 }
53038 
53039 /*
53040 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
53041 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
53042 ** lock on the database file and use heap-memory to store the wal-index
53043 ** in. Otherwise, use the normal shared-memory.
53044 */
53045 static int pagerOpenWal(Pager *pPager){
53046  int rc = SQLITE_OK;
53047 
53048  assert( pPager->pWal==0 && pPager->tempFile==0 );
53049  assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
53050 
53051  /* If the pager is already in exclusive-mode, the WAL module will use
53052  ** heap-memory for the wal-index instead of the VFS shared-memory
53053  ** implementation. Take the exclusive lock now, before opening the WAL
53054  ** file, to make sure this is safe.
53055  */
53056  if( pPager->exclusiveMode ){
53057  rc = pagerExclusiveLock(pPager);
53058  }
53059 
53060  /* Open the connection to the log file. If this operation fails,
53061  ** (e.g. due to malloc() failure), return an error code.
53062  */
53063  if( rc==SQLITE_OK ){
53064  rc = sqlite3WalOpen(pPager->pVfs,
53065  pPager->fd, pPager->zWal, pPager->exclusiveMode,
53066  pPager->journalSizeLimit, &pPager->pWal
53067  );
53068  }
53069  pagerFixMaplimit(pPager);
53070 
53071  return rc;
53072 }
53073 
53074 
53075 /*
53076 ** The caller must be holding a SHARED lock on the database file to call
53077 ** this function.
53078 **
53079 ** If the pager passed as the first argument is open on a real database
53080 ** file (not a temp file or an in-memory database), and the WAL file
53081 ** is not already open, make an attempt to open it now. If successful,
53082 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
53083 ** not support the xShmXXX() methods, return an error code. *pbOpen is
53084 ** not modified in either case.
53085 **
53086 ** If the pager is open on a temp-file (or in-memory database), or if
53087 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
53088 ** without doing anything.
53089 */
53091  Pager *pPager, /* Pager object */
53092  int *pbOpen /* OUT: Set to true if call is a no-op */
53093 ){
53094  int rc = SQLITE_OK; /* Return code */
53095 
53096  assert( assert_pager_state(pPager) );
53097  assert( pPager->eState==PAGER_OPEN || pbOpen );
53098  assert( pPager->eState==PAGER_READER || !pbOpen );
53099  assert( pbOpen==0 || *pbOpen==0 );
53100  assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
53101 
53102  if( !pPager->tempFile && !pPager->pWal ){
53103  if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
53104 
53105  /* Close any rollback journal previously open */
53106  sqlite3OsClose(pPager->jfd);
53107 
53108  rc = pagerOpenWal(pPager);
53109  if( rc==SQLITE_OK ){
53111  pPager->eState = PAGER_OPEN;
53112  }
53113  }else{
53114  *pbOpen = 1;
53115  }
53116 
53117  return rc;
53118 }
53119 
53120 /*
53121 ** This function is called to close the connection to the log file prior
53122 ** to switching from WAL to rollback mode.
53123 **
53124 ** Before closing the log file, this function attempts to take an
53125 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
53126 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
53127 ** If successful, the EXCLUSIVE lock is not released before returning.
53128 */
53130  int rc = SQLITE_OK;
53131 
53133 
53134  /* If the log file is not already open, but does exist in the file-system,
53135  ** it may need to be checkpointed before the connection can switch to
53136  ** rollback mode. Open it now so this can happen.
53137  */
53138  if( !pPager->pWal ){
53139  int logexists = 0;
53140  rc = pagerLockDb(pPager, SHARED_LOCK);
53141  if( rc==SQLITE_OK ){
53142  rc = sqlite3OsAccess(
53143  pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
53144  );
53145  }
53146  if( rc==SQLITE_OK && logexists ){
53147  rc = pagerOpenWal(pPager);
53148  }
53149  }
53150 
53151  /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
53152  ** the database file, the log and log-summary files will be deleted.
53153  */
53154  if( rc==SQLITE_OK && pPager->pWal ){
53155  rc = pagerExclusiveLock(pPager);
53156  if( rc==SQLITE_OK ){
53157  rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
53158  pPager->pageSize, (u8*)pPager->pTmpSpace);
53159  pPager->pWal = 0;
53160  pagerFixMaplimit(pPager);
53161  if( rc && !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
53162  }
53163  }
53164  return rc;
53165 }
53166 
53167 #ifdef SQLITE_ENABLE_SNAPSHOT
53168 /*
53169 ** If this is a WAL database, obtain a snapshot handle for the snapshot
53170 ** currently open. Otherwise, return an error.
53171 */
53172 SQLITE_PRIVATE int sqlite3PagerSnapshotGet(Pager *pPager, sqlite3_snapshot **ppSnapshot){
53173  int rc = SQLITE_ERROR;
53174  if( pPager->pWal ){
53175  rc = sqlite3WalSnapshotGet(pPager->pWal, ppSnapshot);
53176  }
53177  return rc;
53178 }
53179 
53180 /*
53181 ** If this is a WAL database, store a pointer to pSnapshot. Next time a
53182 ** read transaction is opened, attempt to read from the snapshot it
53183 ** identifies. If this is not a WAL database, return an error.
53184 */
53185 SQLITE_PRIVATE int sqlite3PagerSnapshotOpen(Pager *pPager, sqlite3_snapshot *pSnapshot){
53186  int rc = SQLITE_OK;
53187  if( pPager->pWal ){
53188  sqlite3WalSnapshotOpen(pPager->pWal, pSnapshot);
53189  }else{
53190  rc = SQLITE_ERROR;
53191  }
53192  return rc;
53193 }
53194 #endif /* SQLITE_ENABLE_SNAPSHOT */
53195 #endif /* !SQLITE_OMIT_WAL */
53196 
53197 #ifdef SQLITE_ENABLE_ZIPVFS
53198 /*
53199 ** A read-lock must be held on the pager when this function is called. If
53200 ** the pager is in WAL mode and the WAL file currently contains one or more
53201 ** frames, return the size in bytes of the page images stored within the
53202 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
53203 ** is empty, return 0.
53204 */
53205 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
53206  assert( pPager->eState>=PAGER_READER );
53207  return sqlite3WalFramesize(pPager->pWal);
53208 }
53209 #endif
53210 
53211 
53212 #endif /* SQLITE_OMIT_DISKIO */
53213 
53214 /************** End of pager.c ***********************************************/
53215 /************** Begin file wal.c *********************************************/
53216 /*
53217 ** 2010 February 1
53218 **
53219 ** The author disclaims copyright to this source code. In place of
53220 ** a legal notice, here is a blessing:
53221 **
53222 ** May you do good and not evil.
53223 ** May you find forgiveness for yourself and forgive others.
53224 ** May you share freely, never taking more than you give.
53225 **
53226 *************************************************************************
53227 **
53228 ** This file contains the implementation of a write-ahead log (WAL) used in
53229 ** "journal_mode=WAL" mode.
53230 **
53231 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
53232 **
53233 ** A WAL file consists of a header followed by zero or more "frames".
53234 ** Each frame records the revised content of a single page from the
53235 ** database file. All changes to the database are recorded by writing
53236 ** frames into the WAL. Transactions commit when a frame is written that
53237 ** contains a commit marker. A single WAL can and usually does record
53238 ** multiple transactions. Periodically, the content of the WAL is
53239 ** transferred back into the database file in an operation called a
53240 ** "checkpoint".
53241 **
53242 ** A single WAL file can be used multiple times. In other words, the
53243 ** WAL can fill up with frames and then be checkpointed and then new
53244 ** frames can overwrite the old ones. A WAL always grows from beginning
53245 ** toward the end. Checksums and counters attached to each frame are
53246 ** used to determine which frames within the WAL are valid and which
53247 ** are leftovers from prior checkpoints.
53248 **
53249 ** The WAL header is 32 bytes in size and consists of the following eight
53250 ** big-endian 32-bit unsigned integer values:
53251 **
53252 ** 0: Magic number. 0x377f0682 or 0x377f0683
53253 ** 4: File format version. Currently 3007000
53254 ** 8: Database page size. Example: 1024
53255 ** 12: Checkpoint sequence number
53256 ** 16: Salt-1, random integer incremented with each checkpoint
53257 ** 20: Salt-2, a different random integer changing with each ckpt
53258 ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
53259 ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
53260 **
53261 ** Immediately following the wal-header are zero or more frames. Each
53262 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
53263 ** of page data. The frame-header is six big-endian 32-bit unsigned
53264 ** integer values, as follows:
53265 **
53266 ** 0: Page number.
53267 ** 4: For commit records, the size of the database image in pages
53268 ** after the commit. For all other records, zero.
53269 ** 8: Salt-1 (copied from the header)
53270 ** 12: Salt-2 (copied from the header)
53271 ** 16: Checksum-1.
53272 ** 20: Checksum-2.
53273 **
53274 ** A frame is considered valid if and only if the following conditions are
53275 ** true:
53276 **
53277 ** (1) The salt-1 and salt-2 values in the frame-header match
53278 ** salt values in the wal-header
53279 **
53280 ** (2) The checksum values in the final 8 bytes of the frame-header
53281 ** exactly match the checksum computed consecutively on the
53282 ** WAL header and the first 8 bytes and the content of all frames
53283 ** up to and including the current frame.
53284 **
53285 ** The checksum is computed using 32-bit big-endian integers if the
53286 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
53287 ** is computed using little-endian if the magic number is 0x377f0682.
53288 ** The checksum values are always stored in the frame header in a
53289 ** big-endian format regardless of which byte order is used to compute
53290 ** the checksum. The checksum is computed by interpreting the input as
53291 ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
53292 ** algorithm used for the checksum is as follows:
53293 **
53294 ** for i from 0 to n-1 step 2:
53295 ** s0 += x[i] + s1;
53296 ** s1 += x[i+1] + s0;
53297 ** endfor
53298 **
53299 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
53300 ** in reverse order (the largest fibonacci weight occurs on the first element
53301 ** of the sequence being summed.) The s1 value spans all 32-bit
53302 ** terms of the sequence whereas s0 omits the final term.
53303 **
53304 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
53305 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
53306 ** The VFS.xSync operations serve as write barriers - all writes launched
53307 ** before the xSync must complete before any write that launches after the
53308 ** xSync begins.
53309 **
53310 ** After each checkpoint, the salt-1 value is incremented and the salt-2
53311 ** value is randomized. This prevents old and new frames in the WAL from
53312 ** being considered valid at the same time and being checkpointing together
53313 ** following a crash.
53314 **
53315 ** READER ALGORITHM
53316 **
53317 ** To read a page from the database (call it page number P), a reader
53318 ** first checks the WAL to see if it contains page P. If so, then the
53319 ** last valid instance of page P that is a followed by a commit frame
53320 ** or is a commit frame itself becomes the value read. If the WAL
53321 ** contains no copies of page P that are valid and which are a commit
53322 ** frame or are followed by a commit frame, then page P is read from
53323 ** the database file.
53324 **
53325 ** To start a read transaction, the reader records the index of the last
53326 ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
53327 ** for all subsequent read operations. New transactions can be appended
53328 ** to the WAL, but as long as the reader uses its original mxFrame value
53329 ** and ignores the newly appended content, it will see a consistent snapshot
53330 ** of the database from a single point in time. This technique allows
53331 ** multiple concurrent readers to view different versions of the database
53332 ** content simultaneously.
53333 **
53334 ** The reader algorithm in the previous paragraphs works correctly, but
53335 ** because frames for page P can appear anywhere within the WAL, the
53336 ** reader has to scan the entire WAL looking for page P frames. If the
53337 ** WAL is large (multiple megabytes is typical) that scan can be slow,
53338 ** and read performance suffers. To overcome this problem, a separate
53339 ** data structure called the wal-index is maintained to expedite the
53340 ** search for frames of a particular page.
53341 **
53342 ** WAL-INDEX FORMAT
53343 **
53344 ** Conceptually, the wal-index is shared memory, though VFS implementations
53345 ** might choose to implement the wal-index using a mmapped file. Because
53346 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
53347 ** on a network filesystem. All users of the database must be able to
53348 ** share memory.
53349 **
53350 ** The wal-index is transient. After a crash, the wal-index can (and should
53351 ** be) reconstructed from the original WAL file. In fact, the VFS is required
53352 ** to either truncate or zero the header of the wal-index when the last
53353 ** connection to it closes. Because the wal-index is transient, it can
53354 ** use an architecture-specific format; it does not have to be cross-platform.
53355 ** Hence, unlike the database and WAL file formats which store all values
53356 ** as big endian, the wal-index can store multi-byte values in the native
53357 ** byte order of the host computer.
53358 **
53359 ** The purpose of the wal-index is to answer this question quickly: Given
53360 ** a page number P and a maximum frame index M, return the index of the
53361 ** last frame in the wal before frame M for page P in the WAL, or return
53362 ** NULL if there are no frames for page P in the WAL prior to M.
53363 **
53364 ** The wal-index consists of a header region, followed by an one or
53365 ** more index blocks.
53366 **
53367 ** The wal-index header contains the total number of frames within the WAL
53368 ** in the mxFrame field.
53369 **
53370 ** Each index block except for the first contains information on
53371 ** HASHTABLE_NPAGE frames. The first index block contains information on
53372 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
53373 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
53374 ** first index block are the same size as all other index blocks in the
53375 ** wal-index.
53376 **
53377 ** Each index block contains two sections, a page-mapping that contains the
53378 ** database page number associated with each wal frame, and a hash-table
53379 ** that allows readers to query an index block for a specific page number.
53380 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
53381 ** for the first index block) 32-bit page numbers. The first entry in the
53382 ** first index-block contains the database page number corresponding to the
53383 ** first frame in the WAL file. The first entry in the second index block
53384 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
53385 ** the log, and so on.
53386 **
53387 ** The last index block in a wal-index usually contains less than the full
53388 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
53389 ** depending on the contents of the WAL file. This does not change the
53390 ** allocated size of the page-mapping array - the page-mapping array merely
53391 ** contains unused entries.
53392 **
53393 ** Even without using the hash table, the last frame for page P
53394 ** can be found by scanning the page-mapping sections of each index block
53395 ** starting with the last index block and moving toward the first, and
53396 ** within each index block, starting at the end and moving toward the
53397 ** beginning. The first entry that equals P corresponds to the frame
53398 ** holding the content for that page.
53399 **
53400 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
53401 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
53402 ** hash table for each page number in the mapping section, so the hash
53403 ** table is never more than half full. The expected number of collisions
53404 ** prior to finding a match is 1. Each entry of the hash table is an
53405 ** 1-based index of an entry in the mapping section of the same
53406 ** index block. Let K be the 1-based index of the largest entry in
53407 ** the mapping section. (For index blocks other than the last, K will
53408 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
53409 ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
53410 ** contain a value of 0.
53411 **
53412 ** To look for page P in the hash table, first compute a hash iKey on
53413 ** P as follows:
53414 **
53415 ** iKey = (P * 383) % HASHTABLE_NSLOT
53416 **
53417 ** Then start scanning entries of the hash table, starting with iKey
53418 ** (wrapping around to the beginning when the end of the hash table is
53419 ** reached) until an unused hash slot is found. Let the first unused slot
53420 ** be at index iUnused. (iUnused might be less than iKey if there was
53421 ** wrap-around.) Because the hash table is never more than half full,
53422 ** the search is guaranteed to eventually hit an unused entry. Let
53423 ** iMax be the value between iKey and iUnused, closest to iUnused,
53424 ** where aHash[iMax]==P. If there is no iMax entry (if there exists
53425 ** no hash slot such that aHash[i]==p) then page P is not in the
53426 ** current index block. Otherwise the iMax-th mapping entry of the
53427 ** current index block corresponds to the last entry that references
53428 ** page P.
53429 **
53430 ** A hash search begins with the last index block and moves toward the
53431 ** first index block, looking for entries corresponding to page P. On
53432 ** average, only two or three slots in each index block need to be
53433 ** examined in order to either find the last entry for page P, or to
53434 ** establish that no such entry exists in the block. Each index block
53435 ** holds over 4000 entries. So two or three index blocks are sufficient
53436 ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
53437 ** comparisons (on average) suffice to either locate a frame in the
53438 ** WAL or to establish that the frame does not exist in the WAL. This
53439 ** is much faster than scanning the entire 10MB WAL.
53440 **
53441 ** Note that entries are added in order of increasing K. Hence, one
53442 ** reader might be using some value K0 and a second reader that started
53443 ** at a later time (after additional transactions were added to the WAL
53444 ** and to the wal-index) might be using a different value K1, where K1>K0.
53445 ** Both readers can use the same hash table and mapping section to get
53446 ** the correct result. There may be entries in the hash table with
53447 ** K>K0 but to the first reader, those entries will appear to be unused
53448 ** slots in the hash table and so the first reader will get an answer as
53449 ** if no values greater than K0 had ever been inserted into the hash table
53450 ** in the first place - which is what reader one wants. Meanwhile, the
53451 ** second reader using K1 will see additional values that were inserted
53452 ** later, which is exactly what reader two wants.
53453 **
53454 ** When a rollback occurs, the value of K is decreased. Hash table entries
53455 ** that correspond to frames greater than the new K value are removed
53456 ** from the hash table at this point.
53457 */
53458 #ifndef SQLITE_OMIT_WAL
53459 
53460 /* #include "wal.h" */
53461 
53462 /*
53463 ** Trace output macros
53464 */
53465 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53466 SQLITE_PRIVATE int sqlite3WalTrace = 0;
53467 # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
53468 #else
53469 # define WALTRACE(X)
53470 #endif
53471 
53472 /*
53473 ** The maximum (and only) versions of the wal and wal-index formats
53474 ** that may be interpreted by this version of SQLite.
53475 **
53476 ** If a client begins recovering a WAL file and finds that (a) the checksum
53477 ** values in the wal-header are correct and (b) the version field is not
53478 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
53479 **
53480 ** Similarly, if a client successfully reads a wal-index header (i.e. the
53481 ** checksum test is successful) and finds that the version field is not
53482 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
53483 ** returns SQLITE_CANTOPEN.
53484 */
53485 #define WAL_MAX_VERSION 3007000
53486 #define WALINDEX_MAX_VERSION 3007000
53487 
53488 /*
53489 ** Indices of various locking bytes. WAL_NREADER is the number
53490 ** of available reader locks and should be at least 3. The default
53491 ** is SQLITE_SHM_NLOCK==8 and WAL_NREADER==5.
53492 */
53493 #define WAL_WRITE_LOCK 0
53494 #define WAL_ALL_BUT_WRITE 1
53495 #define WAL_CKPT_LOCK 1
53496 #define WAL_RECOVER_LOCK 2
53497 #define WAL_READ_LOCK(I) (3+(I))
53498 #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
53499 
53500 
53501 /* Object declarations */
53502 typedef struct WalIndexHdr WalIndexHdr;
53503 typedef struct WalIterator WalIterator;
53504 typedef struct WalCkptInfo WalCkptInfo;
53505 
53506 
53507 /*
53508 ** The following object holds a copy of the wal-index header content.
53509 **
53510 ** The actual header in the wal-index consists of two copies of this
53511 ** object followed by one instance of the WalCkptInfo object.
53512 ** For all versions of SQLite through 3.10.0 and probably beyond,
53513 ** the locking bytes (WalCkptInfo.aLock) start at offset 120 and
53514 ** the total header size is 136 bytes.
53515 **
53516 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
53517 ** Or it can be 1 to represent a 65536-byte page. The latter case was
53518 ** added in 3.7.1 when support for 64K pages was added.
53519 */
53520 struct WalIndexHdr {
53521  u32 iVersion; /* Wal-index version */
53522  u32 unused; /* Unused (padding) field */
53523  u32 iChange; /* Counter incremented each transaction */
53524  u8 isInit; /* 1 when initialized */
53525  u8 bigEndCksum; /* True if checksums in WAL are big-endian */
53526  u16 szPage; /* Database page size in bytes. 1==64K */
53527  u32 mxFrame; /* Index of last valid frame in the WAL */
53528  u32 nPage; /* Size of database in pages */
53529  u32 aFrameCksum[2]; /* Checksum of last frame in log */
53530  u32 aSalt[2]; /* Two salt values copied from WAL header */
53531  u32 aCksum[2]; /* Checksum over all prior fields */
53532 };
53533 
53534 /*
53535 ** A copy of the following object occurs in the wal-index immediately
53536 ** following the second copy of the WalIndexHdr. This object stores
53537 ** information used by checkpoint.
53538 **
53539 ** nBackfill is the number of frames in the WAL that have been written
53540 ** back into the database. (We call the act of moving content from WAL to
53541 ** database "backfilling".) The nBackfill number is never greater than
53542 ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
53543 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
53544 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
53545 ** mxFrame back to zero when the WAL is reset.
53546 **
53547 ** nBackfillAttempted is the largest value of nBackfill that a checkpoint
53548 ** has attempted to achieve. Normally nBackfill==nBackfillAtempted, however
53549 ** the nBackfillAttempted is set before any backfilling is done and the
53550 ** nBackfill is only set after all backfilling completes. So if a checkpoint
53551 ** crashes, nBackfillAttempted might be larger than nBackfill. The
53552 ** WalIndexHdr.mxFrame must never be less than nBackfillAttempted.
53553 **
53554 ** The aLock[] field is a set of bytes used for locking. These bytes should
53555 ** never be read or written.
53556 **
53557 ** There is one entry in aReadMark[] for each reader lock. If a reader
53558 ** holds read-lock K, then the value in aReadMark[K] is no greater than
53559 ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
53560 ** for any aReadMark[] means that entry is unused. aReadMark[0] is
53561 ** a special case; its value is never used and it exists as a place-holder
53562 ** to avoid having to offset aReadMark[] indexs by one. Readers holding
53563 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
53564 ** directly from the database.
53565 **
53566 ** The value of aReadMark[K] may only be changed by a thread that
53567 ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
53568 ** aReadMark[K] cannot changed while there is a reader is using that mark
53569 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
53570 **
53571 ** The checkpointer may only transfer frames from WAL to database where
53572 ** the frame numbers are less than or equal to every aReadMark[] that is
53573 ** in use (that is, every aReadMark[j] for which there is a corresponding
53574 ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
53575 ** largest value and will increase an unused aReadMark[] to mxFrame if there
53576 ** is not already an aReadMark[] equal to mxFrame. The exception to the
53577 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
53578 ** in the WAL has been backfilled into the database) then new readers
53579 ** will choose aReadMark[0] which has value 0 and hence such reader will
53580 ** get all their all content directly from the database file and ignore
53581 ** the WAL.
53582 **
53583 ** Writers normally append new frames to the end of the WAL. However,
53584 ** if nBackfill equals mxFrame (meaning that all WAL content has been
53585 ** written back into the database) and if no readers are using the WAL
53586 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
53587 ** the writer will first "reset" the WAL back to the beginning and start
53588 ** writing new content beginning at frame 1.
53589 **
53590 ** We assume that 32-bit loads are atomic and so no locks are needed in
53591 ** order to read from any aReadMark[] entries.
53592 */
53593 struct WalCkptInfo {
53594  u32 nBackfill; /* Number of WAL frames backfilled into DB */
53595  u32 aReadMark[WAL_NREADER]; /* Reader marks */
53596  u8 aLock[SQLITE_SHM_NLOCK]; /* Reserved space for locks */
53597  u32 nBackfillAttempted; /* WAL frames perhaps written, or maybe not */
53598  u32 notUsed0; /* Available for future enhancements */
53599 };
53600 #define READMARK_NOT_USED 0xffffffff
53601 
53602 
53603 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
53604 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
53605 ** only support mandatory file-locks, we do not read or write data
53606 ** from the region of the file on which locks are applied.
53607 */
53608 #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2+offsetof(WalCkptInfo,aLock))
53609 #define WALINDEX_HDR_SIZE (sizeof(WalIndexHdr)*2+sizeof(WalCkptInfo))
53610 
53611 /* Size of header before each frame in wal */
53612 #define WAL_FRAME_HDRSIZE 24
53613 
53614 /* Size of write ahead log header, including checksum. */
53615 /* #define WAL_HDRSIZE 24 */
53616 #define WAL_HDRSIZE 32
53617 
53618 /* WAL magic value. Either this value, or the same value with the least
53619 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
53620 ** big-endian format in the first 4 bytes of a WAL file.
53621 **
53622 ** If the LSB is set, then the checksums for each frame within the WAL
53623 ** file are calculated by treating all data as an array of 32-bit
53624 ** big-endian words. Otherwise, they are calculated by interpreting
53625 ** all data as 32-bit little-endian words.
53626 */
53627 #define WAL_MAGIC 0x377f0682
53628 
53629 /*
53630 ** Return the offset of frame iFrame in the write-ahead log file,
53631 ** assuming a database page size of szPage bytes. The offset returned
53632 ** is to the start of the write-ahead log frame-header.
53633 */
53634 #define walFrameOffset(iFrame, szPage) ( \
53635  WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
53636 )
53637 
53638 /*
53639 ** An open write-ahead log file is represented by an instance of the
53640 ** following object.
53641 */
53642 struct Wal {
53643  sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
53644  sqlite3_file *pDbFd; /* File handle for the database file */
53645  sqlite3_file *pWalFd; /* File handle for WAL file */
53646  u32 iCallback; /* Value to pass to log callback (or 0) */
53647  i64 mxWalSize; /* Truncate WAL to this size upon reset */
53648  int nWiData; /* Size of array apWiData */
53649  int szFirstBlock; /* Size of first block written to WAL file */
53650  volatile u32 **apWiData; /* Pointer to wal-index content in memory */
53651  u32 szPage; /* Database page size */
53652  i16 readLock; /* Which read lock is being held. -1 for none */
53653  u8 syncFlags; /* Flags to use to sync header writes */
53654  u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
53655  u8 writeLock; /* True if in a write transaction */
53656  u8 ckptLock; /* True if holding a checkpoint lock */
53657  u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
53658  u8 truncateOnCommit; /* True to truncate WAL file on commit */
53659  u8 syncHeader; /* Fsync the WAL header if true */
53660  u8 padToSectorBoundary; /* Pad transactions out to the next sector */
53661  WalIndexHdr hdr; /* Wal-index header for current transaction */
53662  u32 minFrame; /* Ignore wal frames before this one */
53663  u32 iReCksum; /* On commit, recalculate checksums from here */
53664  const char *zWalName; /* Name of WAL file */
53665  u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
53666 #ifdef SQLITE_DEBUG
53667  u8 lockError; /* True if a locking error has occurred */
53668 #endif
53669 #ifdef SQLITE_ENABLE_SNAPSHOT
53670  WalIndexHdr *pSnapshot; /* Start transaction here if not NULL */
53671 #endif
53672 };
53673 
53674 /*
53675 ** Candidate values for Wal.exclusiveMode.
53676 */
53677 #define WAL_NORMAL_MODE 0
53678 #define WAL_EXCLUSIVE_MODE 1
53679 #define WAL_HEAPMEMORY_MODE 2
53680 
53681 /*
53682 ** Possible values for WAL.readOnly
53683 */
53684 #define WAL_RDWR 0 /* Normal read/write connection */
53685 #define WAL_RDONLY 1 /* The WAL file is readonly */
53686 #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
53687 
53688 /*
53689 ** Each page of the wal-index mapping contains a hash-table made up of
53690 ** an array of HASHTABLE_NSLOT elements of the following type.
53691 */
53692 typedef u16 ht_slot;
53693 
53694 /*
53695 ** This structure is used to implement an iterator that loops through
53696 ** all frames in the WAL in database page order. Where two or more frames
53697 ** correspond to the same database page, the iterator visits only the
53698 ** frame most recently written to the WAL (in other words, the frame with
53699 ** the largest index).
53700 **
53701 ** The internals of this structure are only accessed by:
53702 **
53703 ** walIteratorInit() - Create a new iterator,
53704 ** walIteratorNext() - Step an iterator,
53705 ** walIteratorFree() - Free an iterator.
53706 **
53707 ** This functionality is used by the checkpoint code (see walCheckpoint()).
53708 */
53709 struct WalIterator {
53710  int iPrior; /* Last result returned from the iterator */
53711  int nSegment; /* Number of entries in aSegment[] */
53712  struct WalSegment {
53713  int iNext; /* Next slot in aIndex[] not yet returned */
53714  ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
53715  u32 *aPgno; /* Array of page numbers. */
53716  int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
53717  int iZero; /* Frame number associated with aPgno[0] */
53718  } aSegment[1]; /* One for every 32KB page in the wal-index */
53719 };
53720 
53721 /*
53722 ** Define the parameters of the hash tables in the wal-index file. There
53723 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
53724 ** wal-index.
53725 **
53726 ** Changing any of these constants will alter the wal-index format and
53727 ** create incompatibilities.
53728 */
53729 #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
53730 #define HASHTABLE_HASH_1 383 /* Should be prime */
53731 #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
53732 
53733 /*
53734 ** The block of page numbers associated with the first hash-table in a
53735 ** wal-index is smaller than usual. This is so that there is a complete
53736 ** hash-table on each aligned 32KB page of the wal-index.
53737 */
53738 #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
53739 
53740 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
53741 #define WALINDEX_PGSZ ( \
53742  sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
53743 )
53744 
53745 /*
53746 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
53747 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
53748 ** numbered from zero.
53749 **
53750 ** If this call is successful, *ppPage is set to point to the wal-index
53751 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
53752 ** then an SQLite error code is returned and *ppPage is set to 0.
53753 */
53754 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
53755  int rc = SQLITE_OK;
53756 
53757  /* Enlarge the pWal->apWiData[] array if required */
53758  if( pWal->nWiData<=iPage ){
53759  int nByte = sizeof(u32*)*(iPage+1);
53760  volatile u32 **apNew;
53761  apNew = (volatile u32 **)sqlite3_realloc64((void *)pWal->apWiData, nByte);
53762  if( !apNew ){
53763  *ppPage = 0;
53764  return SQLITE_NOMEM_BKPT;
53765  }
53766  memset((void*)&apNew[pWal->nWiData], 0,
53767  sizeof(u32*)*(iPage+1-pWal->nWiData));
53768  pWal->apWiData = apNew;
53769  pWal->nWiData = iPage+1;
53770  }
53771 
53772  /* Request a pointer to the required page from the VFS */
53773  if( pWal->apWiData[iPage]==0 ){
53774  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
53775  pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
53776  if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM_BKPT;
53777  }else{
53778  rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
53779  pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
53780  );
53781  if( rc==SQLITE_READONLY ){
53782  pWal->readOnly |= WAL_SHM_RDONLY;
53783  rc = SQLITE_OK;
53784  }
53785  }
53786  }
53787 
53788  *ppPage = pWal->apWiData[iPage];
53789  assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
53790  return rc;
53791 }
53792 
53793 /*
53794 ** Return a pointer to the WalCkptInfo structure in the wal-index.
53795 */
53796 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
53797  assert( pWal->nWiData>0 && pWal->apWiData[0] );
53798  return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
53799 }
53800 
53801 /*
53802 ** Return a pointer to the WalIndexHdr structure in the wal-index.
53803 */
53804 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
53805  assert( pWal->nWiData>0 && pWal->apWiData[0] );
53806  return (volatile WalIndexHdr*)pWal->apWiData[0];
53807 }
53808 
53809 /*
53810 ** The argument to this macro must be of type u32. On a little-endian
53811 ** architecture, it returns the u32 value that results from interpreting
53812 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
53813 ** returns the value that would be produced by interpreting the 4 bytes
53814 ** of the input value as a little-endian integer.
53815 */
53816 #define BYTESWAP32(x) ( \
53817  (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
53818  + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
53819 )
53820 
53821 /*
53822 ** Generate or extend an 8 byte checksum based on the data in
53823 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
53824 ** initial values of 0 and 0 if aIn==NULL).
53825 **
53826 ** The checksum is written back into aOut[] before returning.
53827 **
53828 ** nByte must be a positive multiple of 8.
53829 */
53830 static void walChecksumBytes(
53831  int nativeCksum, /* True for native byte-order, false for non-native */
53832  u8 *a, /* Content to be checksummed */
53833  int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
53834  const u32 *aIn, /* Initial checksum value input */
53835  u32 *aOut /* OUT: Final checksum value output */
53836 ){
53837  u32 s1, s2;
53838  u32 *aData = (u32 *)a;
53839  u32 *aEnd = (u32 *)&a[nByte];
53840 
53841  if( aIn ){
53842  s1 = aIn[0];
53843  s2 = aIn[1];
53844  }else{
53845  s1 = s2 = 0;
53846  }
53847 
53848  assert( nByte>=8 );
53849  assert( (nByte&0x00000007)==0 );
53850 
53851  if( nativeCksum ){
53852  do {
53853  s1 += *aData++ + s2;
53854  s2 += *aData++ + s1;
53855  }while( aData<aEnd );
53856  }else{
53857  do {
53858  s1 += BYTESWAP32(aData[0]) + s2;
53859  s2 += BYTESWAP32(aData[1]) + s1;
53860  aData += 2;
53861  }while( aData<aEnd );
53862  }
53863 
53864  aOut[0] = s1;
53865  aOut[1] = s2;
53866 }
53867 
53868 static void walShmBarrier(Wal *pWal){
53869  if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
53870  sqlite3OsShmBarrier(pWal->pDbFd);
53871  }
53872 }
53873 
53874 /*
53875 ** Write the header information in pWal->hdr into the wal-index.
53876 **
53877 ** The checksum on pWal->hdr is updated before it is written.
53878 */
53879 static void walIndexWriteHdr(Wal *pWal){
53880  volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
53881  const int nCksum = offsetof(WalIndexHdr, aCksum);
53882 
53883  assert( pWal->writeLock );
53884  pWal->hdr.isInit = 1;
53886  walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
53887  memcpy((void*)&aHdr[1], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
53888  walShmBarrier(pWal);
53889  memcpy((void*)&aHdr[0], (const void*)&pWal->hdr, sizeof(WalIndexHdr));
53890 }
53891 
53892 /*
53893 ** This function encodes a single frame header and writes it to a buffer
53894 ** supplied by the caller. A frame-header is made up of a series of
53895 ** 4-byte big-endian integers, as follows:
53896 **
53897 ** 0: Page number.
53898 ** 4: For commit records, the size of the database image in pages
53899 ** after the commit. For all other records, zero.
53900 ** 8: Salt-1 (copied from the wal-header)
53901 ** 12: Salt-2 (copied from the wal-header)
53902 ** 16: Checksum-1.
53903 ** 20: Checksum-2.
53904 */
53905 static void walEncodeFrame(
53906  Wal *pWal, /* The write-ahead log */
53907  u32 iPage, /* Database page number for frame */
53908  u32 nTruncate, /* New db size (or 0 for non-commit frames) */
53909  u8 *aData, /* Pointer to page data */
53910  u8 *aFrame /* OUT: Write encoded frame here */
53911 ){
53912  int nativeCksum; /* True for native byte-order checksums */
53913  u32 *aCksum = pWal->hdr.aFrameCksum;
53914  assert( WAL_FRAME_HDRSIZE==24 );
53915  sqlite3Put4byte(&aFrame[0], iPage);
53916  sqlite3Put4byte(&aFrame[4], nTruncate);
53917  if( pWal->iReCksum==0 ){
53918  memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
53919 
53920  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
53921  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
53922  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
53923 
53924  sqlite3Put4byte(&aFrame[16], aCksum[0]);
53925  sqlite3Put4byte(&aFrame[20], aCksum[1]);
53926  }else{
53927  memset(&aFrame[8], 0, 16);
53928  }
53929 }
53930 
53931 /*
53932 ** Check to see if the frame with header in aFrame[] and content
53933 ** in aData[] is valid. If it is a valid frame, fill *piPage and
53934 ** *pnTruncate and return true. Return if the frame is not valid.
53935 */
53936 static int walDecodeFrame(
53937  Wal *pWal, /* The write-ahead log */
53938  u32 *piPage, /* OUT: Database page number for frame */
53939  u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
53940  u8 *aData, /* Pointer to page data (for checksum) */
53941  u8 *aFrame /* Frame data */
53942 ){
53943  int nativeCksum; /* True for native byte-order checksums */
53944  u32 *aCksum = pWal->hdr.aFrameCksum;
53945  u32 pgno; /* Page number of the frame */
53946  assert( WAL_FRAME_HDRSIZE==24 );
53947 
53948  /* A frame is only valid if the salt values in the frame-header
53949  ** match the salt values in the wal-header.
53950  */
53951  if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
53952  return 0;
53953  }
53954 
53955  /* A frame is only valid if the page number is creater than zero.
53956  */
53957  pgno = sqlite3Get4byte(&aFrame[0]);
53958  if( pgno==0 ){
53959  return 0;
53960  }
53961 
53962  /* A frame is only valid if a checksum of the WAL header,
53963  ** all prior frams, the first 16 bytes of this frame-header,
53964  ** and the frame-data matches the checksum in the last 8
53965  ** bytes of this frame-header.
53966  */
53967  nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
53968  walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
53969  walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
53970  if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
53971  || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
53972  ){
53973  /* Checksum failed. */
53974  return 0;
53975  }
53976 
53977  /* If we reach this point, the frame is valid. Return the page number
53978  ** and the new database size.
53979  */
53980  *piPage = pgno;
53981  *pnTruncate = sqlite3Get4byte(&aFrame[4]);
53982  return 1;
53983 }
53984 
53985 
53986 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
53987 /*
53988 ** Names of locks. This routine is used to provide debugging output and is not
53989 ** a part of an ordinary build.
53990 */
53991 static const char *walLockName(int lockIdx){
53992  if( lockIdx==WAL_WRITE_LOCK ){
53993  return "WRITE-LOCK";
53994  }else if( lockIdx==WAL_CKPT_LOCK ){
53995  return "CKPT-LOCK";
53996  }else if( lockIdx==WAL_RECOVER_LOCK ){
53997  return "RECOVER-LOCK";
53998  }else{
53999  static char zName[15];
54000  sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
54001  lockIdx-WAL_READ_LOCK(0));
54002  return zName;
54003  }
54004 }
54005 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
54006 
54007 
54008 /*
54009 ** Set or release locks on the WAL. Locks are either shared or exclusive.
54010 ** A lock cannot be moved directly between shared and exclusive - it must go
54011 ** through the unlocked state first.
54012 **
54013 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
54014 */
54015 static int walLockShared(Wal *pWal, int lockIdx){
54016  int rc;
54017  if( pWal->exclusiveMode ) return SQLITE_OK;
54018  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54020  WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
54021  walLockName(lockIdx), rc ? "failed" : "ok"));
54022  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54023  return rc;
54024 }
54025 static void walUnlockShared(Wal *pWal, int lockIdx){
54026  if( pWal->exclusiveMode ) return;
54027  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
54029  WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
54030 }
54031 static int walLockExclusive(Wal *pWal, int lockIdx, int n){
54032  int rc;
54033  if( pWal->exclusiveMode ) return SQLITE_OK;
54034  rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54036  WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
54037  walLockName(lockIdx), n, rc ? "failed" : "ok"));
54038  VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
54039  return rc;
54040 }
54041 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
54042  if( pWal->exclusiveMode ) return;
54043  (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
54045  WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
54046  walLockName(lockIdx), n));
54047 }
54048 
54049 /*
54050 ** Compute a hash on a page number. The resulting hash value must land
54051 ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
54052 ** the hash to the next value in the event of a collision.
54053 */
54054 static int walHash(u32 iPage){
54055  assert( iPage>0 );
54056  assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
54057  return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
54058 }
54059 static int walNextHash(int iPriorHash){
54060  return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
54061 }
54062 
54063 /*
54064 ** Return pointers to the hash table and page number array stored on
54065 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
54066 ** numbered starting from 0.
54067 **
54068 ** Set output variable *paHash to point to the start of the hash table
54069 ** in the wal-index file. Set *piZero to one less than the frame
54070 ** number of the first frame indexed by this hash table. If a
54071 ** slot in the hash table is set to N, it refers to frame number
54072 ** (*piZero+N) in the log.
54073 **
54074 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
54075 ** first frame indexed by the hash table, frame (*piZero+1).
54076 */
54077 static int walHashGet(
54078  Wal *pWal, /* WAL handle */
54079  int iHash, /* Find the iHash'th table */
54080  volatile ht_slot **paHash, /* OUT: Pointer to hash index */
54081  volatile u32 **paPgno, /* OUT: Pointer to page number array */
54082  u32 *piZero /* OUT: Frame associated with *paPgno[0] */
54083 ){
54084  int rc; /* Return code */
54085  volatile u32 *aPgno;
54086 
54087  rc = walIndexPage(pWal, iHash, &aPgno);
54088  assert( rc==SQLITE_OK || iHash>0 );
54089 
54090  if( rc==SQLITE_OK ){
54091  u32 iZero;
54092  volatile ht_slot *aHash;
54093 
54094  aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
54095  if( iHash==0 ){
54096  aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
54097  iZero = 0;
54098  }else{
54099  iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
54100  }
54101 
54102  *paPgno = &aPgno[-1];
54103  *paHash = aHash;
54104  *piZero = iZero;
54105  }
54106  return rc;
54107 }
54108 
54109 /*
54110 ** Return the number of the wal-index page that contains the hash-table
54111 ** and page-number array that contain entries corresponding to WAL frame
54112 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
54113 ** are numbered starting from 0.
54114 */
54115 static int walFramePage(u32 iFrame){
54116  int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
54117  assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
54118  && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
54119  && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
54120  && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
54121  && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
54122  );
54123  return iHash;
54124 }
54125 
54126 /*
54127 ** Return the page number associated with frame iFrame in this WAL.
54128 */
54129 static u32 walFramePgno(Wal *pWal, u32 iFrame){
54130  int iHash = walFramePage(iFrame);
54131  if( iHash==0 ){
54132  return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
54133  }
54134  return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
54135 }
54136 
54137 /*
54138 ** Remove entries from the hash table that point to WAL slots greater
54139 ** than pWal->hdr.mxFrame.
54140 **
54141 ** This function is called whenever pWal->hdr.mxFrame is decreased due
54142 ** to a rollback or savepoint.
54143 **
54144 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
54145 ** updated. Any later hash tables will be automatically cleared when
54146 ** pWal->hdr.mxFrame advances to the point where those hash tables are
54147 ** actually needed.
54148 */
54149 static void walCleanupHash(Wal *pWal){
54150  volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
54151  volatile u32 *aPgno = 0; /* Page number array for hash table */
54152  u32 iZero = 0; /* frame == (aHash[x]+iZero) */
54153  int iLimit = 0; /* Zero values greater than this */
54154  int nByte; /* Number of bytes to zero in aPgno[] */
54155  int i; /* Used to iterate through aHash[] */
54156 
54157  assert( pWal->writeLock );
54161 
54162  if( pWal->hdr.mxFrame==0 ) return;
54163 
54164  /* Obtain pointers to the hash-table and page-number array containing
54165  ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
54166  ** that the page said hash-table and array reside on is already mapped.
54167  */
54168  assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
54169  assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
54170  walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
54171 
54172  /* Zero all hash-table entries that correspond to frame numbers greater
54173  ** than pWal->hdr.mxFrame.
54174  */
54175  iLimit = pWal->hdr.mxFrame - iZero;
54176  assert( iLimit>0 );
54177  for(i=0; i<HASHTABLE_NSLOT; i++){
54178  if( aHash[i]>iLimit ){
54179  aHash[i] = 0;
54180  }
54181  }
54182 
54183  /* Zero the entries in the aPgno array that correspond to frames with
54184  ** frame numbers greater than pWal->hdr.mxFrame.
54185  */
54186  nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
54187  memset((void *)&aPgno[iLimit+1], 0, nByte);
54188 
54189 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54190  /* Verify that the every entry in the mapping region is still reachable
54191  ** via the hash table even after the cleanup.
54192  */
54193  if( iLimit ){
54194  int j; /* Loop counter */
54195  int iKey; /* Hash key */
54196  for(j=1; j<=iLimit; j++){
54197  for(iKey=walHash(aPgno[j]); aHash[iKey]; iKey=walNextHash(iKey)){
54198  if( aHash[iKey]==j ) break;
54199  }
54200  assert( aHash[iKey]==j );
54201  }
54202  }
54203 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54204 }
54205 
54206 
54207 /*
54208 ** Set an entry in the wal-index that will map database page number
54209 ** pPage into WAL frame iFrame.
54210 */
54211 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
54212  int rc; /* Return code */
54213  u32 iZero = 0; /* One less than frame number of aPgno[1] */
54214  volatile u32 *aPgno = 0; /* Page number array */
54215  volatile ht_slot *aHash = 0; /* Hash table */
54216 
54217  rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
54218 
54219  /* Assuming the wal-index file was successfully mapped, populate the
54220  ** page number array and hash table entry.
54221  */
54222  if( rc==SQLITE_OK ){
54223  int iKey; /* Hash table key */
54224  int idx; /* Value to write to hash-table slot */
54225  int nCollide; /* Number of hash collisions */
54226 
54227  idx = iFrame - iZero;
54228  assert( idx <= HASHTABLE_NSLOT/2 + 1 );
54229 
54230  /* If this is the first entry to be added to this hash-table, zero the
54231  ** entire hash table and aPgno[] array before proceeding.
54232  */
54233  if( idx==1 ){
54234  int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
54235  memset((void*)&aPgno[1], 0, nByte);
54236  }
54237 
54238  /* If the entry in aPgno[] is already set, then the previous writer
54239  ** must have exited unexpectedly in the middle of a transaction (after
54240  ** writing one or more dirty pages to the WAL to free up memory).
54241  ** Remove the remnants of that writers uncommitted transaction from
54242  ** the hash-table before writing any new entries.
54243  */
54244  if( aPgno[idx] ){
54245  walCleanupHash(pWal);
54246  assert( !aPgno[idx] );
54247  }
54248 
54249  /* Write the aPgno[] array entry and the hash-table slot. */
54250  nCollide = idx;
54251  for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
54252  if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
54253  }
54254  aPgno[idx] = iPage;
54255  aHash[iKey] = (ht_slot)idx;
54256 
54257 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
54258  /* Verify that the number of entries in the hash table exactly equals
54259  ** the number of entries in the mapping region.
54260  */
54261  {
54262  int i; /* Loop counter */
54263  int nEntry = 0; /* Number of entries in the hash table */
54264  for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
54265  assert( nEntry==idx );
54266  }
54267 
54268  /* Verify that the every entry in the mapping region is reachable
54269  ** via the hash table. This turns out to be a really, really expensive
54270  ** thing to check, so only do this occasionally - not on every
54271  ** iteration.
54272  */
54273  if( (idx&0x3ff)==0 ){
54274  int i; /* Loop counter */
54275  for(i=1; i<=idx; i++){
54276  for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
54277  if( aHash[iKey]==i ) break;
54278  }
54279  assert( aHash[iKey]==i );
54280  }
54281  }
54282 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
54283  }
54284 
54285 
54286  return rc;
54287 }
54288 
54289 
54290 /*
54291 ** Recover the wal-index by reading the write-ahead log file.
54292 **
54293 ** This routine first tries to establish an exclusive lock on the
54294 ** wal-index to prevent other threads/processes from doing anything
54295 ** with the WAL or wal-index while recovery is running. The
54296 ** WAL_RECOVER_LOCK is also held so that other threads will know
54297 ** that this thread is running recovery. If unable to establish
54298 ** the necessary locks, this routine returns SQLITE_BUSY.
54299 */
54300 static int walIndexRecover(Wal *pWal){
54301  int rc; /* Return Code */
54302  i64 nSize; /* Size of log file */
54303  u32 aFrameCksum[2] = {0, 0};
54304  int iLock; /* Lock offset to lock for checkpoint */
54305  int nLock; /* Number of locks to hold */
54306 
54307  /* Obtain an exclusive lock on all byte in the locking range not already
54308  ** locked by the caller. The caller is guaranteed to have locked the
54309  ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
54310  ** If successful, the same bytes that are locked here are unlocked before
54311  ** this function returns.
54312  */
54313  assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
54316  assert( pWal->writeLock );
54317  iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
54318  nLock = SQLITE_SHM_NLOCK - iLock;
54319  rc = walLockExclusive(pWal, iLock, nLock);
54320  if( rc ){
54321  return rc;
54322  }
54323  WALTRACE(("WAL%p: recovery begin...\n", pWal));
54324 
54325  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
54326 
54327  rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
54328  if( rc!=SQLITE_OK ){
54329  goto recovery_error;
54330  }
54331 
54332  if( nSize>WAL_HDRSIZE ){
54333  u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
54334  u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
54335  int szFrame; /* Number of bytes in buffer aFrame[] */
54336  u8 *aData; /* Pointer to data part of aFrame buffer */
54337  int iFrame; /* Index of last frame read */
54338  i64 iOffset; /* Next offset to read from log file */
54339  int szPage; /* Page size according to the log */
54340  u32 magic; /* Magic value read from WAL header */
54341  u32 version; /* Magic value read from WAL header */
54342  int isValid; /* True if this frame is valid */
54343 
54344  /* Read in the WAL header. */
54345  rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
54346  if( rc!=SQLITE_OK ){
54347  goto recovery_error;
54348  }
54349 
54350  /* If the database page size is not a power of two, or is greater than
54351  ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
54352  ** data. Similarly, if the 'magic' value is invalid, ignore the whole
54353  ** WAL file.
54354  */
54355  magic = sqlite3Get4byte(&aBuf[0]);
54356  szPage = sqlite3Get4byte(&aBuf[8]);
54357  if( (magic&0xFFFFFFFE)!=WAL_MAGIC
54358  || szPage&(szPage-1)
54359  || szPage>SQLITE_MAX_PAGE_SIZE
54360  || szPage<512
54361  ){
54362  goto finished;
54363  }
54364  pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
54365  pWal->szPage = szPage;
54366  pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
54367  memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
54368 
54369  /* Verify that the WAL header checksum is correct */
54371  aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
54372  );
54373  if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
54374  || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
54375  ){
54376  goto finished;
54377  }
54378 
54379  /* Verify that the version number on the WAL format is one that
54380  ** are able to understand */
54381  version = sqlite3Get4byte(&aBuf[4]);
54382  if( version!=WAL_MAX_VERSION ){
54383  rc = SQLITE_CANTOPEN_BKPT;
54384  goto finished;
54385  }
54386 
54387  /* Malloc a buffer to read frames into. */
54388  szFrame = szPage + WAL_FRAME_HDRSIZE;
54389  aFrame = (u8 *)sqlite3_malloc64(szFrame);
54390  if( !aFrame ){
54391  rc = SQLITE_NOMEM_BKPT;
54392  goto recovery_error;
54393  }
54394  aData = &aFrame[WAL_FRAME_HDRSIZE];
54395 
54396  /* Read all frames from the log file. */
54397  iFrame = 0;
54398  for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
54399  u32 pgno; /* Database page number for frame */
54400  u32 nTruncate; /* dbsize field from frame header */
54401 
54402  /* Read and decode the next log frame. */
54403  iFrame++;
54404  rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
54405  if( rc!=SQLITE_OK ) break;
54406  isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
54407  if( !isValid ) break;
54408  rc = walIndexAppend(pWal, iFrame, pgno);
54409  if( rc!=SQLITE_OK ) break;
54410 
54411  /* If nTruncate is non-zero, this is a commit record. */
54412  if( nTruncate ){
54413  pWal->hdr.mxFrame = iFrame;
54414  pWal->hdr.nPage = nTruncate;
54415  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
54416  testcase( szPage<=32768 );
54417  testcase( szPage>=65536 );
54418  aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
54419  aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
54420  }
54421  }
54422 
54423  sqlite3_free(aFrame);
54424  }
54425 
54426 finished:
54427  if( rc==SQLITE_OK ){
54428  volatile WalCkptInfo *pInfo;
54429  int i;
54430  pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
54431  pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
54432  walIndexWriteHdr(pWal);
54433 
54434  /* Reset the checkpoint-header. This is safe because this thread is
54435  ** currently holding locks that exclude all other readers, writers and
54436  ** checkpointers.
54437  */
54438  pInfo = walCkptInfo(pWal);
54439  pInfo->nBackfill = 0;
54440  pInfo->nBackfillAttempted = pWal->hdr.mxFrame;
54441  pInfo->aReadMark[0] = 0;
54442  for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
54443  if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
54444 
54445  /* If more than one frame was recovered from the log file, report an
54446  ** event via sqlite3_log(). This is to help with identifying performance
54447  ** problems caused by applications routinely shutting down without
54448  ** checkpointing the log file.
54449  */
54450  if( pWal->hdr.nPage ){
54452  "recovered %d frames from WAL file %s",
54453  pWal->hdr.mxFrame, pWal->zWalName
54454  );
54455  }
54456  }
54457 
54458 recovery_error:
54459  WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
54460  walUnlockExclusive(pWal, iLock, nLock);
54461  return rc;
54462 }
54463 
54464 /*
54465 ** Close an open wal-index.
54466 */
54467 static void walIndexClose(Wal *pWal, int isDelete){
54468  if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
54469  int i;
54470  for(i=0; i<pWal->nWiData; i++){
54471  sqlite3_free((void *)pWal->apWiData[i]);
54472  pWal->apWiData[i] = 0;
54473  }
54474  }else{
54475  sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
54476  }
54477 }
54478 
54479 /*
54480 ** Open a connection to the WAL file zWalName. The database file must
54481 ** already be opened on connection pDbFd. The buffer that zWalName points
54482 ** to must remain valid for the lifetime of the returned Wal* handle.
54483 **
54484 ** A SHARED lock should be held on the database file when this function
54485 ** is called. The purpose of this SHARED lock is to prevent any other
54486 ** client from unlinking the WAL or wal-index file. If another process
54487 ** were to do this just after this client opened one of these files, the
54488 ** system would be badly broken.
54489 **
54490 ** If the log file is successfully opened, SQLITE_OK is returned and
54491 ** *ppWal is set to point to a new WAL handle. If an error occurs,
54492 ** an SQLite error code is returned and *ppWal is left unmodified.
54493 */
54495  sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
54496  sqlite3_file *pDbFd, /* The open database file */
54497  const char *zWalName, /* Name of the WAL file */
54498  int bNoShm, /* True to run in heap-memory mode */
54499  i64 mxWalSize, /* Truncate WAL to this size on reset */
54500  Wal **ppWal /* OUT: Allocated Wal handle */
54501 ){
54502  int rc; /* Return Code */
54503  Wal *pRet; /* Object to allocate and return */
54504  int flags; /* Flags passed to OsOpen() */
54505 
54506  assert( zWalName && zWalName[0] );
54507  assert( pDbFd );
54508 
54509  /* In the amalgamation, the os_unix.c and os_win.c source files come before
54510  ** this source file. Verify that the #defines of the locking byte offsets
54511  ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
54512  ** For that matter, if the lock offset ever changes from its initial design
54513  ** value of 120, we need to know that so there is an assert() to check it.
54514  */
54515  assert( 120==WALINDEX_LOCK_OFFSET );
54516  assert( 136==WALINDEX_HDR_SIZE );
54517 #ifdef WIN_SHM_BASE
54518  assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
54519 #endif
54520 #ifdef UNIX_SHM_BASE
54522 #endif
54523 
54524 
54525  /* Allocate an instance of struct Wal to return. */
54526  *ppWal = 0;
54527  pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
54528  if( !pRet ){
54529  return SQLITE_NOMEM_BKPT;
54530  }
54531 
54532  pRet->pVfs = pVfs;
54533  pRet->pWalFd = (sqlite3_file *)&pRet[1];
54534  pRet->pDbFd = pDbFd;
54535  pRet->readLock = -1;
54536  pRet->mxWalSize = mxWalSize;
54537  pRet->zWalName = zWalName;
54538  pRet->syncHeader = 1;
54539  pRet->padToSectorBoundary = 1;
54541 
54542  /* Open file handle on the write-ahead log file. */
54544  rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
54545  if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
54546  pRet->readOnly = WAL_RDONLY;
54547  }
54548 
54549  if( rc!=SQLITE_OK ){
54550  walIndexClose(pRet, 0);
54551  sqlite3OsClose(pRet->pWalFd);
54552  sqlite3_free(pRet);
54553  }else{
54554  int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
54555  if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
54557  pRet->padToSectorBoundary = 0;
54558  }
54559  *ppWal = pRet;
54560  WALTRACE(("WAL%d: opened\n", pRet));
54561  }
54562  return rc;
54563 }
54564 
54565 /*
54566 ** Change the size to which the WAL file is trucated on each reset.
54567 */
54568 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
54569  if( pWal ) pWal->mxWalSize = iLimit;
54570 }
54571 
54572 /*
54573 ** Find the smallest page number out of all pages held in the WAL that
54574 ** has not been returned by any prior invocation of this method on the
54575 ** same WalIterator object. Write into *piFrame the frame index where
54576 ** that page was last written into the WAL. Write into *piPage the page
54577 ** number.
54578 **
54579 ** Return 0 on success. If there are no pages in the WAL with a page
54580 ** number larger than *piPage, then return 1.
54581 */
54582 static int walIteratorNext(
54583  WalIterator *p, /* Iterator */
54584  u32 *piPage, /* OUT: The page number of the next page */
54585  u32 *piFrame /* OUT: Wal frame index of next page */
54586 ){
54587  u32 iMin; /* Result pgno must be greater than iMin */
54588  u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
54589  int i; /* For looping through segments */
54590 
54591  iMin = p->iPrior;
54592  assert( iMin<0xffffffff );
54593  for(i=p->nSegment-1; i>=0; i--){
54594  struct WalSegment *pSegment = &p->aSegment[i];
54595  while( pSegment->iNext<pSegment->nEntry ){
54596  u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
54597  if( iPg>iMin ){
54598  if( iPg<iRet ){
54599  iRet = iPg;
54600  *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
54601  }
54602  break;
54603  }
54604  pSegment->iNext++;
54605  }
54606  }
54607 
54608  *piPage = p->iPrior = iRet;
54609  return (iRet==0xFFFFFFFF);
54610 }
54611 
54612 /*
54613 ** This function merges two sorted lists into a single sorted list.
54614 **
54615 ** aLeft[] and aRight[] are arrays of indices. The sort key is
54616 ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
54617 ** is guaranteed for all J<K:
54618 **
54619 ** aContent[aLeft[J]] < aContent[aLeft[K]]
54620 ** aContent[aRight[J]] < aContent[aRight[K]]
54621 **
54622 ** This routine overwrites aRight[] with a new (probably longer) sequence
54623 ** of indices such that the aRight[] contains every index that appears in
54624 ** either aLeft[] or the old aRight[] and such that the second condition
54625 ** above is still met.
54626 **
54627 ** The aContent[aLeft[X]] values will be unique for all X. And the
54628 ** aContent[aRight[X]] values will be unique too. But there might be
54629 ** one or more combinations of X and Y such that
54630 **
54631 ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
54632 **
54633 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
54634 */
54635 static void walMerge(
54636  const u32 *aContent, /* Pages in wal - keys for the sort */
54637  ht_slot *aLeft, /* IN: Left hand input list */
54638  int nLeft, /* IN: Elements in array *paLeft */
54639  ht_slot **paRight, /* IN/OUT: Right hand input list */
54640  int *pnRight, /* IN/OUT: Elements in *paRight */
54641  ht_slot *aTmp /* Temporary buffer */
54642 ){
54643  int iLeft = 0; /* Current index in aLeft */
54644  int iRight = 0; /* Current index in aRight */
54645  int iOut = 0; /* Current index in output buffer */
54646  int nRight = *pnRight;
54647  ht_slot *aRight = *paRight;
54648 
54649  assert( nLeft>0 && nRight>0 );
54650  while( iRight<nRight || iLeft<nLeft ){
54651  ht_slot logpage;
54652  Pgno dbpage;
54653 
54654  if( (iLeft<nLeft)
54655  && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
54656  ){
54657  logpage = aLeft[iLeft++];
54658  }else{
54659  logpage = aRight[iRight++];
54660  }
54661  dbpage = aContent[logpage];
54662 
54663  aTmp[iOut++] = logpage;
54664  if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
54665 
54666  assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
54667  assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
54668  }
54669 
54670  *paRight = aLeft;
54671  *pnRight = iOut;
54672  memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
54673 }
54674 
54675 /*
54676 ** Sort the elements in list aList using aContent[] as the sort key.
54677 ** Remove elements with duplicate keys, preferring to keep the
54678 ** larger aList[] values.
54679 **
54680 ** The aList[] entries are indices into aContent[]. The values in
54681 ** aList[] are to be sorted so that for all J<K:
54682 **
54683 ** aContent[aList[J]] < aContent[aList[K]]
54684 **
54685 ** For any X and Y such that
54686 **
54687 ** aContent[aList[X]] == aContent[aList[Y]]
54688 **
54689 ** Keep the larger of the two values aList[X] and aList[Y] and discard
54690 ** the smaller.
54691 */
54692 static void walMergesort(
54693  const u32 *aContent, /* Pages in wal */
54694  ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
54695  ht_slot *aList, /* IN/OUT: List to sort */
54696  int *pnList /* IN/OUT: Number of elements in aList[] */
54697 ){
54698  struct Sublist {
54699  int nList; /* Number of elements in aList */
54700  ht_slot *aList; /* Pointer to sub-list content */
54701  };
54702 
54703  const int nList = *pnList; /* Size of input list */
54704  int nMerge = 0; /* Number of elements in list aMerge */
54705  ht_slot *aMerge = 0; /* List to be merged */
54706  int iList; /* Index into input list */
54707  u32 iSub = 0; /* Index into aSub array */
54708  struct Sublist aSub[13]; /* Array of sub-lists */
54709 
54710  memset(aSub, 0, sizeof(aSub));
54711  assert( nList<=HASHTABLE_NPAGE && nList>0 );
54712  assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
54713 
54714  for(iList=0; iList<nList; iList++){
54715  nMerge = 1;
54716  aMerge = &aList[iList];
54717  for(iSub=0; iList & (1<<iSub); iSub++){
54718  struct Sublist *p;
54719  assert( iSub<ArraySize(aSub) );
54720  p = &aSub[iSub];
54721  assert( p->aList && p->nList<=(1<<iSub) );
54722  assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
54723  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
54724  }
54725  aSub[iSub].aList = aMerge;
54726  aSub[iSub].nList = nMerge;
54727  }
54728 
54729  for(iSub++; iSub<ArraySize(aSub); iSub++){
54730  if( nList & (1<<iSub) ){
54731  struct Sublist *p;
54732  assert( iSub<ArraySize(aSub) );
54733  p = &aSub[iSub];
54734  assert( p->nList<=(1<<iSub) );
54735  assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
54736  walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
54737  }
54738  }
54739  assert( aMerge==aList );
54740  *pnList = nMerge;
54741 
54742 #ifdef SQLITE_DEBUG
54743  {
54744  int i;
54745  for(i=1; i<*pnList; i++){
54746  assert( aContent[aList[i]] > aContent[aList[i-1]] );
54747  }
54748  }
54749 #endif
54750 }
54751 
54752 /*
54753 ** Free an iterator allocated by walIteratorInit().
54754 */
54756  sqlite3_free(p);
54757 }
54758 
54759 /*
54760 ** Construct a WalInterator object that can be used to loop over all
54761 ** pages in the WAL in ascending order. The caller must hold the checkpoint
54762 ** lock.
54763 **
54764 ** On success, make *pp point to the newly allocated WalInterator object
54765 ** return SQLITE_OK. Otherwise, return an error code. If this routine
54766 ** returns an error, the value of *pp is undefined.
54767 **
54768 ** The calling routine should invoke walIteratorFree() to destroy the
54769 ** WalIterator object when it has finished with it.
54770 */
54771 static int walIteratorInit(Wal *pWal, WalIterator **pp){
54772  WalIterator *p; /* Return value */
54773  int nSegment; /* Number of segments to merge */
54774  u32 iLast; /* Last frame in log */
54775  int nByte; /* Number of bytes to allocate */
54776  int i; /* Iterator variable */
54777  ht_slot *aTmp; /* Temp space used by merge-sort */
54778  int rc = SQLITE_OK; /* Return Code */
54779 
54780  /* This routine only runs while holding the checkpoint lock. And
54781  ** it only runs if there is actually content in the log (mxFrame>0).
54782  */
54783  assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
54784  iLast = pWal->hdr.mxFrame;
54785 
54786  /* Allocate space for the WalIterator object. */
54787  nSegment = walFramePage(iLast) + 1;
54788  nByte = sizeof(WalIterator)
54789  + (nSegment-1)*sizeof(struct WalSegment)
54790  + iLast*sizeof(ht_slot);
54791  p = (WalIterator *)sqlite3_malloc64(nByte);
54792  if( !p ){
54793  return SQLITE_NOMEM_BKPT;
54794  }
54795  memset(p, 0, nByte);
54796  p->nSegment = nSegment;
54797 
54798  /* Allocate temporary space used by the merge-sort routine. This block
54799  ** of memory will be freed before this function returns.
54800  */
54801  aTmp = (ht_slot *)sqlite3_malloc64(
54802  sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
54803  );
54804  if( !aTmp ){
54805  rc = SQLITE_NOMEM_BKPT;
54806  }
54807 
54808  for(i=0; rc==SQLITE_OK && i<nSegment; i++){
54809  volatile ht_slot *aHash;
54810  u32 iZero;
54811  volatile u32 *aPgno;
54812 
54813  rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
54814  if( rc==SQLITE_OK ){
54815  int j; /* Counter variable */
54816  int nEntry; /* Number of entries in this segment */
54817  ht_slot *aIndex; /* Sorted index for this segment */
54818 
54819  aPgno++;
54820  if( (i+1)==nSegment ){
54821  nEntry = (int)(iLast - iZero);
54822  }else{
54823  nEntry = (int)((u32*)aHash - (u32*)aPgno);
54824  }
54825  aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
54826  iZero++;
54827 
54828  for(j=0; j<nEntry; j++){
54829  aIndex[j] = (ht_slot)j;
54830  }
54831  walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
54832  p->aSegment[i].iZero = iZero;
54833  p->aSegment[i].nEntry = nEntry;
54834  p->aSegment[i].aIndex = aIndex;
54835  p->aSegment[i].aPgno = (u32 *)aPgno;
54836  }
54837  }
54838  sqlite3_free(aTmp);
54839 
54840  if( rc!=SQLITE_OK ){
54841  walIteratorFree(p);
54842  }
54843  *pp = p;
54844  return rc;
54845 }
54846 
54847 /*
54848 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
54849 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
54850 ** busy-handler function. Invoke it and retry the lock until either the
54851 ** lock is successfully obtained or the busy-handler returns 0.
54852 */
54853 static int walBusyLock(
54854  Wal *pWal, /* WAL connection */
54855  int (*xBusy)(void*), /* Function to call when busy */
54856  void *pBusyArg, /* Context argument for xBusyHandler */
54857  int lockIdx, /* Offset of first byte to lock */
54858  int n /* Number of bytes to lock */
54859 ){
54860  int rc;
54861  do {
54862  rc = walLockExclusive(pWal, lockIdx, n);
54863  }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
54864  return rc;
54865 }
54866 
54867 /*
54868 ** The cache of the wal-index header must be valid to call this function.
54869 ** Return the page-size in bytes used by the database.
54870 */
54871 static int walPagesize(Wal *pWal){
54872  return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
54873 }
54874 
54875 /*
54876 ** The following is guaranteed when this function is called:
54877 **
54878 ** a) the WRITER lock is held,
54879 ** b) the entire log file has been checkpointed, and
54880 ** c) any existing readers are reading exclusively from the database
54881 ** file - there are no readers that may attempt to read a frame from
54882 ** the log file.
54883 **
54884 ** This function updates the shared-memory structures so that the next
54885 ** client to write to the database (which may be this one) does so by
54886 ** writing frames into the start of the log file.
54887 **
54888 ** The value of parameter salt1 is used as the aSalt[1] value in the
54889 ** new wal-index header. It should be passed a pseudo-random value (i.e.
54890 ** one obtained from sqlite3_randomness()).
54891 */
54892 static void walRestartHdr(Wal *pWal, u32 salt1){
54893  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
54894  int i; /* Loop counter */
54895  u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
54896  pWal->nCkpt++;
54897  pWal->hdr.mxFrame = 0;
54898  sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
54899  memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
54900  walIndexWriteHdr(pWal);
54901  pInfo->nBackfill = 0;
54902  pInfo->nBackfillAttempted = 0;
54903  pInfo->aReadMark[1] = 0;
54904  for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
54905  assert( pInfo->aReadMark[0]==0 );
54906 }
54907 
54908 /*
54909 ** Copy as much content as we can from the WAL back into the database file
54910 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
54911 **
54912 ** The amount of information copies from WAL to database might be limited
54913 ** by active readers. This routine will never overwrite a database page
54914 ** that a concurrent reader might be using.
54915 **
54916 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
54917 ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
54918 ** checkpoints are always run by a background thread or background
54919 ** process, foreground threads will never block on a lengthy fsync call.
54920 **
54921 ** Fsync is called on the WAL before writing content out of the WAL and
54922 ** into the database. This ensures that if the new content is persistent
54923 ** in the WAL and can be recovered following a power-loss or hard reset.
54924 **
54925 ** Fsync is also called on the database file if (and only if) the entire
54926 ** WAL content is copied into the database file. This second fsync makes
54927 ** it safe to delete the WAL since the new content will persist in the
54928 ** database file.
54929 **
54930 ** This routine uses and updates the nBackfill field of the wal-index header.
54931 ** This is the only routine that will increase the value of nBackfill.
54932 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
54933 ** its value.)
54934 **
54935 ** The caller must be holding sufficient locks to ensure that no other
54936 ** checkpoint is running (in any other thread or process) at the same
54937 ** time.
54938 */
54939 static int walCheckpoint(
54940  Wal *pWal, /* Wal connection */
54941  int eMode, /* One of PASSIVE, FULL or RESTART */
54942  int (*xBusy)(void*), /* Function to call when busy */
54943  void *pBusyArg, /* Context argument for xBusyHandler */
54944  int sync_flags, /* Flags for OsSync() (or 0) */
54945  u8 *zBuf /* Temporary buffer to use */
54946 ){
54947  int rc = SQLITE_OK; /* Return code */
54948  int szPage; /* Database page-size */
54949  WalIterator *pIter = 0; /* Wal iterator context */
54950  u32 iDbpage = 0; /* Next database page to write */
54951  u32 iFrame = 0; /* Wal frame containing data for iDbpage */
54952  u32 mxSafeFrame; /* Max frame that can be backfilled */
54953  u32 mxPage; /* Max database page to write */
54954  int i; /* Loop counter */
54955  volatile WalCkptInfo *pInfo; /* The checkpoint status information */
54956 
54957  szPage = walPagesize(pWal);
54958  testcase( szPage<=32768 );
54959  testcase( szPage>=65536 );
54960  pInfo = walCkptInfo(pWal);
54961  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
54962 
54963  /* Allocate the iterator */
54964  rc = walIteratorInit(pWal, &pIter);
54965  if( rc!=SQLITE_OK ){
54966  return rc;
54967  }
54968  assert( pIter );
54969 
54970  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
54971  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
54972  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
54973 
54974  /* Compute in mxSafeFrame the index of the last frame of the WAL that is
54975  ** safe to write into the database. Frames beyond mxSafeFrame might
54976  ** overwrite database pages that are in use by active readers and thus
54977  ** cannot be backfilled from the WAL.
54978  */
54979  mxSafeFrame = pWal->hdr.mxFrame;
54980  mxPage = pWal->hdr.nPage;
54981  for(i=1; i<WAL_NREADER; i++){
54982  /* Thread-sanitizer reports that the following is an unsafe read,
54983  ** as some other thread may be in the process of updating the value
54984  ** of the aReadMark[] slot. The assumption here is that if that is
54985  ** happening, the other client may only be increasing the value,
54986  ** not decreasing it. So assuming either that either the "old" or
54987  ** "new" version of the value is read, and not some arbitrary value
54988  ** that would never be written by a real client, things are still
54989  ** safe. */
54990  u32 y = pInfo->aReadMark[i];
54991  if( mxSafeFrame>y ){
54992  assert( y<=pWal->hdr.mxFrame );
54993  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
54994  if( rc==SQLITE_OK ){
54995  pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
54996  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
54997  }else if( rc==SQLITE_BUSY ){
54998  mxSafeFrame = y;
54999  xBusy = 0;
55000  }else{
55001  goto walcheckpoint_out;
55002  }
55003  }
55004  }
55005 
55006  if( pInfo->nBackfill<mxSafeFrame
55007  && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
55008  ){
55009  i64 nSize; /* Current size of database file */
55010  u32 nBackfill = pInfo->nBackfill;
55011 
55012  pInfo->nBackfillAttempted = mxSafeFrame;
55013 
55014  /* Sync the WAL to disk */
55015  if( sync_flags ){
55016  rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
55017  }
55018 
55019  /* If the database may grow as a result of this checkpoint, hint
55020  ** about the eventual size of the db file to the VFS layer.
55021  */
55022  if( rc==SQLITE_OK ){
55023  i64 nReq = ((i64)mxPage * szPage);
55024  rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
55025  if( rc==SQLITE_OK && nSize<nReq ){
55027  }
55028  }
55029 
55030 
55031  /* Iterate through the contents of the WAL, copying data to the db file */
55032  while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
55033  i64 iOffset;
55034  assert( walFramePgno(pWal, iFrame)==iDbpage );
55035  if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
55036  continue;
55037  }
55038  iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
55039  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
55040  rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
55041  if( rc!=SQLITE_OK ) break;
55042  iOffset = (iDbpage-1)*(i64)szPage;
55043  testcase( IS_BIG_INT(iOffset) );
55044  rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
55045  if( rc!=SQLITE_OK ) break;
55046  }
55047 
55048  /* If work was actually accomplished... */
55049  if( rc==SQLITE_OK ){
55050  if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
55051  i64 szDb = pWal->hdr.nPage*(i64)szPage;
55052  testcase( IS_BIG_INT(szDb) );
55053  rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
55054  if( rc==SQLITE_OK && sync_flags ){
55055  rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
55056  }
55057  }
55058  if( rc==SQLITE_OK ){
55059  pInfo->nBackfill = mxSafeFrame;
55060  }
55061  }
55062 
55063  /* Release the reader lock held while backfilling */
55064  walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
55065  }
55066 
55067  if( rc==SQLITE_BUSY ){
55068  /* Reset the return code so as not to report a checkpoint failure
55069  ** just because there are active readers. */
55070  rc = SQLITE_OK;
55071  }
55072  }
55073 
55074  /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
55075  ** entire wal file has been copied into the database file, then block
55076  ** until all readers have finished using the wal file. This ensures that
55077  ** the next process to write to the database restarts the wal file.
55078  */
55079  if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
55080  assert( pWal->writeLock );
55081  if( pInfo->nBackfill<pWal->hdr.mxFrame ){
55082  rc = SQLITE_BUSY;
55083  }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
55084  u32 salt1;
55085  sqlite3_randomness(4, &salt1);
55086  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
55087  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
55088  if( rc==SQLITE_OK ){
55089  if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
55090  /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
55091  ** SQLITE_CHECKPOINT_RESTART with the addition that it also
55092  ** truncates the log file to zero bytes just prior to a
55093  ** successful return.
55094  **
55095  ** In theory, it might be safe to do this without updating the
55096  ** wal-index header in shared memory, as all subsequent reader or
55097  ** writer clients should see that the entire log file has been
55098  ** checkpointed and behave accordingly. This seems unsafe though,
55099  ** as it would leave the system in a state where the contents of
55100  ** the wal-index header do not match the contents of the
55101  ** file-system. To avoid this, update the wal-index header to
55102  ** indicate that the log file contains zero valid frames. */
55103  walRestartHdr(pWal, salt1);
55104  rc = sqlite3OsTruncate(pWal->pWalFd, 0);
55105  }
55107  }
55108  }
55109  }
55110 
55111  walcheckpoint_out:
55112  walIteratorFree(pIter);
55113  return rc;
55114 }
55115 
55116 /*
55117 ** If the WAL file is currently larger than nMax bytes in size, truncate
55118 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
55119 */
55120 static void walLimitSize(Wal *pWal, i64 nMax){
55121  i64 sz;
55122  int rx;
55124  rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
55125  if( rx==SQLITE_OK && (sz > nMax ) ){
55126  rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
55127  }
55129  if( rx ){
55130  sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
55131  }
55132 }
55133 
55134 /*
55135 ** Close a connection to a log file.
55136 */
55138  Wal *pWal, /* Wal to close */
55139  int sync_flags, /* Flags to pass to OsSync() (or 0) */
55140  int nBuf,
55141  u8 *zBuf /* Buffer of at least nBuf bytes */
55142 ){
55143  int rc = SQLITE_OK;
55144  if( pWal ){
55145  int isDelete = 0; /* True to unlink wal and wal-index files */
55146 
55147  /* If an EXCLUSIVE lock can be obtained on the database file (using the
55148  ** ordinary, rollback-mode locking methods, this guarantees that the
55149  ** connection associated with this log file is the only connection to
55150  ** the database. In this case checkpoint the database and unlink both
55151  ** the wal and wal-index files.
55152  **
55153  ** The EXCLUSIVE lock is not released before returning.
55154  */
55156  if( rc==SQLITE_OK ){
55157  if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
55159  }
55160  rc = sqlite3WalCheckpoint(
55161  pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
55162  );
55163  if( rc==SQLITE_OK ){
55164  int bPersist = -1;
55166  pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
55167  );
55168  if( bPersist!=1 ){
55169  /* Try to delete the WAL file if the checkpoint completed and
55170  ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
55171  ** mode (!bPersist) */
55172  isDelete = 1;
55173  }else if( pWal->mxWalSize>=0 ){
55174  /* Try to truncate the WAL file to zero bytes if the checkpoint
55175  ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
55176  ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
55177  ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
55178  ** to zero bytes as truncating to the journal_size_limit might
55179  ** leave a corrupt WAL file on disk. */
55180  walLimitSize(pWal, 0);
55181  }
55182  }
55183  }
55184 
55185  walIndexClose(pWal, isDelete);
55186  sqlite3OsClose(pWal->pWalFd);
55187  if( isDelete ){
55189  sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
55191  }
55192  WALTRACE(("WAL%p: closed\n", pWal));
55193  sqlite3_free((void *)pWal->apWiData);
55194  sqlite3_free(pWal);
55195  }
55196  return rc;
55197 }
55198 
55199 /*
55200 ** Try to read the wal-index header. Return 0 on success and 1 if
55201 ** there is a problem.
55202 **
55203 ** The wal-index is in shared memory. Another thread or process might
55204 ** be writing the header at the same time this procedure is trying to
55205 ** read it, which might result in inconsistency. A dirty read is detected
55206 ** by verifying that both copies of the header are the same and also by
55207 ** a checksum on the header.
55208 **
55209 ** If and only if the read is consistent and the header is different from
55210 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
55211 ** and *pChanged is set to 1.
55212 **
55213 ** If the checksum cannot be verified return non-zero. If the header
55214 ** is read successfully and the checksum verified, return zero.
55215 */
55216 static int walIndexTryHdr(Wal *pWal, int *pChanged){
55217  u32 aCksum[2]; /* Checksum on the header content */
55218  WalIndexHdr h1, h2; /* Two copies of the header content */
55219  WalIndexHdr volatile *aHdr; /* Header in shared memory */
55220 
55221  /* The first page of the wal-index must be mapped at this point. */
55222  assert( pWal->nWiData>0 && pWal->apWiData[0] );
55223 
55224  /* Read the header. This might happen concurrently with a write to the
55225  ** same area of shared memory on a different CPU in a SMP,
55226  ** meaning it is possible that an inconsistent snapshot is read
55227  ** from the file. If this happens, return non-zero.
55228  **
55229  ** There are two copies of the header at the beginning of the wal-index.
55230  ** When reading, read [0] first then [1]. Writes are in the reverse order.
55231  ** Memory barriers are used to prevent the compiler or the hardware from
55232  ** reordering the reads and writes.
55233  */
55234  aHdr = walIndexHdr(pWal);
55235  memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
55236  walShmBarrier(pWal);
55237  memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
55238 
55239  if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
55240  return 1; /* Dirty read */
55241  }
55242  if( h1.isInit==0 ){
55243  return 1; /* Malformed header - probably all zeros */
55244  }
55245  walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
55246  if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
55247  return 1; /* Checksum does not match */
55248  }
55249 
55250  if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
55251  *pChanged = 1;
55252  memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
55253  pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
55254  testcase( pWal->szPage<=32768 );
55255  testcase( pWal->szPage>=65536 );
55256  }
55257 
55258  /* The header was successfully read. Return zero. */
55259  return 0;
55260 }
55261 
55262 /*
55263 ** Read the wal-index header from the wal-index and into pWal->hdr.
55264 ** If the wal-header appears to be corrupt, try to reconstruct the
55265 ** wal-index from the WAL before returning.
55266 **
55267 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
55268 ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
55269 ** to 0.
55270 **
55271 ** If the wal-index header is successfully read, return SQLITE_OK.
55272 ** Otherwise an SQLite error code.
55273 */
55274 static int walIndexReadHdr(Wal *pWal, int *pChanged){
55275  int rc; /* Return code */
55276  int badHdr; /* True if a header read failed */
55277  volatile u32 *page0; /* Chunk of wal-index containing header */
55278 
55279  /* Ensure that page 0 of the wal-index (the page that contains the
55280  ** wal-index header) is mapped. Return early if an error occurs here.
55281  */
55282  assert( pChanged );
55283  rc = walIndexPage(pWal, 0, &page0);
55284  if( rc!=SQLITE_OK ){
55285  return rc;
55286  };
55287  assert( page0 || pWal->writeLock==0 );
55288 
55289  /* If the first page of the wal-index has been mapped, try to read the
55290  ** wal-index header immediately, without holding any lock. This usually
55291  ** works, but may fail if the wal-index header is corrupt or currently
55292  ** being modified by another thread or process.
55293  */
55294  badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
55295 
55296  /* If the first attempt failed, it might have been due to a race
55297  ** with a writer. So get a WRITE lock and try again.
55298  */
55299  assert( badHdr==0 || pWal->writeLock==0 );
55300  if( badHdr ){
55301  if( pWal->readOnly & WAL_SHM_RDONLY ){
55302  if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
55305  }
55306  }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
55307  pWal->writeLock = 1;
55308  if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
55309  badHdr = walIndexTryHdr(pWal, pChanged);
55310  if( badHdr ){
55311  /* If the wal-index header is still malformed even while holding
55312  ** a WRITE lock, it can only mean that the header is corrupted and
55313  ** needs to be reconstructed. So run recovery to do exactly that.
55314  */
55315  rc = walIndexRecover(pWal);
55316  *pChanged = 1;
55317  }
55318  }
55319  pWal->writeLock = 0;
55321  }
55322  }
55323 
55324  /* If the header is read successfully, check the version number to make
55325  ** sure the wal-index was not constructed with some future format that
55326  ** this version of SQLite cannot understand.
55327  */
55328  if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
55329  rc = SQLITE_CANTOPEN_BKPT;
55330  }
55331 
55332  return rc;
55333 }
55334 
55335 /*
55336 ** This is the value that walTryBeginRead returns when it needs to
55337 ** be retried.
55338 */
55339 #define WAL_RETRY (-1)
55340 
55341 /*
55342 ** Attempt to start a read transaction. This might fail due to a race or
55343 ** other transient condition. When that happens, it returns WAL_RETRY to
55344 ** indicate to the caller that it is safe to retry immediately.
55345 **
55346 ** On success return SQLITE_OK. On a permanent failure (such an
55347 ** I/O error or an SQLITE_BUSY because another process is running
55348 ** recovery) return a positive error code.
55349 **
55350 ** The useWal parameter is true to force the use of the WAL and disable
55351 ** the case where the WAL is bypassed because it has been completely
55352 ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
55353 ** to make a copy of the wal-index header into pWal->hdr. If the
55354 ** wal-index header has changed, *pChanged is set to 1 (as an indication
55355 ** to the caller that the local paget cache is obsolete and needs to be
55356 ** flushed.) When useWal==1, the wal-index header is assumed to already
55357 ** be loaded and the pChanged parameter is unused.
55358 **
55359 ** The caller must set the cnt parameter to the number of prior calls to
55360 ** this routine during the current read attempt that returned WAL_RETRY.
55361 ** This routine will start taking more aggressive measures to clear the
55362 ** race conditions after multiple WAL_RETRY returns, and after an excessive
55363 ** number of errors will ultimately return SQLITE_PROTOCOL. The
55364 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
55365 ** and is not honoring the locking protocol. There is a vanishingly small
55366 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
55367 ** bad luck when there is lots of contention for the wal-index, but that
55368 ** possibility is so small that it can be safely neglected, we believe.
55369 **
55370 ** On success, this routine obtains a read lock on
55371 ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
55372 ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
55373 ** that means the Wal does not hold any read lock. The reader must not
55374 ** access any database page that is modified by a WAL frame up to and
55375 ** including frame number aReadMark[pWal->readLock]. The reader will
55376 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
55377 ** Or if pWal->readLock==0, then the reader will ignore the WAL
55378 ** completely and get all content directly from the database file.
55379 ** If the useWal parameter is 1 then the WAL will never be ignored and
55380 ** this routine will always set pWal->readLock>0 on success.
55381 ** When the read transaction is completed, the caller must release the
55382 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
55383 **
55384 ** This routine uses the nBackfill and aReadMark[] fields of the header
55385 ** to select a particular WAL_READ_LOCK() that strives to let the
55386 ** checkpoint process do as much work as possible. This routine might
55387 ** update values of the aReadMark[] array in the header, but if it does
55388 ** so it takes care to hold an exclusive lock on the corresponding
55389 ** WAL_READ_LOCK() while changing values.
55390 */
55391 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
55392  volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
55393  u32 mxReadMark; /* Largest aReadMark[] value */
55394  int mxI; /* Index of largest aReadMark[] value */
55395  int i; /* Loop counter */
55396  int rc = SQLITE_OK; /* Return code */
55397  u32 mxFrame; /* Wal frame to lock to */
55398 
55399  assert( pWal->readLock<0 ); /* Not currently locked */
55400 
55401  /* Take steps to avoid spinning forever if there is a protocol error.
55402  **
55403  ** Circumstances that cause a RETRY should only last for the briefest
55404  ** instances of time. No I/O or other system calls are done while the
55405  ** locks are held, so the locks should not be held for very long. But
55406  ** if we are unlucky, another process that is holding a lock might get
55407  ** paged out or take a page-fault that is time-consuming to resolve,
55408  ** during the few nanoseconds that it is holding the lock. In that case,
55409  ** it might take longer than normal for the lock to free.
55410  **
55411  ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
55412  ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
55413  ** is more of a scheduler yield than an actual delay. But on the 10th
55414  ** an subsequent retries, the delays start becoming longer and longer,
55415  ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
55416  ** The total delay time before giving up is less than 10 seconds.
55417  */
55418  if( cnt>5 ){
55419  int nDelay = 1; /* Pause time in microseconds */
55420  if( cnt>100 ){
55421  VVA_ONLY( pWal->lockError = 1; )
55422  return SQLITE_PROTOCOL;
55423  }
55424  if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
55425  sqlite3OsSleep(pWal->pVfs, nDelay);
55426  }
55427 
55428  if( !useWal ){
55429  rc = walIndexReadHdr(pWal, pChanged);
55430  if( rc==SQLITE_BUSY ){
55431  /* If there is not a recovery running in another thread or process
55432  ** then convert BUSY errors to WAL_RETRY. If recovery is known to
55433  ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
55434  ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
55435  ** would be technically correct. But the race is benign since with
55436  ** WAL_RETRY this routine will be called again and will probably be
55437  ** right on the second iteration.
55438  */
55439  if( pWal->apWiData[0]==0 ){
55440  /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
55441  ** We assume this is a transient condition, so return WAL_RETRY. The
55442  ** xShmMap() implementation used by the default unix and win32 VFS
55443  ** modules may return SQLITE_BUSY due to a race condition in the
55444  ** code that determines whether or not the shared-memory region
55445  ** must be zeroed before the requested page is returned.
55446  */
55447  rc = WAL_RETRY;
55448  }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
55450  rc = WAL_RETRY;
55451  }else if( rc==SQLITE_BUSY ){
55452  rc = SQLITE_BUSY_RECOVERY;
55453  }
55454  }
55455  if( rc!=SQLITE_OK ){
55456  return rc;
55457  }
55458  }
55459 
55460  pInfo = walCkptInfo(pWal);
55461  if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame
55462 #ifdef SQLITE_ENABLE_SNAPSHOT
55463  && (pWal->pSnapshot==0 || pWal->hdr.mxFrame==0
55464  || 0==memcmp(&pWal->hdr, pWal->pSnapshot, sizeof(WalIndexHdr)))
55465 #endif
55466  ){
55467  /* The WAL has been completely backfilled (or it is empty).
55468  ** and can be safely ignored.
55469  */
55470  rc = walLockShared(pWal, WAL_READ_LOCK(0));
55471  walShmBarrier(pWal);
55472  if( rc==SQLITE_OK ){
55473  if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
55474  /* It is not safe to allow the reader to continue here if frames
55475  ** may have been appended to the log before READ_LOCK(0) was obtained.
55476  ** When holding READ_LOCK(0), the reader ignores the entire log file,
55477  ** which implies that the database file contains a trustworthy
55478  ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
55479  ** happening, this is usually correct.
55480  **
55481  ** However, if frames have been appended to the log (or if the log
55482  ** is wrapped and written for that matter) before the READ_LOCK(0)
55483  ** is obtained, that is not necessarily true. A checkpointer may
55484  ** have started to backfill the appended frames but crashed before
55485  ** it finished. Leaving a corrupt image in the database file.
55486  */
55487  walUnlockShared(pWal, WAL_READ_LOCK(0));
55488  return WAL_RETRY;
55489  }
55490  pWal->readLock = 0;
55491  return SQLITE_OK;
55492  }else if( rc!=SQLITE_BUSY ){
55493  return rc;
55494  }
55495  }
55496 
55497  /* If we get this far, it means that the reader will want to use
55498  ** the WAL to get at content from recent commits. The job now is
55499  ** to select one of the aReadMark[] entries that is closest to
55500  ** but not exceeding pWal->hdr.mxFrame and lock that entry.
55501  */
55502  mxReadMark = 0;
55503  mxI = 0;
55504  mxFrame = pWal->hdr.mxFrame;
55505 #ifdef SQLITE_ENABLE_SNAPSHOT
55506  if( pWal->pSnapshot && pWal->pSnapshot->mxFrame<mxFrame ){
55507  mxFrame = pWal->pSnapshot->mxFrame;
55508  }
55509 #endif
55510  for(i=1; i<WAL_NREADER; i++){
55511  u32 thisMark = pInfo->aReadMark[i];
55512  if( mxReadMark<=thisMark && thisMark<=mxFrame ){
55513  assert( thisMark!=READMARK_NOT_USED );
55514  mxReadMark = thisMark;
55515  mxI = i;
55516  }
55517  }
55518  if( (pWal->readOnly & WAL_SHM_RDONLY)==0
55519  && (mxReadMark<mxFrame || mxI==0)
55520  ){
55521  for(i=1; i<WAL_NREADER; i++){
55522  rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
55523  if( rc==SQLITE_OK ){
55524  mxReadMark = pInfo->aReadMark[i] = mxFrame;
55525  mxI = i;
55526  walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
55527  break;
55528  }else if( rc!=SQLITE_BUSY ){
55529  return rc;
55530  }
55531  }
55532  }
55533  if( mxI==0 ){
55534  assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
55536  }
55537 
55538  rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
55539  if( rc ){
55540  return rc==SQLITE_BUSY ? WAL_RETRY : rc;
55541  }
55542  /* Now that the read-lock has been obtained, check that neither the
55543  ** value in the aReadMark[] array or the contents of the wal-index
55544  ** header have changed.
55545  **
55546  ** It is necessary to check that the wal-index header did not change
55547  ** between the time it was read and when the shared-lock was obtained
55548  ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
55549  ** that the log file may have been wrapped by a writer, or that frames
55550  ** that occur later in the log than pWal->hdr.mxFrame may have been
55551  ** copied into the database by a checkpointer. If either of these things
55552  ** happened, then reading the database with the current value of
55553  ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
55554  ** instead.
55555  **
55556  ** Before checking that the live wal-index header has not changed
55557  ** since it was read, set Wal.minFrame to the first frame in the wal
55558  ** file that has not yet been checkpointed. This client will not need
55559  ** to read any frames earlier than minFrame from the wal file - they
55560  ** can be safely read directly from the database file.
55561  **
55562  ** Because a ShmBarrier() call is made between taking the copy of
55563  ** nBackfill and checking that the wal-header in shared-memory still
55564  ** matches the one cached in pWal->hdr, it is guaranteed that the
55565  ** checkpointer that set nBackfill was not working with a wal-index
55566  ** header newer than that cached in pWal->hdr. If it were, that could
55567  ** cause a problem. The checkpointer could omit to checkpoint
55568  ** a version of page X that lies before pWal->minFrame (call that version
55569  ** A) on the basis that there is a newer version (version B) of the same
55570  ** page later in the wal file. But if version B happens to like past
55571  ** frame pWal->hdr.mxFrame - then the client would incorrectly assume
55572  ** that it can read version A from the database file. However, since
55573  ** we can guarantee that the checkpointer that set nBackfill could not
55574  ** see any pages past pWal->hdr.mxFrame, this problem does not come up.
55575  */
55576  pWal->minFrame = pInfo->nBackfill+1;
55577  walShmBarrier(pWal);
55578  if( pInfo->aReadMark[mxI]!=mxReadMark
55579  || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
55580  ){
55581  walUnlockShared(pWal, WAL_READ_LOCK(mxI));
55582  return WAL_RETRY;
55583  }else{
55584  assert( mxReadMark<=pWal->hdr.mxFrame );
55585  pWal->readLock = (i16)mxI;
55586  }
55587  return rc;
55588 }
55589 
55590 /*
55591 ** Begin a read transaction on the database.
55592 **
55593 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
55594 ** it takes a snapshot of the state of the WAL and wal-index for the current
55595 ** instant in time. The current thread will continue to use this snapshot.
55596 ** Other threads might append new content to the WAL and wal-index but
55597 ** that extra content is ignored by the current thread.
55598 **
55599 ** If the database contents have changes since the previous read
55600 ** transaction, then *pChanged is set to 1 before returning. The
55601 ** Pager layer will use this to know that is cache is stale and
55602 ** needs to be flushed.
55603 */
55605  int rc; /* Return code */
55606  int cnt = 0; /* Number of TryBeginRead attempts */
55607 
55608 #ifdef SQLITE_ENABLE_SNAPSHOT
55609  int bChanged = 0;
55610  WalIndexHdr *pSnapshot = pWal->pSnapshot;
55611  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
55612  bChanged = 1;
55613  }
55614 #endif
55615 
55616  do{
55617  rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
55618  }while( rc==WAL_RETRY );
55619  testcase( (rc&0xff)==SQLITE_BUSY );
55620  testcase( (rc&0xff)==SQLITE_IOERR );
55621  testcase( rc==SQLITE_PROTOCOL );
55622  testcase( rc==SQLITE_OK );
55623 
55624 #ifdef SQLITE_ENABLE_SNAPSHOT
55625  if( rc==SQLITE_OK ){
55626  if( pSnapshot && memcmp(pSnapshot, &pWal->hdr, sizeof(WalIndexHdr))!=0 ){
55627  /* At this point the client has a lock on an aReadMark[] slot holding
55628  ** a value equal to or smaller than pSnapshot->mxFrame, but pWal->hdr
55629  ** is populated with the wal-index header corresponding to the head
55630  ** of the wal file. Verify that pSnapshot is still valid before
55631  ** continuing. Reasons why pSnapshot might no longer be valid:
55632  **
55633  ** (1) The WAL file has been reset since the snapshot was taken.
55634  ** In this case, the salt will have changed.
55635  **
55636  ** (2) A checkpoint as been attempted that wrote frames past
55637  ** pSnapshot->mxFrame into the database file. Note that the
55638  ** checkpoint need not have completed for this to cause problems.
55639  */
55640  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
55641 
55642  assert( pWal->readLock>0 || pWal->hdr.mxFrame==0 );
55643  assert( pInfo->aReadMark[pWal->readLock]<=pSnapshot->mxFrame );
55644 
55645  /* It is possible that there is a checkpointer thread running
55646  ** concurrent with this code. If this is the case, it may be that the
55647  ** checkpointer has already determined that it will checkpoint
55648  ** snapshot X, where X is later in the wal file than pSnapshot, but
55649  ** has not yet set the pInfo->nBackfillAttempted variable to indicate
55650  ** its intent. To avoid the race condition this leads to, ensure that
55651  ** there is no checkpointer process by taking a shared CKPT lock
55652  ** before checking pInfo->nBackfillAttempted. */
55653  rc = walLockShared(pWal, WAL_CKPT_LOCK);
55654 
55655  if( rc==SQLITE_OK ){
55656  /* Check that the wal file has not been wrapped. Assuming that it has
55657  ** not, also check that no checkpointer has attempted to checkpoint any
55658  ** frames beyond pSnapshot->mxFrame. If either of these conditions are
55659  ** true, return SQLITE_BUSY_SNAPSHOT. Otherwise, overwrite pWal->hdr
55660  ** with *pSnapshot and set *pChanged as appropriate for opening the
55661  ** snapshot. */
55662  if( !memcmp(pSnapshot->aSalt, pWal->hdr.aSalt, sizeof(pWal->hdr.aSalt))
55663  && pSnapshot->mxFrame>=pInfo->nBackfillAttempted
55664  ){
55665  assert( pWal->readLock>0 );
55666  memcpy(&pWal->hdr, pSnapshot, sizeof(WalIndexHdr));
55667  *pChanged = bChanged;
55668  }else{
55669  rc = SQLITE_BUSY_SNAPSHOT;
55670  }
55671 
55672  /* Release the shared CKPT lock obtained above. */
55674  }
55675 
55676 
55677  if( rc!=SQLITE_OK ){
55679  }
55680  }
55681  }
55682 #endif
55683  return rc;
55684 }
55685 
55686 /*
55687 ** Finish with a read transaction. All this does is release the
55688 ** read-lock.
55689 */
55692  if( pWal->readLock>=0 ){
55693  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
55694  pWal->readLock = -1;
55695  }
55696 }
55697 
55698 /*
55699 ** Search the wal file for page pgno. If found, set *piRead to the frame that
55700 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
55701 ** to zero.
55702 **
55703 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
55704 ** error does occur, the final value of *piRead is undefined.
55705 */
55707  Wal *pWal, /* WAL handle */
55708  Pgno pgno, /* Database page number to read data for */
55709  u32 *piRead /* OUT: Frame number (or zero) */
55710 ){
55711  u32 iRead = 0; /* If !=0, WAL frame to return data from */
55712  u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
55713  int iHash; /* Used to loop through N hash tables */
55714  int iMinHash;
55715 
55716  /* This routine is only be called from within a read transaction. */
55717  assert( pWal->readLock>=0 || pWal->lockError );
55718 
55719  /* If the "last page" field of the wal-index header snapshot is 0, then
55720  ** no data will be read from the wal under any circumstances. Return early
55721  ** in this case as an optimization. Likewise, if pWal->readLock==0,
55722  ** then the WAL is ignored by the reader so return early, as if the
55723  ** WAL were empty.
55724  */
55725  if( iLast==0 || pWal->readLock==0 ){
55726  *piRead = 0;
55727  return SQLITE_OK;
55728  }
55729 
55730  /* Search the hash table or tables for an entry matching page number
55731  ** pgno. Each iteration of the following for() loop searches one
55732  ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
55733  **
55734  ** This code might run concurrently to the code in walIndexAppend()
55735  ** that adds entries to the wal-index (and possibly to this hash
55736  ** table). This means the value just read from the hash
55737  ** slot (aHash[iKey]) may have been added before or after the
55738  ** current read transaction was opened. Values added after the
55739  ** read transaction was opened may have been written incorrectly -
55740  ** i.e. these slots may contain garbage data. However, we assume
55741  ** that any slots written before the current read transaction was
55742  ** opened remain unmodified.
55743  **
55744  ** For the reasons above, the if(...) condition featured in the inner
55745  ** loop of the following block is more stringent that would be required
55746  ** if we had exclusive access to the hash-table:
55747  **
55748  ** (aPgno[iFrame]==pgno):
55749  ** This condition filters out normal hash-table collisions.
55750  **
55751  ** (iFrame<=iLast):
55752  ** This condition filters out entries that were added to the hash
55753  ** table after the current read-transaction had started.
55754  */
55755  iMinHash = walFramePage(pWal->minFrame);
55756  for(iHash=walFramePage(iLast); iHash>=iMinHash && iRead==0; iHash--){
55757  volatile ht_slot *aHash; /* Pointer to hash table */
55758  volatile u32 *aPgno; /* Pointer to array of page numbers */
55759  u32 iZero; /* Frame number corresponding to aPgno[0] */
55760  int iKey; /* Hash slot index */
55761  int nCollide; /* Number of hash collisions remaining */
55762  int rc; /* Error code */
55763 
55764  rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
55765  if( rc!=SQLITE_OK ){
55766  return rc;
55767  }
55768  nCollide = HASHTABLE_NSLOT;
55769  for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
55770  u32 iFrame = aHash[iKey] + iZero;
55771  if( iFrame<=iLast && iFrame>=pWal->minFrame && aPgno[aHash[iKey]]==pgno ){
55772  assert( iFrame>iRead || CORRUPT_DB );
55773  iRead = iFrame;
55774  }
55775  if( (nCollide--)==0 ){
55776  return SQLITE_CORRUPT_BKPT;
55777  }
55778  }
55779  }
55780 
55781 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
55782  /* If expensive assert() statements are available, do a linear search
55783  ** of the wal-index file content. Make sure the results agree with the
55784  ** result obtained using the hash indexes above. */
55785  {
55786  u32 iRead2 = 0;
55787  u32 iTest;
55788  assert( pWal->minFrame>0 );
55789  for(iTest=iLast; iTest>=pWal->minFrame; iTest--){
55790  if( walFramePgno(pWal, iTest)==pgno ){
55791  iRead2 = iTest;
55792  break;
55793  }
55794  }
55795  assert( iRead==iRead2 );
55796  }
55797 #endif
55798 
55799  *piRead = iRead;
55800  return SQLITE_OK;
55801 }
55802 
55803 /*
55804 ** Read the contents of frame iRead from the wal file into buffer pOut
55805 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
55806 ** error code otherwise.
55807 */
55809  Wal *pWal, /* WAL handle */
55810  u32 iRead, /* Frame to read */
55811  int nOut, /* Size of buffer pOut in bytes */
55812  u8 *pOut /* Buffer to write page data to */
55813 ){
55814  int sz;
55815  i64 iOffset;
55816  sz = pWal->hdr.szPage;
55817  sz = (sz&0xfe00) + ((sz&0x0001)<<16);
55818  testcase( sz<=32768 );
55819  testcase( sz>=65536 );
55820  iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
55821  /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
55822  return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
55823 }
55824 
55825 /*
55826 ** Return the size of the database in pages (or zero, if unknown).
55827 */
55829  if( pWal && ALWAYS(pWal->readLock>=0) ){
55830  return pWal->hdr.nPage;
55831  }
55832  return 0;
55833 }
55834 
55835 
55836 /*
55837 ** This function starts a write transaction on the WAL.
55838 **
55839 ** A read transaction must have already been started by a prior call
55840 ** to sqlite3WalBeginReadTransaction().
55841 **
55842 ** If another thread or process has written into the database since
55843 ** the read transaction was started, then it is not possible for this
55844 ** thread to write as doing so would cause a fork. So this routine
55845 ** returns SQLITE_BUSY in that case and no write transaction is started.
55846 **
55847 ** There can only be a single writer active at a time.
55848 */
55850  int rc;
55851 
55852  /* Cannot start a write transaction without first holding a read
55853  ** transaction. */
55854  assert( pWal->readLock>=0 );
55855  assert( pWal->writeLock==0 && pWal->iReCksum==0 );
55856 
55857  if( pWal->readOnly ){
55858  return SQLITE_READONLY;
55859  }
55860 
55861  /* Only one writer allowed at a time. Get the write lock. Return
55862  ** SQLITE_BUSY if unable.
55863  */
55864  rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
55865  if( rc ){
55866  return rc;
55867  }
55868  pWal->writeLock = 1;
55869 
55870  /* If another connection has written to the database file since the
55871  ** time the read transaction on this connection was started, then
55872  ** the write is disallowed.
55873  */
55874  if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
55876  pWal->writeLock = 0;
55877  rc = SQLITE_BUSY_SNAPSHOT;
55878  }
55879 
55880  return rc;
55881 }
55882 
55883 /*
55884 ** End a write transaction. The commit has already been done. This
55885 ** routine merely releases the lock.
55886 */
55888  if( pWal->writeLock ){
55890  pWal->writeLock = 0;
55891  pWal->iReCksum = 0;
55892  pWal->truncateOnCommit = 0;
55893  }
55894  return SQLITE_OK;
55895 }
55896 
55897 /*
55898 ** If any data has been written (but not committed) to the log file, this
55899 ** function moves the write-pointer back to the start of the transaction.
55900 **
55901 ** Additionally, the callback function is invoked for each frame written
55902 ** to the WAL since the start of the transaction. If the callback returns
55903 ** other than SQLITE_OK, it is not invoked again and the error code is
55904 ** returned to the caller.
55905 **
55906 ** Otherwise, if the callback function does not return an error, this
55907 ** function returns SQLITE_OK.
55908 */
55909 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
55910  int rc = SQLITE_OK;
55911  if( ALWAYS(pWal->writeLock) ){
55912  Pgno iMax = pWal->hdr.mxFrame;
55913  Pgno iFrame;
55914 
55915  /* Restore the clients cache of the wal-index header to the state it
55916  ** was in before the client began writing to the database.
55917  */
55918  memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
55919 
55920  for(iFrame=pWal->hdr.mxFrame+1;
55921  ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
55922  iFrame++
55923  ){
55924  /* This call cannot fail. Unless the page for which the page number
55925  ** is passed as the second argument is (a) in the cache and
55926  ** (b) has an outstanding reference, then xUndo is either a no-op
55927  ** (if (a) is false) or simply expels the page from the cache (if (b)
55928  ** is false).
55929  **
55930  ** If the upper layer is doing a rollback, it is guaranteed that there
55931  ** are no outstanding references to any page other than page 1. And
55932  ** page 1 is never written to the log until the transaction is
55933  ** committed. As a result, the call to xUndo may not fail.
55934  */
55935  assert( walFramePgno(pWal, iFrame)!=1 );
55936  rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
55937  }
55938  if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
55939  }
55940  return rc;
55941 }
55942 
55943 /*
55944 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
55945 ** values. This function populates the array with values required to
55946 ** "rollback" the write position of the WAL handle back to the current
55947 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
55948 */
55949 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
55950  assert( pWal->writeLock );
55951  aWalData[0] = pWal->hdr.mxFrame;
55952  aWalData[1] = pWal->hdr.aFrameCksum[0];
55953  aWalData[2] = pWal->hdr.aFrameCksum[1];
55954  aWalData[3] = pWal->nCkpt;
55955 }
55956 
55957 /*
55958 ** Move the write position of the WAL back to the point identified by
55959 ** the values in the aWalData[] array. aWalData must point to an array
55960 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
55961 ** by a call to WalSavepoint().
55962 */
55963 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
55964  int rc = SQLITE_OK;
55965 
55966  assert( pWal->writeLock );
55967  assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
55968 
55969  if( aWalData[3]!=pWal->nCkpt ){
55970  /* This savepoint was opened immediately after the write-transaction
55971  ** was started. Right after that, the writer decided to wrap around
55972  ** to the start of the log. Update the savepoint values to match.
55973  */
55974  aWalData[0] = 0;
55975  aWalData[3] = pWal->nCkpt;
55976  }
55977 
55978  if( aWalData[0]<pWal->hdr.mxFrame ){
55979  pWal->hdr.mxFrame = aWalData[0];
55980  pWal->hdr.aFrameCksum[0] = aWalData[1];
55981  pWal->hdr.aFrameCksum[1] = aWalData[2];
55982  walCleanupHash(pWal);
55983  }
55984 
55985  return rc;
55986 }
55987 
55988 /*
55989 ** This function is called just before writing a set of frames to the log
55990 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
55991 ** to the current log file, it is possible to overwrite the start of the
55992 ** existing log file with the new frames (i.e. "reset" the log). If so,
55993 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
55994 ** unchanged.
55995 **
55996 ** SQLITE_OK is returned if no error is encountered (regardless of whether
55997 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
55998 ** if an error occurs.
55999 */
56000 static int walRestartLog(Wal *pWal){
56001  int rc = SQLITE_OK;
56002  int cnt;
56003 
56004  if( pWal->readLock==0 ){
56005  volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
56006  assert( pInfo->nBackfill==pWal->hdr.mxFrame );
56007  if( pInfo->nBackfill>0 ){
56008  u32 salt1;
56009  sqlite3_randomness(4, &salt1);
56010  rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
56011  if( rc==SQLITE_OK ){
56012  /* If all readers are using WAL_READ_LOCK(0) (in other words if no
56013  ** readers are currently using the WAL), then the transactions
56014  ** frames will overwrite the start of the existing log. Update the
56015  ** wal-index header to reflect this.
56016  **
56017  ** In theory it would be Ok to update the cache of the header only
56018  ** at this point. But updating the actual wal-index header is also
56019  ** safe and means there is no special case for sqlite3WalUndo()
56020  ** to handle if this transaction is rolled back. */
56021  walRestartHdr(pWal, salt1);
56023  }else if( rc!=SQLITE_BUSY ){
56024  return rc;
56025  }
56026  }
56027  walUnlockShared(pWal, WAL_READ_LOCK(0));
56028  pWal->readLock = -1;
56029  cnt = 0;
56030  do{
56031  int notUsed;
56032  rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
56033  }while( rc==WAL_RETRY );
56034  assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
56035  testcase( (rc&0xff)==SQLITE_IOERR );
56036  testcase( rc==SQLITE_PROTOCOL );
56037  testcase( rc==SQLITE_OK );
56038  }
56039  return rc;
56040 }
56041 
56042 /*
56043 ** Information about the current state of the WAL file and where
56044 ** the next fsync should occur - passed from sqlite3WalFrames() into
56045 ** walWriteToLog().
56046 */
56047 typedef struct WalWriter {
56048  Wal *pWal; /* The complete WAL information */
56049  sqlite3_file *pFd; /* The WAL file to which we write */
56050  sqlite3_int64 iSyncPoint; /* Fsync at this offset */
56051  int syncFlags; /* Flags for the fsync */
56052  int szPage; /* Size of one page */
56053 } WalWriter;
56054 
56055 /*
56056 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
56057 ** Do a sync when crossing the p->iSyncPoint boundary.
56058 **
56059 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
56060 ** first write the part before iSyncPoint, then sync, then write the
56061 ** rest.
56062 */
56063 static int walWriteToLog(
56064  WalWriter *p, /* WAL to write to */
56065  void *pContent, /* Content to be written */
56066  int iAmt, /* Number of bytes to write */
56067  sqlite3_int64 iOffset /* Start writing at this offset */
56068 ){
56069  int rc;
56070  if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
56071  int iFirstAmt = (int)(p->iSyncPoint - iOffset);
56072  rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
56073  if( rc ) return rc;
56074  iOffset += iFirstAmt;
56075  iAmt -= iFirstAmt;
56076  pContent = (void*)(iFirstAmt + (char*)pContent);
56079  if( iAmt==0 || rc ) return rc;
56080  }
56081  rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
56082  return rc;
56083 }
56084 
56085 /*
56086 ** Write out a single frame of the WAL
56087 */
56088 static int walWriteOneFrame(
56089  WalWriter *p, /* Where to write the frame */
56090  PgHdr *pPage, /* The page of the frame to be written */
56091  int nTruncate, /* The commit flag. Usually 0. >0 for commit */
56092  sqlite3_int64 iOffset /* Byte offset at which to write */
56093 ){
56094  int rc; /* Result code from subfunctions */
56095  void *pData; /* Data actually written */
56096  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
56097 #if defined(SQLITE_HAS_CODEC)
56098  if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM_BKPT;
56099 #else
56100  pData = pPage->pData;
56101 #endif
56102  walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
56103  rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
56104  if( rc ) return rc;
56105  /* Write the page data */
56106  rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
56107  return rc;
56108 }
56109 
56110 /*
56111 ** This function is called as part of committing a transaction within which
56112 ** one or more frames have been overwritten. It updates the checksums for
56113 ** all frames written to the wal file by the current transaction starting
56114 ** with the earliest to have been overwritten.
56115 **
56116 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
56117 */
56118 static int walRewriteChecksums(Wal *pWal, u32 iLast){
56119  const int szPage = pWal->szPage;/* Database page size */
56120  int rc = SQLITE_OK; /* Return code */
56121  u8 *aBuf; /* Buffer to load data from wal file into */
56122  u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-headers in */
56123  u32 iRead; /* Next frame to read from wal file */
56124  i64 iCksumOff;
56125 
56126  aBuf = sqlite3_malloc(szPage + WAL_FRAME_HDRSIZE);
56127  if( aBuf==0 ) return SQLITE_NOMEM_BKPT;
56128 
56129  /* Find the checksum values to use as input for the recalculating the
56130  ** first checksum. If the first frame is frame 1 (implying that the current
56131  ** transaction restarted the wal file), these values must be read from the
56132  ** wal-file header. Otherwise, read them from the frame header of the
56133  ** previous frame. */
56134  assert( pWal->iReCksum>0 );
56135  if( pWal->iReCksum==1 ){
56136  iCksumOff = 24;
56137  }else{
56138  iCksumOff = walFrameOffset(pWal->iReCksum-1, szPage) + 16;
56139  }
56140  rc = sqlite3OsRead(pWal->pWalFd, aBuf, sizeof(u32)*2, iCksumOff);
56141  pWal->hdr.aFrameCksum[0] = sqlite3Get4byte(aBuf);
56142  pWal->hdr.aFrameCksum[1] = sqlite3Get4byte(&aBuf[sizeof(u32)]);
56143 
56144  iRead = pWal->iReCksum;
56145  pWal->iReCksum = 0;
56146  for(; rc==SQLITE_OK && iRead<=iLast; iRead++){
56147  i64 iOff = walFrameOffset(iRead, szPage);
56148  rc = sqlite3OsRead(pWal->pWalFd, aBuf, szPage+WAL_FRAME_HDRSIZE, iOff);
56149  if( rc==SQLITE_OK ){
56150  u32 iPgno, nDbSize;
56151  iPgno = sqlite3Get4byte(aBuf);
56152  nDbSize = sqlite3Get4byte(&aBuf[4]);
56153 
56154  walEncodeFrame(pWal, iPgno, nDbSize, &aBuf[WAL_FRAME_HDRSIZE], aFrame);
56155  rc = sqlite3OsWrite(pWal->pWalFd, aFrame, sizeof(aFrame), iOff);
56156  }
56157  }
56158 
56159  sqlite3_free(aBuf);
56160  return rc;
56161 }
56162 
56163 /*
56164 ** Write a set of frames to the log. The caller must hold the write-lock
56165 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
56166 */
56168  Wal *pWal, /* Wal handle to write to */
56169  int szPage, /* Database page-size in bytes */
56170  PgHdr *pList, /* List of dirty pages to write */
56171  Pgno nTruncate, /* Database size after this commit */
56172  int isCommit, /* True if this is a commit */
56173  int sync_flags /* Flags to pass to OsSync() (or 0) */
56174 ){
56175  int rc; /* Used to catch return codes */
56176  u32 iFrame; /* Next frame address */
56177  PgHdr *p; /* Iterator to run through pList with. */
56178  PgHdr *pLast = 0; /* Last frame in list */
56179  int nExtra = 0; /* Number of extra copies of last page */
56180  int szFrame; /* The size of a single frame */
56181  i64 iOffset; /* Next byte to write in WAL file */
56182  WalWriter w; /* The writer */
56183  u32 iFirst = 0; /* First frame that may be overwritten */
56184  WalIndexHdr *pLive; /* Pointer to shared header */
56185 
56186  assert( pList );
56187  assert( pWal->writeLock );
56188 
56189  /* If this frame set completes a transaction, then nTruncate>0. If
56190  ** nTruncate==0 then this frame set does not complete the transaction. */
56191  assert( (isCommit!=0)==(nTruncate!=0) );
56192 
56193 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
56194  { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
56195  WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
56196  pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
56197  }
56198 #endif
56199 
56200  pLive = (WalIndexHdr*)walIndexHdr(pWal);
56201  if( memcmp(&pWal->hdr, (void *)pLive, sizeof(WalIndexHdr))!=0 ){
56202  iFirst = pLive->mxFrame+1;
56203  }
56204 
56205  /* See if it is possible to write these frames into the start of the
56206  ** log file, instead of appending to it at pWal->hdr.mxFrame.
56207  */
56208  if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
56209  return rc;
56210  }
56211 
56212  /* If this is the first frame written into the log, write the WAL
56213  ** header to the start of the WAL file. See comments at the top of
56214  ** this source file for a description of the WAL header format.
56215  */
56216  iFrame = pWal->hdr.mxFrame;
56217  if( iFrame==0 ){
56218  u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
56219  u32 aCksum[2]; /* Checksum for wal-header */
56220 
56221  sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
56222  sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
56223  sqlite3Put4byte(&aWalHdr[8], szPage);
56224  sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
56225  if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
56226  memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
56227  walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
56228  sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
56229  sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
56230 
56231  pWal->szPage = szPage;
56233  pWal->hdr.aFrameCksum[0] = aCksum[0];
56234  pWal->hdr.aFrameCksum[1] = aCksum[1];
56235  pWal->truncateOnCommit = 1;
56236 
56237  rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
56238  WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
56239  if( rc!=SQLITE_OK ){
56240  return rc;
56241  }
56242 
56243  /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
56244  ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
56245  ** an out-of-order write following a WAL restart could result in
56246  ** database corruption. See the ticket:
56247  **
56248  ** http://localhost:591/sqlite/info/ff5be73dee
56249  */
56250  if( pWal->syncHeader && sync_flags ){
56251  rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
56252  if( rc ) return rc;
56253  }
56254  }
56255  assert( (int)pWal->szPage==szPage );
56256 
56257  /* Setup information needed to write frames into the WAL */
56258  w.pWal = pWal;
56259  w.pFd = pWal->pWalFd;
56260  w.iSyncPoint = 0;
56261  w.syncFlags = sync_flags;
56262  w.szPage = szPage;
56263  iOffset = walFrameOffset(iFrame+1, szPage);
56264  szFrame = szPage + WAL_FRAME_HDRSIZE;
56265 
56266  /* Write all frames into the log file exactly once */
56267  for(p=pList; p; p=p->pDirty){
56268  int nDbSize; /* 0 normally. Positive == commit flag */
56269 
56270  /* Check if this page has already been written into the wal file by
56271  ** the current transaction. If so, overwrite the existing frame and
56272  ** set Wal.writeLock to WAL_WRITELOCK_RECKSUM - indicating that
56273  ** checksums must be recomputed when the transaction is committed. */
56274  if( iFirst && (p->pDirty || isCommit==0) ){
56275  u32 iWrite = 0;
56276  VVA_ONLY(rc =) sqlite3WalFindFrame(pWal, p->pgno, &iWrite);
56277  assert( rc==SQLITE_OK || iWrite==0 );
56278  if( iWrite>=iFirst ){
56279  i64 iOff = walFrameOffset(iWrite, szPage) + WAL_FRAME_HDRSIZE;
56280  void *pData;
56281  if( pWal->iReCksum==0 || iWrite<pWal->iReCksum ){
56282  pWal->iReCksum = iWrite;
56283  }
56284 #if defined(SQLITE_HAS_CODEC)
56285  if( (pData = sqlite3PagerCodec(p))==0 ) return SQLITE_NOMEM;
56286 #else
56287  pData = p->pData;
56288 #endif
56289  rc = sqlite3OsWrite(pWal->pWalFd, pData, szPage, iOff);
56290  if( rc ) return rc;
56291  p->flags &= ~PGHDR_WAL_APPEND;
56292  continue;
56293  }
56294  }
56295 
56296  iFrame++;
56297  assert( iOffset==walFrameOffset(iFrame, szPage) );
56298  nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
56299  rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
56300  if( rc ) return rc;
56301  pLast = p;
56302  iOffset += szFrame;
56303  p->flags |= PGHDR_WAL_APPEND;
56304  }
56305 
56306  /* Recalculate checksums within the wal file if required. */
56307  if( isCommit && pWal->iReCksum ){
56308  rc = walRewriteChecksums(pWal, iFrame);
56309  if( rc ) return rc;
56310  }
56311 
56312  /* If this is the end of a transaction, then we might need to pad
56313  ** the transaction and/or sync the WAL file.
56314  **
56315  ** Padding and syncing only occur if this set of frames complete a
56316  ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
56317  ** or synchronous==OFF, then no padding or syncing are needed.
56318  **
56319  ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
56320  ** needed and only the sync is done. If padding is needed, then the
56321  ** final frame is repeated (with its commit mark) until the next sector
56322  ** boundary is crossed. Only the part of the WAL prior to the last
56323  ** sector boundary is synced; the part of the last frame that extends
56324  ** past the sector boundary is written after the sync.
56325  */
56326  if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
56327  if( pWal->padToSectorBoundary ){
56328  int sectorSize = sqlite3SectorSize(pWal->pWalFd);
56329  w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
56330  while( iOffset<w.iSyncPoint ){
56331  rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
56332  if( rc ) return rc;
56333  iOffset += szFrame;
56334  nExtra++;
56335  }
56336  }else{
56337  rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
56338  }
56339  }
56340 
56341  /* If this frame set completes the first transaction in the WAL and
56342  ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
56343  ** journal size limit, if possible.
56344  */
56345  if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
56346  i64 sz = pWal->mxWalSize;
56347  if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
56348  sz = walFrameOffset(iFrame+nExtra+1, szPage);
56349  }
56350  walLimitSize(pWal, sz);
56351  pWal->truncateOnCommit = 0;
56352  }
56353 
56354  /* Append data to the wal-index. It is not necessary to lock the
56355  ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
56356  ** guarantees that there are no other writers, and no data that may
56357  ** be in use by existing readers is being overwritten.
56358  */
56359  iFrame = pWal->hdr.mxFrame;
56360  for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
56361  if( (p->flags & PGHDR_WAL_APPEND)==0 ) continue;
56362  iFrame++;
56363  rc = walIndexAppend(pWal, iFrame, p->pgno);
56364  }
56365  while( rc==SQLITE_OK && nExtra>0 ){
56366  iFrame++;
56367  nExtra--;
56368  rc = walIndexAppend(pWal, iFrame, pLast->pgno);
56369  }
56370 
56371  if( rc==SQLITE_OK ){
56372  /* Update the private copy of the header. */
56373  pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
56374  testcase( szPage<=32768 );
56375  testcase( szPage>=65536 );
56376  pWal->hdr.mxFrame = iFrame;
56377  if( isCommit ){
56378  pWal->hdr.iChange++;
56379  pWal->hdr.nPage = nTruncate;
56380  }
56381  /* If this is a commit, update the wal-index header too. */
56382  if( isCommit ){
56383  walIndexWriteHdr(pWal);
56384  pWal->iCallback = iFrame;
56385  }
56386  }
56387 
56388  WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
56389  return rc;
56390 }
56391 
56392 /*
56393 ** This routine is called to implement sqlite3_wal_checkpoint() and
56394 ** related interfaces.
56395 **
56396 ** Obtain a CHECKPOINT lock and then backfill as much information as
56397 ** we can from WAL into the database.
56398 **
56399 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
56400 ** callback. In this case this function runs a blocking checkpoint.
56401 */
56403  Wal *pWal, /* Wal connection */
56404  int eMode, /* PASSIVE, FULL, RESTART, or TRUNCATE */
56405  int (*xBusy)(void*), /* Function to call when busy */
56406  void *pBusyArg, /* Context argument for xBusyHandler */
56407  int sync_flags, /* Flags to sync db file with (or 0) */
56408  int nBuf, /* Size of temporary buffer */
56409  u8 *zBuf, /* Temporary buffer to use */
56410  int *pnLog, /* OUT: Number of frames in WAL */
56411  int *pnCkpt /* OUT: Number of backfilled frames in WAL */
56412 ){
56413  int rc; /* Return code */
56414  int isChanged = 0; /* True if a new wal-index header is loaded */
56415  int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
56416  int (*xBusy2)(void*) = xBusy; /* Busy handler for eMode2 */
56417 
56418  assert( pWal->ckptLock==0 );
56419  assert( pWal->writeLock==0 );
56420 
56421  /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
56422  ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
56423  assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
56424 
56425  if( pWal->readOnly ) return SQLITE_READONLY;
56426  WALTRACE(("WAL%p: checkpoint begins\n", pWal));
56427 
56428  /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive
56429  ** "checkpoint" lock on the database file. */
56430  rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
56431  if( rc ){
56432  /* EVIDENCE-OF: R-10421-19736 If any other process is running a
56433  ** checkpoint operation at the same time, the lock cannot be obtained and
56434  ** SQLITE_BUSY is returned.
56435  ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
56436  ** it will not be invoked in this case.
56437  */
56438  testcase( rc==SQLITE_BUSY );
56439  testcase( xBusy!=0 );
56440  return rc;
56441  }
56442  pWal->ckptLock = 1;
56443 
56444  /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
56445  ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
56446  ** file.
56447  **
56448  ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
56449  ** immediately, and a busy-handler is configured, it is invoked and the
56450  ** writer lock retried until either the busy-handler returns 0 or the
56451  ** lock is successfully obtained.
56452  */
56453  if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
56454  rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
56455  if( rc==SQLITE_OK ){
56456  pWal->writeLock = 1;
56457  }else if( rc==SQLITE_BUSY ){
56458  eMode2 = SQLITE_CHECKPOINT_PASSIVE;
56459  xBusy2 = 0;
56460  rc = SQLITE_OK;
56461  }
56462  }
56463 
56464  /* Read the wal-index header. */
56465  if( rc==SQLITE_OK ){
56466  rc = walIndexReadHdr(pWal, &isChanged);
56467  if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
56468  sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
56469  }
56470  }
56471 
56472  /* Copy data from the log to the database file. */
56473  if( rc==SQLITE_OK ){
56474 
56475  if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
56476  rc = SQLITE_CORRUPT_BKPT;
56477  }else{
56478  rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
56479  }
56480 
56481  /* If no error occurred, set the output variables. */
56482  if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
56483  if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
56484  if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
56485  }
56486  }
56487 
56488  if( isChanged ){
56489  /* If a new wal-index header was loaded before the checkpoint was
56490  ** performed, then the pager-cache associated with pWal is now
56491  ** out of date. So zero the cached wal-index header to ensure that
56492  ** next time the pager opens a snapshot on this database it knows that
56493  ** the cache needs to be reset.
56494  */
56495  memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
56496  }
56497 
56498  /* Release the locks. */
56501  pWal->ckptLock = 0;
56502  WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
56503  return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
56504 }
56505 
56506 /* Return the value to pass to a sqlite3_wal_hook callback, the
56507 ** number of frames in the WAL at the point of the last commit since
56508 ** sqlite3WalCallback() was called. If no commits have occurred since
56509 ** the last call, then return 0.
56510 */
56512  u32 ret = 0;
56513  if( pWal ){
56514  ret = pWal->iCallback;
56515  pWal->iCallback = 0;
56516  }
56517  return (int)ret;
56518 }
56519 
56520 /*
56521 ** This function is called to change the WAL subsystem into or out
56522 ** of locking_mode=EXCLUSIVE.
56523 **
56524 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
56525 ** into locking_mode=NORMAL. This means that we must acquire a lock
56526 ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
56527 ** or if the acquisition of the lock fails, then return 0. If the
56528 ** transition out of exclusive-mode is successful, return 1. This
56529 ** operation must occur while the pager is still holding the exclusive
56530 ** lock on the main database file.
56531 **
56532 ** If op is one, then change from locking_mode=NORMAL into
56533 ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
56534 ** be released. Return 1 if the transition is made and 0 if the
56535 ** WAL is already in exclusive-locking mode - meaning that this
56536 ** routine is a no-op. The pager must already hold the exclusive lock
56537 ** on the main database file before invoking this operation.
56538 **
56539 ** If op is negative, then do a dry-run of the op==1 case but do
56540 ** not actually change anything. The pager uses this to see if it
56541 ** should acquire the database exclusive lock prior to invoking
56542 ** the op==1 case.
56543 */
56545  int rc;
56546  assert( pWal->writeLock==0 );
56547  assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
56548 
56549  /* pWal->readLock is usually set, but might be -1 if there was a
56550  ** prior error while attempting to acquire are read-lock. This cannot
56551  ** happen if the connection is actually in exclusive mode (as no xShmLock
56552  ** locks are taken in this case). Nor should the pager attempt to
56553  ** upgrade to exclusive-mode following such an error.
56554  */
56555  assert( pWal->readLock>=0 || pWal->lockError );
56556  assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
56557 
56558  if( op==0 ){
56559  if( pWal->exclusiveMode ){
56560  pWal->exclusiveMode = 0;
56561  if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
56562  pWal->exclusiveMode = 1;
56563  }
56564  rc = pWal->exclusiveMode==0;
56565  }else{
56566  /* Already in locking_mode=NORMAL */
56567  rc = 0;
56568  }
56569  }else if( op>0 ){
56570  assert( pWal->exclusiveMode==0 );
56571  assert( pWal->readLock>=0 );
56572  walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
56573  pWal->exclusiveMode = 1;
56574  rc = 1;
56575  }else{
56576  rc = pWal->exclusiveMode==0;
56577  }
56578  return rc;
56579 }
56580 
56581 /*
56582 ** Return true if the argument is non-NULL and the WAL module is using
56583 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
56584 ** WAL module is using shared-memory, return false.
56585 */
56587  return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
56588 }
56589 
56590 #ifdef SQLITE_ENABLE_SNAPSHOT
56591 /* Create a snapshot object. The content of a snapshot is opaque to
56592 ** every other subsystem, so the WAL module can put whatever it needs
56593 ** in the object.
56594 */
56595 SQLITE_PRIVATE int sqlite3WalSnapshotGet(Wal *pWal, sqlite3_snapshot **ppSnapshot){
56596  int rc = SQLITE_OK;
56597  WalIndexHdr *pRet;
56598 
56599  assert( pWal->readLock>=0 && pWal->writeLock==0 );
56600 
56601  pRet = (WalIndexHdr*)sqlite3_malloc(sizeof(WalIndexHdr));
56602  if( pRet==0 ){
56603  rc = SQLITE_NOMEM_BKPT;
56604  }else{
56605  memcpy(pRet, &pWal->hdr, sizeof(WalIndexHdr));
56606  *ppSnapshot = (sqlite3_snapshot*)pRet;
56607  }
56608 
56609  return rc;
56610 }
56611 
56612 /* Try to open on pSnapshot when the next read-transaction starts
56613 */
56614 SQLITE_PRIVATE void sqlite3WalSnapshotOpen(Wal *pWal, sqlite3_snapshot *pSnapshot){
56615  pWal->pSnapshot = (WalIndexHdr*)pSnapshot;
56616 }
56617 
56618 /*
56619 ** Return a +ve value if snapshot p1 is newer than p2. A -ve value if
56620 ** p1 is older than p2 and zero if p1 and p2 are the same snapshot.
56621 */
56623  WalIndexHdr *pHdr1 = (WalIndexHdr*)p1;
56624  WalIndexHdr *pHdr2 = (WalIndexHdr*)p2;
56625 
56626  /* aSalt[0] is a copy of the value stored in the wal file header. It
56627  ** is incremented each time the wal file is restarted. */
56628  if( pHdr1->aSalt[0]<pHdr2->aSalt[0] ) return -1;
56629  if( pHdr1->aSalt[0]>pHdr2->aSalt[0] ) return +1;
56630  if( pHdr1->mxFrame<pHdr2->mxFrame ) return -1;
56631  if( pHdr1->mxFrame>pHdr2->mxFrame ) return +1;
56632  return 0;
56633 }
56634 #endif /* SQLITE_ENABLE_SNAPSHOT */
56635 
56636 #ifdef SQLITE_ENABLE_ZIPVFS
56637 /*
56638 ** If the argument is not NULL, it points to a Wal object that holds a
56639 ** read-lock. This function returns the database page-size if it is known,
56640 ** or zero if it is not (or if pWal is NULL).
56641 */
56642 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
56643  assert( pWal==0 || pWal->readLock>=0 );
56644  return (pWal ? pWal->szPage : 0);
56645 }
56646 #endif
56647 
56648 /* Return the sqlite3_file object for the WAL file
56649 */
56650 SQLITE_PRIVATE sqlite3_file *sqlite3WalFile(Wal *pWal){
56651  return pWal->pWalFd;
56652 }
56653 
56654 #endif /* #ifndef SQLITE_OMIT_WAL */
56655 
56656 /************** End of wal.c *************************************************/
56657 /************** Begin file btmutex.c *****************************************/
56658 /*
56659 ** 2007 August 27
56660 **
56661 ** The author disclaims copyright to this source code. In place of
56662 ** a legal notice, here is a blessing:
56663 **
56664 ** May you do good and not evil.
56665 ** May you find forgiveness for yourself and forgive others.
56666 ** May you share freely, never taking more than you give.
56667 **
56668 *************************************************************************
56669 **
56670 ** This file contains code used to implement mutexes on Btree objects.
56671 ** This code really belongs in btree.c. But btree.c is getting too
56672 ** big and we want to break it down some. This packaged seemed like
56673 ** a good breakout.
56674 */
56675 /************** Include btreeInt.h in the middle of btmutex.c ****************/
56676 /************** Begin file btreeInt.h ****************************************/
56677 /*
56678 ** 2004 April 6
56679 **
56680 ** The author disclaims copyright to this source code. In place of
56681 ** a legal notice, here is a blessing:
56682 **
56683 ** May you do good and not evil.
56684 ** May you find forgiveness for yourself and forgive others.
56685 ** May you share freely, never taking more than you give.
56686 **
56687 *************************************************************************
56688 ** This file implements an external (disk-based) database using BTrees.
56689 ** For a detailed discussion of BTrees, refer to
56690 **
56691 ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
56692 ** "Sorting And Searching", pages 473-480. Addison-Wesley
56693 ** Publishing Company, Reading, Massachusetts.
56694 **
56695 ** The basic idea is that each page of the file contains N database
56696 ** entries and N+1 pointers to subpages.
56697 **
56698 ** ----------------------------------------------------------------
56699 ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
56700 ** ----------------------------------------------------------------
56701 **
56702 ** All of the keys on the page that Ptr(0) points to have values less
56703 ** than Key(0). All of the keys on page Ptr(1) and its subpages have
56704 ** values greater than Key(0) and less than Key(1). All of the keys
56705 ** on Ptr(N) and its subpages have values greater than Key(N-1). And
56706 ** so forth.
56707 **
56708 ** Finding a particular key requires reading O(log(M)) pages from the
56709 ** disk where M is the number of entries in the tree.
56710 **
56711 ** In this implementation, a single file can hold one or more separate
56712 ** BTrees. Each BTree is identified by the index of its root page. The
56713 ** key and data for any entry are combined to form the "payload". A
56714 ** fixed amount of payload can be carried directly on the database
56715 ** page. If the payload is larger than the preset amount then surplus
56716 ** bytes are stored on overflow pages. The payload for an entry
56717 ** and the preceding pointer are combined to form a "Cell". Each
56718 ** page has a small header which contains the Ptr(N) pointer and other
56719 ** information such as the size of key and data.
56720 **
56721 ** FORMAT DETAILS
56722 **
56723 ** The file is divided into pages. The first page is called page 1,
56724 ** the second is page 2, and so forth. A page number of zero indicates
56725 ** "no such page". The page size can be any power of 2 between 512 and 65536.
56726 ** Each page can be either a btree page, a freelist page, an overflow
56727 ** page, or a pointer-map page.
56728 **
56729 ** The first page is always a btree page. The first 100 bytes of the first
56730 ** page contain a special header (the "file header") that describes the file.
56731 ** The format of the file header is as follows:
56732 **
56733 ** OFFSET SIZE DESCRIPTION
56734 ** 0 16 Header string: "SQLite format 3\000"
56735 ** 16 2 Page size in bytes. (1 means 65536)
56736 ** 18 1 File format write version
56737 ** 19 1 File format read version
56738 ** 20 1 Bytes of unused space at the end of each page
56739 ** 21 1 Max embedded payload fraction (must be 64)
56740 ** 22 1 Min embedded payload fraction (must be 32)
56741 ** 23 1 Min leaf payload fraction (must be 32)
56742 ** 24 4 File change counter
56743 ** 28 4 Reserved for future use
56744 ** 32 4 First freelist page
56745 ** 36 4 Number of freelist pages in the file
56746 ** 40 60 15 4-byte meta values passed to higher layers
56747 **
56748 ** 40 4 Schema cookie
56749 ** 44 4 File format of schema layer
56750 ** 48 4 Size of page cache
56751 ** 52 4 Largest root-page (auto/incr_vacuum)
56752 ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
56753 ** 60 4 User version
56754 ** 64 4 Incremental vacuum mode
56755 ** 68 4 Application-ID
56756 ** 72 20 unused
56757 ** 92 4 The version-valid-for number
56758 ** 96 4 SQLITE_VERSION_NUMBER
56759 **
56760 ** All of the integer values are big-endian (most significant byte first).
56761 **
56762 ** The file change counter is incremented when the database is changed
56763 ** This counter allows other processes to know when the file has changed
56764 ** and thus when they need to flush their cache.
56765 **
56766 ** The max embedded payload fraction is the amount of the total usable
56767 ** space in a page that can be consumed by a single cell for standard
56768 ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
56769 ** is to limit the maximum cell size so that at least 4 cells will fit
56770 ** on one page. Thus the default max embedded payload fraction is 64.
56771 **
56772 ** If the payload for a cell is larger than the max payload, then extra
56773 ** payload is spilled to overflow pages. Once an overflow page is allocated,
56774 ** as many bytes as possible are moved into the overflow pages without letting
56775 ** the cell size drop below the min embedded payload fraction.
56776 **
56777 ** The min leaf payload fraction is like the min embedded payload fraction
56778 ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
56779 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
56780 ** not specified in the header.
56781 **
56782 ** Each btree pages is divided into three sections: The header, the
56783 ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
56784 ** file header that occurs before the page header.
56785 **
56786 ** |----------------|
56787 ** | file header | 100 bytes. Page 1 only.
56788 ** |----------------|
56789 ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
56790 ** |----------------|
56791 ** | cell pointer | | 2 bytes per cell. Sorted order.
56792 ** | array | | Grows downward
56793 ** | | v
56794 ** |----------------|
56795 ** | unallocated |
56796 ** | space |
56797 ** |----------------| ^ Grows upwards
56798 ** | cell content | | Arbitrary order interspersed with freeblocks.
56799 ** | area | | and free space fragments.
56800 ** |----------------|
56801 **
56802 ** The page headers looks like this:
56803 **
56804 ** OFFSET SIZE DESCRIPTION
56805 ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
56806 ** 1 2 byte offset to the first freeblock
56807 ** 3 2 number of cells on this page
56808 ** 5 2 first byte of the cell content area
56809 ** 7 1 number of fragmented free bytes
56810 ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
56811 **
56812 ** The flags define the format of this btree page. The leaf flag means that
56813 ** this page has no children. The zerodata flag means that this page carries
56814 ** only keys and no data. The intkey flag means that the key is an integer
56815 ** which is stored in the key size entry of the cell header rather than in
56816 ** the payload area.
56817 **
56818 ** The cell pointer array begins on the first byte after the page header.
56819 ** The cell pointer array contains zero or more 2-byte numbers which are
56820 ** offsets from the beginning of the page to the cell content in the cell
56821 ** content area. The cell pointers occur in sorted order. The system strives
56822 ** to keep free space after the last cell pointer so that new cells can
56823 ** be easily added without having to defragment the page.
56824 **
56825 ** Cell content is stored at the very end of the page and grows toward the
56826 ** beginning of the page.
56827 **
56828 ** Unused space within the cell content area is collected into a linked list of
56829 ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
56830 ** to the first freeblock is given in the header. Freeblocks occur in
56831 ** increasing order. Because a freeblock must be at least 4 bytes in size,
56832 ** any group of 3 or fewer unused bytes in the cell content area cannot
56833 ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
56834 ** a fragment. The total number of bytes in all fragments is recorded.
56835 ** in the page header at offset 7.
56836 **
56837 ** SIZE DESCRIPTION
56838 ** 2 Byte offset of the next freeblock
56839 ** 2 Bytes in this freeblock
56840 **
56841 ** Cells are of variable length. Cells are stored in the cell content area at
56842 ** the end of the page. Pointers to the cells are in the cell pointer array
56843 ** that immediately follows the page header. Cells is not necessarily
56844 ** contiguous or in order, but cell pointers are contiguous and in order.
56845 **
56846 ** Cell content makes use of variable length integers. A variable
56847 ** length integer is 1 to 9 bytes where the lower 7 bits of each
56848 ** byte are used. The integer consists of all bytes that have bit 8 set and
56849 ** the first byte with bit 8 clear. The most significant byte of the integer
56850 ** appears first. A variable-length integer may not be more than 9 bytes long.
56851 ** As a special case, all 8 bytes of the 9th byte are used as data. This
56852 ** allows a 64-bit integer to be encoded in 9 bytes.
56853 **
56854 ** 0x00 becomes 0x00000000
56855 ** 0x7f becomes 0x0000007f
56856 ** 0x81 0x00 becomes 0x00000080
56857 ** 0x82 0x00 becomes 0x00000100
56858 ** 0x80 0x7f becomes 0x0000007f
56859 ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
56860 ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
56861 **
56862 ** Variable length integers are used for rowids and to hold the number of
56863 ** bytes of key and data in a btree cell.
56864 **
56865 ** The content of a cell looks like this:
56866 **
56867 ** SIZE DESCRIPTION
56868 ** 4 Page number of the left child. Omitted if leaf flag is set.
56869 ** var Number of bytes of data. Omitted if the zerodata flag is set.
56870 ** var Number of bytes of key. Or the key itself if intkey flag is set.
56871 ** * Payload
56872 ** 4 First page of the overflow chain. Omitted if no overflow
56873 **
56874 ** Overflow pages form a linked list. Each page except the last is completely
56875 ** filled with data (pagesize - 4 bytes). The last page can have as little
56876 ** as 1 byte of data.
56877 **
56878 ** SIZE DESCRIPTION
56879 ** 4 Page number of next overflow page
56880 ** * Data
56881 **
56882 ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
56883 ** file header points to the first in a linked list of trunk page. Each trunk
56884 ** page points to multiple leaf pages. The content of a leaf page is
56885 ** unspecified. A trunk page looks like this:
56886 **
56887 ** SIZE DESCRIPTION
56888 ** 4 Page number of next trunk page
56889 ** 4 Number of leaf pointers on this page
56890 ** * zero or more pages numbers of leaves
56891 */
56892 /* #include "sqliteInt.h" */
56893 
56894 
56895 /* The following value is the maximum cell size assuming a maximum page
56896 ** size give above.
56897 */
56898 #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
56899 
56900 /* The maximum number of cells on a single page of the database. This
56901 ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
56902 ** plus 2 bytes for the index to the cell in the page header). Such
56903 ** small cells will be rare, but they are possible.
56904 */
56905 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
56906 
56907 /* Forward declarations */
56908 typedef struct MemPage MemPage;
56909 typedef struct BtLock BtLock;
56910 typedef struct CellInfo CellInfo;
56911 
56912 /*
56913 ** This is a magic string that appears at the beginning of every
56914 ** SQLite database in order to identify the file as a real database.
56915 **
56916 ** You can change this value at compile-time by specifying a
56917 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
56918 ** header must be exactly 16 bytes including the zero-terminator so
56919 ** the string itself should be 15 characters long. If you change
56920 ** the header, then your custom library will not be able to read
56921 ** databases generated by the standard tools and the standard tools
56922 ** will not be able to read databases created by your custom library.
56923 */
56924 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
56925 # define SQLITE_FILE_HEADER "SQLite format 3"
56926 #endif
56927 
56928 /*
56929 ** Page type flags. An ORed combination of these flags appear as the
56930 ** first byte of on-disk image of every BTree page.
56931 */
56932 #define PTF_INTKEY 0x01
56933 #define PTF_ZERODATA 0x02
56934 #define PTF_LEAFDATA 0x04
56935 #define PTF_LEAF 0x08
56936 
56937 /*
56938 ** As each page of the file is loaded into memory, an instance of the following
56939 ** structure is appended and initialized to zero. This structure stores
56940 ** information about the page that is decoded from the raw file page.
56941 **
56942 ** The pParent field points back to the parent page. This allows us to
56943 ** walk up the BTree from any leaf to the root. Care must be taken to
56944 ** unref() the parent page pointer when this page is no longer referenced.
56945 ** The pageDestructor() routine handles that chore.
56946 **
56947 ** Access to all fields of this structure is controlled by the mutex
56948 ** stored in MemPage.pBt->mutex.
56949 */
56950 struct MemPage {
56951  u8 isInit; /* True if previously initialized. MUST BE FIRST! */
56952  u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
56953  u8 intKey; /* True if table b-trees. False for index b-trees */
56954  u8 intKeyLeaf; /* True if the leaf of an intKey table */
56955  u8 leaf; /* True if a leaf page */
56956  u8 hdrOffset; /* 100 for page 1. 0 otherwise */
56957  u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
56958  u8 max1bytePayload; /* min(maxLocal,127) */
56959  u8 bBusy; /* Prevent endless loops on corrupt database files */
56960  u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
56961  u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
56962  u16 cellOffset; /* Index in aData of first cell pointer */
56963  u16 nFree; /* Number of free bytes on the page */
56964  u16 nCell; /* Number of cells on this page, local and ovfl */
56965  u16 maskPage; /* Mask for page offset */
56966  u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
56967  ** non-overflow cell */
56968  u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
56969  BtShared *pBt; /* Pointer to BtShared that this page is part of */
56970  u8 *aData; /* Pointer to disk image of the page data */
56971  u8 *aDataEnd; /* One byte past the end of usable data */
56972  u8 *aCellIdx; /* The cell index area */
56973  u8 *aDataOfst; /* Same as aData for leaves. aData+4 for interior */
56974  DbPage *pDbPage; /* Pager page handle */
56975  u16 (*xCellSize)(MemPage*,u8*); /* cellSizePtr method */
56976  void (*xParseCell)(MemPage*,u8*,CellInfo*); /* btreeParseCell method */
56977  Pgno pgno; /* Page number for this page */
56978 };
56979 
56980 /*
56981 ** The in-memory image of a disk page has the auxiliary information appended
56982 ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
56983 ** that extra information.
56984 */
56985 #define EXTRA_SIZE sizeof(MemPage)
56986 
56987 /*
56988 ** A linked list of the following structures is stored at BtShared.pLock.
56989 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
56990 ** is opened on the table with root page BtShared.iTable. Locks are removed
56991 ** from this list when a transaction is committed or rolled back, or when
56992 ** a btree handle is closed.
56993 */
56994 struct BtLock {
56995  Btree *pBtree; /* Btree handle holding this lock */
56996  Pgno iTable; /* Root page of table */
56997  u8 eLock; /* READ_LOCK or WRITE_LOCK */
56998  BtLock *pNext; /* Next in BtShared.pLock list */
56999 };
57000 
57001 /* Candidate values for BtLock.eLock */
57002 #define READ_LOCK 1
57003 #define WRITE_LOCK 2
57004 
57005 /* A Btree handle
57006 **
57007 ** A database connection contains a pointer to an instance of
57008 ** this object for every database file that it has open. This structure
57009 ** is opaque to the database connection. The database connection cannot
57010 ** see the internals of this structure and only deals with pointers to
57011 ** this structure.
57012 **
57013 ** For some database files, the same underlying database cache might be
57014 ** shared between multiple connections. In that case, each connection
57015 ** has it own instance of this object. But each instance of this object
57016 ** points to the same BtShared object. The database cache and the
57017 ** schema associated with the database file are all contained within
57018 ** the BtShared object.
57019 **
57020 ** All fields in this structure are accessed under sqlite3.mutex.
57021 ** The pBt pointer itself may not be changed while there exists cursors
57022 ** in the referenced BtShared that point back to this Btree since those
57023 ** cursors have to go through this Btree to find their BtShared and
57024 ** they often do so without holding sqlite3.mutex.
57025 */
57026 struct Btree {
57027  sqlite3 *db; /* The database connection holding this btree */
57028  BtShared *pBt; /* Sharable content of this btree */
57029  u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
57030  u8 sharable; /* True if we can share pBt with another db */
57031  u8 locked; /* True if db currently has pBt locked */
57032  u8 hasIncrblobCur; /* True if there are one or more Incrblob cursors */
57033  int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
57034  int nBackup; /* Number of backup operations reading this btree */
57035  u32 iDataVersion; /* Combines with pBt->pPager->iDataVersion */
57036  Btree *pNext; /* List of other sharable Btrees from the same db */
57037  Btree *pPrev; /* Back pointer of the same list */
57038 #ifndef SQLITE_OMIT_SHARED_CACHE
57039  BtLock lock; /* Object used to lock page 1 */
57040 #endif
57041 };
57042 
57043 /*
57044 ** Btree.inTrans may take one of the following values.
57045 **
57046 ** If the shared-data extension is enabled, there may be multiple users
57047 ** of the Btree structure. At most one of these may open a write transaction,
57048 ** but any number may have active read transactions.
57049 */
57050 #define TRANS_NONE 0
57051 #define TRANS_READ 1
57052 #define TRANS_WRITE 2
57053 
57054 /*
57055 ** An instance of this object represents a single database file.
57056 **
57057 ** A single database file can be in use at the same time by two
57058 ** or more database connections. When two or more connections are
57059 ** sharing the same database file, each connection has it own
57060 ** private Btree object for the file and each of those Btrees points
57061 ** to this one BtShared object. BtShared.nRef is the number of
57062 ** connections currently sharing this database file.
57063 **
57064 ** Fields in this structure are accessed under the BtShared.mutex
57065 ** mutex, except for nRef and pNext which are accessed under the
57066 ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
57067 ** may not be modified once it is initially set as long as nRef>0.
57068 ** The pSchema field may be set once under BtShared.mutex and
57069 ** thereafter is unchanged as long as nRef>0.
57070 **
57071 ** isPending:
57072 **
57073 ** If a BtShared client fails to obtain a write-lock on a database
57074 ** table (because there exists one or more read-locks on the table),
57075 ** the shared-cache enters 'pending-lock' state and isPending is
57076 ** set to true.
57077 **
57078 ** The shared-cache leaves the 'pending lock' state when either of
57079 ** the following occur:
57080 **
57081 ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
57082 ** 2) The number of locks held by other connections drops to zero.
57083 **
57084 ** while in the 'pending-lock' state, no connection may start a new
57085 ** transaction.
57086 **
57087 ** This feature is included to help prevent writer-starvation.
57088 */
57089 struct BtShared {
57090  Pager *pPager; /* The page cache */
57091  sqlite3 *db; /* Database connection currently using this Btree */
57092  BtCursor *pCursor; /* A list of all open cursors */
57093  MemPage *pPage1; /* First page of the database */
57094  u8 openFlags; /* Flags to sqlite3BtreeOpen() */
57095 #ifndef SQLITE_OMIT_AUTOVACUUM
57096  u8 autoVacuum; /* True if auto-vacuum is enabled */
57097  u8 incrVacuum; /* True if incr-vacuum is enabled */
57098  u8 bDoTruncate; /* True to truncate db on commit */
57099 #endif
57100  u8 inTransaction; /* Transaction state */
57101  u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
57102 #ifdef SQLITE_HAS_CODEC
57103  u8 optimalReserve; /* Desired amount of reserved space per page */
57104 #endif
57105  u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
57106  u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
57107  u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
57108  u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
57109  u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
57110  u32 pageSize; /* Total number of bytes on a page */
57111  u32 usableSize; /* Number of usable bytes on each page */
57112  int nTransaction; /* Number of open transactions (read + write) */
57113  u32 nPage; /* Number of pages in the database */
57114  void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
57115  void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
57116  sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
57117  Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
57118 #ifndef SQLITE_OMIT_SHARED_CACHE
57119  int nRef; /* Number of references to this structure */
57120  BtShared *pNext; /* Next on a list of sharable BtShared structs */
57121  BtLock *pLock; /* List of locks held on this shared-btree struct */
57122  Btree *pWriter; /* Btree with currently open write transaction */
57123 #endif
57124  u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
57125 };
57126 
57127 /*
57128 ** Allowed values for BtShared.btsFlags
57129 */
57130 #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
57131 #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
57132 #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
57133 #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
57134 #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
57135 #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
57136 #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
57137 
57138 /*
57139 ** An instance of the following structure is used to hold information
57140 ** about a cell. The parseCellPtr() function fills in this structure
57141 ** based on information extract from the raw disk page.
57142 */
57143 struct CellInfo {
57144  i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
57145  u8 *pPayload; /* Pointer to the start of payload */
57146  u32 nPayload; /* Bytes of payload */
57147  u16 nLocal; /* Amount of payload held locally, not on overflow */
57148  u16 nSize; /* Size of the cell content on the main b-tree page */
57149 };
57150 
57151 /*
57152 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
57153 ** this will be declared corrupt. This value is calculated based on a
57154 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
57155 ** root-node and 3 for all other internal nodes.
57156 **
57157 ** If a tree that appears to be taller than this is encountered, it is
57158 ** assumed that the database is corrupt.
57159 */
57160 #define BTCURSOR_MAX_DEPTH 20
57161 
57162 /*
57163 ** A cursor is a pointer to a particular entry within a particular
57164 ** b-tree within a database file.
57165 **
57166 ** The entry is identified by its MemPage and the index in
57167 ** MemPage.aCell[] of the entry.
57168 **
57169 ** A single database file can be shared by two more database connections,
57170 ** but cursors cannot be shared. Each cursor is associated with a
57171 ** particular database connection identified BtCursor.pBtree.db.
57172 **
57173 ** Fields in this structure are accessed under the BtShared.mutex
57174 ** found at self->pBt->mutex.
57175 **
57176 ** skipNext meaning:
57177 ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
57178 ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
57179 ** eState==FAULT: Cursor fault with skipNext as error code.
57180 */
57181 struct BtCursor {
57182  Btree *pBtree; /* The Btree to which this cursor belongs */
57183  BtShared *pBt; /* The BtShared this cursor points to */
57184  BtCursor *pNext; /* Forms a linked list of all cursors */
57185  Pgno *aOverflow; /* Cache of overflow page locations */
57186  CellInfo info; /* A parse of the cell we are pointing at */
57187  i64 nKey; /* Size of pKey, or last integer key */
57188  void *pKey; /* Saved key that was cursor last known position */
57189  Pgno pgnoRoot; /* The root page of this tree */
57190  int nOvflAlloc; /* Allocated size of aOverflow[] array */
57191  int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
57192  ** Error code if eState==CURSOR_FAULT */
57193  u8 curFlags; /* zero or more BTCF_* flags defined below */
57194  u8 curPagerFlags; /* Flags to send to sqlite3PagerGet() */
57195  u8 eState; /* One of the CURSOR_XXX constants (see below) */
57196  u8 hints; /* As configured by CursorSetHints() */
57197  /* All fields above are zeroed when the cursor is allocated. See
57198  ** sqlite3BtreeCursorZero(). Fields that follow must be manually
57199  ** initialized. */
57200  i8 iPage; /* Index of current page in apPage */
57201  u8 curIntKey; /* Value of apPage[0]->intKey */
57202  struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
57203  void *padding1; /* Make object size a multiple of 16 */
57204  u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
57205  MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
57206 };
57207 
57208 /*
57209 ** Legal values for BtCursor.curFlags
57210 */
57211 #define BTCF_WriteFlag 0x01 /* True if a write cursor */
57212 #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
57213 #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
57214 #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
57215 #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
57216 #define BTCF_Multiple 0x20 /* Maybe another cursor on the same btree */
57217 
57218 /*
57219 ** Potential values for BtCursor.eState.
57220 **
57221 ** CURSOR_INVALID:
57222 ** Cursor does not point to a valid entry. This can happen (for example)
57223 ** because the table is empty or because BtreeCursorFirst() has not been
57224 ** called.
57225 **
57226 ** CURSOR_VALID:
57227 ** Cursor points to a valid entry. getPayload() etc. may be called.
57228 **
57229 ** CURSOR_SKIPNEXT:
57230 ** Cursor is valid except that the Cursor.skipNext field is non-zero
57231 ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
57232 ** operation should be a no-op.
57233 **
57234 ** CURSOR_REQUIRESEEK:
57235 ** The table that this cursor was opened on still exists, but has been
57236 ** modified since the cursor was last used. The cursor position is saved
57237 ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
57238 ** this state, restoreCursorPosition() can be called to attempt to
57239 ** seek the cursor to the saved position.
57240 **
57241 ** CURSOR_FAULT:
57242 ** An unrecoverable error (an I/O error or a malloc failure) has occurred
57243 ** on a different connection that shares the BtShared cache with this
57244 ** cursor. The error has left the cache in an inconsistent state.
57245 ** Do nothing else with this cursor. Any attempt to use the cursor
57246 ** should return the error code stored in BtCursor.skipNext
57247 */
57248 #define CURSOR_INVALID 0
57249 #define CURSOR_VALID 1
57250 #define CURSOR_SKIPNEXT 2
57251 #define CURSOR_REQUIRESEEK 3
57252 #define CURSOR_FAULT 4
57253 
57254 /*
57255 ** The database page the PENDING_BYTE occupies. This page is never used.
57256 */
57257 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
57258 
57259 /*
57260 ** These macros define the location of the pointer-map entry for a
57261 ** database page. The first argument to each is the number of usable
57262 ** bytes on each page of the database (often 1024). The second is the
57263 ** page number to look up in the pointer map.
57264 **
57265 ** PTRMAP_PAGENO returns the database page number of the pointer-map
57266 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
57267 ** the offset of the requested map entry.
57268 **
57269 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
57270 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
57271 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
57272 ** this test.
57273 */
57274 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
57275 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
57276 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
57277 
57278 /*
57279 ** The pointer map is a lookup table that identifies the parent page for
57280 ** each child page in the database file. The parent page is the page that
57281 ** contains a pointer to the child. Every page in the database contains
57282 ** 0 or 1 parent pages. (In this context 'database page' refers
57283 ** to any page that is not part of the pointer map itself.) Each pointer map
57284 ** entry consists of a single byte 'type' and a 4 byte parent page number.
57285 ** The PTRMAP_XXX identifiers below are the valid types.
57286 **
57287 ** The purpose of the pointer map is to facility moving pages from one
57288 ** position in the file to another as part of autovacuum. When a page
57289 ** is moved, the pointer in its parent must be updated to point to the
57290 ** new location. The pointer map is used to locate the parent page quickly.
57291 **
57292 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
57293 ** used in this case.
57294 **
57295 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
57296 ** is not used in this case.
57297 **
57298 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
57299 ** overflow pages. The page number identifies the page that
57300 ** contains the cell with a pointer to this overflow page.
57301 **
57302 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
57303 ** overflow pages. The page-number identifies the previous
57304 ** page in the overflow page list.
57305 **
57306 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
57307 ** identifies the parent page in the btree.
57308 */
57309 #define PTRMAP_ROOTPAGE 1
57310 #define PTRMAP_FREEPAGE 2
57311 #define PTRMAP_OVERFLOW1 3
57312 #define PTRMAP_OVERFLOW2 4
57313 #define PTRMAP_BTREE 5
57314 
57315 /* A bunch of assert() statements to check the transaction state variables
57316 ** of handle p (type Btree*) are internally consistent.
57317 */
57318 #define btreeIntegrity(p) \
57319  assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
57320  assert( p->pBt->inTransaction>=p->inTrans );
57321 
57322 
57323 /*
57324 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
57325 ** if the database supports auto-vacuum or not. Because it is used
57326 ** within an expression that is an argument to another macro
57327 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
57328 ** So, this macro is defined instead.
57329 */
57330 #ifndef SQLITE_OMIT_AUTOVACUUM
57331 #define ISAUTOVACUUM (pBt->autoVacuum)
57332 #else
57333 #define ISAUTOVACUUM 0
57334 #endif
57335 
57336 
57337 /*
57338 ** This structure is passed around through all the sanity checking routines
57339 ** in order to keep track of some global state information.
57340 **
57341 ** The aRef[] array is allocated so that there is 1 bit for each page in
57342 ** the database. As the integrity-check proceeds, for each page used in
57343 ** the database the corresponding bit is set. This allows integrity-check to
57344 ** detect pages that are used twice and orphaned pages (both of which
57345 ** indicate corruption).
57346 */
57347 typedef struct IntegrityCk IntegrityCk;
57348 struct IntegrityCk {
57349  BtShared *pBt; /* The tree being checked out */
57350  Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
57351  u8 *aPgRef; /* 1 bit per page in the db (see above) */
57352  Pgno nPage; /* Number of pages in the database */
57353  int mxErr; /* Stop accumulating errors when this reaches zero */
57354  int nErr; /* Number of messages written to zErrMsg so far */
57355  int mallocFailed; /* A memory allocation error has occurred */
57356  const char *zPfx; /* Error message prefix */
57357  int v1, v2; /* Values for up to two %d fields in zPfx */
57358  StrAccum errMsg; /* Accumulate the error message text here */
57359  u32 *heap; /* Min-heap used for analyzing cell coverage */
57360 };
57361 
57362 /*
57363 ** Routines to read or write a two- and four-byte big-endian integer values.
57364 */
57365 #define get2byte(x) ((x)[0]<<8 | (x)[1])
57366 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
57367 #define get4byte sqlite3Get4byte
57368 #define put4byte sqlite3Put4byte
57369 
57370 /*
57371 ** get2byteAligned(), unlike get2byte(), requires that its argument point to a
57372 ** two-byte aligned address. get2bytea() is only used for accessing the
57373 ** cell addresses in a btree header.
57374 */
57375 #if SQLITE_BYTEORDER==4321
57376 # define get2byteAligned(x) (*(u16*)(x))
57377 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57378  && GCC_VERSION>=4008000
57379 # define get2byteAligned(x) __builtin_bswap16(*(u16*)(x))
57380 #elif SQLITE_BYTEORDER==1234 && !defined(SQLITE_DISABLE_INTRINSIC) \
57381  && defined(_MSC_VER) && _MSC_VER>=1300
57382 # define get2byteAligned(x) _byteswap_ushort(*(u16*)(x))
57383 #else
57384 # define get2byteAligned(x) ((x)[0]<<8 | (x)[1])
57385 #endif
57386 
57387 /************** End of btreeInt.h ********************************************/
57388 /************** Continuing where we left off in btmutex.c ********************/
57389 #ifndef SQLITE_OMIT_SHARED_CACHE
57390 #if SQLITE_THREADSAFE
57391 
57392 /*
57393 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
57394 ** set BtShared.db to the database handle associated with p and the
57395 ** p->locked boolean to true.
57396 */
57397 static void lockBtreeMutex(Btree *p){
57398  assert( p->locked==0 );
57401 
57403  p->pBt->db = p->db;
57404  p->locked = 1;
57405 }
57406 
57407 /*
57408 ** Release the BtShared mutex associated with B-Tree handle p and
57409 ** clear the p->locked boolean.
57410 */
57412  BtShared *pBt = p->pBt;
57413  assert( p->locked==1 );
57414  assert( sqlite3_mutex_held(pBt->mutex) );
57416  assert( p->db==pBt->db );
57417 
57418  sqlite3_mutex_leave(pBt->mutex);
57419  p->locked = 0;
57420 }
57421 
57422 /* Forward reference */
57423 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
57424 
57425 /*
57426 ** Enter a mutex on the given BTree object.
57427 **
57428 ** If the object is not sharable, then no mutex is ever required
57429 ** and this routine is a no-op. The underlying mutex is non-recursive.
57430 ** But we keep a reference count in Btree.wantToLock so the behavior
57431 ** of this interface is recursive.
57432 **
57433 ** To avoid deadlocks, multiple Btrees are locked in the same order
57434 ** by all database connections. The p->pNext is a list of other
57435 ** Btrees belonging to the same database connection as the p Btree
57436 ** which need to be locked after p. If we cannot get a lock on
57437 ** p, then first unlock all of the others on p->pNext, then wait
57438 ** for the lock to become available on p, then relock all of the
57439 ** subsequent Btrees that desire a lock.
57440 */
57442  /* Some basic sanity checking on the Btree. The list of Btrees
57443  ** connected by pNext and pPrev should be in sorted order by
57444  ** Btree.pBt value. All elements of the list should belong to
57445  ** the same connection. Only shared Btrees are on the list. */
57446  assert( p->pNext==0 || p->pNext->pBt>p->pBt );
57447  assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
57448  assert( p->pNext==0 || p->pNext->db==p->db );
57449  assert( p->pPrev==0 || p->pPrev->db==p->db );
57450  assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
57451 
57452  /* Check for locking consistency */
57453  assert( !p->locked || p->wantToLock>0 );
57454  assert( p->sharable || p->wantToLock==0 );
57455 
57456  /* We should already hold a lock on the database connection */
57458 
57459  /* Unless the database is sharable and unlocked, then BtShared.db
57460  ** should already be set correctly. */
57461  assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
57462 
57463  if( !p->sharable ) return;
57464  p->wantToLock++;
57465  if( p->locked ) return;
57466  btreeLockCarefully(p);
57467 }
57468 
57469 /* This is a helper function for sqlite3BtreeLock(). By moving
57470 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
57471 ** into this routine, we avoid unnecessary stack pointer changes
57472 ** and thus help the sqlite3BtreeLock() routine to run much faster
57473 ** in the common case.
57474 */
57476  Btree *pLater;
57477 
57478  /* In most cases, we should be able to acquire the lock we
57479  ** want without having to go through the ascending lock
57480  ** procedure that follows. Just be sure not to block.
57481  */
57482  if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
57483  p->pBt->db = p->db;
57484  p->locked = 1;
57485  return;
57486  }
57487 
57488  /* To avoid deadlock, first release all locks with a larger
57489  ** BtShared address. Then acquire our lock. Then reacquire
57490  ** the other BtShared locks that we used to hold in ascending
57491  ** order.
57492  */
57493  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57494  assert( pLater->sharable );
57495  assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
57496  assert( !pLater->locked || pLater->wantToLock>0 );
57497  if( pLater->locked ){
57498  unlockBtreeMutex(pLater);
57499  }
57500  }
57501  lockBtreeMutex(p);
57502  for(pLater=p->pNext; pLater; pLater=pLater->pNext){
57503  if( pLater->wantToLock ){
57504  lockBtreeMutex(pLater);
57505  }
57506  }
57507 }
57508 
57509 
57510 /*
57511 ** Exit the recursive mutex on a Btree.
57512 */
57515  if( p->sharable ){
57516  assert( p->wantToLock>0 );
57517  p->wantToLock--;
57518  if( p->wantToLock==0 ){
57519  unlockBtreeMutex(p);
57520  }
57521  }
57522 }
57523 
57524 #ifndef NDEBUG
57525 /*
57526 ** Return true if the BtShared mutex is held on the btree, or if the
57527 ** B-Tree is not marked as sharable.
57528 **
57529 ** This routine is used only from within assert() statements.
57530 */
57531 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
57532  assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
57533  assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
57534  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
57535  assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
57536 
57537  return (p->sharable==0 || p->locked);
57538 }
57539 #endif
57540 
57541 
57542 /*
57543 ** Enter the mutex on every Btree associated with a database
57544 ** connection. This is needed (for example) prior to parsing
57545 ** a statement since we will be comparing table and column names
57546 ** against all schemas and we do not want those schemas being
57547 ** reset out from under us.
57548 **
57549 ** There is a corresponding leave-all procedures.
57550 **
57551 ** Enter the mutexes in accending order by BtShared pointer address
57552 ** to avoid the possibility of deadlock when two threads with
57553 ** two or more btrees in common both try to lock all their btrees
57554 ** at the same instant.
57555 */
57557  int i;
57558  Btree *p;
57560  for(i=0; i<db->nDb; i++){
57561  p = db->aDb[i].pBt;
57562  if( p ) sqlite3BtreeEnter(p);
57563  }
57564 }
57566  int i;
57567  Btree *p;
57569  for(i=0; i<db->nDb; i++){
57570  p = db->aDb[i].pBt;
57571  if( p ) sqlite3BtreeLeave(p);
57572  }
57573 }
57574 
57575 #ifndef NDEBUG
57576 /*
57577 ** Return true if the current thread holds the database connection
57578 ** mutex and all required BtShared mutexes.
57579 **
57580 ** This routine is used inside assert() statements only.
57581 */
57582 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
57583  int i;
57584  if( !sqlite3_mutex_held(db->mutex) ){
57585  return 0;
57586  }
57587  for(i=0; i<db->nDb; i++){
57588  Btree *p;
57589  p = db->aDb[i].pBt;
57590  if( p && p->sharable &&
57591  (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
57592  return 0;
57593  }
57594  }
57595  return 1;
57596 }
57597 #endif /* NDEBUG */
57598 
57599 #ifndef NDEBUG
57600 /*
57601 ** Return true if the correct mutexes are held for accessing the
57602 ** db->aDb[iDb].pSchema structure. The mutexes required for schema
57603 ** access are:
57604 **
57605 ** (1) The mutex on db
57606 ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
57607 **
57608 ** If pSchema is not NULL, then iDb is computed from pSchema and
57609 ** db using sqlite3SchemaToIndex().
57610 */
57611 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
57612  Btree *p;
57613  assert( db!=0 );
57614  if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
57615  assert( iDb>=0 && iDb<db->nDb );
57616  if( !sqlite3_mutex_held(db->mutex) ) return 0;
57617  if( iDb==1 ) return 1;
57618  p = db->aDb[iDb].pBt;
57619  assert( p!=0 );
57620  return p->sharable==0 || p->locked==1;
57621 }
57622 #endif /* NDEBUG */
57623 
57624 #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
57625 /*
57626 ** The following are special cases for mutex enter routines for use
57627 ** in single threaded applications that use shared cache. Except for
57628 ** these two routines, all mutex operations are no-ops in that case and
57629 ** are null #defines in btree.h.
57630 **
57631 ** If shared cache is disabled, then all btree mutex routines, including
57632 ** the ones below, are no-ops and are null #defines in btree.h.
57633 */
57634 
57636  p->pBt->db = p->db;
57637 }
57639  int i;
57640  for(i=0; i<db->nDb; i++){
57641  Btree *p = db->aDb[i].pBt;
57642  if( p ){
57643  p->pBt->db = p->db;
57644  }
57645  }
57646 }
57647 #endif /* if SQLITE_THREADSAFE */
57648 
57649 #ifndef SQLITE_OMIT_INCRBLOB
57650 /*
57651 ** Enter a mutex on a Btree given a cursor owned by that Btree.
57652 **
57653 ** These entry points are used by incremental I/O only. Enter() is required
57654 ** any time OMIT_SHARED_CACHE is not defined, regardless of whether or not
57655 ** the build is threadsafe. Leave() is only required by threadsafe builds.
57656 */
57658  sqlite3BtreeEnter(pCur->pBtree);
57659 }
57660 # if SQLITE_THREADSAFE
57662  sqlite3BtreeLeave(pCur->pBtree);
57663 }
57664 # endif
57665 #endif /* ifndef SQLITE_OMIT_INCRBLOB */
57666 
57667 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
57668 
57669 /************** End of btmutex.c *********************************************/
57670 /************** Begin file btree.c *******************************************/
57671 /*
57672 ** 2004 April 6
57673 **
57674 ** The author disclaims copyright to this source code. In place of
57675 ** a legal notice, here is a blessing:
57676 **
57677 ** May you do good and not evil.
57678 ** May you find forgiveness for yourself and forgive others.
57679 ** May you share freely, never taking more than you give.
57680 **
57681 *************************************************************************
57682 ** This file implements an external (disk-based) database using BTrees.
57683 ** See the header comment on "btreeInt.h" for additional information.
57684 ** Including a description of file format and an overview of operation.
57685 */
57686 /* #include "btreeInt.h" */
57687 
57688 /*
57689 ** The header string that appears at the beginning of every
57690 ** SQLite database.
57691 */
57692 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
57693 
57694 /*
57695 ** Set this global variable to 1 to enable tracing using the TRACE
57696 ** macro.
57697 */
57698 #if 0
57699 int sqlite3BtreeTrace=1; /* True to enable tracing */
57700 # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
57701 #else
57702 # define TRACE(X)
57703 #endif
57704 
57705 /*
57706 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
57707 ** But if the value is zero, make it 65536.
57708 **
57709 ** This routine is used to extract the "offset to cell content area" value
57710 ** from the header of a btree page. If the page size is 65536 and the page
57711 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
57712 ** This routine makes the necessary adjustment to 65536.
57713 */
57714 #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
57715 
57716 /*
57717 ** Values passed as the 5th argument to allocateBtreePage()
57718 */
57719 #define BTALLOC_ANY 0 /* Allocate any page */
57720 #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
57721 #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
57722 
57723 /*
57724 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
57725 ** defined, or 0 if it is. For example:
57726 **
57727 ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
57728 */
57729 #ifndef SQLITE_OMIT_AUTOVACUUM
57730 #define IfNotOmitAV(expr) (expr)
57731 #else
57732 #define IfNotOmitAV(expr) 0
57733 #endif
57734 
57735 #ifndef SQLITE_OMIT_SHARED_CACHE
57736 /*
57737 ** A list of BtShared objects that are eligible for participation
57738 ** in shared cache. This variable has file scope during normal builds,
57739 ** but the test harness needs to access it so we make it global for
57740 ** test builds.
57741 **
57742 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
57743 */
57744 #ifdef SQLITE_TEST
57746 #else
57747 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
57748 #endif
57749 #endif /* SQLITE_OMIT_SHARED_CACHE */
57750 
57751 #ifndef SQLITE_OMIT_SHARED_CACHE
57752 /*
57753 ** Enable or disable the shared pager and schema features.
57754 **
57755 ** This routine has no effect on existing database connections.
57756 ** The shared cache setting effects only future calls to
57757 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
57758 */
57760  sqlite3GlobalConfig.sharedCacheEnabled = enable;
57761  return SQLITE_OK;
57762 }
57763 #endif
57764 
57765 
57766 
57767 #ifdef SQLITE_OMIT_SHARED_CACHE
57768  /*
57769  ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
57770  ** and clearAllSharedCacheTableLocks()
57771  ** manipulate entries in the BtShared.pLock linked list used to store
57772  ** shared-cache table level locks. If the library is compiled with the
57773  ** shared-cache feature disabled, then there is only ever one user
57774  ** of each BtShared structure and so this locking is not necessary.
57775  ** So define the lock related functions as no-ops.
57776  */
57777  #define querySharedCacheTableLock(a,b,c) SQLITE_OK
57778  #define setSharedCacheTableLock(a,b,c) SQLITE_OK
57779  #define clearAllSharedCacheTableLocks(a)
57780  #define downgradeAllSharedCacheTableLocks(a)
57781  #define hasSharedCacheTableLock(a,b,c,d) 1
57782  #define hasReadConflicts(a, b) 0
57783 #endif
57784 
57785 #ifndef SQLITE_OMIT_SHARED_CACHE
57786 
57787 #ifdef SQLITE_DEBUG
57788 /*
57789 **** This function is only used as part of an assert() statement. ***
57790 **
57791 ** Check to see if pBtree holds the required locks to read or write to the
57792 ** table with root page iRoot. Return 1 if it does and 0 if not.
57793 **
57794 ** For example, when writing to a table with root-page iRoot via
57795 ** Btree connection pBtree:
57796 **
57797 ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
57798 **
57799 ** When writing to an index that resides in a sharable database, the
57800 ** caller should have first obtained a lock specifying the root page of
57801 ** the corresponding table. This makes things a bit more complicated,
57802 ** as this module treats each table as a separate structure. To determine
57803 ** the table corresponding to the index being written, this
57804 ** function has to search through the database schema.
57805 **
57806 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
57807 ** hold a write-lock on the schema table (root page 1). This is also
57808 ** acceptable.
57809 */
57810 static int hasSharedCacheTableLock(
57811  Btree *pBtree, /* Handle that must hold lock */
57812  Pgno iRoot, /* Root page of b-tree */
57813  int isIndex, /* True if iRoot is the root of an index b-tree */
57814  int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
57815 ){
57816  Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
57817  Pgno iTab = 0;
57818  BtLock *pLock;
57819 
57820  /* If this database is not shareable, or if the client is reading
57821  ** and has the read-uncommitted flag set, then no lock is required.
57822  ** Return true immediately.
57823  */
57824  if( (pBtree->sharable==0)
57825  || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
57826  ){
57827  return 1;
57828  }
57829 
57830  /* If the client is reading or writing an index and the schema is
57831  ** not loaded, then it is too difficult to actually check to see if
57832  ** the correct locks are held. So do not bother - just return true.
57833  ** This case does not come up very often anyhow.
57834  */
57835  if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
57836  return 1;
57837  }
57838 
57839  /* Figure out the root-page that the lock should be held on. For table
57840  ** b-trees, this is just the root page of the b-tree being read or
57841  ** written. For index b-trees, it is the root page of the associated
57842  ** table. */
57843  if( isIndex ){
57844  HashElem *p;
57845  for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
57846  Index *pIdx = (Index *)sqliteHashData(p);
57847  if( pIdx->tnum==(int)iRoot ){
57848  if( iTab ){
57849  /* Two or more indexes share the same root page. There must
57850  ** be imposter tables. So just return true. The assert is not
57851  ** useful in that case. */
57852  return 1;
57853  }
57854  iTab = pIdx->pTable->tnum;
57855  }
57856  }
57857  }else{
57858  iTab = iRoot;
57859  }
57860 
57861  /* Search for the required lock. Either a write-lock on root-page iTab, a
57862  ** write-lock on the schema table, or (if the client is reading) a
57863  ** read-lock on iTab will suffice. Return 1 if any of these are found. */
57864  for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
57865  if( pLock->pBtree==pBtree
57866  && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
57867  && pLock->eLock>=eLockType
57868  ){
57869  return 1;
57870  }
57871  }
57872 
57873  /* Failed to find the required lock. */
57874  return 0;
57875 }
57876 #endif /* SQLITE_DEBUG */
57877 
57878 #ifdef SQLITE_DEBUG
57879 /*
57880 **** This function may be used as part of assert() statements only. ****
57881 **
57882 ** Return true if it would be illegal for pBtree to write into the
57883 ** table or index rooted at iRoot because other shared connections are
57884 ** simultaneously reading that same table or index.
57885 **
57886 ** It is illegal for pBtree to write if some other Btree object that
57887 ** shares the same BtShared object is currently reading or writing
57888 ** the iRoot table. Except, if the other Btree object has the
57889 ** read-uncommitted flag set, then it is OK for the other object to
57890 ** have a read cursor.
57891 **
57892 ** For example, before writing to any part of the table or index
57893 ** rooted at page iRoot, one should call:
57894 **
57895 ** assert( !hasReadConflicts(pBtree, iRoot) );
57896 */
57897 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
57898  BtCursor *p;
57899  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
57900  if( p->pgnoRoot==iRoot
57901  && p->pBtree!=pBtree
57902  && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
57903  ){
57904  return 1;
57905  }
57906  }
57907  return 0;
57908 }
57909 #endif /* #ifdef SQLITE_DEBUG */
57910 
57911 /*
57912 ** Query to see if Btree handle p may obtain a lock of type eLock
57913 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
57914 ** SQLITE_OK if the lock may be obtained (by calling
57915 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
57916 */
57917 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
57918  BtShared *pBt = p->pBt;
57919  BtLock *pIter;
57920 
57921  assert( sqlite3BtreeHoldsMutex(p) );
57922  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
57923  assert( p->db!=0 );
57924  assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
57925 
57926  /* If requesting a write-lock, then the Btree must have an open write
57927  ** transaction on this file. And, obviously, for this to be so there
57928  ** must be an open write transaction on the file itself.
57929  */
57930  assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
57931  assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
57932 
57933  /* This routine is a no-op if the shared-cache is not enabled */
57934  if( !p->sharable ){
57935  return SQLITE_OK;
57936  }
57937 
57938  /* If some other connection is holding an exclusive lock, the
57939  ** requested lock may not be obtained.
57940  */
57941  if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
57944  }
57945 
57946  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
57947  /* The condition (pIter->eLock!=eLock) in the following if(...)
57948  ** statement is a simplification of:
57949  **
57950  ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
57951  **
57952  ** since we know that if eLock==WRITE_LOCK, then no other connection
57953  ** may hold a WRITE_LOCK on any table in this file (since there can
57954  ** only be a single writer).
57955  */
57956  assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
57957  assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
57958  if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
57959  sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
57960  if( eLock==WRITE_LOCK ){
57961  assert( p==pBt->pWriter );
57962  pBt->btsFlags |= BTS_PENDING;
57963  }
57965  }
57966  }
57967  return SQLITE_OK;
57968 }
57969 #endif /* !SQLITE_OMIT_SHARED_CACHE */
57970 
57971 #ifndef SQLITE_OMIT_SHARED_CACHE
57972 /*
57973 ** Add a lock on the table with root-page iTable to the shared-btree used
57974 ** by Btree handle p. Parameter eLock must be either READ_LOCK or
57975 ** WRITE_LOCK.
57976 **
57977 ** This function assumes the following:
57978 **
57979 ** (a) The specified Btree object p is connected to a sharable
57980 ** database (one with the BtShared.sharable flag set), and
57981 **
57982 ** (b) No other Btree objects hold a lock that conflicts
57983 ** with the requested lock (i.e. querySharedCacheTableLock() has
57984 ** already been called and returned SQLITE_OK).
57985 **
57986 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
57987 ** is returned if a malloc attempt fails.
57988 */
57989 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
57990  BtShared *pBt = p->pBt;
57991  BtLock *pLock = 0;
57992  BtLock *pIter;
57993 
57994  assert( sqlite3BtreeHoldsMutex(p) );
57995  assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
57996  assert( p->db!=0 );
57997 
57998  /* A connection with the read-uncommitted flag set will never try to
57999  ** obtain a read-lock using this function. The only read-lock obtained
58000  ** by a connection in read-uncommitted mode is on the sqlite_master
58001  ** table, and that lock is obtained in BtreeBeginTrans(). */
58002  assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
58003 
58004  /* This function should only be called on a sharable b-tree after it
58005  ** has been determined that no other b-tree holds a conflicting lock. */
58006  assert( p->sharable );
58007  assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
58008 
58009  /* First search the list for an existing lock on this table. */
58010  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
58011  if( pIter->iTable==iTable && pIter->pBtree==p ){
58012  pLock = pIter;
58013  break;
58014  }
58015  }
58016 
58017  /* If the above search did not find a BtLock struct associating Btree p
58018  ** with table iTable, allocate one and link it into the list.
58019  */
58020  if( !pLock ){
58021  pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
58022  if( !pLock ){
58023  return SQLITE_NOMEM_BKPT;
58024  }
58025  pLock->iTable = iTable;
58026  pLock->pBtree = p;
58027  pLock->pNext = pBt->pLock;
58028  pBt->pLock = pLock;
58029  }
58030 
58031  /* Set the BtLock.eLock variable to the maximum of the current lock
58032  ** and the requested lock. This means if a write-lock was already held
58033  ** and a read-lock requested, we don't incorrectly downgrade the lock.
58034  */
58036  if( eLock>pLock->eLock ){
58037  pLock->eLock = eLock;
58038  }
58039 
58040  return SQLITE_OK;
58041 }
58042 #endif /* !SQLITE_OMIT_SHARED_CACHE */
58043 
58044 #ifndef SQLITE_OMIT_SHARED_CACHE
58045 /*
58046 ** Release all the table locks (locks obtained via calls to
58047 ** the setSharedCacheTableLock() procedure) held by Btree object p.
58048 **
58049 ** This function assumes that Btree p has an open read or write
58050 ** transaction. If it does not, then the BTS_PENDING flag
58051 ** may be incorrectly cleared.
58052 */
58054  BtShared *pBt = p->pBt;
58055  BtLock **ppIter = &pBt->pLock;
58056 
58057  assert( sqlite3BtreeHoldsMutex(p) );
58058  assert( p->sharable || 0==*ppIter );
58059  assert( p->inTrans>0 );
58060 
58061  while( *ppIter ){
58062  BtLock *pLock = *ppIter;
58063  assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
58064  assert( pLock->pBtree->inTrans>=pLock->eLock );
58065  if( pLock->pBtree==p ){
58066  *ppIter = pLock->pNext;
58067  assert( pLock->iTable!=1 || pLock==&p->lock );
58068  if( pLock->iTable!=1 ){
58069  sqlite3_free(pLock);
58070  }
58071  }else{
58072  ppIter = &pLock->pNext;
58073  }
58074  }
58075 
58076  assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
58077  if( pBt->pWriter==p ){
58078  pBt->pWriter = 0;
58079  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58080  }else if( pBt->nTransaction==2 ){
58081  /* This function is called when Btree p is concluding its
58082  ** transaction. If there currently exists a writer, and p is not
58083  ** that writer, then the number of locks held by connections other
58084  ** than the writer must be about to drop to zero. In this case
58085  ** set the BTS_PENDING flag to 0.
58086  **
58087  ** If there is not currently a writer, then BTS_PENDING must
58088  ** be zero already. So this next line is harmless in that case.
58089  */
58090  pBt->btsFlags &= ~BTS_PENDING;
58091  }
58092 }
58093 
58094 /*
58095 ** This function changes all write-locks held by Btree p into read-locks.
58096 */
58098  BtShared *pBt = p->pBt;
58099  if( pBt->pWriter==p ){
58100  BtLock *pLock;
58101  pBt->pWriter = 0;
58102  pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
58103  for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
58104  assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
58105  pLock->eLock = READ_LOCK;
58106  }
58107  }
58108 }
58109 
58110 #endif /* SQLITE_OMIT_SHARED_CACHE */
58111 
58112 static void releasePage(MemPage *pPage); /* Forward reference */
58113 
58114 /*
58115 ***** This routine is used inside of assert() only ****
58116 **
58117 ** Verify that the cursor holds the mutex on its BtShared
58118 */
58119 #ifdef SQLITE_DEBUG
58120 static int cursorHoldsMutex(BtCursor *p){
58121  return sqlite3_mutex_held(p->pBt->mutex);
58122 }
58123 static int cursorOwnsBtShared(BtCursor *p){
58124  assert( cursorHoldsMutex(p) );
58125  return (p->pBtree->db==p->pBt->db);
58126 }
58127 #endif
58128 
58129 /*
58130 ** Invalidate the overflow cache of the cursor passed as the first argument.
58131 ** on the shared btree structure pBt.
58132 */
58133 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
58134 
58135 /*
58136 ** Invalidate the overflow page-list cache for all cursors opened
58137 ** on the shared btree structure pBt.
58138 */
58140  BtCursor *p;
58141  assert( sqlite3_mutex_held(pBt->mutex) );
58142  for(p=pBt->pCursor; p; p=p->pNext){
58144  }
58145 }
58146 
58147 #ifndef SQLITE_OMIT_INCRBLOB
58148 /*
58149 ** This function is called before modifying the contents of a table
58150 ** to invalidate any incrblob cursors that are open on the
58151 ** row or one of the rows being modified.
58152 **
58153 ** If argument isClearTable is true, then the entire contents of the
58154 ** table is about to be deleted. In this case invalidate all incrblob
58155 ** cursors open on any row within the table with root-page pgnoRoot.
58156 **
58157 ** Otherwise, if argument isClearTable is false, then the row with
58158 ** rowid iRow is being replaced or deleted. In this case invalidate
58159 ** only those incrblob cursors open on that specific row.
58160 */
58162  Btree *pBtree, /* The database file to check */
58163  i64 iRow, /* The rowid that might be changing */
58164  int isClearTable /* True if all rows are being deleted */
58165 ){
58166  BtCursor *p;
58167  if( pBtree->hasIncrblobCur==0 ) return;
58168  assert( sqlite3BtreeHoldsMutex(pBtree) );
58169  pBtree->hasIncrblobCur = 0;
58170  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
58171  if( (p->curFlags & BTCF_Incrblob)!=0 ){
58172  pBtree->hasIncrblobCur = 1;
58173  if( isClearTable || p->info.nKey==iRow ){
58174  p->eState = CURSOR_INVALID;
58175  }
58176  }
58177  }
58178 }
58179 
58180 #else
58181  /* Stub function when INCRBLOB is omitted */
58182  #define invalidateIncrblobCursors(x,y,z)
58183 #endif /* SQLITE_OMIT_INCRBLOB */
58184 
58185 /*
58186 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
58187 ** when a page that previously contained data becomes a free-list leaf
58188 ** page.
58189 **
58190 ** The BtShared.pHasContent bitvec exists to work around an obscure
58191 ** bug caused by the interaction of two useful IO optimizations surrounding
58192 ** free-list leaf pages:
58193 **
58194 ** 1) When all data is deleted from a page and the page becomes
58195 ** a free-list leaf page, the page is not written to the database
58196 ** (as free-list leaf pages contain no meaningful data). Sometimes
58197 ** such a page is not even journalled (as it will not be modified,
58198 ** why bother journalling it?).
58199 **
58200 ** 2) When a free-list leaf page is reused, its content is not read
58201 ** from the database or written to the journal file (why should it
58202 ** be, if it is not at all meaningful?).
58203 **
58204 ** By themselves, these optimizations work fine and provide a handy
58205 ** performance boost to bulk delete or insert operations. However, if
58206 ** a page is moved to the free-list and then reused within the same
58207 ** transaction, a problem comes up. If the page is not journalled when
58208 ** it is moved to the free-list and it is also not journalled when it
58209 ** is extracted from the free-list and reused, then the original data
58210 ** may be lost. In the event of a rollback, it may not be possible
58211 ** to restore the database to its original configuration.
58212 **
58213 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
58214 ** moved to become a free-list leaf page, the corresponding bit is
58215 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
58216 ** optimization 2 above is omitted if the corresponding bit is already
58217 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
58218 ** at the end of every transaction.
58219 */
58220 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
58221  int rc = SQLITE_OK;
58222  if( !pBt->pHasContent ){
58223  assert( pgno<=pBt->nPage );
58224  pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
58225  if( !pBt->pHasContent ){
58226  rc = SQLITE_NOMEM_BKPT;
58227  }
58228  }
58229  if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
58230  rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
58231  }
58232  return rc;
58233 }
58234 
58235 /*
58236 ** Query the BtShared.pHasContent vector.
58237 **
58238 ** This function is called when a free-list leaf page is removed from the
58239 ** free-list for reuse. It returns false if it is safe to retrieve the
58240 ** page from the pager layer with the 'no-content' flag set. True otherwise.
58241 */
58242 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
58243  Bitvec *p = pBt->pHasContent;
58244  return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
58245 }
58246 
58247 /*
58248 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
58249 ** invoked at the conclusion of each write-transaction.
58250 */
58251 static void btreeClearHasContent(BtShared *pBt){
58253  pBt->pHasContent = 0;
58254 }
58255 
58256 /*
58257 ** Release all of the apPage[] pages for a cursor.
58258 */
58260  int i;
58261  for(i=0; i<=pCur->iPage; i++){
58262  releasePage(pCur->apPage[i]);
58263  pCur->apPage[i] = 0;
58264  }
58265  pCur->iPage = -1;
58266 }
58267 
58268 /*
58269 ** The cursor passed as the only argument must point to a valid entry
58270 ** when this function is called (i.e. have eState==CURSOR_VALID). This
58271 ** function saves the current cursor key in variables pCur->nKey and
58272 ** pCur->pKey. SQLITE_OK is returned if successful or an SQLite error
58273 ** code otherwise.
58274 **
58275 ** If the cursor is open on an intkey table, then the integer key
58276 ** (the rowid) is stored in pCur->nKey and pCur->pKey is left set to
58277 ** NULL. If the cursor is open on a non-intkey table, then pCur->pKey is
58278 ** set to point to a malloced buffer pCur->nKey bytes in size containing
58279 ** the key.
58280 */
58281 static int saveCursorKey(BtCursor *pCur){
58282  int rc;
58283  assert( CURSOR_VALID==pCur->eState );
58284  assert( 0==pCur->pKey );
58285  assert( cursorHoldsMutex(pCur) );
58286 
58287  rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
58288  assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
58289 
58290  /* If this is an intKey table, then the above call to BtreeKeySize()
58291  ** stores the integer key in pCur->nKey. In this case this value is
58292  ** all that is required. Otherwise, if pCur is not open on an intKey
58293  ** table, then malloc space for and store the pCur->nKey bytes of key
58294  ** data. */
58295  if( 0==pCur->curIntKey ){
58296  void *pKey = sqlite3Malloc( pCur->nKey );
58297  if( pKey ){
58298  rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
58299  if( rc==SQLITE_OK ){
58300  pCur->pKey = pKey;
58301  }else{
58302  sqlite3_free(pKey);
58303  }
58304  }else{
58305  rc = SQLITE_NOMEM_BKPT;
58306  }
58307  }
58308  assert( !pCur->curIntKey || !pCur->pKey );
58309  return rc;
58310 }
58311 
58312 /*
58313 ** Save the current cursor position in the variables BtCursor.nKey
58314 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
58315 **
58316 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
58317 ** prior to calling this routine.
58318 */
58319 static int saveCursorPosition(BtCursor *pCur){
58320  int rc;
58321 
58322  assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
58323  assert( 0==pCur->pKey );
58324  assert( cursorHoldsMutex(pCur) );
58325 
58326  if( pCur->eState==CURSOR_SKIPNEXT ){
58327  pCur->eState = CURSOR_VALID;
58328  }else{
58329  pCur->skipNext = 0;
58330  }
58331 
58332  rc = saveCursorKey(pCur);
58333  if( rc==SQLITE_OK ){
58335  pCur->eState = CURSOR_REQUIRESEEK;
58336  }
58337 
58339  return rc;
58340 }
58341 
58342 /* Forward reference */
58344 
58345 /*
58346 ** Save the positions of all cursors (except pExcept) that are open on
58347 ** the table with root-page iRoot. "Saving the cursor position" means that
58348 ** the location in the btree is remembered in such a way that it can be
58349 ** moved back to the same spot after the btree has been modified. This
58350 ** routine is called just before cursor pExcept is used to modify the
58351 ** table, for example in BtreeDelete() or BtreeInsert().
58352 **
58353 ** If there are two or more cursors on the same btree, then all such
58354 ** cursors should have their BTCF_Multiple flag set. The btreeCursor()
58355 ** routine enforces that rule. This routine only needs to be called in
58356 ** the uncommon case when pExpect has the BTCF_Multiple flag set.
58357 **
58358 ** If pExpect!=NULL and if no other cursors are found on the same root-page,
58359 ** then the BTCF_Multiple flag on pExpect is cleared, to avoid another
58360 ** pointless call to this routine.
58361 **
58362 ** Implementation note: This routine merely checks to see if any cursors
58363 ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
58364 ** event that cursors are in need to being saved.
58365 */
58366 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
58367  BtCursor *p;
58368  assert( sqlite3_mutex_held(pBt->mutex) );
58369  assert( pExcept==0 || pExcept->pBt==pBt );
58370  for(p=pBt->pCursor; p; p=p->pNext){
58371  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
58372  }
58373  if( p ) return saveCursorsOnList(p, iRoot, pExcept);
58374  if( pExcept ) pExcept->curFlags &= ~BTCF_Multiple;
58375  return SQLITE_OK;
58376 }
58377 
58378 /* This helper routine to saveAllCursors does the actual work of saving
58379 ** the cursors if and when a cursor is found that actually requires saving.
58380 ** The common case is that no cursors need to be saved, so this routine is
58381 ** broken out from its caller to avoid unnecessary stack pointer movement.
58382 */
58384  BtCursor *p, /* The first cursor that needs saving */
58385  Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
58386  BtCursor *pExcept /* Do not save this cursor */
58387 ){
58388  do{
58389  if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
58390  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
58391  int rc = saveCursorPosition(p);
58392  if( SQLITE_OK!=rc ){
58393  return rc;
58394  }
58395  }else{
58396  testcase( p->iPage>0 );
58398  }
58399  }
58400  p = p->pNext;
58401  }while( p );
58402  return SQLITE_OK;
58403 }
58404 
58405 /*
58406 ** Clear the current cursor position.
58407 */
58409  assert( cursorHoldsMutex(pCur) );
58410  sqlite3_free(pCur->pKey);
58411  pCur->pKey = 0;
58412  pCur->eState = CURSOR_INVALID;
58413 }
58414 
58415 /*
58416 ** In this version of BtreeMoveto, pKey is a packed index record
58417 ** such as is generated by the OP_MakeRecord opcode. Unpack the
58418 ** record and then call BtreeMovetoUnpacked() to do the work.
58419 */
58420 static int btreeMoveto(
58421  BtCursor *pCur, /* Cursor open on the btree to be searched */
58422  const void *pKey, /* Packed key if the btree is an index */
58423  i64 nKey, /* Integer key for tables. Size of pKey for indices */
58424  int bias, /* Bias search to the high end */
58425  int *pRes /* Write search results here */
58426 ){
58427  int rc; /* Status code */
58428  UnpackedRecord *pIdxKey; /* Unpacked index key */
58429  char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
58430  char *pFree = 0;
58431 
58432  if( pKey ){
58433  assert( nKey==(i64)(int)nKey );
58435  pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
58436  );
58437  if( pIdxKey==0 ) return SQLITE_NOMEM_BKPT;
58438  sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
58439  if( pIdxKey->nField==0 ){
58440  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58441  return SQLITE_CORRUPT_BKPT;
58442  }
58443  }else{
58444  pIdxKey = 0;
58445  }
58446  rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
58447  if( pFree ){
58448  sqlite3DbFree(pCur->pKeyInfo->db, pFree);
58449  }
58450  return rc;
58451 }
58452 
58453 /*
58454 ** Restore the cursor to the position it was in (or as close to as possible)
58455 ** when saveCursorPosition() was called. Note that this call deletes the
58456 ** saved position info stored by saveCursorPosition(), so there can be
58457 ** at most one effective restoreCursorPosition() call after each
58458 ** saveCursorPosition().
58459 */
58461  int rc;
58462  int skipNext;
58463  assert( cursorOwnsBtShared(pCur) );
58464  assert( pCur->eState>=CURSOR_REQUIRESEEK );
58465  if( pCur->eState==CURSOR_FAULT ){
58466  return pCur->skipNext;
58467  }
58468  pCur->eState = CURSOR_INVALID;
58469  rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
58470  if( rc==SQLITE_OK ){
58471  sqlite3_free(pCur->pKey);
58472  pCur->pKey = 0;
58473  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
58474  pCur->skipNext |= skipNext;
58475  if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
58476  pCur->eState = CURSOR_SKIPNEXT;
58477  }
58478  }
58479  return rc;
58480 }
58481 
58482 #define restoreCursorPosition(p) \
58483  (p->eState>=CURSOR_REQUIRESEEK ? \
58484  btreeRestoreCursorPosition(p) : \
58485  SQLITE_OK)
58486 
58487 /*
58488 ** Determine whether or not a cursor has moved from the position where
58489 ** it was last placed, or has been invalidated for any other reason.
58490 ** Cursors can move when the row they are pointing at is deleted out
58491 ** from under them, for example. Cursor might also move if a btree
58492 ** is rebalanced.
58493 **
58494 ** Calling this routine with a NULL cursor pointer returns false.
58495 **
58496 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
58497 ** back to where it ought to be if this routine returns true.
58498 */
58500  return pCur->eState!=CURSOR_VALID;
58501 }
58502 
58503 /*
58504 ** This routine restores a cursor back to its original position after it
58505 ** has been moved by some outside activity (such as a btree rebalance or
58506 ** a row having been deleted out from under the cursor).
58507 **
58508 ** On success, the *pDifferentRow parameter is false if the cursor is left
58509 ** pointing at exactly the same row. *pDifferntRow is the row the cursor
58510 ** was pointing to has been deleted, forcing the cursor to point to some
58511 ** nearby row.
58512 **
58513 ** This routine should only be called for a cursor that just returned
58514 ** TRUE from sqlite3BtreeCursorHasMoved().
58515 */
58516 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
58517  int rc;
58518 
58519  assert( pCur!=0 );
58520  assert( pCur->eState!=CURSOR_VALID );
58521  rc = restoreCursorPosition(pCur);
58522  if( rc ){
58523  *pDifferentRow = 1;
58524  return rc;
58525  }
58526  if( pCur->eState!=CURSOR_VALID ){
58527  *pDifferentRow = 1;
58528  }else{
58529  assert( pCur->skipNext==0 );
58530  *pDifferentRow = 0;
58531  }
58532  return SQLITE_OK;
58533 }
58534 
58535 #ifdef SQLITE_ENABLE_CURSOR_HINTS
58536 /*
58537 ** Provide hints to the cursor. The particular hint given (and the type
58538 ** and number of the varargs parameters) is determined by the eHintType
58539 ** parameter. See the definitions of the BTREE_HINT_* macros for details.
58540 */
58541 SQLITE_PRIVATE void sqlite3BtreeCursorHint(BtCursor *pCur, int eHintType, ...){
58542  /* Used only by system that substitute their own storage engine */
58543 }
58544 #endif
58545 
58546 /*
58547 ** Provide flag hints to the cursor.
58548 */
58550  assert( x==BTREE_SEEK_EQ || x==BTREE_BULKLOAD || x==0 );
58551  pCur->hints = x;
58552 }
58553 
58554 
58555 #ifndef SQLITE_OMIT_AUTOVACUUM
58556 /*
58557 ** Given a page number of a regular database page, return the page
58558 ** number for the pointer-map page that contains the entry for the
58559 ** input page number.
58560 **
58561 ** Return 0 (not a valid page) for pgno==1 since there is
58562 ** no pointer map associated with page 1. The integrity_check logic
58563 ** requires that ptrmapPageno(*,1)!=1.
58564 */
58565 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
58566  int nPagesPerMapPage;
58567  Pgno iPtrMap, ret;
58568  assert( sqlite3_mutex_held(pBt->mutex) );
58569  if( pgno<2 ) return 0;
58570  nPagesPerMapPage = (pBt->usableSize/5)+1;
58571  iPtrMap = (pgno-2)/nPagesPerMapPage;
58572  ret = (iPtrMap*nPagesPerMapPage) + 2;
58573  if( ret==PENDING_BYTE_PAGE(pBt) ){
58574  ret++;
58575  }
58576  return ret;
58577 }
58578 
58579 /*
58580 ** Write an entry into the pointer map.
58581 **
58582 ** This routine updates the pointer map entry for page number 'key'
58583 ** so that it maps to type 'eType' and parent page number 'pgno'.
58584 **
58585 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
58586 ** a no-op. If an error occurs, the appropriate error code is written
58587 ** into *pRC.
58588 */
58589 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
58590  DbPage *pDbPage; /* The pointer map page */
58591  u8 *pPtrmap; /* The pointer map data */
58592  Pgno iPtrmap; /* The pointer map page number */
58593  int offset; /* Offset in pointer map page */
58594  int rc; /* Return code from subfunctions */
58595 
58596  if( *pRC ) return;
58597 
58598  assert( sqlite3_mutex_held(pBt->mutex) );
58599  /* The master-journal page number must never be used as a pointer map page */
58600  assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
58601 
58602  assert( pBt->autoVacuum );
58603  if( key==0 ){
58604  *pRC = SQLITE_CORRUPT_BKPT;
58605  return;
58606  }
58607  iPtrmap = PTRMAP_PAGENO(pBt, key);
58608  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
58609  if( rc!=SQLITE_OK ){
58610  *pRC = rc;
58611  return;
58612  }
58613  offset = PTRMAP_PTROFFSET(iPtrmap, key);
58614  if( offset<0 ){
58615  *pRC = SQLITE_CORRUPT_BKPT;
58616  goto ptrmap_exit;
58617  }
58618  assert( offset <= (int)pBt->usableSize-5 );
58619  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
58620 
58621  if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
58622  TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
58623  *pRC= rc = sqlite3PagerWrite(pDbPage);
58624  if( rc==SQLITE_OK ){
58625  pPtrmap[offset] = eType;
58626  put4byte(&pPtrmap[offset+1], parent);
58627  }
58628  }
58629 
58630 ptrmap_exit:
58631  sqlite3PagerUnref(pDbPage);
58632 }
58633 
58634 /*
58635 ** Read an entry from the pointer map.
58636 **
58637 ** This routine retrieves the pointer map entry for page 'key', writing
58638 ** the type and parent page number to *pEType and *pPgno respectively.
58639 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
58640 */
58641 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
58642  DbPage *pDbPage; /* The pointer map page */
58643  int iPtrmap; /* Pointer map page index */
58644  u8 *pPtrmap; /* Pointer map page data */
58645  int offset; /* Offset of entry in pointer map */
58646  int rc;
58647 
58648  assert( sqlite3_mutex_held(pBt->mutex) );
58649 
58650  iPtrmap = PTRMAP_PAGENO(pBt, key);
58651  rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage, 0);
58652  if( rc!=0 ){
58653  return rc;
58654  }
58655  pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
58656 
58657  offset = PTRMAP_PTROFFSET(iPtrmap, key);
58658  if( offset<0 ){
58659  sqlite3PagerUnref(pDbPage);
58660  return SQLITE_CORRUPT_BKPT;
58661  }
58662  assert( offset <= (int)pBt->usableSize-5 );
58663  assert( pEType!=0 );
58664  *pEType = pPtrmap[offset];
58665  if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
58666 
58667  sqlite3PagerUnref(pDbPage);
58668  if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
58669  return SQLITE_OK;
58670 }
58671 
58672 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
58673  #define ptrmapPut(w,x,y,z,rc)
58674  #define ptrmapGet(w,x,y,z) SQLITE_OK
58675  #define ptrmapPutOvflPtr(x, y, rc)
58676 #endif
58677 
58678 /*
58679 ** Given a btree page and a cell index (0 means the first cell on
58680 ** the page, 1 means the second cell, and so forth) return a pointer
58681 ** to the cell content.
58682 **
58683 ** findCellPastPtr() does the same except it skips past the initial
58684 ** 4-byte child pointer found on interior pages, if there is one.
58685 **
58686 ** This routine works only for pages that do not contain overflow cells.
58687 */
58688 #define findCell(P,I) \
58689  ((P)->aData + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
58690 #define findCellPastPtr(P,I) \
58691  ((P)->aDataOfst + ((P)->maskPage & get2byteAligned(&(P)->aCellIdx[2*(I)])))
58692 
58693 
58694 /*
58695 ** This is common tail processing for btreeParseCellPtr() and
58696 ** btreeParseCellPtrIndex() for the case when the cell does not fit entirely
58697 ** on a single B-tree page. Make necessary adjustments to the CellInfo
58698 ** structure.
58699 */
58701  MemPage *pPage, /* Page containing the cell */
58702  u8 *pCell, /* Pointer to the cell text. */
58703  CellInfo *pInfo /* Fill in this structure */
58704 ){
58705  /* If the payload will not fit completely on the local page, we have
58706  ** to decide how much to store locally and how much to spill onto
58707  ** overflow pages. The strategy is to minimize the amount of unused
58708  ** space on overflow pages while keeping the amount of local storage
58709  ** in between minLocal and maxLocal.
58710  **
58711  ** Warning: changing the way overflow payload is distributed in any
58712  ** way will result in an incompatible file format.
58713  */
58714  int minLocal; /* Minimum amount of payload held locally */
58715  int maxLocal; /* Maximum amount of payload held locally */
58716  int surplus; /* Overflow payload available for local storage */
58717 
58718  minLocal = pPage->minLocal;
58719  maxLocal = pPage->maxLocal;
58720  surplus = minLocal + (pInfo->nPayload - minLocal)%(pPage->pBt->usableSize-4);
58721  testcase( surplus==maxLocal );
58722  testcase( surplus==maxLocal+1 );
58723  if( surplus <= maxLocal ){
58724  pInfo->nLocal = (u16)surplus;
58725  }else{
58726  pInfo->nLocal = (u16)minLocal;
58727  }
58728  pInfo->nSize = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell) + 4;
58729 }
58730 
58731 /*
58732 ** The following routines are implementations of the MemPage.xParseCell()
58733 ** method.
58734 **
58735 ** Parse a cell content block and fill in the CellInfo structure.
58736 **
58737 ** btreeParseCellPtr() => table btree leaf nodes
58738 ** btreeParseCellNoPayload() => table btree internal nodes
58739 ** btreeParseCellPtrIndex() => index btree nodes
58740 **
58741 ** There is also a wrapper function btreeParseCell() that works for
58742 ** all MemPage types and that references the cell by index rather than
58743 ** by pointer.
58744 */
58746  MemPage *pPage, /* Page containing the cell */
58747  u8 *pCell, /* Pointer to the cell text. */
58748  CellInfo *pInfo /* Fill in this structure */
58749 ){
58750  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58751  assert( pPage->leaf==0 );
58752  assert( pPage->childPtrSize==4 );
58753 #ifndef SQLITE_DEBUG
58754  UNUSED_PARAMETER(pPage);
58755 #endif
58756  pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
58757  pInfo->nPayload = 0;
58758  pInfo->nLocal = 0;
58759  pInfo->pPayload = 0;
58760  return;
58761 }
58762 static void btreeParseCellPtr(
58763  MemPage *pPage, /* Page containing the cell */
58764  u8 *pCell, /* Pointer to the cell text. */
58765  CellInfo *pInfo /* Fill in this structure */
58766 ){
58767  u8 *pIter; /* For scanning through pCell */
58768  u32 nPayload; /* Number of bytes of cell payload */
58769  u64 iKey; /* Extracted Key value */
58770 
58771  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58772  assert( pPage->leaf==0 || pPage->leaf==1 );
58773  assert( pPage->intKeyLeaf );
58774  assert( pPage->childPtrSize==0 );
58775  pIter = pCell;
58776 
58777  /* The next block of code is equivalent to:
58778  **
58779  ** pIter += getVarint32(pIter, nPayload);
58780  **
58781  ** The code is inlined to avoid a function call.
58782  */
58783  nPayload = *pIter;
58784  if( nPayload>=0x80 ){
58785  u8 *pEnd = &pIter[8];
58786  nPayload &= 0x7f;
58787  do{
58788  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
58789  }while( (*pIter)>=0x80 && pIter<pEnd );
58790  }
58791  pIter++;
58792 
58793  /* The next block of code is equivalent to:
58794  **
58795  ** pIter += getVarint(pIter, (u64*)&pInfo->nKey);
58796  **
58797  ** The code is inlined to avoid a function call.
58798  */
58799  iKey = *pIter;
58800  if( iKey>=0x80 ){
58801  u8 *pEnd = &pIter[7];
58802  iKey &= 0x7f;
58803  while(1){
58804  iKey = (iKey<<7) | (*++pIter & 0x7f);
58805  if( (*pIter)<0x80 ) break;
58806  if( pIter>=pEnd ){
58807  iKey = (iKey<<8) | *++pIter;
58808  break;
58809  }
58810  }
58811  }
58812  pIter++;
58813 
58814  pInfo->nKey = *(i64*)&iKey;
58815  pInfo->nPayload = nPayload;
58816  pInfo->pPayload = pIter;
58817  testcase( nPayload==pPage->maxLocal );
58818  testcase( nPayload==pPage->maxLocal+1 );
58819  if( nPayload<=pPage->maxLocal ){
58820  /* This is the (easy) common case where the entire payload fits
58821  ** on the local page. No overflow is required.
58822  */
58823  pInfo->nSize = nPayload + (u16)(pIter - pCell);
58824  if( pInfo->nSize<4 ) pInfo->nSize = 4;
58825  pInfo->nLocal = (u16)nPayload;
58826  }else{
58827  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
58828  }
58829 }
58831  MemPage *pPage, /* Page containing the cell */
58832  u8 *pCell, /* Pointer to the cell text. */
58833  CellInfo *pInfo /* Fill in this structure */
58834 ){
58835  u8 *pIter; /* For scanning through pCell */
58836  u32 nPayload; /* Number of bytes of cell payload */
58837 
58838  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58839  assert( pPage->leaf==0 || pPage->leaf==1 );
58840  assert( pPage->intKeyLeaf==0 );
58841  pIter = pCell + pPage->childPtrSize;
58842  nPayload = *pIter;
58843  if( nPayload>=0x80 ){
58844  u8 *pEnd = &pIter[8];
58845  nPayload &= 0x7f;
58846  do{
58847  nPayload = (nPayload<<7) | (*++pIter & 0x7f);
58848  }while( *(pIter)>=0x80 && pIter<pEnd );
58849  }
58850  pIter++;
58851  pInfo->nKey = nPayload;
58852  pInfo->nPayload = nPayload;
58853  pInfo->pPayload = pIter;
58854  testcase( nPayload==pPage->maxLocal );
58855  testcase( nPayload==pPage->maxLocal+1 );
58856  if( nPayload<=pPage->maxLocal ){
58857  /* This is the (easy) common case where the entire payload fits
58858  ** on the local page. No overflow is required.
58859  */
58860  pInfo->nSize = nPayload + (u16)(pIter - pCell);
58861  if( pInfo->nSize<4 ) pInfo->nSize = 4;
58862  pInfo->nLocal = (u16)nPayload;
58863  }else{
58864  btreeParseCellAdjustSizeForOverflow(pPage, pCell, pInfo);
58865  }
58866 }
58867 static void btreeParseCell(
58868  MemPage *pPage, /* Page containing the cell */
58869  int iCell, /* The cell index. First cell is 0 */
58870  CellInfo *pInfo /* Fill in this structure */
58871 ){
58872  pPage->xParseCell(pPage, findCell(pPage, iCell), pInfo);
58873 }
58874 
58875 /*
58876 ** The following routines are implementations of the MemPage.xCellSize
58877 ** method.
58878 **
58879 ** Compute the total number of bytes that a Cell needs in the cell
58880 ** data area of the btree-page. The return number includes the cell
58881 ** data header and the local payload, but not any overflow page or
58882 ** the space used by the cell pointer.
58883 **
58884 ** cellSizePtrNoPayload() => table internal nodes
58885 ** cellSizePtr() => all index nodes & table leaf nodes
58886 */
58887 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
58888  u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
58889  u8 *pEnd; /* End mark for a varint */
58890  u32 nSize; /* Size value to return */
58891 
58892 #ifdef SQLITE_DEBUG
58893  /* The value returned by this function should always be the same as
58894  ** the (CellInfo.nSize) value found by doing a full parse of the
58895  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
58896  ** this function verifies that this invariant is not violated. */
58897  CellInfo debuginfo;
58898  pPage->xParseCell(pPage, pCell, &debuginfo);
58899 #endif
58900 
58901  nSize = *pIter;
58902  if( nSize>=0x80 ){
58903  pEnd = &pIter[8];
58904  nSize &= 0x7f;
58905  do{
58906  nSize = (nSize<<7) | (*++pIter & 0x7f);
58907  }while( *(pIter)>=0x80 && pIter<pEnd );
58908  }
58909  pIter++;
58910  if( pPage->intKey ){
58911  /* pIter now points at the 64-bit integer key value, a variable length
58912  ** integer. The following block moves pIter to point at the first byte
58913  ** past the end of the key value. */
58914  pEnd = &pIter[9];
58915  while( (*pIter++)&0x80 && pIter<pEnd );
58916  }
58917  testcase( nSize==pPage->maxLocal );
58918  testcase( nSize==pPage->maxLocal+1 );
58919  if( nSize<=pPage->maxLocal ){
58920  nSize += (u32)(pIter - pCell);
58921  if( nSize<4 ) nSize = 4;
58922  }else{
58923  int minLocal = pPage->minLocal;
58924  nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
58925  testcase( nSize==pPage->maxLocal );
58926  testcase( nSize==pPage->maxLocal+1 );
58927  if( nSize>pPage->maxLocal ){
58928  nSize = minLocal;
58929  }
58930  nSize += 4 + (u16)(pIter - pCell);
58931  }
58932  assert( nSize==debuginfo.nSize || CORRUPT_DB );
58933  return (u16)nSize;
58934 }
58935 static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell){
58936  u8 *pIter = pCell + 4; /* For looping over bytes of pCell */
58937  u8 *pEnd; /* End mark for a varint */
58938 
58939 #ifdef SQLITE_DEBUG
58940  /* The value returned by this function should always be the same as
58941  ** the (CellInfo.nSize) value found by doing a full parse of the
58942  ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
58943  ** this function verifies that this invariant is not violated. */
58944  CellInfo debuginfo;
58945  pPage->xParseCell(pPage, pCell, &debuginfo);
58946 #else
58947  UNUSED_PARAMETER(pPage);
58948 #endif
58949 
58950  assert( pPage->childPtrSize==4 );
58951  pEnd = pIter + 9;
58952  while( (*pIter++)&0x80 && pIter<pEnd );
58953  assert( debuginfo.nSize==(u16)(pIter - pCell) || CORRUPT_DB );
58954  return (u16)(pIter - pCell);
58955 }
58956 
58957 
58958 #ifdef SQLITE_DEBUG
58959 /* This variation on cellSizePtr() is used inside of assert() statements
58960 ** only. */
58961 static u16 cellSize(MemPage *pPage, int iCell){
58962  return pPage->xCellSize(pPage, findCell(pPage, iCell));
58963 }
58964 #endif
58965 
58966 #ifndef SQLITE_OMIT_AUTOVACUUM
58967 /*
58968 ** If the cell pCell, part of page pPage contains a pointer
58969 ** to an overflow page, insert an entry into the pointer-map
58970 ** for the overflow page.
58971 */
58972 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
58973  CellInfo info;
58974  if( *pRC ) return;
58975  assert( pCell!=0 );
58976  pPage->xParseCell(pPage, pCell, &info);
58977  if( info.nLocal<info.nPayload ){
58978  Pgno ovfl = get4byte(&pCell[info.nSize-4]);
58979  ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
58980  }
58981 }
58982 #endif
58983 
58984 
58985 /*
58986 ** Defragment the page given. All Cells are moved to the
58987 ** end of the page and all free space is collected into one
58988 ** big FreeBlk that occurs in between the header and cell
58989 ** pointer array and the cell content area.
58990 **
58991 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
58992 ** b-tree page so that there are no freeblocks or fragment bytes, all
58993 ** unused bytes are contained in the unallocated space region, and all
58994 ** cells are packed tightly at the end of the page.
58995 */
58996 static int defragmentPage(MemPage *pPage){
58997  int i; /* Loop counter */
58998  int pc; /* Address of the i-th cell */
58999  int hdr; /* Offset to the page header */
59000  int size; /* Size of a cell */
59001  int usableSize; /* Number of usable bytes on a page */
59002  int cellOffset; /* Offset to the cell pointer array */
59003  int cbrk; /* Offset to the cell content area */
59004  int nCell; /* Number of cells on the page */
59005  unsigned char *data; /* The page data */
59006  unsigned char *temp; /* Temp area for cell content */
59007  unsigned char *src; /* Source of content */
59008  int iCellFirst; /* First allowable cell index */
59009  int iCellLast; /* Last possible cell index */
59010 
59011 
59012  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59013  assert( pPage->pBt!=0 );
59014  assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
59015  assert( pPage->nOverflow==0 );
59016  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59017  temp = 0;
59018  src = data = pPage->aData;
59019  hdr = pPage->hdrOffset;
59020  cellOffset = pPage->cellOffset;
59021  nCell = pPage->nCell;
59022  assert( nCell==get2byte(&data[hdr+3]) );
59023  usableSize = pPage->pBt->usableSize;
59024  cbrk = usableSize;
59025  iCellFirst = cellOffset + 2*nCell;
59026  iCellLast = usableSize - 4;
59027  for(i=0; i<nCell; i++){
59028  u8 *pAddr; /* The i-th cell pointer */
59029  pAddr = &data[cellOffset + i*2];
59030  pc = get2byte(pAddr);
59031  testcase( pc==iCellFirst );
59032  testcase( pc==iCellLast );
59033  /* These conditions have already been verified in btreeInitPage()
59034  ** if PRAGMA cell_size_check=ON.
59035  */
59036  if( pc<iCellFirst || pc>iCellLast ){
59037  return SQLITE_CORRUPT_BKPT;
59038  }
59039  assert( pc>=iCellFirst && pc<=iCellLast );
59040  size = pPage->xCellSize(pPage, &src[pc]);
59041  cbrk -= size;
59042  if( cbrk<iCellFirst || pc+size>usableSize ){
59043  return SQLITE_CORRUPT_BKPT;
59044  }
59045  assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
59046  testcase( cbrk+size==usableSize );
59047  testcase( pc+size==usableSize );
59048  put2byte(pAddr, cbrk);
59049  if( temp==0 ){
59050  int x;
59051  if( cbrk==pc ) continue;
59052  temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
59053  x = get2byte(&data[hdr+5]);
59054  memcpy(&temp[x], &data[x], (cbrk+size) - x);
59055  src = temp;
59056  }
59057  memcpy(&data[cbrk], &src[pc], size);
59058  }
59059  assert( cbrk>=iCellFirst );
59060  put2byte(&data[hdr+5], cbrk);
59061  data[hdr+1] = 0;
59062  data[hdr+2] = 0;
59063  data[hdr+7] = 0;
59064  memset(&data[iCellFirst], 0, cbrk-iCellFirst);
59065  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59066  if( cbrk-iCellFirst!=pPage->nFree ){
59067  return SQLITE_CORRUPT_BKPT;
59068  }
59069  return SQLITE_OK;
59070 }
59071 
59072 /*
59073 ** Search the free-list on page pPg for space to store a cell nByte bytes in
59074 ** size. If one can be found, return a pointer to the space and remove it
59075 ** from the free-list.
59076 **
59077 ** If no suitable space can be found on the free-list, return NULL.
59078 **
59079 ** This function may detect corruption within pPg. If corruption is
59080 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
59081 **
59082 ** Slots on the free list that are between 1 and 3 bytes larger than nByte
59083 ** will be ignored if adding the extra space to the fragmentation count
59084 ** causes the fragmentation count to exceed 60.
59085 */
59086 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc){
59087  const int hdr = pPg->hdrOffset;
59088  u8 * const aData = pPg->aData;
59089  int iAddr = hdr + 1;
59090  int pc = get2byte(&aData[iAddr]);
59091  int x;
59092  int usableSize = pPg->pBt->usableSize;
59093 
59094  assert( pc>0 );
59095  do{
59096  int size; /* Size of the free slot */
59097  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
59098  ** increasing offset. */
59099  if( pc>usableSize-4 || pc<iAddr+4 ){
59100  *pRc = SQLITE_CORRUPT_BKPT;
59101  return 0;
59102  }
59103  /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
59104  ** freeblock form a big-endian integer which is the size of the freeblock
59105  ** in bytes, including the 4-byte header. */
59106  size = get2byte(&aData[pc+2]);
59107  if( (x = size - nByte)>=0 ){
59108  testcase( x==4 );
59109  testcase( x==3 );
59110  if( pc < pPg->cellOffset+2*pPg->nCell || size+pc > usableSize ){
59111  *pRc = SQLITE_CORRUPT_BKPT;
59112  return 0;
59113  }else if( x<4 ){
59114  /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
59115  ** number of bytes in fragments may not exceed 60. */
59116  if( aData[hdr+7]>57 ) return 0;
59117 
59118  /* Remove the slot from the free-list. Update the number of
59119  ** fragmented bytes within the page. */
59120  memcpy(&aData[iAddr], &aData[pc], 2);
59121  aData[hdr+7] += (u8)x;
59122  }else{
59123  /* The slot remains on the free-list. Reduce its size to account
59124  ** for the portion used by the new allocation. */
59125  put2byte(&aData[pc+2], x);
59126  }
59127  return &aData[pc + x];
59128  }
59129  iAddr = pc;
59130  pc = get2byte(&aData[pc]);
59131  }while( pc );
59132 
59133  return 0;
59134 }
59135 
59136 /*
59137 ** Allocate nByte bytes of space from within the B-Tree page passed
59138 ** as the first argument. Write into *pIdx the index into pPage->aData[]
59139 ** of the first byte of allocated space. Return either SQLITE_OK or
59140 ** an error code (usually SQLITE_CORRUPT).
59141 **
59142 ** The caller guarantees that there is sufficient space to make the
59143 ** allocation. This routine might need to defragment in order to bring
59144 ** all the space together, however. This routine will avoid using
59145 ** the first two bytes past the cell pointer area since presumably this
59146 ** allocation is being made in order to insert a new cell, so we will
59147 ** also end up needing a new cell pointer.
59148 */
59149 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
59150  const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
59151  u8 * const data = pPage->aData; /* Local cache of pPage->aData */
59152  int top; /* First byte of cell content area */
59153  int rc = SQLITE_OK; /* Integer return code */
59154  int gap; /* First byte of gap between cell pointers and cell content */
59155 
59156  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59157  assert( pPage->pBt );
59158  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59159  assert( nByte>=0 ); /* Minimum cell size is 4 */
59160  assert( pPage->nFree>=nByte );
59161  assert( pPage->nOverflow==0 );
59162  assert( nByte < (int)(pPage->pBt->usableSize-8) );
59163 
59164  assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
59165  gap = pPage->cellOffset + 2*pPage->nCell;
59166  assert( gap<=65536 );
59167  /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
59168  ** and the reserved space is zero (the usual value for reserved space)
59169  ** then the cell content offset of an empty page wants to be 65536.
59170  ** However, that integer is too large to be stored in a 2-byte unsigned
59171  ** integer, so a value of 0 is used in its place. */
59172  top = get2byte(&data[hdr+5]);
59173  assert( top<=(int)pPage->pBt->usableSize ); /* Prevent by getAndInitPage() */
59174  if( gap>top ){
59175  if( top==0 && pPage->pBt->usableSize==65536 ){
59176  top = 65536;
59177  }else{
59178  return SQLITE_CORRUPT_BKPT;
59179  }
59180  }
59181 
59182  /* If there is enough space between gap and top for one more cell pointer
59183  ** array entry offset, and if the freelist is not empty, then search the
59184  ** freelist looking for a free slot big enough to satisfy the request.
59185  */
59186  testcase( gap+2==top );
59187  testcase( gap+1==top );
59188  testcase( gap==top );
59189  if( (data[hdr+2] || data[hdr+1]) && gap+2<=top ){
59190  u8 *pSpace = pageFindSlot(pPage, nByte, &rc);
59191  if( pSpace ){
59192  assert( pSpace>=data && (pSpace - data)<65536 );
59193  *pIdx = (int)(pSpace - data);
59194  return SQLITE_OK;
59195  }else if( rc ){
59196  return rc;
59197  }
59198  }
59199 
59200  /* The request could not be fulfilled using a freelist slot. Check
59201  ** to see if defragmentation is necessary.
59202  */
59203  testcase( gap+2+nByte==top );
59204  if( gap+2+nByte>top ){
59205  assert( pPage->nCell>0 || CORRUPT_DB );
59206  rc = defragmentPage(pPage);
59207  if( rc ) return rc;
59208  top = get2byteNotZero(&data[hdr+5]);
59209  assert( gap+nByte<=top );
59210  }
59211 
59212 
59213  /* Allocate memory from the gap in between the cell pointer array
59214  ** and the cell content area. The btreeInitPage() call has already
59215  ** validated the freelist. Given that the freelist is valid, there
59216  ** is no way that the allocation can extend off the end of the page.
59217  ** The assert() below verifies the previous sentence.
59218  */
59219  top -= nByte;
59220  put2byte(&data[hdr+5], top);
59221  assert( top+nByte <= (int)pPage->pBt->usableSize );
59222  *pIdx = top;
59223  return SQLITE_OK;
59224 }
59225 
59226 /*
59227 ** Return a section of the pPage->aData to the freelist.
59228 ** The first byte of the new free block is pPage->aData[iStart]
59229 ** and the size of the block is iSize bytes.
59230 **
59231 ** Adjacent freeblocks are coalesced.
59232 **
59233 ** Note that even though the freeblock list was checked by btreeInitPage(),
59234 ** that routine will not detect overlap between cells or freeblocks. Nor
59235 ** does it detect cells or freeblocks that encrouch into the reserved bytes
59236 ** at the end of the page. So do additional corruption checks inside this
59237 ** routine and return SQLITE_CORRUPT if any problems are found.
59238 */
59239 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
59240  u16 iPtr; /* Address of ptr to next freeblock */
59241  u16 iFreeBlk; /* Address of the next freeblock */
59242  u8 hdr; /* Page header size. 0 or 100 */
59243  u8 nFrag = 0; /* Reduction in fragmentation */
59244  u16 iOrigSize = iSize; /* Original value of iSize */
59245  u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
59246  u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
59247  unsigned char *data = pPage->aData; /* Page content */
59248 
59249  assert( pPage->pBt!=0 );
59250  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59251  assert( CORRUPT_DB || iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
59252  assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
59253  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59254  assert( iSize>=4 ); /* Minimum cell size is 4 */
59255  assert( iStart<=iLast );
59256 
59257  /* Overwrite deleted information with zeros when the secure_delete
59258  ** option is enabled */
59259  if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
59260  memset(&data[iStart], 0, iSize);
59261  }
59262 
59263  /* The list of freeblocks must be in ascending order. Find the
59264  ** spot on the list where iStart should be inserted.
59265  */
59266  hdr = pPage->hdrOffset;
59267  iPtr = hdr + 1;
59268  if( data[iPtr+1]==0 && data[iPtr]==0 ){
59269  iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
59270  }else{
59271  while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
59272  if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
59273  iPtr = iFreeBlk;
59274  }
59275  if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
59276  assert( iFreeBlk>iPtr || iFreeBlk==0 );
59277 
59278  /* At this point:
59279  ** iFreeBlk: First freeblock after iStart, or zero if none
59280  ** iPtr: The address of a pointer to iFreeBlk
59281  **
59282  ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
59283  */
59284  if( iFreeBlk && iEnd+3>=iFreeBlk ){
59285  nFrag = iFreeBlk - iEnd;
59286  if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
59287  iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
59288  if( iEnd > pPage->pBt->usableSize ) return SQLITE_CORRUPT_BKPT;
59289  iSize = iEnd - iStart;
59290  iFreeBlk = get2byte(&data[iFreeBlk]);
59291  }
59292 
59293  /* If iPtr is another freeblock (that is, if iPtr is not the freelist
59294  ** pointer in the page header) then check to see if iStart should be
59295  ** coalesced onto the end of iPtr.
59296  */
59297  if( iPtr>hdr+1 ){
59298  int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
59299  if( iPtrEnd+3>=iStart ){
59300  if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
59301  nFrag += iStart - iPtrEnd;
59302  iSize = iEnd - iPtr;
59303  iStart = iPtr;
59304  }
59305  }
59306  if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
59307  data[hdr+7] -= nFrag;
59308  }
59309  if( iStart==get2byte(&data[hdr+5]) ){
59310  /* The new freeblock is at the beginning of the cell content area,
59311  ** so just extend the cell content area rather than create another
59312  ** freelist entry */
59313  if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
59314  put2byte(&data[hdr+1], iFreeBlk);
59315  put2byte(&data[hdr+5], iEnd);
59316  }else{
59317  /* Insert the new freeblock into the freelist */
59318  put2byte(&data[iPtr], iStart);
59319  put2byte(&data[iStart], iFreeBlk);
59320  put2byte(&data[iStart+2], iSize);
59321  }
59322  pPage->nFree += iOrigSize;
59323  return SQLITE_OK;
59324 }
59325 
59326 /*
59327 ** Decode the flags byte (the first byte of the header) for a page
59328 ** and initialize fields of the MemPage structure accordingly.
59329 **
59330 ** Only the following combinations are supported. Anything different
59331 ** indicates a corrupt database files:
59332 **
59333 ** PTF_ZERODATA
59334 ** PTF_ZERODATA | PTF_LEAF
59335 ** PTF_LEAFDATA | PTF_INTKEY
59336 ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
59337 */
59338 static int decodeFlags(MemPage *pPage, int flagByte){
59339  BtShared *pBt; /* A copy of pPage->pBt */
59340 
59341  assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
59342  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59343  pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
59344  flagByte &= ~PTF_LEAF;
59345  pPage->childPtrSize = 4-4*pPage->leaf;
59346  pPage->xCellSize = cellSizePtr;
59347  pBt = pPage->pBt;
59348  if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
59349  /* EVIDENCE-OF: R-07291-35328 A value of 5 (0x05) means the page is an
59350  ** interior table b-tree page. */
59351  assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
59352  /* EVIDENCE-OF: R-26900-09176 A value of 13 (0x0d) means the page is a
59353  ** leaf table b-tree page. */
59355  pPage->intKey = 1;
59356  if( pPage->leaf ){
59357  pPage->intKeyLeaf = 1;
59358  pPage->xParseCell = btreeParseCellPtr;
59359  }else{
59360  pPage->intKeyLeaf = 0;
59363  }
59364  pPage->maxLocal = pBt->maxLeaf;
59365  pPage->minLocal = pBt->minLeaf;
59366  }else if( flagByte==PTF_ZERODATA ){
59367  /* EVIDENCE-OF: R-43316-37308 A value of 2 (0x02) means the page is an
59368  ** interior index b-tree page. */
59369  assert( (PTF_ZERODATA)==2 );
59370  /* EVIDENCE-OF: R-59615-42828 A value of 10 (0x0a) means the page is a
59371  ** leaf index b-tree page. */
59372  assert( (PTF_ZERODATA|PTF_LEAF)==10 );
59373  pPage->intKey = 0;
59374  pPage->intKeyLeaf = 0;
59376  pPage->maxLocal = pBt->maxLocal;
59377  pPage->minLocal = pBt->minLocal;
59378  }else{
59379  /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
59380  ** an error. */
59381  return SQLITE_CORRUPT_BKPT;
59382  }
59383  pPage->max1bytePayload = pBt->max1bytePayload;
59384  return SQLITE_OK;
59385 }
59386 
59387 /*
59388 ** Initialize the auxiliary information for a disk block.
59389 **
59390 ** Return SQLITE_OK on success. If we see that the page does
59391 ** not contain a well-formed database page, then return
59392 ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
59393 ** guarantee that the page is well-formed. It only shows that
59394 ** we failed to detect any corruption.
59395 */
59396 static int btreeInitPage(MemPage *pPage){
59397 
59398  assert( pPage->pBt!=0 );
59399  assert( pPage->pBt->db!=0 );
59400  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59401  assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
59402  assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
59403  assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
59404 
59405  if( !pPage->isInit ){
59406  u16 pc; /* Address of a freeblock within pPage->aData[] */
59407  u8 hdr; /* Offset to beginning of page header */
59408  u8 *data; /* Equal to pPage->aData */
59409  BtShared *pBt; /* The main btree structure */
59410  int usableSize; /* Amount of usable space on each page */
59411  u16 cellOffset; /* Offset from start of page to first cell pointer */
59412  int nFree; /* Number of unused bytes on the page */
59413  int top; /* First byte of the cell content area */
59414  int iCellFirst; /* First allowable cell or freeblock offset */
59415  int iCellLast; /* Last possible cell or freeblock offset */
59416 
59417  pBt = pPage->pBt;
59418 
59419  hdr = pPage->hdrOffset;
59420  data = pPage->aData;
59421  /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
59422  ** the b-tree page type. */
59423  if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
59424  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
59425  pPage->maskPage = (u16)(pBt->pageSize - 1);
59426  pPage->nOverflow = 0;
59427  usableSize = pBt->usableSize;
59428  pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
59429  pPage->aDataEnd = &data[usableSize];
59430  pPage->aCellIdx = &data[cellOffset];
59431  pPage->aDataOfst = &data[pPage->childPtrSize];
59432  /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
59433  ** the start of the cell content area. A zero value for this integer is
59434  ** interpreted as 65536. */
59435  top = get2byteNotZero(&data[hdr+5]);
59436  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
59437  ** number of cells on the page. */
59438  pPage->nCell = get2byte(&data[hdr+3]);
59439  if( pPage->nCell>MX_CELL(pBt) ){
59440  /* To many cells for a single page. The page must be corrupt */
59441  return SQLITE_CORRUPT_BKPT;
59442  }
59443  testcase( pPage->nCell==MX_CELL(pBt) );
59444  /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
59445  ** possible for a root page of a table that contains no rows) then the
59446  ** offset to the cell content area will equal the page size minus the
59447  ** bytes of reserved space. */
59448  assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
59449 
59450  /* A malformed database page might cause us to read past the end
59451  ** of page when parsing a cell.
59452  **
59453  ** The following block of code checks early to see if a cell extends
59454  ** past the end of a page boundary and causes SQLITE_CORRUPT to be
59455  ** returned if it does.
59456  */
59457  iCellFirst = cellOffset + 2*pPage->nCell;
59458  iCellLast = usableSize - 4;
59459  if( pBt->db->flags & SQLITE_CellSizeCk ){
59460  int i; /* Index into the cell pointer array */
59461  int sz; /* Size of a cell */
59462 
59463  if( !pPage->leaf ) iCellLast--;
59464  for(i=0; i<pPage->nCell; i++){
59465  pc = get2byteAligned(&data[cellOffset+i*2]);
59466  testcase( pc==iCellFirst );
59467  testcase( pc==iCellLast );
59468  if( pc<iCellFirst || pc>iCellLast ){
59469  return SQLITE_CORRUPT_BKPT;
59470  }
59471  sz = pPage->xCellSize(pPage, &data[pc]);
59472  testcase( pc+sz==usableSize );
59473  if( pc+sz>usableSize ){
59474  return SQLITE_CORRUPT_BKPT;
59475  }
59476  }
59477  if( !pPage->leaf ) iCellLast++;
59478  }
59479 
59480  /* Compute the total free space on the page
59481  ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
59482  ** start of the first freeblock on the page, or is zero if there are no
59483  ** freeblocks. */
59484  pc = get2byte(&data[hdr+1]);
59485  nFree = data[hdr+7] + top; /* Init nFree to non-freeblock free space */
59486  while( pc>0 ){
59487  u16 next, size;
59488  if( pc<iCellFirst || pc>iCellLast ){
59489  /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
59490  ** always be at least one cell before the first freeblock.
59491  **
59492  ** Or, the freeblock is off the end of the page
59493  */
59494  return SQLITE_CORRUPT_BKPT;
59495  }
59496  next = get2byte(&data[pc]);
59497  size = get2byte(&data[pc+2]);
59498  if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
59499  /* Free blocks must be in ascending order. And the last byte of
59500  ** the free-block must lie on the database page. */
59501  return SQLITE_CORRUPT_BKPT;
59502  }
59503  nFree = nFree + size;
59504  pc = next;
59505  }
59506 
59507  /* At this point, nFree contains the sum of the offset to the start
59508  ** of the cell-content area plus the number of free bytes within
59509  ** the cell-content area. If this is greater than the usable-size
59510  ** of the page, then the page must be corrupted. This check also
59511  ** serves to verify that the offset to the start of the cell-content
59512  ** area, according to the page header, lies within the page.
59513  */
59514  if( nFree>usableSize ){
59515  return SQLITE_CORRUPT_BKPT;
59516  }
59517  pPage->nFree = (u16)(nFree - iCellFirst);
59518  pPage->isInit = 1;
59519  }
59520  return SQLITE_OK;
59521 }
59522 
59523 /*
59524 ** Set up a raw page so that it looks like a database page holding
59525 ** no entries.
59526 */
59527 static void zeroPage(MemPage *pPage, int flags){
59528  unsigned char *data = pPage->aData;
59529  BtShared *pBt = pPage->pBt;
59530  u8 hdr = pPage->hdrOffset;
59531  u16 first;
59532 
59533  assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
59534  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
59535  assert( sqlite3PagerGetData(pPage->pDbPage) == data );
59536  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59537  assert( sqlite3_mutex_held(pBt->mutex) );
59538  if( pBt->btsFlags & BTS_SECURE_DELETE ){
59539  memset(&data[hdr], 0, pBt->usableSize - hdr);
59540  }
59541  data[hdr] = (char)flags;
59542  first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
59543  memset(&data[hdr+1], 0, 4);
59544  data[hdr+7] = 0;
59545  put2byte(&data[hdr+5], pBt->usableSize);
59546  pPage->nFree = (u16)(pBt->usableSize - first);
59547  decodeFlags(pPage, flags);
59548  pPage->cellOffset = first;
59549  pPage->aDataEnd = &data[pBt->usableSize];
59550  pPage->aCellIdx = &data[first];
59551  pPage->aDataOfst = &data[pPage->childPtrSize];
59552  pPage->nOverflow = 0;
59553  assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
59554  pPage->maskPage = (u16)(pBt->pageSize - 1);
59555  pPage->nCell = 0;
59556  pPage->isInit = 1;
59557 }
59558 
59559 
59560 /*
59561 ** Convert a DbPage obtained from the pager into a MemPage used by
59562 ** the btree layer.
59563 */
59564 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
59565  MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
59566  if( pgno!=pPage->pgno ){
59567  pPage->aData = sqlite3PagerGetData(pDbPage);
59568  pPage->pDbPage = pDbPage;
59569  pPage->pBt = pBt;
59570  pPage->pgno = pgno;
59571  pPage->hdrOffset = pgno==1 ? 100 : 0;
59572  }
59573  assert( pPage->aData==sqlite3PagerGetData(pDbPage) );
59574  return pPage;
59575 }
59576 
59577 /*
59578 ** Get a page from the pager. Initialize the MemPage.pBt and
59579 ** MemPage.aData elements if needed. See also: btreeGetUnusedPage().
59580 **
59581 ** If the PAGER_GET_NOCONTENT flag is set, it means that we do not care
59582 ** about the content of the page at this time. So do not go to the disk
59583 ** to fetch the content. Just fill in the content with zeros for now.
59584 ** If in the future we call sqlite3PagerWrite() on this page, that
59585 ** means we have started to be concerned about content and the disk
59586 ** read should occur at that point.
59587 */
59588 static int btreeGetPage(
59589  BtShared *pBt, /* The btree */
59590  Pgno pgno, /* Number of the page to fetch */
59591  MemPage **ppPage, /* Return the page in this parameter */
59592  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
59593 ){
59594  int rc;
59595  DbPage *pDbPage;
59596 
59597  assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
59598  assert( sqlite3_mutex_held(pBt->mutex) );
59599  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
59600  if( rc ) return rc;
59601  *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
59602  return SQLITE_OK;
59603 }
59604 
59605 /*
59606 ** Retrieve a page from the pager cache. If the requested page is not
59607 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
59608 ** MemPage.aData elements if needed.
59609 */
59610 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
59611  DbPage *pDbPage;
59612  assert( sqlite3_mutex_held(pBt->mutex) );
59613  pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
59614  if( pDbPage ){
59615  return btreePageFromDbPage(pDbPage, pgno, pBt);
59616  }
59617  return 0;
59618 }
59619 
59620 /*
59621 ** Return the size of the database file in pages. If there is any kind of
59622 ** error, return ((unsigned int)-1).
59623 */
59624 static Pgno btreePagecount(BtShared *pBt){
59625  return pBt->nPage;
59626 }
59628  assert( sqlite3BtreeHoldsMutex(p) );
59629  assert( ((p->pBt->nPage)&0x8000000)==0 );
59630  return btreePagecount(p->pBt);
59631 }
59632 
59633 /*
59634 ** Get a page from the pager and initialize it.
59635 **
59636 ** If pCur!=0 then the page is being fetched as part of a moveToChild()
59637 ** call. Do additional sanity checking on the page in this case.
59638 ** And if the fetch fails, this routine must decrement pCur->iPage.
59639 **
59640 ** The page is fetched as read-write unless pCur is not NULL and is
59641 ** a read-only cursor.
59642 **
59643 ** If an error occurs, then *ppPage is undefined. It
59644 ** may remain unchanged, or it may be set to an invalid value.
59645 */
59646 static int getAndInitPage(
59647  BtShared *pBt, /* The database file */
59648  Pgno pgno, /* Number of the page to get */
59649  MemPage **ppPage, /* Write the page pointer here */
59650  BtCursor *pCur, /* Cursor to receive the page, or NULL */
59651  int bReadOnly /* True for a read-only page */
59652 ){
59653  int rc;
59654  DbPage *pDbPage;
59655  assert( sqlite3_mutex_held(pBt->mutex) );
59656  assert( pCur==0 || ppPage==&pCur->apPage[pCur->iPage] );
59657  assert( pCur==0 || bReadOnly==pCur->curPagerFlags );
59658  assert( pCur==0 || pCur->iPage>0 );
59659 
59660  if( pgno>btreePagecount(pBt) ){
59661  rc = SQLITE_CORRUPT_BKPT;
59662  goto getAndInitPage_error;
59663  }
59664  rc = sqlite3PagerGet(pBt->pPager, pgno, (DbPage**)&pDbPage, bReadOnly);
59665  if( rc ){
59666  goto getAndInitPage_error;
59667  }
59668  *ppPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
59669  if( (*ppPage)->isInit==0 ){
59670  btreePageFromDbPage(pDbPage, pgno, pBt);
59671  rc = btreeInitPage(*ppPage);
59672  if( rc!=SQLITE_OK ){
59673  releasePage(*ppPage);
59674  goto getAndInitPage_error;
59675  }
59676  }
59677  assert( (*ppPage)->pgno==pgno );
59678  assert( (*ppPage)->aData==sqlite3PagerGetData(pDbPage) );
59679 
59680  /* If obtaining a child page for a cursor, we must verify that the page is
59681  ** compatible with the root page. */
59682  if( pCur && ((*ppPage)->nCell<1 || (*ppPage)->intKey!=pCur->curIntKey) ){
59683  rc = SQLITE_CORRUPT_BKPT;
59684  releasePage(*ppPage);
59685  goto getAndInitPage_error;
59686  }
59687  return SQLITE_OK;
59688 
59689 getAndInitPage_error:
59690  if( pCur ) pCur->iPage--;
59691  testcase( pgno==0 );
59692  assert( pgno!=0 || rc==SQLITE_CORRUPT );
59693  return rc;
59694 }
59695 
59696 /*
59697 ** Release a MemPage. This should be called once for each prior
59698 ** call to btreeGetPage.
59699 */
59700 static void releasePageNotNull(MemPage *pPage){
59701  assert( pPage->aData );
59702  assert( pPage->pBt );
59703  assert( pPage->pDbPage!=0 );
59704  assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
59705  assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
59706  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59708 }
59709 static void releasePage(MemPage *pPage){
59710  if( pPage ) releasePageNotNull(pPage);
59711 }
59712 
59713 /*
59714 ** Get an unused page.
59715 **
59716 ** This works just like btreeGetPage() with the addition:
59717 **
59718 ** * If the page is already in use for some other purpose, immediately
59719 ** release it and return an SQLITE_CURRUPT error.
59720 ** * Make sure the isInit flag is clear
59721 */
59723  BtShared *pBt, /* The btree */
59724  Pgno pgno, /* Number of the page to fetch */
59725  MemPage **ppPage, /* Return the page in this parameter */
59726  int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
59727 ){
59728  int rc = btreeGetPage(pBt, pgno, ppPage, flags);
59729  if( rc==SQLITE_OK ){
59730  if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
59731  releasePage(*ppPage);
59732  *ppPage = 0;
59733  return SQLITE_CORRUPT_BKPT;
59734  }
59735  (*ppPage)->isInit = 0;
59736  }else{
59737  *ppPage = 0;
59738  }
59739  return rc;
59740 }
59741 
59742 
59743 /*
59744 ** During a rollback, when the pager reloads information into the cache
59745 ** so that the cache is restored to its original state at the start of
59746 ** the transaction, for each page restored this routine is called.
59747 **
59748 ** This routine needs to reset the extra data section at the end of the
59749 ** page to agree with the restored data.
59750 */
59751 static void pageReinit(DbPage *pData){
59752  MemPage *pPage;
59753  pPage = (MemPage *)sqlite3PagerGetExtra(pData);
59754  assert( sqlite3PagerPageRefcount(pData)>0 );
59755  if( pPage->isInit ){
59756  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59757  pPage->isInit = 0;
59758  if( sqlite3PagerPageRefcount(pData)>1 ){
59759  /* pPage might not be a btree page; it might be an overflow page
59760  ** or ptrmap page or a free page. In those cases, the following
59761  ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
59762  ** But no harm is done by this. And it is very important that
59763  ** btreeInitPage() be called on every btree page so we make
59764  ** the call for every page that comes in for re-initing. */
59765  btreeInitPage(pPage);
59766  }
59767  }
59768 }
59769 
59770 /*
59771 ** Invoke the busy handler for a btree.
59772 */
59773 static int btreeInvokeBusyHandler(void *pArg){
59774  BtShared *pBt = (BtShared*)pArg;
59775  assert( pBt->db );
59776  assert( sqlite3_mutex_held(pBt->db->mutex) );
59777  return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
59778 }
59779 
59780 /*
59781 ** Open a database file.
59782 **
59783 ** zFilename is the name of the database file. If zFilename is NULL
59784 ** then an ephemeral database is created. The ephemeral database might
59785 ** be exclusively in memory, or it might use a disk-based memory cache.
59786 ** Either way, the ephemeral database will be automatically deleted
59787 ** when sqlite3BtreeClose() is called.
59788 **
59789 ** If zFilename is ":memory:" then an in-memory database is created
59790 ** that is automatically destroyed when it is closed.
59791 **
59792 ** The "flags" parameter is a bitmask that might contain bits like
59793 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
59794 **
59795 ** If the database is already opened in the same database connection
59796 ** and we are in shared cache mode, then the open will fail with an
59797 ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
59798 ** objects in the same database connection since doing so will lead
59799 ** to problems with locking.
59800 */
59802  sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
59803  const char *zFilename, /* Name of the file containing the BTree database */
59804  sqlite3 *db, /* Associated database handle */
59805  Btree **ppBtree, /* Pointer to new Btree object written here */
59806  int flags, /* Options */
59807  int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
59808 ){
59809  BtShared *pBt = 0; /* Shared part of btree structure */
59810  Btree *p; /* Handle to return */
59811  sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
59812  int rc = SQLITE_OK; /* Result code from this function */
59813  u8 nReserve; /* Byte of unused space on each page */
59814  unsigned char zDbHeader[100]; /* Database header content */
59815 
59816  /* True if opening an ephemeral, temporary database */
59817  const int isTempDb = zFilename==0 || zFilename[0]==0;
59818 
59819  /* Set the variable isMemdb to true for an in-memory database, or
59820  ** false for a file-based database.
59821  */
59822 #ifdef SQLITE_OMIT_MEMORYDB
59823  const int isMemdb = 0;
59824 #else
59825  const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
59826  || (isTempDb && sqlite3TempInMemory(db))
59827  || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
59828 #endif
59829 
59830  assert( db!=0 );
59831  assert( pVfs!=0 );
59833  assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
59834 
59835  /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
59836  assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
59837 
59838  /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
59839  assert( (flags & BTREE_SINGLE)==0 || isTempDb );
59840 
59841  if( isMemdb ){
59842  flags |= BTREE_MEMORY;
59843  }
59844  if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
59845  vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
59846  }
59847  p = sqlite3MallocZero(sizeof(Btree));
59848  if( !p ){
59849  return SQLITE_NOMEM_BKPT;
59850  }
59851  p->inTrans = TRANS_NONE;
59852  p->db = db;
59853 #ifndef SQLITE_OMIT_SHARED_CACHE
59854  p->lock.pBtree = p;
59855  p->lock.iTable = 1;
59856 #endif
59857 
59858 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
59859  /*
59860  ** If this Btree is a candidate for shared cache, try to find an
59861  ** existing BtShared object that we can share with
59862  */
59863  if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
59864  if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
59865  int nFilename = sqlite3Strlen30(zFilename)+1;
59866  int nFullPathname = pVfs->mxPathname+1;
59867  char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
59868  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
59869 
59870  p->sharable = 1;
59871  if( !zFullPathname ){
59872  sqlite3_free(p);
59873  return SQLITE_NOMEM_BKPT;
59874  }
59875  if( isMemdb ){
59876  memcpy(zFullPathname, zFilename, nFilename);
59877  }else{
59878  rc = sqlite3OsFullPathname(pVfs, zFilename,
59879  nFullPathname, zFullPathname);
59880  if( rc ){
59881  sqlite3_free(zFullPathname);
59882  sqlite3_free(p);
59883  return rc;
59884  }
59885  }
59886 #if SQLITE_THREADSAFE
59888  sqlite3_mutex_enter(mutexOpen);
59890  sqlite3_mutex_enter(mutexShared);
59891 #endif
59892  for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
59893  assert( pBt->nRef>0 );
59894  if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
59895  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
59896  int iDb;
59897  for(iDb=db->nDb-1; iDb>=0; iDb--){
59898  Btree *pExisting = db->aDb[iDb].pBt;
59899  if( pExisting && pExisting->pBt==pBt ){
59900  sqlite3_mutex_leave(mutexShared);
59901  sqlite3_mutex_leave(mutexOpen);
59902  sqlite3_free(zFullPathname);
59903  sqlite3_free(p);
59904  return SQLITE_CONSTRAINT;
59905  }
59906  }
59907  p->pBt = pBt;
59908  pBt->nRef++;
59909  break;
59910  }
59911  }
59912  sqlite3_mutex_leave(mutexShared);
59913  sqlite3_free(zFullPathname);
59914  }
59915 #ifdef SQLITE_DEBUG
59916  else{
59917  /* In debug mode, we mark all persistent databases as sharable
59918  ** even when they are not. This exercises the locking code and
59919  ** gives more opportunity for asserts(sqlite3_mutex_held())
59920  ** statements to find locking problems.
59921  */
59922  p->sharable = 1;
59923  }
59924 #endif
59925  }
59926 #endif
59927  if( pBt==0 ){
59928  /*
59929  ** The following asserts make sure that structures used by the btree are
59930  ** the right size. This is to guard against size changes that result
59931  ** when compiling on a different architecture.
59932  */
59933  assert( sizeof(i64)==8 );
59934  assert( sizeof(u64)==8 );
59935  assert( sizeof(u32)==4 );
59936  assert( sizeof(u16)==2 );
59937  assert( sizeof(Pgno)==4 );
59938 
59939  pBt = sqlite3MallocZero( sizeof(*pBt) );
59940  if( pBt==0 ){
59941  rc = SQLITE_NOMEM_BKPT;
59942  goto btree_open_out;
59943  }
59944  rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
59945  EXTRA_SIZE, flags, vfsFlags, pageReinit);
59946  if( rc==SQLITE_OK ){
59948  rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
59949  }
59950  if( rc!=SQLITE_OK ){
59951  goto btree_open_out;
59952  }
59953  pBt->openFlags = (u8)flags;
59954  pBt->db = db;
59956  p->pBt = pBt;
59957 
59958  pBt->pCursor = 0;
59959  pBt->pPage1 = 0;
59961 #ifdef SQLITE_SECURE_DELETE
59962  pBt->btsFlags |= BTS_SECURE_DELETE;
59963 #endif
59964  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
59965  ** determined by the 2-byte integer located at an offset of 16 bytes from
59966  ** the beginning of the database file. */
59967  pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
59968  if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
59969  || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
59970  pBt->pageSize = 0;
59971 #ifndef SQLITE_OMIT_AUTOVACUUM
59972  /* If the magic name ":memory:" will create an in-memory database, then
59973  ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
59974  ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
59975  ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
59976  ** regular file-name. In this case the auto-vacuum applies as per normal.
59977  */
59978  if( zFilename && !isMemdb ){
59979  pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
59980  pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
59981  }
59982 #endif
59983  nReserve = 0;
59984  }else{
59985  /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
59986  ** determined by the one-byte unsigned integer found at an offset of 20
59987  ** into the database file header. */
59988  nReserve = zDbHeader[20];
59989  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
59990 #ifndef SQLITE_OMIT_AUTOVACUUM
59991  pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
59992  pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
59993 #endif
59994  }
59995  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
59996  if( rc ) goto btree_open_out;
59997  pBt->usableSize = pBt->pageSize - nReserve;
59998  assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
59999 
60000 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60001  /* Add the new BtShared object to the linked list sharable BtShareds.
60002  */
60003  if( p->sharable ){
60004  MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
60005  pBt->nRef = 1;
60007  if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
60009  if( pBt->mutex==0 ){
60010  rc = SQLITE_NOMEM_BKPT;
60011  goto btree_open_out;
60012  }
60013  }
60014  sqlite3_mutex_enter(mutexShared);
60015  pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
60016  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
60017  sqlite3_mutex_leave(mutexShared);
60018  }
60019 #endif
60020  }
60021 
60022 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
60023  /* If the new Btree uses a sharable pBtShared, then link the new
60024  ** Btree into the list of all sharable Btrees for the same connection.
60025  ** The list is kept in ascending order by pBt address.
60026  */
60027  if( p->sharable ){
60028  int i;
60029  Btree *pSib;
60030  for(i=0; i<db->nDb; i++){
60031  if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
60032  while( pSib->pPrev ){ pSib = pSib->pPrev; }
60033  if( (uptr)p->pBt<(uptr)pSib->pBt ){
60034  p->pNext = pSib;
60035  p->pPrev = 0;
60036  pSib->pPrev = p;
60037  }else{
60038  while( pSib->pNext && (uptr)pSib->pNext->pBt<(uptr)p->pBt ){
60039  pSib = pSib->pNext;
60040  }
60041  p->pNext = pSib->pNext;
60042  p->pPrev = pSib;
60043  if( p->pNext ){
60044  p->pNext->pPrev = p;
60045  }
60046  pSib->pNext = p;
60047  }
60048  break;
60049  }
60050  }
60051  }
60052 #endif
60053  *ppBtree = p;
60054 
60055 btree_open_out:
60056  if( rc!=SQLITE_OK ){
60057  if( pBt && pBt->pPager ){
60058  sqlite3PagerClose(pBt->pPager);
60059  }
60060  sqlite3_free(pBt);
60061  sqlite3_free(p);
60062  *ppBtree = 0;
60063  }else{
60064  /* If the B-Tree was successfully opened, set the pager-cache size to the
60065  ** default value. Except, when opening on an existing shared pager-cache,
60066  ** do not change the pager-cache size.
60067  */
60068  if( sqlite3BtreeSchema(p, 0, 0)==0 ){
60070  }
60071  }
60072  if( mutexOpen ){
60073  assert( sqlite3_mutex_held(mutexOpen) );
60074  sqlite3_mutex_leave(mutexOpen);
60075  }
60076  return rc;
60077 }
60078 
60079 /*
60080 ** Decrement the BtShared.nRef counter. When it reaches zero,
60081 ** remove the BtShared structure from the sharing list. Return
60082 ** true if the BtShared.nRef counter reaches zero and return
60083 ** false if it is still positive.
60084 */
60086 #ifndef SQLITE_OMIT_SHARED_CACHE
60087  MUTEX_LOGIC( sqlite3_mutex *pMaster; )
60088  BtShared *pList;
60089  int removed = 0;
60090 
60093  sqlite3_mutex_enter(pMaster);
60094  pBt->nRef--;
60095  if( pBt->nRef<=0 ){
60096  if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
60097  GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
60098  }else{
60099  pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
60100  while( ALWAYS(pList) && pList->pNext!=pBt ){
60101  pList=pList->pNext;
60102  }
60103  if( ALWAYS(pList) ){
60104  pList->pNext = pBt->pNext;
60105  }
60106  }
60107  if( SQLITE_THREADSAFE ){
60108  sqlite3_mutex_free(pBt->mutex);
60109  }
60110  removed = 1;
60111  }
60112  sqlite3_mutex_leave(pMaster);
60113  return removed;
60114 #else
60115  return 1;
60116 #endif
60117 }
60118 
60119 /*
60120 ** Make sure pBt->pTmpSpace points to an allocation of
60121 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
60122 ** pointer.
60123 */
60124 static void allocateTempSpace(BtShared *pBt){
60125  if( !pBt->pTmpSpace ){
60126  pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
60127 
60128  /* One of the uses of pBt->pTmpSpace is to format cells before
60129  ** inserting them into a leaf page (function fillInCell()). If
60130  ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
60131  ** by the various routines that manipulate binary cells. Which
60132  ** can mean that fillInCell() only initializes the first 2 or 3
60133  ** bytes of pTmpSpace, but that the first 4 bytes are copied from
60134  ** it into a database page. This is not actually a problem, but it
60135  ** does cause a valgrind error when the 1 or 2 bytes of unitialized
60136  ** data is passed to system call write(). So to avoid this error,
60137  ** zero the first 4 bytes of temp space here.
60138  **
60139  ** Also: Provide four bytes of initialized space before the
60140  ** beginning of pTmpSpace as an area available to prepend the
60141  ** left-child pointer to the beginning of a cell.
60142  */
60143  if( pBt->pTmpSpace ){
60144  memset(pBt->pTmpSpace, 0, 8);
60145  pBt->pTmpSpace += 4;
60146  }
60147  }
60148 }
60149 
60150 /*
60151 ** Free the pBt->pTmpSpace allocation
60152 */
60153 static void freeTempSpace(BtShared *pBt){
60154  if( pBt->pTmpSpace ){
60155  pBt->pTmpSpace -= 4;
60156  sqlite3PageFree(pBt->pTmpSpace);
60157  pBt->pTmpSpace = 0;
60158  }
60159 }
60160 
60161 /*
60162 ** Close an open database and invalidate all cursors.
60163 */
60165  BtShared *pBt = p->pBt;
60166  BtCursor *pCur;
60167 
60168  /* Close all cursors opened via this handle. */
60170  sqlite3BtreeEnter(p);
60171  pCur = pBt->pCursor;
60172  while( pCur ){
60173  BtCursor *pTmp = pCur;
60174  pCur = pCur->pNext;
60175  if( pTmp->pBtree==p ){
60177  }
60178  }
60179 
60180  /* Rollback any active transaction and free the handle structure.
60181  ** The call to sqlite3BtreeRollback() drops any table-locks held by
60182  ** this handle.
60183  */
60185  sqlite3BtreeLeave(p);
60186 
60187  /* If there are still other outstanding references to the shared-btree
60188  ** structure, return now. The remainder of this procedure cleans
60189  ** up the shared-btree.
60190  */
60191  assert( p->wantToLock==0 && p->locked==0 );
60192  if( !p->sharable || removeFromSharingList(pBt) ){
60193  /* The pBt is no longer on the sharing list, so we can access
60194  ** it without having to hold the mutex.
60195  **
60196  ** Clean out and delete the BtShared object.
60197  */
60198  assert( !pBt->pCursor );
60199  sqlite3PagerClose(pBt->pPager);
60200  if( pBt->xFreeSchema && pBt->pSchema ){
60201  pBt->xFreeSchema(pBt->pSchema);
60202  }
60203  sqlite3DbFree(0, pBt->pSchema);
60204  freeTempSpace(pBt);
60205  sqlite3_free(pBt);
60206  }
60207 
60208 #ifndef SQLITE_OMIT_SHARED_CACHE
60209  assert( p->wantToLock==0 );
60210  assert( p->locked==0 );
60211  if( p->pPrev ) p->pPrev->pNext = p->pNext;
60212  if( p->pNext ) p->pNext->pPrev = p->pPrev;
60213 #endif
60214 
60215  sqlite3_free(p);
60216  return SQLITE_OK;
60217 }
60218 
60219 /*
60220 ** Change the "soft" limit on the number of pages in the cache.
60221 ** Unused and unmodified pages will be recycled when the number of
60222 ** pages in the cache exceeds this soft limit. But the size of the
60223 ** cache is allowed to grow larger than this limit if it contains
60224 ** dirty pages or pages still in active use.
60225 */
60227  BtShared *pBt = p->pBt;
60229  sqlite3BtreeEnter(p);
60230  sqlite3PagerSetCachesize(pBt->pPager, mxPage);
60231  sqlite3BtreeLeave(p);
60232  return SQLITE_OK;
60233 }
60234 
60235 /*
60236 ** Change the "spill" limit on the number of pages in the cache.
60237 ** If the number of pages exceeds this limit during a write transaction,
60238 ** the pager might attempt to "spill" pages to the journal early in
60239 ** order to free up memory.
60240 **
60241 ** The value returned is the current spill size. If zero is passed
60242 ** as an argument, no changes are made to the spill size setting, so
60243 ** using mxPage of 0 is a way to query the current spill size.
60244 */
60246  BtShared *pBt = p->pBt;
60247  int res;
60249  sqlite3BtreeEnter(p);
60250  res = sqlite3PagerSetSpillsize(pBt->pPager, mxPage);
60251  sqlite3BtreeLeave(p);
60252  return res;
60253 }
60254 
60255 #if SQLITE_MAX_MMAP_SIZE>0
60256 /*
60257 ** Change the limit on the amount of the database file that may be
60258 ** memory mapped.
60259 */
60260 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
60261  BtShared *pBt = p->pBt;
60263  sqlite3BtreeEnter(p);
60264  sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
60265  sqlite3BtreeLeave(p);
60266  return SQLITE_OK;
60267 }
60268 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
60269 
60270 /*
60271 ** Change the way data is synced to disk in order to increase or decrease
60272 ** how well the database resists damage due to OS crashes and power
60273 ** failures. Level 1 is the same as asynchronous (no syncs() occur and
60274 ** there is a high probability of damage) Level 2 is the default. There
60275 ** is a very low but non-zero probability of damage. Level 3 reduces the
60276 ** probability of damage to near zero but with a write performance reduction.
60277 */
60278 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
60280  Btree *p, /* The btree to set the safety level on */
60281  unsigned pgFlags /* Various PAGER_* flags */
60282 ){
60283  BtShared *pBt = p->pBt;
60285  sqlite3BtreeEnter(p);
60286  sqlite3PagerSetFlags(pBt->pPager, pgFlags);
60287  sqlite3BtreeLeave(p);
60288  return SQLITE_OK;
60289 }
60290 #endif
60291 
60292 /*
60293 ** Change the default pages size and the number of reserved bytes per page.
60294 ** Or, if the page size has already been fixed, return SQLITE_READONLY
60295 ** without changing anything.
60296 **
60297 ** The page size must be a power of 2 between 512 and 65536. If the page
60298 ** size supplied does not meet this constraint then the page size is not
60299 ** changed.
60300 **
60301 ** Page sizes are constrained to be a power of two so that the region
60302 ** of the database file used for locking (beginning at PENDING_BYTE,
60303 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
60304 ** at the beginning of a page.
60305 **
60306 ** If parameter nReserve is less than zero, then the number of reserved
60307 ** bytes per page is left unchanged.
60308 **
60309 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
60310 ** and autovacuum mode can no longer be changed.
60311 */
60312 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
60313  int rc = SQLITE_OK;
60314  BtShared *pBt = p->pBt;
60315  assert( nReserve>=-1 && nReserve<=255 );
60316  sqlite3BtreeEnter(p);
60317 #if SQLITE_HAS_CODEC
60318  if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
60319 #endif
60320  if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
60321  sqlite3BtreeLeave(p);
60322  return SQLITE_READONLY;
60323  }
60324  if( nReserve<0 ){
60325  nReserve = pBt->pageSize - pBt->usableSize;
60326  }
60327  assert( nReserve>=0 && nReserve<=255 );
60328  if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
60329  ((pageSize-1)&pageSize)==0 ){
60330  assert( (pageSize & 7)==0 );
60331  assert( !pBt->pCursor );
60332  pBt->pageSize = (u32)pageSize;
60333  freeTempSpace(pBt);
60334  }
60335  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
60336  pBt->usableSize = pBt->pageSize - (u16)nReserve;
60337  if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60338  sqlite3BtreeLeave(p);
60339  return rc;
60340 }
60341 
60342 /*
60343 ** Return the currently defined page size
60344 */
60346  return p->pBt->pageSize;
60347 }
60348 
60349 /*
60350 ** This function is similar to sqlite3BtreeGetReserve(), except that it
60351 ** may only be called if it is guaranteed that the b-tree mutex is already
60352 ** held.
60353 **
60354 ** This is useful in one special case in the backup API code where it is
60355 ** known that the shared b-tree mutex is held, but the mutex on the
60356 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
60357 ** were to be called, it might collide with some other operation on the
60358 ** database handle that owns *p, causing undefined behavior.
60359 */
60361  int n;
60363  n = p->pBt->pageSize - p->pBt->usableSize;
60364  return n;
60365 }
60366 
60367 /*
60368 ** Return the number of bytes of space at the end of every page that
60369 ** are intentually left unused. This is the "reserved" space that is
60370 ** sometimes used by extensions.
60371 **
60372 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
60373 ** greater of the current reserved space and the maximum requested
60374 ** reserve space.
60375 */
60377  int n;
60378  sqlite3BtreeEnter(p);
60380 #ifdef SQLITE_HAS_CODEC
60381  if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
60382 #endif
60383  sqlite3BtreeLeave(p);
60384  return n;
60385 }
60386 
60387 
60388 /*
60389 ** Set the maximum page count for a database if mxPage is positive.
60390 ** No changes are made if mxPage is 0 or negative.
60391 ** Regardless of the value of mxPage, return the maximum page count.
60392 */
60394  int n;
60395  sqlite3BtreeEnter(p);
60396  n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
60397  sqlite3BtreeLeave(p);
60398  return n;
60399 }
60400 
60401 /*
60402 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
60403 ** then make no changes. Always return the value of the BTS_SECURE_DELETE
60404 ** setting after the change.
60405 */
60407  int b;
60408  if( p==0 ) return 0;
60409  sqlite3BtreeEnter(p);
60410  if( newFlag>=0 ){
60411  p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
60412  if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
60413  }
60414  b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
60415  sqlite3BtreeLeave(p);
60416  return b;
60417 }
60418 
60419 /*
60420 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
60421 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
60422 ** is disabled. The default value for the auto-vacuum property is
60423 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
60424 */
60426 #ifdef SQLITE_OMIT_AUTOVACUUM
60427  return SQLITE_READONLY;
60428 #else
60429  BtShared *pBt = p->pBt;
60430  int rc = SQLITE_OK;
60431  u8 av = (u8)autoVacuum;
60432 
60433  sqlite3BtreeEnter(p);
60434  if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
60435  rc = SQLITE_READONLY;
60436  }else{
60437  pBt->autoVacuum = av ?1:0;
60438  pBt->incrVacuum = av==2 ?1:0;
60439  }
60440  sqlite3BtreeLeave(p);
60441  return rc;
60442 #endif
60443 }
60444 
60445 /*
60446 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
60447 ** enabled 1 is returned. Otherwise 0.
60448 */
60450 #ifdef SQLITE_OMIT_AUTOVACUUM
60451  return BTREE_AUTOVACUUM_NONE;
60452 #else
60453  int rc;
60454  sqlite3BtreeEnter(p);
60455  rc = (
60459  );
60460  sqlite3BtreeLeave(p);
60461  return rc;
60462 #endif
60463 }
60464 
60465 
60466 /*
60467 ** Get a reference to pPage1 of the database file. This will
60468 ** also acquire a readlock on that file.
60469 **
60470 ** SQLITE_OK is returned on success. If the file is not a
60471 ** well-formed database file, then SQLITE_CORRUPT is returned.
60472 ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
60473 ** is returned if we run out of memory.
60474 */
60475 static int lockBtree(BtShared *pBt){
60476  int rc; /* Result code from subfunctions */
60477  MemPage *pPage1; /* Page 1 of the database file */
60478  int nPage; /* Number of pages in the database */
60479  int nPageFile = 0; /* Number of pages in the database file */
60480  int nPageHeader; /* Number of pages in the database according to hdr */
60481 
60482  assert( sqlite3_mutex_held(pBt->mutex) );
60483  assert( pBt->pPage1==0 );
60484  rc = sqlite3PagerSharedLock(pBt->pPager);
60485  if( rc!=SQLITE_OK ) return rc;
60486  rc = btreeGetPage(pBt, 1, &pPage1, 0);
60487  if( rc!=SQLITE_OK ) return rc;
60488 
60489  /* Do some checking to help insure the file we opened really is
60490  ** a valid database file.
60491  */
60492  nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
60493  sqlite3PagerPagecount(pBt->pPager, &nPageFile);
60494  if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
60495  nPage = nPageFile;
60496  }
60497  if( nPage>0 ){
60498  u32 pageSize;
60499  u32 usableSize;
60500  u8 *page1 = pPage1->aData;
60501  rc = SQLITE_NOTADB;
60502  /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
60503  ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
60504  ** 61 74 20 33 00. */
60505  if( memcmp(page1, zMagicHeader, 16)!=0 ){
60506  goto page1_init_failed;
60507  }
60508 
60509 #ifdef SQLITE_OMIT_WAL
60510  if( page1[18]>1 ){
60511  pBt->btsFlags |= BTS_READ_ONLY;
60512  }
60513  if( page1[19]>1 ){
60514  goto page1_init_failed;
60515  }
60516 #else
60517  if( page1[18]>2 ){
60518  pBt->btsFlags |= BTS_READ_ONLY;
60519  }
60520  if( page1[19]>2 ){
60521  goto page1_init_failed;
60522  }
60523 
60524  /* If the write version is set to 2, this database should be accessed
60525  ** in WAL mode. If the log is not already open, open it now. Then
60526  ** return SQLITE_OK and return without populating BtShared.pPage1.
60527  ** The caller detects this and calls this function again. This is
60528  ** required as the version of page 1 currently in the page1 buffer
60529  ** may not be the latest version - there may be a newer one in the log
60530  ** file.
60531  */
60532  if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
60533  int isOpen = 0;
60534  rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
60535  if( rc!=SQLITE_OK ){
60536  goto page1_init_failed;
60537  }else{
60538 #if SQLITE_DEFAULT_SYNCHRONOUS!=SQLITE_DEFAULT_WAL_SYNCHRONOUS
60539  sqlite3 *db;
60540  Db *pDb;
60541  if( (db=pBt->db)!=0 && (pDb=db->aDb)!=0 ){
60542  while( pDb->pBt==0 || pDb->pBt->pBt!=pBt ){ pDb++; }
60543  if( pDb->bSyncSet==0
60545  ){
60548  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK));
60549  }
60550  }
60551 #endif
60552  if( isOpen==0 ){
60553  releasePage(pPage1);
60554  return SQLITE_OK;
60555  }
60556  }
60557  rc = SQLITE_NOTADB;
60558  }
60559 #endif
60560 
60561  /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
60562  ** fractions and the leaf payload fraction values must be 64, 32, and 32.
60563  **
60564  ** The original design allowed these amounts to vary, but as of
60565  ** version 3.6.0, we require them to be fixed.
60566  */
60567  if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
60568  goto page1_init_failed;
60569  }
60570  /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
60571  ** determined by the 2-byte integer located at an offset of 16 bytes from
60572  ** the beginning of the database file. */
60573  pageSize = (page1[16]<<8) | (page1[17]<<16);
60574  /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
60575  ** between 512 and 65536 inclusive. */
60576  if( ((pageSize-1)&pageSize)!=0
60577  || pageSize>SQLITE_MAX_PAGE_SIZE
60578  || pageSize<=256
60579  ){
60580  goto page1_init_failed;
60581  }
60582  assert( (pageSize & 7)==0 );
60583  /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
60584  ** integer at offset 20 is the number of bytes of space at the end of
60585  ** each page to reserve for extensions.
60586  **
60587  ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
60588  ** determined by the one-byte unsigned integer found at an offset of 20
60589  ** into the database file header. */
60590  usableSize = pageSize - page1[20];
60591  if( (u32)pageSize!=pBt->pageSize ){
60592  /* After reading the first page of the database assuming a page size
60593  ** of BtShared.pageSize, we have discovered that the page-size is
60594  ** actually pageSize. Unlock the database, leave pBt->pPage1 at
60595  ** zero and return SQLITE_OK. The caller will call this function
60596  ** again with the correct page-size.
60597  */
60598  releasePage(pPage1);
60599  pBt->usableSize = usableSize;
60600  pBt->pageSize = pageSize;
60601  freeTempSpace(pBt);
60602  rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
60603  pageSize-usableSize);
60604  return rc;
60605  }
60606  if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
60607  rc = SQLITE_CORRUPT_BKPT;
60608  goto page1_init_failed;
60609  }
60610  /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
60611  ** be less than 480. In other words, if the page size is 512, then the
60612  ** reserved space size cannot exceed 32. */
60613  if( usableSize<480 ){
60614  goto page1_init_failed;
60615  }
60616  pBt->pageSize = pageSize;
60617  pBt->usableSize = usableSize;
60618 #ifndef SQLITE_OMIT_AUTOVACUUM
60619  pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
60620  pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
60621 #endif
60622  }
60623 
60624  /* maxLocal is the maximum amount of payload to store locally for
60625  ** a cell. Make sure it is small enough so that at least minFanout
60626  ** cells can will fit on one page. We assume a 10-byte page header.
60627  ** Besides the payload, the cell must store:
60628  ** 2-byte pointer to the cell
60629  ** 4-byte child pointer
60630  ** 9-byte nKey value
60631  ** 4-byte nData value
60632  ** 4-byte overflow page pointer
60633  ** So a cell consists of a 2-byte pointer, a header which is as much as
60634  ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
60635  ** page pointer.
60636  */
60637  pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
60638  pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
60639  pBt->maxLeaf = (u16)(pBt->usableSize - 35);
60640  pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
60641  if( pBt->maxLocal>127 ){
60642  pBt->max1bytePayload = 127;
60643  }else{
60644  pBt->max1bytePayload = (u8)pBt->maxLocal;
60645  }
60646  assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
60647  pBt->pPage1 = pPage1;
60648  pBt->nPage = nPage;
60649  return SQLITE_OK;
60650 
60651 page1_init_failed:
60652  releasePage(pPage1);
60653  pBt->pPage1 = 0;
60654  return rc;
60655 }
60656 
60657 #ifndef NDEBUG
60658 /*
60659 ** Return the number of cursors open on pBt. This is for use
60660 ** in assert() expressions, so it is only compiled if NDEBUG is not
60661 ** defined.
60662 **
60663 ** Only write cursors are counted if wrOnly is true. If wrOnly is
60664 ** false then all cursors are counted.
60665 **
60666 ** For the purposes of this routine, a cursor is any cursor that
60667 ** is capable of reading or writing to the database. Cursors that
60668 ** have been tripped into the CURSOR_FAULT state are not counted.
60669 */
60670 static int countValidCursors(BtShared *pBt, int wrOnly){
60671  BtCursor *pCur;
60672  int r = 0;
60673  for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
60674  if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
60675  && pCur->eState!=CURSOR_FAULT ) r++;
60676  }
60677  return r;
60678 }
60679 #endif
60680 
60681 /*
60682 ** If there are no outstanding cursors and we are not in the middle
60683 ** of a transaction but there is a read lock on the database, then
60684 ** this routine unrefs the first page of the database file which
60685 ** has the effect of releasing the read lock.
60686 **
60687 ** If there is a transaction in progress, this routine is a no-op.
60688 */
60689 static void unlockBtreeIfUnused(BtShared *pBt){
60690  assert( sqlite3_mutex_held(pBt->mutex) );
60691  assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
60692  if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
60693  MemPage *pPage1 = pBt->pPage1;
60694  assert( pPage1->aData );
60695  assert( sqlite3PagerRefcount(pBt->pPager)==1 );
60696  pBt->pPage1 = 0;
60697  releasePageNotNull(pPage1);
60698  }
60699 }
60700 
60701 /*
60702 ** If pBt points to an empty file then convert that empty file
60703 ** into a new empty database by initializing the first page of
60704 ** the database.
60705 */
60706 static int newDatabase(BtShared *pBt){
60707  MemPage *pP1;
60708  unsigned char *data;
60709  int rc;
60710 
60711  assert( sqlite3_mutex_held(pBt->mutex) );
60712  if( pBt->nPage>0 ){
60713  return SQLITE_OK;
60714  }
60715  pP1 = pBt->pPage1;
60716  assert( pP1!=0 );
60717  data = pP1->aData;
60718  rc = sqlite3PagerWrite(pP1->pDbPage);
60719  if( rc ) return rc;
60720  memcpy(data, zMagicHeader, sizeof(zMagicHeader));
60721  assert( sizeof(zMagicHeader)==16 );
60722  data[16] = (u8)((pBt->pageSize>>8)&0xff);
60723  data[17] = (u8)((pBt->pageSize>>16)&0xff);
60724  data[18] = 1;
60725  data[19] = 1;
60726  assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
60727  data[20] = (u8)(pBt->pageSize - pBt->usableSize);
60728  data[21] = 64;
60729  data[22] = 32;
60730  data[23] = 32;
60731  memset(&data[24], 0, 100-24);
60733  pBt->btsFlags |= BTS_PAGESIZE_FIXED;
60734 #ifndef SQLITE_OMIT_AUTOVACUUM
60735  assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
60736  assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
60737  put4byte(&data[36 + 4*4], pBt->autoVacuum);
60738  put4byte(&data[36 + 7*4], pBt->incrVacuum);
60739 #endif
60740  pBt->nPage = 1;
60741  data[31] = 1;
60742  return SQLITE_OK;
60743 }
60744 
60745 /*
60746 ** Initialize the first page of the database file (creating a database
60747 ** consisting of a single page and no schema objects). Return SQLITE_OK
60748 ** if successful, or an SQLite error code otherwise.
60749 */
60751  int rc;
60752  sqlite3BtreeEnter(p);
60753  p->pBt->nPage = 0;
60754  rc = newDatabase(p->pBt);
60755  sqlite3BtreeLeave(p);
60756  return rc;
60757 }
60758 
60759 /*
60760 ** Attempt to start a new transaction. A write-transaction
60761 ** is started if the second argument is nonzero, otherwise a read-
60762 ** transaction. If the second argument is 2 or more and exclusive
60763 ** transaction is started, meaning that no other process is allowed
60764 ** to access the database. A preexisting transaction may not be
60765 ** upgraded to exclusive by calling this routine a second time - the
60766 ** exclusivity flag only works for a new transaction.
60767 **
60768 ** A write-transaction must be started before attempting any
60769 ** changes to the database. None of the following routines
60770 ** will work unless a transaction is started first:
60771 **
60772 ** sqlite3BtreeCreateTable()
60773 ** sqlite3BtreeCreateIndex()
60774 ** sqlite3BtreeClearTable()
60775 ** sqlite3BtreeDropTable()
60776 ** sqlite3BtreeInsert()
60777 ** sqlite3BtreeDelete()
60778 ** sqlite3BtreeUpdateMeta()
60779 **
60780 ** If an initial attempt to acquire the lock fails because of lock contention
60781 ** and the database was previously unlocked, then invoke the busy handler
60782 ** if there is one. But if there was previously a read-lock, do not
60783 ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
60784 ** returned when there is already a read-lock in order to avoid a deadlock.
60785 **
60786 ** Suppose there are two processes A and B. A has a read lock and B has
60787 ** a reserved lock. B tries to promote to exclusive but is blocked because
60788 ** of A's read lock. A tries to promote to reserved but is blocked by B.
60789 ** One or the other of the two processes must give way or there can be
60790 ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
60791 ** when A already has a read lock, we encourage A to give up and let B
60792 ** proceed.
60793 */
60795  BtShared *pBt = p->pBt;
60796  int rc = SQLITE_OK;
60797 
60798  sqlite3BtreeEnter(p);
60799  btreeIntegrity(p);
60800 
60801  /* If the btree is already in a write-transaction, or it
60802  ** is already in a read-transaction and a read-transaction
60803  ** is requested, this is a no-op.
60804  */
60805  if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
60806  goto trans_begun;
60807  }
60809 
60810  /* Write transactions are not possible on a read-only database */
60811  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
60812  rc = SQLITE_READONLY;
60813  goto trans_begun;
60814  }
60815 
60816 #ifndef SQLITE_OMIT_SHARED_CACHE
60817  {
60818  sqlite3 *pBlock = 0;
60819  /* If another database handle has already opened a write transaction
60820  ** on this shared-btree structure and a second write transaction is
60821  ** requested, return SQLITE_LOCKED.
60822  */
60823  if( (wrflag && pBt->inTransaction==TRANS_WRITE)
60824  || (pBt->btsFlags & BTS_PENDING)!=0
60825  ){
60826  pBlock = pBt->pWriter->db;
60827  }else if( wrflag>1 ){
60828  BtLock *pIter;
60829  for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
60830  if( pIter->pBtree!=p ){
60831  pBlock = pIter->pBtree->db;
60832  break;
60833  }
60834  }
60835  }
60836  if( pBlock ){
60837  sqlite3ConnectionBlocked(p->db, pBlock);
60839  goto trans_begun;
60840  }
60841  }
60842 #endif
60843 
60844  /* Any read-only or read-write transaction implies a read-lock on
60845  ** page 1. So if some other shared-cache client already has a write-lock
60846  ** on page 1, the transaction cannot be opened. */
60848  if( SQLITE_OK!=rc ) goto trans_begun;
60849 
60850  pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
60851  if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
60852  do {
60853  /* Call lockBtree() until either pBt->pPage1 is populated or
60854  ** lockBtree() returns something other than SQLITE_OK. lockBtree()
60855  ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
60856  ** reading page 1 it discovers that the page-size of the database
60857  ** file is not pBt->pageSize. In this case lockBtree() will update
60858  ** pBt->pageSize to the page-size of the file on disk.
60859  */
60860  while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
60861 
60862  if( rc==SQLITE_OK && wrflag ){
60863  if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
60864  rc = SQLITE_READONLY;
60865  }else{
60866  rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
60867  if( rc==SQLITE_OK ){
60868  rc = newDatabase(pBt);
60869  }
60870  }
60871  }
60872 
60873  if( rc!=SQLITE_OK ){
60874  unlockBtreeIfUnused(pBt);
60875  }
60876  }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
60877  btreeInvokeBusyHandler(pBt) );
60878 
60879  if( rc==SQLITE_OK ){
60880  if( p->inTrans==TRANS_NONE ){
60881  pBt->nTransaction++;
60882 #ifndef SQLITE_OMIT_SHARED_CACHE
60883  if( p->sharable ){
60884  assert( p->lock.pBtree==p && p->lock.iTable==1 );
60885  p->lock.eLock = READ_LOCK;
60886  p->lock.pNext = pBt->pLock;
60887  pBt->pLock = &p->lock;
60888  }
60889 #endif
60890  }
60891  p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
60892  if( p->inTrans>pBt->inTransaction ){
60893  pBt->inTransaction = p->inTrans;
60894  }
60895  if( wrflag ){
60896  MemPage *pPage1 = pBt->pPage1;
60897 #ifndef SQLITE_OMIT_SHARED_CACHE
60898  assert( !pBt->pWriter );
60899  pBt->pWriter = p;
60900  pBt->btsFlags &= ~BTS_EXCLUSIVE;
60901  if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
60902 #endif
60903 
60904  /* If the db-size header field is incorrect (as it may be if an old
60905  ** client has been writing the database file), update it now. Doing
60906  ** this sooner rather than later means the database size can safely
60907  ** re-read the database size from page 1 if a savepoint or transaction
60908  ** rollback occurs within the transaction.
60909  */
60910  if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
60911  rc = sqlite3PagerWrite(pPage1->pDbPage);
60912  if( rc==SQLITE_OK ){
60913  put4byte(&pPage1->aData[28], pBt->nPage);
60914  }
60915  }
60916  }
60917  }
60918 
60919 
60920 trans_begun:
60921  if( rc==SQLITE_OK && wrflag ){
60922  /* This call makes sure that the pager has the correct number of
60923  ** open savepoints. If the second parameter is greater than 0 and
60924  ** the sub-journal is not already open, then it will be opened here.
60925  */
60927  }
60928 
60929  btreeIntegrity(p);
60930  sqlite3BtreeLeave(p);
60931  return rc;
60932 }
60933 
60934 #ifndef SQLITE_OMIT_AUTOVACUUM
60935 
60936 /*
60937 ** Set the pointer-map entries for all children of page pPage. Also, if
60938 ** pPage contains cells that point to overflow pages, set the pointer
60939 ** map entries for the overflow pages as well.
60940 */
60941 static int setChildPtrmaps(MemPage *pPage){
60942  int i; /* Counter variable */
60943  int nCell; /* Number of cells in page pPage */
60944  int rc; /* Return code */
60945  BtShared *pBt = pPage->pBt;
60946  u8 isInitOrig = pPage->isInit;
60947  Pgno pgno = pPage->pgno;
60948 
60949  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60950  rc = btreeInitPage(pPage);
60951  if( rc!=SQLITE_OK ){
60952  goto set_child_ptrmaps_out;
60953  }
60954  nCell = pPage->nCell;
60955 
60956  for(i=0; i<nCell; i++){
60957  u8 *pCell = findCell(pPage, i);
60958 
60959  ptrmapPutOvflPtr(pPage, pCell, &rc);
60960 
60961  if( !pPage->leaf ){
60962  Pgno childPgno = get4byte(pCell);
60963  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
60964  }
60965  }
60966 
60967  if( !pPage->leaf ){
60968  Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
60969  ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
60970  }
60971 
60972 set_child_ptrmaps_out:
60973  pPage->isInit = isInitOrig;
60974  return rc;
60975 }
60976 
60977 /*
60978 ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
60979 ** that it points to iTo. Parameter eType describes the type of pointer to
60980 ** be modified, as follows:
60981 **
60982 ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
60983 ** page of pPage.
60984 **
60985 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
60986 ** page pointed to by one of the cells on pPage.
60987 **
60988 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
60989 ** overflow page in the list.
60990 */
60991 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
60992  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
60993  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
60994  if( eType==PTRMAP_OVERFLOW2 ){
60995  /* The pointer is always the first 4 bytes of the page in this case. */
60996  if( get4byte(pPage->aData)!=iFrom ){
60997  return SQLITE_CORRUPT_BKPT;
60998  }
60999  put4byte(pPage->aData, iTo);
61000  }else{
61001  u8 isInitOrig = pPage->isInit;
61002  int i;
61003  int nCell;
61004  int rc;
61005 
61006  rc = btreeInitPage(pPage);
61007  if( rc ) return rc;
61008  nCell = pPage->nCell;
61009 
61010  for(i=0; i<nCell; i++){
61011  u8 *pCell = findCell(pPage, i);
61012  if( eType==PTRMAP_OVERFLOW1 ){
61013  CellInfo info;
61014  pPage->xParseCell(pPage, pCell, &info);
61015  if( info.nLocal<info.nPayload
61016  && pCell+info.nSize-1<=pPage->aData+pPage->maskPage
61017  && iFrom==get4byte(pCell+info.nSize-4)
61018  ){
61019  put4byte(pCell+info.nSize-4, iTo);
61020  break;
61021  }
61022  }else{
61023  if( get4byte(pCell)==iFrom ){
61024  put4byte(pCell, iTo);
61025  break;
61026  }
61027  }
61028  }
61029 
61030  if( i==nCell ){
61031  if( eType!=PTRMAP_BTREE ||
61032  get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
61033  return SQLITE_CORRUPT_BKPT;
61034  }
61035  put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
61036  }
61037 
61038  pPage->isInit = isInitOrig;
61039  }
61040  return SQLITE_OK;
61041 }
61042 
61043 
61044 /*
61045 ** Move the open database page pDbPage to location iFreePage in the
61046 ** database. The pDbPage reference remains valid.
61047 **
61048 ** The isCommit flag indicates that there is no need to remember that
61049 ** the journal needs to be sync()ed before database page pDbPage->pgno
61050 ** can be written to. The caller has already promised not to write to that
61051 ** page.
61052 */
61053 static int relocatePage(
61054  BtShared *pBt, /* Btree */
61055  MemPage *pDbPage, /* Open page to move */
61056  u8 eType, /* Pointer map 'type' entry for pDbPage */
61057  Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
61058  Pgno iFreePage, /* The location to move pDbPage to */
61059  int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
61060 ){
61061  MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
61062  Pgno iDbPage = pDbPage->pgno;
61063  Pager *pPager = pBt->pPager;
61064  int rc;
61065 
61066  assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
61067  eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
61068  assert( sqlite3_mutex_held(pBt->mutex) );
61069  assert( pDbPage->pBt==pBt );
61070 
61071  /* Move page iDbPage from its current location to page number iFreePage */
61072  TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
61073  iDbPage, iFreePage, iPtrPage, eType));
61074  rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
61075  if( rc!=SQLITE_OK ){
61076  return rc;
61077  }
61078  pDbPage->pgno = iFreePage;
61079 
61080  /* If pDbPage was a btree-page, then it may have child pages and/or cells
61081  ** that point to overflow pages. The pointer map entries for all these
61082  ** pages need to be changed.
61083  **
61084  ** If pDbPage is an overflow page, then the first 4 bytes may store a
61085  ** pointer to a subsequent overflow page. If this is the case, then
61086  ** the pointer map needs to be updated for the subsequent overflow page.
61087  */
61088  if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
61089  rc = setChildPtrmaps(pDbPage);
61090  if( rc!=SQLITE_OK ){
61091  return rc;
61092  }
61093  }else{
61094  Pgno nextOvfl = get4byte(pDbPage->aData);
61095  if( nextOvfl!=0 ){
61096  ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
61097  if( rc!=SQLITE_OK ){
61098  return rc;
61099  }
61100  }
61101  }
61102 
61103  /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
61104  ** that it points at iFreePage. Also fix the pointer map entry for
61105  ** iPtrPage.
61106  */
61107  if( eType!=PTRMAP_ROOTPAGE ){
61108  rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
61109  if( rc!=SQLITE_OK ){
61110  return rc;
61111  }
61112  rc = sqlite3PagerWrite(pPtrPage->pDbPage);
61113  if( rc!=SQLITE_OK ){
61114  releasePage(pPtrPage);
61115  return rc;
61116  }
61117  rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
61118  releasePage(pPtrPage);
61119  if( rc==SQLITE_OK ){
61120  ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
61121  }
61122  }
61123  return rc;
61124 }
61125 
61126 /* Forward declaration required by incrVacuumStep(). */
61127 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
61128 
61129 /*
61130 ** Perform a single step of an incremental-vacuum. If successful, return
61131 ** SQLITE_OK. If there is no work to do (and therefore no point in
61132 ** calling this function again), return SQLITE_DONE. Or, if an error
61133 ** occurs, return some other error code.
61134 **
61135 ** More specifically, this function attempts to re-organize the database so
61136 ** that the last page of the file currently in use is no longer in use.
61137 **
61138 ** Parameter nFin is the number of pages that this database would contain
61139 ** were this function called until it returns SQLITE_DONE.
61140 **
61141 ** If the bCommit parameter is non-zero, this function assumes that the
61142 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
61143 ** or an error. bCommit is passed true for an auto-vacuum-on-commit
61144 ** operation, or false for an incremental vacuum.
61145 */
61146 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
61147  Pgno nFreeList; /* Number of pages still on the free-list */
61148  int rc;
61149 
61150  assert( sqlite3_mutex_held(pBt->mutex) );
61151  assert( iLastPg>nFin );
61152 
61153  if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
61154  u8 eType;
61155  Pgno iPtrPage;
61156 
61157  nFreeList = get4byte(&pBt->pPage1->aData[36]);
61158  if( nFreeList==0 ){
61159  return SQLITE_DONE;
61160  }
61161 
61162  rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
61163  if( rc!=SQLITE_OK ){
61164  return rc;
61165  }
61166  if( eType==PTRMAP_ROOTPAGE ){
61167  return SQLITE_CORRUPT_BKPT;
61168  }
61169 
61170  if( eType==PTRMAP_FREEPAGE ){
61171  if( bCommit==0 ){
61172  /* Remove the page from the files free-list. This is not required
61173  ** if bCommit is non-zero. In that case, the free-list will be
61174  ** truncated to zero after this function returns, so it doesn't
61175  ** matter if it still contains some garbage entries.
61176  */
61177  Pgno iFreePg;
61178  MemPage *pFreePg;
61179  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
61180  if( rc!=SQLITE_OK ){
61181  return rc;
61182  }
61183  assert( iFreePg==iLastPg );
61184  releasePage(pFreePg);
61185  }
61186  } else {
61187  Pgno iFreePg; /* Index of free page to move pLastPg to */
61188  MemPage *pLastPg;
61189  u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
61190  Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
61191 
61192  rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
61193  if( rc!=SQLITE_OK ){
61194  return rc;
61195  }
61196 
61197  /* If bCommit is zero, this loop runs exactly once and page pLastPg
61198  ** is swapped with the first free page pulled off the free list.
61199  **
61200  ** On the other hand, if bCommit is greater than zero, then keep
61201  ** looping until a free-page located within the first nFin pages
61202  ** of the file is found.
61203  */
61204  if( bCommit==0 ){
61205  eMode = BTALLOC_LE;
61206  iNear = nFin;
61207  }
61208  do {
61209  MemPage *pFreePg;
61210  rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
61211  if( rc!=SQLITE_OK ){
61212  releasePage(pLastPg);
61213  return rc;
61214  }
61215  releasePage(pFreePg);
61216  }while( bCommit && iFreePg>nFin );
61217  assert( iFreePg<iLastPg );
61218 
61219  rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
61220  releasePage(pLastPg);
61221  if( rc!=SQLITE_OK ){
61222  return rc;
61223  }
61224  }
61225  }
61226 
61227  if( bCommit==0 ){
61228  do {
61229  iLastPg--;
61230  }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
61231  pBt->bDoTruncate = 1;
61232  pBt->nPage = iLastPg;
61233  }
61234  return SQLITE_OK;
61235 }
61236 
61237 /*
61238 ** The database opened by the first argument is an auto-vacuum database
61239 ** nOrig pages in size containing nFree free pages. Return the expected
61240 ** size of the database in pages following an auto-vacuum operation.
61241 */
61242 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
61243  int nEntry; /* Number of entries on one ptrmap page */
61244  Pgno nPtrmap; /* Number of PtrMap pages to be freed */
61245  Pgno nFin; /* Return value */
61246 
61247  nEntry = pBt->usableSize/5;
61248  nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
61249  nFin = nOrig - nFree - nPtrmap;
61250  if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
61251  nFin--;
61252  }
61253  while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
61254  nFin--;
61255  }
61256 
61257  return nFin;
61258 }
61259 
61260 /*
61261 ** A write-transaction must be opened before calling this function.
61262 ** It performs a single unit of work towards an incremental vacuum.
61263 **
61264 ** If the incremental vacuum is finished after this function has run,
61265 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
61266 ** SQLITE_OK is returned. Otherwise an SQLite error code.
61267 */
61269  int rc;
61270  BtShared *pBt = p->pBt;
61271 
61272  sqlite3BtreeEnter(p);
61274  if( !pBt->autoVacuum ){
61275  rc = SQLITE_DONE;
61276  }else{
61277  Pgno nOrig = btreePagecount(pBt);
61278  Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
61279  Pgno nFin = finalDbSize(pBt, nOrig, nFree);
61280 
61281  if( nOrig<nFin ){
61282  rc = SQLITE_CORRUPT_BKPT;
61283  }else if( nFree>0 ){
61284  rc = saveAllCursors(pBt, 0, 0);
61285  if( rc==SQLITE_OK ){
61287  rc = incrVacuumStep(pBt, nFin, nOrig, 0);
61288  }
61289  if( rc==SQLITE_OK ){
61290  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61291  put4byte(&pBt->pPage1->aData[28], pBt->nPage);
61292  }
61293  }else{
61294  rc = SQLITE_DONE;
61295  }
61296  }
61297  sqlite3BtreeLeave(p);
61298  return rc;
61299 }
61300 
61301 /*
61302 ** This routine is called prior to sqlite3PagerCommit when a transaction
61303 ** is committed for an auto-vacuum database.
61304 **
61305 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
61306 ** the database file should be truncated to during the commit process.
61307 ** i.e. the database has been reorganized so that only the first *pnTrunc
61308 ** pages are in use.
61309 */
61310 static int autoVacuumCommit(BtShared *pBt){
61311  int rc = SQLITE_OK;
61312  Pager *pPager = pBt->pPager;
61313  VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager); )
61314 
61315  assert( sqlite3_mutex_held(pBt->mutex) );
61317  assert(pBt->autoVacuum);
61318  if( !pBt->incrVacuum ){
61319  Pgno nFin; /* Number of pages in database after autovacuuming */
61320  Pgno nFree; /* Number of pages on the freelist initially */
61321  Pgno iFree; /* The next page to be freed */
61322  Pgno nOrig; /* Database size before freeing */
61323 
61324  nOrig = btreePagecount(pBt);
61325  if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
61326  /* It is not possible to create a database for which the final page
61327  ** is either a pointer-map page or the pending-byte page. If one
61328  ** is encountered, this indicates corruption.
61329  */
61330  return SQLITE_CORRUPT_BKPT;
61331  }
61332 
61333  nFree = get4byte(&pBt->pPage1->aData[36]);
61334  nFin = finalDbSize(pBt, nOrig, nFree);
61335  if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
61336  if( nFin<nOrig ){
61337  rc = saveAllCursors(pBt, 0, 0);
61338  }
61339  for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
61340  rc = incrVacuumStep(pBt, nFin, iFree, 1);
61341  }
61342  if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
61343  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61344  put4byte(&pBt->pPage1->aData[32], 0);
61345  put4byte(&pBt->pPage1->aData[36], 0);
61346  put4byte(&pBt->pPage1->aData[28], nFin);
61347  pBt->bDoTruncate = 1;
61348  pBt->nPage = nFin;
61349  }
61350  if( rc!=SQLITE_OK ){
61351  sqlite3PagerRollback(pPager);
61352  }
61353  }
61354 
61355  assert( nRef>=sqlite3PagerRefcount(pPager) );
61356  return rc;
61357 }
61358 
61359 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
61360 # define setChildPtrmaps(x) SQLITE_OK
61361 #endif
61362 
61363 /*
61364 ** This routine does the first phase of a two-phase commit. This routine
61365 ** causes a rollback journal to be created (if it does not already exist)
61366 ** and populated with enough information so that if a power loss occurs
61367 ** the database can be restored to its original state by playing back
61368 ** the journal. Then the contents of the journal are flushed out to
61369 ** the disk. After the journal is safely on oxide, the changes to the
61370 ** database are written into the database file and flushed to oxide.
61371 ** At the end of this call, the rollback journal still exists on the
61372 ** disk and we are still holding all locks, so the transaction has not
61373 ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
61374 ** commit process.
61375 **
61376 ** This call is a no-op if no write-transaction is currently active on pBt.
61377 **
61378 ** Otherwise, sync the database file for the btree pBt. zMaster points to
61379 ** the name of a master journal file that should be written into the
61380 ** individual journal file, or is NULL, indicating no master journal file
61381 ** (single database transaction).
61382 **
61383 ** When this is called, the master journal should already have been
61384 ** created, populated with this journal pointer and synced to disk.
61385 **
61386 ** Once this is routine has returned, the only thing required to commit
61387 ** the write-transaction for this database file is to delete the journal.
61388 */
61389 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
61390  int rc = SQLITE_OK;
61391  if( p->inTrans==TRANS_WRITE ){
61392  BtShared *pBt = p->pBt;
61393  sqlite3BtreeEnter(p);
61394 #ifndef SQLITE_OMIT_AUTOVACUUM
61395  if( pBt->autoVacuum ){
61396  rc = autoVacuumCommit(pBt);
61397  if( rc!=SQLITE_OK ){
61398  sqlite3BtreeLeave(p);
61399  return rc;
61400  }
61401  }
61402  if( pBt->bDoTruncate ){
61404  }
61405 #endif
61406  rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
61407  sqlite3BtreeLeave(p);
61408  }
61409  return rc;
61410 }
61411 
61412 /*
61413 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
61414 ** at the conclusion of a transaction.
61415 */
61416 static void btreeEndTransaction(Btree *p){
61417  BtShared *pBt = p->pBt;
61418  sqlite3 *db = p->db;
61419  assert( sqlite3BtreeHoldsMutex(p) );
61420 
61421 #ifndef SQLITE_OMIT_AUTOVACUUM
61422  pBt->bDoTruncate = 0;
61423 #endif
61424  if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
61425  /* If there are other active statements that belong to this database
61426  ** handle, downgrade to a read-only transaction. The other statements
61427  ** may still be reading from the database. */
61429  p->inTrans = TRANS_READ;
61430  }else{
61431  /* If the handle had any kind of transaction open, decrement the
61432  ** transaction count of the shared btree. If the transaction count
61433  ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
61434  ** call below will unlock the pager. */
61435  if( p->inTrans!=TRANS_NONE ){
61437  pBt->nTransaction--;
61438  if( 0==pBt->nTransaction ){
61439  pBt->inTransaction = TRANS_NONE;
61440  }
61441  }
61442 
61443  /* Set the current transaction state to TRANS_NONE and unlock the
61444  ** pager if this call closed the only read or write transaction. */
61445  p->inTrans = TRANS_NONE;
61446  unlockBtreeIfUnused(pBt);
61447  }
61448 
61449  btreeIntegrity(p);
61450 }
61451 
61452 /*
61453 ** Commit the transaction currently in progress.
61454 **
61455 ** This routine implements the second phase of a 2-phase commit. The
61456 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
61457 ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
61458 ** routine did all the work of writing information out to disk and flushing the
61459 ** contents so that they are written onto the disk platter. All this
61460 ** routine has to do is delete or truncate or zero the header in the
61461 ** the rollback journal (which causes the transaction to commit) and
61462 ** drop locks.
61463 **
61464 ** Normally, if an error occurs while the pager layer is attempting to
61465 ** finalize the underlying journal file, this function returns an error and
61466 ** the upper layer will attempt a rollback. However, if the second argument
61467 ** is non-zero then this b-tree transaction is part of a multi-file
61468 ** transaction. In this case, the transaction has already been committed
61469 ** (by deleting a master journal file) and the caller will ignore this
61470 ** functions return code. So, even if an error occurs in the pager layer,
61471 ** reset the b-tree objects internal state to indicate that the write
61472 ** transaction has been closed. This is quite safe, as the pager will have
61473 ** transitioned to the error state.
61474 **
61475 ** This will release the write lock on the database file. If there
61476 ** are no active cursors, it also releases the read lock.
61477 */
61479 
61480  if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
61481  sqlite3BtreeEnter(p);
61482  btreeIntegrity(p);
61483 
61484  /* If the handle has a write-transaction open, commit the shared-btrees
61485  ** transaction and set the shared state to TRANS_READ.
61486  */
61487  if( p->inTrans==TRANS_WRITE ){
61488  int rc;
61489  BtShared *pBt = p->pBt;
61490  assert( pBt->inTransaction==TRANS_WRITE );
61491  assert( pBt->nTransaction>0 );
61493  if( rc!=SQLITE_OK && bCleanup==0 ){
61494  sqlite3BtreeLeave(p);
61495  return rc;
61496  }
61497  p->iDataVersion--; /* Compensate for pPager->iDataVersion++; */
61498  pBt->inTransaction = TRANS_READ;
61499  btreeClearHasContent(pBt);
61500  }
61501 
61503  sqlite3BtreeLeave(p);
61504  return SQLITE_OK;
61505 }
61506 
61507 /*
61508 ** Do both phases of a commit.
61509 */
61511  int rc;
61512  sqlite3BtreeEnter(p);
61513  rc = sqlite3BtreeCommitPhaseOne(p, 0);
61514  if( rc==SQLITE_OK ){
61515  rc = sqlite3BtreeCommitPhaseTwo(p, 0);
61516  }
61517  sqlite3BtreeLeave(p);
61518  return rc;
61519 }
61520 
61521 /*
61522 ** This routine sets the state to CURSOR_FAULT and the error
61523 ** code to errCode for every cursor on any BtShared that pBtree
61524 ** references. Or if the writeOnly flag is set to 1, then only
61525 ** trip write cursors and leave read cursors unchanged.
61526 **
61527 ** Every cursor is a candidate to be tripped, including cursors
61528 ** that belong to other database connections that happen to be
61529 ** sharing the cache with pBtree.
61530 **
61531 ** This routine gets called when a rollback occurs. If the writeOnly
61532 ** flag is true, then only write-cursors need be tripped - read-only
61533 ** cursors save their current positions so that they may continue
61534 ** following the rollback. Or, if writeOnly is false, all cursors are
61535 ** tripped. In general, writeOnly is false if the transaction being
61536 ** rolled back modified the database schema. In this case b-tree root
61537 ** pages may be moved or deleted from the database altogether, making
61538 ** it unsafe for read cursors to continue.
61539 **
61540 ** If the writeOnly flag is true and an error is encountered while
61541 ** saving the current position of a read-only cursor, all cursors,
61542 ** including all read-cursors are tripped.
61543 **
61544 ** SQLITE_OK is returned if successful, or if an error occurs while
61545 ** saving a cursor position, an SQLite error code.
61546 */
61547 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
61548  BtCursor *p;
61549  int rc = SQLITE_OK;
61550 
61551  assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
61552  if( pBtree ){
61553  sqlite3BtreeEnter(pBtree);
61554  for(p=pBtree->pBt->pCursor; p; p=p->pNext){
61555  int i;
61556  if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
61557  if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
61558  rc = saveCursorPosition(p);
61559  if( rc!=SQLITE_OK ){
61560  (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
61561  break;
61562  }
61563  }
61564  }else{
61566  p->eState = CURSOR_FAULT;
61567  p->skipNext = errCode;
61568  }
61569  for(i=0; i<=p->iPage; i++){
61570  releasePage(p->apPage[i]);
61571  p->apPage[i] = 0;
61572  }
61573  }
61574  sqlite3BtreeLeave(pBtree);
61575  }
61576  return rc;
61577 }
61578 
61579 /*
61580 ** Rollback the transaction in progress.
61581 **
61582 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
61583 ** Only write cursors are tripped if writeOnly is true but all cursors are
61584 ** tripped if writeOnly is false. Any attempt to use
61585 ** a tripped cursor will result in an error.
61586 **
61587 ** This will release the write lock on the database file. If there
61588 ** are no active cursors, it also releases the read lock.
61589 */
61590 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
61591  int rc;
61592  BtShared *pBt = p->pBt;
61593  MemPage *pPage1;
61594 
61595  assert( writeOnly==1 || writeOnly==0 );
61596  assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
61597  sqlite3BtreeEnter(p);
61598  if( tripCode==SQLITE_OK ){
61599  rc = tripCode = saveAllCursors(pBt, 0, 0);
61600  if( rc ) writeOnly = 0;
61601  }else{
61602  rc = SQLITE_OK;
61603  }
61604  if( tripCode ){
61605  int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
61606  assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
61607  if( rc2!=SQLITE_OK ) rc = rc2;
61608  }
61609  btreeIntegrity(p);
61610 
61611  if( p->inTrans==TRANS_WRITE ){
61612  int rc2;
61613 
61614  assert( TRANS_WRITE==pBt->inTransaction );
61615  rc2 = sqlite3PagerRollback(pBt->pPager);
61616  if( rc2!=SQLITE_OK ){
61617  rc = rc2;
61618  }
61619 
61620  /* The rollback may have destroyed the pPage1->aData value. So
61621  ** call btreeGetPage() on page 1 again to make
61622  ** sure pPage1->aData is set correctly. */
61623  if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
61624  int nPage = get4byte(28+(u8*)pPage1->aData);
61625  testcase( nPage==0 );
61626  if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
61627  testcase( pBt->nPage!=nPage );
61628  pBt->nPage = nPage;
61629  releasePage(pPage1);
61630  }
61631  assert( countValidCursors(pBt, 1)==0 );
61632  pBt->inTransaction = TRANS_READ;
61633  btreeClearHasContent(pBt);
61634  }
61635 
61637  sqlite3BtreeLeave(p);
61638  return rc;
61639 }
61640 
61641 /*
61642 ** Start a statement subtransaction. The subtransaction can be rolled
61643 ** back independently of the main transaction. You must start a transaction
61644 ** before starting a subtransaction. The subtransaction is ended automatically
61645 ** if the main transaction commits or rolls back.
61646 **
61647 ** Statement subtransactions are used around individual SQL statements
61648 ** that are contained within a BEGIN...COMMIT block. If a constraint
61649 ** error occurs within the statement, the effect of that one statement
61650 ** can be rolled back without having to rollback the entire transaction.
61651 **
61652 ** A statement sub-transaction is implemented as an anonymous savepoint. The
61653 ** value passed as the second parameter is the total number of savepoints,
61654 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
61655 ** are no active savepoints and no other statement-transactions open,
61656 ** iStatement is 1. This anonymous savepoint can be released or rolled back
61657 ** using the sqlite3BtreeSavepoint() function.
61658 */
61660  int rc;
61661  BtShared *pBt = p->pBt;
61662  sqlite3BtreeEnter(p);
61663  assert( p->inTrans==TRANS_WRITE );
61664  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
61665  assert( iStatement>0 );
61666  assert( iStatement>p->db->nSavepoint );
61667  assert( pBt->inTransaction==TRANS_WRITE );
61668  /* At the pager level, a statement transaction is a savepoint with
61669  ** an index greater than all savepoints created explicitly using
61670  ** SQL statements. It is illegal to open, release or rollback any
61671  ** such savepoints while the statement transaction savepoint is active.
61672  */
61673  rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
61674  sqlite3BtreeLeave(p);
61675  return rc;
61676 }
61677 
61678 /*
61679 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
61680 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
61681 ** savepoint identified by parameter iSavepoint, depending on the value
61682 ** of op.
61683 **
61684 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
61685 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
61686 ** contents of the entire transaction are rolled back. This is different
61687 ** from a normal transaction rollback, as no locks are released and the
61688 ** transaction remains open.
61689 */
61690 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
61691  int rc = SQLITE_OK;
61692  if( p && p->inTrans==TRANS_WRITE ){
61693  BtShared *pBt = p->pBt;
61695  assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
61696  sqlite3BtreeEnter(p);
61697  rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
61698  if( rc==SQLITE_OK ){
61699  if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
61700  pBt->nPage = 0;
61701  }
61702  rc = newDatabase(pBt);
61703  pBt->nPage = get4byte(28 + pBt->pPage1->aData);
61704 
61705  /* The database size was written into the offset 28 of the header
61706  ** when the transaction started, so we know that the value at offset
61707  ** 28 is nonzero. */
61708  assert( pBt->nPage>0 );
61709  }
61710  sqlite3BtreeLeave(p);
61711  }
61712  return rc;
61713 }
61714 
61715 /*
61716 ** Create a new cursor for the BTree whose root is on the page
61717 ** iTable. If a read-only cursor is requested, it is assumed that
61718 ** the caller already has at least a read-only transaction open
61719 ** on the database already. If a write-cursor is requested, then
61720 ** the caller is assumed to have an open write transaction.
61721 **
61722 ** If the BTREE_WRCSR bit of wrFlag is clear, then the cursor can only
61723 ** be used for reading. If the BTREE_WRCSR bit is set, then the cursor
61724 ** can be used for reading or for writing if other conditions for writing
61725 ** are also met. These are the conditions that must be met in order
61726 ** for writing to be allowed:
61727 **
61728 ** 1: The cursor must have been opened with wrFlag containing BTREE_WRCSR
61729 **
61730 ** 2: Other database connections that share the same pager cache
61731 ** but which are not in the READ_UNCOMMITTED state may not have
61732 ** cursors open with wrFlag==0 on the same table. Otherwise
61733 ** the changes made by this write cursor would be visible to
61734 ** the read cursors in the other database connection.
61735 **
61736 ** 3: The database must be writable (not on read-only media)
61737 **
61738 ** 4: There must be an active transaction.
61739 **
61740 ** The BTREE_FORDELETE bit of wrFlag may optionally be set if BTREE_WRCSR
61741 ** is set. If FORDELETE is set, that is a hint to the implementation that
61742 ** this cursor will only be used to seek to and delete entries of an index
61743 ** as part of a larger DELETE statement. The FORDELETE hint is not used by
61744 ** this implementation. But in a hypothetical alternative storage engine
61745 ** in which index entries are automatically deleted when corresponding table
61746 ** rows are deleted, the FORDELETE flag is a hint that all SEEK and DELETE
61747 ** operations on this cursor can be no-ops and all READ operations can
61748 ** return a null row (2-bytes: 0x01 0x00).
61749 **
61750 ** No checking is done to make sure that page iTable really is the
61751 ** root page of a b-tree. If it is not, then the cursor acquired
61752 ** will not work correctly.
61753 **
61754 ** It is assumed that the sqlite3BtreeCursorZero() has been called
61755 ** on pCur to initialize the memory space prior to invoking this routine.
61756 */
61757 static int btreeCursor(
61758  Btree *p, /* The btree */
61759  int iTable, /* Root page of table to open */
61760  int wrFlag, /* 1 to write. 0 read-only */
61761  struct KeyInfo *pKeyInfo, /* First arg to comparison function */
61762  BtCursor *pCur /* Space for new cursor */
61763 ){
61764  BtShared *pBt = p->pBt; /* Shared b-tree handle */
61765  BtCursor *pX; /* Looping over other all cursors */
61766 
61767  assert( sqlite3BtreeHoldsMutex(p) );
61768  assert( wrFlag==0
61769  || wrFlag==BTREE_WRCSR
61770  || wrFlag==(BTREE_WRCSR|BTREE_FORDELETE)
61771  );
61772 
61773  /* The following assert statements verify that if this is a sharable
61774  ** b-tree database, the connection is holding the required table locks,
61775  ** and that no other connection has any open cursor that conflicts with
61776  ** this lock. */
61777  assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, (wrFlag?2:1)) );
61778  assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
61779 
61780  /* Assert that the caller has opened the required transaction. */
61781  assert( p->inTrans>TRANS_NONE );
61782  assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
61783  assert( pBt->pPage1 && pBt->pPage1->aData );
61784  assert( wrFlag==0 || (pBt->btsFlags & BTS_READ_ONLY)==0 );
61785 
61786  if( wrFlag ){
61787  allocateTempSpace(pBt);
61788  if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM_BKPT;
61789  }
61790  if( iTable==1 && btreePagecount(pBt)==0 ){
61791  assert( wrFlag==0 );
61792  iTable = 0;
61793  }
61794 
61795  /* Now that no other errors can occur, finish filling in the BtCursor
61796  ** variables and link the cursor into the BtShared list. */
61797  pCur->pgnoRoot = (Pgno)iTable;
61798  pCur->iPage = -1;
61799  pCur->pKeyInfo = pKeyInfo;
61800  pCur->pBtree = p;
61801  pCur->pBt = pBt;
61802  pCur->curFlags = wrFlag ? BTCF_WriteFlag : 0;
61803  pCur->curPagerFlags = wrFlag ? 0 : PAGER_GET_READONLY;
61804  /* If there are two or more cursors on the same btree, then all such
61805  ** cursors *must* have the BTCF_Multiple flag set. */
61806  for(pX=pBt->pCursor; pX; pX=pX->pNext){
61807  if( pX->pgnoRoot==(Pgno)iTable ){
61808  pX->curFlags |= BTCF_Multiple;
61809  pCur->curFlags |= BTCF_Multiple;
61810  }
61811  }
61812  pCur->pNext = pBt->pCursor;
61813  pBt->pCursor = pCur;
61814  pCur->eState = CURSOR_INVALID;
61815  return SQLITE_OK;
61816 }
61818  Btree *p, /* The btree */
61819  int iTable, /* Root page of table to open */
61820  int wrFlag, /* 1 to write. 0 read-only */
61821  struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
61822  BtCursor *pCur /* Write new cursor here */
61823 ){
61824  int rc;
61825  if( iTable<1 ){
61826  rc = SQLITE_CORRUPT_BKPT;
61827  }else{
61828  sqlite3BtreeEnter(p);
61829  rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
61830  sqlite3BtreeLeave(p);
61831  }
61832  return rc;
61833 }
61834 
61835 /*
61836 ** Return the size of a BtCursor object in bytes.
61837 **
61838 ** This interfaces is needed so that users of cursors can preallocate
61839 ** sufficient storage to hold a cursor. The BtCursor object is opaque
61840 ** to users so they cannot do the sizeof() themselves - they must call
61841 ** this routine.
61842 */
61844  return ROUND8(sizeof(BtCursor));
61845 }
61846 
61847 /*
61848 ** Initialize memory that will be converted into a BtCursor object.
61849 **
61850 ** The simple approach here would be to memset() the entire object
61851 ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
61852 ** do not need to be zeroed and they are large, so we can save a lot
61853 ** of run-time by skipping the initialization of those elements.
61854 */
61856  memset(p, 0, offsetof(BtCursor, iPage));
61857 }
61858 
61859 /*
61860 ** Close a cursor. The read lock on the database file is released
61861 ** when the last cursor is closed.
61862 */
61864  Btree *pBtree = pCur->pBtree;
61865  if( pBtree ){
61866  int i;
61867  BtShared *pBt = pCur->pBt;
61868  sqlite3BtreeEnter(pBtree);
61870  assert( pBt->pCursor!=0 );
61871  if( pBt->pCursor==pCur ){
61872  pBt->pCursor = pCur->pNext;
61873  }else{
61874  BtCursor *pPrev = pBt->pCursor;
61875  do{
61876  if( pPrev->pNext==pCur ){
61877  pPrev->pNext = pCur->pNext;
61878  break;
61879  }
61880  pPrev = pPrev->pNext;
61881  }while( ALWAYS(pPrev) );
61882  }
61883  for(i=0; i<=pCur->iPage; i++){
61884  releasePage(pCur->apPage[i]);
61885  }
61886  unlockBtreeIfUnused(pBt);
61887  sqlite3_free(pCur->aOverflow);
61888  /* sqlite3_free(pCur); */
61889  sqlite3BtreeLeave(pBtree);
61890  }
61891  return SQLITE_OK;
61892 }
61893 
61894 /*
61895 ** Make sure the BtCursor* given in the argument has a valid
61896 ** BtCursor.info structure. If it is not already valid, call
61897 ** btreeParseCell() to fill it in.
61898 **
61899 ** BtCursor.info is a cache of the information in the current cell.
61900 ** Using this cache reduces the number of calls to btreeParseCell().
61901 */
61902 #ifndef NDEBUG
61903  static void assertCellInfo(BtCursor *pCur){
61904  CellInfo info;
61905  int iPage = pCur->iPage;
61906  memset(&info, 0, sizeof(info));
61907  btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
61908  assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
61909  }
61910 #else
61911  #define assertCellInfo(x)
61912 #endif
61914  if( pCur->info.nSize==0 ){
61915  int iPage = pCur->iPage;
61916  pCur->curFlags |= BTCF_ValidNKey;
61917  btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
61918  }else{
61919  assertCellInfo(pCur);
61920  }
61921 }
61922 
61923 #ifndef NDEBUG /* The next routine used only within assert() statements */
61924 /*
61925 ** Return true if the given BtCursor is valid. A valid cursor is one
61926 ** that is currently pointing to a row in a (non-empty) table.
61927 ** This is a verification routine is used only within assert() statements.
61928 */
61929 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
61930  return pCur && pCur->eState==CURSOR_VALID;
61931 }
61932 #endif /* NDEBUG */
61933 
61934 /*
61935 ** Set *pSize to the size of the buffer needed to hold the value of
61936 ** the key for the current entry. If the cursor is not pointing
61937 ** to a valid entry, *pSize is set to 0.
61938 **
61939 ** For a table with the INTKEY flag set, this routine returns the key
61940 ** itself, not the number of bytes in the key.
61941 **
61942 ** The caller must position the cursor prior to invoking this routine.
61943 **
61944 ** This routine cannot fail. It always returns SQLITE_OK.
61945 */
61947  assert( cursorHoldsMutex(pCur) );
61948  assert( pCur->eState==CURSOR_VALID );
61949  getCellInfo(pCur);
61950  *pSize = pCur->info.nKey;
61951  return SQLITE_OK;
61952 }
61953 
61954 /*
61955 ** Set *pSize to the number of bytes of data in the entry the
61956 ** cursor currently points to.
61957 **
61958 ** The caller must guarantee that the cursor is pointing to a non-NULL
61959 ** valid entry. In other words, the calling procedure must guarantee
61960 ** that the cursor has Cursor.eState==CURSOR_VALID.
61961 **
61962 ** Failure is not possible. This function always returns SQLITE_OK.
61963 ** It might just as well be a procedure (returning void) but we continue
61964 ** to return an integer result code for historical reasons.
61965 */
61967  assert( cursorOwnsBtShared(pCur) );
61968  assert( pCur->eState==CURSOR_VALID );
61969  assert( pCur->iPage>=0 );
61970  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
61971  assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
61972  getCellInfo(pCur);
61973  *pSize = pCur->info.nPayload;
61974  return SQLITE_OK;
61975 }
61976 
61977 /*
61978 ** Given the page number of an overflow page in the database (parameter
61979 ** ovfl), this function finds the page number of the next page in the
61980 ** linked list of overflow pages. If possible, it uses the auto-vacuum
61981 ** pointer-map data instead of reading the content of page ovfl to do so.
61982 **
61983 ** If an error occurs an SQLite error code is returned. Otherwise:
61984 **
61985 ** The page number of the next overflow page in the linked list is
61986 ** written to *pPgnoNext. If page ovfl is the last page in its linked
61987 ** list, *pPgnoNext is set to zero.
61988 **
61989 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
61990 ** to page number pOvfl was obtained, then *ppPage is set to point to that
61991 ** reference. It is the responsibility of the caller to call releasePage()
61992 ** on *ppPage to free the reference. In no reference was obtained (because
61993 ** the pointer-map was used to obtain the value for *pPgnoNext), then
61994 ** *ppPage is set to zero.
61995 */
61996 static int getOverflowPage(
61997  BtShared *pBt, /* The database file */
61998  Pgno ovfl, /* Current overflow page number */
61999  MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
62000  Pgno *pPgnoNext /* OUT: Next overflow page number */
62001 ){
62002  Pgno next = 0;
62003  MemPage *pPage = 0;
62004  int rc = SQLITE_OK;
62005 
62006  assert( sqlite3_mutex_held(pBt->mutex) );
62007  assert(pPgnoNext);
62008 
62009 #ifndef SQLITE_OMIT_AUTOVACUUM
62010  /* Try to find the next page in the overflow list using the
62011  ** autovacuum pointer-map pages. Guess that the next page in
62012  ** the overflow list is page number (ovfl+1). If that guess turns
62013  ** out to be wrong, fall back to loading the data of page
62014  ** number ovfl to determine the next page number.
62015  */
62016  if( pBt->autoVacuum ){
62017  Pgno pgno;
62018  Pgno iGuess = ovfl+1;
62019  u8 eType;
62020 
62021  while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
62022  iGuess++;
62023  }
62024 
62025  if( iGuess<=btreePagecount(pBt) ){
62026  rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
62027  if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
62028  next = iGuess;
62029  rc = SQLITE_DONE;
62030  }
62031  }
62032  }
62033 #endif
62034 
62035  assert( next==0 || rc==SQLITE_DONE );
62036  if( rc==SQLITE_OK ){
62037  rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
62038  assert( rc==SQLITE_OK || pPage==0 );
62039  if( rc==SQLITE_OK ){
62040  next = get4byte(pPage->aData);
62041  }
62042  }
62043 
62044  *pPgnoNext = next;
62045  if( ppPage ){
62046  *ppPage = pPage;
62047  }else{
62048  releasePage(pPage);
62049  }
62050  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
62051 }
62052 
62053 /*
62054 ** Copy data from a buffer to a page, or from a page to a buffer.
62055 **
62056 ** pPayload is a pointer to data stored on database page pDbPage.
62057 ** If argument eOp is false, then nByte bytes of data are copied
62058 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
62059 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
62060 ** of data are copied from the buffer pBuf to pPayload.
62061 **
62062 ** SQLITE_OK is returned on success, otherwise an error code.
62063 */
62064 static int copyPayload(
62065  void *pPayload, /* Pointer to page data */
62066  void *pBuf, /* Pointer to buffer */
62067  int nByte, /* Number of bytes to copy */
62068  int eOp, /* 0 -> copy from page, 1 -> copy to page */
62069  DbPage *pDbPage /* Page containing pPayload */
62070 ){
62071  if( eOp ){
62072  /* Copy data from buffer to page (a write operation) */
62073  int rc = sqlite3PagerWrite(pDbPage);
62074  if( rc!=SQLITE_OK ){
62075  return rc;
62076  }
62077  memcpy(pPayload, pBuf, nByte);
62078  }else{
62079  /* Copy data from page to buffer (a read operation) */
62080  memcpy(pBuf, pPayload, nByte);
62081  }
62082  return SQLITE_OK;
62083 }
62084 
62085 /*
62086 ** This function is used to read or overwrite payload information
62087 ** for the entry that the pCur cursor is pointing to. The eOp
62088 ** argument is interpreted as follows:
62089 **
62090 ** 0: The operation is a read. Populate the overflow cache.
62091 ** 1: The operation is a write. Populate the overflow cache.
62092 ** 2: The operation is a read. Do not populate the overflow cache.
62093 **
62094 ** A total of "amt" bytes are read or written beginning at "offset".
62095 ** Data is read to or from the buffer pBuf.
62096 **
62097 ** The content being read or written might appear on the main page
62098 ** or be scattered out on multiple overflow pages.
62099 **
62100 ** If the current cursor entry uses one or more overflow pages and the
62101 ** eOp argument is not 2, this function may allocate space for and lazily
62102 ** populates the overflow page-list cache array (BtCursor.aOverflow).
62103 ** Subsequent calls use this cache to make seeking to the supplied offset
62104 ** more efficient.
62105 **
62106 ** Once an overflow page-list cache has been allocated, it may be
62107 ** invalidated if some other cursor writes to the same table, or if
62108 ** the cursor is moved to a different row. Additionally, in auto-vacuum
62109 ** mode, the following events may invalidate an overflow page-list cache.
62110 **
62111 ** * An incremental vacuum,
62112 ** * A commit in auto_vacuum="full" mode,
62113 ** * Creating a table (may require moving an overflow page).
62114 */
62115 static int accessPayload(
62116  BtCursor *pCur, /* Cursor pointing to entry to read from */
62117  u32 offset, /* Begin reading this far into payload */
62118  u32 amt, /* Read this many bytes */
62119  unsigned char *pBuf, /* Write the bytes into this buffer */
62120  int eOp /* zero to read. non-zero to write. */
62121 ){
62122  unsigned char *aPayload;
62123  int rc = SQLITE_OK;
62124  int iIdx = 0;
62125  MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
62126  BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
62127 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62128  unsigned char * const pBufStart = pBuf;
62129  int bEnd; /* True if reading to end of data */
62130 #endif
62131 
62132  assert( pPage );
62133  assert( pCur->eState==CURSOR_VALID );
62134  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62135  assert( cursorHoldsMutex(pCur) );
62136  assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
62137 
62138  getCellInfo(pCur);
62139  aPayload = pCur->info.pPayload;
62140 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62141  bEnd = offset+amt==pCur->info.nPayload;
62142 #endif
62143  assert( offset+amt <= pCur->info.nPayload );
62144 
62145  assert( aPayload > pPage->aData );
62146  if( (uptr)(aPayload - pPage->aData) > (pBt->usableSize - pCur->info.nLocal) ){
62147  /* Trying to read or write past the end of the data is an error. The
62148  ** conditional above is really:
62149  ** &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
62150  ** but is recast into its current form to avoid integer overflow problems
62151  */
62152  return SQLITE_CORRUPT_BKPT;
62153  }
62154 
62155  /* Check if data must be read/written to/from the btree page itself. */
62156  if( offset<pCur->info.nLocal ){
62157  int a = amt;
62158  if( a+offset>pCur->info.nLocal ){
62159  a = pCur->info.nLocal - offset;
62160  }
62161  rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
62162  offset = 0;
62163  pBuf += a;
62164  amt -= a;
62165  }else{
62166  offset -= pCur->info.nLocal;
62167  }
62168 
62169 
62170  if( rc==SQLITE_OK && amt>0 ){
62171  const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
62172  Pgno nextPage;
62173 
62174  nextPage = get4byte(&aPayload[pCur->info.nLocal]);
62175 
62176  /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
62177  ** Except, do not allocate aOverflow[] for eOp==2.
62178  **
62179  ** The aOverflow[] array is sized at one entry for each overflow page
62180  ** in the overflow chain. The page number of the first overflow page is
62181  ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
62182  ** means "not yet known" (the cache is lazily populated).
62183  */
62184  if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
62185  int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
62186  if( nOvfl>pCur->nOvflAlloc ){
62187  Pgno *aNew = (Pgno*)sqlite3Realloc(
62188  pCur->aOverflow, nOvfl*2*sizeof(Pgno)
62189  );
62190  if( aNew==0 ){
62191  rc = SQLITE_NOMEM_BKPT;
62192  }else{
62193  pCur->nOvflAlloc = nOvfl*2;
62194  pCur->aOverflow = aNew;
62195  }
62196  }
62197  if( rc==SQLITE_OK ){
62198  memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
62199  pCur->curFlags |= BTCF_ValidOvfl;
62200  }
62201  }
62202 
62203  /* If the overflow page-list cache has been allocated and the
62204  ** entry for the first required overflow page is valid, skip
62205  ** directly to it.
62206  */
62207  if( (pCur->curFlags & BTCF_ValidOvfl)!=0
62208  && pCur->aOverflow[offset/ovflSize]
62209  ){
62210  iIdx = (offset/ovflSize);
62211  nextPage = pCur->aOverflow[iIdx];
62212  offset = (offset%ovflSize);
62213  }
62214 
62215  for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
62216 
62217  /* If required, populate the overflow page-list cache. */
62218  if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
62219  assert( pCur->aOverflow[iIdx]==0
62220  || pCur->aOverflow[iIdx]==nextPage
62221  || CORRUPT_DB );
62222  pCur->aOverflow[iIdx] = nextPage;
62223  }
62224 
62225  if( offset>=ovflSize ){
62226  /* The only reason to read this page is to obtain the page
62227  ** number for the next page in the overflow chain. The page
62228  ** data is not required. So first try to lookup the overflow
62229  ** page-list cache, if any, then fall back to the getOverflowPage()
62230  ** function.
62231  **
62232  ** Note that the aOverflow[] array must be allocated because eOp!=2
62233  ** here. If eOp==2, then offset==0 and this branch is never taken.
62234  */
62235  assert( eOp!=2 );
62236  assert( pCur->curFlags & BTCF_ValidOvfl );
62237  assert( pCur->pBtree->db==pBt->db );
62238  if( pCur->aOverflow[iIdx+1] ){
62239  nextPage = pCur->aOverflow[iIdx+1];
62240  }else{
62241  rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
62242  }
62243  offset -= ovflSize;
62244  }else{
62245  /* Need to read this page properly. It contains some of the
62246  ** range of data that is being read (eOp==0) or written (eOp!=0).
62247  */
62248 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62249  sqlite3_file *fd;
62250 #endif
62251  int a = amt;
62252  if( a + offset > ovflSize ){
62253  a = ovflSize - offset;
62254  }
62255 
62256 #ifdef SQLITE_DIRECT_OVERFLOW_READ
62257  /* If all the following are true:
62258  **
62259  ** 1) this is a read operation, and
62260  ** 2) data is required from the start of this overflow page, and
62261  ** 3) the database is file-backed, and
62262  ** 4) there is no open write-transaction, and
62263  ** 5) the database is not a WAL database,
62264  ** 6) all data from the page is being read.
62265  ** 7) at least 4 bytes have already been read into the output buffer
62266  **
62267  ** then data can be read directly from the database file into the
62268  ** output buffer, bypassing the page-cache altogether. This speeds
62269  ** up loading large records that span many overflow pages.
62270  */
62271  if( (eOp&0x01)==0 /* (1) */
62272  && offset==0 /* (2) */
62273  && (bEnd || a==ovflSize) /* (6) */
62274  && pBt->inTransaction==TRANS_READ /* (4) */
62275  && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
62276  && pBt->pPage1->aData[19]==0x01 /* (5) */
62277  && &pBuf[-4]>=pBufStart /* (7) */
62278  ){
62279  u8 aSave[4];
62280  u8 *aWrite = &pBuf[-4];
62281  assert( aWrite>=pBufStart ); /* hence (7) */
62282  memcpy(aSave, aWrite, 4);
62283  rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
62284  nextPage = get4byte(aWrite);
62285  memcpy(aWrite, aSave, 4);
62286  }else
62287 #endif
62288 
62289  {
62290  DbPage *pDbPage;
62291  rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage,
62292  ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
62293  );
62294  if( rc==SQLITE_OK ){
62295  aPayload = sqlite3PagerGetData(pDbPage);
62296  nextPage = get4byte(aPayload);
62297  rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
62298  sqlite3PagerUnref(pDbPage);
62299  offset = 0;
62300  }
62301  }
62302  amt -= a;
62303  pBuf += a;
62304  }
62305  }
62306  }
62307 
62308  if( rc==SQLITE_OK && amt>0 ){
62309  return SQLITE_CORRUPT_BKPT;
62310  }
62311  return rc;
62312 }
62313 
62314 /*
62315 ** Read part of the key associated with cursor pCur. Exactly
62316 ** "amt" bytes will be transferred into pBuf[]. The transfer
62317 ** begins at "offset".
62318 **
62319 ** The caller must ensure that pCur is pointing to a valid row
62320 ** in the table.
62321 **
62322 ** Return SQLITE_OK on success or an error code if anything goes
62323 ** wrong. An error is returned if "offset+amt" is larger than
62324 ** the available payload.
62325 */
62326 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62327  assert( cursorHoldsMutex(pCur) );
62328  assert( pCur->eState==CURSOR_VALID );
62329  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62330  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62331  return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
62332 }
62333 
62334 /*
62335 ** Read part of the data associated with cursor pCur. Exactly
62336 ** "amt" bytes will be transfered into pBuf[]. The transfer
62337 ** begins at "offset".
62338 **
62339 ** Return SQLITE_OK on success or an error code if anything goes
62340 ** wrong. An error is returned if "offset+amt" is larger than
62341 ** the available payload.
62342 */
62343 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
62344  int rc;
62345 
62346 #ifndef SQLITE_OMIT_INCRBLOB
62347  if ( pCur->eState==CURSOR_INVALID ){
62348  return SQLITE_ABORT;
62349  }
62350 #endif
62351 
62352  assert( cursorOwnsBtShared(pCur) );
62353  rc = restoreCursorPosition(pCur);
62354  if( rc==SQLITE_OK ){
62355  assert( pCur->eState==CURSOR_VALID );
62356  assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
62357  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62358  rc = accessPayload(pCur, offset, amt, pBuf, 0);
62359  }
62360  return rc;
62361 }
62362 
62363 /*
62364 ** Return a pointer to payload information from the entry that the
62365 ** pCur cursor is pointing to. The pointer is to the beginning of
62366 ** the key if index btrees (pPage->intKey==0) and is the data for
62367 ** table btrees (pPage->intKey==1). The number of bytes of available
62368 ** key/data is written into *pAmt. If *pAmt==0, then the value
62369 ** returned will not be a valid pointer.
62370 **
62371 ** This routine is an optimization. It is common for the entire key
62372 ** and data to fit on the local page and for there to be no overflow
62373 ** pages. When that is so, this routine can be used to access the
62374 ** key and data without making a copy. If the key and/or data spills
62375 ** onto overflow pages, then accessPayload() must be used to reassemble
62376 ** the key/data and copy it into a preallocated buffer.
62377 **
62378 ** The pointer returned by this routine looks directly into the cached
62379 ** page of the database. The data might change or move the next time
62380 ** any btree routine is called.
62381 */
62382 static const void *fetchPayload(
62383  BtCursor *pCur, /* Cursor pointing to entry to read from */
62384  u32 *pAmt /* Write the number of available bytes here */
62385 ){
62386  u32 amt;
62387  assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
62388  assert( pCur->eState==CURSOR_VALID );
62389  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62390  assert( cursorOwnsBtShared(pCur) );
62391  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62392  assert( pCur->info.nSize>0 );
62393  assert( pCur->info.pPayload>pCur->apPage[pCur->iPage]->aData || CORRUPT_DB );
62394  assert( pCur->info.pPayload<pCur->apPage[pCur->iPage]->aDataEnd ||CORRUPT_DB);
62395  amt = (int)(pCur->apPage[pCur->iPage]->aDataEnd - pCur->info.pPayload);
62396  if( pCur->info.nLocal<amt ) amt = pCur->info.nLocal;
62397  *pAmt = amt;
62398  return (void*)pCur->info.pPayload;
62399 }
62400 
62401 
62402 /*
62403 ** For the entry that cursor pCur is point to, return as
62404 ** many bytes of the key or data as are available on the local
62405 ** b-tree page. Write the number of available bytes into *pAmt.
62406 **
62407 ** The pointer returned is ephemeral. The key/data may move
62408 ** or be destroyed on the next call to any Btree routine,
62409 ** including calls from other threads against the same cache.
62410 ** Hence, a mutex on the BtShared should be held prior to calling
62411 ** this routine.
62412 **
62413 ** These routines is used to get quick access to key and data
62414 ** in the common case where no overflow pages are used.
62415 */
62416 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
62417  return fetchPayload(pCur, pAmt);
62418 }
62419 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
62420  return fetchPayload(pCur, pAmt);
62421 }
62422 
62423 
62424 /*
62425 ** Move the cursor down to a new child page. The newPgno argument is the
62426 ** page number of the child page to move to.
62427 **
62428 ** This function returns SQLITE_CORRUPT if the page-header flags field of
62429 ** the new child page does not match the flags field of the parent (i.e.
62430 ** if an intkey page appears to be the parent of a non-intkey page, or
62431 ** vice-versa).
62432 */
62433 static int moveToChild(BtCursor *pCur, u32 newPgno){
62434  BtShared *pBt = pCur->pBt;
62435 
62436  assert( cursorOwnsBtShared(pCur) );
62437  assert( pCur->eState==CURSOR_VALID );
62438  assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
62439  assert( pCur->iPage>=0 );
62440  if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
62441  return SQLITE_CORRUPT_BKPT;
62442  }
62443  pCur->info.nSize = 0;
62445  pCur->iPage++;
62446  pCur->aiIdx[pCur->iPage] = 0;
62447  return getAndInitPage(pBt, newPgno, &pCur->apPage[pCur->iPage],
62448  pCur, pCur->curPagerFlags);
62449 }
62450 
62451 #if SQLITE_DEBUG
62452 /*
62453 ** Page pParent is an internal (non-leaf) tree page. This function
62454 ** asserts that page number iChild is the left-child if the iIdx'th
62455 ** cell in page pParent. Or, if iIdx is equal to the total number of
62456 ** cells in pParent, that page number iChild is the right-child of
62457 ** the page.
62458 */
62459 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
62460  if( CORRUPT_DB ) return; /* The conditions tested below might not be true
62461  ** in a corrupt database */
62462  assert( iIdx<=pParent->nCell );
62463  if( iIdx==pParent->nCell ){
62464  assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
62465  }else{
62466  assert( get4byte(findCell(pParent, iIdx))==iChild );
62467  }
62468 }
62469 #else
62470 # define assertParentIndex(x,y,z)
62471 #endif
62472 
62473 /*
62474 ** Move the cursor up to the parent page.
62475 **
62476 ** pCur->idx is set to the cell index that contains the pointer
62477 ** to the page we are coming from. If we are coming from the
62478 ** right-most child page then pCur->idx is set to one more than
62479 ** the largest cell index.
62480 */
62481 static void moveToParent(BtCursor *pCur){
62482  assert( cursorOwnsBtShared(pCur) );
62483  assert( pCur->eState==CURSOR_VALID );
62484  assert( pCur->iPage>0 );
62485  assert( pCur->apPage[pCur->iPage] );
62487  pCur->apPage[pCur->iPage-1],
62488  pCur->aiIdx[pCur->iPage-1],
62489  pCur->apPage[pCur->iPage]->pgno
62490  );
62491  testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
62492  pCur->info.nSize = 0;
62494  releasePageNotNull(pCur->apPage[pCur->iPage--]);
62495 }
62496 
62497 /*
62498 ** Move the cursor to point to the root page of its b-tree structure.
62499 **
62500 ** If the table has a virtual root page, then the cursor is moved to point
62501 ** to the virtual root page instead of the actual root page. A table has a
62502 ** virtual root page when the actual root page contains no cells and a
62503 ** single child page. This can only happen with the table rooted at page 1.
62504 **
62505 ** If the b-tree structure is empty, the cursor state is set to
62506 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
62507 ** cell located on the root (or virtual root) page and the cursor state
62508 ** is set to CURSOR_VALID.
62509 **
62510 ** If this function returns successfully, it may be assumed that the
62511 ** page-header flags indicate that the [virtual] root-page is the expected
62512 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
62513 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
62514 ** indicating a table b-tree, or if the caller did specify a KeyInfo
62515 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
62516 ** b-tree).
62517 */
62518 static int moveToRoot(BtCursor *pCur){
62519  MemPage *pRoot;
62520  int rc = SQLITE_OK;
62521 
62522  assert( cursorOwnsBtShared(pCur) );
62526  if( pCur->eState>=CURSOR_REQUIRESEEK ){
62527  if( pCur->eState==CURSOR_FAULT ){
62528  assert( pCur->skipNext!=SQLITE_OK );
62529  return pCur->skipNext;
62530  }
62532  }
62533 
62534  if( pCur->iPage>=0 ){
62535  while( pCur->iPage ){
62536  assert( pCur->apPage[pCur->iPage]!=0 );
62537  releasePageNotNull(pCur->apPage[pCur->iPage--]);
62538  }
62539  }else if( pCur->pgnoRoot==0 ){
62540  pCur->eState = CURSOR_INVALID;
62541  return SQLITE_OK;
62542  }else{
62543  assert( pCur->iPage==(-1) );
62544  rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
62545  0, pCur->curPagerFlags);
62546  if( rc!=SQLITE_OK ){
62547  pCur->eState = CURSOR_INVALID;
62548  return rc;
62549  }
62550  pCur->iPage = 0;
62551  pCur->curIntKey = pCur->apPage[0]->intKey;
62552  }
62553  pRoot = pCur->apPage[0];
62554  assert( pRoot->pgno==pCur->pgnoRoot );
62555 
62556  /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
62557  ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
62558  ** NULL, the caller expects a table b-tree. If this is not the case,
62559  ** return an SQLITE_CORRUPT error.
62560  **
62561  ** Earlier versions of SQLite assumed that this test could not fail
62562  ** if the root page was already loaded when this function was called (i.e.
62563  ** if pCur->iPage>=0). But this is not so if the database is corrupted
62564  ** in such a way that page pRoot is linked into a second b-tree table
62565  ** (or the freelist). */
62566  assert( pRoot->intKey==1 || pRoot->intKey==0 );
62567  if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
62568  return SQLITE_CORRUPT_BKPT;
62569  }
62570 
62571  pCur->aiIdx[0] = 0;
62572  pCur->info.nSize = 0;
62574 
62575  if( pRoot->nCell>0 ){
62576  pCur->eState = CURSOR_VALID;
62577  }else if( !pRoot->leaf ){
62578  Pgno subpage;
62579  if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
62580  subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
62581  pCur->eState = CURSOR_VALID;
62582  rc = moveToChild(pCur, subpage);
62583  }else{
62584  pCur->eState = CURSOR_INVALID;
62585  }
62586  return rc;
62587 }
62588 
62589 /*
62590 ** Move the cursor down to the left-most leaf entry beneath the
62591 ** entry to which it is currently pointing.
62592 **
62593 ** The left-most leaf is the one with the smallest key - the first
62594 ** in ascending order.
62595 */
62596 static int moveToLeftmost(BtCursor *pCur){
62597  Pgno pgno;
62598  int rc = SQLITE_OK;
62599  MemPage *pPage;
62600 
62601  assert( cursorOwnsBtShared(pCur) );
62602  assert( pCur->eState==CURSOR_VALID );
62603  while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
62604  assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
62605  pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
62606  rc = moveToChild(pCur, pgno);
62607  }
62608  return rc;
62609 }
62610 
62611 /*
62612 ** Move the cursor down to the right-most leaf entry beneath the
62613 ** page to which it is currently pointing. Notice the difference
62614 ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
62615 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
62616 ** finds the right-most entry beneath the *page*.
62617 **
62618 ** The right-most entry is the one with the largest key - the last
62619 ** key in ascending order.
62620 */
62621 static int moveToRightmost(BtCursor *pCur){
62622  Pgno pgno;
62623  int rc = SQLITE_OK;
62624  MemPage *pPage = 0;
62625 
62626  assert( cursorOwnsBtShared(pCur) );
62627  assert( pCur->eState==CURSOR_VALID );
62628  while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
62629  pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
62630  pCur->aiIdx[pCur->iPage] = pPage->nCell;
62631  rc = moveToChild(pCur, pgno);
62632  if( rc ) return rc;
62633  }
62634  pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
62635  assert( pCur->info.nSize==0 );
62636  assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
62637  return SQLITE_OK;
62638 }
62639 
62640 /* Move the cursor to the first entry in the table. Return SQLITE_OK
62641 ** on success. Set *pRes to 0 if the cursor actually points to something
62642 ** or set *pRes to 1 if the table is empty.
62643 */
62645  int rc;
62646 
62647  assert( cursorOwnsBtShared(pCur) );
62648  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62649  rc = moveToRoot(pCur);
62650  if( rc==SQLITE_OK ){
62651  if( pCur->eState==CURSOR_INVALID ){
62652  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
62653  *pRes = 1;
62654  }else{
62655  assert( pCur->apPage[pCur->iPage]->nCell>0 );
62656  *pRes = 0;
62657  rc = moveToLeftmost(pCur);
62658  }
62659  }
62660  return rc;
62661 }
62662 
62663 /* Move the cursor to the last entry in the table. Return SQLITE_OK
62664 ** on success. Set *pRes to 0 if the cursor actually points to something
62665 ** or set *pRes to 1 if the table is empty.
62666 */
62668  int rc;
62669 
62670  assert( cursorOwnsBtShared(pCur) );
62671  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62672 
62673  /* If the cursor already points to the last entry, this is a no-op. */
62674  if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
62675 #ifdef SQLITE_DEBUG
62676  /* This block serves to assert() that the cursor really does point
62677  ** to the last entry in the b-tree. */
62678  int ii;
62679  for(ii=0; ii<pCur->iPage; ii++){
62680  assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
62681  }
62682  assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
62683  assert( pCur->apPage[pCur->iPage]->leaf );
62684 #endif
62685  return SQLITE_OK;
62686  }
62687 
62688  rc = moveToRoot(pCur);
62689  if( rc==SQLITE_OK ){
62690  if( CURSOR_INVALID==pCur->eState ){
62691  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
62692  *pRes = 1;
62693  }else{
62694  assert( pCur->eState==CURSOR_VALID );
62695  *pRes = 0;
62696  rc = moveToRightmost(pCur);
62697  if( rc==SQLITE_OK ){
62698  pCur->curFlags |= BTCF_AtLast;
62699  }else{
62700  pCur->curFlags &= ~BTCF_AtLast;
62701  }
62702 
62703  }
62704  }
62705  return rc;
62706 }
62707 
62708 /* Move the cursor so that it points to an entry near the key
62709 ** specified by pIdxKey or intKey. Return a success code.
62710 **
62711 ** For INTKEY tables, the intKey parameter is used. pIdxKey
62712 ** must be NULL. For index tables, pIdxKey is used and intKey
62713 ** is ignored.
62714 **
62715 ** If an exact match is not found, then the cursor is always
62716 ** left pointing at a leaf page which would hold the entry if it
62717 ** were present. The cursor might point to an entry that comes
62718 ** before or after the key.
62719 **
62720 ** An integer is written into *pRes which is the result of
62721 ** comparing the key with the entry to which the cursor is
62722 ** pointing. The meaning of the integer written into
62723 ** *pRes is as follows:
62724 **
62725 ** *pRes<0 The cursor is left pointing at an entry that
62726 ** is smaller than intKey/pIdxKey or if the table is empty
62727 ** and the cursor is therefore left point to nothing.
62728 **
62729 ** *pRes==0 The cursor is left pointing at an entry that
62730 ** exactly matches intKey/pIdxKey.
62731 **
62732 ** *pRes>0 The cursor is left pointing at an entry that
62733 ** is larger than intKey/pIdxKey.
62734 **
62735 ** For index tables, the pIdxKey->eqSeen field is set to 1 if there
62736 ** exists an entry in the table that exactly matches pIdxKey.
62737 */
62739  BtCursor *pCur, /* The cursor to be moved */
62740  UnpackedRecord *pIdxKey, /* Unpacked index key */
62741  i64 intKey, /* The table key */
62742  int biasRight, /* If true, bias the search to the high end */
62743  int *pRes /* Write search results here */
62744 ){
62745  int rc;
62746  RecordCompare xRecordCompare;
62747 
62748  assert( cursorOwnsBtShared(pCur) );
62749  assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
62750  assert( pRes );
62751  assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
62752 
62753  /* If the cursor is already positioned at the point we are trying
62754  ** to move to, then just return without doing any work */
62755  if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
62756  && pCur->curIntKey
62757  ){
62758  if( pCur->info.nKey==intKey ){
62759  *pRes = 0;
62760  return SQLITE_OK;
62761  }
62762  if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
62763  *pRes = -1;
62764  return SQLITE_OK;
62765  }
62766  }
62767 
62768  if( pIdxKey ){
62769  xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
62770  pIdxKey->errCode = 0;
62771  assert( pIdxKey->default_rc==1
62772  || pIdxKey->default_rc==0
62773  || pIdxKey->default_rc==-1
62774  );
62775  }else{
62776  xRecordCompare = 0; /* All keys are integers */
62777  }
62778 
62779  rc = moveToRoot(pCur);
62780  if( rc ){
62781  return rc;
62782  }
62783  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
62784  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
62785  assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
62786  if( pCur->eState==CURSOR_INVALID ){
62787  *pRes = -1;
62788  assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
62789  return SQLITE_OK;
62790  }
62791  assert( pCur->apPage[0]->intKey==pCur->curIntKey );
62792  assert( pCur->curIntKey || pIdxKey );
62793  for(;;){
62794  int lwr, upr, idx, c;
62795  Pgno chldPg;
62796  MemPage *pPage = pCur->apPage[pCur->iPage];
62797  u8 *pCell; /* Pointer to current cell in pPage */
62798 
62799  /* pPage->nCell must be greater than zero. If this is the root-page
62800  ** the cursor would have been INVALID above and this for(;;) loop
62801  ** not run. If this is not the root-page, then the moveToChild() routine
62802  ** would have already detected db corruption. Similarly, pPage must
62803  ** be the right kind (index or table) of b-tree page. Otherwise
62804  ** a moveToChild() or moveToRoot() call would have detected corruption. */
62805  assert( pPage->nCell>0 );
62806  assert( pPage->intKey==(pIdxKey==0) );
62807  lwr = 0;
62808  upr = pPage->nCell-1;
62809  assert( biasRight==0 || biasRight==1 );
62810  idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
62811  pCur->aiIdx[pCur->iPage] = (u16)idx;
62812  if( xRecordCompare==0 ){
62813  for(;;){
62814  i64 nCellKey;
62815  pCell = findCellPastPtr(pPage, idx);
62816  if( pPage->intKeyLeaf ){
62817  while( 0x80 <= *(pCell++) ){
62818  if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
62819  }
62820  }
62821  getVarint(pCell, (u64*)&nCellKey);
62822  if( nCellKey<intKey ){
62823  lwr = idx+1;
62824  if( lwr>upr ){ c = -1; break; }
62825  }else if( nCellKey>intKey ){
62826  upr = idx-1;
62827  if( lwr>upr ){ c = +1; break; }
62828  }else{
62829  assert( nCellKey==intKey );
62830  pCur->curFlags |= BTCF_ValidNKey;
62831  pCur->info.nKey = nCellKey;
62832  pCur->aiIdx[pCur->iPage] = (u16)idx;
62833  if( !pPage->leaf ){
62834  lwr = idx;
62835  goto moveto_next_layer;
62836  }else{
62837  *pRes = 0;
62838  rc = SQLITE_OK;
62839  goto moveto_finish;
62840  }
62841  }
62842  assert( lwr+upr>=0 );
62843  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
62844  }
62845  }else{
62846  for(;;){
62847  int nCell; /* Size of the pCell cell in bytes */
62848  pCell = findCellPastPtr(pPage, idx);
62849 
62850  /* The maximum supported page-size is 65536 bytes. This means that
62851  ** the maximum number of record bytes stored on an index B-Tree
62852  ** page is less than 16384 bytes and may be stored as a 2-byte
62853  ** varint. This information is used to attempt to avoid parsing
62854  ** the entire cell by checking for the cases where the record is
62855  ** stored entirely within the b-tree page by inspecting the first
62856  ** 2 bytes of the cell.
62857  */
62858  nCell = pCell[0];
62859  if( nCell<=pPage->max1bytePayload ){
62860  /* This branch runs if the record-size field of the cell is a
62861  ** single byte varint and the record fits entirely on the main
62862  ** b-tree page. */
62863  testcase( pCell+nCell+1==pPage->aDataEnd );
62864  c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
62865  }else if( !(pCell[1] & 0x80)
62866  && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
62867  ){
62868  /* The record-size field is a 2 byte varint and the record
62869  ** fits entirely on the main b-tree page. */
62870  testcase( pCell+nCell+2==pPage->aDataEnd );
62871  c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
62872  }else{
62873  /* The record flows over onto one or more overflow pages. In
62874  ** this case the whole cell needs to be parsed, a buffer allocated
62875  ** and accessPayload() used to retrieve the record into the
62876  ** buffer before VdbeRecordCompare() can be called.
62877  **
62878  ** If the record is corrupt, the xRecordCompare routine may read
62879  ** up to two varints past the end of the buffer. An extra 18
62880  ** bytes of padding is allocated at the end of the buffer in
62881  ** case this happens. */
62882  void *pCellKey;
62883  u8 * const pCellBody = pCell - pPage->childPtrSize;
62884  pPage->xParseCell(pPage, pCellBody, &pCur->info);
62885  nCell = (int)pCur->info.nKey;
62886  testcase( nCell<0 ); /* True if key size is 2^32 or more */
62887  testcase( nCell==0 ); /* Invalid key size: 0x80 0x80 0x00 */
62888  testcase( nCell==1 ); /* Invalid key size: 0x80 0x80 0x01 */
62889  testcase( nCell==2 ); /* Minimum legal index key size */
62890  if( nCell<2 ){
62891  rc = SQLITE_CORRUPT_BKPT;
62892  goto moveto_finish;
62893  }
62894  pCellKey = sqlite3Malloc( nCell+18 );
62895  if( pCellKey==0 ){
62896  rc = SQLITE_NOMEM_BKPT;
62897  goto moveto_finish;
62898  }
62899  pCur->aiIdx[pCur->iPage] = (u16)idx;
62900  rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
62901  if( rc ){
62902  sqlite3_free(pCellKey);
62903  goto moveto_finish;
62904  }
62905  c = xRecordCompare(nCell, pCellKey, pIdxKey);
62906  sqlite3_free(pCellKey);
62907  }
62908  assert(
62909  (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
62910  && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
62911  );
62912  if( c<0 ){
62913  lwr = idx+1;
62914  }else if( c>0 ){
62915  upr = idx-1;
62916  }else{
62917  assert( c==0 );
62918  *pRes = 0;
62919  rc = SQLITE_OK;
62920  pCur->aiIdx[pCur->iPage] = (u16)idx;
62921  if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
62922  goto moveto_finish;
62923  }
62924  if( lwr>upr ) break;
62925  assert( lwr+upr>=0 );
62926  idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
62927  }
62928  }
62929  assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
62930  assert( pPage->isInit );
62931  if( pPage->leaf ){
62932  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
62933  pCur->aiIdx[pCur->iPage] = (u16)idx;
62934  *pRes = c;
62935  rc = SQLITE_OK;
62936  goto moveto_finish;
62937  }
62938 moveto_next_layer:
62939  if( lwr>=pPage->nCell ){
62940  chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
62941  }else{
62942  chldPg = get4byte(findCell(pPage, lwr));
62943  }
62944  pCur->aiIdx[pCur->iPage] = (u16)lwr;
62945  rc = moveToChild(pCur, chldPg);
62946  if( rc ) break;
62947  }
62948 moveto_finish:
62949  pCur->info.nSize = 0;
62951  return rc;
62952 }
62953 
62954 
62955 /*
62956 ** Return TRUE if the cursor is not pointing at an entry of the table.
62957 **
62958 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
62959 ** past the last entry in the table or sqlite3BtreePrev() moves past
62960 ** the first entry. TRUE is also returned if the table is empty.
62961 */
62963  /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
62964  ** have been deleted? This API will need to change to return an error code
62965  ** as well as the boolean result value.
62966  */
62967  return (CURSOR_VALID!=pCur->eState);
62968 }
62969 
62970 /*
62971 ** Advance the cursor to the next entry in the database. If
62972 ** successful then set *pRes=0. If the cursor
62973 ** was already pointing to the last entry in the database before
62974 ** this routine was called, then set *pRes=1.
62975 **
62976 ** The main entry point is sqlite3BtreeNext(). That routine is optimized
62977 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
62978 ** to the next cell on the current page. The (slower) btreeNext() helper
62979 ** routine is called when it is necessary to move to a different page or
62980 ** to restore the cursor.
62981 **
62982 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
62983 ** will be 1 if the cursor being stepped corresponds to an SQL index and
62984 ** if this routine could have been skipped if that SQL index had been
62985 ** a unique index. Otherwise the caller will have set *pRes to zero.
62986 ** Zero is the common case. The btree implementation is free to use the
62987 ** initial *pRes value as a hint to improve performance, but the current
62988 ** SQLite btree implementation does not. (Note that the comdb2 btree
62989 ** implementation does use this hint, however.)
62990 */
62991 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
62992  int rc;
62993  int idx;
62994  MemPage *pPage;
62995 
62996  assert( cursorOwnsBtShared(pCur) );
62997  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
62998  assert( *pRes==0 );
62999  if( pCur->eState!=CURSOR_VALID ){
63000  assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
63001  rc = restoreCursorPosition(pCur);
63002  if( rc!=SQLITE_OK ){
63003  return rc;
63004  }
63005  if( CURSOR_INVALID==pCur->eState ){
63006  *pRes = 1;
63007  return SQLITE_OK;
63008  }
63009  if( pCur->skipNext ){
63010  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63011  pCur->eState = CURSOR_VALID;
63012  if( pCur->skipNext>0 ){
63013  pCur->skipNext = 0;
63014  return SQLITE_OK;
63015  }
63016  pCur->skipNext = 0;
63017  }
63018  }
63019 
63020  pPage = pCur->apPage[pCur->iPage];
63021  idx = ++pCur->aiIdx[pCur->iPage];
63022  assert( pPage->isInit );
63023 
63024  /* If the database file is corrupt, it is possible for the value of idx
63025  ** to be invalid here. This can only occur if a second cursor modifies
63026  ** the page while cursor pCur is holding a reference to it. Which can
63027  ** only happen if the database is corrupt in such a way as to link the
63028  ** page into more than one b-tree structure. */
63029  testcase( idx>pPage->nCell );
63030 
63031  if( idx>=pPage->nCell ){
63032  if( !pPage->leaf ){
63033  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
63034  if( rc ) return rc;
63035  return moveToLeftmost(pCur);
63036  }
63037  do{
63038  if( pCur->iPage==0 ){
63039  *pRes = 1;
63040  pCur->eState = CURSOR_INVALID;
63041  return SQLITE_OK;
63042  }
63043  moveToParent(pCur);
63044  pPage = pCur->apPage[pCur->iPage];
63045  }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
63046  if( pPage->intKey ){
63047  return sqlite3BtreeNext(pCur, pRes);
63048  }else{
63049  return SQLITE_OK;
63050  }
63051  }
63052  if( pPage->leaf ){
63053  return SQLITE_OK;
63054  }else{
63055  return moveToLeftmost(pCur);
63056  }
63057 }
63059  MemPage *pPage;
63060  assert( cursorOwnsBtShared(pCur) );
63061  assert( pRes!=0 );
63062  assert( *pRes==0 || *pRes==1 );
63063  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63064  pCur->info.nSize = 0;
63066  *pRes = 0;
63067  if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
63068  pPage = pCur->apPage[pCur->iPage];
63069  if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
63070  pCur->aiIdx[pCur->iPage]--;
63071  return btreeNext(pCur, pRes);
63072  }
63073  if( pPage->leaf ){
63074  return SQLITE_OK;
63075  }else{
63076  return moveToLeftmost(pCur);
63077  }
63078 }
63079 
63080 /*
63081 ** Step the cursor to the back to the previous entry in the database. If
63082 ** successful then set *pRes=0. If the cursor
63083 ** was already pointing to the first entry in the database before
63084 ** this routine was called, then set *pRes=1.
63085 **
63086 ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
63087 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
63088 ** to the previous cell on the current page. The (slower) btreePrevious()
63089 ** helper routine is called when it is necessary to move to a different page
63090 ** or to restore the cursor.
63091 **
63092 ** The calling function will set *pRes to 0 or 1. The initial *pRes value
63093 ** will be 1 if the cursor being stepped corresponds to an SQL index and
63094 ** if this routine could have been skipped if that SQL index had been
63095 ** a unique index. Otherwise the caller will have set *pRes to zero.
63096 ** Zero is the common case. The btree implementation is free to use the
63097 ** initial *pRes value as a hint to improve performance, but the current
63098 ** SQLite btree implementation does not. (Note that the comdb2 btree
63099 ** implementation does use this hint, however.)
63100 */
63101 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
63102  int rc;
63103  MemPage *pPage;
63104 
63105  assert( cursorOwnsBtShared(pCur) );
63106  assert( pRes!=0 );
63107  assert( *pRes==0 );
63108  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63110  assert( pCur->info.nSize==0 );
63111  if( pCur->eState!=CURSOR_VALID ){
63112  rc = restoreCursorPosition(pCur);
63113  if( rc!=SQLITE_OK ){
63114  return rc;
63115  }
63116  if( CURSOR_INVALID==pCur->eState ){
63117  *pRes = 1;
63118  return SQLITE_OK;
63119  }
63120  if( pCur->skipNext ){
63121  assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
63122  pCur->eState = CURSOR_VALID;
63123  if( pCur->skipNext<0 ){
63124  pCur->skipNext = 0;
63125  return SQLITE_OK;
63126  }
63127  pCur->skipNext = 0;
63128  }
63129  }
63130 
63131  pPage = pCur->apPage[pCur->iPage];
63132  assert( pPage->isInit );
63133  if( !pPage->leaf ){
63134  int idx = pCur->aiIdx[pCur->iPage];
63135  rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
63136  if( rc ) return rc;
63137  rc = moveToRightmost(pCur);
63138  }else{
63139  while( pCur->aiIdx[pCur->iPage]==0 ){
63140  if( pCur->iPage==0 ){
63141  pCur->eState = CURSOR_INVALID;
63142  *pRes = 1;
63143  return SQLITE_OK;
63144  }
63145  moveToParent(pCur);
63146  }
63147  assert( pCur->info.nSize==0 );
63148  assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
63149 
63150  pCur->aiIdx[pCur->iPage]--;
63151  pPage = pCur->apPage[pCur->iPage];
63152  if( pPage->intKey && !pPage->leaf ){
63153  rc = sqlite3BtreePrevious(pCur, pRes);
63154  }else{
63155  rc = SQLITE_OK;
63156  }
63157  }
63158  return rc;
63159 }
63161  assert( cursorOwnsBtShared(pCur) );
63162  assert( pRes!=0 );
63163  assert( *pRes==0 || *pRes==1 );
63164  assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
63165  *pRes = 0;
63167  pCur->info.nSize = 0;
63168  if( pCur->eState!=CURSOR_VALID
63169  || pCur->aiIdx[pCur->iPage]==0
63170  || pCur->apPage[pCur->iPage]->leaf==0
63171  ){
63172  return btreePrevious(pCur, pRes);
63173  }
63174  pCur->aiIdx[pCur->iPage]--;
63175  return SQLITE_OK;
63176 }
63177 
63178 /*
63179 ** Allocate a new page from the database file.
63180 **
63181 ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
63182 ** has already been called on the new page.) The new page has also
63183 ** been referenced and the calling routine is responsible for calling
63184 ** sqlite3PagerUnref() on the new page when it is done.
63185 **
63186 ** SQLITE_OK is returned on success. Any other return value indicates
63187 ** an error. *ppPage is set to NULL in the event of an error.
63188 **
63189 ** If the "nearby" parameter is not 0, then an effort is made to
63190 ** locate a page close to the page number "nearby". This can be used in an
63191 ** attempt to keep related pages close to each other in the database file,
63192 ** which in turn can make database access faster.
63193 **
63194 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
63195 ** anywhere on the free-list, then it is guaranteed to be returned. If
63196 ** eMode is BTALLOC_LT then the page returned will be less than or equal
63197 ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
63198 ** are no restrictions on which page is returned.
63199 */
63201  BtShared *pBt, /* The btree */
63202  MemPage **ppPage, /* Store pointer to the allocated page here */
63203  Pgno *pPgno, /* Store the page number here */
63204  Pgno nearby, /* Search for a page near this one */
63205  u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
63206 ){
63207  MemPage *pPage1;
63208  int rc;
63209  u32 n; /* Number of pages on the freelist */
63210  u32 k; /* Number of leaves on the trunk of the freelist */
63211  MemPage *pTrunk = 0;
63212  MemPage *pPrevTrunk = 0;
63213  Pgno mxPage; /* Total size of the database file */
63214 
63215  assert( sqlite3_mutex_held(pBt->mutex) );
63216  assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
63217  pPage1 = pBt->pPage1;
63218  mxPage = btreePagecount(pBt);
63219  /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
63220  ** stores stores the total number of pages on the freelist. */
63221  n = get4byte(&pPage1->aData[36]);
63222  testcase( n==mxPage-1 );
63223  if( n>=mxPage ){
63224  return SQLITE_CORRUPT_BKPT;
63225  }
63226  if( n>0 ){
63227  /* There are pages on the freelist. Reuse one of those pages. */
63228  Pgno iTrunk;
63229  u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
63230  u32 nSearch = 0; /* Count of the number of search attempts */
63231 
63232  /* If eMode==BTALLOC_EXACT and a query of the pointer-map
63233  ** shows that the page 'nearby' is somewhere on the free-list, then
63234  ** the entire-list will be searched for that page.
63235  */
63236 #ifndef SQLITE_OMIT_AUTOVACUUM
63237  if( eMode==BTALLOC_EXACT ){
63238  if( nearby<=mxPage ){
63239  u8 eType;
63240  assert( nearby>0 );
63241  assert( pBt->autoVacuum );
63242  rc = ptrmapGet(pBt, nearby, &eType, 0);
63243  if( rc ) return rc;
63244  if( eType==PTRMAP_FREEPAGE ){
63245  searchList = 1;
63246  }
63247  }
63248  }else if( eMode==BTALLOC_LE ){
63249  searchList = 1;
63250  }
63251 #endif
63252 
63253  /* Decrement the free-list count by 1. Set iTrunk to the index of the
63254  ** first free-list trunk page. iPrevTrunk is initially 1.
63255  */
63256  rc = sqlite3PagerWrite(pPage1->pDbPage);
63257  if( rc ) return rc;
63258  put4byte(&pPage1->aData[36], n-1);
63259 
63260  /* The code within this loop is run only once if the 'searchList' variable
63261  ** is not true. Otherwise, it runs once for each trunk-page on the
63262  ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
63263  ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
63264  */
63265  do {
63266  pPrevTrunk = pTrunk;
63267  if( pPrevTrunk ){
63268  /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
63269  ** is the page number of the next freelist trunk page in the list or
63270  ** zero if this is the last freelist trunk page. */
63271  iTrunk = get4byte(&pPrevTrunk->aData[0]);
63272  }else{
63273  /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
63274  ** stores the page number of the first page of the freelist, or zero if
63275  ** the freelist is empty. */
63276  iTrunk = get4byte(&pPage1->aData[32]);
63277  }
63278  testcase( iTrunk==mxPage );
63279  if( iTrunk>mxPage || nSearch++ > n ){
63280  rc = SQLITE_CORRUPT_BKPT;
63281  }else{
63282  rc = btreeGetUnusedPage(pBt, iTrunk, &pTrunk, 0);
63283  }
63284  if( rc ){
63285  pTrunk = 0;
63286  goto end_allocate_page;
63287  }
63288  assert( pTrunk!=0 );
63289  assert( pTrunk->aData!=0 );
63290  /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
63291  ** is the number of leaf page pointers to follow. */
63292  k = get4byte(&pTrunk->aData[4]);
63293  if( k==0 && !searchList ){
63294  /* The trunk has no leaves and the list is not being searched.
63295  ** So extract the trunk page itself and use it as the newly
63296  ** allocated page */
63297  assert( pPrevTrunk==0 );
63298  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63299  if( rc ){
63300  goto end_allocate_page;
63301  }
63302  *pPgno = iTrunk;
63303  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63304  *ppPage = pTrunk;
63305  pTrunk = 0;
63306  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63307  }else if( k>(u32)(pBt->usableSize/4 - 2) ){
63308  /* Value of k is out of range. Database corruption */
63309  rc = SQLITE_CORRUPT_BKPT;
63310  goto end_allocate_page;
63311 #ifndef SQLITE_OMIT_AUTOVACUUM
63312  }else if( searchList
63313  && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
63314  ){
63315  /* The list is being searched and this trunk page is the page
63316  ** to allocate, regardless of whether it has leaves.
63317  */
63318  *pPgno = iTrunk;
63319  *ppPage = pTrunk;
63320  searchList = 0;
63321  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63322  if( rc ){
63323  goto end_allocate_page;
63324  }
63325  if( k==0 ){
63326  if( !pPrevTrunk ){
63327  memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
63328  }else{
63329  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63330  if( rc!=SQLITE_OK ){
63331  goto end_allocate_page;
63332  }
63333  memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
63334  }
63335  }else{
63336  /* The trunk page is required by the caller but it contains
63337  ** pointers to free-list leaves. The first leaf becomes a trunk
63338  ** page in this case.
63339  */
63340  MemPage *pNewTrunk;
63341  Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
63342  if( iNewTrunk>mxPage ){
63343  rc = SQLITE_CORRUPT_BKPT;
63344  goto end_allocate_page;
63345  }
63346  testcase( iNewTrunk==mxPage );
63347  rc = btreeGetUnusedPage(pBt, iNewTrunk, &pNewTrunk, 0);
63348  if( rc!=SQLITE_OK ){
63349  goto end_allocate_page;
63350  }
63351  rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
63352  if( rc!=SQLITE_OK ){
63353  releasePage(pNewTrunk);
63354  goto end_allocate_page;
63355  }
63356  memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
63357  put4byte(&pNewTrunk->aData[4], k-1);
63358  memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
63359  releasePage(pNewTrunk);
63360  if( !pPrevTrunk ){
63361  assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
63362  put4byte(&pPage1->aData[32], iNewTrunk);
63363  }else{
63364  rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
63365  if( rc ){
63366  goto end_allocate_page;
63367  }
63368  put4byte(&pPrevTrunk->aData[0], iNewTrunk);
63369  }
63370  }
63371  pTrunk = 0;
63372  TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
63373 #endif
63374  }else if( k>0 ){
63375  /* Extract a leaf from the trunk */
63376  u32 closest;
63377  Pgno iPage;
63378  unsigned char *aData = pTrunk->aData;
63379  if( nearby>0 ){
63380  u32 i;
63381  closest = 0;
63382  if( eMode==BTALLOC_LE ){
63383  for(i=0; i<k; i++){
63384  iPage = get4byte(&aData[8+i*4]);
63385  if( iPage<=nearby ){
63386  closest = i;
63387  break;
63388  }
63389  }
63390  }else{
63391  int dist;
63392  dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
63393  for(i=1; i<k; i++){
63394  int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
63395  if( d2<dist ){
63396  closest = i;
63397  dist = d2;
63398  }
63399  }
63400  }
63401  }else{
63402  closest = 0;
63403  }
63404 
63405  iPage = get4byte(&aData[8+closest*4]);
63406  testcase( iPage==mxPage );
63407  if( iPage>mxPage ){
63408  rc = SQLITE_CORRUPT_BKPT;
63409  goto end_allocate_page;
63410  }
63411  testcase( iPage==mxPage );
63412  if( !searchList
63413  || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
63414  ){
63415  int noContent;
63416  *pPgno = iPage;
63417  TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
63418  ": %d more free pages\n",
63419  *pPgno, closest+1, k, pTrunk->pgno, n-1));
63420  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63421  if( rc ) goto end_allocate_page;
63422  if( closest<k-1 ){
63423  memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
63424  }
63425  put4byte(&aData[4], k-1);
63426  noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
63427  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, noContent);
63428  if( rc==SQLITE_OK ){
63429  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63430  if( rc!=SQLITE_OK ){
63431  releasePage(*ppPage);
63432  *ppPage = 0;
63433  }
63434  }
63435  searchList = 0;
63436  }
63437  }
63438  releasePage(pPrevTrunk);
63439  pPrevTrunk = 0;
63440  }while( searchList );
63441  }else{
63442  /* There are no pages on the freelist, so append a new page to the
63443  ** database image.
63444  **
63445  ** Normally, new pages allocated by this block can be requested from the
63446  ** pager layer with the 'no-content' flag set. This prevents the pager
63447  ** from trying to read the pages content from disk. However, if the
63448  ** current transaction has already run one or more incremental-vacuum
63449  ** steps, then the page we are about to allocate may contain content
63450  ** that is required in the event of a rollback. In this case, do
63451  ** not set the no-content flag. This causes the pager to load and journal
63452  ** the current page content before overwriting it.
63453  **
63454  ** Note that the pager will not actually attempt to load or journal
63455  ** content for any page that really does lie past the end of the database
63456  ** file on disk. So the effects of disabling the no-content optimization
63457  ** here are confined to those pages that lie between the end of the
63458  ** database image and the end of the database file.
63459  */
63460  int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
63461 
63462  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
63463  if( rc ) return rc;
63464  pBt->nPage++;
63465  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
63466 
63467 #ifndef SQLITE_OMIT_AUTOVACUUM
63468  if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
63469  /* If *pPgno refers to a pointer-map page, allocate two new pages
63470  ** at the end of the file instead of one. The first allocated page
63471  ** becomes a new pointer-map page, the second is used by the caller.
63472  */
63473  MemPage *pPg = 0;
63474  TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
63475  assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
63476  rc = btreeGetUnusedPage(pBt, pBt->nPage, &pPg, bNoContent);
63477  if( rc==SQLITE_OK ){
63478  rc = sqlite3PagerWrite(pPg->pDbPage);
63479  releasePage(pPg);
63480  }
63481  if( rc ) return rc;
63482  pBt->nPage++;
63483  if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
63484  }
63485 #endif
63486  put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
63487  *pPgno = pBt->nPage;
63488 
63489  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63490  rc = btreeGetUnusedPage(pBt, *pPgno, ppPage, bNoContent);
63491  if( rc ) return rc;
63492  rc = sqlite3PagerWrite((*ppPage)->pDbPage);
63493  if( rc!=SQLITE_OK ){
63494  releasePage(*ppPage);
63495  *ppPage = 0;
63496  }
63497  TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
63498  }
63499 
63500  assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
63501 
63502 end_allocate_page:
63503  releasePage(pTrunk);
63504  releasePage(pPrevTrunk);
63505  assert( rc!=SQLITE_OK || sqlite3PagerPageRefcount((*ppPage)->pDbPage)<=1 );
63506  assert( rc!=SQLITE_OK || (*ppPage)->isInit==0 );
63507  return rc;
63508 }
63509 
63510 /*
63511 ** This function is used to add page iPage to the database file free-list.
63512 ** It is assumed that the page is not already a part of the free-list.
63513 **
63514 ** The value passed as the second argument to this function is optional.
63515 ** If the caller happens to have a pointer to the MemPage object
63516 ** corresponding to page iPage handy, it may pass it as the second value.
63517 ** Otherwise, it may pass NULL.
63518 **
63519 ** If a pointer to a MemPage object is passed as the second argument,
63520 ** its reference count is not altered by this function.
63521 */
63522 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
63523  MemPage *pTrunk = 0; /* Free-list trunk page */
63524  Pgno iTrunk = 0; /* Page number of free-list trunk page */
63525  MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
63526  MemPage *pPage; /* Page being freed. May be NULL. */
63527  int rc; /* Return Code */
63528  int nFree; /* Initial number of pages on free-list */
63529 
63530  assert( sqlite3_mutex_held(pBt->mutex) );
63531  assert( CORRUPT_DB || iPage>1 );
63532  assert( !pMemPage || pMemPage->pgno==iPage );
63533 
63534  if( iPage<2 ) return SQLITE_CORRUPT_BKPT;
63535  if( pMemPage ){
63536  pPage = pMemPage;
63537  sqlite3PagerRef(pPage->pDbPage);
63538  }else{
63539  pPage = btreePageLookup(pBt, iPage);
63540  }
63541 
63542  /* Increment the free page count on pPage1 */
63543  rc = sqlite3PagerWrite(pPage1->pDbPage);
63544  if( rc ) goto freepage_out;
63545  nFree = get4byte(&pPage1->aData[36]);
63546  put4byte(&pPage1->aData[36], nFree+1);
63547 
63548  if( pBt->btsFlags & BTS_SECURE_DELETE ){
63549  /* If the secure_delete option is enabled, then
63550  ** always fully overwrite deleted information with zeros.
63551  */
63552  if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
63553  || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
63554  ){
63555  goto freepage_out;
63556  }
63557  memset(pPage->aData, 0, pPage->pBt->pageSize);
63558  }
63559 
63560  /* If the database supports auto-vacuum, write an entry in the pointer-map
63561  ** to indicate that the page is free.
63562  */
63563  if( ISAUTOVACUUM ){
63564  ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
63565  if( rc ) goto freepage_out;
63566  }
63567 
63568  /* Now manipulate the actual database free-list structure. There are two
63569  ** possibilities. If the free-list is currently empty, or if the first
63570  ** trunk page in the free-list is full, then this page will become a
63571  ** new free-list trunk page. Otherwise, it will become a leaf of the
63572  ** first trunk page in the current free-list. This block tests if it
63573  ** is possible to add the page as a new free-list leaf.
63574  */
63575  if( nFree!=0 ){
63576  u32 nLeaf; /* Initial number of leaf cells on trunk page */
63577 
63578  iTrunk = get4byte(&pPage1->aData[32]);
63579  rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
63580  if( rc!=SQLITE_OK ){
63581  goto freepage_out;
63582  }
63583 
63584  nLeaf = get4byte(&pTrunk->aData[4]);
63585  assert( pBt->usableSize>32 );
63586  if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
63587  rc = SQLITE_CORRUPT_BKPT;
63588  goto freepage_out;
63589  }
63590  if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
63591  /* In this case there is room on the trunk page to insert the page
63592  ** being freed as a new leaf.
63593  **
63594  ** Note that the trunk page is not really full until it contains
63595  ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
63596  ** coded. But due to a coding error in versions of SQLite prior to
63597  ** 3.6.0, databases with freelist trunk pages holding more than
63598  ** usableSize/4 - 8 entries will be reported as corrupt. In order
63599  ** to maintain backwards compatibility with older versions of SQLite,
63600  ** we will continue to restrict the number of entries to usableSize/4 - 8
63601  ** for now. At some point in the future (once everyone has upgraded
63602  ** to 3.6.0 or later) we should consider fixing the conditional above
63603  ** to read "usableSize/4-2" instead of "usableSize/4-8".
63604  **
63605  ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
63606  ** avoid using the last six entries in the freelist trunk page array in
63607  ** order that database files created by newer versions of SQLite can be
63608  ** read by older versions of SQLite.
63609  */
63610  rc = sqlite3PagerWrite(pTrunk->pDbPage);
63611  if( rc==SQLITE_OK ){
63612  put4byte(&pTrunk->aData[4], nLeaf+1);
63613  put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
63614  if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
63616  }
63617  rc = btreeSetHasContent(pBt, iPage);
63618  }
63619  TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
63620  goto freepage_out;
63621  }
63622  }
63623 
63624  /* If control flows to this point, then it was not possible to add the
63625  ** the page being freed as a leaf page of the first trunk in the free-list.
63626  ** Possibly because the free-list is empty, or possibly because the
63627  ** first trunk in the free-list is full. Either way, the page being freed
63628  ** will become the new first trunk page in the free-list.
63629  */
63630  if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
63631  goto freepage_out;
63632  }
63633  rc = sqlite3PagerWrite(pPage->pDbPage);
63634  if( rc!=SQLITE_OK ){
63635  goto freepage_out;
63636  }
63637  put4byte(pPage->aData, iTrunk);
63638  put4byte(&pPage->aData[4], 0);
63639  put4byte(&pPage1->aData[32], iPage);
63640  TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
63641 
63642 freepage_out:
63643  if( pPage ){
63644  pPage->isInit = 0;
63645  }
63646  releasePage(pPage);
63647  releasePage(pTrunk);
63648  return rc;
63649 }
63650 static void freePage(MemPage *pPage, int *pRC){
63651  if( (*pRC)==SQLITE_OK ){
63652  *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
63653  }
63654 }
63655 
63656 /*
63657 ** Free any overflow pages associated with the given Cell. Write the
63658 ** local Cell size (the number of bytes on the original page, omitting
63659 ** overflow) into *pnSize.
63660 */
63661 static int clearCell(
63662  MemPage *pPage, /* The page that contains the Cell */
63663  unsigned char *pCell, /* First byte of the Cell */
63664  u16 *pnSize /* Write the size of the Cell here */
63665 ){
63666  BtShared *pBt = pPage->pBt;
63667  CellInfo info;
63668  Pgno ovflPgno;
63669  int rc;
63670  int nOvfl;
63671  u32 ovflPageSize;
63672 
63673  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
63674  pPage->xParseCell(pPage, pCell, &info);
63675  *pnSize = info.nSize;
63676  if( info.nLocal==info.nPayload ){
63677  return SQLITE_OK; /* No overflow pages. Return without doing anything */
63678  }
63679  if( pCell+info.nSize-1 > pPage->aData+pPage->maskPage ){
63680  return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
63681  }
63682  ovflPgno = get4byte(pCell + info.nSize - 4);
63683  assert( pBt->usableSize > 4 );
63684  ovflPageSize = pBt->usableSize - 4;
63685  nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
63686  assert( nOvfl>0 ||
63687  (CORRUPT_DB && (info.nPayload + ovflPageSize)<ovflPageSize)
63688  );
63689  while( nOvfl-- ){
63690  Pgno iNext = 0;
63691  MemPage *pOvfl = 0;
63692  if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
63693  /* 0 is not a legal page number and page 1 cannot be an
63694  ** overflow page. Therefore if ovflPgno<2 or past the end of the
63695  ** file the database must be corrupt. */
63696  return SQLITE_CORRUPT_BKPT;
63697  }
63698  if( nOvfl ){
63699  rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
63700  if( rc ) return rc;
63701  }
63702 
63703  if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
63704  && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
63705  ){
63706  /* There is no reason any cursor should have an outstanding reference
63707  ** to an overflow page belonging to a cell that is being deleted/updated.
63708  ** So if there exists more than one reference to this page, then it
63709  ** must not really be an overflow page and the database must be corrupt.
63710  ** It is helpful to detect this before calling freePage2(), as
63711  ** freePage2() may zero the page contents if secure-delete mode is
63712  ** enabled. If this 'overflow' page happens to be a page that the
63713  ** caller is iterating through or using in some other way, this
63714  ** can be problematic.
63715  */
63716  rc = SQLITE_CORRUPT_BKPT;
63717  }else{
63718  rc = freePage2(pBt, pOvfl, ovflPgno);
63719  }
63720 
63721  if( pOvfl ){
63722  sqlite3PagerUnref(pOvfl->pDbPage);
63723  }
63724  if( rc ) return rc;
63725  ovflPgno = iNext;
63726  }
63727  return SQLITE_OK;
63728 }
63729 
63730 /*
63731 ** Create the byte sequence used to represent a cell on page pPage
63732 ** and write that byte sequence into pCell[]. Overflow pages are
63733 ** allocated and filled in as necessary. The calling procedure
63734 ** is responsible for making sure sufficient space has been allocated
63735 ** for pCell[].
63736 **
63737 ** Note that pCell does not necessary need to point to the pPage->aData
63738 ** area. pCell might point to some temporary storage. The cell will
63739 ** be constructed in this temporary area then copied into pPage->aData
63740 ** later.
63741 */
63742 static int fillInCell(
63743  MemPage *pPage, /* The page that contains the cell */
63744  unsigned char *pCell, /* Complete text of the cell */
63745  const void *pKey, i64 nKey, /* The key */
63746  const void *pData,int nData, /* The data */
63747  int nZero, /* Extra zero bytes to append to pData */
63748  int *pnSize /* Write cell size here */
63749 ){
63750  int nPayload;
63751  const u8 *pSrc;
63752  int nSrc, n, rc;
63753  int spaceLeft;
63754  MemPage *pOvfl = 0;
63755  MemPage *pToRelease = 0;
63756  unsigned char *pPrior;
63757  unsigned char *pPayload;
63758  BtShared *pBt = pPage->pBt;
63759  Pgno pgnoOvfl = 0;
63760  int nHeader;
63761 
63762  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
63763 
63764  /* pPage is not necessarily writeable since pCell might be auxiliary
63765  ** buffer space that is separate from the pPage buffer area */
63766  assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
63767  || sqlite3PagerIswriteable(pPage->pDbPage) );
63768 
63769  /* Fill in the header. */
63770  nHeader = pPage->childPtrSize;
63771  nPayload = nData + nZero;
63772  if( pPage->intKeyLeaf ){
63773  nHeader += putVarint32(&pCell[nHeader], nPayload);
63774  }else{
63775  assert( nData==0 );
63776  assert( nZero==0 );
63777  }
63778  nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
63779 
63780  /* Fill in the payload size */
63781  if( pPage->intKey ){
63782  pSrc = pData;
63783  nSrc = nData;
63784  nData = 0;
63785  }else{
63786  assert( nKey<=0x7fffffff && pKey!=0 );
63787  nPayload = (int)nKey;
63788  pSrc = pKey;
63789  nSrc = (int)nKey;
63790  }
63791  if( nPayload<=pPage->maxLocal ){
63792  n = nHeader + nPayload;
63793  testcase( n==3 );
63794  testcase( n==4 );
63795  if( n<4 ) n = 4;
63796  *pnSize = n;
63797  spaceLeft = nPayload;
63798  pPrior = pCell;
63799  }else{
63800  int mn = pPage->minLocal;
63801  n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
63802  testcase( n==pPage->maxLocal );
63803  testcase( n==pPage->maxLocal+1 );
63804  if( n > pPage->maxLocal ) n = mn;
63805  spaceLeft = n;
63806  *pnSize = n + nHeader + 4;
63807  pPrior = &pCell[nHeader+n];
63808  }
63809  pPayload = &pCell[nHeader];
63810 
63811  /* At this point variables should be set as follows:
63812  **
63813  ** nPayload Total payload size in bytes
63814  ** pPayload Begin writing payload here
63815  ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
63816  ** that means content must spill into overflow pages.
63817  ** *pnSize Size of the local cell (not counting overflow pages)
63818  ** pPrior Where to write the pgno of the first overflow page
63819  **
63820  ** Use a call to btreeParseCellPtr() to verify that the values above
63821  ** were computed correctly.
63822  */
63823 #if SQLITE_DEBUG
63824  {
63825  CellInfo info;
63826  pPage->xParseCell(pPage, pCell, &info);
63827  assert( nHeader==(int)(info.pPayload - pCell) );
63828  assert( info.nKey==nKey );
63829  assert( *pnSize == info.nSize );
63830  assert( spaceLeft == info.nLocal );
63831  }
63832 #endif
63833 
63834  /* Write the payload into the local Cell and any extra into overflow pages */
63835  while( nPayload>0 ){
63836  if( spaceLeft==0 ){
63837 #ifndef SQLITE_OMIT_AUTOVACUUM
63838  Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
63839  if( pBt->autoVacuum ){
63840  do{
63841  pgnoOvfl++;
63842  } while(
63843  PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
63844  );
63845  }
63846 #endif
63847  rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
63848 #ifndef SQLITE_OMIT_AUTOVACUUM
63849  /* If the database supports auto-vacuum, and the second or subsequent
63850  ** overflow page is being allocated, add an entry to the pointer-map
63851  ** for that page now.
63852  **
63853  ** If this is the first overflow page, then write a partial entry
63854  ** to the pointer-map. If we write nothing to this pointer-map slot,
63855  ** then the optimistic overflow chain processing in clearCell()
63856  ** may misinterpret the uninitialized values and delete the
63857  ** wrong pages from the database.
63858  */
63859  if( pBt->autoVacuum && rc==SQLITE_OK ){
63860  u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
63861  ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
63862  if( rc ){
63863  releasePage(pOvfl);
63864  }
63865  }
63866 #endif
63867  if( rc ){
63868  releasePage(pToRelease);
63869  return rc;
63870  }
63871 
63872  /* If pToRelease is not zero than pPrior points into the data area
63873  ** of pToRelease. Make sure pToRelease is still writeable. */
63874  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
63875 
63876  /* If pPrior is part of the data area of pPage, then make sure pPage
63877  ** is still writeable */
63878  assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
63879  || sqlite3PagerIswriteable(pPage->pDbPage) );
63880 
63881  put4byte(pPrior, pgnoOvfl);
63882  releasePage(pToRelease);
63883  pToRelease = pOvfl;
63884  pPrior = pOvfl->aData;
63885  put4byte(pPrior, 0);
63886  pPayload = &pOvfl->aData[4];
63887  spaceLeft = pBt->usableSize - 4;
63888  }
63889  n = nPayload;
63890  if( n>spaceLeft ) n = spaceLeft;
63891 
63892  /* If pToRelease is not zero than pPayload points into the data area
63893  ** of pToRelease. Make sure pToRelease is still writeable. */
63894  assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
63895 
63896  /* If pPayload is part of the data area of pPage, then make sure pPage
63897  ** is still writeable */
63898  assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
63899  || sqlite3PagerIswriteable(pPage->pDbPage) );
63900 
63901  if( nSrc>0 ){
63902  if( n>nSrc ) n = nSrc;
63903  assert( pSrc );
63904  memcpy(pPayload, pSrc, n);
63905  }else{
63906  memset(pPayload, 0, n);
63907  }
63908  nPayload -= n;
63909  pPayload += n;
63910  pSrc += n;
63911  nSrc -= n;
63912  spaceLeft -= n;
63913  if( nSrc==0 ){
63914  nSrc = nData;
63915  pSrc = pData;
63916  }
63917  }
63918  releasePage(pToRelease);
63919  return SQLITE_OK;
63920 }
63921 
63922 /*
63923 ** Remove the i-th cell from pPage. This routine effects pPage only.
63924 ** The cell content is not freed or deallocated. It is assumed that
63925 ** the cell content has been copied someplace else. This routine just
63926 ** removes the reference to the cell from pPage.
63927 **
63928 ** "sz" must be the number of bytes in the cell.
63929 */
63930 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
63931  u32 pc; /* Offset to cell content of cell being deleted */
63932  u8 *data; /* pPage->aData */
63933  u8 *ptr; /* Used to move bytes around within data[] */
63934  int rc; /* The return code */
63935  int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
63936 
63937  if( *pRC ) return;
63938 
63939  assert( idx>=0 && idx<pPage->nCell );
63940  assert( CORRUPT_DB || sz==cellSize(pPage, idx) );
63941  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
63942  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
63943  data = pPage->aData;
63944  ptr = &pPage->aCellIdx[2*idx];
63945  pc = get2byte(ptr);
63946  hdr = pPage->hdrOffset;
63947  testcase( pc==get2byte(&data[hdr+5]) );
63948  testcase( pc+sz==pPage->pBt->usableSize );
63949  if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
63950  *pRC = SQLITE_CORRUPT_BKPT;
63951  return;
63952  }
63953  rc = freeSpace(pPage, pc, sz);
63954  if( rc ){
63955  *pRC = rc;
63956  return;
63957  }
63958  pPage->nCell--;
63959  if( pPage->nCell==0 ){
63960  memset(&data[hdr+1], 0, 4);
63961  data[hdr+7] = 0;
63962  put2byte(&data[hdr+5], pPage->pBt->usableSize);
63963  pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
63964  - pPage->childPtrSize - 8;
63965  }else{
63966  memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
63967  put2byte(&data[hdr+3], pPage->nCell);
63968  pPage->nFree += 2;
63969  }
63970 }
63971 
63972 /*
63973 ** Insert a new cell on pPage at cell index "i". pCell points to the
63974 ** content of the cell.
63975 **
63976 ** If the cell content will fit on the page, then put it there. If it
63977 ** will not fit, then make a copy of the cell content into pTemp if
63978 ** pTemp is not null. Regardless of pTemp, allocate a new entry
63979 ** in pPage->apOvfl[] and make it point to the cell content (either
63980 ** in pTemp or the original pCell) and also record its index.
63981 ** Allocating a new entry in pPage->aCell[] implies that
63982 ** pPage->nOverflow is incremented.
63983 */
63984 static void insertCell(
63985  MemPage *pPage, /* Page into which we are copying */
63986  int i, /* New cell becomes the i-th cell of the page */
63987  u8 *pCell, /* Content of the new cell */
63988  int sz, /* Bytes of content in pCell */
63989  u8 *pTemp, /* Temp storage space for pCell, if needed */
63990  Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
63991  int *pRC /* Read and write return code from here */
63992 ){
63993  int idx = 0; /* Where to write new cell content in data[] */
63994  int j; /* Loop counter */
63995  u8 *data; /* The content of the whole page */
63996  u8 *pIns; /* The point in pPage->aCellIdx[] where no cell inserted */
63997 
63998  if( *pRC ) return;
63999 
64000  assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
64001  assert( MX_CELL(pPage->pBt)<=10921 );
64002  assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
64003  assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
64004  assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
64005  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64006  /* The cell should normally be sized correctly. However, when moving a
64007  ** malformed cell from a leaf page to an interior page, if the cell size
64008  ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
64009  ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
64010  ** the term after the || in the following assert(). */
64011  assert( sz==pPage->xCellSize(pPage, pCell) || (sz==8 && iChild>0) );
64012  if( pPage->nOverflow || sz+2>pPage->nFree ){
64013  if( pTemp ){
64014  memcpy(pTemp, pCell, sz);
64015  pCell = pTemp;
64016  }
64017  if( iChild ){
64018  put4byte(pCell, iChild);
64019  }
64020  j = pPage->nOverflow++;
64021  assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
64022  pPage->apOvfl[j] = pCell;
64023  pPage->aiOvfl[j] = (u16)i;
64024 
64025  /* When multiple overflows occur, they are always sequential and in
64026  ** sorted order. This invariants arise because multiple overflows can
64027  ** only occur when inserting divider cells into the parent page during
64028  ** balancing, and the dividers are adjacent and sorted.
64029  */
64030  assert( j==0 || pPage->aiOvfl[j-1]<(u16)i ); /* Overflows in sorted order */
64031  assert( j==0 || i==pPage->aiOvfl[j-1]+1 ); /* Overflows are sequential */
64032  }else{
64033  int rc = sqlite3PagerWrite(pPage->pDbPage);
64034  if( rc!=SQLITE_OK ){
64035  *pRC = rc;
64036  return;
64037  }
64038  assert( sqlite3PagerIswriteable(pPage->pDbPage) );
64039  data = pPage->aData;
64040  assert( &data[pPage->cellOffset]==pPage->aCellIdx );
64041  rc = allocateSpace(pPage, sz, &idx);
64042  if( rc ){ *pRC = rc; return; }
64043  /* The allocateSpace() routine guarantees the following properties
64044  ** if it returns successfully */
64045  assert( idx >= 0 );
64046  assert( idx >= pPage->cellOffset+2*pPage->nCell+2 || CORRUPT_DB );
64047  assert( idx+sz <= (int)pPage->pBt->usableSize );
64048  pPage->nFree -= (u16)(2 + sz);
64049  memcpy(&data[idx], pCell, sz);
64050  if( iChild ){
64051  put4byte(&data[idx], iChild);
64052  }
64053  pIns = pPage->aCellIdx + i*2;
64054  memmove(pIns+2, pIns, 2*(pPage->nCell - i));
64055  put2byte(pIns, idx);
64056  pPage->nCell++;
64057  /* increment the cell count */
64058  if( (++data[pPage->hdrOffset+4])==0 ) data[pPage->hdrOffset+3]++;
64059  assert( get2byte(&data[pPage->hdrOffset+3])==pPage->nCell );
64060 #ifndef SQLITE_OMIT_AUTOVACUUM
64061  if( pPage->pBt->autoVacuum ){
64062  /* The cell may contain a pointer to an overflow page. If so, write
64063  ** the entry for the overflow page into the pointer map.
64064  */
64065  ptrmapPutOvflPtr(pPage, pCell, pRC);
64066  }
64067 #endif
64068  }
64069 }
64070 
64071 /*
64072 ** A CellArray object contains a cache of pointers and sizes for a
64073 ** consecutive sequence of cells that might be held multiple pages.
64074 */
64075 typedef struct CellArray CellArray;
64076 struct CellArray {
64077  int nCell; /* Number of cells in apCell[] */
64078  MemPage *pRef; /* Reference page */
64079  u8 **apCell; /* All cells begin balanced */
64080  u16 *szCell; /* Local size of all cells in apCell[] */
64081 };
64082 
64083 /*
64084 ** Make sure the cell sizes at idx, idx+1, ..., idx+N-1 have been
64085 ** computed.
64086 */
64087 static void populateCellCache(CellArray *p, int idx, int N){
64088  assert( idx>=0 && idx+N<=p->nCell );
64089  while( N>0 ){
64090  assert( p->apCell[idx]!=0 );
64091  if( p->szCell[idx]==0 ){
64092  p->szCell[idx] = p->pRef->xCellSize(p->pRef, p->apCell[idx]);
64093  }else{
64094  assert( CORRUPT_DB ||
64095  p->szCell[idx]==p->pRef->xCellSize(p->pRef, p->apCell[idx]) );
64096  }
64097  idx++;
64098  N--;
64099  }
64100 }
64101 
64102 /*
64103 ** Return the size of the Nth element of the cell array
64104 */
64106  assert( N>=0 && N<p->nCell );
64107  assert( p->szCell[N]==0 );
64108  p->szCell[N] = p->pRef->xCellSize(p->pRef, p->apCell[N]);
64109  return p->szCell[N];
64110 }
64111 static u16 cachedCellSize(CellArray *p, int N){
64112  assert( N>=0 && N<p->nCell );
64113  if( p->szCell[N] ) return p->szCell[N];
64114  return computeCellSize(p, N);
64115 }
64116 
64117 /*
64118 ** Array apCell[] contains pointers to nCell b-tree page cells. The
64119 ** szCell[] array contains the size in bytes of each cell. This function
64120 ** replaces the current contents of page pPg with the contents of the cell
64121 ** array.
64122 **
64123 ** Some of the cells in apCell[] may currently be stored in pPg. This
64124 ** function works around problems caused by this by making a copy of any
64125 ** such cells before overwriting the page data.
64126 **
64127 ** The MemPage.nFree field is invalidated by this function. It is the
64128 ** responsibility of the caller to set it correctly.
64129 */
64130 static int rebuildPage(
64131  MemPage *pPg, /* Edit this page */
64132  int nCell, /* Final number of cells on page */
64133  u8 **apCell, /* Array of cells */
64134  u16 *szCell /* Array of cell sizes */
64135 ){
64136  const int hdr = pPg->hdrOffset; /* Offset of header on pPg */
64137  u8 * const aData = pPg->aData; /* Pointer to data for pPg */
64138  const int usableSize = pPg->pBt->usableSize;
64139  u8 * const pEnd = &aData[usableSize];
64140  int i;
64141  u8 *pCellptr = pPg->aCellIdx;
64142  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64143  u8 *pData;
64144 
64145  i = get2byte(&aData[hdr+5]);
64146  memcpy(&pTmp[i], &aData[i], usableSize - i);
64147 
64148  pData = pEnd;
64149  for(i=0; i<nCell; i++){
64150  u8 *pCell = apCell[i];
64151  if( SQLITE_WITHIN(pCell,aData,pEnd) ){
64152  pCell = &pTmp[pCell - aData];
64153  }
64154  pData -= szCell[i];
64155  put2byte(pCellptr, (pData - aData));
64156  pCellptr += 2;
64157  if( pData < pCellptr ) return SQLITE_CORRUPT_BKPT;
64158  memcpy(pData, pCell, szCell[i]);
64159  assert( szCell[i]==pPg->xCellSize(pPg, pCell) || CORRUPT_DB );
64160  testcase( szCell[i]!=pPg->xCellSize(pPg,pCell) );
64161  }
64162 
64163  /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
64164  pPg->nCell = nCell;
64165  pPg->nOverflow = 0;
64166 
64167  put2byte(&aData[hdr+1], 0);
64168  put2byte(&aData[hdr+3], pPg->nCell);
64169  put2byte(&aData[hdr+5], pData - aData);
64170  aData[hdr+7] = 0x00;
64171  return SQLITE_OK;
64172 }
64173 
64174 /*
64175 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64176 ** contains the size in bytes of each such cell. This function attempts to
64177 ** add the cells stored in the array to page pPg. If it cannot (because
64178 ** the page needs to be defragmented before the cells will fit), non-zero
64179 ** is returned. Otherwise, if the cells are added successfully, zero is
64180 ** returned.
64181 **
64182 ** Argument pCellptr points to the first entry in the cell-pointer array
64183 ** (part of page pPg) to populate. After cell apCell[0] is written to the
64184 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
64185 ** cell in the array. It is the responsibility of the caller to ensure
64186 ** that it is safe to overwrite this part of the cell-pointer array.
64187 **
64188 ** When this function is called, *ppData points to the start of the
64189 ** content area on page pPg. If the size of the content area is extended,
64190 ** *ppData is updated to point to the new start of the content area
64191 ** before returning.
64192 **
64193 ** Finally, argument pBegin points to the byte immediately following the
64194 ** end of the space required by this page for the cell-pointer area (for
64195 ** all cells - not just those inserted by the current call). If the content
64196 ** area must be extended to before this point in order to accomodate all
64197 ** cells in apCell[], then the cells do not fit and non-zero is returned.
64198 */
64199 static int pageInsertArray(
64200  MemPage *pPg, /* Page to add cells to */
64201  u8 *pBegin, /* End of cell-pointer array */
64202  u8 **ppData, /* IN/OUT: Page content -area pointer */
64203  u8 *pCellptr, /* Pointer to cell-pointer area */
64204  int iFirst, /* Index of first cell to add */
64205  int nCell, /* Number of cells to add to pPg */
64206  CellArray *pCArray /* Array of cells */
64207 ){
64208  int i;
64209  u8 *aData = pPg->aData;
64210  u8 *pData = *ppData;
64211  int iEnd = iFirst + nCell;
64212  assert( CORRUPT_DB || pPg->hdrOffset==0 ); /* Never called on page 1 */
64213  for(i=iFirst; i<iEnd; i++){
64214  int sz, rc;
64215  u8 *pSlot;
64216  sz = cachedCellSize(pCArray, i);
64217  if( (aData[1]==0 && aData[2]==0) || (pSlot = pageFindSlot(pPg,sz,&rc))==0 ){
64218  if( (pData - pBegin)<sz ) return 1;
64219  pData -= sz;
64220  pSlot = pData;
64221  }
64222  /* pSlot and pCArray->apCell[i] will never overlap on a well-formed
64223  ** database. But they might for a corrupt database. Hence use memmove()
64224  ** since memcpy() sends SIGABORT with overlapping buffers on OpenBSD */
64225  assert( (pSlot+sz)<=pCArray->apCell[i]
64226  || pSlot>=(pCArray->apCell[i]+sz)
64227  || CORRUPT_DB );
64228  memmove(pSlot, pCArray->apCell[i], sz);
64229  put2byte(pCellptr, (pSlot - aData));
64230  pCellptr += 2;
64231  }
64232  *ppData = pData;
64233  return 0;
64234 }
64235 
64236 /*
64237 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
64238 ** contains the size in bytes of each such cell. This function adds the
64239 ** space associated with each cell in the array that is currently stored
64240 ** within the body of pPg to the pPg free-list. The cell-pointers and other
64241 ** fields of the page are not updated.
64242 **
64243 ** This function returns the total number of cells added to the free-list.
64244 */
64245 static int pageFreeArray(
64246  MemPage *pPg, /* Page to edit */
64247  int iFirst, /* First cell to delete */
64248  int nCell, /* Cells to delete */
64249  CellArray *pCArray /* Array of cells */
64250 ){
64251  u8 * const aData = pPg->aData;
64252  u8 * const pEnd = &aData[pPg->pBt->usableSize];
64253  u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
64254  int nRet = 0;
64255  int i;
64256  int iEnd = iFirst + nCell;
64257  u8 *pFree = 0;
64258  int szFree = 0;
64259 
64260  for(i=iFirst; i<iEnd; i++){
64261  u8 *pCell = pCArray->apCell[i];
64262  if( SQLITE_WITHIN(pCell, pStart, pEnd) ){
64263  int sz;
64264  /* No need to use cachedCellSize() here. The sizes of all cells that
64265  ** are to be freed have already been computing while deciding which
64266  ** cells need freeing */
64267  sz = pCArray->szCell[i]; assert( sz>0 );
64268  if( pFree!=(pCell + sz) ){
64269  if( pFree ){
64270  assert( pFree>aData && (pFree - aData)<65536 );
64271  freeSpace(pPg, (u16)(pFree - aData), szFree);
64272  }
64273  pFree = pCell;
64274  szFree = sz;
64275  if( pFree+sz>pEnd ) return 0;
64276  }else{
64277  pFree = pCell;
64278  szFree += sz;
64279  }
64280  nRet++;
64281  }
64282  }
64283  if( pFree ){
64284  assert( pFree>aData && (pFree - aData)<65536 );
64285  freeSpace(pPg, (u16)(pFree - aData), szFree);
64286  }
64287  return nRet;
64288 }
64289 
64290 /*
64291 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
64292 ** pages being balanced. The current page, pPg, has pPg->nCell cells starting
64293 ** with apCell[iOld]. After balancing, this page should hold nNew cells
64294 ** starting at apCell[iNew].
64295 **
64296 ** This routine makes the necessary adjustments to pPg so that it contains
64297 ** the correct cells after being balanced.
64298 **
64299 ** The pPg->nFree field is invalid when this function returns. It is the
64300 ** responsibility of the caller to set it correctly.
64301 */
64302 static int editPage(
64303  MemPage *pPg, /* Edit this page */
64304  int iOld, /* Index of first cell currently on page */
64305  int iNew, /* Index of new first cell on page */
64306  int nNew, /* Final number of cells on page */
64307  CellArray *pCArray /* Array of cells and sizes */
64308 ){
64309  u8 * const aData = pPg->aData;
64310  const int hdr = pPg->hdrOffset;
64311  u8 *pBegin = &pPg->aCellIdx[nNew * 2];
64312  int nCell = pPg->nCell; /* Cells stored on pPg */
64313  u8 *pData;
64314  u8 *pCellptr;
64315  int i;
64316  int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
64317  int iNewEnd = iNew + nNew;
64318 
64319 #ifdef SQLITE_DEBUG
64320  u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
64321  memcpy(pTmp, aData, pPg->pBt->usableSize);
64322 #endif
64323 
64324  /* Remove cells from the start and end of the page */
64325  if( iOld<iNew ){
64326  int nShift = pageFreeArray(pPg, iOld, iNew-iOld, pCArray);
64327  memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
64328  nCell -= nShift;
64329  }
64330  if( iNewEnd < iOldEnd ){
64331  nCell -= pageFreeArray(pPg, iNewEnd, iOldEnd - iNewEnd, pCArray);
64332  }
64333 
64334  pData = &aData[get2byteNotZero(&aData[hdr+5])];
64335  if( pData<pBegin ) goto editpage_fail;
64336 
64337  /* Add cells to the start of the page */
64338  if( iNew<iOld ){
64339  int nAdd = MIN(nNew,iOld-iNew);
64340  assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
64341  pCellptr = pPg->aCellIdx;
64342  memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
64343  if( pageInsertArray(
64344  pPg, pBegin, &pData, pCellptr,
64345  iNew, nAdd, pCArray
64346  ) ) goto editpage_fail;
64347  nCell += nAdd;
64348  }
64349 
64350  /* Add any overflow cells */
64351  for(i=0; i<pPg->nOverflow; i++){
64352  int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
64353  if( iCell>=0 && iCell<nNew ){
64354  pCellptr = &pPg->aCellIdx[iCell * 2];
64355  memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
64356  nCell++;
64357  if( pageInsertArray(
64358  pPg, pBegin, &pData, pCellptr,
64359  iCell+iNew, 1, pCArray
64360  ) ) goto editpage_fail;
64361  }
64362  }
64363 
64364  /* Append cells to the end of the page */
64365  pCellptr = &pPg->aCellIdx[nCell*2];
64366  if( pageInsertArray(
64367  pPg, pBegin, &pData, pCellptr,
64368  iNew+nCell, nNew-nCell, pCArray
64369  ) ) goto editpage_fail;
64370 
64371  pPg->nCell = nNew;
64372  pPg->nOverflow = 0;
64373 
64374  put2byte(&aData[hdr+3], pPg->nCell);
64375  put2byte(&aData[hdr+5], pData - aData);
64376 
64377 #ifdef SQLITE_DEBUG
64378  for(i=0; i<nNew && !CORRUPT_DB; i++){
64379  u8 *pCell = pCArray->apCell[i+iNew];
64380  int iOff = get2byteAligned(&pPg->aCellIdx[i*2]);
64381  if( SQLITE_WITHIN(pCell, aData, &aData[pPg->pBt->usableSize]) ){
64382  pCell = &pTmp[pCell - aData];
64383  }
64384  assert( 0==memcmp(pCell, &aData[iOff],
64385  pCArray->pRef->xCellSize(pCArray->pRef, pCArray->apCell[i+iNew])) );
64386  }
64387 #endif
64388 
64389  return SQLITE_OK;
64390  editpage_fail:
64391  /* Unable to edit this page. Rebuild it from scratch instead. */
64392  populateCellCache(pCArray, iNew, nNew);
64393  return rebuildPage(pPg, nNew, &pCArray->apCell[iNew], &pCArray->szCell[iNew]);
64394 }
64395 
64396 /*
64397 ** The following parameters determine how many adjacent pages get involved
64398 ** in a balancing operation. NN is the number of neighbors on either side
64399 ** of the page that participate in the balancing operation. NB is the
64400 ** total number of pages that participate, including the target page and
64401 ** NN neighbors on either side.
64402 **
64403 ** The minimum value of NN is 1 (of course). Increasing NN above 1
64404 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
64405 ** in exchange for a larger degradation in INSERT and UPDATE performance.
64406 ** The value of NN appears to give the best results overall.
64407 */
64408 #define NN 1 /* Number of neighbors on either side of pPage */
64409 #define NB (NN*2+1) /* Total pages involved in the balance */
64410 
64411 
64412 #ifndef SQLITE_OMIT_QUICKBALANCE
64413 /*
64414 ** This version of balance() handles the common special case where
64415 ** a new entry is being inserted on the extreme right-end of the
64416 ** tree, in other words, when the new entry will become the largest
64417 ** entry in the tree.
64418 **
64419 ** Instead of trying to balance the 3 right-most leaf pages, just add
64420 ** a new page to the right-hand side and put the one new entry in
64421 ** that page. This leaves the right side of the tree somewhat
64422 ** unbalanced. But odds are that we will be inserting new entries
64423 ** at the end soon afterwards so the nearly empty page will quickly
64424 ** fill up. On average.
64425 **
64426 ** pPage is the leaf page which is the right-most page in the tree.
64427 ** pParent is its parent. pPage must have a single overflow entry
64428 ** which is also the right-most entry on the page.
64429 **
64430 ** The pSpace buffer is used to store a temporary copy of the divider
64431 ** cell that will be inserted into pParent. Such a cell consists of a 4
64432 ** byte page number followed by a variable length integer. In other
64433 ** words, at most 13 bytes. Hence the pSpace buffer must be at
64434 ** least 13 bytes in size.
64435 */
64436 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
64437  BtShared *const pBt = pPage->pBt; /* B-Tree Database */
64438  MemPage *pNew; /* Newly allocated page */
64439  int rc; /* Return Code */
64440  Pgno pgnoNew; /* Page number of pNew */
64441 
64442  assert( sqlite3_mutex_held(pPage->pBt->mutex) );
64443  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
64444  assert( pPage->nOverflow==1 );
64445 
64446  /* This error condition is now caught prior to reaching this function */
64447  if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
64448 
64449  /* Allocate a new page. This page will become the right-sibling of
64450  ** pPage. Make the parent page writable, so that the new divider cell
64451  ** may be inserted. If both these operations are successful, proceed.
64452  */
64453  rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
64454 
64455  if( rc==SQLITE_OK ){
64456 
64457  u8 *pOut = &pSpace[4];
64458  u8 *pCell = pPage->apOvfl[0];
64459  u16 szCell = pPage->xCellSize(pPage, pCell);
64460  u8 *pStop;
64461 
64462  assert( sqlite3PagerIswriteable(pNew->pDbPage) );
64463  assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
64465  rc = rebuildPage(pNew, 1, &pCell, &szCell);
64466  if( NEVER(rc) ) return rc;
64467  pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
64468 
64469  /* If this is an auto-vacuum database, update the pointer map
64470  ** with entries for the new page, and any pointer from the
64471  ** cell on the page to an overflow page. If either of these
64472  ** operations fails, the return code is set, but the contents
64473  ** of the parent page are still manipulated by thh code below.
64474  ** That is Ok, at this point the parent page is guaranteed to
64475  ** be marked as dirty. Returning an error code will cause a
64476  ** rollback, undoing any changes made to the parent page.
64477  */
64478  if( ISAUTOVACUUM ){
64479  ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
64480  if( szCell>pNew->minLocal ){
64481  ptrmapPutOvflPtr(pNew, pCell, &rc);
64482  }
64483  }
64484 
64485  /* Create a divider cell to insert into pParent. The divider cell
64486  ** consists of a 4-byte page number (the page number of pPage) and
64487  ** a variable length key value (which must be the same value as the
64488  ** largest key on pPage).
64489  **
64490  ** To find the largest key value on pPage, first find the right-most
64491  ** cell on pPage. The first two fields of this cell are the
64492  ** record-length (a variable length integer at most 32-bits in size)
64493  ** and the key value (a variable length integer, may have any value).
64494  ** The first of the while(...) loops below skips over the record-length
64495  ** field. The second while(...) loop copies the key value from the
64496  ** cell on pPage into the pSpace buffer.
64497  */
64498  pCell = findCell(pPage, pPage->nCell-1);
64499  pStop = &pCell[9];
64500  while( (*(pCell++)&0x80) && pCell<pStop );
64501  pStop = &pCell[9];
64502  while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
64503 
64504  /* Insert the new divider cell into pParent. */
64505  insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
64506  0, pPage->pgno, &rc);
64507 
64508  /* Set the right-child pointer of pParent to point to the new page. */
64509  put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
64510 
64511  /* Release the reference to the new page. */
64512  releasePage(pNew);
64513  }
64514 
64515  return rc;
64516 }
64517 #endif /* SQLITE_OMIT_QUICKBALANCE */
64518 
64519 #if 0
64520 /*
64521 ** This function does not contribute anything to the operation of SQLite.
64522 ** it is sometimes activated temporarily while debugging code responsible
64523 ** for setting pointer-map entries.
64524 */
64525 static int ptrmapCheckPages(MemPage **apPage, int nPage){
64526  int i, j;
64527  for(i=0; i<nPage; i++){
64528  Pgno n;
64529  u8 e;
64530  MemPage *pPage = apPage[i];
64531  BtShared *pBt = pPage->pBt;
64532  assert( pPage->isInit );
64533 
64534  for(j=0; j<pPage->nCell; j++){
64535  CellInfo info;
64536  u8 *z;
64537 
64538  z = findCell(pPage, j);
64539  pPage->xParseCell(pPage, z, &info);
64540  if( info.nLocal<info.nPayload ){
64541  Pgno ovfl = get4byte(&z[info.nSize-4]);
64542  ptrmapGet(pBt, ovfl, &e, &n);
64543  assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
64544  }
64545  if( !pPage->leaf ){
64546  Pgno child = get4byte(z);
64547  ptrmapGet(pBt, child, &e, &n);
64548  assert( n==pPage->pgno && e==PTRMAP_BTREE );
64549  }
64550  }
64551  if( !pPage->leaf ){
64552  Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
64553  ptrmapGet(pBt, child, &e, &n);
64554  assert( n==pPage->pgno && e==PTRMAP_BTREE );
64555  }
64556  }
64557  return 1;
64558 }
64559 #endif
64560 
64561 /*
64562 ** This function is used to copy the contents of the b-tree node stored
64563 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
64564 ** the pointer-map entries for each child page are updated so that the
64565 ** parent page stored in the pointer map is page pTo. If pFrom contained
64566 ** any cells with overflow page pointers, then the corresponding pointer
64567 ** map entries are also updated so that the parent page is page pTo.
64568 **
64569 ** If pFrom is currently carrying any overflow cells (entries in the
64570 ** MemPage.apOvfl[] array), they are not copied to pTo.
64571 **
64572 ** Before returning, page pTo is reinitialized using btreeInitPage().
64573 **
64574 ** The performance of this function is not critical. It is only used by
64575 ** the balance_shallower() and balance_deeper() procedures, neither of
64576 ** which are called often under normal circumstances.
64577 */
64578 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
64579  if( (*pRC)==SQLITE_OK ){
64580  BtShared * const pBt = pFrom->pBt;
64581  u8 * const aFrom = pFrom->aData;
64582  u8 * const aTo = pTo->aData;
64583  int const iFromHdr = pFrom->hdrOffset;
64584  int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
64585  int rc;
64586  int iData;
64587 
64588 
64589  assert( pFrom->isInit );
64590  assert( pFrom->nFree>=iToHdr );
64591  assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
64592 
64593  /* Copy the b-tree node content from page pFrom to page pTo. */
64594  iData = get2byte(&aFrom[iFromHdr+5]);
64595  memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
64596  memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
64597 
64598  /* Reinitialize page pTo so that the contents of the MemPage structure
64599  ** match the new data. The initialization of pTo can actually fail under
64600  ** fairly obscure circumstances, even though it is a copy of initialized
64601  ** page pFrom.
64602  */
64603  pTo->isInit = 0;
64604  rc = btreeInitPage(pTo);
64605  if( rc!=SQLITE_OK ){
64606  *pRC = rc;
64607  return;
64608  }
64609 
64610  /* If this is an auto-vacuum database, update the pointer-map entries
64611  ** for any b-tree or overflow pages that pTo now contains the pointers to.
64612  */
64613  if( ISAUTOVACUUM ){
64614  *pRC = setChildPtrmaps(pTo);
64615  }
64616  }
64617 }
64618 
64619 /*
64620 ** This routine redistributes cells on the iParentIdx'th child of pParent
64621 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
64622 ** same amount of free space. Usually a single sibling on either side of the
64623 ** page are used in the balancing, though both siblings might come from one
64624 ** side if the page is the first or last child of its parent. If the page
64625 ** has fewer than 2 siblings (something which can only happen if the page
64626 ** is a root page or a child of a root page) then all available siblings
64627 ** participate in the balancing.
64628 **
64629 ** The number of siblings of the page might be increased or decreased by
64630 ** one or two in an effort to keep pages nearly full but not over full.
64631 **
64632 ** Note that when this routine is called, some of the cells on the page
64633 ** might not actually be stored in MemPage.aData[]. This can happen
64634 ** if the page is overfull. This routine ensures that all cells allocated
64635 ** to the page and its siblings fit into MemPage.aData[] before returning.
64636 **
64637 ** In the course of balancing the page and its siblings, cells may be
64638 ** inserted into or removed from the parent page (pParent). Doing so
64639 ** may cause the parent page to become overfull or underfull. If this
64640 ** happens, it is the responsibility of the caller to invoke the correct
64641 ** balancing routine to fix this problem (see the balance() routine).
64642 **
64643 ** If this routine fails for any reason, it might leave the database
64644 ** in a corrupted state. So if this routine fails, the database should
64645 ** be rolled back.
64646 **
64647 ** The third argument to this function, aOvflSpace, is a pointer to a
64648 ** buffer big enough to hold one page. If while inserting cells into the parent
64649 ** page (pParent) the parent page becomes overfull, this buffer is
64650 ** used to store the parent's overflow cells. Because this function inserts
64651 ** a maximum of four divider cells into the parent page, and the maximum
64652 ** size of a cell stored within an internal node is always less than 1/4
64653 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
64654 ** enough for all overflow cells.
64655 **
64656 ** If aOvflSpace is set to a null pointer, this function returns
64657 ** SQLITE_NOMEM.
64658 */
64659 static int balance_nonroot(
64660  MemPage *pParent, /* Parent page of siblings being balanced */
64661  int iParentIdx, /* Index of "the page" in pParent */
64662  u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
64663  int isRoot, /* True if pParent is a root-page */
64664  int bBulk /* True if this call is part of a bulk load */
64665 ){
64666  BtShared *pBt; /* The whole database */
64667  int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
64668  int nNew = 0; /* Number of pages in apNew[] */
64669  int nOld; /* Number of pages in apOld[] */
64670  int i, j, k; /* Loop counters */
64671  int nxDiv; /* Next divider slot in pParent->aCell[] */
64672  int rc = SQLITE_OK; /* The return code */
64673  u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
64674  int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
64675  int usableSpace; /* Bytes in pPage beyond the header */
64676  int pageFlags; /* Value of pPage->aData[0] */
64677  int iSpace1 = 0; /* First unused byte of aSpace1[] */
64678  int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
64679  int szScratch; /* Size of scratch memory requested */
64680  MemPage *apOld[NB]; /* pPage and up to two siblings */
64681  MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
64682  u8 *pRight; /* Location in parent of right-sibling pointer */
64683  u8 *apDiv[NB-1]; /* Divider cells in pParent */
64684  int cntNew[NB+2]; /* Index in b.paCell[] of cell after i-th page */
64685  int cntOld[NB+2]; /* Old index in b.apCell[] */
64686  int szNew[NB+2]; /* Combined size of cells placed on i-th page */
64687  u8 *aSpace1; /* Space for copies of dividers cells */
64688  Pgno pgno; /* Temp var to store a page number in */
64689  u8 abDone[NB+2]; /* True after i'th new page is populated */
64690  Pgno aPgno[NB+2]; /* Page numbers of new pages before shuffling */
64691  Pgno aPgOrder[NB+2]; /* Copy of aPgno[] used for sorting pages */
64692  u16 aPgFlags[NB+2]; /* flags field of new pages before shuffling */
64693  CellArray b; /* Parsed information on cells being balanced */
64694 
64695  memset(abDone, 0, sizeof(abDone));
64696  b.nCell = 0;
64697  b.apCell = 0;
64698  pBt = pParent->pBt;
64699  assert( sqlite3_mutex_held(pBt->mutex) );
64700  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
64701 
64702 #if 0
64703  TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
64704 #endif
64705 
64706  /* At this point pParent may have at most one overflow cell. And if
64707  ** this overflow cell is present, it must be the cell with
64708  ** index iParentIdx. This scenario comes about when this function
64709  ** is called (indirectly) from sqlite3BtreeDelete().
64710  */
64711  assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
64712  assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
64713 
64714  if( !aOvflSpace ){
64715  return SQLITE_NOMEM_BKPT;
64716  }
64717 
64718  /* Find the sibling pages to balance. Also locate the cells in pParent
64719  ** that divide the siblings. An attempt is made to find NN siblings on
64720  ** either side of pPage. More siblings are taken from one side, however,
64721  ** if there are fewer than NN siblings on the other side. If pParent
64722  ** has NB or fewer children then all children of pParent are taken.
64723  **
64724  ** This loop also drops the divider cells from the parent page. This
64725  ** way, the remainder of the function does not have to deal with any
64726  ** overflow cells in the parent page, since if any existed they will
64727  ** have already been removed.
64728  */
64729  i = pParent->nOverflow + pParent->nCell;
64730  if( i<2 ){
64731  nxDiv = 0;
64732  }else{
64733  assert( bBulk==0 || bBulk==1 );
64734  if( iParentIdx==0 ){
64735  nxDiv = 0;
64736  }else if( iParentIdx==i ){
64737  nxDiv = i-2+bBulk;
64738  }else{
64739  nxDiv = iParentIdx-1;
64740  }
64741  i = 2-bBulk;
64742  }
64743  nOld = i+1;
64744  if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
64745  pRight = &pParent->aData[pParent->hdrOffset+8];
64746  }else{
64747  pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
64748  }
64749  pgno = get4byte(pRight);
64750  while( 1 ){
64751  rc = getAndInitPage(pBt, pgno, &apOld[i], 0, 0);
64752  if( rc ){
64753  memset(apOld, 0, (i+1)*sizeof(MemPage*));
64754  goto balance_cleanup;
64755  }
64756  nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
64757  if( (i--)==0 ) break;
64758 
64759  if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
64760  apDiv[i] = pParent->apOvfl[0];
64761  pgno = get4byte(apDiv[i]);
64762  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
64763  pParent->nOverflow = 0;
64764  }else{
64765  apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
64766  pgno = get4byte(apDiv[i]);
64767  szNew[i] = pParent->xCellSize(pParent, apDiv[i]);
64768 
64769  /* Drop the cell from the parent page. apDiv[i] still points to
64770  ** the cell within the parent, even though it has been dropped.
64771  ** This is safe because dropping a cell only overwrites the first
64772  ** four bytes of it, and this function does not need the first
64773  ** four bytes of the divider cell. So the pointer is safe to use
64774  ** later on.
64775  **
64776  ** But not if we are in secure-delete mode. In secure-delete mode,
64777  ** the dropCell() routine will overwrite the entire cell with zeroes.
64778  ** In this case, temporarily copy the cell into the aOvflSpace[]
64779  ** buffer. It will be copied out again as soon as the aSpace[] buffer
64780  ** is allocated. */
64781  if( pBt->btsFlags & BTS_SECURE_DELETE ){
64782  int iOff;
64783 
64784  iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
64785  if( (iOff+szNew[i])>(int)pBt->usableSize ){
64786  rc = SQLITE_CORRUPT_BKPT;
64787  memset(apOld, 0, (i+1)*sizeof(MemPage*));
64788  goto balance_cleanup;
64789  }else{
64790  memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
64791  apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
64792  }
64793  }
64794  dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
64795  }
64796  }
64797 
64798  /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
64799  ** alignment */
64800  nMaxCells = (nMaxCells + 3)&~3;
64801 
64802  /*
64803  ** Allocate space for memory structures
64804  */
64805  szScratch =
64806  nMaxCells*sizeof(u8*) /* b.apCell */
64807  + nMaxCells*sizeof(u16) /* b.szCell */
64808  + pBt->pageSize; /* aSpace1 */
64809 
64810  /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
64811  ** that is more than 6 times the database page size. */
64812  assert( szScratch<=6*(int)pBt->pageSize );
64813  b.apCell = sqlite3ScratchMalloc( szScratch );
64814  if( b.apCell==0 ){
64815  rc = SQLITE_NOMEM_BKPT;
64816  goto balance_cleanup;
64817  }
64818  b.szCell = (u16*)&b.apCell[nMaxCells];
64819  aSpace1 = (u8*)&b.szCell[nMaxCells];
64820  assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
64821 
64822  /*
64823  ** Load pointers to all cells on sibling pages and the divider cells
64824  ** into the local b.apCell[] array. Make copies of the divider cells
64825  ** into space obtained from aSpace1[]. The divider cells have already
64826  ** been removed from pParent.
64827  **
64828  ** If the siblings are on leaf pages, then the child pointers of the
64829  ** divider cells are stripped from the cells before they are copied
64830  ** into aSpace1[]. In this way, all cells in b.apCell[] are without
64831  ** child pointers. If siblings are not leaves, then all cell in
64832  ** b.apCell[] include child pointers. Either way, all cells in b.apCell[]
64833  ** are alike.
64834  **
64835  ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
64836  ** leafData: 1 if pPage holds key+data and pParent holds only keys.
64837  */
64838  b.pRef = apOld[0];
64839  leafCorrection = b.pRef->leaf*4;
64840  leafData = b.pRef->intKeyLeaf;
64841  for(i=0; i<nOld; i++){
64842  MemPage *pOld = apOld[i];
64843  int limit = pOld->nCell;
64844  u8 *aData = pOld->aData;
64845  u16 maskPage = pOld->maskPage;
64846  u8 *piCell = aData + pOld->cellOffset;
64847  u8 *piEnd;
64848 
64849  /* Verify that all sibling pages are of the same "type" (table-leaf,
64850  ** table-interior, index-leaf, or index-interior).
64851  */
64852  if( pOld->aData[0]!=apOld[0]->aData[0] ){
64853  rc = SQLITE_CORRUPT_BKPT;
64854  goto balance_cleanup;
64855  }
64856 
64857  /* Load b.apCell[] with pointers to all cells in pOld. If pOld
64858  ** constains overflow cells, include them in the b.apCell[] array
64859  ** in the correct spot.
64860  **
64861  ** Note that when there are multiple overflow cells, it is always the
64862  ** case that they are sequential and adjacent. This invariant arises
64863  ** because multiple overflows can only occurs when inserting divider
64864  ** cells into a parent on a prior balance, and divider cells are always
64865  ** adjacent and are inserted in order. There is an assert() tagged
64866  ** with "NOTE 1" in the overflow cell insertion loop to prove this
64867  ** invariant.
64868  **
64869  ** This must be done in advance. Once the balance starts, the cell
64870  ** offset section of the btree page will be overwritten and we will no
64871  ** long be able to find the cells if a pointer to each cell is not saved
64872  ** first.
64873  */
64874  memset(&b.szCell[b.nCell], 0, sizeof(b.szCell[0])*(limit+pOld->nOverflow));
64875  if( pOld->nOverflow>0 ){
64876  limit = pOld->aiOvfl[0];
64877  for(j=0; j<limit; j++){
64878  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
64879  piCell += 2;
64880  b.nCell++;
64881  }
64882  for(k=0; k<pOld->nOverflow; k++){
64883  assert( k==0 || pOld->aiOvfl[k-1]+1==pOld->aiOvfl[k] );/* NOTE 1 */
64884  b.apCell[b.nCell] = pOld->apOvfl[k];
64885  b.nCell++;
64886  }
64887  }
64888  piEnd = aData + pOld->cellOffset + 2*pOld->nCell;
64889  while( piCell<piEnd ){
64890  assert( b.nCell<nMaxCells );
64891  b.apCell[b.nCell] = aData + (maskPage & get2byteAligned(piCell));
64892  piCell += 2;
64893  b.nCell++;
64894  }
64895 
64896  cntOld[i] = b.nCell;
64897  if( i<nOld-1 && !leafData){
64898  u16 sz = (u16)szNew[i];
64899  u8 *pTemp;
64900  assert( b.nCell<nMaxCells );
64901  b.szCell[b.nCell] = sz;
64902  pTemp = &aSpace1[iSpace1];
64903  iSpace1 += sz;
64904  assert( sz<=pBt->maxLocal+23 );
64905  assert( iSpace1 <= (int)pBt->pageSize );
64906  memcpy(pTemp, apDiv[i], sz);
64907  b.apCell[b.nCell] = pTemp+leafCorrection;
64908  assert( leafCorrection==0 || leafCorrection==4 );
64909  b.szCell[b.nCell] = b.szCell[b.nCell] - leafCorrection;
64910  if( !pOld->leaf ){
64911  assert( leafCorrection==0 );
64912  assert( pOld->hdrOffset==0 );
64913  /* The right pointer of the child page pOld becomes the left
64914  ** pointer of the divider cell */
64915  memcpy(b.apCell[b.nCell], &pOld->aData[8], 4);
64916  }else{
64917  assert( leafCorrection==4 );
64918  while( b.szCell[b.nCell]<4 ){
64919  /* Do not allow any cells smaller than 4 bytes. If a smaller cell
64920  ** does exist, pad it with 0x00 bytes. */
64921  assert( b.szCell[b.nCell]==3 || CORRUPT_DB );
64922  assert( b.apCell[b.nCell]==&aSpace1[iSpace1-3] || CORRUPT_DB );
64923  aSpace1[iSpace1++] = 0x00;
64924  b.szCell[b.nCell]++;
64925  }
64926  }
64927  b.nCell++;
64928  }
64929  }
64930 
64931  /*
64932  ** Figure out the number of pages needed to hold all b.nCell cells.
64933  ** Store this number in "k". Also compute szNew[] which is the total
64934  ** size of all cells on the i-th page and cntNew[] which is the index
64935  ** in b.apCell[] of the cell that divides page i from page i+1.
64936  ** cntNew[k] should equal b.nCell.
64937  **
64938  ** Values computed by this block:
64939  **
64940  ** k: The total number of sibling pages
64941  ** szNew[i]: Spaced used on the i-th sibling page.
64942  ** cntNew[i]: Index in b.apCell[] and b.szCell[] for the first cell to
64943  ** the right of the i-th sibling page.
64944  ** usableSpace: Number of bytes of space available on each sibling.
64945  **
64946  */
64947  usableSpace = pBt->usableSize - 12 + leafCorrection;
64948  for(i=0; i<nOld; i++){
64949  MemPage *p = apOld[i];
64950  szNew[i] = usableSpace - p->nFree;
64951  if( szNew[i]<0 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
64952  for(j=0; j<p->nOverflow; j++){
64953  szNew[i] += 2 + p->xCellSize(p, p->apOvfl[j]);
64954  }
64955  cntNew[i] = cntOld[i];
64956  }
64957  k = nOld;
64958  for(i=0; i<k; i++){
64959  int sz;
64960  while( szNew[i]>usableSpace ){
64961  if( i+1>=k ){
64962  k = i+2;
64963  if( k>NB+2 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
64964  szNew[k-1] = 0;
64965  cntNew[k-1] = b.nCell;
64966  }
64967  sz = 2 + cachedCellSize(&b, cntNew[i]-1);
64968  szNew[i] -= sz;
64969  if( !leafData ){
64970  if( cntNew[i]<b.nCell ){
64971  sz = 2 + cachedCellSize(&b, cntNew[i]);
64972  }else{
64973  sz = 0;
64974  }
64975  }
64976  szNew[i+1] += sz;
64977  cntNew[i]--;
64978  }
64979  while( cntNew[i]<b.nCell ){
64980  sz = 2 + cachedCellSize(&b, cntNew[i]);
64981  if( szNew[i]+sz>usableSpace ) break;
64982  szNew[i] += sz;
64983  cntNew[i]++;
64984  if( !leafData ){
64985  if( cntNew[i]<b.nCell ){
64986  sz = 2 + cachedCellSize(&b, cntNew[i]);
64987  }else{
64988  sz = 0;
64989  }
64990  }
64991  szNew[i+1] -= sz;
64992  }
64993  if( cntNew[i]>=b.nCell ){
64994  k = i+1;
64995  }else if( cntNew[i] <= (i>0 ? cntNew[i-1] : 0) ){
64996  rc = SQLITE_CORRUPT_BKPT;
64997  goto balance_cleanup;
64998  }
64999  }
65000 
65001  /*
65002  ** The packing computed by the previous block is biased toward the siblings
65003  ** on the left side (siblings with smaller keys). The left siblings are
65004  ** always nearly full, while the right-most sibling might be nearly empty.
65005  ** The next block of code attempts to adjust the packing of siblings to
65006  ** get a better balance.
65007  **
65008  ** This adjustment is more than an optimization. The packing above might
65009  ** be so out of balance as to be illegal. For example, the right-most
65010  ** sibling might be completely empty. This adjustment is not optional.
65011  */
65012  for(i=k-1; i>0; i--){
65013  int szRight = szNew[i]; /* Size of sibling on the right */
65014  int szLeft = szNew[i-1]; /* Size of sibling on the left */
65015  int r; /* Index of right-most cell in left sibling */
65016  int d; /* Index of first cell to the left of right sibling */
65017 
65018  r = cntNew[i-1] - 1;
65019  d = r + 1 - leafData;
65020  (void)cachedCellSize(&b, d);
65021  do{
65022  assert( d<nMaxCells );
65023  assert( r<nMaxCells );
65024  (void)cachedCellSize(&b, r);
65025  if( szRight!=0
65026  && (bBulk || szRight+b.szCell[d]+2 > szLeft-(b.szCell[r]+2)) ){
65027  break;
65028  }
65029  szRight += b.szCell[d] + 2;
65030  szLeft -= b.szCell[r] + 2;
65031  cntNew[i-1] = r;
65032  r--;
65033  d--;
65034  }while( r>=0 );
65035  szNew[i] = szRight;
65036  szNew[i-1] = szLeft;
65037  if( cntNew[i-1] <= (i>1 ? cntNew[i-2] : 0) ){
65038  rc = SQLITE_CORRUPT_BKPT;
65039  goto balance_cleanup;
65040  }
65041  }
65042 
65043  /* Sanity check: For a non-corrupt database file one of the follwing
65044  ** must be true:
65045  ** (1) We found one or more cells (cntNew[0])>0), or
65046  ** (2) pPage is a virtual root page. A virtual root page is when
65047  ** the real root page is page 1 and we are the only child of
65048  ** that page.
65049  */
65050  assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
65051  TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
65052  apOld[0]->pgno, apOld[0]->nCell,
65053  nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
65054  nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
65055  ));
65056 
65057  /*
65058  ** Allocate k new pages. Reuse old pages where possible.
65059  */
65060  pageFlags = apOld[0]->aData[0];
65061  for(i=0; i<k; i++){
65062  MemPage *pNew;
65063  if( i<nOld ){
65064  pNew = apNew[i] = apOld[i];
65065  apOld[i] = 0;
65066  rc = sqlite3PagerWrite(pNew->pDbPage);
65067  nNew++;
65068  if( rc ) goto balance_cleanup;
65069  }else{
65070  assert( i>0 );
65071  rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
65072  if( rc ) goto balance_cleanup;
65073  zeroPage(pNew, pageFlags);
65074  apNew[i] = pNew;
65075  nNew++;
65076  cntOld[i] = b.nCell;
65077 
65078  /* Set the pointer-map entry for the new sibling page. */
65079  if( ISAUTOVACUUM ){
65080  ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
65081  if( rc!=SQLITE_OK ){
65082  goto balance_cleanup;
65083  }
65084  }
65085  }
65086  }
65087 
65088  /*
65089  ** Reassign page numbers so that the new pages are in ascending order.
65090  ** This helps to keep entries in the disk file in order so that a scan
65091  ** of the table is closer to a linear scan through the file. That in turn
65092  ** helps the operating system to deliver pages from the disk more rapidly.
65093  **
65094  ** An O(n^2) insertion sort algorithm is used, but since n is never more
65095  ** than (NB+2) (a small constant), that should not be a problem.
65096  **
65097  ** When NB==3, this one optimization makes the database about 25% faster
65098  ** for large insertions and deletions.
65099  */
65100  for(i=0; i<nNew; i++){
65101  aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
65102  aPgFlags[i] = apNew[i]->pDbPage->flags;
65103  for(j=0; j<i; j++){
65104  if( aPgno[j]==aPgno[i] ){
65105  /* This branch is taken if the set of sibling pages somehow contains
65106  ** duplicate entries. This can happen if the database is corrupt.
65107  ** It would be simpler to detect this as part of the loop below, but
65108  ** we do the detection here in order to avoid populating the pager
65109  ** cache with two separate objects associated with the same
65110  ** page number. */
65111  assert( CORRUPT_DB );
65112  rc = SQLITE_CORRUPT_BKPT;
65113  goto balance_cleanup;
65114  }
65115  }
65116  }
65117  for(i=0; i<nNew; i++){
65118  int iBest = 0; /* aPgno[] index of page number to use */
65119  for(j=1; j<nNew; j++){
65120  if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
65121  }
65122  pgno = aPgOrder[iBest];
65123  aPgOrder[iBest] = 0xffffffff;
65124  if( iBest!=i ){
65125  if( iBest>i ){
65126  sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
65127  }
65128  sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
65129  apNew[i]->pgno = pgno;
65130  }
65131  }
65132 
65133  TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
65134  "%d(%d nc=%d) %d(%d nc=%d)\n",
65135  apNew[0]->pgno, szNew[0], cntNew[0],
65136  nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
65137  nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
65138  nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
65139  nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
65140  nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
65141  nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
65142  nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
65143  nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
65144  ));
65145 
65146  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65147  put4byte(pRight, apNew[nNew-1]->pgno);
65148 
65149  /* If the sibling pages are not leaves, ensure that the right-child pointer
65150  ** of the right-most new sibling page is set to the value that was
65151  ** originally in the same field of the right-most old sibling page. */
65152  if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
65153  MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
65154  memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
65155  }
65156 
65157  /* Make any required updates to pointer map entries associated with
65158  ** cells stored on sibling pages following the balance operation. Pointer
65159  ** map entries associated with divider cells are set by the insertCell()
65160  ** routine. The associated pointer map entries are:
65161  **
65162  ** a) if the cell contains a reference to an overflow chain, the
65163  ** entry associated with the first page in the overflow chain, and
65164  **
65165  ** b) if the sibling pages are not leaves, the child page associated
65166  ** with the cell.
65167  **
65168  ** If the sibling pages are not leaves, then the pointer map entry
65169  ** associated with the right-child of each sibling may also need to be
65170  ** updated. This happens below, after the sibling pages have been
65171  ** populated, not here.
65172  */
65173  if( ISAUTOVACUUM ){
65174  MemPage *pNew = apNew[0];
65175  u8 *aOld = pNew->aData;
65176  int cntOldNext = pNew->nCell + pNew->nOverflow;
65177  int usableSize = pBt->usableSize;
65178  int iNew = 0;
65179  int iOld = 0;
65180 
65181  for(i=0; i<b.nCell; i++){
65182  u8 *pCell = b.apCell[i];
65183  if( i==cntOldNext ){
65184  MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
65185  cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
65186  aOld = pOld->aData;
65187  }
65188  if( i==cntNew[iNew] ){
65189  pNew = apNew[++iNew];
65190  if( !leafData ) continue;
65191  }
65192 
65193  /* Cell pCell is destined for new sibling page pNew. Originally, it
65194  ** was either part of sibling page iOld (possibly an overflow cell),
65195  ** or else the divider cell to the left of sibling page iOld. So,
65196  ** if sibling page iOld had the same page number as pNew, and if
65197  ** pCell really was a part of sibling page iOld (not a divider or
65198  ** overflow cell), we can skip updating the pointer map entries. */
65199  if( iOld>=nNew
65200  || pNew->pgno!=aPgno[iOld]
65201  || !SQLITE_WITHIN(pCell,aOld,&aOld[usableSize])
65202  ){
65203  if( !leafCorrection ){
65204  ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
65205  }
65206  if( cachedCellSize(&b,i)>pNew->minLocal ){
65207  ptrmapPutOvflPtr(pNew, pCell, &rc);
65208  }
65209  if( rc ) goto balance_cleanup;
65210  }
65211  }
65212  }
65213 
65214  /* Insert new divider cells into pParent. */
65215  for(i=0; i<nNew-1; i++){
65216  u8 *pCell;
65217  u8 *pTemp;
65218  int sz;
65219  MemPage *pNew = apNew[i];
65220  j = cntNew[i];
65221 
65222  assert( j<nMaxCells );
65223  assert( b.apCell[j]!=0 );
65224  pCell = b.apCell[j];
65225  sz = b.szCell[j] + leafCorrection;
65226  pTemp = &aOvflSpace[iOvflSpace];
65227  if( !pNew->leaf ){
65228  memcpy(&pNew->aData[8], pCell, 4);
65229  }else if( leafData ){
65230  /* If the tree is a leaf-data tree, and the siblings are leaves,
65231  ** then there is no divider cell in b.apCell[]. Instead, the divider
65232  ** cell consists of the integer key for the right-most cell of
65233  ** the sibling-page assembled above only.
65234  */
65235  CellInfo info;
65236  j--;
65237  pNew->xParseCell(pNew, b.apCell[j], &info);
65238  pCell = pTemp;
65239  sz = 4 + putVarint(&pCell[4], info.nKey);
65240  pTemp = 0;
65241  }else{
65242  pCell -= 4;
65243  /* Obscure case for non-leaf-data trees: If the cell at pCell was
65244  ** previously stored on a leaf node, and its reported size was 4
65245  ** bytes, then it may actually be smaller than this
65246  ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
65247  ** any cell). But it is important to pass the correct size to
65248  ** insertCell(), so reparse the cell now.
65249  **
65250  ** This can only happen for b-trees used to evaluate "IN (SELECT ...)"
65251  ** and WITHOUT ROWID tables with exactly one column which is the
65252  ** primary key.
65253  */
65254  if( b.szCell[j]==4 ){
65255  assert(leafCorrection==4);
65256  sz = pParent->xCellSize(pParent, pCell);
65257  }
65258  }
65259  iOvflSpace += sz;
65260  assert( sz<=pBt->maxLocal+23 );
65261  assert( iOvflSpace <= (int)pBt->pageSize );
65262  insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
65263  if( rc!=SQLITE_OK ) goto balance_cleanup;
65264  assert( sqlite3PagerIswriteable(pParent->pDbPage) );
65265  }
65266 
65267  /* Now update the actual sibling pages. The order in which they are updated
65268  ** is important, as this code needs to avoid disrupting any page from which
65269  ** cells may still to be read. In practice, this means:
65270  **
65271  ** (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
65272  ** then it is not safe to update page apNew[iPg] until after
65273  ** the left-hand sibling apNew[iPg-1] has been updated.
65274  **
65275  ** (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
65276  ** then it is not safe to update page apNew[iPg] until after
65277  ** the right-hand sibling apNew[iPg+1] has been updated.
65278  **
65279  ** If neither of the above apply, the page is safe to update.
65280  **
65281  ** The iPg value in the following loop starts at nNew-1 goes down
65282  ** to 0, then back up to nNew-1 again, thus making two passes over
65283  ** the pages. On the initial downward pass, only condition (1) above
65284  ** needs to be tested because (2) will always be true from the previous
65285  ** step. On the upward pass, both conditions are always true, so the
65286  ** upwards pass simply processes pages that were missed on the downward
65287  ** pass.
65288  */
65289  for(i=1-nNew; i<nNew; i++){
65290  int iPg = i<0 ? -i : i;
65291  assert( iPg>=0 && iPg<nNew );
65292  if( abDone[iPg] ) continue; /* Skip pages already processed */
65293  if( i>=0 /* On the upwards pass, or... */
65294  || cntOld[iPg-1]>=cntNew[iPg-1] /* Condition (1) is true */
65295  ){
65296  int iNew;
65297  int iOld;
65298  int nNewCell;
65299 
65300  /* Verify condition (1): If cells are moving left, update iPg
65301  ** only after iPg-1 has already been updated. */
65302  assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
65303 
65304  /* Verify condition (2): If cells are moving right, update iPg
65305  ** only after iPg+1 has already been updated. */
65306  assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
65307 
65308  if( iPg==0 ){
65309  iNew = iOld = 0;
65310  nNewCell = cntNew[0];
65311  }else{
65312  iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : b.nCell;
65313  iNew = cntNew[iPg-1] + !leafData;
65314  nNewCell = cntNew[iPg] - iNew;
65315  }
65316 
65317  rc = editPage(apNew[iPg], iOld, iNew, nNewCell, &b);
65318  if( rc ) goto balance_cleanup;
65319  abDone[iPg]++;
65320  apNew[iPg]->nFree = usableSpace-szNew[iPg];
65321  assert( apNew[iPg]->nOverflow==0 );
65322  assert( apNew[iPg]->nCell==nNewCell );
65323  }
65324  }
65325 
65326  /* All pages have been processed exactly once */
65327  assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
65328 
65329  assert( nOld>0 );
65330  assert( nNew>0 );
65331 
65332  if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
65333  /* The root page of the b-tree now contains no cells. The only sibling
65334  ** page is the right-child of the parent. Copy the contents of the
65335  ** child page into the parent, decreasing the overall height of the
65336  ** b-tree structure by one. This is described as the "balance-shallower"
65337  ** sub-algorithm in some documentation.
65338  **
65339  ** If this is an auto-vacuum database, the call to copyNodeContent()
65340  ** sets all pointer-map entries corresponding to database image pages
65341  ** for which the pointer is stored within the content being copied.
65342  **
65343  ** It is critical that the child page be defragmented before being
65344  ** copied into the parent, because if the parent is page 1 then it will
65345  ** by smaller than the child due to the database header, and so all the
65346  ** free space needs to be up front.
65347  */
65348  assert( nNew==1 || CORRUPT_DB );
65349  rc = defragmentPage(apNew[0]);
65350  testcase( rc!=SQLITE_OK );
65351  assert( apNew[0]->nFree ==
65352  (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
65353  || rc!=SQLITE_OK
65354  );
65355  copyNodeContent(apNew[0], pParent, &rc);
65356  freePage(apNew[0], &rc);
65357  }else if( ISAUTOVACUUM && !leafCorrection ){
65358  /* Fix the pointer map entries associated with the right-child of each
65359  ** sibling page. All other pointer map entries have already been taken
65360  ** care of. */
65361  for(i=0; i<nNew; i++){
65362  u32 key = get4byte(&apNew[i]->aData[8]);
65363  ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
65364  }
65365  }
65366 
65367  assert( pParent->isInit );
65368  TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
65369  nOld, nNew, b.nCell));
65370 
65371  /* Free any old pages that were not reused as new pages.
65372  */
65373  for(i=nNew; i<nOld; i++){
65374  freePage(apOld[i], &rc);
65375  }
65376 
65377 #if 0
65378  if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
65379  /* The ptrmapCheckPages() contains assert() statements that verify that
65380  ** all pointer map pages are set correctly. This is helpful while
65381  ** debugging. This is usually disabled because a corrupt database may
65382  ** cause an assert() statement to fail. */
65383  ptrmapCheckPages(apNew, nNew);
65384  ptrmapCheckPages(&pParent, 1);
65385  }
65386 #endif
65387 
65388  /*
65389  ** Cleanup before returning.
65390  */
65391 balance_cleanup:
65393  for(i=0; i<nOld; i++){
65394  releasePage(apOld[i]);
65395  }
65396  for(i=0; i<nNew; i++){
65397  releasePage(apNew[i]);
65398  }
65399 
65400  return rc;
65401 }
65402 
65403 
65404 /*
65405 ** This function is called when the root page of a b-tree structure is
65406 ** overfull (has one or more overflow pages).
65407 **
65408 ** A new child page is allocated and the contents of the current root
65409 ** page, including overflow cells, are copied into the child. The root
65410 ** page is then overwritten to make it an empty page with the right-child
65411 ** pointer pointing to the new page.
65412 **
65413 ** Before returning, all pointer-map entries corresponding to pages
65414 ** that the new child-page now contains pointers to are updated. The
65415 ** entry corresponding to the new right-child pointer of the root
65416 ** page is also updated.
65417 **
65418 ** If successful, *ppChild is set to contain a reference to the child
65419 ** page and SQLITE_OK is returned. In this case the caller is required
65420 ** to call releasePage() on *ppChild exactly once. If an error occurs,
65421 ** an error code is returned and *ppChild is set to 0.
65422 */
65423 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
65424  int rc; /* Return value from subprocedures */
65425  MemPage *pChild = 0; /* Pointer to a new child page */
65426  Pgno pgnoChild = 0; /* Page number of the new child page */
65427  BtShared *pBt = pRoot->pBt; /* The BTree */
65428 
65429  assert( pRoot->nOverflow>0 );
65430  assert( sqlite3_mutex_held(pBt->mutex) );
65431 
65432  /* Make pRoot, the root page of the b-tree, writable. Allocate a new
65433  ** page that will become the new right-child of pPage. Copy the contents
65434  ** of the node stored on pRoot into the new child page.
65435  */
65436  rc = sqlite3PagerWrite(pRoot->pDbPage);
65437  if( rc==SQLITE_OK ){
65438  rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
65439  copyNodeContent(pRoot, pChild, &rc);
65440  if( ISAUTOVACUUM ){
65441  ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
65442  }
65443  }
65444  if( rc ){
65445  *ppChild = 0;
65446  releasePage(pChild);
65447  return rc;
65448  }
65449  assert( sqlite3PagerIswriteable(pChild->pDbPage) );
65450  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
65451  assert( pChild->nCell==pRoot->nCell );
65452 
65453  TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
65454 
65455  /* Copy the overflow cells from pRoot to pChild */
65456  memcpy(pChild->aiOvfl, pRoot->aiOvfl,
65457  pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
65458  memcpy(pChild->apOvfl, pRoot->apOvfl,
65459  pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
65460  pChild->nOverflow = pRoot->nOverflow;
65461 
65462  /* Zero the contents of pRoot. Then install pChild as the right-child. */
65463  zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
65464  put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
65465 
65466  *ppChild = pChild;
65467  return SQLITE_OK;
65468 }
65469 
65470 /*
65471 ** The page that pCur currently points to has just been modified in
65472 ** some way. This function figures out if this modification means the
65473 ** tree needs to be balanced, and if so calls the appropriate balancing
65474 ** routine. Balancing routines are:
65475 **
65476 ** balance_quick()
65477 ** balance_deeper()
65478 ** balance_nonroot()
65479 */
65480 static int balance(BtCursor *pCur){
65481  int rc = SQLITE_OK;
65482  const int nMin = pCur->pBt->usableSize * 2 / 3;
65483  u8 aBalanceQuickSpace[13];
65484  u8 *pFree = 0;
65485 
65486  VVA_ONLY( int balance_quick_called = 0 );
65487  VVA_ONLY( int balance_deeper_called = 0 );
65488 
65489  do {
65490  int iPage = pCur->iPage;
65491  MemPage *pPage = pCur->apPage[iPage];
65492 
65493  if( iPage==0 ){
65494  if( pPage->nOverflow ){
65495  /* The root page of the b-tree is overfull. In this case call the
65496  ** balance_deeper() function to create a new child for the root-page
65497  ** and copy the current contents of the root-page to it. The
65498  ** next iteration of the do-loop will balance the child page.
65499  */
65500  assert( balance_deeper_called==0 );
65501  VVA_ONLY( balance_deeper_called++ );
65502  rc = balance_deeper(pPage, &pCur->apPage[1]);
65503  if( rc==SQLITE_OK ){
65504  pCur->iPage = 1;
65505  pCur->aiIdx[0] = 0;
65506  pCur->aiIdx[1] = 0;
65507  assert( pCur->apPage[1]->nOverflow );
65508  }
65509  }else{
65510  break;
65511  }
65512  }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
65513  break;
65514  }else{
65515  MemPage * const pParent = pCur->apPage[iPage-1];
65516  int const iIdx = pCur->aiIdx[iPage-1];
65517 
65518  rc = sqlite3PagerWrite(pParent->pDbPage);
65519  if( rc==SQLITE_OK ){
65520 #ifndef SQLITE_OMIT_QUICKBALANCE
65521  if( pPage->intKeyLeaf
65522  && pPage->nOverflow==1
65523  && pPage->aiOvfl[0]==pPage->nCell
65524  && pParent->pgno!=1
65525  && pParent->nCell==iIdx
65526  ){
65527  /* Call balance_quick() to create a new sibling of pPage on which
65528  ** to store the overflow cell. balance_quick() inserts a new cell
65529  ** into pParent, which may cause pParent overflow. If this
65530  ** happens, the next iteration of the do-loop will balance pParent
65531  ** use either balance_nonroot() or balance_deeper(). Until this
65532  ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
65533  ** buffer.
65534  **
65535  ** The purpose of the following assert() is to check that only a
65536  ** single call to balance_quick() is made for each call to this
65537  ** function. If this were not verified, a subtle bug involving reuse
65538  ** of the aBalanceQuickSpace[] might sneak in.
65539  */
65540  assert( balance_quick_called==0 );
65541  VVA_ONLY( balance_quick_called++ );
65542  rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
65543  }else
65544 #endif
65545  {
65546  /* In this case, call balance_nonroot() to redistribute cells
65547  ** between pPage and up to 2 of its sibling pages. This involves
65548  ** modifying the contents of pParent, which may cause pParent to
65549  ** become overfull or underfull. The next iteration of the do-loop
65550  ** will balance the parent page to correct this.
65551  **
65552  ** If the parent page becomes overfull, the overflow cell or cells
65553  ** are stored in the pSpace buffer allocated immediately below.
65554  ** A subsequent iteration of the do-loop will deal with this by
65555  ** calling balance_nonroot() (balance_deeper() may be called first,
65556  ** but it doesn't deal with overflow cells - just moves them to a
65557  ** different page). Once this subsequent call to balance_nonroot()
65558  ** has completed, it is safe to release the pSpace buffer used by
65559  ** the previous call, as the overflow cell data will have been
65560  ** copied either into the body of a database page or into the new
65561  ** pSpace buffer passed to the latter call to balance_nonroot().
65562  */
65563  u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
65564  rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
65565  pCur->hints&BTREE_BULKLOAD);
65566  if( pFree ){
65567  /* If pFree is not NULL, it points to the pSpace buffer used
65568  ** by a previous call to balance_nonroot(). Its contents are
65569  ** now stored either on real database pages or within the
65570  ** new pSpace buffer, so it may be safely freed here. */
65571  sqlite3PageFree(pFree);
65572  }
65573 
65574  /* The pSpace buffer will be freed after the next call to
65575  ** balance_nonroot(), or just before this function returns, whichever
65576  ** comes first. */
65577  pFree = pSpace;
65578  }
65579  }
65580 
65581  pPage->nOverflow = 0;
65582 
65583  /* The next iteration of the do-loop balances the parent page. */
65584  releasePage(pPage);
65585  pCur->iPage--;
65586  assert( pCur->iPage>=0 );
65587  }
65588  }while( rc==SQLITE_OK );
65589 
65590  if( pFree ){
65591  sqlite3PageFree(pFree);
65592  }
65593  return rc;
65594 }
65595 
65596 
65597 /*
65598 ** Insert a new record into the BTree. The key is given by (pKey,nKey)
65599 ** and the data is given by (pData,nData). The cursor is used only to
65600 ** define what table the record should be inserted into. The cursor
65601 ** is left pointing at a random location.
65602 **
65603 ** For an INTKEY table, only the nKey value of the key is used. pKey is
65604 ** ignored. For a ZERODATA table, the pData and nData are both ignored.
65605 **
65606 ** If the seekResult parameter is non-zero, then a successful call to
65607 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
65608 ** been performed. seekResult is the search result returned (a negative
65609 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
65610 ** a positive value if pCur points at an entry that is larger than
65611 ** (pKey, nKey)).
65612 **
65613 ** If the seekResult parameter is non-zero, then the caller guarantees that
65614 ** cursor pCur is pointing at the existing copy of a row that is to be
65615 ** overwritten. If the seekResult parameter is 0, then cursor pCur may
65616 ** point to any entry or to no entry at all and so this function has to seek
65617 ** the cursor before the new key can be inserted.
65618 */
65620  BtCursor *pCur, /* Insert data into the table of this cursor */
65621  const void *pKey, i64 nKey, /* The key of the new record */
65622  const void *pData, int nData, /* The data of the new record */
65623  int nZero, /* Number of extra 0 bytes to append to data */
65624  int appendBias, /* True if this is likely an append */
65625  int seekResult /* Result of prior MovetoUnpacked() call */
65626 ){
65627  int rc;
65628  int loc = seekResult; /* -1: before desired location +1: after */
65629  int szNew = 0;
65630  int idx;
65631  MemPage *pPage;
65632  Btree *p = pCur->pBtree;
65633  BtShared *pBt = p->pBt;
65634  unsigned char *oldCell;
65635  unsigned char *newCell = 0;
65636 
65637  if( pCur->eState==CURSOR_FAULT ){
65638  assert( pCur->skipNext!=SQLITE_OK );
65639  return pCur->skipNext;
65640  }
65641 
65642  assert( cursorOwnsBtShared(pCur) );
65643  assert( (pCur->curFlags & BTCF_WriteFlag)!=0
65644  && pBt->inTransaction==TRANS_WRITE
65645  && (pBt->btsFlags & BTS_READ_ONLY)==0 );
65646  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
65647 
65648  /* Assert that the caller has been consistent. If this cursor was opened
65649  ** expecting an index b-tree, then the caller should be inserting blob
65650  ** keys with no associated data. If the cursor was opened expecting an
65651  ** intkey table, the caller should be inserting integer keys with a
65652  ** blob of associated data. */
65653  assert( (pKey==0)==(pCur->pKeyInfo==0) );
65654 
65655  /* Save the positions of any other cursors open on this table.
65656  **
65657  ** In some cases, the call to btreeMoveto() below is a no-op. For
65658  ** example, when inserting data into a table with auto-generated integer
65659  ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
65660  ** integer key to use. It then calls this function to actually insert the
65661  ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
65662  ** that the cursor is already where it needs to be and returns without
65663  ** doing any work. To avoid thwarting these optimizations, it is important
65664  ** not to clear the cursor here.
65665  */
65666  if( pCur->curFlags & BTCF_Multiple ){
65667  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
65668  if( rc ) return rc;
65669  }
65670 
65671  if( pCur->pKeyInfo==0 ){
65672  assert( pKey==0 );
65673  /* If this is an insert into a table b-tree, invalidate any incrblob
65674  ** cursors open on the row being replaced */
65675  invalidateIncrblobCursors(p, nKey, 0);
65676 
65677  /* If the cursor is currently on the last row and we are appending a
65678  ** new row onto the end, set the "loc" to avoid an unnecessary
65679  ** btreeMoveto() call */
65680  if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
65681  && pCur->info.nKey==nKey-1 ){
65682  loc = -1;
65683  }else if( loc==0 ){
65684  rc = sqlite3BtreeMovetoUnpacked(pCur, 0, nKey, appendBias, &loc);
65685  if( rc ) return rc;
65686  }
65687  }else if( loc==0 ){
65688  rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
65689  if( rc ) return rc;
65690  }
65691  assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
65692 
65693  pPage = pCur->apPage[pCur->iPage];
65694  assert( pPage->intKey || nKey>=0 );
65695  assert( pPage->leaf || !pPage->intKey );
65696 
65697  TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
65698  pCur->pgnoRoot, nKey, nData, pPage->pgno,
65699  loc==0 ? "overwrite" : "new entry"));
65700  assert( pPage->isInit );
65701  newCell = pBt->pTmpSpace;
65702  assert( newCell!=0 );
65703  rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
65704  if( rc ) goto end_insert;
65705  assert( szNew==pPage->xCellSize(pPage, newCell) );
65706  assert( szNew <= MX_CELL_SIZE(pBt) );
65707  idx = pCur->aiIdx[pCur->iPage];
65708  if( loc==0 ){
65709  u16 szOld;
65710  assert( idx<pPage->nCell );
65711  rc = sqlite3PagerWrite(pPage->pDbPage);
65712  if( rc ){
65713  goto end_insert;
65714  }
65715  oldCell = findCell(pPage, idx);
65716  if( !pPage->leaf ){
65717  memcpy(newCell, oldCell, 4);
65718  }
65719  rc = clearCell(pPage, oldCell, &szOld);
65720  dropCell(pPage, idx, szOld, &rc);
65721  if( rc ) goto end_insert;
65722  }else if( loc<0 && pPage->nCell>0 ){
65723  assert( pPage->leaf );
65724  idx = ++pCur->aiIdx[pCur->iPage];
65725  }else{
65726  assert( pPage->leaf );
65727  }
65728  insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
65729  assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
65730 
65731  /* If no error has occurred and pPage has an overflow cell, call balance()
65732  ** to redistribute the cells within the tree. Since balance() may move
65733  ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
65734  ** variables.
65735  **
65736  ** Previous versions of SQLite called moveToRoot() to move the cursor
65737  ** back to the root page as balance() used to invalidate the contents
65738  ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
65739  ** set the cursor state to "invalid". This makes common insert operations
65740  ** slightly faster.
65741  **
65742  ** There is a subtle but important optimization here too. When inserting
65743  ** multiple records into an intkey b-tree using a single cursor (as can
65744  ** happen while processing an "INSERT INTO ... SELECT" statement), it
65745  ** is advantageous to leave the cursor pointing to the last entry in
65746  ** the b-tree if possible. If the cursor is left pointing to the last
65747  ** entry in the table, and the next row inserted has an integer key
65748  ** larger than the largest existing key, it is possible to insert the
65749  ** row without seeking the cursor. This can be a big performance boost.
65750  */
65751  pCur->info.nSize = 0;
65752  if( rc==SQLITE_OK && pPage->nOverflow ){
65753  pCur->curFlags &= ~(BTCF_ValidNKey);
65754  rc = balance(pCur);
65755 
65756  /* Must make sure nOverflow is reset to zero even if the balance()
65757  ** fails. Internal data structure corruption will result otherwise.
65758  ** Also, set the cursor state to invalid. This stops saveCursorPosition()
65759  ** from trying to save the current position of the cursor. */
65760  pCur->apPage[pCur->iPage]->nOverflow = 0;
65761  pCur->eState = CURSOR_INVALID;
65762  }
65763  assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
65764 
65765 end_insert:
65766  return rc;
65767 }
65768 
65769 /*
65770 ** Delete the entry that the cursor is pointing to.
65771 **
65772 ** If the BTREE_SAVEPOSITION bit of the flags parameter is zero, then
65773 ** the cursor is left pointing at an arbitrary location after the delete.
65774 ** But if that bit is set, then the cursor is left in a state such that
65775 ** the next call to BtreeNext() or BtreePrev() moves it to the same row
65776 ** as it would have been on if the call to BtreeDelete() had been omitted.
65777 **
65778 ** The BTREE_AUXDELETE bit of flags indicates that is one of several deletes
65779 ** associated with a single table entry and its indexes. Only one of those
65780 ** deletes is considered the "primary" delete. The primary delete occurs
65781 ** on a cursor that is not a BTREE_FORDELETE cursor. All but one delete
65782 ** operation on non-FORDELETE cursors is tagged with the AUXDELETE flag.
65783 ** The BTREE_AUXDELETE bit is a hint that is not used by this implementation,
65784 ** but which might be used by alternative storage engines.
65785 */
65787  Btree *p = pCur->pBtree;
65788  BtShared *pBt = p->pBt;
65789  int rc; /* Return code */
65790  MemPage *pPage; /* Page to delete cell from */
65791  unsigned char *pCell; /* Pointer to cell to delete */
65792  int iCellIdx; /* Index of cell to delete */
65793  int iCellDepth; /* Depth of node containing pCell */
65794  u16 szCell; /* Size of the cell being deleted */
65795  int bSkipnext = 0; /* Leaf cursor in SKIPNEXT state */
65796  u8 bPreserve = flags & BTREE_SAVEPOSITION; /* Keep cursor valid */
65797 
65798  assert( cursorOwnsBtShared(pCur) );
65799  assert( pBt->inTransaction==TRANS_WRITE );
65800  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
65801  assert( pCur->curFlags & BTCF_WriteFlag );
65802  assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
65803  assert( !hasReadConflicts(p, pCur->pgnoRoot) );
65804  assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
65805  assert( pCur->eState==CURSOR_VALID );
65806  assert( (flags & ~(BTREE_SAVEPOSITION | BTREE_AUXDELETE))==0 );
65807 
65808  iCellDepth = pCur->iPage;
65809  iCellIdx = pCur->aiIdx[iCellDepth];
65810  pPage = pCur->apPage[iCellDepth];
65811  pCell = findCell(pPage, iCellIdx);
65812 
65813  /* If the bPreserve flag is set to true, then the cursor position must
65814  ** be preserved following this delete operation. If the current delete
65815  ** will cause a b-tree rebalance, then this is done by saving the cursor
65816  ** key and leaving the cursor in CURSOR_REQUIRESEEK state before
65817  ** returning.
65818  **
65819  ** Or, if the current delete will not cause a rebalance, then the cursor
65820  ** will be left in CURSOR_SKIPNEXT state pointing to the entry immediately
65821  ** before or after the deleted entry. In this case set bSkipnext to true. */
65822  if( bPreserve ){
65823  if( !pPage->leaf
65824  || (pPage->nFree+cellSizePtr(pPage,pCell)+2)>(int)(pBt->usableSize*2/3)
65825  ){
65826  /* A b-tree rebalance will be required after deleting this entry.
65827  ** Save the cursor key. */
65828  rc = saveCursorKey(pCur);
65829  if( rc ) return rc;
65830  }else{
65831  bSkipnext = 1;
65832  }
65833  }
65834 
65835  /* If the page containing the entry to delete is not a leaf page, move
65836  ** the cursor to the largest entry in the tree that is smaller than
65837  ** the entry being deleted. This cell will replace the cell being deleted
65838  ** from the internal node. The 'previous' entry is used for this instead
65839  ** of the 'next' entry, as the previous entry is always a part of the
65840  ** sub-tree headed by the child page of the cell being deleted. This makes
65841  ** balancing the tree following the delete operation easier. */
65842  if( !pPage->leaf ){
65843  int notUsed = 0;
65844  rc = sqlite3BtreePrevious(pCur, &notUsed);
65845  if( rc ) return rc;
65846  }
65847 
65848  /* Save the positions of any other cursors open on this table before
65849  ** making any modifications. */
65850  if( pCur->curFlags & BTCF_Multiple ){
65851  rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
65852  if( rc ) return rc;
65853  }
65854 
65855  /* If this is a delete operation to remove a row from a table b-tree,
65856  ** invalidate any incrblob cursors open on the row being deleted. */
65857  if( pCur->pKeyInfo==0 ){
65858  invalidateIncrblobCursors(p, pCur->info.nKey, 0);
65859  }
65860 
65861  /* Make the page containing the entry to be deleted writable. Then free any
65862  ** overflow pages associated with the entry and finally remove the cell
65863  ** itself from within the page. */
65864  rc = sqlite3PagerWrite(pPage->pDbPage);
65865  if( rc ) return rc;
65866  rc = clearCell(pPage, pCell, &szCell);
65867  dropCell(pPage, iCellIdx, szCell, &rc);
65868  if( rc ) return rc;
65869 
65870  /* If the cell deleted was not located on a leaf page, then the cursor
65871  ** is currently pointing to the largest entry in the sub-tree headed
65872  ** by the child-page of the cell that was just deleted from an internal
65873  ** node. The cell from the leaf node needs to be moved to the internal
65874  ** node to replace the deleted cell. */
65875  if( !pPage->leaf ){
65876  MemPage *pLeaf = pCur->apPage[pCur->iPage];
65877  int nCell;
65878  Pgno n = pCur->apPage[iCellDepth+1]->pgno;
65879  unsigned char *pTmp;
65880 
65881  pCell = findCell(pLeaf, pLeaf->nCell-1);
65882  if( pCell<&pLeaf->aData[4] ) return SQLITE_CORRUPT_BKPT;
65883  nCell = pLeaf->xCellSize(pLeaf, pCell);
65884  assert( MX_CELL_SIZE(pBt) >= nCell );
65885  pTmp = pBt->pTmpSpace;
65886  assert( pTmp!=0 );
65887  rc = sqlite3PagerWrite(pLeaf->pDbPage);
65888  insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
65889  dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
65890  if( rc ) return rc;
65891  }
65892 
65893  /* Balance the tree. If the entry deleted was located on a leaf page,
65894  ** then the cursor still points to that page. In this case the first
65895  ** call to balance() repairs the tree, and the if(...) condition is
65896  ** never true.
65897  **
65898  ** Otherwise, if the entry deleted was on an internal node page, then
65899  ** pCur is pointing to the leaf page from which a cell was removed to
65900  ** replace the cell deleted from the internal node. This is slightly
65901  ** tricky as the leaf node may be underfull, and the internal node may
65902  ** be either under or overfull. In this case run the balancing algorithm
65903  ** on the leaf node first. If the balance proceeds far enough up the
65904  ** tree that we can be sure that any problem in the internal node has
65905  ** been corrected, so be it. Otherwise, after balancing the leaf node,
65906  ** walk the cursor up the tree to the internal node and balance it as
65907  ** well. */
65908  rc = balance(pCur);
65909  if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
65910  while( pCur->iPage>iCellDepth ){
65911  releasePage(pCur->apPage[pCur->iPage--]);
65912  }
65913  rc = balance(pCur);
65914  }
65915 
65916  if( rc==SQLITE_OK ){
65917  if( bSkipnext ){
65918  assert( bPreserve && (pCur->iPage==iCellDepth || CORRUPT_DB) );
65919  assert( pPage==pCur->apPage[pCur->iPage] || CORRUPT_DB );
65920  assert( (pPage->nCell>0 || CORRUPT_DB) && iCellIdx<=pPage->nCell );
65921  pCur->eState = CURSOR_SKIPNEXT;
65922  if( iCellIdx>=pPage->nCell ){
65923  pCur->skipNext = -1;
65924  pCur->aiIdx[iCellDepth] = pPage->nCell-1;
65925  }else{
65926  pCur->skipNext = 1;
65927  }
65928  }else{
65929  rc = moveToRoot(pCur);
65930  if( bPreserve ){
65931  pCur->eState = CURSOR_REQUIRESEEK;
65932  }
65933  }
65934  }
65935  return rc;
65936 }
65937 
65938 /*
65939 ** Create a new BTree table. Write into *piTable the page
65940 ** number for the root page of the new table.
65941 **
65942 ** The type of type is determined by the flags parameter. Only the
65943 ** following values of flags are currently in use. Other values for
65944 ** flags might not work:
65945 **
65946 ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
65947 ** BTREE_ZERODATA Used for SQL indices
65948 */
65949 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
65950  BtShared *pBt = p->pBt;
65951  MemPage *pRoot;
65952  Pgno pgnoRoot;
65953  int rc;
65954  int ptfFlags; /* Page-type flage for the root page of new table */
65955 
65956  assert( sqlite3BtreeHoldsMutex(p) );
65957  assert( pBt->inTransaction==TRANS_WRITE );
65958  assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
65959 
65960 #ifdef SQLITE_OMIT_AUTOVACUUM
65961  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
65962  if( rc ){
65963  return rc;
65964  }
65965 #else
65966  if( pBt->autoVacuum ){
65967  Pgno pgnoMove; /* Move a page here to make room for the root-page */
65968  MemPage *pPageMove; /* The page to move to. */
65969 
65970  /* Creating a new table may probably require moving an existing database
65971  ** to make room for the new tables root page. In case this page turns
65972  ** out to be an overflow page, delete all overflow page-map caches
65973  ** held by open cursors.
65974  */
65976 
65977  /* Read the value of meta[3] from the database to determine where the
65978  ** root page of the new table should go. meta[3] is the largest root-page
65979  ** created so far, so the new root-page is (meta[3]+1).
65980  */
65982  pgnoRoot++;
65983 
65984  /* The new root-page may not be allocated on a pointer-map page, or the
65985  ** PENDING_BYTE page.
65986  */
65987  while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
65988  pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
65989  pgnoRoot++;
65990  }
65991  assert( pgnoRoot>=3 || CORRUPT_DB );
65992  testcase( pgnoRoot<3 );
65993 
65994  /* Allocate a page. The page that currently resides at pgnoRoot will
65995  ** be moved to the allocated page (unless the allocated page happens
65996  ** to reside at pgnoRoot).
65997  */
65998  rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
65999  if( rc!=SQLITE_OK ){
66000  return rc;
66001  }
66002 
66003  if( pgnoMove!=pgnoRoot ){
66004  /* pgnoRoot is the page that will be used for the root-page of
66005  ** the new table (assuming an error did not occur). But we were
66006  ** allocated pgnoMove. If required (i.e. if it was not allocated
66007  ** by extending the file), the current page at position pgnoMove
66008  ** is already journaled.
66009  */
66010  u8 eType = 0;
66011  Pgno iPtrPage = 0;
66012 
66013  /* Save the positions of any open cursors. This is required in
66014  ** case they are holding a reference to an xFetch reference
66015  ** corresponding to page pgnoRoot. */
66016  rc = saveAllCursors(pBt, 0, 0);
66017  releasePage(pPageMove);
66018  if( rc!=SQLITE_OK ){
66019  return rc;
66020  }
66021 
66022  /* Move the page currently at pgnoRoot to pgnoMove. */
66023  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66024  if( rc!=SQLITE_OK ){
66025  return rc;
66026  }
66027  rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
66028  if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
66029  rc = SQLITE_CORRUPT_BKPT;
66030  }
66031  if( rc!=SQLITE_OK ){
66032  releasePage(pRoot);
66033  return rc;
66034  }
66035  assert( eType!=PTRMAP_ROOTPAGE );
66036  assert( eType!=PTRMAP_FREEPAGE );
66037  rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
66038  releasePage(pRoot);
66039 
66040  /* Obtain the page at pgnoRoot */
66041  if( rc!=SQLITE_OK ){
66042  return rc;
66043  }
66044  rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
66045  if( rc!=SQLITE_OK ){
66046  return rc;
66047  }
66048  rc = sqlite3PagerWrite(pRoot->pDbPage);
66049  if( rc!=SQLITE_OK ){
66050  releasePage(pRoot);
66051  return rc;
66052  }
66053  }else{
66054  pRoot = pPageMove;
66055  }
66056 
66057  /* Update the pointer-map and meta-data with the new root-page number. */
66058  ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
66059  if( rc ){
66060  releasePage(pRoot);
66061  return rc;
66062  }
66063 
66064  /* When the new root page was allocated, page 1 was made writable in
66065  ** order either to increase the database filesize, or to decrement the
66066  ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
66067  */
66068  assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
66069  rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
66070  if( NEVER(rc) ){
66071  releasePage(pRoot);
66072  return rc;
66073  }
66074 
66075  }else{
66076  rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
66077  if( rc ) return rc;
66078  }
66079 #endif
66080  assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
66081  if( createTabFlags & BTREE_INTKEY ){
66082  ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
66083  }else{
66084  ptfFlags = PTF_ZERODATA | PTF_LEAF;
66085  }
66086  zeroPage(pRoot, ptfFlags);
66087  sqlite3PagerUnref(pRoot->pDbPage);
66088  assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
66089  *piTable = (int)pgnoRoot;
66090  return SQLITE_OK;
66091 }
66092 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
66093  int rc;
66094  sqlite3BtreeEnter(p);
66095  rc = btreeCreateTable(p, piTable, flags);
66096  sqlite3BtreeLeave(p);
66097  return rc;
66098 }
66099 
66100 /*
66101 ** Erase the given database page and all its children. Return
66102 ** the page to the freelist.
66103 */
66105  BtShared *pBt, /* The BTree that contains the table */
66106  Pgno pgno, /* Page number to clear */
66107  int freePageFlag, /* Deallocate page if true */
66108  int *pnChange /* Add number of Cells freed to this counter */
66109 ){
66110  MemPage *pPage;
66111  int rc;
66112  unsigned char *pCell;
66113  int i;
66114  int hdr;
66115  u16 szCell;
66116 
66117  assert( sqlite3_mutex_held(pBt->mutex) );
66118  if( pgno>btreePagecount(pBt) ){
66119  return SQLITE_CORRUPT_BKPT;
66120  }
66121  rc = getAndInitPage(pBt, pgno, &pPage, 0, 0);
66122  if( rc ) return rc;
66123  if( pPage->bBusy ){
66124  rc = SQLITE_CORRUPT_BKPT;
66125  goto cleardatabasepage_out;
66126  }
66127  pPage->bBusy = 1;
66128  hdr = pPage->hdrOffset;
66129  for(i=0; i<pPage->nCell; i++){
66130  pCell = findCell(pPage, i);
66131  if( !pPage->leaf ){
66132  rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
66133  if( rc ) goto cleardatabasepage_out;
66134  }
66135  rc = clearCell(pPage, pCell, &szCell);
66136  if( rc ) goto cleardatabasepage_out;
66137  }
66138  if( !pPage->leaf ){
66139  rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
66140  if( rc ) goto cleardatabasepage_out;
66141  }else if( pnChange ){
66142  assert( pPage->intKey || CORRUPT_DB );
66143  testcase( !pPage->intKey );
66144  *pnChange += pPage->nCell;
66145  }
66146  if( freePageFlag ){
66147  freePage(pPage, &rc);
66148  }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
66149  zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
66150  }
66151 
66152 cleardatabasepage_out:
66153  pPage->bBusy = 0;
66154  releasePage(pPage);
66155  return rc;
66156 }
66157 
66158 /*
66159 ** Delete all information from a single table in the database. iTable is
66160 ** the page number of the root of the table. After this routine returns,
66161 ** the root page is empty, but still exists.
66162 **
66163 ** This routine will fail with SQLITE_LOCKED if there are any open
66164 ** read cursors on the table. Open write cursors are moved to the
66165 ** root of the table.
66166 **
66167 ** If pnChange is not NULL, then table iTable must be an intkey table. The
66168 ** integer value pointed to by pnChange is incremented by the number of
66169 ** entries in the table.
66170 */
66171 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
66172  int rc;
66173  BtShared *pBt = p->pBt;
66174  sqlite3BtreeEnter(p);
66175  assert( p->inTrans==TRANS_WRITE );
66176 
66177  rc = saveAllCursors(pBt, (Pgno)iTable, 0);
66178 
66179  if( SQLITE_OK==rc ){
66180  /* Invalidate all incrblob cursors open on table iTable (assuming iTable
66181  ** is the root of a table b-tree - if it is not, the following call is
66182  ** a no-op). */
66183  invalidateIncrblobCursors(p, 0, 1);
66184  rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
66185  }
66186  sqlite3BtreeLeave(p);
66187  return rc;
66188 }
66189 
66190 /*
66191 ** Delete all information from the single table that pCur is open on.
66192 **
66193 ** This routine only work for pCur on an ephemeral table.
66194 */
66196  return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
66197 }
66198 
66199 /*
66200 ** Erase all information in a table and add the root of the table to
66201 ** the freelist. Except, the root of the principle table (the one on
66202 ** page 1) is never added to the freelist.
66203 **
66204 ** This routine will fail with SQLITE_LOCKED if there are any open
66205 ** cursors on the table.
66206 **
66207 ** If AUTOVACUUM is enabled and the page at iTable is not the last
66208 ** root page in the database file, then the last root page
66209 ** in the database file is moved into the slot formerly occupied by
66210 ** iTable and that last slot formerly occupied by the last root page
66211 ** is added to the freelist instead of iTable. In this say, all
66212 ** root pages are kept at the beginning of the database file, which
66213 ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
66214 ** page number that used to be the last root page in the file before
66215 ** the move. If no page gets moved, *piMoved is set to 0.
66216 ** The last root page is recorded in meta[3] and the value of
66217 ** meta[3] is updated by this procedure.
66218 */
66219 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
66220  int rc;
66221  MemPage *pPage = 0;
66222  BtShared *pBt = p->pBt;
66223 
66224  assert( sqlite3BtreeHoldsMutex(p) );
66225  assert( p->inTrans==TRANS_WRITE );
66226 
66227  /* It is illegal to drop a table if any cursors are open on the
66228  ** database. This is because in auto-vacuum mode the backend may
66229  ** need to move another root-page to fill a gap left by the deleted
66230  ** root page. If an open cursor was using this page a problem would
66231  ** occur.
66232  **
66233  ** This error is caught long before control reaches this point.
66234  */
66235  if( NEVER(pBt->pCursor) ){
66238  }
66239 
66240  /*
66241  ** It is illegal to drop the sqlite_master table on page 1. But again,
66242  ** this error is caught long before reaching this point.
66243  */
66244  if( NEVER(iTable<2) ){
66245  return SQLITE_CORRUPT_BKPT;
66246  }
66247 
66248  rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
66249  if( rc ) return rc;
66250  rc = sqlite3BtreeClearTable(p, iTable, 0);
66251  if( rc ){
66252  releasePage(pPage);
66253  return rc;
66254  }
66255 
66256  *piMoved = 0;
66257 
66258 #ifdef SQLITE_OMIT_AUTOVACUUM
66259  freePage(pPage, &rc);
66260  releasePage(pPage);
66261 #else
66262  if( pBt->autoVacuum ){
66263  Pgno maxRootPgno;
66264  sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
66265 
66266  if( iTable==maxRootPgno ){
66267  /* If the table being dropped is the table with the largest root-page
66268  ** number in the database, put the root page on the free list.
66269  */
66270  freePage(pPage, &rc);
66271  releasePage(pPage);
66272  if( rc!=SQLITE_OK ){
66273  return rc;
66274  }
66275  }else{
66276  /* The table being dropped does not have the largest root-page
66277  ** number in the database. So move the page that does into the
66278  ** gap left by the deleted root-page.
66279  */
66280  MemPage *pMove;
66281  releasePage(pPage);
66282  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66283  if( rc!=SQLITE_OK ){
66284  return rc;
66285  }
66286  rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
66287  releasePage(pMove);
66288  if( rc!=SQLITE_OK ){
66289  return rc;
66290  }
66291  pMove = 0;
66292  rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
66293  freePage(pMove, &rc);
66294  releasePage(pMove);
66295  if( rc!=SQLITE_OK ){
66296  return rc;
66297  }
66298  *piMoved = maxRootPgno;
66299  }
66300 
66301  /* Set the new 'max-root-page' value in the database header. This
66302  ** is the old value less one, less one more if that happens to
66303  ** be a root-page number, less one again if that is the
66304  ** PENDING_BYTE_PAGE.
66305  */
66306  maxRootPgno--;
66307  while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
66308  || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
66309  maxRootPgno--;
66310  }
66311  assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
66312 
66313  rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
66314  }else{
66315  freePage(pPage, &rc);
66316  releasePage(pPage);
66317  }
66318 #endif
66319  return rc;
66320 }
66321 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
66322  int rc;
66323  sqlite3BtreeEnter(p);
66324  rc = btreeDropTable(p, iTable, piMoved);
66325  sqlite3BtreeLeave(p);
66326  return rc;
66327 }
66328 
66329 
66330 /*
66331 ** This function may only be called if the b-tree connection already
66332 ** has a read or write transaction open on the database.
66333 **
66334 ** Read the meta-information out of a database file. Meta[0]
66335 ** is the number of free pages currently in the database. Meta[1]
66336 ** through meta[15] are available for use by higher layers. Meta[0]
66337 ** is read-only, the others are read/write.
66338 **
66339 ** The schema layer numbers meta values differently. At the schema
66340 ** layer (and the SetCookie and ReadCookie opcodes) the number of
66341 ** free pages is not visible. So Cookie[0] is the same as Meta[1].
66342 **
66343 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case. Instead
66344 ** of reading the value out of the header, it instead loads the "DataVersion"
66345 ** from the pager. The BTREE_DATA_VERSION value is not actually stored in the
66346 ** database file. It is a number computed by the pager. But its access
66347 ** pattern is the same as header meta values, and so it is convenient to
66348 ** read it from this routine.
66349 */
66350 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
66351  BtShared *pBt = p->pBt;
66352 
66353  sqlite3BtreeEnter(p);
66354  assert( p->inTrans>TRANS_NONE );
66356  assert( pBt->pPage1 );
66357  assert( idx>=0 && idx<=15 );
66358 
66359  if( idx==BTREE_DATA_VERSION ){
66360  *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
66361  }else{
66362  *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
66363  }
66364 
66365  /* If auto-vacuum is disabled in this build and this is an auto-vacuum
66366  ** database, mark the database as read-only. */
66367 #ifdef SQLITE_OMIT_AUTOVACUUM
66368  if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
66369  pBt->btsFlags |= BTS_READ_ONLY;
66370  }
66371 #endif
66372 
66373  sqlite3BtreeLeave(p);
66374 }
66375 
66376 /*
66377 ** Write meta-information back into the database. Meta[0] is
66378 ** read-only and may not be written.
66379 */
66381  BtShared *pBt = p->pBt;
66382  unsigned char *pP1;
66383  int rc;
66384  assert( idx>=1 && idx<=15 );
66385  sqlite3BtreeEnter(p);
66386  assert( p->inTrans==TRANS_WRITE );
66387  assert( pBt->pPage1!=0 );
66388  pP1 = pBt->pPage1->aData;
66389  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
66390  if( rc==SQLITE_OK ){
66391  put4byte(&pP1[36 + idx*4], iMeta);
66392 #ifndef SQLITE_OMIT_AUTOVACUUM
66393  if( idx==BTREE_INCR_VACUUM ){
66394  assert( pBt->autoVacuum || iMeta==0 );
66395  assert( iMeta==0 || iMeta==1 );
66396  pBt->incrVacuum = (u8)iMeta;
66397  }
66398 #endif
66399  }
66400  sqlite3BtreeLeave(p);
66401  return rc;
66402 }
66403 
66404 #ifndef SQLITE_OMIT_BTREECOUNT
66405 /*
66406 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
66407 ** number of entries in the b-tree and write the result to *pnEntry.
66408 **
66409 ** SQLITE_OK is returned if the operation is successfully executed.
66410 ** Otherwise, if an error is encountered (i.e. an IO error or database
66411 ** corruption) an SQLite error code is returned.
66412 */
66413 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
66414  i64 nEntry = 0; /* Value to return in *pnEntry */
66415  int rc; /* Return code */
66416 
66417  if( pCur->pgnoRoot==0 ){
66418  *pnEntry = 0;
66419  return SQLITE_OK;
66420  }
66421  rc = moveToRoot(pCur);
66422 
66423  /* Unless an error occurs, the following loop runs one iteration for each
66424  ** page in the B-Tree structure (not including overflow pages).
66425  */
66426  while( rc==SQLITE_OK ){
66427  int iIdx; /* Index of child node in parent */
66428  MemPage *pPage; /* Current page of the b-tree */
66429 
66430  /* If this is a leaf page or the tree is not an int-key tree, then
66431  ** this page contains countable entries. Increment the entry counter
66432  ** accordingly.
66433  */
66434  pPage = pCur->apPage[pCur->iPage];
66435  if( pPage->leaf || !pPage->intKey ){
66436  nEntry += pPage->nCell;
66437  }
66438 
66439  /* pPage is a leaf node. This loop navigates the cursor so that it
66440  ** points to the first interior cell that it points to the parent of
66441  ** the next page in the tree that has not yet been visited. The
66442  ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
66443  ** of the page, or to the number of cells in the page if the next page
66444  ** to visit is the right-child of its parent.
66445  **
66446  ** If all pages in the tree have been visited, return SQLITE_OK to the
66447  ** caller.
66448  */
66449  if( pPage->leaf ){
66450  do {
66451  if( pCur->iPage==0 ){
66452  /* All pages of the b-tree have been visited. Return successfully. */
66453  *pnEntry = nEntry;
66454  return moveToRoot(pCur);
66455  }
66456  moveToParent(pCur);
66457  }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
66458 
66459  pCur->aiIdx[pCur->iPage]++;
66460  pPage = pCur->apPage[pCur->iPage];
66461  }
66462 
66463  /* Descend to the child node of the cell that the cursor currently
66464  ** points at. This is the right-child if (iIdx==pPage->nCell).
66465  */
66466  iIdx = pCur->aiIdx[pCur->iPage];
66467  if( iIdx==pPage->nCell ){
66468  rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
66469  }else{
66470  rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
66471  }
66472  }
66473 
66474  /* An error has occurred. Return an error code. */
66475  return rc;
66476 }
66477 #endif
66478 
66479 /*
66480 ** Return the pager associated with a BTree. This routine is used for
66481 ** testing and debugging only.
66482 */
66484  return p->pBt->pPager;
66485 }
66486 
66487 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66488 /*
66489 ** Append a message to the error message string.
66490 */
66491 static void checkAppendMsg(
66492  IntegrityCk *pCheck,
66493  const char *zFormat,
66494  ...
66495 ){
66496  va_list ap;
66497  if( !pCheck->mxErr ) return;
66498  pCheck->mxErr--;
66499  pCheck->nErr++;
66500  va_start(ap, zFormat);
66501  if( pCheck->errMsg.nChar ){
66502  sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
66503  }
66504  if( pCheck->zPfx ){
66505  sqlite3XPrintf(&pCheck->errMsg, pCheck->zPfx, pCheck->v1, pCheck->v2);
66506  }
66507  sqlite3VXPrintf(&pCheck->errMsg, zFormat, ap);
66508  va_end(ap);
66509  if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
66510  pCheck->mallocFailed = 1;
66511  }
66512 }
66513 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66514 
66515 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66516 
66517 /*
66518 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
66519 ** corresponds to page iPg is already set.
66520 */
66521 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66522  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66523  return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
66524 }
66525 
66526 /*
66527 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
66528 */
66529 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
66530  assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
66531  pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
66532 }
66533 
66534 
66535 /*
66536 ** Add 1 to the reference count for page iPage. If this is the second
66537 ** reference to the page, add an error message to pCheck->zErrMsg.
66538 ** Return 1 if there are 2 or more references to the page and 0 if
66539 ** if this is the first reference to the page.
66540 **
66541 ** Also check that the page number is in bounds.
66542 */
66543 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
66544  if( iPage==0 ) return 1;
66545  if( iPage>pCheck->nPage ){
66546  checkAppendMsg(pCheck, "invalid page number %d", iPage);
66547  return 1;
66548  }
66549  if( getPageReferenced(pCheck, iPage) ){
66550  checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
66551  return 1;
66552  }
66553  setPageReferenced(pCheck, iPage);
66554  return 0;
66555 }
66556 
66557 #ifndef SQLITE_OMIT_AUTOVACUUM
66558 /*
66559 ** Check that the entry in the pointer-map for page iChild maps to
66560 ** page iParent, pointer type ptrType. If not, append an error message
66561 ** to pCheck.
66562 */
66563 static void checkPtrmap(
66564  IntegrityCk *pCheck, /* Integrity check context */
66565  Pgno iChild, /* Child page number */
66566  u8 eType, /* Expected pointer map type */
66567  Pgno iParent /* Expected pointer map parent page number */
66568 ){
66569  int rc;
66570  u8 ePtrmapType;
66571  Pgno iPtrmapParent;
66572 
66573  rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
66574  if( rc!=SQLITE_OK ){
66575  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
66576  checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
66577  return;
66578  }
66579 
66580  if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
66581  checkAppendMsg(pCheck,
66582  "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
66583  iChild, eType, iParent, ePtrmapType, iPtrmapParent);
66584  }
66585 }
66586 #endif
66587 
66588 /*
66589 ** Check the integrity of the freelist or of an overflow page list.
66590 ** Verify that the number of pages on the list is N.
66591 */
66592 static void checkList(
66593  IntegrityCk *pCheck, /* Integrity checking context */
66594  int isFreeList, /* True for a freelist. False for overflow page list */
66595  int iPage, /* Page number for first page in the list */
66596  int N /* Expected number of pages in the list */
66597 ){
66598  int i;
66599  int expected = N;
66600  int iFirst = iPage;
66601  while( N-- > 0 && pCheck->mxErr ){
66602  DbPage *pOvflPage;
66603  unsigned char *pOvflData;
66604  if( iPage<1 ){
66605  checkAppendMsg(pCheck,
66606  "%d of %d pages missing from overflow list starting at %d",
66607  N+1, expected, iFirst);
66608  break;
66609  }
66610  if( checkRef(pCheck, iPage) ) break;
66611  if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage, 0) ){
66612  checkAppendMsg(pCheck, "failed to get page %d", iPage);
66613  break;
66614  }
66615  pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
66616  if( isFreeList ){
66617  int n = get4byte(&pOvflData[4]);
66618 #ifndef SQLITE_OMIT_AUTOVACUUM
66619  if( pCheck->pBt->autoVacuum ){
66620  checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
66621  }
66622 #endif
66623  if( n>(int)pCheck->pBt->usableSize/4-2 ){
66624  checkAppendMsg(pCheck,
66625  "freelist leaf count too big on page %d", iPage);
66626  N--;
66627  }else{
66628  for(i=0; i<n; i++){
66629  Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
66630 #ifndef SQLITE_OMIT_AUTOVACUUM
66631  if( pCheck->pBt->autoVacuum ){
66632  checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
66633  }
66634 #endif
66635  checkRef(pCheck, iFreePage);
66636  }
66637  N -= n;
66638  }
66639  }
66640 #ifndef SQLITE_OMIT_AUTOVACUUM
66641  else{
66642  /* If this database supports auto-vacuum and iPage is not the last
66643  ** page in this overflow list, check that the pointer-map entry for
66644  ** the following page matches iPage.
66645  */
66646  if( pCheck->pBt->autoVacuum && N>0 ){
66647  i = get4byte(pOvflData);
66648  checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
66649  }
66650  }
66651 #endif
66652  iPage = get4byte(pOvflData);
66653  sqlite3PagerUnref(pOvflPage);
66654 
66655  if( isFreeList && N<(iPage!=0) ){
66656  checkAppendMsg(pCheck, "free-page count in header is too small");
66657  }
66658  }
66659 }
66660 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66661 
66662 /*
66663 ** An implementation of a min-heap.
66664 **
66665 ** aHeap[0] is the number of elements on the heap. aHeap[1] is the
66666 ** root element. The daughter nodes of aHeap[N] are aHeap[N*2]
66667 ** and aHeap[N*2+1].
66668 **
66669 ** The heap property is this: Every node is less than or equal to both
66670 ** of its daughter nodes. A consequence of the heap property is that the
66671 ** root node aHeap[1] is always the minimum value currently in the heap.
66672 **
66673 ** The btreeHeapInsert() routine inserts an unsigned 32-bit number onto
66674 ** the heap, preserving the heap property. The btreeHeapPull() routine
66675 ** removes the root element from the heap (the minimum value in the heap)
66676 ** and then moves other nodes around as necessary to preserve the heap
66677 ** property.
66678 **
66679 ** This heap is used for cell overlap and coverage testing. Each u32
66680 ** entry represents the span of a cell or freeblock on a btree page.
66681 ** The upper 16 bits are the index of the first byte of a range and the
66682 ** lower 16 bits are the index of the last byte of that range.
66683 */
66684 static void btreeHeapInsert(u32 *aHeap, u32 x){
66685  u32 j, i = ++aHeap[0];
66686  aHeap[i] = x;
66687  while( (j = i/2)>0 && aHeap[j]>aHeap[i] ){
66688  x = aHeap[j];
66689  aHeap[j] = aHeap[i];
66690  aHeap[i] = x;
66691  i = j;
66692  }
66693 }
66694 static int btreeHeapPull(u32 *aHeap, u32 *pOut){
66695  u32 j, i, x;
66696  if( (x = aHeap[0])==0 ) return 0;
66697  *pOut = aHeap[1];
66698  aHeap[1] = aHeap[x];
66699  aHeap[x] = 0xffffffff;
66700  aHeap[0]--;
66701  i = 1;
66702  while( (j = i*2)<=aHeap[0] ){
66703  if( aHeap[j]>aHeap[j+1] ) j++;
66704  if( aHeap[i]<aHeap[j] ) break;
66705  x = aHeap[i];
66706  aHeap[i] = aHeap[j];
66707  aHeap[j] = x;
66708  i = j;
66709  }
66710  return 1;
66711 }
66712 
66713 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66714 /*
66715 ** Do various sanity checks on a single page of a tree. Return
66716 ** the tree depth. Root pages return 0. Parents of root pages
66717 ** return 1, and so forth.
66718 **
66719 ** These checks are done:
66720 **
66721 ** 1. Make sure that cells and freeblocks do not overlap
66722 ** but combine to completely cover the page.
66723 ** 2. Make sure integer cell keys are in order.
66724 ** 3. Check the integrity of overflow pages.
66725 ** 4. Recursively call checkTreePage on all children.
66726 ** 5. Verify that the depth of all children is the same.
66727 */
66728 static int checkTreePage(
66729  IntegrityCk *pCheck, /* Context for the sanity check */
66730  int iPage, /* Page number of the page to check */
66731  i64 *piMinKey, /* Write minimum integer primary key here */
66732  i64 maxKey /* Error if integer primary key greater than this */
66733 ){
66734  MemPage *pPage = 0; /* The page being analyzed */
66735  int i; /* Loop counter */
66736  int rc; /* Result code from subroutine call */
66737  int depth = -1, d2; /* Depth of a subtree */
66738  int pgno; /* Page number */
66739  int nFrag; /* Number of fragmented bytes on the page */
66740  int hdr; /* Offset to the page header */
66741  int cellStart; /* Offset to the start of the cell pointer array */
66742  int nCell; /* Number of cells */
66743  int doCoverageCheck = 1; /* True if cell coverage checking should be done */
66744  int keyCanBeEqual = 1; /* True if IPK can be equal to maxKey
66745  ** False if IPK must be strictly less than maxKey */
66746  u8 *data; /* Page content */
66747  u8 *pCell; /* Cell content */
66748  u8 *pCellIdx; /* Next element of the cell pointer array */
66749  BtShared *pBt; /* The BtShared object that owns pPage */
66750  u32 pc; /* Address of a cell */
66751  u32 usableSize; /* Usable size of the page */
66752  u32 contentOffset; /* Offset to the start of the cell content area */
66753  u32 *heap = 0; /* Min-heap used for checking cell coverage */
66754  u32 x, prev = 0; /* Next and previous entry on the min-heap */
66755  const char *saved_zPfx = pCheck->zPfx;
66756  int saved_v1 = pCheck->v1;
66757  int saved_v2 = pCheck->v2;
66758  u8 savedIsInit = 0;
66759 
66760  /* Check that the page exists
66761  */
66762  pBt = pCheck->pBt;
66763  usableSize = pBt->usableSize;
66764  if( iPage==0 ) return 0;
66765  if( checkRef(pCheck, iPage) ) return 0;
66766  pCheck->zPfx = "Page %d: ";
66767  pCheck->v1 = iPage;
66768  if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
66769  checkAppendMsg(pCheck,
66770  "unable to get the page. error code=%d", rc);
66771  goto end_of_check;
66772  }
66773 
66774  /* Clear MemPage.isInit to make sure the corruption detection code in
66775  ** btreeInitPage() is executed. */
66776  savedIsInit = pPage->isInit;
66777  pPage->isInit = 0;
66778  if( (rc = btreeInitPage(pPage))!=0 ){
66779  assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
66780  checkAppendMsg(pCheck,
66781  "btreeInitPage() returns error code %d", rc);
66782  goto end_of_check;
66783  }
66784  data = pPage->aData;
66785  hdr = pPage->hdrOffset;
66786 
66787  /* Set up for cell analysis */
66788  pCheck->zPfx = "On tree page %d cell %d: ";
66789  contentOffset = get2byteNotZero(&data[hdr+5]);
66790  assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
66791 
66792  /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
66793  ** number of cells on the page. */
66794  nCell = get2byte(&data[hdr+3]);
66795  assert( pPage->nCell==nCell );
66796 
66797  /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
66798  ** immediately follows the b-tree page header. */
66799  cellStart = hdr + 12 - 4*pPage->leaf;
66800  assert( pPage->aCellIdx==&data[cellStart] );
66801  pCellIdx = &data[cellStart + 2*(nCell-1)];
66802 
66803  if( !pPage->leaf ){
66804  /* Analyze the right-child page of internal pages */
66805  pgno = get4byte(&data[hdr+8]);
66806 #ifndef SQLITE_OMIT_AUTOVACUUM
66807  if( pBt->autoVacuum ){
66808  pCheck->zPfx = "On page %d at right child: ";
66809  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
66810  }
66811 #endif
66812  depth = checkTreePage(pCheck, pgno, &maxKey, maxKey);
66813  keyCanBeEqual = 0;
66814  }else{
66815  /* For leaf pages, the coverage check will occur in the same loop
66816  ** as the other cell checks, so initialize the heap. */
66817  heap = pCheck->heap;
66818  heap[0] = 0;
66819  }
66820 
66821  /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
66822  ** integer offsets to the cell contents. */
66823  for(i=nCell-1; i>=0 && pCheck->mxErr; i--){
66824  CellInfo info;
66825 
66826  /* Check cell size */
66827  pCheck->v2 = i;
66828  assert( pCellIdx==&data[cellStart + i*2] );
66829  pc = get2byteAligned(pCellIdx);
66830  pCellIdx -= 2;
66831  if( pc<contentOffset || pc>usableSize-4 ){
66832  checkAppendMsg(pCheck, "Offset %d out of range %d..%d",
66833  pc, contentOffset, usableSize-4);
66834  doCoverageCheck = 0;
66835  continue;
66836  }
66837  pCell = &data[pc];
66838  pPage->xParseCell(pPage, pCell, &info);
66839  if( pc+info.nSize>usableSize ){
66840  checkAppendMsg(pCheck, "Extends off end of page");
66841  doCoverageCheck = 0;
66842  continue;
66843  }
66844 
66845  /* Check for integer primary key out of range */
66846  if( pPage->intKey ){
66847  if( keyCanBeEqual ? (info.nKey > maxKey) : (info.nKey >= maxKey) ){
66848  checkAppendMsg(pCheck, "Rowid %lld out of order", info.nKey);
66849  }
66850  maxKey = info.nKey;
66851  }
66852 
66853  /* Check the content overflow list */
66854  if( info.nPayload>info.nLocal ){
66855  int nPage; /* Number of pages on the overflow chain */
66856  Pgno pgnoOvfl; /* First page of the overflow chain */
66857  assert( pc + info.nSize - 4 <= usableSize );
66858  nPage = (info.nPayload - info.nLocal + usableSize - 5)/(usableSize - 4);
66859  pgnoOvfl = get4byte(&pCell[info.nSize - 4]);
66860 #ifndef SQLITE_OMIT_AUTOVACUUM
66861  if( pBt->autoVacuum ){
66862  checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
66863  }
66864 #endif
66865  checkList(pCheck, 0, pgnoOvfl, nPage);
66866  }
66867 
66868  if( !pPage->leaf ){
66869  /* Check sanity of left child page for internal pages */
66870  pgno = get4byte(pCell);
66871 #ifndef SQLITE_OMIT_AUTOVACUUM
66872  if( pBt->autoVacuum ){
66873  checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
66874  }
66875 #endif
66876  d2 = checkTreePage(pCheck, pgno, &maxKey, maxKey);
66877  keyCanBeEqual = 0;
66878  if( d2!=depth ){
66879  checkAppendMsg(pCheck, "Child page depth differs");
66880  depth = d2;
66881  }
66882  }else{
66883  /* Populate the coverage-checking heap for leaf pages */
66884  btreeHeapInsert(heap, (pc<<16)|(pc+info.nSize-1));
66885  }
66886  }
66887  *piMinKey = maxKey;
66888 
66889  /* Check for complete coverage of the page
66890  */
66891  pCheck->zPfx = 0;
66892  if( doCoverageCheck && pCheck->mxErr>0 ){
66893  /* For leaf pages, the min-heap has already been initialized and the
66894  ** cells have already been inserted. But for internal pages, that has
66895  ** not yet been done, so do it now */
66896  if( !pPage->leaf ){
66897  heap = pCheck->heap;
66898  heap[0] = 0;
66899  for(i=nCell-1; i>=0; i--){
66900  u32 size;
66901  pc = get2byteAligned(&data[cellStart+i*2]);
66902  size = pPage->xCellSize(pPage, &data[pc]);
66903  btreeHeapInsert(heap, (pc<<16)|(pc+size-1));
66904  }
66905  }
66906  /* Add the freeblocks to the min-heap
66907  **
66908  ** EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
66909  ** is the offset of the first freeblock, or zero if there are no
66910  ** freeblocks on the page.
66911  */
66912  i = get2byte(&data[hdr+1]);
66913  while( i>0 ){
66914  int size, j;
66915  assert( (u32)i<=usableSize-4 ); /* Enforced by btreeInitPage() */
66916  size = get2byte(&data[i+2]);
66917  assert( (u32)(i+size)<=usableSize ); /* Enforced by btreeInitPage() */
66918  btreeHeapInsert(heap, (((u32)i)<<16)|(i+size-1));
66919  /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
66920  ** big-endian integer which is the offset in the b-tree page of the next
66921  ** freeblock in the chain, or zero if the freeblock is the last on the
66922  ** chain. */
66923  j = get2byte(&data[i]);
66924  /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
66925  ** increasing offset. */
66926  assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
66927  assert( (u32)j<=usableSize-4 ); /* Enforced by btreeInitPage() */
66928  i = j;
66929  }
66930  /* Analyze the min-heap looking for overlap between cells and/or
66931  ** freeblocks, and counting the number of untracked bytes in nFrag.
66932  **
66933  ** Each min-heap entry is of the form: (start_address<<16)|end_address.
66934  ** There is an implied first entry the covers the page header, the cell
66935  ** pointer index, and the gap between the cell pointer index and the start
66936  ** of cell content.
66937  **
66938  ** The loop below pulls entries from the min-heap in order and compares
66939  ** the start_address against the previous end_address. If there is an
66940  ** overlap, that means bytes are used multiple times. If there is a gap,
66941  ** that gap is added to the fragmentation count.
66942  */
66943  nFrag = 0;
66944  prev = contentOffset - 1; /* Implied first min-heap entry */
66945  while( btreeHeapPull(heap,&x) ){
66946  if( (prev&0xffff)>=(x>>16) ){
66947  checkAppendMsg(pCheck,
66948  "Multiple uses for byte %u of page %d", x>>16, iPage);
66949  break;
66950  }else{
66951  nFrag += (x>>16) - (prev&0xffff) - 1;
66952  prev = x;
66953  }
66954  }
66955  nFrag += usableSize - (prev&0xffff) - 1;
66956  /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
66957  ** is stored in the fifth field of the b-tree page header.
66958  ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
66959  ** number of fragmented free bytes within the cell content area.
66960  */
66961  if( heap[0]==0 && nFrag!=data[hdr+7] ){
66962  checkAppendMsg(pCheck,
66963  "Fragmentation of %d bytes reported as %d on page %d",
66964  nFrag, data[hdr+7], iPage);
66965  }
66966  }
66967 
66968 end_of_check:
66969  if( !doCoverageCheck ) pPage->isInit = savedIsInit;
66970  releasePage(pPage);
66971  pCheck->zPfx = saved_zPfx;
66972  pCheck->v1 = saved_v1;
66973  pCheck->v2 = saved_v2;
66974  return depth+1;
66975 }
66976 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
66977 
66978 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
66979 /*
66980 ** This routine does a complete check of the given BTree file. aRoot[] is
66981 ** an array of pages numbers were each page number is the root page of
66982 ** a table. nRoot is the number of entries in aRoot.
66983 **
66984 ** A read-only or read-write transaction must be opened before calling
66985 ** this function.
66986 **
66987 ** Write the number of error seen in *pnErr. Except for some memory
66988 ** allocation errors, an error message held in memory obtained from
66989 ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
66990 ** returned. If a memory allocation error occurs, NULL is returned.
66991 */
66993  Btree *p, /* The btree to be checked */
66994  int *aRoot, /* An array of root pages numbers for individual trees */
66995  int nRoot, /* Number of entries in aRoot[] */
66996  int mxErr, /* Stop reporting errors after this many */
66997  int *pnErr /* Write number of errors seen to this variable */
66998 ){
66999  Pgno i;
67000  IntegrityCk sCheck;
67001  BtShared *pBt = p->pBt;
67002  int savedDbFlags = pBt->db->flags;
67003  char zErr[100];
67004  VVA_ONLY( int nRef );
67005 
67006  sqlite3BtreeEnter(p);
67008  VVA_ONLY( nRef = sqlite3PagerRefcount(pBt->pPager) );
67009  assert( nRef>=0 );
67010  sCheck.pBt = pBt;
67011  sCheck.pPager = pBt->pPager;
67012  sCheck.nPage = btreePagecount(sCheck.pBt);
67013  sCheck.mxErr = mxErr;
67014  sCheck.nErr = 0;
67015  sCheck.mallocFailed = 0;
67016  sCheck.zPfx = 0;
67017  sCheck.v1 = 0;
67018  sCheck.v2 = 0;
67019  sCheck.aPgRef = 0;
67020  sCheck.heap = 0;
67021  sqlite3StrAccumInit(&sCheck.errMsg, 0, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
67023  if( sCheck.nPage==0 ){
67024  goto integrity_ck_cleanup;
67025  }
67026 
67027  sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
67028  if( !sCheck.aPgRef ){
67029  sCheck.mallocFailed = 1;
67030  goto integrity_ck_cleanup;
67031  }
67032  sCheck.heap = (u32*)sqlite3PageMalloc( pBt->pageSize );
67033  if( sCheck.heap==0 ){
67034  sCheck.mallocFailed = 1;
67035  goto integrity_ck_cleanup;
67036  }
67037 
67038  i = PENDING_BYTE_PAGE(pBt);
67039  if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
67040 
67041  /* Check the integrity of the freelist
67042  */
67043  sCheck.zPfx = "Main freelist: ";
67044  checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
67045  get4byte(&pBt->pPage1->aData[36]));
67046  sCheck.zPfx = 0;
67047 
67048  /* Check all the tables.
67049  */
67050  testcase( pBt->db->flags & SQLITE_CellSizeCk );
67051  pBt->db->flags &= ~SQLITE_CellSizeCk;
67052  for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
67053  i64 notUsed;
67054  if( aRoot[i]==0 ) continue;
67055 #ifndef SQLITE_OMIT_AUTOVACUUM
67056  if( pBt->autoVacuum && aRoot[i]>1 ){
67057  checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
67058  }
67059 #endif
67060  checkTreePage(&sCheck, aRoot[i], &notUsed, LARGEST_INT64);
67061  }
67062  pBt->db->flags = savedDbFlags;
67063 
67064  /* Make sure every page in the file is referenced
67065  */
67066  for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
67067 #ifdef SQLITE_OMIT_AUTOVACUUM
67068  if( getPageReferenced(&sCheck, i)==0 ){
67069  checkAppendMsg(&sCheck, "Page %d is never used", i);
67070  }
67071 #else
67072  /* If the database supports auto-vacuum, make sure no tables contain
67073  ** references to pointer-map pages.
67074  */
67075  if( getPageReferenced(&sCheck, i)==0 &&
67076  (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
67077  checkAppendMsg(&sCheck, "Page %d is never used", i);
67078  }
67079  if( getPageReferenced(&sCheck, i)!=0 &&
67080  (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
67081  checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
67082  }
67083 #endif
67084  }
67085 
67086  /* Clean up and report errors.
67087  */
67088 integrity_ck_cleanup:
67089  sqlite3PageFree(sCheck.heap);
67090  sqlite3_free(sCheck.aPgRef);
67091  if( sCheck.mallocFailed ){
67092  sqlite3StrAccumReset(&sCheck.errMsg);
67093  sCheck.nErr++;
67094  }
67095  *pnErr = sCheck.nErr;
67096  if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
67097  /* Make sure this analysis did not leave any unref() pages. */
67098  assert( nRef==sqlite3PagerRefcount(pBt->pPager) );
67099  sqlite3BtreeLeave(p);
67100  return sqlite3StrAccumFinish(&sCheck.errMsg);
67101 }
67102 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
67103 
67104 /*
67105 ** Return the full pathname of the underlying database file. Return
67106 ** an empty string if the database is in-memory or a TEMP database.
67107 **
67108 ** The pager filename is invariant as long as the pager is
67109 ** open so it is safe to access without the BtShared mutex.
67110 */
67112  assert( p->pBt->pPager!=0 );
67113  return sqlite3PagerFilename(p->pBt->pPager, 1);
67114 }
67115 
67116 /*
67117 ** Return the pathname of the journal file for this database. The return
67118 ** value of this routine is the same regardless of whether the journal file
67119 ** has been created or not.
67120 **
67121 ** The pager journal filename is invariant as long as the pager is
67122 ** open so it is safe to access without the BtShared mutex.
67123 */
67125  assert( p->pBt->pPager!=0 );
67126  return sqlite3PagerJournalname(p->pBt->pPager);
67127 }
67128 
67129 /*
67130 ** Return non-zero if a transaction is active.
67131 */
67133  assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
67134  return (p && (p->inTrans==TRANS_WRITE));
67135 }
67136 
67137 #ifndef SQLITE_OMIT_WAL
67138 /*
67139 ** Run a checkpoint on the Btree passed as the first argument.
67140 **
67141 ** Return SQLITE_LOCKED if this or any other connection has an open
67142 ** transaction on the shared-cache the argument Btree is connected to.
67143 **
67144 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
67145 */
67146 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
67147  int rc = SQLITE_OK;
67148  if( p ){
67149  BtShared *pBt = p->pBt;
67150  sqlite3BtreeEnter(p);
67151  if( pBt->inTransaction!=TRANS_NONE ){
67152  rc = SQLITE_LOCKED;
67153  }else{
67154  rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
67155  }
67156  sqlite3BtreeLeave(p);
67157  }
67158  return rc;
67159 }
67160 #endif
67161 
67162 /*
67163 ** Return non-zero if a read (or write) transaction is active.
67164 */
67166  assert( p );
67168  return p->inTrans!=TRANS_NONE;
67169 }
67170 
67172  assert( p );
67174  return p->nBackup!=0;
67175 }
67176 
67177 /*
67178 ** This function returns a pointer to a blob of memory associated with
67179 ** a single shared-btree. The memory is used by client code for its own
67180 ** purposes (for example, to store a high-level schema associated with
67181 ** the shared-btree). The btree layer manages reference counting issues.
67182 **
67183 ** The first time this is called on a shared-btree, nBytes bytes of memory
67184 ** are allocated, zeroed, and returned to the caller. For each subsequent
67185 ** call the nBytes parameter is ignored and a pointer to the same blob
67186 ** of memory returned.
67187 **
67188 ** If the nBytes parameter is 0 and the blob of memory has not yet been
67189 ** allocated, a null pointer is returned. If the blob has already been
67190 ** allocated, it is returned as normal.
67191 **
67192 ** Just before the shared-btree is closed, the function passed as the
67193 ** xFree argument when the memory allocation was made is invoked on the
67194 ** blob of allocated memory. The xFree function should not call sqlite3_free()
67195 ** on the memory, the btree layer does that.
67196 */
67197 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
67198  BtShared *pBt = p->pBt;
67199  sqlite3BtreeEnter(p);
67200  if( !pBt->pSchema && nBytes ){
67201  pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
67202  pBt->xFreeSchema = xFree;
67203  }
67204  sqlite3BtreeLeave(p);
67205  return pBt->pSchema;
67206 }
67207 
67208 /*
67209 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
67210 ** btree as the argument handle holds an exclusive lock on the
67211 ** sqlite_master table. Otherwise SQLITE_OK.
67212 */
67214  int rc;
67216  sqlite3BtreeEnter(p);
67219  sqlite3BtreeLeave(p);
67220  return rc;
67221 }
67222 
67223 
67224 #ifndef SQLITE_OMIT_SHARED_CACHE
67225 /*
67226 ** Obtain a lock on the table whose root page is iTab. The
67227 ** lock is a write lock if isWritelock is true or a read lock
67228 ** if it is false.
67229 */
67230 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
67231  int rc = SQLITE_OK;
67232  assert( p->inTrans!=TRANS_NONE );
67233  if( p->sharable ){
67234  u8 lockType = READ_LOCK + isWriteLock;
67235  assert( READ_LOCK+1==WRITE_LOCK );
67236  assert( isWriteLock==0 || isWriteLock==1 );
67237 
67238  sqlite3BtreeEnter(p);
67239  rc = querySharedCacheTableLock(p, iTab, lockType);
67240  if( rc==SQLITE_OK ){
67241  rc = setSharedCacheTableLock(p, iTab, lockType);
67242  }
67243  sqlite3BtreeLeave(p);
67244  }
67245  return rc;
67246 }
67247 #endif
67248 
67249 #ifndef SQLITE_OMIT_INCRBLOB
67250 /*
67251 ** Argument pCsr must be a cursor opened for writing on an
67252 ** INTKEY table currently pointing at a valid table entry.
67253 ** This function modifies the data stored as part of that entry.
67254 **
67255 ** Only the data content may only be modified, it is not possible to
67256 ** change the length of the data stored. If this function is called with
67257 ** parameters that attempt to write past the end of the existing data,
67258 ** no modifications are made and SQLITE_CORRUPT is returned.
67259 */
67260 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
67261  int rc;
67262  assert( cursorOwnsBtShared(pCsr) );
67263  assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
67264  assert( pCsr->curFlags & BTCF_Incrblob );
67265 
67266  rc = restoreCursorPosition(pCsr);
67267  if( rc!=SQLITE_OK ){
67268  return rc;
67269  }
67270  assert( pCsr->eState!=CURSOR_REQUIRESEEK );
67271  if( pCsr->eState!=CURSOR_VALID ){
67272  return SQLITE_ABORT;
67273  }
67274 
67275  /* Save the positions of all other cursors open on this table. This is
67276  ** required in case any of them are holding references to an xFetch
67277  ** version of the b-tree page modified by the accessPayload call below.
67278  **
67279  ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
67280  ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
67281  ** saveAllCursors can only return SQLITE_OK.
67282  */
67283  VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
67284  assert( rc==SQLITE_OK );
67285 
67286  /* Check some assumptions:
67287  ** (a) the cursor is open for writing,
67288  ** (b) there is a read/write transaction open,
67289  ** (c) the connection holds a write-lock on the table (if required),
67290  ** (d) there are no conflicting read-locks, and
67291  ** (e) the cursor points at a valid row of an intKey table.
67292  */
67293  if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
67294  return SQLITE_READONLY;
67295  }
67296  assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
67297  && pCsr->pBt->inTransaction==TRANS_WRITE );
67298  assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
67299  assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
67300  assert( pCsr->apPage[pCsr->iPage]->intKey );
67301 
67302  return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
67303 }
67304 
67305 /*
67306 ** Mark this cursor as an incremental blob cursor.
67307 */
67309  pCur->curFlags |= BTCF_Incrblob;
67310  pCur->pBtree->hasIncrblobCur = 1;
67311 }
67312 #endif
67313 
67314 /*
67315 ** Set both the "read version" (single byte at byte offset 18) and
67316 ** "write version" (single byte at byte offset 19) fields in the database
67317 ** header to iVersion.
67318 */
67319 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
67320  BtShared *pBt = pBtree->pBt;
67321  int rc; /* Return code */
67322 
67323  assert( iVersion==1 || iVersion==2 );
67324 
67325  /* If setting the version fields to 1, do not automatically open the
67326  ** WAL connection, even if the version fields are currently set to 2.
67327  */
67328  pBt->btsFlags &= ~BTS_NO_WAL;
67329  if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
67330 
67331  rc = sqlite3BtreeBeginTrans(pBtree, 0);
67332  if( rc==SQLITE_OK ){
67333  u8 *aData = pBt->pPage1->aData;
67334  if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
67335  rc = sqlite3BtreeBeginTrans(pBtree, 2);
67336  if( rc==SQLITE_OK ){
67337  rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
67338  if( rc==SQLITE_OK ){
67339  aData[18] = (u8)iVersion;
67340  aData[19] = (u8)iVersion;
67341  }
67342  }
67343  }
67344  }
67345 
67346  pBt->btsFlags &= ~BTS_NO_WAL;
67347  return rc;
67348 }
67349 
67350 /*
67351 ** Return true if the cursor has a hint specified. This routine is
67352 ** only used from within assert() statements
67353 */
67354 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
67355  return (pCsr->hints & mask)!=0;
67356 }
67357 
67358 /*
67359 ** Return true if the given Btree is read-only.
67360 */
67362  return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
67363 }
67364 
67365 /*
67366 ** Return the size of the header added to each page by this module.
67367 */
67369 
67370 #if !defined(SQLITE_OMIT_SHARED_CACHE)
67371 /*
67372 ** Return true if the Btree passed as the only argument is sharable.
67373 */
67375  return p->sharable;
67376 }
67377 #endif
67378 
67379 /************** End of btree.c ***********************************************/
67380 /************** Begin file backup.c ******************************************/
67381 /*
67382 ** 2009 January 28
67383 **
67384 ** The author disclaims copyright to this source code. In place of
67385 ** a legal notice, here is a blessing:
67386 **
67387 ** May you do good and not evil.
67388 ** May you find forgiveness for yourself and forgive others.
67389 ** May you share freely, never taking more than you give.
67390 **
67391 *************************************************************************
67392 ** This file contains the implementation of the sqlite3_backup_XXX()
67393 ** API functions and the related features.
67394 */
67395 /* #include "sqliteInt.h" */
67396 /* #include "btreeInt.h" */
67397 
67398 /*
67399 ** Structure allocated for each backup operation.
67400 */
67402  sqlite3* pDestDb; /* Destination database handle */
67403  Btree *pDest; /* Destination b-tree file */
67404  u32 iDestSchema; /* Original schema cookie in destination */
67405  int bDestLocked; /* True once a write-transaction is open on pDest */
67406 
67407  Pgno iNext; /* Page number of the next source page to copy */
67408  sqlite3* pSrcDb; /* Source database handle */
67409  Btree *pSrc; /* Source b-tree file */
67410 
67411  int rc; /* Backup process error code */
67412 
67413  /* These two variables are set by every call to backup_step(). They are
67414  ** read by calls to backup_remaining() and backup_pagecount().
67415  */
67416  Pgno nRemaining; /* Number of pages left to copy */
67417  Pgno nPagecount; /* Total number of pages to copy */
67418 
67419  int isAttached; /* True once backup has been registered with pager */
67420  sqlite3_backup *pNext; /* Next backup associated with source pager */
67421 };
67422 
67423 /*
67424 ** THREAD SAFETY NOTES:
67425 **
67426 ** Once it has been created using backup_init(), a single sqlite3_backup
67427 ** structure may be accessed via two groups of thread-safe entry points:
67428 **
67429 ** * Via the sqlite3_backup_XXX() API function backup_step() and
67430 ** backup_finish(). Both these functions obtain the source database
67431 ** handle mutex and the mutex associated with the source BtShared
67432 ** structure, in that order.
67433 **
67434 ** * Via the BackupUpdate() and BackupRestart() functions, which are
67435 ** invoked by the pager layer to report various state changes in
67436 ** the page cache associated with the source database. The mutex
67437 ** associated with the source database BtShared structure will always
67438 ** be held when either of these functions are invoked.
67439 **
67440 ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
67441 ** backup_pagecount() are not thread-safe functions. If they are called
67442 ** while some other thread is calling backup_step() or backup_finish(),
67443 ** the values returned may be invalid. There is no way for a call to
67444 ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
67445 ** or backup_pagecount().
67446 **
67447 ** Depending on the SQLite configuration, the database handles and/or
67448 ** the Btree objects may have their own mutexes that require locking.
67449 ** Non-sharable Btrees (in-memory databases for example), do not have
67450 ** associated mutexes.
67451 */
67452 
67453 /*
67454 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
67455 ** in connection handle pDb. If such a database cannot be found, return
67456 ** a NULL pointer and write an error message to pErrorDb.
67457 **
67458 ** If the "temp" database is requested, it may need to be opened by this
67459 ** function. If an error occurs while doing so, return 0 and write an
67460 ** error message to pErrorDb.
67461 */
67462 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
67463  int i = sqlite3FindDbName(pDb, zDb);
67464 
67465  if( i==1 ){
67466  Parse *pParse;
67467  int rc = 0;
67468  pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
67469  if( pParse==0 ){
67470  sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
67471  rc = SQLITE_NOMEM_BKPT;
67472  }else{
67473  pParse->db = pDb;
67474  if( sqlite3OpenTempDatabase(pParse) ){
67475  sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
67476  rc = SQLITE_ERROR;
67477  }
67478  sqlite3DbFree(pErrorDb, pParse->zErrMsg);
67479  sqlite3ParserReset(pParse);
67480  sqlite3StackFree(pErrorDb, pParse);
67481  }
67482  if( rc ){
67483  return 0;
67484  }
67485  }
67486 
67487  if( i<0 ){
67488  sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
67489  return 0;
67490  }
67491 
67492  return pDb->aDb[i].pBt;
67493 }
67494 
67495 /*
67496 ** Attempt to set the page size of the destination to match the page size
67497 ** of the source.
67498 */
67500  int rc;
67502  return rc;
67503 }
67504 
67505 /*
67506 ** Check that there is no open read-transaction on the b-tree passed as the
67507 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
67508 ** is an open read-transaction, return SQLITE_ERROR and leave an error
67509 ** message in database handle db.
67510 */
67511 static int checkReadTransaction(sqlite3 *db, Btree *p){
67512  if( sqlite3BtreeIsInReadTrans(p) ){
67513  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
67514  return SQLITE_ERROR;
67515  }
67516  return SQLITE_OK;
67517 }
67518 
67519 /*
67520 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
67521 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
67522 ** a pointer to the new sqlite3_backup object.
67523 **
67524 ** If an error occurs, NULL is returned and an error code and error message
67525 ** stored in database handle pDestDb.
67526 */
67528  sqlite3* pDestDb, /* Database to write to */
67529  const char *zDestDb, /* Name of database within pDestDb */
67530  sqlite3* pSrcDb, /* Database connection to read from */
67531  const char *zSrcDb /* Name of database within pSrcDb */
67532 ){
67533  sqlite3_backup *p; /* Value to return */
67534 
67535 #ifdef SQLITE_ENABLE_API_ARMOR
67536  if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
67538  return 0;
67539  }
67540 #endif
67541 
67542  /* Lock the source database handle. The destination database
67543  ** handle is not locked in this routine, but it is locked in
67544  ** sqlite3_backup_step(). The user is required to ensure that no
67545  ** other thread accesses the destination handle for the duration
67546  ** of the backup operation. Any attempt to use the destination
67547  ** database connection while a backup is in progress may cause
67548  ** a malfunction or a deadlock.
67549  */
67550  sqlite3_mutex_enter(pSrcDb->mutex);
67551  sqlite3_mutex_enter(pDestDb->mutex);
67552 
67553  if( pSrcDb==pDestDb ){
67555  pDestDb, SQLITE_ERROR, "source and destination must be distinct"
67556  );
67557  p = 0;
67558  }else {
67559  /* Allocate space for a new sqlite3_backup object...
67560  ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
67561  ** call to sqlite3_backup_init() and is destroyed by a call to
67562  ** sqlite3_backup_finish(). */
67564  if( !p ){
67565  sqlite3Error(pDestDb, SQLITE_NOMEM_BKPT);
67566  }
67567  }
67568 
67569  /* If the allocation succeeded, populate the new object. */
67570  if( p ){
67571  p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
67572  p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
67573  p->pDestDb = pDestDb;
67574  p->pSrcDb = pSrcDb;
67575  p->iNext = 1;
67576  p->isAttached = 0;
67577 
67578  if( 0==p->pSrc || 0==p->pDest
67579  || setDestPgsz(p)==SQLITE_NOMEM
67580  || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK
67581  ){
67582  /* One (or both) of the named databases did not exist or an OOM
67583  ** error was hit. Or there is a transaction open on the destination
67584  ** database. The error has already been written into the pDestDb
67585  ** handle. All that is left to do here is free the sqlite3_backup
67586  ** structure. */
67587  sqlite3_free(p);
67588  p = 0;
67589  }
67590  }
67591  if( p ){
67592  p->pSrc->nBackup++;
67593  }
67594 
67595  sqlite3_mutex_leave(pDestDb->mutex);
67596  sqlite3_mutex_leave(pSrcDb->mutex);
67597  return p;
67598 }
67599 
67600 /*
67601 ** Argument rc is an SQLite error code. Return true if this error is
67602 ** considered fatal if encountered during a backup operation. All errors
67603 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
67604 */
67605 static int isFatalError(int rc){
67606  return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
67607 }
67608 
67609 /*
67610 ** Parameter zSrcData points to a buffer containing the data for
67611 ** page iSrcPg from the source database. Copy this data into the
67612 ** destination database.
67613 */
67614 static int backupOnePage(
67615  sqlite3_backup *p, /* Backup handle */
67616  Pgno iSrcPg, /* Source database page to backup */
67617  const u8 *zSrcData, /* Source database page data */
67618  int bUpdate /* True for an update, false otherwise */
67619 ){
67620  Pager * const pDestPager = sqlite3BtreePager(p->pDest);
67621  const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
67622  int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
67623  const int nCopy = MIN(nSrcPgsz, nDestPgsz);
67624  const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
67625 #ifdef SQLITE_HAS_CODEC
67626  /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
67627  ** guaranteed that the shared-mutex is held by this thread, handle
67628  ** p->pSrc may not actually be the owner. */
67629  int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
67630  int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
67631 #endif
67632  int rc = SQLITE_OK;
67633  i64 iOff;
67634 
67636  assert( p->bDestLocked );
67637  assert( !isFatalError(p->rc) );
67638  assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
67639  assert( zSrcData );
67640 
67641  /* Catch the case where the destination is an in-memory database and the
67642  ** page sizes of the source and destination differ.
67643  */
67644  if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
67645  rc = SQLITE_READONLY;
67646  }
67647 
67648 #ifdef SQLITE_HAS_CODEC
67649  /* Backup is not possible if the page size of the destination is changing
67650  ** and a codec is in use.
67651  */
67652  if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
67653  rc = SQLITE_READONLY;
67654  }
67655 
67656  /* Backup is not possible if the number of bytes of reserve space differ
67657  ** between source and destination. If there is a difference, try to
67658  ** fix the destination to agree with the source. If that is not possible,
67659  ** then the backup cannot proceed.
67660  */
67661  if( nSrcReserve!=nDestReserve ){
67662  u32 newPgsz = nSrcPgsz;
67663  rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
67664  if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
67665  }
67666 #endif
67667 
67668  /* This loop runs once for each destination page spanned by the source
67669  ** page. For each iteration, variable iOff is set to the byte offset
67670  ** of the destination page.
67671  */
67672  for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
67673  DbPage *pDestPg = 0;
67674  Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
67675  if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
67676  if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg, 0))
67677  && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
67678  ){
67679  const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
67680  u8 *zDestData = sqlite3PagerGetData(pDestPg);
67681  u8 *zOut = &zDestData[iOff%nDestPgsz];
67682 
67683  /* Copy the data from the source page into the destination page.
67684  ** Then clear the Btree layer MemPage.isInit flag. Both this module
67685  ** and the pager code use this trick (clearing the first byte
67686  ** of the page 'extra' space to invalidate the Btree layers
67687  ** cached parse of the page). MemPage.isInit is marked
67688  ** "MUST BE FIRST" for this purpose.
67689  */
67690  memcpy(zOut, zIn, nCopy);
67691  ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
67692  if( iOff==0 && bUpdate==0 ){
67693  sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
67694  }
67695  }
67696  sqlite3PagerUnref(pDestPg);
67697  }
67698 
67699  return rc;
67700 }
67701 
67702 /*
67703 ** If pFile is currently larger than iSize bytes, then truncate it to
67704 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
67705 ** this function is a no-op.
67706 **
67707 ** Return SQLITE_OK if everything is successful, or an SQLite error
67708 ** code if an error occurs.
67709 */
67710 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
67711  i64 iCurrent;
67712  int rc = sqlite3OsFileSize(pFile, &iCurrent);
67713  if( rc==SQLITE_OK && iCurrent>iSize ){
67714  rc = sqlite3OsTruncate(pFile, iSize);
67715  }
67716  return rc;
67717 }
67718 
67719 /*
67720 ** Register this backup object with the associated source pager for
67721 ** callbacks when pages are changed or the cache invalidated.
67722 */
67724  sqlite3_backup **pp;
67725  assert( sqlite3BtreeHoldsMutex(p->pSrc) );
67727  p->pNext = *pp;
67728  *pp = p;
67729  p->isAttached = 1;
67730 }
67731 
67732 /*
67733 ** Copy nPage pages from the source b-tree to the destination.
67734 */
67736  int rc;
67737  int destMode; /* Destination journal mode */
67738  int pgszSrc = 0; /* Source page size */
67739  int pgszDest = 0; /* Destination page size */
67740 
67741 #ifdef SQLITE_ENABLE_API_ARMOR
67742  if( p==0 ) return SQLITE_MISUSE_BKPT;
67743 #endif
67745  sqlite3BtreeEnter(p->pSrc);
67746  if( p->pDestDb ){
67748  }
67749 
67750  rc = p->rc;
67751  if( !isFatalError(rc) ){
67752  Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
67753  Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
67754  int ii; /* Iterator variable */
67755  int nSrcPage = -1; /* Size of source db in pages */
67756  int bCloseTrans = 0; /* True if src db requires unlocking */
67757 
67758  /* If the source pager is currently in a write-transaction, return
67759  ** SQLITE_BUSY immediately.
67760  */
67761  if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
67762  rc = SQLITE_BUSY;
67763  }else{
67764  rc = SQLITE_OK;
67765  }
67766 
67767  /* Lock the destination database, if it is not locked already. */
67768  if( SQLITE_OK==rc && p->bDestLocked==0
67769  && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
67770  ){
67771  p->bDestLocked = 1;
67773  }
67774 
67775  /* If there is no open read-transaction on the source database, open
67776  ** one now. If a transaction is opened here, then it will be closed
67777  ** before this function exits.
67778  */
67779  if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
67780  rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
67781  bCloseTrans = 1;
67782  }
67783 
67784  /* Do not allow backup if the destination database is in WAL mode
67785  ** and the page sizes are different between source and destination */
67786  pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
67787  pgszDest = sqlite3BtreeGetPageSize(p->pDest);
67789  if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
67790  rc = SQLITE_READONLY;
67791  }
67792 
67793  /* Now that there is a read-lock on the source database, query the
67794  ** source pager for the number of pages in the database.
67795  */
67796  nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
67797  assert( nSrcPage>=0 );
67798  for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
67799  const Pgno iSrcPg = p->iNext; /* Source page number */
67800  if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
67801  DbPage *pSrcPg; /* Source page object */
67802  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg,PAGER_GET_READONLY);
67803  if( rc==SQLITE_OK ){
67804  rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
67805  sqlite3PagerUnref(pSrcPg);
67806  }
67807  }
67808  p->iNext++;
67809  }
67810  if( rc==SQLITE_OK ){
67811  p->nPagecount = nSrcPage;
67812  p->nRemaining = nSrcPage+1-p->iNext;
67813  if( p->iNext>(Pgno)nSrcPage ){
67814  rc = SQLITE_DONE;
67815  }else if( !p->isAttached ){
67816  attachBackupObject(p);
67817  }
67818  }
67819 
67820  /* Update the schema version field in the destination database. This
67821  ** is to make sure that the schema-version really does change in
67822  ** the case where the source and destination databases have the
67823  ** same schema version.
67824  */
67825  if( rc==SQLITE_DONE ){
67826  if( nSrcPage==0 ){
67827  rc = sqlite3BtreeNewDb(p->pDest);
67828  nSrcPage = 1;
67829  }
67830  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
67831  rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
67832  }
67833  if( rc==SQLITE_OK ){
67834  if( p->pDestDb ){
67836  }
67837  if( destMode==PAGER_JOURNALMODE_WAL ){
67838  rc = sqlite3BtreeSetVersion(p->pDest, 2);
67839  }
67840  }
67841  if( rc==SQLITE_OK ){
67842  int nDestTruncate;
67843  /* Set nDestTruncate to the final number of pages in the destination
67844  ** database. The complication here is that the destination page
67845  ** size may be different to the source page size.
67846  **
67847  ** If the source page size is smaller than the destination page size,
67848  ** round up. In this case the call to sqlite3OsTruncate() below will
67849  ** fix the size of the file. However it is important to call
67850  ** sqlite3PagerTruncateImage() here so that any pages in the
67851  ** destination file that lie beyond the nDestTruncate page mark are
67852  ** journalled by PagerCommitPhaseOne() before they are destroyed
67853  ** by the file truncation.
67854  */
67855  assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
67856  assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
67857  if( pgszSrc<pgszDest ){
67858  int ratio = pgszDest/pgszSrc;
67859  nDestTruncate = (nSrcPage+ratio-1)/ratio;
67860  if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
67861  nDestTruncate--;
67862  }
67863  }else{
67864  nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
67865  }
67866  assert( nDestTruncate>0 );
67867 
67868  if( pgszSrc<pgszDest ){
67869  /* If the source page-size is smaller than the destination page-size,
67870  ** two extra things may need to happen:
67871  **
67872  ** * The destination may need to be truncated, and
67873  **
67874  ** * Data stored on the pages immediately following the
67875  ** pending-byte page in the source database may need to be
67876  ** copied into the destination database.
67877  */
67878  const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
67879  sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
67880  Pgno iPg;
67881  int nDstPage;
67882  i64 iOff;
67883  i64 iEnd;
67884 
67885  assert( pFile );
67886  assert( nDestTruncate==0
67887  || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
67888  nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
67889  && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
67890  ));
67891 
67892  /* This block ensures that all data required to recreate the original
67893  ** database has been stored in the journal for pDestPager and the
67894  ** journal synced to disk. So at this point we may safely modify
67895  ** the database file in any way, knowing that if a power failure
67896  ** occurs, the original database will be reconstructed from the
67897  ** journal file. */
67898  sqlite3PagerPagecount(pDestPager, &nDstPage);
67899  for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
67900  if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
67901  DbPage *pPg;
67902  rc = sqlite3PagerGet(pDestPager, iPg, &pPg, 0);
67903  if( rc==SQLITE_OK ){
67904  rc = sqlite3PagerWrite(pPg);
67905  sqlite3PagerUnref(pPg);
67906  }
67907  }
67908  }
67909  if( rc==SQLITE_OK ){
67910  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
67911  }
67912 
67913  /* Write the extra pages and truncate the database file as required */
67914  iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
67915  for(
67916  iOff=PENDING_BYTE+pgszSrc;
67917  rc==SQLITE_OK && iOff<iEnd;
67918  iOff+=pgszSrc
67919  ){
67920  PgHdr *pSrcPg = 0;
67921  const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
67922  rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg, 0);
67923  if( rc==SQLITE_OK ){
67924  u8 *zData = sqlite3PagerGetData(pSrcPg);
67925  rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
67926  }
67927  sqlite3PagerUnref(pSrcPg);
67928  }
67929  if( rc==SQLITE_OK ){
67930  rc = backupTruncateFile(pFile, iSize);
67931  }
67932 
67933  /* Sync the database file to disk. */
67934  if( rc==SQLITE_OK ){
67935  rc = sqlite3PagerSync(pDestPager, 0);
67936  }
67937  }else{
67938  sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
67939  rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
67940  }
67941 
67942  /* Finish committing the transaction to the destination database. */
67943  if( SQLITE_OK==rc
67944  && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
67945  ){
67946  rc = SQLITE_DONE;
67947  }
67948  }
67949  }
67950 
67951  /* If bCloseTrans is true, then this function opened a read transaction
67952  ** on the source database. Close the read transaction here. There is
67953  ** no need to check the return values of the btree methods here, as
67954  ** "committing" a read-only transaction cannot fail.
67955  */
67956  if( bCloseTrans ){
67957  TESTONLY( int rc2 );
67958  TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
67959  TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
67960  assert( rc2==SQLITE_OK );
67961  }
67962 
67963  if( rc==SQLITE_IOERR_NOMEM ){
67964  rc = SQLITE_NOMEM_BKPT;
67965  }
67966  p->rc = rc;
67967  }
67968  if( p->pDestDb ){
67970  }
67971  sqlite3BtreeLeave(p->pSrc);
67973  return rc;
67974 }
67975 
67976 /*
67977 ** Release all resources associated with an sqlite3_backup* handle.
67978 */
67980  sqlite3_backup **pp; /* Ptr to head of pagers backup list */
67981  sqlite3 *pSrcDb; /* Source database connection */
67982  int rc; /* Value to return */
67983 
67984  /* Enter the mutexes */
67985  if( p==0 ) return SQLITE_OK;
67986  pSrcDb = p->pSrcDb;
67987  sqlite3_mutex_enter(pSrcDb->mutex);
67988  sqlite3BtreeEnter(p->pSrc);
67989  if( p->pDestDb ){
67991  }
67992 
67993  /* Detach this backup from the source pager. */
67994  if( p->pDestDb ){
67995  p->pSrc->nBackup--;
67996  }
67997  if( p->isAttached ){
67999  while( *pp!=p ){
68000  pp = &(*pp)->pNext;
68001  }
68002  *pp = p->pNext;
68003  }
68004 
68005  /* If a transaction is still open on the Btree, roll it back. */
68007 
68008  /* Set the error code of the destination database handle. */
68009  rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
68010  if( p->pDestDb ){
68011  sqlite3Error(p->pDestDb, rc);
68012 
68013  /* Exit the mutexes and free the backup context structure. */
68015  }
68016  sqlite3BtreeLeave(p->pSrc);
68017  if( p->pDestDb ){
68018  /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
68019  ** call to sqlite3_backup_init() and is destroyed by a call to
68020  ** sqlite3_backup_finish(). */
68021  sqlite3_free(p);
68022  }
68024  return rc;
68025 }
68026 
68027 /*
68028 ** Return the number of pages still to be backed up as of the most recent
68029 ** call to sqlite3_backup_step().
68030 */
68032 #ifdef SQLITE_ENABLE_API_ARMOR
68033  if( p==0 ){
68035  return 0;
68036  }
68037 #endif
68038  return p->nRemaining;
68039 }
68040 
68041 /*
68042 ** Return the total number of pages in the source database as of the most
68043 ** recent call to sqlite3_backup_step().
68044 */
68046 #ifdef SQLITE_ENABLE_API_ARMOR
68047  if( p==0 ){
68049  return 0;
68050  }
68051 #endif
68052  return p->nPagecount;
68053 }
68054 
68055 /*
68056 ** This function is called after the contents of page iPage of the
68057 ** source database have been modified. If page iPage has already been
68058 ** copied into the destination database, then the data written to the
68059 ** destination is now invalidated. The destination copy of iPage needs
68060 ** to be updated with the new data before the backup operation is
68061 ** complete.
68062 **
68063 ** It is assumed that the mutex associated with the BtShared object
68064 ** corresponding to the source database is held when this function is
68065 ** called.
68066 */
68068  sqlite3_backup *p,
68069  Pgno iPage,
68070  const u8 *aData
68071 ){
68072  assert( p!=0 );
68073  do{
68075  if( !isFatalError(p->rc) && iPage<p->iNext ){
68076  /* The backup process p has already copied page iPage. But now it
68077  ** has been modified by a transaction on the source pager. Copy
68078  ** the new data into the backup.
68079  */
68080  int rc;
68081  assert( p->pDestDb );
68083  rc = backupOnePage(p, iPage, aData, 1);
68085  assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
68086  if( rc!=SQLITE_OK ){
68087  p->rc = rc;
68088  }
68089  }
68090  }while( (p = p->pNext)!=0 );
68091 }
68092 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
68093  if( pBackup ) backupUpdate(pBackup, iPage, aData);
68094 }
68095 
68096 /*
68097 ** Restart the backup process. This is called when the pager layer
68098 ** detects that the database has been modified by an external database
68099 ** connection. In this case there is no way of knowing which of the
68100 ** pages that have been copied into the destination database are still
68101 ** valid and which are not, so the entire process needs to be restarted.
68102 **
68103 ** It is assumed that the mutex associated with the BtShared object
68104 ** corresponding to the source database is held when this function is
68105 ** called.
68106 */
68108  sqlite3_backup *p; /* Iterator variable */
68109  for(p=pBackup; p; p=p->pNext){
68111  p->iNext = 1;
68112  }
68113 }
68114 
68115 #ifndef SQLITE_OMIT_VACUUM
68116 /*
68117 ** Copy the complete content of pBtFrom into pBtTo. A transaction
68118 ** must be active for both files.
68119 **
68120 ** The size of file pTo may be reduced by this operation. If anything
68121 ** goes wrong, the transaction on pTo is rolled back. If successful, the
68122 ** transaction is committed before returning.
68123 */
68125  int rc;
68126  sqlite3_file *pFd; /* File descriptor for database pTo */
68127  sqlite3_backup b;
68128  sqlite3BtreeEnter(pTo);
68129  sqlite3BtreeEnter(pFrom);
68130 
68131  assert( sqlite3BtreeIsInTrans(pTo) );
68132  pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
68133  if( pFd->pMethods ){
68134  i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
68135  rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
68136  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
68137  if( rc ) goto copy_finished;
68138  }
68139 
68140  /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
68141  ** to 0. This is used by the implementations of sqlite3_backup_step()
68142  ** and sqlite3_backup_finish() to detect that they are being called
68143  ** from this function, not directly by the user.
68144  */
68145  memset(&b, 0, sizeof(b));
68146  b.pSrcDb = pFrom->db;
68147  b.pSrc = pFrom;
68148  b.pDest = pTo;
68149  b.iNext = 1;
68150 
68151 #ifdef SQLITE_HAS_CODEC
68152  sqlite3PagerAlignReserve(sqlite3BtreePager(pTo), sqlite3BtreePager(pFrom));
68153 #endif
68154 
68155  /* 0x7FFFFFFF is the hard limit for the number of pages in a database
68156  ** file. By passing this as the number of pages to copy to
68157  ** sqlite3_backup_step(), we can guarantee that the copy finishes
68158  ** within a single call (unless an error occurs). The assert() statement
68159  ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
68160  ** or an error code.
68161  */
68162  sqlite3_backup_step(&b, 0x7FFFFFFF);
68163  assert( b.rc!=SQLITE_OK );
68164  rc = sqlite3_backup_finish(&b);
68165  if( rc==SQLITE_OK ){
68166  pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
68167  }else{
68169  }
68170 
68171  assert( sqlite3BtreeIsInTrans(pTo)==0 );
68172 copy_finished:
68173  sqlite3BtreeLeave(pFrom);
68174  sqlite3BtreeLeave(pTo);
68175  return rc;
68176 }
68177 #endif /* SQLITE_OMIT_VACUUM */
68178 
68179 /************** End of backup.c **********************************************/
68180 /************** Begin file vdbemem.c *****************************************/
68181 /*
68182 ** 2004 May 26
68183 **
68184 ** The author disclaims copyright to this source code. In place of
68185 ** a legal notice, here is a blessing:
68186 **
68187 ** May you do good and not evil.
68188 ** May you find forgiveness for yourself and forgive others.
68189 ** May you share freely, never taking more than you give.
68190 **
68191 *************************************************************************
68192 **
68193 ** This file contains code use to manipulate "Mem" structure. A "Mem"
68194 ** stores a single value in the VDBE. Mem is an opaque structure visible
68195 ** only within the VDBE. Interface routines refer to a Mem using the
68196 ** name sqlite_value
68197 */
68198 /* #include "sqliteInt.h" */
68199 /* #include "vdbeInt.h" */
68200 
68201 #ifdef SQLITE_DEBUG
68202 /*
68203 ** Check invariants on a Mem object.
68204 **
68205 ** This routine is intended for use inside of assert() statements, like
68206 ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
68207 */
68208 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
68209  /* If MEM_Dyn is set then Mem.xDel!=0.
68210  ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
68211  */
68212  assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
68213 
68214  /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
68215  ** ensure that if Mem.szMalloc>0 then it is safe to do
68216  ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
68217  ** That saves a few cycles in inner loops. */
68218  assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
68219 
68220  /* Cannot be both MEM_Int and MEM_Real at the same time */
68221  assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
68222 
68223  /* The szMalloc field holds the correct memory allocation size */
68224  assert( p->szMalloc==0
68225  || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
68226 
68227  /* If p holds a string or blob, the Mem.z must point to exactly
68228  ** one of the following:
68229  **
68230  ** (1) Memory in Mem.zMalloc and managed by the Mem object
68231  ** (2) Memory to be freed using Mem.xDel
68232  ** (3) An ephemeral string or blob
68233  ** (4) A static string or blob
68234  */
68235  if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
68236  assert(
68237  ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
68238  ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
68239  ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
68240  ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
68241  );
68242  }
68243  return 1;
68244 }
68245 #endif
68246 
68247 
68248 /*
68249 ** If pMem is an object with a valid string representation, this routine
68250 ** ensures the internal encoding for the string representation is
68251 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
68252 **
68253 ** If pMem is not a string object, or the encoding of the string
68254 ** representation is already stored using the requested encoding, then this
68255 ** routine is a no-op.
68256 **
68257 ** SQLITE_OK is returned if the conversion is successful (or not required).
68258 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
68259 ** between formats.
68260 */
68261 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
68262 #ifndef SQLITE_OMIT_UTF16
68263  int rc;
68264 #endif
68265  assert( (pMem->flags&MEM_RowSet)==0 );
68266  assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
68267  || desiredEnc==SQLITE_UTF16BE );
68268  if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
68269  return SQLITE_OK;
68270  }
68271  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68272 #ifdef SQLITE_OMIT_UTF16
68273  return SQLITE_ERROR;
68274 #else
68275 
68276  /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
68277  ** then the encoding of the value may not have changed.
68278  */
68279  rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
68280  assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
68281  assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
68282  assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
68283  return rc;
68284 #endif
68285 }
68286 
68287 /*
68288 ** Make sure pMem->z points to a writable allocation of at least
68289 ** min(n,32) bytes.
68290 **
68291 ** If the bPreserve argument is true, then copy of the content of
68292 ** pMem->z into the new allocation. pMem must be either a string or
68293 ** blob if bPreserve is true. If bPreserve is false, any prior content
68294 ** in pMem->z is discarded.
68295 */
68296 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
68297  assert( sqlite3VdbeCheckMemInvariants(pMem) );
68298  assert( (pMem->flags&MEM_RowSet)==0 );
68299  testcase( pMem->db==0 );
68300 
68301  /* If the bPreserve flag is set to true, then the memory cell must already
68302  ** contain a valid string or blob value. */
68303  assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
68304  testcase( bPreserve && pMem->z==0 );
68305 
68306  assert( pMem->szMalloc==0
68307  || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
68308  if( pMem->szMalloc<n ){
68309  if( n<32 ) n = 32;
68310  if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
68311  pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
68312  bPreserve = 0;
68313  }else{
68314  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68315  pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
68316  }
68317  if( pMem->zMalloc==0 ){
68318  sqlite3VdbeMemSetNull(pMem);
68319  pMem->z = 0;
68320  pMem->szMalloc = 0;
68321  return SQLITE_NOMEM_BKPT;
68322  }else{
68323  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
68324  }
68325  }
68326 
68327  if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
68328  memcpy(pMem->zMalloc, pMem->z, pMem->n);
68329  }
68330  if( (pMem->flags&MEM_Dyn)!=0 ){
68331  assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
68332  pMem->xDel((void *)(pMem->z));
68333  }
68334 
68335  pMem->z = pMem->zMalloc;
68336  pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
68337  return SQLITE_OK;
68338 }
68339 
68340 /*
68341 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
68342 ** If pMem->zMalloc already meets or exceeds the requested size, this
68343 ** routine is a no-op.
68344 **
68345 ** Any prior string or blob content in the pMem object may be discarded.
68346 ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
68347 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
68348 ** values are preserved.
68349 **
68350 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
68351 ** if unable to complete the resizing.
68352 */
68354  assert( szNew>0 );
68355  assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
68356  if( pMem->szMalloc<szNew ){
68357  return sqlite3VdbeMemGrow(pMem, szNew, 0);
68358  }
68359  assert( (pMem->flags & MEM_Dyn)==0 );
68360  pMem->z = pMem->zMalloc;
68361  pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
68362  return SQLITE_OK;
68363 }
68364 
68365 /*
68366 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
68367 ** MEM.zMalloc, where it can be safely written.
68368 **
68369 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
68370 */
68372  int f;
68373  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68374  assert( (pMem->flags&MEM_RowSet)==0 );
68375  ExpandBlob(pMem);
68376  f = pMem->flags;
68377  if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
68378  if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
68379  return SQLITE_NOMEM_BKPT;
68380  }
68381  pMem->z[pMem->n] = 0;
68382  pMem->z[pMem->n+1] = 0;
68383  pMem->flags |= MEM_Term;
68384  }
68385  pMem->flags &= ~MEM_Ephem;
68386 #ifdef SQLITE_DEBUG
68387  pMem->pScopyFrom = 0;
68388 #endif
68389 
68390  return SQLITE_OK;
68391 }
68392 
68393 /*
68394 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
68395 ** blob stored in dynamically allocated space.
68396 */
68397 #ifndef SQLITE_OMIT_INCRBLOB
68399  if( pMem->flags & MEM_Zero ){
68400  int nByte;
68401  assert( pMem->flags&MEM_Blob );
68402  assert( (pMem->flags&MEM_RowSet)==0 );
68403  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68404 
68405  /* Set nByte to the number of bytes required to store the expanded blob. */
68406  nByte = pMem->n + pMem->u.nZero;
68407  if( nByte<=0 ){
68408  nByte = 1;
68409  }
68410  if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
68411  return SQLITE_NOMEM_BKPT;
68412  }
68413 
68414  memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
68415  pMem->n += pMem->u.nZero;
68416  pMem->flags &= ~(MEM_Zero|MEM_Term);
68417  }
68418  return SQLITE_OK;
68419 }
68420 #endif
68421 
68422 /*
68423 ** It is already known that pMem contains an unterminated string.
68424 ** Add the zero terminator.
68425 */
68427  if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
68428  return SQLITE_NOMEM_BKPT;
68429  }
68430  pMem->z[pMem->n] = 0;
68431  pMem->z[pMem->n+1] = 0;
68432  pMem->flags |= MEM_Term;
68433  return SQLITE_OK;
68434 }
68435 
68436 /*
68437 ** Make sure the given Mem is \u0000 terminated.
68438 */
68440  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68441  testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
68442  testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
68443  if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
68444  return SQLITE_OK; /* Nothing to do */
68445  }else{
68446  return vdbeMemAddTerminator(pMem);
68447  }
68448 }
68449 
68450 /*
68451 ** Add MEM_Str to the set of representations for the given Mem. Numbers
68452 ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
68453 ** is a no-op.
68454 **
68455 ** Existing representations MEM_Int and MEM_Real are invalidated if
68456 ** bForce is true but are retained if bForce is false.
68457 **
68458 ** A MEM_Null value will never be passed to this function. This function is
68459 ** used for converting values to text for returning to the user (i.e. via
68460 ** sqlite3_value_text()), or for ensuring that values to be used as btree
68461 ** keys are strings. In the former case a NULL pointer is returned the
68462 ** user and the latter is an internal programming error.
68463 */
68464 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
68465  int fg = pMem->flags;
68466  const int nByte = 32;
68467 
68468  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68469  assert( !(fg&MEM_Zero) );
68470  assert( !(fg&(MEM_Str|MEM_Blob)) );
68471  assert( fg&(MEM_Int|MEM_Real) );
68472  assert( (pMem->flags&MEM_RowSet)==0 );
68473  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68474 
68475 
68476  if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
68477  return SQLITE_NOMEM_BKPT;
68478  }
68479 
68480  /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
68481  ** string representation of the value. Then, if the required encoding
68482  ** is UTF-16le or UTF-16be do a translation.
68483  **
68484  ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
68485  */
68486  if( fg & MEM_Int ){
68487  sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
68488  }else{
68489  assert( fg & MEM_Real );
68490  sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
68491  }
68492  pMem->n = sqlite3Strlen30(pMem->z);
68493  pMem->enc = SQLITE_UTF8;
68494  pMem->flags |= MEM_Str|MEM_Term;
68495  if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
68496  sqlite3VdbeChangeEncoding(pMem, enc);
68497  return SQLITE_OK;
68498 }
68499 
68500 /*
68501 ** Memory cell pMem contains the context of an aggregate function.
68502 ** This routine calls the finalize method for that function. The
68503 ** result of the aggregate is stored back into pMem.
68504 **
68505 ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
68506 ** otherwise.
68507 */
68509  int rc = SQLITE_OK;
68510  if( ALWAYS(pFunc && pFunc->xFinalize) ){
68512  Mem t;
68513  assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
68514  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68515  memset(&ctx, 0, sizeof(ctx));
68516  memset(&t, 0, sizeof(t));
68517  t.flags = MEM_Null;
68518  t.db = pMem->db;
68519  ctx.pOut = &t;
68520  ctx.pMem = pMem;
68521  ctx.pFunc = pFunc;
68522  pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
68523  assert( (pMem->flags & MEM_Dyn)==0 );
68524  if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
68525  memcpy(pMem, &t, sizeof(t));
68526  rc = ctx.isError;
68527  }
68528  return rc;
68529 }
68530 
68531 /*
68532 ** If the memory cell contains a value that must be freed by
68533 ** invoking the external callback in Mem.xDel, then this routine
68534 ** will free that value. It also sets Mem.flags to MEM_Null.
68535 **
68536 ** This is a helper routine for sqlite3VdbeMemSetNull() and
68537 ** for sqlite3VdbeMemRelease(). Use those other routines as the
68538 ** entry point for releasing Mem resources.
68539 */
68541  assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
68542  assert( VdbeMemDynamic(p) );
68543  if( p->flags&MEM_Agg ){
68544  sqlite3VdbeMemFinalize(p, p->u.pDef);
68545  assert( (p->flags & MEM_Agg)==0 );
68546  testcase( p->flags & MEM_Dyn );
68547  }
68548  if( p->flags&MEM_Dyn ){
68549  assert( (p->flags&MEM_RowSet)==0 );
68550  assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
68551  p->xDel((void *)p->z);
68552  }else if( p->flags&MEM_RowSet ){
68554  }else if( p->flags&MEM_Frame ){
68555  VdbeFrame *pFrame = p->u.pFrame;
68556  pFrame->pParent = pFrame->v->pDelFrame;
68557  pFrame->v->pDelFrame = pFrame;
68558  }
68559  p->flags = MEM_Null;
68560 }
68561 
68562 /*
68563 ** Release memory held by the Mem p, both external memory cleared
68564 ** by p->xDel and memory in p->zMalloc.
68565 **
68566 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
68567 ** the unusual case where there really is memory in p that needs
68568 ** to be freed.
68569 */
68571  if( VdbeMemDynamic(p) ){
68573  }
68574  if( p->szMalloc ){
68575  sqlite3DbFree(p->db, p->zMalloc);
68576  p->szMalloc = 0;
68577  }
68578  p->z = 0;
68579 }
68580 
68581 /*
68582 ** Release any memory resources held by the Mem. Both the memory that is
68583 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
68584 **
68585 ** Use this routine prior to clean up prior to abandoning a Mem, or to
68586 ** reset a Mem back to its minimum memory utilization.
68587 **
68588 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
68589 ** prior to inserting new content into the Mem.
68590 */
68592  assert( sqlite3VdbeCheckMemInvariants(p) );
68593  if( VdbeMemDynamic(p) || p->szMalloc ){
68594  vdbeMemClear(p);
68595  }
68596 }
68597 
68598 /*
68599 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
68600 ** If the double is out of range of a 64-bit signed integer then
68601 ** return the closest available 64-bit signed integer.
68602 */
68603 static i64 doubleToInt64(double r){
68604 #ifdef SQLITE_OMIT_FLOATING_POINT
68605  /* When floating-point is omitted, double and int64 are the same thing */
68606  return r;
68607 #else
68608  /*
68609  ** Many compilers we encounter do not define constants for the
68610  ** minimum and maximum 64-bit integers, or they define them
68611  ** inconsistently. And many do not understand the "LL" notation.
68612  ** So we define our own static constants here using nothing
68613  ** larger than a 32-bit integer constant.
68614  */
68615  static const i64 maxInt = LARGEST_INT64;
68616  static const i64 minInt = SMALLEST_INT64;
68617 
68618  if( r<=(double)minInt ){
68619  return minInt;
68620  }else if( r>=(double)maxInt ){
68621  return maxInt;
68622  }else{
68623  return (i64)r;
68624  }
68625 #endif
68626 }
68627 
68628 /*
68629 ** Return some kind of integer value which is the best we can do
68630 ** at representing the value that *pMem describes as an integer.
68631 ** If pMem is an integer, then the value is exact. If pMem is
68632 ** a floating-point then the value returned is the integer part.
68633 ** If pMem is a string or blob, then we make an attempt to convert
68634 ** it into an integer and return that. If pMem represents an
68635 ** an SQL-NULL value, return 0.
68636 **
68637 ** If pMem represents a string value, its encoding might be changed.
68638 */
68640  int flags;
68641  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68642  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68643  flags = pMem->flags;
68644  if( flags & MEM_Int ){
68645  return pMem->u.i;
68646  }else if( flags & MEM_Real ){
68647  return doubleToInt64(pMem->u.r);
68648  }else if( flags & (MEM_Str|MEM_Blob) ){
68649  i64 value = 0;
68650  assert( pMem->z || pMem->n==0 );
68651  sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
68652  return value;
68653  }else{
68654  return 0;
68655  }
68656 }
68657 
68658 /*
68659 ** Return the best representation of pMem that we can get into a
68660 ** double. If pMem is already a double or an integer, return its
68661 ** value. If it is a string or blob, try to convert it to a double.
68662 ** If it is a NULL, return 0.0.
68663 */
68665  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68666  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68667  if( pMem->flags & MEM_Real ){
68668  return pMem->u.r;
68669  }else if( pMem->flags & MEM_Int ){
68670  return (double)pMem->u.i;
68671  }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
68672  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
68673  double val = (double)0;
68674  sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
68675  return val;
68676  }else{
68677  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
68678  return (double)0;
68679  }
68680 }
68681 
68682 /*
68683 ** The MEM structure is already a MEM_Real. Try to also make it a
68684 ** MEM_Int if we can.
68685 */
68687  i64 ix;
68688  assert( pMem->flags & MEM_Real );
68689  assert( (pMem->flags & MEM_RowSet)==0 );
68690  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68691  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68692 
68693  ix = doubleToInt64(pMem->u.r);
68694 
68695  /* Only mark the value as an integer if
68696  **
68697  ** (1) the round-trip conversion real->int->real is a no-op, and
68698  ** (2) The integer is neither the largest nor the smallest
68699  ** possible integer (ticket #3922)
68700  **
68701  ** The second and third terms in the following conditional enforces
68702  ** the second condition under the assumption that addition overflow causes
68703  ** values to wrap around.
68704  */
68705  if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
68706  pMem->u.i = ix;
68707  MemSetTypeFlag(pMem, MEM_Int);
68708  }
68709 }
68710 
68711 /*
68712 ** Convert pMem to type integer. Invalidate any prior representations.
68713 */
68715  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68716  assert( (pMem->flags & MEM_RowSet)==0 );
68717  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68718 
68719  pMem->u.i = sqlite3VdbeIntValue(pMem);
68720  MemSetTypeFlag(pMem, MEM_Int);
68721  return SQLITE_OK;
68722 }
68723 
68724 /*
68725 ** Convert pMem so that it is of type MEM_Real.
68726 ** Invalidate any prior representations.
68727 */
68729  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68730  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
68731 
68732  pMem->u.r = sqlite3VdbeRealValue(pMem);
68733  MemSetTypeFlag(pMem, MEM_Real);
68734  return SQLITE_OK;
68735 }
68736 
68737 /*
68738 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
68739 ** Invalidate any prior representations.
68740 **
68741 ** Every effort is made to force the conversion, even if the input
68742 ** is a string that does not look completely like a number. Convert
68743 ** as much of the string as we can and ignore the rest.
68744 */
68746  if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
68747  assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
68748  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
68749  if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
68750  MemSetTypeFlag(pMem, MEM_Int);
68751  }else{
68752  pMem->u.r = sqlite3VdbeRealValue(pMem);
68753  MemSetTypeFlag(pMem, MEM_Real);
68755  }
68756  }
68757  assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
68758  pMem->flags &= ~(MEM_Str|MEM_Blob);
68759  return SQLITE_OK;
68760 }
68761 
68762 /*
68763 ** Cast the datatype of the value in pMem according to the affinity
68764 ** "aff". Casting is different from applying affinity in that a cast
68765 ** is forced. In other words, the value is converted into the desired
68766 ** affinity even if that results in loss of data. This routine is
68767 ** used (for example) to implement the SQL "cast()" operator.
68768 */
68770  if( pMem->flags & MEM_Null ) return;
68771  switch( aff ){
68772  case SQLITE_AFF_BLOB: { /* Really a cast to BLOB */
68773  if( (pMem->flags & MEM_Blob)==0 ){
68774  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
68775  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
68776  MemSetTypeFlag(pMem, MEM_Blob);
68777  }else{
68778  pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
68779  }
68780  break;
68781  }
68782  case SQLITE_AFF_NUMERIC: {
68783  sqlite3VdbeMemNumerify(pMem);
68784  break;
68785  }
68786  case SQLITE_AFF_INTEGER: {
68788  break;
68789  }
68790  case SQLITE_AFF_REAL: {
68791  sqlite3VdbeMemRealify(pMem);
68792  break;
68793  }
68794  default: {
68795  assert( aff==SQLITE_AFF_TEXT );
68796  assert( MEM_Str==(MEM_Blob>>3) );
68797  pMem->flags |= (pMem->flags&MEM_Blob)>>3;
68798  sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
68799  assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
68800  pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
68801  break;
68802  }
68803  }
68804 }
68805 
68806 /*
68807 ** Initialize bulk memory to be a consistent Mem object.
68808 **
68809 ** The minimum amount of initialization feasible is performed.
68810 */
68811 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
68812  assert( (flags & ~MEM_TypeMask)==0 );
68813  pMem->flags = flags;
68814  pMem->db = db;
68815  pMem->szMalloc = 0;
68816 }
68817 
68818 
68819 /*
68820 ** Delete any previous value and set the value stored in *pMem to NULL.
68821 **
68822 ** This routine calls the Mem.xDel destructor to dispose of values that
68823 ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
68824 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
68825 ** routine to invoke the destructor and deallocates Mem.zMalloc.
68826 **
68827 ** Use this routine to reset the Mem prior to insert a new value.
68828 **
68829 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
68830 */
68832  if( VdbeMemDynamic(pMem) ){
68834  }else{
68835  pMem->flags = MEM_Null;
68836  }
68837 }
68839  sqlite3VdbeMemSetNull((Mem*)p);
68840 }
68841 
68842 /*
68843 ** Delete any previous value and set the value to be a BLOB of length
68844 ** n containing all zeros.
68845 */
68847  sqlite3VdbeMemRelease(pMem);
68848  pMem->flags = MEM_Blob|MEM_Zero;
68849  pMem->n = 0;
68850  if( n<0 ) n = 0;
68851  pMem->u.nZero = n;
68852  pMem->enc = SQLITE_UTF8;
68853  pMem->z = 0;
68854 }
68855 
68856 /*
68857 ** The pMem is known to contain content that needs to be destroyed prior
68858 ** to a value change. So invoke the destructor, then set the value to
68859 ** a 64-bit integer.
68860 */
68862  sqlite3VdbeMemSetNull(pMem);
68863  pMem->u.i = val;
68864  pMem->flags = MEM_Int;
68865 }
68866 
68867 /*
68868 ** Delete any previous value and set the value stored in *pMem to val,
68869 ** manifest type INTEGER.
68870 */
68872  if( VdbeMemDynamic(pMem) ){
68873  vdbeReleaseAndSetInt64(pMem, val);
68874  }else{
68875  pMem->u.i = val;
68876  pMem->flags = MEM_Int;
68877  }
68878 }
68879 
68880 #ifndef SQLITE_OMIT_FLOATING_POINT
68881 /*
68882 ** Delete any previous value and set the value stored in *pMem to val,
68883 ** manifest type REAL.
68884 */
68886  sqlite3VdbeMemSetNull(pMem);
68887  if( !sqlite3IsNaN(val) ){
68888  pMem->u.r = val;
68889  pMem->flags = MEM_Real;
68890  }
68891 }
68892 #endif
68893 
68894 /*
68895 ** Delete any previous value and set the value of pMem to be an
68896 ** empty boolean index.
68897 */
68899  sqlite3 *db = pMem->db;
68900  assert( db!=0 );
68901  assert( (pMem->flags & MEM_RowSet)==0 );
68902  sqlite3VdbeMemRelease(pMem);
68903  pMem->zMalloc = sqlite3DbMallocRawNN(db, 64);
68904  if( db->mallocFailed ){
68905  pMem->flags = MEM_Null;
68906  pMem->szMalloc = 0;
68907  }else{
68908  assert( pMem->zMalloc );
68909  pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
68910  pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
68911  assert( pMem->u.pRowSet!=0 );
68912  pMem->flags = MEM_RowSet;
68913  }
68914 }
68915 
68916 /*
68917 ** Return true if the Mem object contains a TEXT or BLOB that is
68918 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
68919 */
68921  assert( p->db!=0 );
68922  if( p->flags & (MEM_Str|MEM_Blob) ){
68923  int n = p->n;
68924  if( p->flags & MEM_Zero ){
68925  n += p->u.nZero;
68926  }
68927  return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
68928  }
68929  return 0;
68930 }
68931 
68932 #ifdef SQLITE_DEBUG
68933 /*
68934 ** This routine prepares a memory cell for modification by breaking
68935 ** its link to a shallow copy and by marking any current shallow
68936 ** copies of this cell as invalid.
68937 **
68938 ** This is used for testing and debugging only - to make sure shallow
68939 ** copies are not misused.
68940 */
68941 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
68942  int i;
68943  Mem *pX;
68944  for(i=0, pX=pVdbe->aMem; i<pVdbe->nMem; i++, pX++){
68945  if( pX->pScopyFrom==pMem ){
68946  pX->flags |= MEM_Undefined;
68947  pX->pScopyFrom = 0;
68948  }
68949  }
68950  pMem->pScopyFrom = 0;
68951 }
68952 #endif /* SQLITE_DEBUG */
68953 
68954 
68955 /*
68956 ** Make an shallow copy of pFrom into pTo. Prior contents of
68957 ** pTo are freed. The pFrom->z field is not duplicated. If
68958 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
68959 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
68960 */
68961 static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType){
68963  assert( !VdbeMemDynamic(pTo) );
68964  sqlite3VdbeMemShallowCopy(pTo, pFrom, eType);
68965 }
68966 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
68967  assert( (pFrom->flags & MEM_RowSet)==0 );
68968  assert( pTo->db==pFrom->db );
68969  if( VdbeMemDynamic(pTo) ){ vdbeClrCopy(pTo,pFrom,srcType); return; }
68970  memcpy(pTo, pFrom, MEMCELLSIZE);
68971  if( (pFrom->flags&MEM_Static)==0 ){
68972  pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
68973  assert( srcType==MEM_Ephem || srcType==MEM_Static );
68974  pTo->flags |= srcType;
68975  }
68976 }
68977 
68978 /*
68979 ** Make a full copy of pFrom into pTo. Prior contents of pTo are
68980 ** freed before the copy is made.
68981 */
68982 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
68983  int rc = SQLITE_OK;
68984 
68985  assert( (pFrom->flags & MEM_RowSet)==0 );
68987  memcpy(pTo, pFrom, MEMCELLSIZE);
68988  pTo->flags &= ~MEM_Dyn;
68989  if( pTo->flags&(MEM_Str|MEM_Blob) ){
68990  if( 0==(pFrom->flags&MEM_Static) ){
68991  pTo->flags |= MEM_Ephem;
68992  rc = sqlite3VdbeMemMakeWriteable(pTo);
68993  }
68994  }
68995 
68996  return rc;
68997 }
68998 
68999 /*
69000 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
69001 ** freed. If pFrom contains ephemeral data, a copy is made.
69002 **
69003 ** pFrom contains an SQL NULL when this routine returns.
69004 */
69006  assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
69007  assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
69008  assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
69009 
69010  sqlite3VdbeMemRelease(pTo);
69011  memcpy(pTo, pFrom, sizeof(Mem));
69012  pFrom->flags = MEM_Null;
69013  pFrom->szMalloc = 0;
69014 }
69015 
69016 /*
69017 ** Change the value of a Mem to be a string or a BLOB.
69018 **
69019 ** The memory management strategy depends on the value of the xDel
69020 ** parameter. If the value passed is SQLITE_TRANSIENT, then the
69021 ** string is copied into a (possibly existing) buffer managed by the
69022 ** Mem structure. Otherwise, any existing buffer is freed and the
69023 ** pointer copied.
69024 **
69025 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
69026 ** size limit) then no memory allocation occurs. If the string can be
69027 ** stored without allocating memory, then it is. If a memory allocation
69028 ** is required to store the string, then value of pMem is unchanged. In
69029 ** either case, SQLITE_TOOBIG is returned.
69030 */
69032  Mem *pMem, /* Memory cell to set to string value */
69033  const char *z, /* String pointer */
69034  int n, /* Bytes in string, or negative */
69035  u8 enc, /* Encoding of z. 0 for BLOBs */
69036  void (*xDel)(void*) /* Destructor function */
69037 ){
69038  int nByte = n; /* New value for pMem->n */
69039  int iLimit; /* Maximum allowed string or blob size */
69040  u16 flags = 0; /* New value for pMem->flags */
69041 
69042  assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
69043  assert( (pMem->flags & MEM_RowSet)==0 );
69044 
69045  /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
69046  if( !z ){
69047  sqlite3VdbeMemSetNull(pMem);
69048  return SQLITE_OK;
69049  }
69050 
69051  if( pMem->db ){
69052  iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
69053  }else{
69054  iLimit = SQLITE_MAX_LENGTH;
69055  }
69056  flags = (enc==0?MEM_Blob:MEM_Str);
69057  if( nByte<0 ){
69058  assert( enc!=0 );
69059  if( enc==SQLITE_UTF8 ){
69060  nByte = sqlite3Strlen30(z);
69061  if( nByte>iLimit ) nByte = iLimit+1;
69062  }else{
69063  for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
69064  }
69065  flags |= MEM_Term;
69066  }
69067 
69068  /* The following block sets the new values of Mem.z and Mem.xDel. It
69069  ** also sets a flag in local variable "flags" to indicate the memory
69070  ** management (one of MEM_Dyn or MEM_Static).
69071  */
69072  if( xDel==SQLITE_TRANSIENT ){
69073  int nAlloc = nByte;
69074  if( flags&MEM_Term ){
69075  nAlloc += (enc==SQLITE_UTF8?1:2);
69076  }
69077  if( nByte>iLimit ){
69078  return SQLITE_TOOBIG;
69079  }
69080  testcase( nAlloc==0 );
69081  testcase( nAlloc==31 );
69082  testcase( nAlloc==32 );
69083  if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
69084  return SQLITE_NOMEM_BKPT;
69085  }
69086  memcpy(pMem->z, z, nAlloc);
69087  }else if( xDel==SQLITE_DYNAMIC ){
69088  sqlite3VdbeMemRelease(pMem);
69089  pMem->zMalloc = pMem->z = (char *)z;
69090  pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
69091  }else{
69092  sqlite3VdbeMemRelease(pMem);
69093  pMem->z = (char *)z;
69094  pMem->xDel = xDel;
69095  flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
69096  }
69097 
69098  pMem->n = nByte;
69099  pMem->flags = flags;
69100  pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
69101 
69102 #ifndef SQLITE_OMIT_UTF16
69103  if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
69104  return SQLITE_NOMEM_BKPT;
69105  }
69106 #endif
69107 
69108  if( nByte>iLimit ){
69109  return SQLITE_TOOBIG;
69110  }
69111 
69112  return SQLITE_OK;
69113 }
69114 
69115 /*
69116 ** Move data out of a btree key or data field and into a Mem structure.
69117 ** The data or key is taken from the entry that pCur is currently pointing
69118 ** to. offset and amt determine what portion of the data or key to retrieve.
69119 ** key is true to get the key or false to get data. The result is written
69120 ** into the pMem element.
69121 **
69122 ** The pMem object must have been initialized. This routine will use
69123 ** pMem->zMalloc to hold the content from the btree, if possible. New
69124 ** pMem->zMalloc space will be allocated if necessary. The calling routine
69125 ** is responsible for making sure that the pMem object is eventually
69126 ** destroyed.
69127 **
69128 ** If this routine fails for any reason (malloc returns NULL or unable
69129 ** to read from the disk) then the pMem is left in an inconsistent state.
69130 */
69132  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69133  u32 offset, /* Offset from the start of data to return bytes from. */
69134  u32 amt, /* Number of bytes to return. */
69135  int key, /* If true, retrieve from the btree key, not data. */
69136  Mem *pMem /* OUT: Return data in this Mem structure. */
69137 ){
69138  int rc;
69139  pMem->flags = MEM_Null;
69140  if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
69141  if( key ){
69142  rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
69143  }else{
69144  rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
69145  }
69146  if( rc==SQLITE_OK ){
69147  pMem->z[amt] = 0;
69148  pMem->z[amt+1] = 0;
69149  pMem->flags = MEM_Blob|MEM_Term;
69150  pMem->n = (int)amt;
69151  }else{
69152  sqlite3VdbeMemRelease(pMem);
69153  }
69154  }
69155  return rc;
69156 }
69158  BtCursor *pCur, /* Cursor pointing at record to retrieve. */
69159  u32 offset, /* Offset from the start of data to return bytes from. */
69160  u32 amt, /* Number of bytes to return. */
69161  int key, /* If true, retrieve from the btree key, not data. */
69162  Mem *pMem /* OUT: Return data in this Mem structure. */
69163 ){
69164  char *zData; /* Data from the btree layer */
69165  u32 available = 0; /* Number of bytes available on the local btree page */
69166  int rc = SQLITE_OK; /* Return code */
69167 
69168  assert( sqlite3BtreeCursorIsValid(pCur) );
69169  assert( !VdbeMemDynamic(pMem) );
69170 
69171  /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
69172  ** that both the BtShared and database handle mutexes are held. */
69173  assert( (pMem->flags & MEM_RowSet)==0 );
69174  if( key ){
69175  zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
69176  }else{
69177  zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
69178  }
69179  assert( zData!=0 );
69180 
69181  if( offset+amt<=available ){
69182  pMem->z = &zData[offset];
69183  pMem->flags = MEM_Blob|MEM_Ephem;
69184  pMem->n = (int)amt;
69185  }else{
69186  rc = vdbeMemFromBtreeResize(pCur, offset, amt, key, pMem);
69187  }
69188 
69189  return rc;
69190 }
69191 
69192 /*
69193 ** The pVal argument is known to be a value other than NULL.
69194 ** Convert it into a string with encoding enc and return a pointer
69195 ** to a zero-terminated version of that string.
69196 */
69197 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
69198  assert( pVal!=0 );
69199  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69200  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69201  assert( (pVal->flags & MEM_RowSet)==0 );
69202  assert( (pVal->flags & (MEM_Null))==0 );
69203  if( pVal->flags & (MEM_Blob|MEM_Str) ){
69204  pVal->flags |= MEM_Str;
69205  if( pVal->flags & MEM_Zero ){
69207  }
69208  if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
69210  }
69211  if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
69212  assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
69214  return 0;
69215  }
69216  }
69217  sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
69218  }else{
69219  sqlite3VdbeMemStringify(pVal, enc, 0);
69220  assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
69221  }
69222  assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
69223  || pVal->db->mallocFailed );
69224  if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
69225  return pVal->z;
69226  }else{
69227  return 0;
69228  }
69229 }
69230 
69231 /* This function is only available internally, it is not part of the
69232 ** external API. It works in a similar way to sqlite3_value_text(),
69233 ** except the data returned is in the encoding specified by the second
69234 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
69235 ** SQLITE_UTF8.
69236 **
69237 ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
69238 ** If that is the case, then the result must be aligned on an even byte
69239 ** boundary.
69240 */
69241 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
69242  if( !pVal ) return 0;
69243  assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
69244  assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
69245  assert( (pVal->flags & MEM_RowSet)==0 );
69246  if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
69247  return pVal->z;
69248  }
69249  if( pVal->flags&MEM_Null ){
69250  return 0;
69251  }
69252  return valueToText(pVal, enc);
69253 }
69254 
69255 /*
69256 ** Create a new sqlite3_value object.
69257 */
69259  Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
69260  if( p ){
69261  p->flags = MEM_Null;
69262  p->db = db;
69263  }
69264  return p;
69265 }
69266 
69267 /*
69268 ** Context object passed by sqlite3Stat4ProbeSetValue() through to
69269 ** valueNew(). See comments above valueNew() for details.
69270 */
69275  int iVal;
69276 };
69277 
69278 /*
69279 ** Allocate and return a pointer to a new sqlite3_value object. If
69280 ** the second argument to this function is NULL, the object is allocated
69281 ** by calling sqlite3ValueNew().
69282 **
69283 ** Otherwise, if the second argument is non-zero, then this function is
69284 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
69285 ** already been allocated, allocate the UnpackedRecord structure that
69286 ** that function will return to its caller here. Then return a pointer to
69287 ** an sqlite3_value within the UnpackedRecord.a[] array.
69288 */
69290 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69291  if( p ){
69292  UnpackedRecord *pRec = p->ppRec[0];
69293 
69294  if( pRec==0 ){
69295  Index *pIdx = p->pIdx; /* Index being probed */
69296  int nByte; /* Bytes of space to allocate */
69297  int i; /* Counter variable */
69298  int nCol = pIdx->nColumn; /* Number of index columns including rowid */
69299 
69300  nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
69301  pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
69302  if( pRec ){
69303  pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
69304  if( pRec->pKeyInfo ){
69305  assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
69306  assert( pRec->pKeyInfo->enc==ENC(db) );
69307  pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
69308  for(i=0; i<nCol; i++){
69309  pRec->aMem[i].flags = MEM_Null;
69310  pRec->aMem[i].db = db;
69311  }
69312  }else{
69313  sqlite3DbFree(db, pRec);
69314  pRec = 0;
69315  }
69316  }
69317  if( pRec==0 ) return 0;
69318  p->ppRec[0] = pRec;
69319  }
69320 
69321  pRec->nField = p->iVal+1;
69322  return &pRec->aMem[p->iVal];
69323  }
69324 #else
69325  UNUSED_PARAMETER(p);
69326 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69327  return sqlite3ValueNew(db);
69328 }
69329 
69330 /*
69331 ** The expression object indicated by the second argument is guaranteed
69332 ** to be a scalar SQL function. If
69333 **
69334 ** * all function arguments are SQL literals,
69335 ** * one of the SQLITE_FUNC_CONSTANT or _SLOCHNG function flags is set, and
69336 ** * the SQLITE_FUNC_NEEDCOLL function flag is not set,
69337 **
69338 ** then this routine attempts to invoke the SQL function. Assuming no
69339 ** error occurs, output parameter (*ppVal) is set to point to a value
69340 ** object containing the result before returning SQLITE_OK.
69341 **
69342 ** Affinity aff is applied to the result of the function before returning.
69343 ** If the result is a text value, the sqlite3_value object uses encoding
69344 ** enc.
69345 **
69346 ** If the conditions above are not met, this function returns SQLITE_OK
69347 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
69348 ** NULL and an SQLite error code returned.
69349 */
69350 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69351 static int valueFromFunction(
69352  sqlite3 *db, /* The database connection */
69353  Expr *p, /* The expression to evaluate */
69354  u8 enc, /* Encoding to use */
69355  u8 aff, /* Affinity to use */
69356  sqlite3_value **ppVal, /* Write the new value here */
69357  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
69358 ){
69359  sqlite3_context ctx; /* Context object for function invocation */
69360  sqlite3_value **apVal = 0; /* Function arguments */
69361  int nVal = 0; /* Size of apVal[] array */
69362  FuncDef *pFunc = 0; /* Function definition */
69363  sqlite3_value *pVal = 0; /* New value */
69364  int rc = SQLITE_OK; /* Return code */
69365  ExprList *pList = 0; /* Function arguments */
69366  int i; /* Iterator variable */
69367 
69368  assert( pCtx!=0 );
69369  assert( (p->flags & EP_TokenOnly)==0 );
69370  pList = p->x.pList;
69371  if( pList ) nVal = pList->nExpr;
69372  pFunc = sqlite3FindFunction(db, p->u.zToken, nVal, enc, 0);
69373  assert( pFunc );
69375  || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
69376  ){
69377  return SQLITE_OK;
69378  }
69379 
69380  if( pList ){
69381  apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
69382  if( apVal==0 ){
69383  rc = SQLITE_NOMEM_BKPT;
69384  goto value_from_function_out;
69385  }
69386  for(i=0; i<nVal; i++){
69387  rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
69388  if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
69389  }
69390  }
69391 
69392  pVal = valueNew(db, pCtx);
69393  if( pVal==0 ){
69394  rc = SQLITE_NOMEM_BKPT;
69395  goto value_from_function_out;
69396  }
69397 
69398  assert( pCtx->pParse->rc==SQLITE_OK );
69399  memset(&ctx, 0, sizeof(ctx));
69400  ctx.pOut = pVal;
69401  ctx.pFunc = pFunc;
69402  pFunc->xSFunc(&ctx, nVal, apVal);
69403  if( ctx.isError ){
69404  rc = ctx.isError;
69405  sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
69406  }else{
69408  assert( rc==SQLITE_OK );
69409  rc = sqlite3VdbeChangeEncoding(pVal, enc);
69410  if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
69411  rc = SQLITE_TOOBIG;
69412  pCtx->pParse->nErr++;
69413  }
69414  }
69415  pCtx->pParse->rc = rc;
69416 
69417  value_from_function_out:
69418  if( rc!=SQLITE_OK ){
69419  pVal = 0;
69420  }
69421  if( apVal ){
69422  for(i=0; i<nVal; i++){
69423  sqlite3ValueFree(apVal[i]);
69424  }
69425  sqlite3DbFree(db, apVal);
69426  }
69427 
69428  *ppVal = pVal;
69429  return rc;
69430 }
69431 #else
69432 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
69433 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
69434 
69435 /*
69436 ** Extract a value from the supplied expression in the manner described
69437 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
69438 ** using valueNew().
69439 **
69440 ** If pCtx is NULL and an error occurs after the sqlite3_value object
69441 ** has been allocated, it is freed before returning. Or, if pCtx is not
69442 ** NULL, it is assumed that the caller will free any allocated object
69443 ** in all cases.
69444 */
69445 static int valueFromExpr(
69446  sqlite3 *db, /* The database connection */
69447  Expr *pExpr, /* The expression to evaluate */
69448  u8 enc, /* Encoding to use */
69449  u8 affinity, /* Affinity to use */
69450  sqlite3_value **ppVal, /* Write the new value here */
69451  struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
69452 ){
69453  int op;
69454  char *zVal = 0;
69455  sqlite3_value *pVal = 0;
69456  int negInt = 1;
69457  const char *zNeg = "";
69458  int rc = SQLITE_OK;
69459 
69460  if( !pExpr ){
69461  *ppVal = 0;
69462  return SQLITE_OK;
69463  }
69464  while( (op = pExpr->op)==TK_UPLUS || op==TK_SPAN ) pExpr = pExpr->pLeft;
69465  if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
69466 
69467  /* Compressed expressions only appear when parsing the DEFAULT clause
69468  ** on a table column definition, and hence only when pCtx==0. This
69469  ** check ensures that an EP_TokenOnly expression is never passed down
69470  ** into valueFromFunction(). */
69471  assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
69472 
69473  if( op==TK_CAST ){
69474  u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
69475  rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
69476  testcase( rc!=SQLITE_OK );
69477  if( *ppVal ){
69478  sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
69479  sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
69480  }
69481  return rc;
69482  }
69483 
69484  /* Handle negative integers in a single step. This is needed in the
69485  ** case when the value is -9223372036854775808.
69486  */
69487  if( op==TK_UMINUS
69488  && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
69489  pExpr = pExpr->pLeft;
69490  op = pExpr->op;
69491  negInt = -1;
69492  zNeg = "-";
69493  }
69494 
69495  if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
69496  pVal = valueNew(db, pCtx);
69497  if( pVal==0 ) goto no_mem;
69498  if( ExprHasProperty(pExpr, EP_IntValue) ){
69499  sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
69500  }else{
69501  zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
69502  if( zVal==0 ) goto no_mem;
69503  sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
69504  }
69505  if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_BLOB ){
69507  }else{
69508  sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
69509  }
69510  if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
69511  if( enc!=SQLITE_UTF8 ){
69512  rc = sqlite3VdbeChangeEncoding(pVal, enc);
69513  }
69514  }else if( op==TK_UMINUS ) {
69515  /* This branch happens for multiple negative signs. Ex: -(-5) */
69516  if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
69517  && pVal!=0
69518  ){
69519  sqlite3VdbeMemNumerify(pVal);
69520  if( pVal->flags & MEM_Real ){
69521  pVal->u.r = -pVal->u.r;
69522  }else if( pVal->u.i==SMALLEST_INT64 ){
69523  pVal->u.r = -(double)SMALLEST_INT64;
69524  MemSetTypeFlag(pVal, MEM_Real);
69525  }else{
69526  pVal->u.i = -pVal->u.i;
69527  }
69528  sqlite3ValueApplyAffinity(pVal, affinity, enc);
69529  }
69530  }else if( op==TK_NULL ){
69531  pVal = valueNew(db, pCtx);
69532  if( pVal==0 ) goto no_mem;
69533  }
69534 #ifndef SQLITE_OMIT_BLOB_LITERAL
69535  else if( op==TK_BLOB ){
69536  int nVal;
69537  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
69538  assert( pExpr->u.zToken[1]=='\'' );
69539  pVal = valueNew(db, pCtx);
69540  if( !pVal ) goto no_mem;
69541  zVal = &pExpr->u.zToken[2];
69542  nVal = sqlite3Strlen30(zVal)-1;
69543  assert( zVal[nVal]=='\'' );
69544  sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
69545  0, SQLITE_DYNAMIC);
69546  }
69547 #endif
69548 
69549 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69550  else if( op==TK_FUNCTION && pCtx!=0 ){
69551  rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
69552  }
69553 #endif
69554 
69555  *ppVal = pVal;
69556  return rc;
69557 
69558 no_mem:
69559  sqlite3OomFault(db);
69560  sqlite3DbFree(db, zVal);
69561  assert( *ppVal==0 );
69562 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69563  if( pCtx==0 ) sqlite3ValueFree(pVal);
69564 #else
69565  assert( pCtx==0 ); sqlite3ValueFree(pVal);
69566 #endif
69567  return SQLITE_NOMEM_BKPT;
69568 }
69569 
69570 /*
69571 ** Create a new sqlite3_value object, containing the value of pExpr.
69572 **
69573 ** This only works for very simple expressions that consist of one constant
69574 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
69575 ** be converted directly into a value, then the value is allocated and
69576 ** a pointer written to *ppVal. The caller is responsible for deallocating
69577 ** the value by passing it to sqlite3ValueFree() later on. If the expression
69578 ** cannot be converted to a value, then *ppVal is set to NULL.
69579 */
69581  sqlite3 *db, /* The database connection */
69582  Expr *pExpr, /* The expression to evaluate */
69583  u8 enc, /* Encoding to use */
69584  u8 affinity, /* Affinity to use */
69585  sqlite3_value **ppVal /* Write the new value here */
69586 ){
69587  return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
69588 }
69589 
69590 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69591 /*
69592 ** The implementation of the sqlite_record() function. This function accepts
69593 ** a single argument of any type. The return value is a formatted database
69594 ** record (a blob) containing the argument value.
69595 **
69596 ** This is used to convert the value stored in the 'sample' column of the
69597 ** sqlite_stat3 table to the record format SQLite uses internally.
69598 */
69599 static void recordFunc(
69600  sqlite3_context *context,
69601  int argc,
69602  sqlite3_value **argv
69603 ){
69604  const int file_format = 1;
69605  u32 iSerial; /* Serial type */
69606  int nSerial; /* Bytes of space for iSerial as varint */
69607  u32 nVal; /* Bytes of space required for argv[0] */
69608  int nRet;
69609  sqlite3 *db;
69610  u8 *aRet;
69611 
69612  UNUSED_PARAMETER( argc );
69613  iSerial = sqlite3VdbeSerialType(argv[0], file_format, &nVal);
69614  nSerial = sqlite3VarintLen(iSerial);
69615  db = sqlite3_context_db_handle(context);
69616 
69617  nRet = 1 + nSerial + nVal;
69618  aRet = sqlite3DbMallocRawNN(db, nRet);
69619  if( aRet==0 ){
69620  sqlite3_result_error_nomem(context);
69621  }else{
69622  aRet[0] = nSerial+1;
69623  putVarint32(&aRet[1], iSerial);
69624  sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
69625  sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
69626  sqlite3DbFree(db, aRet);
69627  }
69628 }
69629 
69630 /*
69631 ** Register built-in functions used to help read ANALYZE data.
69632 */
69633 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
69634  static FuncDef aAnalyzeTableFuncs[] = {
69635  FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
69636  };
69637  sqlite3InsertBuiltinFuncs(aAnalyzeTableFuncs, ArraySize(aAnalyzeTableFuncs));
69638 }
69639 
69640 /*
69641 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
69642 **
69643 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
69644 ** pAlloc if one does not exist and the new value is added to the
69645 ** UnpackedRecord object.
69646 **
69647 ** A value is extracted in the following cases:
69648 **
69649 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
69650 **
69651 ** * The expression is a bound variable, and this is a reprepare, or
69652 **
69653 ** * The expression is a literal value.
69654 **
69655 ** On success, *ppVal is made to point to the extracted value. The caller
69656 ** is responsible for ensuring that the value is eventually freed.
69657 */
69658 static int stat4ValueFromExpr(
69659  Parse *pParse, /* Parse context */
69660  Expr *pExpr, /* The expression to extract a value from */
69661  u8 affinity, /* Affinity to use */
69662  struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
69663  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
69664 ){
69665  int rc = SQLITE_OK;
69666  sqlite3_value *pVal = 0;
69667  sqlite3 *db = pParse->db;
69668 
69669  /* Skip over any TK_COLLATE nodes */
69670  pExpr = sqlite3ExprSkipCollate(pExpr);
69671 
69672  if( !pExpr ){
69673  pVal = valueNew(db, pAlloc);
69674  if( pVal ){
69675  sqlite3VdbeMemSetNull((Mem*)pVal);
69676  }
69677  }else if( pExpr->op==TK_VARIABLE
69678  || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
69679  ){
69680  Vdbe *v;
69681  int iBindVar = pExpr->iColumn;
69682  sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
69683  if( (v = pParse->pReprepare)!=0 ){
69684  pVal = valueNew(db, pAlloc);
69685  if( pVal ){
69686  rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
69687  if( rc==SQLITE_OK ){
69688  sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
69689  }
69690  pVal->db = pParse->db;
69691  }
69692  }
69693  }else{
69694  rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
69695  }
69696 
69697  assert( pVal==0 || pVal->db==db );
69698  *ppVal = pVal;
69699  return rc;
69700 }
69701 
69702 /*
69703 ** This function is used to allocate and populate UnpackedRecord
69704 ** structures intended to be compared against sample index keys stored
69705 ** in the sqlite_stat4 table.
69706 **
69707 ** A single call to this function attempts to populates field iVal (leftmost
69708 ** is 0 etc.) of the unpacked record with a value extracted from expression
69709 ** pExpr. Extraction of values is possible if:
69710 **
69711 ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
69712 **
69713 ** * The expression is a bound variable, and this is a reprepare, or
69714 **
69715 ** * The sqlite3ValueFromExpr() function is able to extract a value
69716 ** from the expression (i.e. the expression is a literal value).
69717 **
69718 ** If a value can be extracted, the affinity passed as the 5th argument
69719 ** is applied to it before it is copied into the UnpackedRecord. Output
69720 ** parameter *pbOk is set to true if a value is extracted, or false
69721 ** otherwise.
69722 **
69723 ** When this function is called, *ppRec must either point to an object
69724 ** allocated by an earlier call to this function, or must be NULL. If it
69725 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
69726 ** is allocated (and *ppRec set to point to it) before returning.
69727 **
69728 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
69729 ** error if a value cannot be extracted from pExpr. If an error does
69730 ** occur, an SQLite error code is returned.
69731 */
69732 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
69733  Parse *pParse, /* Parse context */
69734  Index *pIdx, /* Index being probed */
69735  UnpackedRecord **ppRec, /* IN/OUT: Probe record */
69736  Expr *pExpr, /* The expression to extract a value from */
69737  u8 affinity, /* Affinity to use */
69738  int iVal, /* Array element to populate */
69739  int *pbOk /* OUT: True if value was extracted */
69740 ){
69741  int rc;
69742  sqlite3_value *pVal = 0;
69743  struct ValueNewStat4Ctx alloc;
69744 
69745  alloc.pParse = pParse;
69746  alloc.pIdx = pIdx;
69747  alloc.ppRec = ppRec;
69748  alloc.iVal = iVal;
69749 
69750  rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
69751  assert( pVal==0 || pVal->db==pParse->db );
69752  *pbOk = (pVal!=0);
69753  return rc;
69754 }
69755 
69756 /*
69757 ** Attempt to extract a value from expression pExpr using the methods
69758 ** as described for sqlite3Stat4ProbeSetValue() above.
69759 **
69760 ** If successful, set *ppVal to point to a new value object and return
69761 ** SQLITE_OK. If no value can be extracted, but no other error occurs
69762 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
69763 ** does occur, return an SQLite error code. The final value of *ppVal
69764 ** is undefined in this case.
69765 */
69766 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
69767  Parse *pParse, /* Parse context */
69768  Expr *pExpr, /* The expression to extract a value from */
69769  u8 affinity, /* Affinity to use */
69770  sqlite3_value **ppVal /* OUT: New value object (or NULL) */
69771 ){
69772  return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
69773 }
69774 
69775 /*
69776 ** Extract the iCol-th column from the nRec-byte record in pRec. Write
69777 ** the column value into *ppVal. If *ppVal is initially NULL then a new
69778 ** sqlite3_value object is allocated.
69779 **
69780 ** If *ppVal is initially NULL then the caller is responsible for
69781 ** ensuring that the value written into *ppVal is eventually freed.
69782 */
69783 SQLITE_PRIVATE int sqlite3Stat4Column(
69784  sqlite3 *db, /* Database handle */
69785  const void *pRec, /* Pointer to buffer containing record */
69786  int nRec, /* Size of buffer pRec in bytes */
69787  int iCol, /* Column to extract */
69788  sqlite3_value **ppVal /* OUT: Extracted value */
69789 ){
69790  u32 t; /* a column type code */
69791  int nHdr; /* Size of the header in the record */
69792  int iHdr; /* Next unread header byte */
69793  int iField; /* Next unread data byte */
69794  int szField; /* Size of the current data field */
69795  int i; /* Column index */
69796  u8 *a = (u8*)pRec; /* Typecast byte array */
69797  Mem *pMem = *ppVal; /* Write result into this Mem object */
69798 
69799  assert( iCol>0 );
69800  iHdr = getVarint32(a, nHdr);
69801  if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
69802  iField = nHdr;
69803  for(i=0; i<=iCol; i++){
69804  iHdr += getVarint32(&a[iHdr], t);
69805  testcase( iHdr==nHdr );
69806  testcase( iHdr==nHdr+1 );
69807  if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
69808  szField = sqlite3VdbeSerialTypeLen(t);
69809  iField += szField;
69810  }
69811  testcase( iField==nRec );
69812  testcase( iField==nRec+1 );
69813  if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
69814  if( pMem==0 ){
69815  pMem = *ppVal = sqlite3ValueNew(db);
69816  if( pMem==0 ) return SQLITE_NOMEM_BKPT;
69817  }
69818  sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
69819  pMem->enc = ENC(db);
69820  return SQLITE_OK;
69821 }
69822 
69823 /*
69824 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
69825 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
69826 ** the object.
69827 */
69828 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
69829  if( pRec ){
69830  int i;
69831  int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
69832  Mem *aMem = pRec->aMem;
69833  sqlite3 *db = aMem[0].db;
69834  for(i=0; i<nCol; i++){
69835  sqlite3VdbeMemRelease(&aMem[i]);
69836  }
69838  sqlite3DbFree(db, pRec);
69839  }
69840 }
69841 #endif /* ifdef SQLITE_ENABLE_STAT4 */
69842 
69843 /*
69844 ** Change the string value of an sqlite3_value object
69845 */
69847  sqlite3_value *v, /* Value to be set */
69848  int n, /* Length of string z */
69849  const void *z, /* Text of the new string */
69850  u8 enc, /* Encoding to use */
69851  void (*xDel)(void*) /* Destructor for the string */
69852 ){
69853  if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
69854 }
69855 
69856 /*
69857 ** Free an sqlite3_value object
69858 */
69860  if( !v ) return;
69861  sqlite3VdbeMemRelease((Mem *)v);
69862  sqlite3DbFree(((Mem*)v)->db, v);
69863 }
69864 
69865 /*
69866 ** The sqlite3ValueBytes() routine returns the number of bytes in the
69867 ** sqlite3_value object assuming that it uses the encoding "enc".
69868 ** The valueBytes() routine is a helper function.
69869 */
69870 static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc){
69871  return valueToText(pVal, enc)!=0 ? pVal->n : 0;
69872 }
69874  Mem *p = (Mem*)pVal;
69875  assert( (p->flags & MEM_Null)==0 || (p->flags & (MEM_Str|MEM_Blob))==0 );
69876  if( (p->flags & MEM_Str)!=0 && pVal->enc==enc ){
69877  return p->n;
69878  }
69879  if( (p->flags & MEM_Blob)!=0 ){
69880  if( p->flags & MEM_Zero ){
69881  return p->n + p->u.nZero;
69882  }else{
69883  return p->n;
69884  }
69885  }
69886  if( p->flags & MEM_Null ) return 0;
69887  return valueBytes(pVal, enc);
69888 }
69889 
69890 /************** End of vdbemem.c *********************************************/
69891 /************** Begin file vdbeaux.c *****************************************/
69892 /*
69893 ** 2003 September 6
69894 **
69895 ** The author disclaims copyright to this source code. In place of
69896 ** a legal notice, here is a blessing:
69897 **
69898 ** May you do good and not evil.
69899 ** May you find forgiveness for yourself and forgive others.
69900 ** May you share freely, never taking more than you give.
69901 **
69902 *************************************************************************
69903 ** This file contains code used for creating, destroying, and populating
69904 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
69905 */
69906 /* #include "sqliteInt.h" */
69907 /* #include "vdbeInt.h" */
69908 
69909 /*
69910 ** Create a new virtual database engine.
69911 */
69913  sqlite3 *db = pParse->db;
69914  Vdbe *p;
69915  p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
69916  if( p==0 ) return 0;
69917  p->db = db;
69918  if( db->pVdbe ){
69919  db->pVdbe->pPrev = p;
69920  }
69921  p->pNext = db->pVdbe;
69922  p->pPrev = 0;
69923  db->pVdbe = p;
69924  p->magic = VDBE_MAGIC_INIT;
69925  p->pParse = pParse;
69926  assert( pParse->aLabel==0 );
69927  assert( pParse->nLabel==0 );
69928  assert( pParse->nOpAlloc==0 );
69929  assert( pParse->szOpAlloc==0 );
69930  return p;
69931 }
69932 
69933 /*
69934 ** Change the error string stored in Vdbe.zErrMsg
69935 */
69936 SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *p, const char *zFormat, ...){
69937  va_list ap;
69938  sqlite3DbFree(p->db, p->zErrMsg);
69939  va_start(ap, zFormat);
69940  p->zErrMsg = sqlite3VMPrintf(p->db, zFormat, ap);
69941  va_end(ap);
69942 }
69943 
69944 /*
69945 ** Remember the SQL string for a prepared statement.
69946 */
69947 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
69948  assert( isPrepareV2==1 || isPrepareV2==0 );
69949  if( p==0 ) return;
69950 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
69951  if( !isPrepareV2 ) return;
69952 #endif
69953  assert( p->zSql==0 );
69954  p->zSql = sqlite3DbStrNDup(p->db, z, n);
69955  p->isPrepareV2 = (u8)isPrepareV2;
69956 }
69957 
69958 /*
69959 ** Return the SQL associated with a prepared statement
69960 */
69962  Vdbe *p = (Vdbe *)pStmt;
69963  return p ? p->zSql : 0;
69964 }
69965 
69966 /*
69967 ** Swap all content between two VDBE structures.
69968 */
69970  Vdbe tmp, *pTmp;
69971  char *zTmp;
69972  assert( pA->db==pB->db );
69973  tmp = *pA;
69974  *pA = *pB;
69975  *pB = tmp;
69976  pTmp = pA->pNext;
69977  pA->pNext = pB->pNext;
69978  pB->pNext = pTmp;
69979  pTmp = pA->pPrev;
69980  pA->pPrev = pB->pPrev;
69981  pB->pPrev = pTmp;
69982  zTmp = pA->zSql;
69983  pA->zSql = pB->zSql;
69984  pB->zSql = zTmp;
69985  pB->isPrepareV2 = pA->isPrepareV2;
69986 }
69987 
69988 /*
69989 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
69990 ** than its current size. nOp is guaranteed to be less than or equal
69991 ** to 1024/sizeof(Op).
69992 **
69993 ** If an out-of-memory error occurs while resizing the array, return
69994 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
69995 ** unchanged (this is so that any opcodes already allocated can be
69996 ** correctly deallocated along with the rest of the Vdbe).
69997 */
69998 static int growOpArray(Vdbe *v, int nOp){
69999  VdbeOp *pNew;
70000  Parse *p = v->pParse;
70001 
70002  /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
70003  ** more frequent reallocs and hence provide more opportunities for
70004  ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
70005  ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
70006  ** by the minimum* amount required until the size reaches 512. Normal
70007  ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
70008  ** size of the op array or add 1KB of space, whichever is smaller. */
70009 #ifdef SQLITE_TEST_REALLOC_STRESS
70010  int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
70011 #else
70012  int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
70013  UNUSED_PARAMETER(nOp);
70014 #endif
70015 
70016  assert( nOp<=(1024/sizeof(Op)) );
70017  assert( nNew>=(p->nOpAlloc+nOp) );
70018  pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
70019  if( pNew ){
70020  p->szOpAlloc = sqlite3DbMallocSize(p->db, pNew);
70021  p->nOpAlloc = p->szOpAlloc/sizeof(Op);
70022  v->aOp = pNew;
70023  }
70024  return (pNew ? SQLITE_OK : SQLITE_NOMEM_BKPT);
70025 }
70026 
70027 #ifdef SQLITE_DEBUG
70028 /* This routine is just a convenient place to set a breakpoint that will
70029 ** fire after each opcode is inserted and displayed using
70030 ** "PRAGMA vdbe_addoptrace=on".
70031 */
70032 static void test_addop_breakpoint(void){
70033  static int n = 0;
70034  n++;
70035 }
70036 #endif
70037 
70038 /*
70039 ** Add a new instruction to the list of instructions current in the
70040 ** VDBE. Return the address of the new instruction.
70041 **
70042 ** Parameters:
70043 **
70044 ** p Pointer to the VDBE
70045 **
70046 ** op The opcode for this instruction
70047 **
70048 ** p1, p2, p3 Operands
70049 **
70050 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
70051 ** the sqlite3VdbeChangeP4() function to change the value of the P4
70052 ** operand.
70053 */
70054 static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3){
70055  assert( p->pParse->nOpAlloc<=p->nOp );
70056  if( growOpArray(p, 1) ) return 1;
70057  assert( p->pParse->nOpAlloc>p->nOp );
70058  return sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70059 }
70060 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
70061  int i;
70062  VdbeOp *pOp;
70063 
70064  i = p->nOp;
70065  assert( p->magic==VDBE_MAGIC_INIT );
70066  assert( op>=0 && op<0xff );
70067  if( p->pParse->nOpAlloc<=i ){
70068  return growOp3(p, op, p1, p2, p3);
70069  }
70070  p->nOp++;
70071  pOp = &p->aOp[i];
70072  pOp->opcode = (u8)op;
70073  pOp->p5 = 0;
70074  pOp->p1 = p1;
70075  pOp->p2 = p2;
70076  pOp->p3 = p3;
70077  pOp->p4.p = 0;
70078  pOp->p4type = P4_NOTUSED;
70079 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70080  pOp->zComment = 0;
70081 #endif
70082 #ifdef SQLITE_DEBUG
70083  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70084  int jj, kk;
70085  Parse *pParse = p->pParse;
70086  for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
70087  struct yColCache *x = pParse->aColCache + jj;
70088  if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
70089  printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
70090  kk++;
70091  }
70092  if( kk ) printf("\n");
70093  sqlite3VdbePrintOp(0, i, &p->aOp[i]);
70094  test_addop_breakpoint();
70095  }
70096 #endif
70097 #ifdef VDBE_PROFILE
70098  pOp->cycles = 0;
70099  pOp->cnt = 0;
70100 #endif
70101 #ifdef SQLITE_VDBE_COVERAGE
70102  pOp->iSrcLine = 0;
70103 #endif
70104  return i;
70105 }
70107  return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
70108 }
70109 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
70110  return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
70111 }
70112 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
70113  return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
70114 }
70115 
70116 /* Generate code for an unconditional jump to instruction iDest
70117 */
70119  return sqlite3VdbeAddOp3(p, OP_Goto, 0, iDest, 0);
70120 }
70121 
70122 /* Generate code to cause the string zStr to be loaded into
70123 ** register iDest
70124 */
70125 SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *p, int iDest, const char *zStr){
70126  return sqlite3VdbeAddOp4(p, OP_String8, 0, iDest, 0, zStr, 0);
70127 }
70128 
70129 /*
70130 ** Generate code that initializes multiple registers to string or integer
70131 ** constants. The registers begin with iDest and increase consecutively.
70132 ** One register is initialized for each characgter in zTypes[]. For each
70133 ** "s" character in zTypes[], the register is a string if the argument is
70134 ** not NULL, or OP_Null if the value is a null pointer. For each "i" character
70135 ** in zTypes[], the register is initialized to an integer.
70136 */
70137 SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *p, int iDest, const char *zTypes, ...){
70138  va_list ap;
70139  int i;
70140  char c;
70141  va_start(ap, zTypes);
70142  for(i=0; (c = zTypes[i])!=0; i++){
70143  if( c=='s' ){
70144  const char *z = va_arg(ap, const char*);
70145  sqlite3VdbeAddOp4(p, z==0 ? OP_Null : OP_String8, 0, iDest++, 0, z, 0);
70146  }else{
70147  assert( c=='i' );
70148  sqlite3VdbeAddOp2(p, OP_Integer, va_arg(ap, int), iDest++);
70149  }
70150  }
70151  va_end(ap);
70152 }
70153 
70154 /*
70155 ** Add an opcode that includes the p4 value as a pointer.
70156 */
70158  Vdbe *p, /* Add the opcode to this VM */
70159  int op, /* The new opcode */
70160  int p1, /* The P1 operand */
70161  int p2, /* The P2 operand */
70162  int p3, /* The P3 operand */
70163  const char *zP4, /* The P4 operand */
70164  int p4type /* P4 operand type */
70165 ){
70166  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70167  sqlite3VdbeChangeP4(p, addr, zP4, p4type);
70168  return addr;
70169 }
70170 
70171 /*
70172 ** Add an opcode that includes the p4 value with a P4_INT64 or
70173 ** P4_REAL type.
70174 */
70176  Vdbe *p, /* Add the opcode to this VM */
70177  int op, /* The new opcode */
70178  int p1, /* The P1 operand */
70179  int p2, /* The P2 operand */
70180  int p3, /* The P3 operand */
70181  const u8 *zP4, /* The P4 operand */
70182  int p4type /* P4 operand type */
70183 ){
70184  char *p4copy = sqlite3DbMallocRawNN(sqlite3VdbeDb(p), 8);
70185  if( p4copy ) memcpy(p4copy, zP4, 8);
70186  return sqlite3VdbeAddOp4(p, op, p1, p2, p3, p4copy, p4type);
70187 }
70188 
70189 /*
70190 ** Add an OP_ParseSchema opcode. This routine is broken out from
70191 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
70192 ** as having been used.
70193 **
70194 ** The zWhere string must have been obtained from sqlite3_malloc().
70195 ** This routine will take ownership of the allocated memory.
70196 */
70197 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
70198  int j;
70199  sqlite3VdbeAddOp4(p, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
70200  for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
70201 }
70202 
70203 /*
70204 ** Add an opcode that includes the p4 value as an integer.
70205 */
70207  Vdbe *p, /* Add the opcode to this VM */
70208  int op, /* The new opcode */
70209  int p1, /* The P1 operand */
70210  int p2, /* The P2 operand */
70211  int p3, /* The P3 operand */
70212  int p4 /* The P4 operand as an integer */
70213 ){
70214  int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
70216  return addr;
70217 }
70218 
70219 /* Insert the end of a co-routine
70220 */
70222  sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
70223 
70224  /* Clear the temporary register cache, thereby ensuring that each
70225  ** co-routine has its own independent set of registers, because co-routines
70226  ** might expect their registers to be preserved across an OP_Yield, and
70227  ** that could cause problems if two or more co-routines are using the same
70228  ** temporary register.
70229  */
70230  v->pParse->nTempReg = 0;
70231  v->pParse->nRangeReg = 0;
70232 }
70233 
70234 /*
70235 ** Create a new symbolic label for an instruction that has yet to be
70236 ** coded. The symbolic label is really just a negative number. The
70237 ** label can be used as the P2 value of an operation. Later, when
70238 ** the label is resolved to a specific address, the VDBE will scan
70239 ** through its operation list and change all values of P2 which match
70240 ** the label into the resolved address.
70241 **
70242 ** The VDBE knows that a P2 value is a label because labels are
70243 ** always negative and P2 values are suppose to be non-negative.
70244 ** Hence, a negative P2 value is a label that has yet to be resolved.
70245 **
70246 ** Zero is returned if a malloc() fails.
70247 */
70249  Parse *p = v->pParse;
70250  int i = p->nLabel++;
70251  assert( v->magic==VDBE_MAGIC_INIT );
70252  if( (i & (i-1))==0 ){
70253  p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
70254  (i*2+1)*sizeof(p->aLabel[0]));
70255  }
70256  if( p->aLabel ){
70257  p->aLabel[i] = -1;
70258  }
70259  return ADDR(i);
70260 }
70261 
70262 /*
70263 ** Resolve label "x" to be the address of the next instruction to
70264 ** be inserted. The parameter "x" must have been obtained from
70265 ** a prior call to sqlite3VdbeMakeLabel().
70266 */
70268  Parse *p = v->pParse;
70269  int j = ADDR(x);
70270  assert( v->magic==VDBE_MAGIC_INIT );
70271  assert( j<p->nLabel );
70272  assert( j>=0 );
70273  if( p->aLabel ){
70274  p->aLabel[j] = v->nOp;
70275  }
70276  p->iFixedOp = v->nOp - 1;
70277 }
70278 
70279 /*
70280 ** Mark the VDBE as one that can only be run one time.
70281 */
70283  p->runOnlyOnce = 1;
70284 }
70285 
70286 /*
70287 ** Mark the VDBE as one that can only be run multiple times.
70288 */
70290  p->runOnlyOnce = 0;
70291 }
70292 
70293 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
70294 
70295 /*
70296 ** The following type and function are used to iterate through all opcodes
70297 ** in a Vdbe main program and each of the sub-programs (triggers) it may
70298 ** invoke directly or indirectly. It should be used as follows:
70299 **
70300 ** Op *pOp;
70301 ** VdbeOpIter sIter;
70302 **
70303 ** memset(&sIter, 0, sizeof(sIter));
70304 ** sIter.v = v; // v is of type Vdbe*
70305 ** while( (pOp = opIterNext(&sIter)) ){
70306 ** // Do something with pOp
70307 ** }
70308 ** sqlite3DbFree(v->db, sIter.apSub);
70309 **
70310 */
70311 typedef struct VdbeOpIter VdbeOpIter;
70312 struct VdbeOpIter {
70313  Vdbe *v; /* Vdbe to iterate through the opcodes of */
70314  SubProgram **apSub; /* Array of subprograms */
70315  int nSub; /* Number of entries in apSub */
70316  int iAddr; /* Address of next instruction to return */
70317  int iSub; /* 0 = main program, 1 = first sub-program etc. */
70318 };
70319 static Op *opIterNext(VdbeOpIter *p){
70320  Vdbe *v = p->v;
70321  Op *pRet = 0;
70322  Op *aOp;
70323  int nOp;
70324 
70325  if( p->iSub<=p->nSub ){
70326 
70327  if( p->iSub==0 ){
70328  aOp = v->aOp;
70329  nOp = v->nOp;
70330  }else{
70331  aOp = p->apSub[p->iSub-1]->aOp;
70332  nOp = p->apSub[p->iSub-1]->nOp;
70333  }
70334  assert( p->iAddr<nOp );
70335 
70336  pRet = &aOp[p->iAddr];
70337  p->iAddr++;
70338  if( p->iAddr==nOp ){
70339  p->iSub++;
70340  p->iAddr = 0;
70341  }
70342 
70343  if( pRet->p4type==P4_SUBPROGRAM ){
70344  int nByte = (p->nSub+1)*sizeof(SubProgram*);
70345  int j;
70346  for(j=0; j<p->nSub; j++){
70347  if( p->apSub[j]==pRet->p4.pProgram ) break;
70348  }
70349  if( j==p->nSub ){
70350  p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
70351  if( !p->apSub ){
70352  pRet = 0;
70353  }else{
70354  p->apSub[p->nSub++] = pRet->p4.pProgram;
70355  }
70356  }
70357  }
70358  }
70359 
70360  return pRet;
70361 }
70362 
70363 /*
70364 ** Check if the program stored in the VM associated with pParse may
70365 ** throw an ABORT exception (causing the statement, but not entire transaction
70366 ** to be rolled back). This condition is true if the main program or any
70367 ** sub-programs contains any of the following:
70368 **
70369 ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70370 ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
70371 ** * OP_Destroy
70372 ** * OP_VUpdate
70373 ** * OP_VRename
70374 ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
70375 ** * OP_CreateTable and OP_InitCoroutine (for CREATE TABLE AS SELECT ...)
70376 **
70377 ** Then check that the value of Parse.mayAbort is true if an
70378 ** ABORT may be thrown, or false otherwise. Return true if it does
70379 ** match, or false otherwise. This function is intended to be used as
70380 ** part of an assert statement in the compiler. Similar to:
70381 **
70382 ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
70383 */
70384 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
70385  int hasAbort = 0;
70386  int hasFkCounter = 0;
70387  int hasCreateTable = 0;
70388  int hasInitCoroutine = 0;
70389  Op *pOp;
70390  VdbeOpIter sIter;
70391  memset(&sIter, 0, sizeof(sIter));
70392  sIter.v = v;
70393 
70394  while( (pOp = opIterNext(&sIter))!=0 ){
70395  int opcode = pOp->opcode;
70396  if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
70397  || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
70398  && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
70399  ){
70400  hasAbort = 1;
70401  break;
70402  }
70403  if( opcode==OP_CreateTable ) hasCreateTable = 1;
70404  if( opcode==OP_InitCoroutine ) hasInitCoroutine = 1;
70405 #ifndef SQLITE_OMIT_FOREIGN_KEY
70406  if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
70407  hasFkCounter = 1;
70408  }
70409 #endif
70410  }
70411  sqlite3DbFree(v->db, sIter.apSub);
70412 
70413  /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
70414  ** If malloc failed, then the while() loop above may not have iterated
70415  ** through all opcodes and hasAbort may be set incorrectly. Return
70416  ** true for this case to prevent the assert() in the callers frame
70417  ** from failing. */
70418  return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter
70419  || (hasCreateTable && hasInitCoroutine) );
70420 }
70421 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
70422 
70423 /*
70424 ** This routine is called after all opcodes have been inserted. It loops
70425 ** through all the opcodes and fixes up some details.
70426 **
70427 ** (1) For each jump instruction with a negative P2 value (a label)
70428 ** resolve the P2 value to an actual address.
70429 **
70430 ** (2) Compute the maximum number of arguments used by any SQL function
70431 ** and store that value in *pMaxFuncArgs.
70432 **
70433 ** (3) Update the Vdbe.readOnly and Vdbe.bIsReader flags to accurately
70434 ** indicate what the prepared statement actually does.
70435 **
70436 ** (4) Initialize the p4.xAdvance pointer on opcodes that use it.
70437 **
70438 ** (5) Reclaim the memory allocated for storing labels.
70439 **
70440 ** This routine will only function correctly if the mkopcodeh.tcl generator
70441 ** script numbers the opcodes correctly. Changes to this routine must be
70442 ** coordinated with changes to mkopcodeh.tcl.
70443 */
70444 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
70445  int nMaxArgs = *pMaxFuncArgs;
70446  Op *pOp;
70447  Parse *pParse = p->pParse;
70448  int *aLabel = pParse->aLabel;
70449  p->readOnly = 1;
70450  p->bIsReader = 0;
70451  pOp = &p->aOp[p->nOp-1];
70452  while(1){
70453 
70454  /* Only JUMP opcodes and the short list of special opcodes in the switch
70455  ** below need to be considered. The mkopcodeh.tcl generator script groups
70456  ** all these opcodes together near the front of the opcode list. Skip
70457  ** any opcode that does not need processing by virtual of the fact that
70458  ** it is larger than SQLITE_MX_JUMP_OPCODE, as a performance optimization.
70459  */
70460  if( pOp->opcode<=SQLITE_MX_JUMP_OPCODE ){
70461  /* NOTE: Be sure to update mkopcodeh.tcl when adding or removing
70462  ** cases from this switch! */
70463  switch( pOp->opcode ){
70464  case OP_Transaction: {
70465  if( pOp->p2!=0 ) p->readOnly = 0;
70466  /* fall thru */
70467  }
70468  case OP_AutoCommit:
70469  case OP_Savepoint: {
70470  p->bIsReader = 1;
70471  break;
70472  }
70473 #ifndef SQLITE_OMIT_WAL
70474  case OP_Checkpoint:
70475 #endif
70476  case OP_Vacuum:
70477  case OP_JournalMode: {
70478  p->readOnly = 0;
70479  p->bIsReader = 1;
70480  break;
70481  }
70482 #ifndef SQLITE_OMIT_VIRTUALTABLE
70483  case OP_VUpdate: {
70484  if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
70485  break;
70486  }
70487  case OP_VFilter: {
70488  int n;
70489  assert( (pOp - p->aOp) >= 3 );
70490  assert( pOp[-1].opcode==OP_Integer );
70491  n = pOp[-1].p1;
70492  if( n>nMaxArgs ) nMaxArgs = n;
70493  break;
70494  }
70495 #endif
70496  case OP_Next:
70497  case OP_NextIfOpen:
70498  case OP_SorterNext: {
70499  pOp->p4.xAdvance = sqlite3BtreeNext;
70500  pOp->p4type = P4_ADVANCE;
70501  break;
70502  }
70503  case OP_Prev:
70504  case OP_PrevIfOpen: {
70506  pOp->p4type = P4_ADVANCE;
70507  break;
70508  }
70509  }
70510  if( (sqlite3OpcodeProperty[pOp->opcode] & OPFLG_JUMP)!=0 && pOp->p2<0 ){
70511  assert( ADDR(pOp->p2)<pParse->nLabel );
70512  pOp->p2 = aLabel[ADDR(pOp->p2)];
70513  }
70514  }
70515  if( pOp==p->aOp ) break;
70516  pOp--;
70517  }
70518  sqlite3DbFree(p->db, pParse->aLabel);
70519  pParse->aLabel = 0;
70520  pParse->nLabel = 0;
70521  *pMaxFuncArgs = nMaxArgs;
70522  assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
70523 }
70524 
70525 /*
70526 ** Return the address of the next instruction to be inserted.
70527 */
70529  assert( p->magic==VDBE_MAGIC_INIT );
70530  return p->nOp;
70531 }
70532 
70533 /*
70534 ** Verify that at least N opcode slots are available in p without
70535 ** having to malloc for more space (except when compiled using
70536 ** SQLITE_TEST_REALLOC_STRESS). This interface is used during testing
70537 ** to verify that certain calls to sqlite3VdbeAddOpList() can never
70538 ** fail due to a OOM fault and hence that the return value from
70539 ** sqlite3VdbeAddOpList() will always be non-NULL.
70540 */
70541 #if defined(SQLITE_DEBUG) && !defined(SQLITE_TEST_REALLOC_STRESS)
70543  assert( p->nOp + N <= p->pParse->nOpAlloc );
70544 }
70545 #endif
70546 
70547 /*
70548 ** This function returns a pointer to the array of opcodes associated with
70549 ** the Vdbe passed as the first argument. It is the callers responsibility
70550 ** to arrange for the returned array to be eventually freed using the
70551 ** vdbeFreeOpArray() function.
70552 **
70553 ** Before returning, *pnOp is set to the number of entries in the returned
70554 ** array. Also, *pnMaxArg is set to the larger of its current value and
70555 ** the number of entries in the Vdbe.apArg[] array required to execute the
70556 ** returned program.
70557 */
70558 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
70559  VdbeOp *aOp = p->aOp;
70560  assert( aOp && !p->db->mallocFailed );
70561 
70562  /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
70564 
70565  resolveP2Values(p, pnMaxArg);
70566  *pnOp = p->nOp;
70567  p->aOp = 0;
70568  return aOp;
70569 }
70570 
70571 /*
70572 ** Add a whole list of operations to the operation stack. Return a
70573 ** pointer to the first operation inserted.
70574 **
70575 ** Non-zero P2 arguments to jump instructions are automatically adjusted
70576 ** so that the jump target is relative to the first operation inserted.
70577 */
70579  Vdbe *p, /* Add opcodes to the prepared statement */
70580  int nOp, /* Number of opcodes to add */
70581  VdbeOpList const *aOp, /* The opcodes to be added */
70582  int iLineno /* Source-file line number of first opcode */
70583 ){
70584  int i;
70585  VdbeOp *pOut, *pFirst;
70586  assert( nOp>0 );
70587  assert( p->magic==VDBE_MAGIC_INIT );
70588  if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
70589  return 0;
70590  }
70591  pFirst = pOut = &p->aOp[p->nOp];
70592  for(i=0; i<nOp; i++, aOp++, pOut++){
70593  pOut->opcode = aOp->opcode;
70594  pOut->p1 = aOp->p1;
70595  pOut->p2 = aOp->p2;
70596  assert( aOp->p2>=0 );
70597  if( (sqlite3OpcodeProperty[aOp->opcode] & OPFLG_JUMP)!=0 && aOp->p2>0 ){
70598  pOut->p2 += p->nOp;
70599  }
70600  pOut->p3 = aOp->p3;
70601  pOut->p4type = P4_NOTUSED;
70602  pOut->p4.p = 0;
70603  pOut->p5 = 0;
70604 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70605  pOut->zComment = 0;
70606 #endif
70607 #ifdef SQLITE_VDBE_COVERAGE
70608  pOut->iSrcLine = iLineno+i;
70609 #else
70610  (void)iLineno;
70611 #endif
70612 #ifdef SQLITE_DEBUG
70613  if( p->db->flags & SQLITE_VdbeAddopTrace ){
70614  sqlite3VdbePrintOp(0, i+p->nOp, &p->aOp[i+p->nOp]);
70615  }
70616 #endif
70617  }
70618  p->nOp += nOp;
70619  return pFirst;
70620 }
70621 
70622 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
70623 /*
70624 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
70625 */
70627  Vdbe *p, /* VM to add scanstatus() to */
70628  int addrExplain, /* Address of OP_Explain (or 0) */
70629  int addrLoop, /* Address of loop counter */
70630  int addrVisit, /* Address of rows visited counter */
70631  LogEst nEst, /* Estimated number of output rows */
70632  const char *zName /* Name of table or index being scanned */
70633 ){
70634  int nByte = (p->nScan+1) * sizeof(ScanStatus);
70635  ScanStatus *aNew;
70636  aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
70637  if( aNew ){
70638  ScanStatus *pNew = &aNew[p->nScan++];
70639  pNew->addrExplain = addrExplain;
70640  pNew->addrLoop = addrLoop;
70641  pNew->addrVisit = addrVisit;
70642  pNew->nEst = nEst;
70643  pNew->zName = sqlite3DbStrDup(p->db, zName);
70644  p->aScan = aNew;
70645  }
70646 }
70647 #endif
70648 
70649 
70650 /*
70651 ** Change the value of the opcode, or P1, P2, P3, or P5 operands
70652 ** for a specific instruction.
70653 */
70654 SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *p, u32 addr, u8 iNewOpcode){
70655  sqlite3VdbeGetOp(p,addr)->opcode = iNewOpcode;
70656 }
70658  sqlite3VdbeGetOp(p,addr)->p1 = val;
70659 }
70661  sqlite3VdbeGetOp(p,addr)->p2 = val;
70662 }
70664  sqlite3VdbeGetOp(p,addr)->p3 = val;
70665 }
70667  if( !p->db->mallocFailed ) p->aOp[p->nOp-1].p5 = p5;
70668 }
70669 
70670 /*
70671 ** Change the P2 operand of instruction addr so that it points to
70672 ** the address of the next instruction to be coded.
70673 */
70675  p->pParse->iFixedOp = p->nOp - 1;
70676  sqlite3VdbeChangeP2(p, addr, p->nOp);
70677 }
70678 
70679 
70680 /*
70681 ** If the input FuncDef structure is ephemeral, then free it. If
70682 ** the FuncDef is not ephermal, then do nothing.
70683 */
70684 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
70685  if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
70686  sqlite3DbFree(db, pDef);
70687  }
70688 }
70689 
70690 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
70691 
70692 /*
70693 ** Delete a P4 value if necessary.
70694 */
70695 static void freeP4(sqlite3 *db, int p4type, void *p4){
70696  assert( db );
70697  switch( p4type ){
70698  case P4_FUNCCTX: {
70699  freeEphemeralFunction(db, ((sqlite3_context*)p4)->pFunc);
70700  /* Fall through into the next case */
70701  }
70702  case P4_REAL:
70703  case P4_INT64:
70704  case P4_DYNAMIC:
70705  case P4_INTARRAY: {
70706  sqlite3DbFree(db, p4);
70707  break;
70708  }
70709  case P4_KEYINFO: {
70710  if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
70711  break;
70712  }
70713 #ifdef SQLITE_ENABLE_CURSOR_HINTS
70714  case P4_EXPR: {
70715  sqlite3ExprDelete(db, (Expr*)p4);
70716  break;
70717  }
70718 #endif
70719  case P4_MPRINTF: {
70720  if( db->pnBytesFreed==0 ) sqlite3_free(p4);
70721  break;
70722  }
70723  case P4_FUNCDEF: {
70724  freeEphemeralFunction(db, (FuncDef*)p4);
70725  break;
70726  }
70727  case P4_MEM: {
70728  if( db->pnBytesFreed==0 ){
70730  }else{
70731  Mem *p = (Mem*)p4;
70732  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
70733  sqlite3DbFree(db, p);
70734  }
70735  break;
70736  }
70737  case P4_VTAB : {
70738  if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
70739  break;
70740  }
70741  }
70742 }
70743 
70744 /*
70745 ** Free the space allocated for aOp and any p4 values allocated for the
70746 ** opcodes contained within. If aOp is not NULL it is assumed to contain
70747 ** nOp entries.
70748 */
70749 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
70750  if( aOp ){
70751  Op *pOp;
70752  for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
70753  if( pOp->p4type ) freeP4(db, pOp->p4type, pOp->p4.p);
70754 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70755  sqlite3DbFree(db, pOp->zComment);
70756 #endif
70757  }
70758  }
70759  sqlite3DbFree(db, aOp);
70760 }
70761 
70762 /*
70763 ** Link the SubProgram object passed as the second argument into the linked
70764 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
70765 ** objects when the VM is no longer required.
70766 */
70768  p->pNext = pVdbe->pProgram;
70769  pVdbe->pProgram = p;
70770 }
70771 
70772 /*
70773 ** Change the opcode at addr into OP_Noop
70774 */
70776  VdbeOp *pOp;
70777  if( p->db->mallocFailed ) return 0;
70778  assert( addr>=0 && addr<p->nOp );
70779  pOp = &p->aOp[addr];
70780  freeP4(p->db, pOp->p4type, pOp->p4.p);
70781  pOp->p4type = P4_NOTUSED;
70782  pOp->p4.z = 0;
70783  pOp->opcode = OP_Noop;
70784  return 1;
70785 }
70786 
70787 /*
70788 ** If the last opcode is "op" and it is not a jump destination,
70789 ** then remove it. Return true if and only if an opcode was removed.
70790 */
70792  if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
70793  return sqlite3VdbeChangeToNoop(p, p->nOp-1);
70794  }else{
70795  return 0;
70796  }
70797 }
70798 
70799 /*
70800 ** Change the value of the P4 operand for a specific instruction.
70801 ** This routine is useful when a large program is loaded from a
70802 ** static array using sqlite3VdbeAddOpList but we want to make a
70803 ** few minor changes to the program.
70804 **
70805 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
70806 ** the string is made into memory obtained from sqlite3_malloc().
70807 ** A value of n==0 means copy bytes of zP4 up to and including the
70808 ** first null byte. If n>0 then copy n+1 bytes of zP4.
70809 **
70810 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
70811 ** to a string or structure that is guaranteed to exist for the lifetime of
70812 ** the Vdbe. In these cases we can just copy the pointer.
70813 **
70814 ** If addr<0 then change P4 on the most recently inserted instruction.
70815 */
70817  Vdbe *p,
70818  Op *pOp,
70819  const char *zP4,
70820  int n
70821 ){
70822  if( pOp->p4type ){
70823  freeP4(p->db, pOp->p4type, pOp->p4.p);
70824  pOp->p4type = 0;
70825  pOp->p4.p = 0;
70826  }
70827  if( n<0 ){
70828  sqlite3VdbeChangeP4(p, (int)(pOp - p->aOp), zP4, n);
70829  }else{
70830  if( n==0 ) n = sqlite3Strlen30(zP4);
70831  pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
70832  pOp->p4type = P4_DYNAMIC;
70833  }
70834 }
70835 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
70836  Op *pOp;
70837  sqlite3 *db;
70838  assert( p!=0 );
70839  db = p->db;
70840  assert( p->magic==VDBE_MAGIC_INIT );
70841  assert( p->aOp!=0 || db->mallocFailed );
70842  if( db->mallocFailed ){
70843  if( n!=P4_VTAB ) freeP4(db, n, (void*)*(char**)&zP4);
70844  return;
70845  }
70846  assert( p->nOp>0 );
70847  assert( addr<p->nOp );
70848  if( addr<0 ){
70849  addr = p->nOp - 1;
70850  }
70851  pOp = &p->aOp[addr];
70852  if( n>=0 || pOp->p4type ){
70853  vdbeChangeP4Full(p, pOp, zP4, n);
70854  return;
70855  }
70856  if( n==P4_INT32 ){
70857  /* Note: this cast is safe, because the origin data point was an int
70858  ** that was cast to a (const char *). */
70859  pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
70860  pOp->p4type = P4_INT32;
70861  }else if( zP4!=0 ){
70862  assert( n<0 );
70863  pOp->p4.p = (void*)zP4;
70864  pOp->p4type = (signed char)n;
70865  if( n==P4_VTAB ) sqlite3VtabLock((VTable*)zP4);
70866  }
70867 }
70868 
70869 /*
70870 ** Set the P4 on the most recently added opcode to the KeyInfo for the
70871 ** index given.
70872 */
70874  Vdbe *v = pParse->pVdbe;
70875  assert( v!=0 );
70876  assert( pIdx!=0 );
70877  sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
70878  P4_KEYINFO);
70879 }
70880 
70881 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
70882 /*
70883 ** Change the comment on the most recently coded instruction. Or
70884 ** insert a No-op and add the comment to that new instruction. This
70885 ** makes the code easier to read during debugging. None of this happens
70886 ** in a production build.
70887 */
70888 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
70889  assert( p->nOp>0 || p->aOp==0 );
70890  assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
70891  if( p->nOp ){
70892  assert( p->aOp );
70893  sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
70894  p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
70895  }
70896 }
70897 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
70898  va_list ap;
70899  if( p ){
70900  va_start(ap, zFormat);
70901  vdbeVComment(p, zFormat, ap);
70902  va_end(ap);
70903  }
70904 }
70905 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
70906  va_list ap;
70907  if( p ){
70909  va_start(ap, zFormat);
70910  vdbeVComment(p, zFormat, ap);
70911  va_end(ap);
70912  }
70913 }
70914 #endif /* NDEBUG */
70915 
70916 #ifdef SQLITE_VDBE_COVERAGE
70917 /*
70918 ** Set the value if the iSrcLine field for the previously coded instruction.
70919 */
70920 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
70921  sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
70922 }
70923 #endif /* SQLITE_VDBE_COVERAGE */
70924 
70925 /*
70926 ** Return the opcode for a given address. If the address is -1, then
70927 ** return the most recently inserted opcode.
70928 **
70929 ** If a memory allocation error has occurred prior to the calling of this
70930 ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
70931 ** is readable but not writable, though it is cast to a writable value.
70932 ** The return of a dummy opcode allows the call to continue functioning
70933 ** after an OOM fault without having to check to see if the return from
70934 ** this routine is a valid pointer. But because the dummy.opcode is 0,
70935 ** dummy will never be written to. This is verified by code inspection and
70936 ** by running with Valgrind.
70937 */
70939  /* C89 specifies that the constant "dummy" will be initialized to all
70940  ** zeros, which is correct. MSVC generates a warning, nevertheless. */
70941  static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
70942  assert( p->magic==VDBE_MAGIC_INIT );
70943  if( addr<0 ){
70944  addr = p->nOp - 1;
70945  }
70946  assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
70947  if( p->db->mallocFailed ){
70948  return (VdbeOp*)&dummy;
70949  }else{
70950  return &p->aOp[addr];
70951  }
70952 }
70953 
70954 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
70955 /*
70956 ** Return an integer value for one of the parameters to the opcode pOp
70957 ** determined by character c.
70958 */
70959 static int translateP(char c, const Op *pOp){
70960  if( c=='1' ) return pOp->p1;
70961  if( c=='2' ) return pOp->p2;
70962  if( c=='3' ) return pOp->p3;
70963  if( c=='4' ) return pOp->p4.i;
70964  return pOp->p5;
70965 }
70966 
70967 /*
70968 ** Compute a string for the "comment" field of a VDBE opcode listing.
70969 **
70970 ** The Synopsis: field in comments in the vdbe.c source file gets converted
70971 ** to an extra string that is appended to the sqlite3OpcodeName(). In the
70972 ** absence of other comments, this synopsis becomes the comment on the opcode.
70973 ** Some translation occurs:
70974 **
70975 ** "PX" -> "r[X]"
70976 ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
70977 ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
70978 ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
70979 */
70980 static int displayComment(
70981  const Op *pOp, /* The opcode to be commented */
70982  const char *zP4, /* Previously obtained value for P4 */
70983  char *zTemp, /* Write result here */
70984  int nTemp /* Space available in zTemp[] */
70985 ){
70986  const char *zOpName;
70987  const char *zSynopsis;
70988  int nOpName;
70989  int ii, jj;
70990  zOpName = sqlite3OpcodeName(pOp->opcode);
70991  nOpName = sqlite3Strlen30(zOpName);
70992  if( zOpName[nOpName+1] ){
70993  int seenCom = 0;
70994  char c;
70995  zSynopsis = zOpName += nOpName + 1;
70996  for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
70997  if( c=='P' ){
70998  c = zSynopsis[++ii];
70999  if( c=='4' ){
71000  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
71001  }else if( c=='X' ){
71002  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
71003  seenCom = 1;
71004  }else{
71005  int v1 = translateP(c, pOp);
71006  int v2;
71007  sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
71008  if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
71009  ii += 3;
71010  jj += sqlite3Strlen30(zTemp+jj);
71011  v2 = translateP(zSynopsis[ii], pOp);
71012  if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
71013  ii += 2;
71014  v2++;
71015  }
71016  if( v2>1 ){
71017  sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
71018  }
71019  }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
71020  ii += 4;
71021  }
71022  }
71023  jj += sqlite3Strlen30(zTemp+jj);
71024  }else{
71025  zTemp[jj++] = c;
71026  }
71027  }
71028  if( !seenCom && jj<nTemp-5 && pOp->zComment ){
71029  sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
71030  jj += sqlite3Strlen30(zTemp+jj);
71031  }
71032  if( jj<nTemp ) zTemp[jj] = 0;
71033  }else if( pOp->zComment ){
71034  sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
71035  jj = sqlite3Strlen30(zTemp);
71036  }else{
71037  zTemp[0] = 0;
71038  jj = 0;
71039  }
71040  return jj;
71041 }
71042 #endif /* SQLITE_DEBUG */
71043 
71044 #if VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS)
71045 /*
71046 ** Translate the P4.pExpr value for an OP_CursorHint opcode into text
71047 ** that can be displayed in the P4 column of EXPLAIN output.
71048 */
71049 static void displayP4Expr(StrAccum *p, Expr *pExpr){
71050  const char *zOp = 0;
71051  switch( pExpr->op ){
71052  case TK_STRING:
71053  sqlite3XPrintf(p, "%Q", pExpr->u.zToken);
71054  break;
71055  case TK_INTEGER:
71056  sqlite3XPrintf(p, "%d", pExpr->u.iValue);
71057  break;
71058  case TK_NULL:
71059  sqlite3XPrintf(p, "NULL");
71060  break;
71061  case TK_REGISTER: {
71062  sqlite3XPrintf(p, "r[%d]", pExpr->iTable);
71063  break;
71064  }
71065  case TK_COLUMN: {
71066  if( pExpr->iColumn<0 ){
71067  sqlite3XPrintf(p, "rowid");
71068  }else{
71069  sqlite3XPrintf(p, "c%d", (int)pExpr->iColumn);
71070  }
71071  break;
71072  }
71073  case TK_LT: zOp = "LT"; break;
71074  case TK_LE: zOp = "LE"; break;
71075  case TK_GT: zOp = "GT"; break;
71076  case TK_GE: zOp = "GE"; break;
71077  case TK_NE: zOp = "NE"; break;
71078  case TK_EQ: zOp = "EQ"; break;
71079  case TK_IS: zOp = "IS"; break;
71080  case TK_ISNOT: zOp = "ISNOT"; break;
71081  case TK_AND: zOp = "AND"; break;
71082  case TK_OR: zOp = "OR"; break;
71083  case TK_PLUS: zOp = "ADD"; break;
71084  case TK_STAR: zOp = "MUL"; break;
71085  case TK_MINUS: zOp = "SUB"; break;
71086  case TK_REM: zOp = "REM"; break;
71087  case TK_BITAND: zOp = "BITAND"; break;
71088  case TK_BITOR: zOp = "BITOR"; break;
71089  case TK_SLASH: zOp = "DIV"; break;
71090  case TK_LSHIFT: zOp = "LSHIFT"; break;
71091  case TK_RSHIFT: zOp = "RSHIFT"; break;
71092  case TK_CONCAT: zOp = "CONCAT"; break;
71093  case TK_UMINUS: zOp = "MINUS"; break;
71094  case TK_UPLUS: zOp = "PLUS"; break;
71095  case TK_BITNOT: zOp = "BITNOT"; break;
71096  case TK_NOT: zOp = "NOT"; break;
71097  case TK_ISNULL: zOp = "ISNULL"; break;
71098  case TK_NOTNULL: zOp = "NOTNULL"; break;
71099 
71100  default:
71101  sqlite3XPrintf(p, "%s", "expr");
71102  break;
71103  }
71104 
71105  if( zOp ){
71106  sqlite3XPrintf(p, "%s(", zOp);
71107  displayP4Expr(p, pExpr->pLeft);
71108  if( pExpr->pRight ){
71109  sqlite3StrAccumAppend(p, ",", 1);
71110  displayP4Expr(p, pExpr->pRight);
71111  }
71112  sqlite3StrAccumAppend(p, ")", 1);
71113  }
71114 }
71115 #endif /* VDBE_DISPLAY_P4 && defined(SQLITE_ENABLE_CURSOR_HINTS) */
71116 
71117 
71118 #if VDBE_DISPLAY_P4
71119 /*
71120 ** Compute a string that describes the P4 parameter for an opcode.
71121 ** Use zTemp for any required temporary buffer space.
71122 */
71123 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
71124  char *zP4 = zTemp;
71125  StrAccum x;
71126  assert( nTemp>=20 );
71127  sqlite3StrAccumInit(&x, 0, zTemp, nTemp, 0);
71128  switch( pOp->p4type ){
71129  case P4_KEYINFO: {
71130  int j;
71131  KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
71132  assert( pKeyInfo->aSortOrder!=0 );
71133  sqlite3XPrintf(&x, "k(%d", pKeyInfo->nField);
71134  for(j=0; j<pKeyInfo->nField; j++){
71135  CollSeq *pColl = pKeyInfo->aColl[j];
71136  const char *zColl = pColl ? pColl->zName : "";
71137  if( strcmp(zColl, "BINARY")==0 ) zColl = "B";
71138  sqlite3XPrintf(&x, ",%s%s", pKeyInfo->aSortOrder[j] ? "-" : "", zColl);
71139  }
71140  sqlite3StrAccumAppend(&x, ")", 1);
71141  break;
71142  }
71143 #ifdef SQLITE_ENABLE_CURSOR_HINTS
71144  case P4_EXPR: {
71145  displayP4Expr(&x, pOp->p4.pExpr);
71146  break;
71147  }
71148 #endif
71149  case P4_COLLSEQ: {
71150  CollSeq *pColl = pOp->p4.pColl;
71151  sqlite3XPrintf(&x, "(%.20s)", pColl->zName);
71152  break;
71153  }
71154  case P4_FUNCDEF: {
71155  FuncDef *pDef = pOp->p4.pFunc;
71156  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71157  break;
71158  }
71159 #ifdef SQLITE_DEBUG
71160  case P4_FUNCCTX: {
71161  FuncDef *pDef = pOp->p4.pCtx->pFunc;
71162  sqlite3XPrintf(&x, "%s(%d)", pDef->zName, pDef->nArg);
71163  break;
71164  }
71165 #endif
71166  case P4_INT64: {
71167  sqlite3XPrintf(&x, "%lld", *pOp->p4.pI64);
71168  break;
71169  }
71170  case P4_INT32: {
71171  sqlite3XPrintf(&x, "%d", pOp->p4.i);
71172  break;
71173  }
71174  case P4_REAL: {
71175  sqlite3XPrintf(&x, "%.16g", *pOp->p4.pReal);
71176  break;
71177  }
71178  case P4_MEM: {
71179  Mem *pMem = pOp->p4.pMem;
71180  if( pMem->flags & MEM_Str ){
71181  zP4 = pMem->z;
71182  }else if( pMem->flags & MEM_Int ){
71183  sqlite3XPrintf(&x, "%lld", pMem->u.i);
71184  }else if( pMem->flags & MEM_Real ){
71185  sqlite3XPrintf(&x, "%.16g", pMem->u.r);
71186  }else if( pMem->flags & MEM_Null ){
71187  zP4 = "NULL";
71188  }else{
71189  assert( pMem->flags & MEM_Blob );
71190  zP4 = "(blob)";
71191  }
71192  break;
71193  }
71194 #ifndef SQLITE_OMIT_VIRTUALTABLE
71195  case P4_VTAB: {
71196  sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
71197  sqlite3XPrintf(&x, "vtab:%p", pVtab);
71198  break;
71199  }
71200 #endif
71201  case P4_INTARRAY: {
71202  int i;
71203  int *ai = pOp->p4.ai;
71204  int n = ai[0]; /* The first element of an INTARRAY is always the
71205  ** count of the number of elements to follow */
71206  for(i=1; i<n; i++){
71207  sqlite3XPrintf(&x, ",%d", ai[i]);
71208  }
71209  zTemp[0] = '[';
71210  sqlite3StrAccumAppend(&x, "]", 1);
71211  break;
71212  }
71213  case P4_SUBPROGRAM: {
71214  sqlite3XPrintf(&x, "program");
71215  break;
71216  }
71217  case P4_ADVANCE: {
71218  zTemp[0] = 0;
71219  break;
71220  }
71221  case P4_TABLE: {
71222  sqlite3XPrintf(&x, "%s", pOp->p4.pTab->zName);
71223  break;
71224  }
71225  default: {
71226  zP4 = pOp->p4.z;
71227  if( zP4==0 ){
71228  zP4 = zTemp;
71229  zTemp[0] = 0;
71230  }
71231  }
71232  }
71234  assert( zP4!=0 );
71235  return zP4;
71236 }
71237 #endif /* VDBE_DISPLAY_P4 */
71238 
71239 /*
71240 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
71241 **
71242 ** The prepared statements need to know in advance the complete set of
71243 ** attached databases that will be use. A mask of these databases
71244 ** is maintained in p->btreeMask. The p->lockMask value is the subset of
71245 ** p->btreeMask of databases that will require a lock.
71246 */
71248  assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
71249  assert( i<(int)sizeof(p->btreeMask)*8 );
71250  DbMaskSet(p->btreeMask, i);
71251  if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
71252  DbMaskSet(p->lockMask, i);
71253  }
71254 }
71255 
71256 #if !defined(SQLITE_OMIT_SHARED_CACHE)
71257 /*
71258 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
71259 ** this routine obtains the mutex associated with each BtShared structure
71260 ** that may be accessed by the VM passed as an argument. In doing so it also
71261 ** sets the BtShared.db member of each of the BtShared structures, ensuring
71262 ** that the correct busy-handler callback is invoked if required.
71263 **
71264 ** If SQLite is not threadsafe but does support shared-cache mode, then
71265 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
71266 ** of all of BtShared structures accessible via the database handle
71267 ** associated with the VM.
71268 **
71269 ** If SQLite is not threadsafe and does not support shared-cache mode, this
71270 ** function is a no-op.
71271 **
71272 ** The p->btreeMask field is a bitmask of all btrees that the prepared
71273 ** statement p will ever use. Let N be the number of bits in p->btreeMask
71274 ** corresponding to btrees that use shared cache. Then the runtime of
71275 ** this routine is N*N. But as N is rarely more than 1, this should not
71276 ** be a problem.
71277 */
71279  int i;
71280  sqlite3 *db;
71281  Db *aDb;
71282  int nDb;
71283  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71284  db = p->db;
71285  aDb = db->aDb;
71286  nDb = db->nDb;
71287  for(i=0; i<nDb; i++){
71288  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71289  sqlite3BtreeEnter(aDb[i].pBt);
71290  }
71291  }
71292 }
71293 #endif
71294 
71295 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
71296 /*
71297 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
71298 */
71300  int i;
71301  sqlite3 *db;
71302  Db *aDb;
71303  int nDb;
71304  db = p->db;
71305  aDb = db->aDb;
71306  nDb = db->nDb;
71307  for(i=0; i<nDb; i++){
71308  if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
71309  sqlite3BtreeLeave(aDb[i].pBt);
71310  }
71311  }
71312 }
71314  if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
71315  vdbeLeave(p);
71316 }
71317 #endif
71318 
71319 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
71320 /*
71321 ** Print a single opcode. This routine is used for debugging only.
71322 */
71323 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
71324  char *zP4;
71325  char zPtr[50];
71326  char zCom[100];
71327  static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
71328  if( pOut==0 ) pOut = stdout;
71329  zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
71330 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71331  displayComment(pOp, zP4, zCom, sizeof(zCom));
71332 #else
71333  zCom[0] = 0;
71334 #endif
71335  /* NB: The sqlite3OpcodeName() function is implemented by code created
71336  ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
71337  ** information from the vdbe.c source text */
71338  fprintf(pOut, zFormat1, pc,
71339  sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
71340  zCom
71341  );
71342  fflush(pOut);
71343 }
71344 #endif
71345 
71346 /*
71347 ** Release an array of N Mem elements
71348 */
71349 static void releaseMemArray(Mem *p, int N){
71350  if( p && N ){
71351  Mem *pEnd = &p[N];
71352  sqlite3 *db = p->db;
71353  if( db->pnBytesFreed ){
71354  do{
71355  if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
71356  }while( (++p)<pEnd );
71357  return;
71358  }
71359  do{
71360  assert( (&p[1])==pEnd || p[0].db==p[1].db );
71361  assert( sqlite3VdbeCheckMemInvariants(p) );
71362 
71363  /* This block is really an inlined version of sqlite3VdbeMemRelease()
71364  ** that takes advantage of the fact that the memory cell value is
71365  ** being set to NULL after releasing any dynamic resources.
71366  **
71367  ** The justification for duplicating code is that according to
71368  ** callgrind, this causes a certain test case to hit the CPU 4.7
71369  ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
71370  ** sqlite3MemRelease() were called from here. With -O2, this jumps
71371  ** to 6.6 percent. The test case is inserting 1000 rows into a table
71372  ** with no indexes using a single prepared INSERT statement, bind()
71373  ** and reset(). Inserts are grouped into a transaction.
71374  */
71375  testcase( p->flags & MEM_Agg );
71376  testcase( p->flags & MEM_Dyn );
71377  testcase( p->flags & MEM_Frame );
71378  testcase( p->flags & MEM_RowSet );
71381  }else if( p->szMalloc ){
71382  sqlite3DbFree(db, p->zMalloc);
71383  p->szMalloc = 0;
71384  }
71385 
71386  p->flags = MEM_Undefined;
71387  }while( (++p)<pEnd );
71388  }
71389 }
71390 
71391 /*
71392 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
71393 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
71394 */
71396  int i;
71397  Mem *aMem = VdbeFrameMem(p);
71398  VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
71399  for(i=0; i<p->nChildCsr; i++){
71400  sqlite3VdbeFreeCursor(p->v, apCsr[i]);
71401  }
71402  releaseMemArray(aMem, p->nChildMem);
71403  sqlite3VdbeDeleteAuxData(p->v->db, &p->pAuxData, -1, 0);
71404  sqlite3DbFree(p->v->db, p);
71405 }
71406 
71407 #ifndef SQLITE_OMIT_EXPLAIN
71408 /*
71409 ** Give a listing of the program in the virtual machine.
71410 **
71411 ** The interface is the same as sqlite3VdbeExec(). But instead of
71412 ** running the code, it invokes the callback once for each instruction.
71413 ** This feature is used to implement "EXPLAIN".
71414 **
71415 ** When p->explain==1, each instruction is listed. When
71416 ** p->explain==2, only OP_Explain instructions are listed and these
71417 ** are shown in a different format. p->explain==2 is used to implement
71418 ** EXPLAIN QUERY PLAN.
71419 **
71420 ** When p->explain==1, first the main program is listed, then each of
71421 ** the trigger subprograms are listed one by one.
71422 */
71424  Vdbe *p /* The VDBE */
71425 ){
71426  int nRow; /* Stop when row count reaches this */
71427  int nSub = 0; /* Number of sub-vdbes seen so far */
71428  SubProgram **apSub = 0; /* Array of sub-vdbes */
71429  Mem *pSub = 0; /* Memory cell hold array of subprogs */
71430  sqlite3 *db = p->db; /* The database connection */
71431  int i; /* Loop counter */
71432  int rc = SQLITE_OK; /* Return code */
71433  Mem *pMem = &p->aMem[1]; /* First Mem of result set */
71434 
71435  assert( p->explain );
71436  assert( p->magic==VDBE_MAGIC_RUN );
71437  assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
71438 
71439  /* Even though this opcode does not use dynamic strings for
71440  ** the result, result columns may become dynamic if the user calls
71441  ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
71442  */
71443  releaseMemArray(pMem, 8);
71444  p->pResultSet = 0;
71445 
71446  if( p->rc==SQLITE_NOMEM_BKPT ){
71447  /* This happens if a malloc() inside a call to sqlite3_column_text() or
71448  ** sqlite3_column_text16() failed. */
71449  sqlite3OomFault(db);
71450  return SQLITE_ERROR;
71451  }
71452 
71453  /* When the number of output rows reaches nRow, that means the
71454  ** listing has finished and sqlite3_step() should return SQLITE_DONE.
71455  ** nRow is the sum of the number of rows in the main program, plus
71456  ** the sum of the number of rows in all trigger subprograms encountered
71457  ** so far. The nRow value will increase as new trigger subprograms are
71458  ** encountered, but p->pc will eventually catch up to nRow.
71459  */
71460  nRow = p->nOp;
71461  if( p->explain==1 ){
71462  /* The first 8 memory cells are used for the result set. So we will
71463  ** commandeer the 9th cell to use as storage for an array of pointers
71464  ** to trigger subprograms. The VDBE is guaranteed to have at least 9
71465  ** cells. */
71466  assert( p->nMem>9 );
71467  pSub = &p->aMem[9];
71468  if( pSub->flags&MEM_Blob ){
71469  /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
71470  ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
71471  nSub = pSub->n/sizeof(Vdbe*);
71472  apSub = (SubProgram **)pSub->z;
71473  }
71474  for(i=0; i<nSub; i++){
71475  nRow += apSub[i]->nOp;
71476  }
71477  }
71478 
71479  do{
71480  i = p->pc++;
71481  }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
71482  if( i>=nRow ){
71483  p->rc = SQLITE_OK;
71484  rc = SQLITE_DONE;
71485  }else if( db->u1.isInterrupted ){
71486  p->rc = SQLITE_INTERRUPT;
71487  rc = SQLITE_ERROR;
71489  }else{
71490  char *zP4;
71491  Op *pOp;
71492  if( i<p->nOp ){
71493  /* The output line number is small enough that we are still in the
71494  ** main program. */
71495  pOp = &p->aOp[i];
71496  }else{
71497  /* We are currently listing subprograms. Figure out which one and
71498  ** pick up the appropriate opcode. */
71499  int j;
71500  i -= p->nOp;
71501  for(j=0; i>=apSub[j]->nOp; j++){
71502  i -= apSub[j]->nOp;
71503  }
71504  pOp = &apSub[j]->aOp[i];
71505  }
71506  if( p->explain==1 ){
71507  pMem->flags = MEM_Int;
71508  pMem->u.i = i; /* Program counter */
71509  pMem++;
71510 
71511  pMem->flags = MEM_Static|MEM_Str|MEM_Term;
71512  pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
71513  assert( pMem->z!=0 );
71514  pMem->n = sqlite3Strlen30(pMem->z);
71515  pMem->enc = SQLITE_UTF8;
71516  pMem++;
71517 
71518  /* When an OP_Program opcode is encounter (the only opcode that has
71519  ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
71520  ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
71521  ** has not already been seen.
71522  */
71523  if( pOp->p4type==P4_SUBPROGRAM ){
71524  int nByte = (nSub+1)*sizeof(SubProgram*);
71525  int j;
71526  for(j=0; j<nSub; j++){
71527  if( apSub[j]==pOp->p4.pProgram ) break;
71528  }
71529  if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
71530  apSub = (SubProgram **)pSub->z;
71531  apSub[nSub++] = pOp->p4.pProgram;
71532  pSub->flags |= MEM_Blob;
71533  pSub->n = nSub*sizeof(SubProgram*);
71534  }
71535  }
71536  }
71537 
71538  pMem->flags = MEM_Int;
71539  pMem->u.i = pOp->p1; /* P1 */
71540  pMem++;
71541 
71542  pMem->flags = MEM_Int;
71543  pMem->u.i = pOp->p2; /* P2 */
71544  pMem++;
71545 
71546  pMem->flags = MEM_Int;
71547  pMem->u.i = pOp->p3; /* P3 */
71548  pMem++;
71549 
71550  if( sqlite3VdbeMemClearAndResize(pMem, 100) ){ /* P4 */
71551  assert( p->db->mallocFailed );
71552  return SQLITE_ERROR;
71553  }
71554  pMem->flags = MEM_Str|MEM_Term;
71555  zP4 = displayP4(pOp, pMem->z, pMem->szMalloc);
71556  if( zP4!=pMem->z ){
71557  sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
71558  }else{
71559  assert( pMem->z!=0 );
71560  pMem->n = sqlite3Strlen30(pMem->z);
71561  pMem->enc = SQLITE_UTF8;
71562  }
71563  pMem++;
71564 
71565  if( p->explain==1 ){
71566  if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
71567  assert( p->db->mallocFailed );
71568  return SQLITE_ERROR;
71569  }
71570  pMem->flags = MEM_Str|MEM_Term;
71571  pMem->n = 2;
71572  sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
71573  pMem->enc = SQLITE_UTF8;
71574  pMem++;
71575 
71576 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
71577  if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
71578  assert( p->db->mallocFailed );
71579  return SQLITE_ERROR;
71580  }
71581  pMem->flags = MEM_Str|MEM_Term;
71582  pMem->n = displayComment(pOp, zP4, pMem->z, 500);
71583  pMem->enc = SQLITE_UTF8;
71584 #else
71585  pMem->flags = MEM_Null; /* Comment */
71586 #endif
71587  }
71588 
71589  p->nResColumn = 8 - 4*(p->explain-1);
71590  p->pResultSet = &p->aMem[1];
71591  p->rc = SQLITE_OK;
71592  rc = SQLITE_ROW;
71593  }
71594  return rc;
71595 }
71596 #endif /* SQLITE_OMIT_EXPLAIN */
71597 
71598 #ifdef SQLITE_DEBUG
71599 /*
71600 ** Print the SQL that was used to generate a VDBE program.
71601 */
71602 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
71603  const char *z = 0;
71604  if( p->zSql ){
71605  z = p->zSql;
71606  }else if( p->nOp>=1 ){
71607  const VdbeOp *pOp = &p->aOp[0];
71608  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
71609  z = pOp->p4.z;
71610  while( sqlite3Isspace(*z) ) z++;
71611  }
71612  }
71613  if( z ) printf("SQL: [%s]\n", z);
71614 }
71615 #endif
71616 
71617 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
71618 /*
71619 ** Print an IOTRACE message showing SQL content.
71620 */
71622  int nOp = p->nOp;
71623  VdbeOp *pOp;
71624  if( sqlite3IoTrace==0 ) return;
71625  if( nOp<1 ) return;
71626  pOp = &p->aOp[0];
71627  if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
71628  int i, j;
71629  char z[1000];
71630  sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
71631  for(i=0; sqlite3Isspace(z[i]); i++){}
71632  for(j=0; z[i]; i++){
71633  if( sqlite3Isspace(z[i]) ){
71634  if( z[i-1]!=' ' ){
71635  z[j++] = ' ';
71636  }
71637  }else{
71638  z[j++] = z[i];
71639  }
71640  }
71641  z[j] = 0;
71642  sqlite3IoTrace("SQL %s\n", z);
71643  }
71644 }
71645 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
71646 
71647 /* An instance of this object describes bulk memory available for use
71648 ** by subcomponents of a prepared statement. Space is allocated out
71649 ** of a ReusableSpace object by the allocSpace() routine below.
71650 */
71652  u8 *pSpace; /* Available memory */
71653  int nFree; /* Bytes of available memory */
71654  int nNeeded; /* Total bytes that could not be allocated */
71655 };
71656 
71657 /* Try to allocate nByte bytes of 8-byte aligned bulk memory for pBuf
71658 ** from the ReusableSpace object. Return a pointer to the allocated
71659 ** memory on success. If insufficient memory is available in the
71660 ** ReusableSpace object, increase the ReusableSpace.nNeeded
71661 ** value by the amount needed and return NULL.
71662 **
71663 ** If pBuf is not initially NULL, that means that the memory has already
71664 ** been allocated by a prior call to this routine, so just return a copy
71665 ** of pBuf and leave ReusableSpace unchanged.
71666 **
71667 ** This allocator is employed to repurpose unused slots at the end of the
71668 ** opcode array of prepared state for other memory needs of the prepared
71669 ** statement.
71670 */
71671 static void *allocSpace(
71672  struct ReusableSpace *p, /* Bulk memory available for allocation */
71673  void *pBuf, /* Pointer to a prior allocation */
71674  int nByte /* Bytes of memory needed */
71675 ){
71677  if( pBuf==0 ){
71678  nByte = ROUND8(nByte);
71679  if( nByte <= p->nFree ){
71680  p->nFree -= nByte;
71681  pBuf = &p->pSpace[p->nFree];
71682  }else{
71683  p->nNeeded += nByte;
71684  }
71685  }
71686  assert( EIGHT_BYTE_ALIGNMENT(pBuf) );
71687  return pBuf;
71688 }
71689 
71690 /*
71691 ** Rewind the VDBE back to the beginning in preparation for
71692 ** running it.
71693 */
71695 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
71696  int i;
71697 #endif
71698  assert( p!=0 );
71699  assert( p->magic==VDBE_MAGIC_INIT );
71700 
71701  /* There should be at least one opcode.
71702  */
71703  assert( p->nOp>0 );
71704 
71705  /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
71706  p->magic = VDBE_MAGIC_RUN;
71707 
71708 #ifdef SQLITE_DEBUG
71709  for(i=0; i<p->nMem; i++){
71710  assert( p->aMem[i].db==p->db );
71711  }
71712 #endif
71713  p->pc = -1;
71714  p->rc = SQLITE_OK;
71715  p->errorAction = OE_Abort;
71716  p->nChange = 0;
71717  p->cacheCtr = 1;
71718  p->minWriteFileFormat = 255;
71719  p->iStatement = 0;
71720  p->nFkConstraint = 0;
71721 #ifdef VDBE_PROFILE
71722  for(i=0; i<p->nOp; i++){
71723  p->aOp[i].cnt = 0;
71724  p->aOp[i].cycles = 0;
71725  }
71726 #endif
71727 }
71728 
71729 /*
71730 ** Prepare a virtual machine for execution for the first time after
71731 ** creating the virtual machine. This involves things such
71732 ** as allocating registers and initializing the program counter.
71733 ** After the VDBE has be prepped, it can be executed by one or more
71734 ** calls to sqlite3VdbeExec().
71735 **
71736 ** This function may be called exactly once on each virtual machine.
71737 ** After this routine is called the VM has been "packaged" and is ready
71738 ** to run. After this routine is called, further calls to
71739 ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
71740 ** the Vdbe from the Parse object that helped generate it so that the
71741 ** the Vdbe becomes an independent entity and the Parse object can be
71742 ** destroyed.
71743 **
71744 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
71745 ** to its initial state after it has been run.
71746 */
71748  Vdbe *p, /* The VDBE */
71749  Parse *pParse /* Parsing context */
71750 ){
71751  sqlite3 *db; /* The database connection */
71752  int nVar; /* Number of parameters */
71753  int nMem; /* Number of VM memory registers */
71754  int nCursor; /* Number of cursors required */
71755  int nArg; /* Number of arguments in subprograms */
71756  int nOnce; /* Number of OP_Once instructions */
71757  int n; /* Loop counter */
71758  struct ReusableSpace x; /* Reusable bulk memory */
71759 
71760  assert( p!=0 );
71761  assert( p->nOp>0 );
71762  assert( pParse!=0 );
71763  assert( p->magic==VDBE_MAGIC_INIT );
71764  assert( pParse==p->pParse );
71765  db = p->db;
71766  assert( db->mallocFailed==0 );
71767  nVar = pParse->nVar;
71768  nMem = pParse->nMem;
71769  nCursor = pParse->nTab;
71770  nArg = pParse->nMaxArg;
71771  nOnce = pParse->nOnce;
71772  if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
71773 
71774  /* Each cursor uses a memory cell. The first cursor (cursor 0) can
71775  ** use aMem[0] which is not otherwise used by the VDBE program. Allocate
71776  ** space at the end of aMem[] for cursors 1 and greater.
71777  ** See also: allocateCursor().
71778  */
71779  nMem += nCursor;
71780  if( nCursor==0 && nMem>0 ) nMem++; /* Space for aMem[0] even if not used */
71781 
71782  /* Figure out how much reusable memory is available at the end of the
71783  ** opcode array. This extra memory will be reallocated for other elements
71784  ** of the prepared statement.
71785  */
71786  n = ROUND8(sizeof(Op)*p->nOp); /* Bytes of opcode memory used */
71787  x.pSpace = &((u8*)p->aOp)[n]; /* Unused opcode memory */
71788  assert( EIGHT_BYTE_ALIGNMENT(x.pSpace) );
71789  x.nFree = ROUNDDOWN8(pParse->szOpAlloc - n); /* Bytes of unused memory */
71790  assert( x.nFree>=0 );
71791  if( x.nFree>0 ){
71792  memset(x.pSpace, 0, x.nFree);
71793  assert( EIGHT_BYTE_ALIGNMENT(&x.pSpace[x.nFree]) );
71794  }
71795 
71796  resolveP2Values(p, &nArg);
71797  p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
71798  if( pParse->explain && nMem<10 ){
71799  nMem = 10;
71800  }
71801  p->expired = 0;
71802 
71803  /* Memory for registers, parameters, cursor, etc, is allocated in one or two
71804  ** passes. On the first pass, we try to reuse unused memory at the
71805  ** end of the opcode array. If we are unable to satisfy all memory
71806  ** requirements by reusing the opcode array tail, then the second
71807  ** pass will fill in the remainder using a fresh memory allocation.
71808  **
71809  ** This two-pass approach that reuses as much memory as possible from
71810  ** the leftover memory at the end of the opcode array. This can significantly
71811  ** reduce the amount of memory held by a prepared statement.
71812  */
71813  do {
71814  x.nNeeded = 0;
71815  p->aMem = allocSpace(&x, p->aMem, nMem*sizeof(Mem));
71816  p->aVar = allocSpace(&x, p->aVar, nVar*sizeof(Mem));
71817  p->apArg = allocSpace(&x, p->apArg, nArg*sizeof(Mem*));
71818  p->apCsr = allocSpace(&x, p->apCsr, nCursor*sizeof(VdbeCursor*));
71819  p->aOnceFlag = allocSpace(&x, p->aOnceFlag, nOnce);
71820 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
71821  p->anExec = allocSpace(&x, p->anExec, p->nOp*sizeof(i64));
71822 #endif
71823  if( x.nNeeded==0 ) break;
71824  x.pSpace = p->pFree = sqlite3DbMallocZero(db, x.nNeeded);
71825  x.nFree = x.nNeeded;
71826  }while( !db->mallocFailed );
71827 
71828  p->nCursor = nCursor;
71829  p->nOnceFlag = nOnce;
71830  if( p->aVar ){
71831  p->nVar = (ynVar)nVar;
71832  for(n=0; n<nVar; n++){
71833  p->aVar[n].flags = MEM_Null;
71834  p->aVar[n].db = db;
71835  }
71836  }
71837  p->nzVar = pParse->nzVar;
71838  p->azVar = pParse->azVar;
71839  pParse->nzVar = 0;
71840  pParse->azVar = 0;
71841  if( p->aMem ){
71842  p->nMem = nMem;
71843  for(n=0; n<nMem; n++){
71844  p->aMem[n].flags = MEM_Undefined;
71845  p->aMem[n].db = db;
71846  }
71847  }
71848  p->explain = pParse->explain;
71849  sqlite3VdbeRewind(p);
71850 }
71851 
71852 /*
71853 ** Close a VDBE cursor and release all the resources that cursor
71854 ** happens to hold.
71855 */
71857  if( pCx==0 ){
71858  return;
71859  }
71860  assert( pCx->pBt==0 || pCx->eCurType==CURTYPE_BTREE );
71861  switch( pCx->eCurType ){
71862  case CURTYPE_SORTER: {
71863  sqlite3VdbeSorterClose(p->db, pCx);
71864  break;
71865  }
71866  case CURTYPE_BTREE: {
71867  if( pCx->pBt ){
71868  sqlite3BtreeClose(pCx->pBt);
71869  /* The pCx->pCursor will be close automatically, if it exists, by
71870  ** the call above. */
71871  }else{
71872  assert( pCx->uc.pCursor!=0 );
71874  }
71875  break;
71876  }
71877 #ifndef SQLITE_OMIT_VIRTUALTABLE
71878  case CURTYPE_VTAB: {
71879  sqlite3_vtab_cursor *pVCur = pCx->uc.pVCur;
71880  const sqlite3_module *pModule = pVCur->pVtab->pModule;
71881  assert( pVCur->pVtab->nRef>0 );
71882  pVCur->pVtab->nRef--;
71883  pModule->xClose(pVCur);
71884  break;
71885  }
71886 #endif
71887  }
71888 }
71889 
71890 /*
71891 ** Close all cursors in the current frame.
71892 */
71893 static void closeCursorsInFrame(Vdbe *p){
71894  if( p->apCsr ){
71895  int i;
71896  for(i=0; i<p->nCursor; i++){
71897  VdbeCursor *pC = p->apCsr[i];
71898  if( pC ){
71899  sqlite3VdbeFreeCursor(p, pC);
71900  p->apCsr[i] = 0;
71901  }
71902  }
71903  }
71904 }
71905 
71906 /*
71907 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
71908 ** is used, for example, when a trigger sub-program is halted to restore
71909 ** control to the main program.
71910 */
71912  Vdbe *v = pFrame->v;
71914 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
71915  v->anExec = pFrame->anExec;
71916 #endif
71917  v->aOnceFlag = pFrame->aOnceFlag;
71918  v->nOnceFlag = pFrame->nOnceFlag;
71919  v->aOp = pFrame->aOp;
71920  v->nOp = pFrame->nOp;
71921  v->aMem = pFrame->aMem;
71922  v->nMem = pFrame->nMem;
71923  v->apCsr = pFrame->apCsr;
71924  v->nCursor = pFrame->nCursor;
71925  v->db->lastRowid = pFrame->lastRowid;
71926  v->nChange = pFrame->nChange;
71927  v->db->nChange = pFrame->nDbChange;
71928  sqlite3VdbeDeleteAuxData(v->db, &v->pAuxData, -1, 0);
71929  v->pAuxData = pFrame->pAuxData;
71930  pFrame->pAuxData = 0;
71931  return pFrame->pc;
71932 }
71933 
71934 /*
71935 ** Close all cursors.
71936 **
71937 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
71938 ** cell array. This is necessary as the memory cell array may contain
71939 ** pointers to VdbeFrame objects, which may in turn contain pointers to
71940 ** open cursors.
71941 */
71942 static void closeAllCursors(Vdbe *p){
71943  if( p->pFrame ){
71944  VdbeFrame *pFrame;
71945  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
71946  sqlite3VdbeFrameRestore(pFrame);
71947  p->pFrame = 0;
71948  p->nFrame = 0;
71949  }
71950  assert( p->nFrame==0 );
71952  if( p->aMem ){
71953  releaseMemArray(p->aMem, p->nMem);
71954  }
71955  while( p->pDelFrame ){
71956  VdbeFrame *pDel = p->pDelFrame;
71957  p->pDelFrame = pDel->pParent;
71958  sqlite3VdbeFrameDelete(pDel);
71959  }
71960 
71961  /* Delete any auxdata allocations made by the VM */
71962  if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p->db, &p->pAuxData, -1, 0);
71963  assert( p->pAuxData==0 );
71964 }
71965 
71966 /*
71967 ** Clean up the VM after a single run.
71968 */
71969 static void Cleanup(Vdbe *p){
71970  sqlite3 *db = p->db;
71971 
71972 #ifdef SQLITE_DEBUG
71973  /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
71974  ** Vdbe.aMem[] arrays have already been cleaned up. */
71975  int i;
71976  if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
71977  if( p->aMem ){
71978  for(i=0; i<p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
71979  }
71980 #endif
71981 
71982  sqlite3DbFree(db, p->zErrMsg);
71983  p->zErrMsg = 0;
71984  p->pResultSet = 0;
71985 }
71986 
71987 /*
71988 ** Set the number of result columns that will be returned by this SQL
71989 ** statement. This is now set at compile time, rather than during
71990 ** execution of the vdbe program so that sqlite3_column_count() can
71991 ** be called on an SQL statement before sqlite3_step().
71992 */
71993 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
71994  Mem *pColName;
71995  int n;
71996  sqlite3 *db = p->db;
71997 
71999  sqlite3DbFree(db, p->aColName);
72000  n = nResColumn*COLNAME_N;
72001  p->nResColumn = (u16)nResColumn;
72002  p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
72003  if( p->aColName==0 ) return;
72004  while( n-- > 0 ){
72005  pColName->flags = MEM_Null;
72006  pColName->db = p->db;
72007  pColName++;
72008  }
72009 }
72010 
72011 /*
72012 ** Set the name of the idx'th column to be returned by the SQL statement.
72013 ** zName must be a pointer to a nul terminated string.
72014 **
72015 ** This call must be made after a call to sqlite3VdbeSetNumCols().
72016 **
72017 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
72018 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
72019 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
72020 */
72022  Vdbe *p, /* Vdbe being configured */
72023  int idx, /* Index of column zName applies to */
72024  int var, /* One of the COLNAME_* constants */
72025  const char *zName, /* Pointer to buffer containing name */
72026  void (*xDel)(void*) /* Memory management strategy for zName */
72027 ){
72028  int rc;
72029  Mem *pColName;
72030  assert( idx<p->nResColumn );
72031  assert( var<COLNAME_N );
72032  if( p->db->mallocFailed ){
72033  assert( !zName || xDel!=SQLITE_DYNAMIC );
72034  return SQLITE_NOMEM_BKPT;
72035  }
72036  assert( p->aColName!=0 );
72037  pColName = &(p->aColName[idx+var*p->nResColumn]);
72038  rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
72039  assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
72040  return rc;
72041 }
72042 
72043 /*
72044 ** A read or write transaction may or may not be active on database handle
72045 ** db. If a transaction is active, commit it. If there is a
72046 ** write-transaction spanning more than one database file, this routine
72047 ** takes care of the master journal trickery.
72048 */
72049 static int vdbeCommit(sqlite3 *db, Vdbe *p){
72050  int i;
72051  int nTrans = 0; /* Number of databases with an active write-transaction
72052  ** that are candidates for a two-phase commit using a
72053  ** master-journal */
72054  int rc = SQLITE_OK;
72055  int needXcommit = 0;
72056 
72057 #ifdef SQLITE_OMIT_VIRTUALTABLE
72058  /* With this option, sqlite3VtabSync() is defined to be simply
72059  ** SQLITE_OK so p is not used.
72060  */
72061  UNUSED_PARAMETER(p);
72062 #endif
72063 
72064  /* Before doing anything else, call the xSync() callback for any
72065  ** virtual module tables written in this transaction. This has to
72066  ** be done before determining whether a master journal file is
72067  ** required, as an xSync() callback may add an attached database
72068  ** to the transaction.
72069  */
72070  rc = sqlite3VtabSync(db, p);
72071 
72072  /* This loop determines (a) if the commit hook should be invoked and
72073  ** (b) how many database files have open write transactions, not
72074  ** including the temp database. (b) is important because if more than
72075  ** one database file has an open write transaction, a master journal
72076  ** file is required for an atomic commit.
72077  */
72078  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72079  Btree *pBt = db->aDb[i].pBt;
72080  if( sqlite3BtreeIsInTrans(pBt) ){
72081  /* Whether or not a database might need a master journal depends upon
72082  ** its journal mode (among other things). This matrix determines which
72083  ** journal modes use a master journal and which do not */
72084  static const u8 aMJNeeded[] = {
72085  /* DELETE */ 1,
72086  /* PERSIST */ 1,
72087  /* OFF */ 0,
72088  /* TRUNCATE */ 1,
72089  /* MEMORY */ 0,
72090  /* WAL */ 0
72091  };
72092  Pager *pPager; /* Pager associated with pBt */
72093  needXcommit = 1;
72094  sqlite3BtreeEnter(pBt);
72095  pPager = sqlite3BtreePager(pBt);
72097  && aMJNeeded[sqlite3PagerGetJournalMode(pPager)]
72098  ){
72099  assert( i!=1 );
72100  nTrans++;
72101  }
72102  rc = sqlite3PagerExclusiveLock(pPager);
72103  sqlite3BtreeLeave(pBt);
72104  }
72105  }
72106  if( rc!=SQLITE_OK ){
72107  return rc;
72108  }
72109 
72110  /* If there are any write-transactions at all, invoke the commit hook */
72111  if( needXcommit && db->xCommitCallback ){
72112  rc = db->xCommitCallback(db->pCommitArg);
72113  if( rc ){
72115  }
72116  }
72117 
72118  /* The simple case - no more than one database file (not counting the
72119  ** TEMP database) has a transaction active. There is no need for the
72120  ** master-journal.
72121  **
72122  ** If the return value of sqlite3BtreeGetFilename() is a zero length
72123  ** string, it means the main database is :memory: or a temp file. In
72124  ** that case we do not support atomic multi-file commits, so use the
72125  ** simple case then too.
72126  */
72128  || nTrans<=1
72129  ){
72130  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72131  Btree *pBt = db->aDb[i].pBt;
72132  if( pBt ){
72133  rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
72134  }
72135  }
72136 
72137  /* Do the commit only if all databases successfully complete phase 1.
72138  ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
72139  ** IO error while deleting or truncating a journal file. It is unlikely,
72140  ** but could happen. In this case abandon processing and return the error.
72141  */
72142  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72143  Btree *pBt = db->aDb[i].pBt;
72144  if( pBt ){
72145  rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
72146  }
72147  }
72148  if( rc==SQLITE_OK ){
72149  sqlite3VtabCommit(db);
72150  }
72151  }
72152 
72153  /* The complex case - There is a multi-file write-transaction active.
72154  ** This requires a master journal file to ensure the transaction is
72155  ** committed atomically.
72156  */
72157 #ifndef SQLITE_OMIT_DISKIO
72158  else{
72159  sqlite3_vfs *pVfs = db->pVfs;
72160  char *zMaster = 0; /* File-name for the master journal */
72161  char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
72162  sqlite3_file *pMaster = 0;
72163  i64 offset = 0;
72164  int res;
72165  int retryCount = 0;
72166  int nMainFile;
72167 
72168  /* Select a master journal file name */
72169  nMainFile = sqlite3Strlen30(zMainFile);
72170  zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
72171  if( zMaster==0 ) return SQLITE_NOMEM_BKPT;
72172  do {
72173  u32 iRandom;
72174  if( retryCount ){
72175  if( retryCount>100 ){
72176  sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
72177  sqlite3OsDelete(pVfs, zMaster, 0);
72178  break;
72179  }else if( retryCount==1 ){
72180  sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
72181  }
72182  }
72183  retryCount++;
72184  sqlite3_randomness(sizeof(iRandom), &iRandom);
72185  sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
72186  (iRandom>>8)&0xffffff, iRandom&0xff);
72187  /* The antipenultimate character of the master journal name must
72188  ** be "9" to avoid name collisions when using 8+3 filenames. */
72189  assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
72190  sqlite3FileSuffix3(zMainFile, zMaster);
72191  rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
72192  }while( rc==SQLITE_OK && res );
72193  if( rc==SQLITE_OK ){
72194  /* Open the master journal. */
72195  rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
72198  );
72199  }
72200  if( rc!=SQLITE_OK ){
72201  sqlite3DbFree(db, zMaster);
72202  return rc;
72203  }
72204 
72205  /* Write the name of each database file in the transaction into the new
72206  ** master journal file. If an error occurs at this point close
72207  ** and delete the master journal file. All the individual journal files
72208  ** still have 'null' as the master journal pointer, so they will roll
72209  ** back independently if a failure occurs.
72210  */
72211  for(i=0; i<db->nDb; i++){
72212  Btree *pBt = db->aDb[i].pBt;
72213  if( sqlite3BtreeIsInTrans(pBt) ){
72214  char const *zFile = sqlite3BtreeGetJournalname(pBt);
72215  if( zFile==0 ){
72216  continue; /* Ignore TEMP and :memory: databases */
72217  }
72218  assert( zFile[0]!=0 );
72219  rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
72220  offset += sqlite3Strlen30(zFile)+1;
72221  if( rc!=SQLITE_OK ){
72222  sqlite3OsCloseFree(pMaster);
72223  sqlite3OsDelete(pVfs, zMaster, 0);
72224  sqlite3DbFree(db, zMaster);
72225  return rc;
72226  }
72227  }
72228  }
72229 
72230  /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
72231  ** flag is set this is not required.
72232  */
72234  && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
72235  ){
72236  sqlite3OsCloseFree(pMaster);
72237  sqlite3OsDelete(pVfs, zMaster, 0);
72238  sqlite3DbFree(db, zMaster);
72239  return rc;
72240  }
72241 
72242  /* Sync all the db files involved in the transaction. The same call
72243  ** sets the master journal pointer in each individual journal. If
72244  ** an error occurs here, do not delete the master journal file.
72245  **
72246  ** If the error occurs during the first call to
72247  ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
72248  ** master journal file will be orphaned. But we cannot delete it,
72249  ** in case the master journal file name was written into the journal
72250  ** file before the failure occurred.
72251  */
72252  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
72253  Btree *pBt = db->aDb[i].pBt;
72254  if( pBt ){
72255  rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
72256  }
72257  }
72258  sqlite3OsCloseFree(pMaster);
72259  assert( rc!=SQLITE_BUSY );
72260  if( rc!=SQLITE_OK ){
72261  sqlite3DbFree(db, zMaster);
72262  return rc;
72263  }
72264 
72265  /* Delete the master journal file. This commits the transaction. After
72266  ** doing this the directory is synced again before any individual
72267  ** transaction files are deleted.
72268  */
72269  rc = sqlite3OsDelete(pVfs, zMaster, 1);
72270  sqlite3DbFree(db, zMaster);
72271  zMaster = 0;
72272  if( rc ){
72273  return rc;
72274  }
72275 
72276  /* All files and directories have already been synced, so the following
72277  ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
72278  ** deleting or truncating journals. If something goes wrong while
72279  ** this is happening we don't really care. The integrity of the
72280  ** transaction is already guaranteed, but some stray 'cold' journals
72281  ** may be lying around. Returning an error code won't help matters.
72282  */
72285  for(i=0; i<db->nDb; i++){
72286  Btree *pBt = db->aDb[i].pBt;
72287  if( pBt ){
72289  }
72290  }
72293 
72294  sqlite3VtabCommit(db);
72295  }
72296 #endif
72297 
72298  return rc;
72299 }
72300 
72301 /*
72302 ** This routine checks that the sqlite3.nVdbeActive count variable
72303 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
72304 ** currently active. An assertion fails if the two counts do not match.
72305 ** This is an internal self-check only - it is not an essential processing
72306 ** step.
72307 **
72308 ** This is a no-op if NDEBUG is defined.
72309 */
72310 #ifndef NDEBUG
72311 static void checkActiveVdbeCnt(sqlite3 *db){
72312  Vdbe *p;
72313  int cnt = 0;
72314  int nWrite = 0;
72315  int nRead = 0;
72316  p = db->pVdbe;
72317  while( p ){
72318  if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
72319  cnt++;
72320  if( p->readOnly==0 ) nWrite++;
72321  if( p->bIsReader ) nRead++;
72322  }
72323  p = p->pNext;
72324  }
72325  assert( cnt==db->nVdbeActive );
72326  assert( nWrite==db->nVdbeWrite );
72327  assert( nRead==db->nVdbeRead );
72328 }
72329 #else
72330 #define checkActiveVdbeCnt(x)
72331 #endif
72332 
72333 /*
72334 ** If the Vdbe passed as the first argument opened a statement-transaction,
72335 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
72336 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
72337 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
72338 ** statement transaction is committed.
72339 **
72340 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
72341 ** Otherwise SQLITE_OK.
72342 */
72344  sqlite3 *const db = p->db;
72345  int rc = SQLITE_OK;
72346 
72347  /* If p->iStatement is greater than zero, then this Vdbe opened a
72348  ** statement transaction that should be closed here. The only exception
72349  ** is that an IO error may have occurred, causing an emergency rollback.
72350  ** In this case (db->nStatement==0), and there is nothing to do.
72351  */
72352  if( db->nStatement && p->iStatement ){
72353  int i;
72354  const int iSavepoint = p->iStatement-1;
72355 
72357  assert( db->nStatement>0 );
72358  assert( p->iStatement==(db->nStatement+db->nSavepoint) );
72359 
72360  for(i=0; i<db->nDb; i++){
72361  int rc2 = SQLITE_OK;
72362  Btree *pBt = db->aDb[i].pBt;
72363  if( pBt ){
72364  if( eOp==SAVEPOINT_ROLLBACK ){
72365  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
72366  }
72367  if( rc2==SQLITE_OK ){
72368  rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
72369  }
72370  if( rc==SQLITE_OK ){
72371  rc = rc2;
72372  }
72373  }
72374  }
72375  db->nStatement--;
72376  p->iStatement = 0;
72377 
72378  if( rc==SQLITE_OK ){
72379  if( eOp==SAVEPOINT_ROLLBACK ){
72380  rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
72381  }
72382  if( rc==SQLITE_OK ){
72383  rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
72384  }
72385  }
72386 
72387  /* If the statement transaction is being rolled back, also restore the
72388  ** database handles deferred constraint counter to the value it had when
72389  ** the statement transaction was opened. */
72390  if( eOp==SAVEPOINT_ROLLBACK ){
72391  db->nDeferredCons = p->nStmtDefCons;
72393  }
72394  }
72395  return rc;
72396 }
72397 
72398 /*
72399 ** This function is called when a transaction opened by the database
72400 ** handle associated with the VM passed as an argument is about to be
72401 ** committed. If there are outstanding deferred foreign key constraint
72402 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
72403 **
72404 ** If there are outstanding FK violations and this function returns
72405 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
72406 ** and write an error message to it. Then return SQLITE_ERROR.
72407 */
72408 #ifndef SQLITE_OMIT_FOREIGN_KEY
72410  sqlite3 *db = p->db;
72411  if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
72412  || (!deferred && p->nFkConstraint>0)
72413  ){
72415  p->errorAction = OE_Abort;
72416  sqlite3VdbeError(p, "FOREIGN KEY constraint failed");
72417  return SQLITE_ERROR;
72418  }
72419  return SQLITE_OK;
72420 }
72421 #endif
72422 
72423 /*
72424 ** This routine is called the when a VDBE tries to halt. If the VDBE
72425 ** has made changes and is in autocommit mode, then commit those
72426 ** changes. If a rollback is needed, then do the rollback.
72427 **
72428 ** This routine is the only way to move the state of a VM from
72429 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
72430 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
72431 **
72432 ** Return an error code. If the commit could not complete because of
72433 ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
72434 ** means the close did not happen and needs to be repeated.
72435 */
72437  int rc; /* Used to store transient return codes */
72438  sqlite3 *db = p->db;
72439 
72440  /* This function contains the logic that determines if a statement or
72441  ** transaction will be committed or rolled back as a result of the
72442  ** execution of this virtual machine.
72443  **
72444  ** If any of the following errors occur:
72445  **
72446  ** SQLITE_NOMEM
72447  ** SQLITE_IOERR
72448  ** SQLITE_FULL
72449  ** SQLITE_INTERRUPT
72450  **
72451  ** Then the internal cache might have been left in an inconsistent
72452  ** state. We need to rollback the statement transaction, if there is
72453  ** one, or the complete transaction if there is no statement transaction.
72454  */
72455 
72456  if( db->mallocFailed ){
72457  p->rc = SQLITE_NOMEM_BKPT;
72458  }
72459  if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
72460  closeAllCursors(p);
72461  if( p->magic!=VDBE_MAGIC_RUN ){
72462  return SQLITE_OK;
72463  }
72464  checkActiveVdbeCnt(db);
72465 
72466  /* No commit or rollback needed if the program never started or if the
72467  ** SQL statement does not read or write a database file. */
72468  if( p->pc>=0 && p->bIsReader ){
72469  int mrc; /* Primary error code from p->rc */
72470  int eStatementOp = 0;
72471  int isSpecialError; /* Set to true if a 'special' error */
72472 
72473  /* Lock all btrees used by the statement */
72474  sqlite3VdbeEnter(p);
72475 
72476  /* Check for one of the special errors */
72477  mrc = p->rc & 0xff;
72478  isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
72479  || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
72480  if( isSpecialError ){
72481  /* If the query was read-only and the error code is SQLITE_INTERRUPT,
72482  ** no rollback is necessary. Otherwise, at least a savepoint
72483  ** transaction must be rolled back to restore the database to a
72484  ** consistent state.
72485  **
72486  ** Even if the statement is read-only, it is important to perform
72487  ** a statement or transaction rollback operation. If the error
72488  ** occurred while writing to the journal, sub-journal or database
72489  ** file as part of an effort to free up cache space (see function
72490  ** pagerStress() in pager.c), the rollback is required to restore
72491  ** the pager to a consistent state.
72492  */
72493  if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
72494  if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
72495  eStatementOp = SAVEPOINT_ROLLBACK;
72496  }else{
72497  /* We are forced to roll back the active transaction. Before doing
72498  ** so, abort any other statements this handle currently has active.
72499  */
72502  db->autoCommit = 1;
72503  p->nChange = 0;
72504  }
72505  }
72506  }
72507 
72508  /* Check for immediate foreign key violations. */
72509  if( p->rc==SQLITE_OK ){
72510  sqlite3VdbeCheckFk(p, 0);
72511  }
72512 
72513  /* If the auto-commit flag is set and this is the only active writer
72514  ** VM, then we do either a commit or rollback of the current transaction.
72515  **
72516  ** Note: This block also runs if one of the special errors handled
72517  ** above has occurred.
72518  */
72519  if( !sqlite3VtabInSync(db)
72520  && db->autoCommit
72521  && db->nVdbeWrite==(p->readOnly==0)
72522  ){
72523  if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
72524  rc = sqlite3VdbeCheckFk(p, 1);
72525  if( rc!=SQLITE_OK ){
72526  if( NEVER(p->readOnly) ){
72527  sqlite3VdbeLeave(p);
72528  return SQLITE_ERROR;
72529  }
72531  }else{
72532  /* The auto-commit flag is true, the vdbe program was successful
72533  ** or hit an 'OR FAIL' constraint and there are no deferred foreign
72534  ** key constraints to hold up the transaction. This means a commit
72535  ** is required. */
72536  rc = vdbeCommit(db, p);
72537  }
72538  if( rc==SQLITE_BUSY && p->readOnly ){
72539  sqlite3VdbeLeave(p);
72540  return SQLITE_BUSY;
72541  }else if( rc!=SQLITE_OK ){
72542  p->rc = rc;
72544  p->nChange = 0;
72545  }else{
72546  db->nDeferredCons = 0;
72547  db->nDeferredImmCons = 0;
72548  db->flags &= ~SQLITE_DeferFKs;
72550  }
72551  }else{
72553  p->nChange = 0;
72554  }
72555  db->nStatement = 0;
72556  }else if( eStatementOp==0 ){
72557  if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
72558  eStatementOp = SAVEPOINT_RELEASE;
72559  }else if( p->errorAction==OE_Abort ){
72560  eStatementOp = SAVEPOINT_ROLLBACK;
72561  }else{
72564  db->autoCommit = 1;
72565  p->nChange = 0;
72566  }
72567  }
72568 
72569  /* If eStatementOp is non-zero, then a statement transaction needs to
72570  ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
72571  ** do so. If this operation returns an error, and the current statement
72572  ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
72573  ** current statement error code.
72574  */
72575  if( eStatementOp ){
72576  rc = sqlite3VdbeCloseStatement(p, eStatementOp);
72577  if( rc ){
72578  if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
72579  p->rc = rc;
72580  sqlite3DbFree(db, p->zErrMsg);
72581  p->zErrMsg = 0;
72582  }
72585  db->autoCommit = 1;
72586  p->nChange = 0;
72587  }
72588  }
72589 
72590  /* If this was an INSERT, UPDATE or DELETE and no statement transaction
72591  ** has been rolled back, update the database connection change-counter.
72592  */
72593  if( p->changeCntOn ){
72594  if( eStatementOp!=SAVEPOINT_ROLLBACK ){
72596  }else{
72597  sqlite3VdbeSetChanges(db, 0);
72598  }
72599  p->nChange = 0;
72600  }
72601 
72602  /* Release the locks */
72603  sqlite3VdbeLeave(p);
72604  }
72605 
72606  /* We have successfully halted and closed the VM. Record this fact. */
72607  if( p->pc>=0 ){
72608  db->nVdbeActive--;
72609  if( !p->readOnly ) db->nVdbeWrite--;
72610  if( p->bIsReader ) db->nVdbeRead--;
72611  assert( db->nVdbeActive>=db->nVdbeRead );
72612  assert( db->nVdbeRead>=db->nVdbeWrite );
72613  assert( db->nVdbeWrite>=0 );
72614  }
72615  p->magic = VDBE_MAGIC_HALT;
72616  checkActiveVdbeCnt(db);
72617  if( db->mallocFailed ){
72618  p->rc = SQLITE_NOMEM_BKPT;
72619  }
72620 
72621  /* If the auto-commit flag is set to true, then any locks that were held
72622  ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
72623  ** to invoke any required unlock-notify callbacks.
72624  */
72625  if( db->autoCommit ){
72627  }
72628 
72629  assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
72630  return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
72631 }
72632 
72633 
72634 /*
72635 ** Each VDBE holds the result of the most recent sqlite3_step() call
72636 ** in p->rc. This routine sets that result back to SQLITE_OK.
72637 */
72639  p->rc = SQLITE_OK;
72640 }
72641 
72642 /*
72643 ** Copy the error code and error message belonging to the VDBE passed
72644 ** as the first argument to its database handle (so that they will be
72645 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
72646 **
72647 ** This function does not clear the VDBE error code or message, just
72648 ** copies them to the database handle.
72649 */
72651  sqlite3 *db = p->db;
72652  int rc = p->rc;
72653  if( p->zErrMsg ){
72654  db->bBenignMalloc++;
72656  if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
72659  db->bBenignMalloc--;
72660  db->errCode = rc;
72661  }else{
72662  sqlite3Error(db, rc);
72663  }
72664  return rc;
72665 }
72666 
72667 #ifdef SQLITE_ENABLE_SQLLOG
72668 /*
72669 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
72670 ** invoke it.
72671 */
72672 static void vdbeInvokeSqllog(Vdbe *v){
72673  if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
72674  char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
72675  assert( v->db->init.busy==0 );
72676  if( zExpanded ){
72677  sqlite3GlobalConfig.xSqllog(
72678  sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
72679  );
72680  sqlite3DbFree(v->db, zExpanded);
72681  }
72682  }
72683 }
72684 #else
72685 # define vdbeInvokeSqllog(x)
72686 #endif
72687 
72688 /*
72689 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
72690 ** Write any error messages into *pzErrMsg. Return the result code.
72691 **
72692 ** After this routine is run, the VDBE should be ready to be executed
72693 ** again.
72694 **
72695 ** To look at it another way, this routine resets the state of the
72696 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
72697 ** VDBE_MAGIC_INIT.
72698 */
72700  sqlite3 *db;
72701  db = p->db;
72702 
72703  /* If the VM did not run to completion or if it encountered an
72704  ** error, then it might not have been halted properly. So halt
72705  ** it now.
72706  */
72707  sqlite3VdbeHalt(p);
72708 
72709  /* If the VDBE has be run even partially, then transfer the error code
72710  ** and error message from the VDBE into the main database structure. But
72711  ** if the VDBE has just been set to run but has not actually executed any
72712  ** instructions yet, leave the main database error information unchanged.
72713  */
72714  if( p->pc>=0 ){
72715  vdbeInvokeSqllog(p);
72717  sqlite3DbFree(db, p->zErrMsg);
72718  p->zErrMsg = 0;
72719  if( p->runOnlyOnce ) p->expired = 1;
72720  }else if( p->rc && p->expired ){
72721  /* The expired flag was set on the VDBE before the first call
72722  ** to sqlite3_step(). For consistency (since sqlite3_step() was
72723  ** called), set the database error in this case as well.
72724  */
72725  sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
72726  sqlite3DbFree(db, p->zErrMsg);
72727  p->zErrMsg = 0;
72728  }
72729 
72730  /* Reclaim all memory used by the VDBE
72731  */
72732  Cleanup(p);
72733 
72734  /* Save profiling information from this VDBE run.
72735  */
72736 #ifdef VDBE_PROFILE
72737  {
72738  FILE *out = fopen("vdbe_profile.out", "a");
72739  if( out ){
72740  int i;
72741  fprintf(out, "---- ");
72742  for(i=0; i<p->nOp; i++){
72743  fprintf(out, "%02x", p->aOp[i].opcode);
72744  }
72745  fprintf(out, "\n");
72746  if( p->zSql ){
72747  char c, pc = 0;
72748  fprintf(out, "-- ");
72749  for(i=0; (c = p->zSql[i])!=0; i++){
72750  if( pc=='\n' ) fprintf(out, "-- ");
72751  putc(c, out);
72752  pc = c;
72753  }
72754  if( pc!='\n' ) fprintf(out, "\n");
72755  }
72756  for(i=0; i<p->nOp; i++){
72757  char zHdr[100];
72758  sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
72759  p->aOp[i].cnt,
72760  p->aOp[i].cycles,
72761  p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
72762  );
72763  fprintf(out, "%s", zHdr);
72764  sqlite3VdbePrintOp(out, i, &p->aOp[i]);
72765  }
72766  fclose(out);
72767  }
72768  }
72769 #endif
72770  p->iCurrentTime = 0;
72771  p->magic = VDBE_MAGIC_INIT;
72772  return p->rc & db->errMask;
72773 }
72774 
72775 /*
72776 ** Clean up and delete a VDBE after execution. Return an integer which is
72777 ** the result code. Write any error message text into *pzErrMsg.
72778 */
72780  int rc = SQLITE_OK;
72781  if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
72782  rc = sqlite3VdbeReset(p);
72783  assert( (rc & p->db->errMask)==rc );
72784  }
72785  sqlite3VdbeDelete(p);
72786  return rc;
72787 }
72788 
72789 /*
72790 ** If parameter iOp is less than zero, then invoke the destructor for
72791 ** all auxiliary data pointers currently cached by the VM passed as
72792 ** the first argument.
72793 **
72794 ** Or, if iOp is greater than or equal to zero, then the destructor is
72795 ** only invoked for those auxiliary data pointers created by the user
72796 ** function invoked by the OP_Function opcode at instruction iOp of
72797 ** VM pVdbe, and only then if:
72798 **
72799 ** * the associated function parameter is the 32nd or later (counting
72800 ** from left to right), or
72801 **
72802 ** * the corresponding bit in argument mask is clear (where the first
72803 ** function parameter corresponds to bit 0 etc.).
72804 */
72805 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *db, AuxData **pp, int iOp, int mask){
72806  while( *pp ){
72807  AuxData *pAux = *pp;
72808  if( (iOp<0)
72809  || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
72810  ){
72811  testcase( pAux->iArg==31 );
72812  if( pAux->xDelete ){
72813  pAux->xDelete(pAux->pAux);
72814  }
72815  *pp = pAux->pNext;
72816  sqlite3DbFree(db, pAux);
72817  }else{
72818  pp= &pAux->pNext;
72819  }
72820  }
72821 }
72822 
72823 /*
72824 ** Free all memory associated with the Vdbe passed as the second argument,
72825 ** except for object itself, which is preserved.
72826 **
72827 ** The difference between this function and sqlite3VdbeDelete() is that
72828 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
72829 ** the database connection and frees the object itself.
72830 */
72832  SubProgram *pSub, *pNext;
72833  int i;
72834  assert( p->db==0 || p->db==db );
72835  releaseMemArray(p->aVar, p->nVar);
72837  for(pSub=p->pProgram; pSub; pSub=pNext){
72838  pNext = pSub->pNext;
72839  vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
72840  sqlite3DbFree(db, pSub);
72841  }
72842  for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
72843  sqlite3DbFree(db, p->azVar);
72844  vdbeFreeOpArray(db, p->aOp, p->nOp);
72845  sqlite3DbFree(db, p->aColName);
72846  sqlite3DbFree(db, p->zSql);
72847  sqlite3DbFree(db, p->pFree);
72848 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
72849  for(i=0; i<p->nScan; i++){
72850  sqlite3DbFree(db, p->aScan[i].zName);
72851  }
72852  sqlite3DbFree(db, p->aScan);
72853 #endif
72854 }
72855 
72856 /*
72857 ** Delete an entire VDBE.
72858 */
72860  sqlite3 *db;
72861 
72862  if( NEVER(p==0) ) return;
72863  db = p->db;
72865  sqlite3VdbeClearObject(db, p);
72866  if( p->pPrev ){
72867  p->pPrev->pNext = p->pNext;
72868  }else{
72869  assert( db->pVdbe==p );
72870  db->pVdbe = p->pNext;
72871  }
72872  if( p->pNext ){
72873  p->pNext->pPrev = p->pPrev;
72874  }
72875  p->magic = VDBE_MAGIC_DEAD;
72876  p->db = 0;
72877  sqlite3DbFree(db, p);
72878 }
72879 
72880 /*
72881 ** The cursor "p" has a pending seek operation that has not yet been
72882 ** carried out. Seek the cursor now. If an error occurs, return
72883 ** the appropriate error code.
72884 */
72886  int res, rc;
72887 #ifdef SQLITE_TEST
72888  extern int sqlite3_search_count;
72889 #endif
72890  assert( p->deferredMoveto );
72891  assert( p->isTable );
72892  assert( p->eCurType==CURTYPE_BTREE );
72893  rc = sqlite3BtreeMovetoUnpacked(p->uc.pCursor, 0, p->movetoTarget, 0, &res);
72894  if( rc ) return rc;
72895  if( res!=0 ) return SQLITE_CORRUPT_BKPT;
72896 #ifdef SQLITE_TEST
72897  sqlite3_search_count++;
72898 #endif
72899  p->deferredMoveto = 0;
72900  p->cacheStatus = CACHE_STALE;
72901  return SQLITE_OK;
72902 }
72903 
72904 /*
72905 ** Something has moved cursor "p" out of place. Maybe the row it was
72906 ** pointed to was deleted out from under it. Or maybe the btree was
72907 ** rebalanced. Whatever the cause, try to restore "p" to the place it
72908 ** is supposed to be pointing. If the row was deleted out from under the
72909 ** cursor, set the cursor to point to a NULL row.
72910 */
72912  int isDifferentRow, rc;
72913  assert( p->eCurType==CURTYPE_BTREE );
72914  assert( p->uc.pCursor!=0 );
72916  rc = sqlite3BtreeCursorRestore(p->uc.pCursor, &isDifferentRow);
72917  p->cacheStatus = CACHE_STALE;
72918  if( isDifferentRow ) p->nullRow = 1;
72919  return rc;
72920 }
72921 
72922 /*
72923 ** Check to ensure that the cursor is valid. Restore the cursor
72924 ** if need be. Return any I/O error from the restore operation.
72925 */
72927  assert( p->eCurType==CURTYPE_BTREE );
72929  return handleMovedCursor(p);
72930  }
72931  return SQLITE_OK;
72932 }
72933 
72934 /*
72935 ** Make sure the cursor p is ready to read or write the row to which it
72936 ** was last positioned. Return an error code if an OOM fault or I/O error
72937 ** prevents us from positioning the cursor to its correct position.
72938 **
72939 ** If a MoveTo operation is pending on the given cursor, then do that
72940 ** MoveTo now. If no move is pending, check to see if the row has been
72941 ** deleted out from under the cursor and if it has, mark the row as
72942 ** a NULL row.
72943 **
72944 ** If the cursor is already pointing to the correct row and that row has
72945 ** not been deleted out from under the cursor, then this routine is a no-op.
72946 */
72948  VdbeCursor *p = *pp;
72949  if( p->eCurType==CURTYPE_BTREE ){
72950  if( p->deferredMoveto ){
72951  int iMap;
72952  if( p->aAltMap && (iMap = p->aAltMap[1+*piCol])>0 ){
72953  *pp = p->pAltCursor;
72954  *piCol = iMap - 1;
72955  return SQLITE_OK;
72956  }
72957  return handleDeferredMoveto(p);
72958  }
72960  return handleMovedCursor(p);
72961  }
72962  }
72963  return SQLITE_OK;
72964 }
72965 
72966 /*
72967 ** The following functions:
72968 **
72969 ** sqlite3VdbeSerialType()
72970 ** sqlite3VdbeSerialTypeLen()
72971 ** sqlite3VdbeSerialLen()
72972 ** sqlite3VdbeSerialPut()
72973 ** sqlite3VdbeSerialGet()
72974 **
72975 ** encapsulate the code that serializes values for storage in SQLite
72976 ** data and index records. Each serialized value consists of a
72977 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
72978 ** integer, stored as a varint.
72979 **
72980 ** In an SQLite index record, the serial type is stored directly before
72981 ** the blob of data that it corresponds to. In a table record, all serial
72982 ** types are stored at the start of the record, and the blobs of data at
72983 ** the end. Hence these functions allow the caller to handle the
72984 ** serial-type and data blob separately.
72985 **
72986 ** The following table describes the various storage classes for data:
72987 **
72988 ** serial type bytes of data type
72989 ** -------------- --------------- ---------------
72990 ** 0 0 NULL
72991 ** 1 1 signed integer
72992 ** 2 2 signed integer
72993 ** 3 3 signed integer
72994 ** 4 4 signed integer
72995 ** 5 6 signed integer
72996 ** 6 8 signed integer
72997 ** 7 8 IEEE float
72998 ** 8 0 Integer constant 0
72999 ** 9 0 Integer constant 1
73000 ** 10,11 reserved for expansion
73001 ** N>=12 and even (N-12)/2 BLOB
73002 ** N>=13 and odd (N-13)/2 text
73003 **
73004 ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
73005 ** of SQLite will not understand those serial types.
73006 */
73007 
73008 /*
73009 ** Return the serial-type for the value stored in pMem.
73010 */
73011 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format, u32 *pLen){
73012  int flags = pMem->flags;
73013  u32 n;
73014 
73015  assert( pLen!=0 );
73016  if( flags&MEM_Null ){
73017  *pLen = 0;
73018  return 0;
73019  }
73020  if( flags&MEM_Int ){
73021  /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
73022 # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
73023  i64 i = pMem->u.i;
73024  u64 u;
73025  if( i<0 ){
73026  u = ~i;
73027  }else{
73028  u = i;
73029  }
73030  if( u<=127 ){
73031  if( (i&1)==i && file_format>=4 ){
73032  *pLen = 0;
73033  return 8+(u32)u;
73034  }else{
73035  *pLen = 1;
73036  return 1;
73037  }
73038  }
73039  if( u<=32767 ){ *pLen = 2; return 2; }
73040  if( u<=8388607 ){ *pLen = 3; return 3; }
73041  if( u<=2147483647 ){ *pLen = 4; return 4; }
73042  if( u<=MAX_6BYTE ){ *pLen = 6; return 5; }
73043  *pLen = 8;
73044  return 6;
73045  }
73046  if( flags&MEM_Real ){
73047  *pLen = 8;
73048  return 7;
73049  }
73050  assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
73051  assert( pMem->n>=0 );
73052  n = (u32)pMem->n;
73053  if( flags & MEM_Zero ){
73054  n += pMem->u.nZero;
73055  }
73056  *pLen = n;
73057  return ((n*2) + 12 + ((flags&MEM_Str)!=0));
73058 }
73059 
73060 /*
73061 ** The sizes for serial types less than 128
73062 */
73063 static const u8 sqlite3SmallTypeSizes[] = {
73064  /* 0 1 2 3 4 5 6 7 8 9 */
73065 /* 0 */ 0, 1, 2, 3, 4, 6, 8, 8, 0, 0,
73066 /* 10 */ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3,
73067 /* 20 */ 4, 4, 5, 5, 6, 6, 7, 7, 8, 8,
73068 /* 30 */ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
73069 /* 40 */ 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
73070 /* 50 */ 19, 19, 20, 20, 21, 21, 22, 22, 23, 23,
73071 /* 60 */ 24, 24, 25, 25, 26, 26, 27, 27, 28, 28,
73072 /* 70 */ 29, 29, 30, 30, 31, 31, 32, 32, 33, 33,
73073 /* 80 */ 34, 34, 35, 35, 36, 36, 37, 37, 38, 38,
73074 /* 90 */ 39, 39, 40, 40, 41, 41, 42, 42, 43, 43,
73075 /* 100 */ 44, 44, 45, 45, 46, 46, 47, 47, 48, 48,
73076 /* 110 */ 49, 49, 50, 50, 51, 51, 52, 52, 53, 53,
73077 /* 120 */ 54, 54, 55, 55, 56, 56, 57, 57
73078 };
73079 
73080 /*
73081 ** Return the length of the data corresponding to the supplied serial-type.
73082 */
73084  if( serial_type>=128 ){
73085  return (serial_type-12)/2;
73086  }else{
73087  assert( serial_type<12
73088  || sqlite3SmallTypeSizes[serial_type]==(serial_type - 12)/2 );
73089  return sqlite3SmallTypeSizes[serial_type];
73090  }
73091 }
73093  assert( serial_type<128 );
73094  return sqlite3SmallTypeSizes[serial_type];
73095 }
73096 
73097 /*
73098 ** If we are on an architecture with mixed-endian floating
73099 ** points (ex: ARM7) then swap the lower 4 bytes with the
73100 ** upper 4 bytes. Return the result.
73101 **
73102 ** For most architectures, this is a no-op.
73103 **
73104 ** (later): It is reported to me that the mixed-endian problem
73105 ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
73106 ** that early versions of GCC stored the two words of a 64-bit
73107 ** float in the wrong order. And that error has been propagated
73108 ** ever since. The blame is not necessarily with GCC, though.
73109 ** GCC might have just copying the problem from a prior compiler.
73110 ** I am also told that newer versions of GCC that follow a different
73111 ** ABI get the byte order right.
73112 **
73113 ** Developers using SQLite on an ARM7 should compile and run their
73114 ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
73115 ** enabled, some asserts below will ensure that the byte order of
73116 ** floating point values is correct.
73117 **
73118 ** (2007-08-30) Frank van Vugt has studied this problem closely
73119 ** and has send his findings to the SQLite developers. Frank
73120 ** writes that some Linux kernels offer floating point hardware
73121 ** emulation that uses only 32-bit mantissas instead of a full
73122 ** 48-bits as required by the IEEE standard. (This is the
73123 ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
73124 ** byte swapping becomes very complicated. To avoid problems,
73125 ** the necessary byte swapping is carried out using a 64-bit integer
73126 ** rather than a 64-bit float. Frank assures us that the code here
73127 ** works for him. We, the developers, have no way to independently
73128 ** verify this, but Frank seems to know what he is talking about
73129 ** so we trust him.
73130 */
73131 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
73132 static u64 floatSwap(u64 in){
73133  union {
73134  u64 r;
73135  u32 i[2];
73136  } u;
73137  u32 t;
73138 
73139  u.r = in;
73140  t = u.i[0];
73141  u.i[0] = u.i[1];
73142  u.i[1] = t;
73143  return u.r;
73144 }
73145 # define swapMixedEndianFloat(X) X = floatSwap(X)
73146 #else
73147 # define swapMixedEndianFloat(X)
73148 #endif
73149 
73150 /*
73151 ** Write the serialized data blob for the value stored in pMem into
73152 ** buf. It is assumed that the caller has allocated sufficient space.
73153 ** Return the number of bytes written.
73154 **
73155 ** nBuf is the amount of space left in buf[]. The caller is responsible
73156 ** for allocating enough space to buf[] to hold the entire field, exclusive
73157 ** of the pMem->u.nZero bytes for a MEM_Zero value.
73158 **
73159 ** Return the number of bytes actually written into buf[]. The number
73160 ** of bytes in the zero-filled tail is included in the return value only
73161 ** if those bytes were zeroed in buf[].
73162 */
73163 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
73164  u32 len;
73165 
73166  /* Integer and Real */
73167  if( serial_type<=7 && serial_type>0 ){
73168  u64 v;
73169  u32 i;
73170  if( serial_type==7 ){
73171  assert( sizeof(v)==sizeof(pMem->u.r) );
73172  memcpy(&v, &pMem->u.r, sizeof(v));
73174  }else{
73175  v = pMem->u.i;
73176  }
73177  len = i = sqlite3SmallTypeSizes[serial_type];
73178  assert( i>0 );
73179  do{
73180  buf[--i] = (u8)(v&0xFF);
73181  v >>= 8;
73182  }while( i );
73183  return len;
73184  }
73185 
73186  /* String or blob */
73187  if( serial_type>=12 ){
73188  assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
73189  == (int)sqlite3VdbeSerialTypeLen(serial_type) );
73190  len = pMem->n;
73191  if( len>0 ) memcpy(buf, pMem->z, len);
73192  return len;
73193  }
73194 
73195  /* NULL or constants 0 or 1 */
73196  return 0;
73197 }
73198 
73199 /* Input "x" is a sequence of unsigned characters that represent a
73200 ** big-endian integer. Return the equivalent native integer
73201 */
73202 #define ONE_BYTE_INT(x) ((i8)(x)[0])
73203 #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
73204 #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
73205 #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73206 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
73207 
73208 /*
73209 ** Deserialize the data blob pointed to by buf as serial type serial_type
73210 ** and store the result in pMem. Return the number of bytes read.
73211 **
73212 ** This function is implemented as two separate routines for performance.
73213 ** The few cases that require local variables are broken out into a separate
73214 ** routine so that in most cases the overhead of moving the stack pointer
73215 ** is avoided.
73216 */
73218  const unsigned char *buf, /* Buffer to deserialize from */
73219  u32 serial_type, /* Serial type to deserialize */
73220  Mem *pMem /* Memory cell to write value into */
73221 ){
73222  u64 x = FOUR_BYTE_UINT(buf);
73223  u32 y = FOUR_BYTE_UINT(buf+4);
73224  x = (x<<32) + y;
73225  if( serial_type==6 ){
73226  /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
73227  ** twos-complement integer. */
73228  pMem->u.i = *(i64*)&x;
73229  pMem->flags = MEM_Int;
73230  testcase( pMem->u.i<0 );
73231  }else{
73232  /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
73233  ** floating point number. */
73234 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
73235  /* Verify that integers and floating point values use the same
73236  ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
73237  ** defined that 64-bit floating point values really are mixed
73238  ** endian.
73239  */
73240  static const u64 t1 = ((u64)0x3ff00000)<<32;
73241  static const double r1 = 1.0;
73242  u64 t2 = t1;
73244  assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
73245 #endif
73246  assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
73248  memcpy(&pMem->u.r, &x, sizeof(x));
73249  pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
73250  }
73251  return 8;
73252 }
73254  const unsigned char *buf, /* Buffer to deserialize from */
73255  u32 serial_type, /* Serial type to deserialize */
73256  Mem *pMem /* Memory cell to write value into */
73257 ){
73258  switch( serial_type ){
73259  case 10: /* Reserved for future use */
73260  case 11: /* Reserved for future use */
73261  case 0: { /* Null */
73262  /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
73263  pMem->flags = MEM_Null;
73264  break;
73265  }
73266  case 1: {
73267  /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
73268  ** integer. */
73269  pMem->u.i = ONE_BYTE_INT(buf);
73270  pMem->flags = MEM_Int;
73271  testcase( pMem->u.i<0 );
73272  return 1;
73273  }
73274  case 2: { /* 2-byte signed integer */
73275  /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
73276  ** twos-complement integer. */
73277  pMem->u.i = TWO_BYTE_INT(buf);
73278  pMem->flags = MEM_Int;
73279  testcase( pMem->u.i<0 );
73280  return 2;
73281  }
73282  case 3: { /* 3-byte signed integer */
73283  /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
73284  ** twos-complement integer. */
73285  pMem->u.i = THREE_BYTE_INT(buf);
73286  pMem->flags = MEM_Int;
73287  testcase( pMem->u.i<0 );
73288  return 3;
73289  }
73290  case 4: { /* 4-byte signed integer */
73291  /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
73292  ** twos-complement integer. */
73293  pMem->u.i = FOUR_BYTE_INT(buf);
73294 #ifdef __HP_cc
73295  /* Work around a sign-extension bug in the HP compiler for HP/UX */
73296  if( buf[0]&0x80 ) pMem->u.i |= 0xffffffff80000000LL;
73297 #endif
73298  pMem->flags = MEM_Int;
73299  testcase( pMem->u.i<0 );
73300  return 4;
73301  }
73302  case 5: { /* 6-byte signed integer */
73303  /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
73304  ** twos-complement integer. */
73305  pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
73306  pMem->flags = MEM_Int;
73307  testcase( pMem->u.i<0 );
73308  return 6;
73309  }
73310  case 6: /* 8-byte signed integer */
73311  case 7: { /* IEEE floating point */
73312  /* These use local variables, so do them in a separate routine
73313  ** to avoid having to move the frame pointer in the common case */
73314  return serialGet(buf,serial_type,pMem);
73315  }
73316  case 8: /* Integer 0 */
73317  case 9: { /* Integer 1 */
73318  /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
73319  /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
73320  pMem->u.i = serial_type-8;
73321  pMem->flags = MEM_Int;
73322  return 0;
73323  }
73324  default: {
73325  /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
73326  ** length.
73327  ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
73328  ** (N-13)/2 bytes in length. */
73329  static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
73330  pMem->z = (char *)buf;
73331  pMem->n = (serial_type-12)/2;
73332  pMem->flags = aFlag[serial_type&1];
73333  return pMem->n;
73334  }
73335  }
73336  return 0;
73337 }
73338 /*
73339 ** This routine is used to allocate sufficient space for an UnpackedRecord
73340 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
73341 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
73342 **
73343 ** The space is either allocated using sqlite3DbMallocRaw() or from within
73344 ** the unaligned buffer passed via the second and third arguments (presumably
73345 ** stack space). If the former, then *ppFree is set to a pointer that should
73346 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
73347 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
73348 ** before returning.
73349 **
73350 ** If an OOM error occurs, NULL is returned.
73351 */
73353  KeyInfo *pKeyInfo, /* Description of the record */
73354  char *pSpace, /* Unaligned space available */
73355  int szSpace, /* Size of pSpace[] in bytes */
73356  char **ppFree /* OUT: Caller should free this pointer */
73357 ){
73358  UnpackedRecord *p; /* Unpacked record to return */
73359  int nOff; /* Increment pSpace by nOff to align it */
73360  int nByte; /* Number of bytes required for *p */
73361 
73362  /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
73363  ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
73364  ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
73365  */
73366  nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
73367  nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
73368  if( nByte>szSpace+nOff ){
73369  p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
73370  *ppFree = (char *)p;
73371  if( !p ) return 0;
73372  }else{
73373  p = (UnpackedRecord*)&pSpace[nOff];
73374  *ppFree = 0;
73375  }
73376 
73377  p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
73378  assert( pKeyInfo->aSortOrder!=0 );
73379  p->pKeyInfo = pKeyInfo;
73380  p->nField = pKeyInfo->nField + 1;
73381  return p;
73382 }
73383 
73384 /*
73385 ** Given the nKey-byte encoding of a record in pKey[], populate the
73386 ** UnpackedRecord structure indicated by the fourth argument with the
73387 ** contents of the decoded record.
73388 */
73390  KeyInfo *pKeyInfo, /* Information about the record format */
73391  int nKey, /* Size of the binary record */
73392  const void *pKey, /* The binary record */
73393  UnpackedRecord *p /* Populate this structure before returning. */
73394 ){
73395  const unsigned char *aKey = (const unsigned char *)pKey;
73396  int d;
73397  u32 idx; /* Offset in aKey[] to read from */
73398  u16 u; /* Unsigned loop counter */
73399  u32 szHdr;
73400  Mem *pMem = p->aMem;
73401 
73402  p->default_rc = 0;
73403  assert( EIGHT_BYTE_ALIGNMENT(pMem) );
73404  idx = getVarint32(aKey, szHdr);
73405  d = szHdr;
73406  u = 0;
73407  while( idx<szHdr && d<=nKey ){
73408  u32 serial_type;
73409 
73410  idx += getVarint32(&aKey[idx], serial_type);
73411  pMem->enc = pKeyInfo->enc;
73412  pMem->db = pKeyInfo->db;
73413  /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
73414  pMem->szMalloc = 0;
73415  pMem->z = 0;
73416  d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
73417  pMem++;
73418  if( (++u)>=p->nField ) break;
73419  }
73420  assert( u<=pKeyInfo->nField + 1 );
73421  p->nField = u;
73422 }
73423 
73424 #if SQLITE_DEBUG
73425 /*
73426 ** This function compares two index or table record keys in the same way
73427 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
73428 ** this function deserializes and compares values using the
73429 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
73430 ** in assert() statements to ensure that the optimized code in
73431 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
73432 **
73433 ** Return true if the result of comparison is equivalent to desiredResult.
73434 ** Return false if there is a disagreement.
73435 */
73436 static int vdbeRecordCompareDebug(
73437  int nKey1, const void *pKey1, /* Left key */
73438  const UnpackedRecord *pPKey2, /* Right key */
73439  int desiredResult /* Correct answer */
73440 ){
73441  u32 d1; /* Offset into aKey[] of next data element */
73442  u32 idx1; /* Offset into aKey[] of next header element */
73443  u32 szHdr1; /* Number of bytes in header */
73444  int i = 0;
73445  int rc = 0;
73446  const unsigned char *aKey1 = (const unsigned char *)pKey1;
73447  KeyInfo *pKeyInfo;
73448  Mem mem1;
73449 
73450  pKeyInfo = pPKey2->pKeyInfo;
73451  if( pKeyInfo->db==0 ) return 1;
73452  mem1.enc = pKeyInfo->enc;
73453  mem1.db = pKeyInfo->db;
73454  /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
73455  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
73456 
73457  /* Compilers may complain that mem1.u.i is potentially uninitialized.
73458  ** We could initialize it, as shown here, to silence those complaints.
73459  ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
73460  ** the unnecessary initialization has a measurable negative performance
73461  ** impact, since this routine is a very high runner. And so, we choose
73462  ** to ignore the compiler warnings and leave this variable uninitialized.
73463  */
73464  /* mem1.u.i = 0; // not needed, here to silence compiler warning */
73465 
73466  idx1 = getVarint32(aKey1, szHdr1);
73467  if( szHdr1>98307 ) return SQLITE_CORRUPT;
73468  d1 = szHdr1;
73469  assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
73470  assert( pKeyInfo->aSortOrder!=0 );
73471  assert( pKeyInfo->nField>0 );
73472  assert( idx1<=szHdr1 || CORRUPT_DB );
73473  do{
73474  u32 serial_type1;
73475 
73476  /* Read the serial types for the next element in each key. */
73477  idx1 += getVarint32( aKey1+idx1, serial_type1 );
73478 
73479  /* Verify that there is enough key space remaining to avoid
73480  ** a buffer overread. The "d1+serial_type1+2" subexpression will
73481  ** always be greater than or equal to the amount of required key space.
73482  ** Use that approximation to avoid the more expensive call to
73483  ** sqlite3VdbeSerialTypeLen() in the common case.
73484  */
73485  if( d1+serial_type1+2>(u32)nKey1
73486  && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
73487  ){
73488  break;
73489  }
73490 
73491  /* Extract the values to be compared.
73492  */
73493  d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
73494 
73495  /* Do the comparison
73496  */
73497  rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
73498  if( rc!=0 ){
73499  assert( mem1.szMalloc==0 ); /* See comment below */
73500  if( pKeyInfo->aSortOrder[i] ){
73501  rc = -rc; /* Invert the result for DESC sort order. */
73502  }
73503  goto debugCompareEnd;
73504  }
73505  i++;
73506  }while( idx1<szHdr1 && i<pPKey2->nField );
73507 
73508  /* No memory allocation is ever used on mem1. Prove this using
73509  ** the following assert(). If the assert() fails, it indicates a
73510  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
73511  */
73512  assert( mem1.szMalloc==0 );
73513 
73514  /* rc==0 here means that one of the keys ran out of fields and
73515  ** all the fields up to that point were equal. Return the default_rc
73516  ** value. */
73517  rc = pPKey2->default_rc;
73518 
73519 debugCompareEnd:
73520  if( desiredResult==0 && rc==0 ) return 1;
73521  if( desiredResult<0 && rc<0 ) return 1;
73522  if( desiredResult>0 && rc>0 ) return 1;
73523  if( CORRUPT_DB ) return 1;
73524  if( pKeyInfo->db->mallocFailed ) return 1;
73525  return 0;
73526 }
73527 #endif
73528 
73529 #if SQLITE_DEBUG
73530 /*
73531 ** Count the number of fields (a.k.a. columns) in the record given by
73532 ** pKey,nKey. The verify that this count is less than or equal to the
73533 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
73534 **
73535 ** If this constraint is not satisfied, it means that the high-speed
73536 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
73537 ** not work correctly. If this assert() ever fires, it probably means
73538 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
73539 ** incorrectly.
73540 */
73542  int nKey, const void *pKey, /* The record to verify */
73543  const KeyInfo *pKeyInfo /* Compare size with this KeyInfo */
73544 ){
73545  int nField = 0;
73546  u32 szHdr;
73547  u32 idx;
73548  u32 notUsed;
73549  const unsigned char *aKey = (const unsigned char*)pKey;
73550 
73551  if( CORRUPT_DB ) return;
73552  idx = getVarint32(aKey, szHdr);
73553  assert( nKey>=0 );
73554  assert( szHdr<=(u32)nKey );
73555  while( idx<szHdr ){
73556  idx += getVarint32(aKey+idx, notUsed);
73557  nField++;
73558  }
73559  assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
73560 }
73561 #else
73562 # define vdbeAssertFieldCountWithinLimits(A,B,C)
73563 #endif
73564 
73565 /*
73566 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
73567 ** using the collation sequence pColl. As usual, return a negative , zero
73568 ** or positive value if *pMem1 is less than, equal to or greater than
73569 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
73570 */
73572  const Mem *pMem1,
73573  const Mem *pMem2,
73574  const CollSeq *pColl,
73575  u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
73576 ){
73577  if( pMem1->enc==pColl->enc ){
73578  /* The strings are already in the correct encoding. Call the
73579  ** comparison function directly */
73580  return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
73581  }else{
73582  int rc;
73583  const void *v1, *v2;
73584  int n1, n2;
73585  Mem c1;
73586  Mem c2;
73587  sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
73588  sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
73589  sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
73590  sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
73591  v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
73592  n1 = v1==0 ? 0 : c1.n;
73593  v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
73594  n2 = v2==0 ? 0 : c2.n;
73595  rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
73596  if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM_BKPT;
73597  sqlite3VdbeMemRelease(&c1);
73598  sqlite3VdbeMemRelease(&c2);
73599  return rc;
73600  }
73601 }
73602 
73603 /*
73604 ** Compare two blobs. Return negative, zero, or positive if the first
73605 ** is less than, equal to, or greater than the second, respectively.
73606 ** If one blob is a prefix of the other, then the shorter is the lessor.
73607 */
73608 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
73609  int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
73610  if( c ) return c;
73611  return pB1->n - pB2->n;
73612 }
73613 
73614 /*
73615 ** Do a comparison between a 64-bit signed integer and a 64-bit floating-point
73616 ** number. Return negative, zero, or positive if the first (i64) is less than,
73617 ** equal to, or greater than the second (double).
73618 */
73619 static int sqlite3IntFloatCompare(i64 i, double r){
73620  if( sizeof(LONGDOUBLE_TYPE)>8 ){
73622  if( x<r ) return -1;
73623  if( x>r ) return +1;
73624  return 0;
73625  }else{
73626  i64 y;
73627  double s;
73628  if( r<-9223372036854775808.0 ) return +1;
73629  if( r>9223372036854775807.0 ) return -1;
73630  y = (i64)r;
73631  if( i<y ) return -1;
73632  if( i>y ){
73633  if( y==SMALLEST_INT64 && r>0.0 ) return -1;
73634  return +1;
73635  }
73636  s = (double)i;
73637  if( s<r ) return -1;
73638  if( s>r ) return +1;
73639  return 0;
73640  }
73641 }
73642 
73643 /*
73644 ** Compare the values contained by the two memory cells, returning
73645 ** negative, zero or positive if pMem1 is less than, equal to, or greater
73646 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
73647 ** and reals) sorted numerically, followed by text ordered by the collating
73648 ** sequence pColl and finally blob's ordered by memcmp().
73649 **
73650 ** Two NULL values are considered equal by this function.
73651 */
73652 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
73653  int f1, f2;
73654  int combined_flags;
73655 
73656  f1 = pMem1->flags;
73657  f2 = pMem2->flags;
73658  combined_flags = f1|f2;
73659  assert( (combined_flags & MEM_RowSet)==0 );
73660 
73661  /* If one value is NULL, it is less than the other. If both values
73662  ** are NULL, return 0.
73663  */
73664  if( combined_flags&MEM_Null ){
73665  return (f2&MEM_Null) - (f1&MEM_Null);
73666  }
73667 
73668  /* At least one of the two values is a number
73669  */
73670  if( combined_flags&(MEM_Int|MEM_Real) ){
73671  if( (f1 & f2 & MEM_Int)!=0 ){
73672  if( pMem1->u.i < pMem2->u.i ) return -1;
73673  if( pMem1->u.i > pMem2->u.i ) return +1;
73674  return 0;
73675  }
73676  if( (f1 & f2 & MEM_Real)!=0 ){
73677  if( pMem1->u.r < pMem2->u.r ) return -1;
73678  if( pMem1->u.r > pMem2->u.r ) return +1;
73679  return 0;
73680  }
73681  if( (f1&MEM_Int)!=0 ){
73682  if( (f2&MEM_Real)!=0 ){
73683  return sqlite3IntFloatCompare(pMem1->u.i, pMem2->u.r);
73684  }else{
73685  return -1;
73686  }
73687  }
73688  if( (f1&MEM_Real)!=0 ){
73689  if( (f2&MEM_Int)!=0 ){
73690  return -sqlite3IntFloatCompare(pMem2->u.i, pMem1->u.r);
73691  }else{
73692  return -1;
73693  }
73694  }
73695  return +1;
73696  }
73697 
73698  /* If one value is a string and the other is a blob, the string is less.
73699  ** If both are strings, compare using the collating functions.
73700  */
73701  if( combined_flags&MEM_Str ){
73702  if( (f1 & MEM_Str)==0 ){
73703  return 1;
73704  }
73705  if( (f2 & MEM_Str)==0 ){
73706  return -1;
73707  }
73708 
73709  assert( pMem1->enc==pMem2->enc || pMem1->db->mallocFailed );
73710  assert( pMem1->enc==SQLITE_UTF8 ||
73711  pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
73712 
73713  /* The collation sequence must be defined at this point, even if
73714  ** the user deletes the collation sequence after the vdbe program is
73715  ** compiled (this was not always the case).
73716  */
73717  assert( !pColl || pColl->xCmp );
73718 
73719  if( pColl ){
73720  return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
73721  }
73722  /* If a NULL pointer was passed as the collate function, fall through
73723  ** to the blob case and use memcmp(). */
73724  }
73725 
73726  /* Both values must be blobs. Compare using memcmp(). */
73727  return sqlite3BlobCompare(pMem1, pMem2);
73728 }
73729 
73730 
73731 /*
73732 ** The first argument passed to this function is a serial-type that
73733 ** corresponds to an integer - all values between 1 and 9 inclusive
73734 ** except 7. The second points to a buffer containing an integer value
73735 ** serialized according to serial_type. This function deserializes
73736 ** and returns the value.
73737 */
73738 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
73739  u32 y;
73740  assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
73741  switch( serial_type ){
73742  case 0:
73743  case 1:
73744  testcase( aKey[0]&0x80 );
73745  return ONE_BYTE_INT(aKey);
73746  case 2:
73747  testcase( aKey[0]&0x80 );
73748  return TWO_BYTE_INT(aKey);
73749  case 3:
73750  testcase( aKey[0]&0x80 );
73751  return THREE_BYTE_INT(aKey);
73752  case 4: {
73753  testcase( aKey[0]&0x80 );
73754  y = FOUR_BYTE_UINT(aKey);
73755  return (i64)*(int*)&y;
73756  }
73757  case 5: {
73758  testcase( aKey[0]&0x80 );
73759  return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
73760  }
73761  case 6: {
73762  u64 x = FOUR_BYTE_UINT(aKey);
73763  testcase( aKey[0]&0x80 );
73764  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
73765  return (i64)*(i64*)&x;
73766  }
73767  }
73768 
73769  return (serial_type - 8);
73770 }
73771 
73772 /*
73773 ** This function compares the two table rows or index records
73774 ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
73775 ** or positive integer if key1 is less than, equal to or
73776 ** greater than key2. The {nKey1, pKey1} key must be a blob
73777 ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
73778 ** key must be a parsed key such as obtained from
73779 ** sqlite3VdbeParseRecord.
73780 **
73781 ** If argument bSkip is non-zero, it is assumed that the caller has already
73782 ** determined that the first fields of the keys are equal.
73783 **
73784 ** Key1 and Key2 do not have to contain the same number of fields. If all
73785 ** fields that appear in both keys are equal, then pPKey2->default_rc is
73786 ** returned.
73787 **
73788 ** If database corruption is discovered, set pPKey2->errCode to
73789 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
73790 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
73791 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
73792 */
73794  int nKey1, const void *pKey1, /* Left key */
73795  UnpackedRecord *pPKey2, /* Right key */
73796  int bSkip /* If true, skip the first field */
73797 ){
73798  u32 d1; /* Offset into aKey[] of next data element */
73799  int i; /* Index of next field to compare */
73800  u32 szHdr1; /* Size of record header in bytes */
73801  u32 idx1; /* Offset of first type in header */
73802  int rc = 0; /* Return value */
73803  Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
73804  KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
73805  const unsigned char *aKey1 = (const unsigned char *)pKey1;
73806  Mem mem1;
73807 
73808  /* If bSkip is true, then the caller has already determined that the first
73809  ** two elements in the keys are equal. Fix the various stack variables so
73810  ** that this routine begins comparing at the second field. */
73811  if( bSkip ){
73812  u32 s1;
73813  idx1 = 1 + getVarint32(&aKey1[1], s1);
73814  szHdr1 = aKey1[0];
73815  d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
73816  i = 1;
73817  pRhs++;
73818  }else{
73819  idx1 = getVarint32(aKey1, szHdr1);
73820  d1 = szHdr1;
73821  if( d1>(unsigned)nKey1 ){
73822  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
73823  return 0; /* Corruption */
73824  }
73825  i = 0;
73826  }
73827 
73828  VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
73829  assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
73830  || CORRUPT_DB );
73831  assert( pPKey2->pKeyInfo->aSortOrder!=0 );
73832  assert( pPKey2->pKeyInfo->nField>0 );
73833  assert( idx1<=szHdr1 || CORRUPT_DB );
73834  do{
73835  u32 serial_type;
73836 
73837  /* RHS is an integer */
73838  if( pRhs->flags & MEM_Int ){
73839  serial_type = aKey1[idx1];
73840  testcase( serial_type==12 );
73841  if( serial_type>=10 ){
73842  rc = +1;
73843  }else if( serial_type==0 ){
73844  rc = -1;
73845  }else if( serial_type==7 ){
73846  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
73847  rc = -sqlite3IntFloatCompare(pRhs->u.i, mem1.u.r);
73848  }else{
73849  i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
73850  i64 rhs = pRhs->u.i;
73851  if( lhs<rhs ){
73852  rc = -1;
73853  }else if( lhs>rhs ){
73854  rc = +1;
73855  }
73856  }
73857  }
73858 
73859  /* RHS is real */
73860  else if( pRhs->flags & MEM_Real ){
73861  serial_type = aKey1[idx1];
73862  if( serial_type>=10 ){
73863  /* Serial types 12 or greater are strings and blobs (greater than
73864  ** numbers). Types 10 and 11 are currently "reserved for future
73865  ** use", so it doesn't really matter what the results of comparing
73866  ** them to numberic values are. */
73867  rc = +1;
73868  }else if( serial_type==0 ){
73869  rc = -1;
73870  }else{
73871  sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
73872  if( serial_type==7 ){
73873  if( mem1.u.r<pRhs->u.r ){
73874  rc = -1;
73875  }else if( mem1.u.r>pRhs->u.r ){
73876  rc = +1;
73877  }
73878  }else{
73879  rc = sqlite3IntFloatCompare(mem1.u.i, pRhs->u.r);
73880  }
73881  }
73882  }
73883 
73884  /* RHS is a string */
73885  else if( pRhs->flags & MEM_Str ){
73886  getVarint32(&aKey1[idx1], serial_type);
73887  testcase( serial_type==12 );
73888  if( serial_type<12 ){
73889  rc = -1;
73890  }else if( !(serial_type & 0x01) ){
73891  rc = +1;
73892  }else{
73893  mem1.n = (serial_type - 12) / 2;
73894  testcase( (d1+mem1.n)==(unsigned)nKey1 );
73895  testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
73896  if( (d1+mem1.n) > (unsigned)nKey1 ){
73897  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
73898  return 0; /* Corruption */
73899  }else if( pKeyInfo->aColl[i] ){
73900  mem1.enc = pKeyInfo->enc;
73901  mem1.db = pKeyInfo->db;
73902  mem1.flags = MEM_Str;
73903  mem1.z = (char*)&aKey1[d1];
73904  rc = vdbeCompareMemString(
73905  &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
73906  );
73907  }else{
73908  int nCmp = MIN(mem1.n, pRhs->n);
73909  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
73910  if( rc==0 ) rc = mem1.n - pRhs->n;
73911  }
73912  }
73913  }
73914 
73915  /* RHS is a blob */
73916  else if( pRhs->flags & MEM_Blob ){
73917  getVarint32(&aKey1[idx1], serial_type);
73918  testcase( serial_type==12 );
73919  if( serial_type<12 || (serial_type & 0x01) ){
73920  rc = -1;
73921  }else{
73922  int nStr = (serial_type - 12) / 2;
73923  testcase( (d1+nStr)==(unsigned)nKey1 );
73924  testcase( (d1+nStr+1)==(unsigned)nKey1 );
73925  if( (d1+nStr) > (unsigned)nKey1 ){
73926  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
73927  return 0; /* Corruption */
73928  }else{
73929  int nCmp = MIN(nStr, pRhs->n);
73930  rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
73931  if( rc==0 ) rc = nStr - pRhs->n;
73932  }
73933  }
73934  }
73935 
73936  /* RHS is null */
73937  else{
73938  serial_type = aKey1[idx1];
73939  rc = (serial_type!=0);
73940  }
73941 
73942  if( rc!=0 ){
73943  if( pKeyInfo->aSortOrder[i] ){
73944  rc = -rc;
73945  }
73946  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
73947  assert( mem1.szMalloc==0 ); /* See comment below */
73948  return rc;
73949  }
73950 
73951  i++;
73952  pRhs++;
73953  d1 += sqlite3VdbeSerialTypeLen(serial_type);
73954  idx1 += sqlite3VarintLen(serial_type);
73955  }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
73956 
73957  /* No memory allocation is ever used on mem1. Prove this using
73958  ** the following assert(). If the assert() fails, it indicates a
73959  ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
73960  assert( mem1.szMalloc==0 );
73961 
73962  /* rc==0 here means that one or both of the keys ran out of fields and
73963  ** all the fields up to that point were equal. Return the default_rc
73964  ** value. */
73965  assert( CORRUPT_DB
73966  || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
73967  || pKeyInfo->db->mallocFailed
73968  );
73969  pPKey2->eqSeen = 1;
73970  return pPKey2->default_rc;
73971 }
73973  int nKey1, const void *pKey1, /* Left key */
73974  UnpackedRecord *pPKey2 /* Right key */
73975 ){
73976  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
73977 }
73978 
73979 
73980 /*
73981 ** This function is an optimized version of sqlite3VdbeRecordCompare()
73982 ** that (a) the first field of pPKey2 is an integer, and (b) the
73983 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
73984 ** byte (i.e. is less than 128).
73985 **
73986 ** To avoid concerns about buffer overreads, this routine is only used
73987 ** on schemas where the maximum valid header size is 63 bytes or less.
73988 */
73990  int nKey1, const void *pKey1, /* Left key */
73991  UnpackedRecord *pPKey2 /* Right key */
73992 ){
73993  const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
73994  int serial_type = ((const u8*)pKey1)[1];
73995  int res;
73996  u32 y;
73997  u64 x;
73998  i64 v = pPKey2->aMem[0].u.i;
73999  i64 lhs;
74000 
74001  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74002  assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
74003  switch( serial_type ){
74004  case 1: { /* 1-byte signed integer */
74005  lhs = ONE_BYTE_INT(aKey);
74006  testcase( lhs<0 );
74007  break;
74008  }
74009  case 2: { /* 2-byte signed integer */
74010  lhs = TWO_BYTE_INT(aKey);
74011  testcase( lhs<0 );
74012  break;
74013  }
74014  case 3: { /* 3-byte signed integer */
74015  lhs = THREE_BYTE_INT(aKey);
74016  testcase( lhs<0 );
74017  break;
74018  }
74019  case 4: { /* 4-byte signed integer */
74020  y = FOUR_BYTE_UINT(aKey);
74021  lhs = (i64)*(int*)&y;
74022  testcase( lhs<0 );
74023  break;
74024  }
74025  case 5: { /* 6-byte signed integer */
74026  lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
74027  testcase( lhs<0 );
74028  break;
74029  }
74030  case 6: { /* 8-byte signed integer */
74031  x = FOUR_BYTE_UINT(aKey);
74032  x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
74033  lhs = *(i64*)&x;
74034  testcase( lhs<0 );
74035  break;
74036  }
74037  case 8:
74038  lhs = 0;
74039  break;
74040  case 9:
74041  lhs = 1;
74042  break;
74043 
74044  /* This case could be removed without changing the results of running
74045  ** this code. Including it causes gcc to generate a faster switch
74046  ** statement (since the range of switch targets now starts at zero and
74047  ** is contiguous) but does not cause any duplicate code to be generated
74048  ** (as gcc is clever enough to combine the two like cases). Other
74049  ** compilers might be similar. */
74050  case 0: case 7:
74051  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74052 
74053  default:
74054  return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
74055  }
74056 
74057  if( v>lhs ){
74058  res = pPKey2->r1;
74059  }else if( v<lhs ){
74060  res = pPKey2->r2;
74061  }else if( pPKey2->nField>1 ){
74062  /* The first fields of the two keys are equal. Compare the trailing
74063  ** fields. */
74064  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74065  }else{
74066  /* The first fields of the two keys are equal and there are no trailing
74067  ** fields. Return pPKey2->default_rc in this case. */
74068  res = pPKey2->default_rc;
74069  pPKey2->eqSeen = 1;
74070  }
74071 
74072  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
74073  return res;
74074 }
74075 
74076 /*
74077 ** This function is an optimized version of sqlite3VdbeRecordCompare()
74078 ** that (a) the first field of pPKey2 is a string, that (b) the first field
74079 ** uses the collation sequence BINARY and (c) that the size-of-header varint
74080 ** at the start of (pKey1/nKey1) fits in a single byte.
74081 */
74083  int nKey1, const void *pKey1, /* Left key */
74084  UnpackedRecord *pPKey2 /* Right key */
74085 ){
74086  const u8 *aKey1 = (const u8*)pKey1;
74087  int serial_type;
74088  int res;
74089 
74090  assert( pPKey2->aMem[0].flags & MEM_Str );
74091  vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
74092  getVarint32(&aKey1[1], serial_type);
74093  if( serial_type<12 ){
74094  res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
74095  }else if( !(serial_type & 0x01) ){
74096  res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
74097  }else{
74098  int nCmp;
74099  int nStr;
74100  int szHdr = aKey1[0];
74101 
74102  nStr = (serial_type-12) / 2;
74103  if( (szHdr + nStr) > nKey1 ){
74104  pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
74105  return 0; /* Corruption */
74106  }
74107  nCmp = MIN( pPKey2->aMem[0].n, nStr );
74108  res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
74109 
74110  if( res==0 ){
74111  res = nStr - pPKey2->aMem[0].n;
74112  if( res==0 ){
74113  if( pPKey2->nField>1 ){
74114  res = sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
74115  }else{
74116  res = pPKey2->default_rc;
74117  pPKey2->eqSeen = 1;
74118  }
74119  }else if( res>0 ){
74120  res = pPKey2->r2;
74121  }else{
74122  res = pPKey2->r1;
74123  }
74124  }else if( res>0 ){
74125  res = pPKey2->r2;
74126  }else{
74127  res = pPKey2->r1;
74128  }
74129  }
74130 
74131  assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
74132  || CORRUPT_DB
74133  || pPKey2->pKeyInfo->db->mallocFailed
74134  );
74135  return res;
74136 }
74137 
74138 /*
74139 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
74140 ** suitable for comparing serialized records to the unpacked record passed
74141 ** as the only argument.
74142 */
74144  /* varintRecordCompareInt() and varintRecordCompareString() both assume
74145  ** that the size-of-header varint that occurs at the start of each record
74146  ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
74147  ** also assumes that it is safe to overread a buffer by at least the
74148  ** maximum possible legal header size plus 8 bytes. Because there is
74149  ** guaranteed to be at least 74 (but not 136) bytes of padding following each
74150  ** buffer passed to varintRecordCompareInt() this makes it convenient to
74151  ** limit the size of the header to 64 bytes in cases where the first field
74152  ** is an integer.
74153  **
74154  ** The easiest way to enforce this limit is to consider only records with
74155  ** 13 fields or less. If the first field is an integer, the maximum legal
74156  ** header size is (12*5 + 1 + 1) bytes. */
74157  if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
74158  int flags = p->aMem[0].flags;
74159  if( p->pKeyInfo->aSortOrder[0] ){
74160  p->r1 = 1;
74161  p->r2 = -1;
74162  }else{
74163  p->r1 = -1;
74164  p->r2 = 1;
74165  }
74166  if( (flags & MEM_Int) ){
74167  return vdbeRecordCompareInt;
74168  }
74169  testcase( flags & MEM_Real );
74170  testcase( flags & MEM_Null );
74171  testcase( flags & MEM_Blob );
74172  if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
74173  assert( flags & MEM_Str );
74174  return vdbeRecordCompareString;
74175  }
74176  }
74177 
74178  return sqlite3VdbeRecordCompare;
74179 }
74180 
74181 /*
74182 ** pCur points at an index entry created using the OP_MakeRecord opcode.
74183 ** Read the rowid (the last field in the record) and store it in *rowid.
74184 ** Return SQLITE_OK if everything works, or an error code otherwise.
74185 **
74186 ** pCur might be pointing to text obtained from a corrupt database file.
74187 ** So the content cannot be trusted. Do appropriate checks on the content.
74188 */
74190  i64 nCellKey = 0;
74191  int rc;
74192  u32 szHdr; /* Size of the header */
74193  u32 typeRowid; /* Serial type of the rowid */
74194  u32 lenRowid; /* Size of the rowid */
74195  Mem m, v;
74196 
74197  /* Get the size of the index entry. Only indices entries of less
74198  ** than 2GiB are support - anything large must be database corruption.
74199  ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
74200  ** this code can safely assume that nCellKey is 32-bits
74201  */
74202  assert( sqlite3BtreeCursorIsValid(pCur) );
74203  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
74204  assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
74205  assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
74206 
74207  /* Read in the complete content of the index entry */
74208  sqlite3VdbeMemInit(&m, db, 0);
74209  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74210  if( rc ){
74211  return rc;
74212  }
74213 
74214  /* The index entry must begin with a header size */
74215  (void)getVarint32((u8*)m.z, szHdr);
74216  testcase( szHdr==3 );
74217  testcase( szHdr==m.n );
74218  if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
74219  goto idx_rowid_corruption;
74220  }
74221 
74222  /* The last field of the index should be an integer - the ROWID.
74223  ** Verify that the last entry really is an integer. */
74224  (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
74225  testcase( typeRowid==1 );
74226  testcase( typeRowid==2 );
74227  testcase( typeRowid==3 );
74228  testcase( typeRowid==4 );
74229  testcase( typeRowid==5 );
74230  testcase( typeRowid==6 );
74231  testcase( typeRowid==8 );
74232  testcase( typeRowid==9 );
74233  if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
74234  goto idx_rowid_corruption;
74235  }
74236  lenRowid = sqlite3SmallTypeSizes[typeRowid];
74237  testcase( (u32)m.n==szHdr+lenRowid );
74238  if( unlikely((u32)m.n<szHdr+lenRowid) ){
74239  goto idx_rowid_corruption;
74240  }
74241 
74242  /* Fetch the integer off the end of the index record */
74243  sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
74244  *rowid = v.u.i;
74246  return SQLITE_OK;
74247 
74248  /* Jump here if database corruption is detected after m has been
74249  ** allocated. Free the m object and return SQLITE_CORRUPT. */
74250 idx_rowid_corruption:
74251  testcase( m.szMalloc!=0 );
74253  return SQLITE_CORRUPT_BKPT;
74254 }
74255 
74256 /*
74257 ** Compare the key of the index entry that cursor pC is pointing to against
74258 ** the key string in pUnpacked. Write into *pRes a number
74259 ** that is negative, zero, or positive if pC is less than, equal to,
74260 ** or greater than pUnpacked. Return SQLITE_OK on success.
74261 **
74262 ** pUnpacked is either created without a rowid or is truncated so that it
74263 ** omits the rowid at the end. The rowid at the end of the index entry
74264 ** is ignored as well. Hence, this routine only compares the prefixes
74265 ** of the keys prior to the final rowid, not the entire key.
74266 */
74268  sqlite3 *db, /* Database connection */
74269  VdbeCursor *pC, /* The cursor to compare against */
74270  UnpackedRecord *pUnpacked, /* Unpacked version of key */
74271  int *res /* Write the comparison result here */
74272 ){
74273  i64 nCellKey = 0;
74274  int rc;
74275  BtCursor *pCur;
74276  Mem m;
74277 
74278  assert( pC->eCurType==CURTYPE_BTREE );
74279  pCur = pC->uc.pCursor;
74280  assert( sqlite3BtreeCursorIsValid(pCur) );
74281  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
74282  assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
74283  /* nCellKey will always be between 0 and 0xffffffff because of the way
74284  ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
74285  if( nCellKey<=0 || nCellKey>0x7fffffff ){
74286  *res = 0;
74287  return SQLITE_CORRUPT_BKPT;
74288  }
74289  sqlite3VdbeMemInit(&m, db, 0);
74290  rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
74291  if( rc ){
74292  return rc;
74293  }
74294  *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
74296  return SQLITE_OK;
74297 }
74298 
74299 /*
74300 ** This routine sets the value to be returned by subsequent calls to
74301 ** sqlite3_changes() on the database handle 'db'.
74302 */
74305  db->nChange = nChange;
74306  db->nTotalChange += nChange;
74307 }
74308 
74309 /*
74310 ** Set a flag in the vdbe to update the change counter when it is finalised
74311 ** or reset.
74312 */
74314  v->changeCntOn = 1;
74315 }
74316 
74317 /*
74318 ** Mark every prepared statement associated with a database connection
74319 ** as expired.
74320 **
74321 ** An expired statement means that recompilation of the statement is
74322 ** recommend. Statements expire when things happen that make their
74323 ** programs obsolete. Removing user-defined functions or collating
74324 ** sequences, or changing an authorization function are the types of
74325 ** things that make prepared statements obsolete.
74326 */
74328  Vdbe *p;
74329  for(p = db->pVdbe; p; p=p->pNext){
74330  p->expired = 1;
74331  }
74332 }
74333 
74334 /*
74335 ** Return the database associated with the Vdbe.
74336 */
74338  return v->db;
74339 }
74340 
74341 /*
74342 ** Return a pointer to an sqlite3_value structure containing the value bound
74343 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
74344 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
74345 ** constants) to the value before returning it.
74346 **
74347 ** The returned value must be freed by the caller using sqlite3ValueFree().
74348 */
74350  assert( iVar>0 );
74351  if( v ){
74352  Mem *pMem = &v->aVar[iVar-1];
74353  if( 0==(pMem->flags & MEM_Null) ){
74354  sqlite3_value *pRet = sqlite3ValueNew(v->db);
74355  if( pRet ){
74356  sqlite3VdbeMemCopy((Mem *)pRet, pMem);
74358  }
74359  return pRet;
74360  }
74361  }
74362  return 0;
74363 }
74364 
74365 /*
74366 ** Configure SQL variable iVar so that binding a new value to it signals
74367 ** to sqlite3_reoptimize() that re-preparing the statement may result
74368 ** in a better query plan.
74369 */
74371  assert( iVar>0 );
74372  if( iVar>32 ){
74373  v->expmask = 0xffffffff;
74374  }else{
74375  v->expmask |= ((u32)1 << (iVar-1));
74376  }
74377 }
74378 
74379 #ifndef SQLITE_OMIT_VIRTUALTABLE
74380 /*
74381 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
74382 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
74383 ** in memory obtained from sqlite3DbMalloc).
74384 */
74386  if( pVtab->zErrMsg ){
74387  sqlite3 *db = p->db;
74388  sqlite3DbFree(db, p->zErrMsg);
74389  p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
74390  sqlite3_free(pVtab->zErrMsg);
74391  pVtab->zErrMsg = 0;
74392  }
74393 }
74394 #endif /* SQLITE_OMIT_VIRTUALTABLE */
74395 
74396 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74397 
74398 /*
74399 ** If the second argument is not NULL, release any allocations associated
74400 ** with the memory cells in the p->aMem[] array. Also free the UnpackedRecord
74401 ** structure itself, using sqlite3DbFree().
74402 **
74403 ** This function is used to free UnpackedRecord structures allocated by
74404 ** the vdbeUnpackRecord() function found in vdbeapi.c.
74405 */
74406 static void vdbeFreeUnpacked(sqlite3 *db, UnpackedRecord *p){
74407  if( p ){
74408  int i;
74409  for(i=0; i<p->nField; i++){
74410  Mem *pMem = &p->aMem[i];
74411  if( pMem->zMalloc ) sqlite3VdbeMemRelease(pMem);
74412  }
74413  sqlite3DbFree(db, p);
74414  }
74415 }
74416 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74417 
74418 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
74419 /*
74420 ** Invoke the pre-update hook. If this is an UPDATE or DELETE pre-update call,
74421 ** then cursor passed as the second argument should point to the row about
74422 ** to be update or deleted. If the application calls sqlite3_preupdate_old(),
74423 ** the required value will be read from the row the cursor points to.
74424 */
74425 SQLITE_PRIVATE void sqlite3VdbePreUpdateHook(
74426  Vdbe *v, /* Vdbe pre-update hook is invoked by */
74427  VdbeCursor *pCsr, /* Cursor to grab old.* values from */
74428  int op, /* SQLITE_INSERT, UPDATE or DELETE */
74429  const char *zDb, /* Database name */
74430  Table *pTab, /* Modified table */
74431  i64 iKey1, /* Initial key value */
74432  int iReg /* Register for new.* record */
74433 ){
74434  sqlite3 *db = v->db;
74435  i64 iKey2;
74436  PreUpdate preupdate;
74437  const char *zTbl = pTab->zName;
74438  static const u8 fakeSortOrder = 0;
74439 
74440  assert( db->pPreUpdate==0 );
74441  memset(&preupdate, 0, sizeof(PreUpdate));
74442  if( op==SQLITE_UPDATE ){
74443  iKey2 = v->aMem[iReg].u.i;
74444  }else{
74445  iKey2 = iKey1;
74446  }
74447 
74448  assert( pCsr->nField==pTab->nCol
74449  || (pCsr->nField==pTab->nCol+1 && op==SQLITE_DELETE && iReg==-1)
74450  );
74451 
74452  preupdate.v = v;
74453  preupdate.pCsr = pCsr;
74454  preupdate.op = op;
74455  preupdate.iNewReg = iReg;
74456  preupdate.keyinfo.db = db;
74457  preupdate.keyinfo.enc = ENC(db);
74458  preupdate.keyinfo.nField = pTab->nCol;
74459  preupdate.keyinfo.aSortOrder = (u8*)&fakeSortOrder;
74460  preupdate.iKey1 = iKey1;
74461  preupdate.iKey2 = iKey2;
74462  preupdate.iPKey = pTab->iPKey;
74463 
74464  db->pPreUpdate = &preupdate;
74465  db->xPreUpdateCallback(db->pPreUpdateArg, db, op, zDb, zTbl, iKey1, iKey2);
74466  db->pPreUpdate = 0;
74467  sqlite3DbFree(db, preupdate.aRecord);
74468  vdbeFreeUnpacked(db, preupdate.pUnpacked);
74469  vdbeFreeUnpacked(db, preupdate.pNewUnpacked);
74470  if( preupdate.aNew ){
74471  int i;
74472  for(i=0; i<pCsr->nField; i++){
74473  sqlite3VdbeMemRelease(&preupdate.aNew[i]);
74474  }
74475  sqlite3DbFree(db, preupdate.aNew);
74476  }
74477 }
74478 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
74479 
74480 /************** End of vdbeaux.c *********************************************/
74481 /************** Begin file vdbeapi.c *****************************************/
74482 /*
74483 ** 2004 May 26
74484 **
74485 ** The author disclaims copyright to this source code. In place of
74486 ** a legal notice, here is a blessing:
74487 **
74488 ** May you do good and not evil.
74489 ** May you find forgiveness for yourself and forgive others.
74490 ** May you share freely, never taking more than you give.
74491 **
74492 *************************************************************************
74493 **
74494 ** This file contains code use to implement APIs that are part of the
74495 ** VDBE.
74496 */
74497 /* #include "sqliteInt.h" */
74498 /* #include "vdbeInt.h" */
74499 
74500 #ifndef SQLITE_OMIT_DEPRECATED
74501 /*
74502 ** Return TRUE (non-zero) of the statement supplied as an argument needs
74503 ** to be recompiled. A statement needs to be recompiled whenever the
74504 ** execution environment changes in a way that would alter the program
74505 ** that sqlite3_prepare() generates. For example, if new functions or
74506 ** collating sequences are registered or if an authorizer function is
74507 ** added or changed.
74508 */
74510  Vdbe *p = (Vdbe*)pStmt;
74511  return p==0 || p->expired;
74512 }
74513 #endif
74514 
74515 /*
74516 ** Check on a Vdbe to make sure it has not been finalized. Log
74517 ** an error and return true if it has been finalized (or is otherwise
74518 ** invalid). Return false if it is ok.
74519 */
74520 static int vdbeSafety(Vdbe *p){
74521  if( p->db==0 ){
74522  sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
74523  return 1;
74524  }else{
74525  return 0;
74526  }
74527 }
74528 static int vdbeSafetyNotNull(Vdbe *p){
74529  if( p==0 ){
74530  sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
74531  return 1;
74532  }else{
74533  return vdbeSafety(p);
74534  }
74535 }
74536 
74537 #ifndef SQLITE_OMIT_TRACE
74538 /*
74539 ** Invoke the profile callback. This routine is only called if we already
74540 ** know that the profile callback is defined and needs to be invoked.
74541 */
74543  sqlite3_int64 iNow;
74544  assert( p->startTime>0 );
74545  assert( db->xProfile!=0 );
74546  assert( db->init.busy==0 );
74547  assert( p->zSql!=0 );
74548  sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
74549  db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
74550  p->startTime = 0;
74551 }
74552 /*
74553 ** The checkProfileCallback(DB,P) macro checks to see if a profile callback
74554 ** is needed, and it invokes the callback if it is needed.
74555 */
74556 # define checkProfileCallback(DB,P) \
74557  if( ((P)->startTime)>0 ){ invokeProfileCallback(DB,P); }
74558 #else
74559 # define checkProfileCallback(DB,P) /*no-op*/
74560 #endif
74561 
74562 /*
74563 ** The following routine destroys a virtual machine that is created by
74564 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
74565 ** success/failure code that describes the result of executing the virtual
74566 ** machine.
74567 **
74568 ** This routine sets the error code and string returned by
74569 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
74570 */
74572  int rc;
74573  if( pStmt==0 ){
74574  /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
74575  ** pointer is a harmless no-op. */
74576  rc = SQLITE_OK;
74577  }else{
74578  Vdbe *v = (Vdbe*)pStmt;
74579  sqlite3 *db = v->db;
74580  if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
74582  checkProfileCallback(db, v);
74583  rc = sqlite3VdbeFinalize(v);
74584  rc = sqlite3ApiExit(db, rc);
74586  }
74587  return rc;
74588 }
74589 
74590 /*
74591 ** Terminate the current execution of an SQL statement and reset it
74592 ** back to its starting state so that it can be reused. A success code from
74593 ** the prior execution is returned.
74594 **
74595 ** This routine sets the error code and string returned by
74596 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
74597 */
74599  int rc;
74600  if( pStmt==0 ){
74601  rc = SQLITE_OK;
74602  }else{
74603  Vdbe *v = (Vdbe*)pStmt;
74604  sqlite3 *db = v->db;
74606  checkProfileCallback(db, v);
74607  rc = sqlite3VdbeReset(v);
74608  sqlite3VdbeRewind(v);
74609  assert( (rc & (db->errMask))==rc );
74610  rc = sqlite3ApiExit(db, rc);
74612  }
74613  return rc;
74614 }
74615 
74616 /*
74617 ** Set all the parameters in the compiled SQL statement to NULL.
74618 */
74620  int i;
74621  int rc = SQLITE_OK;
74622  Vdbe *p = (Vdbe*)pStmt;
74623 #if SQLITE_THREADSAFE
74624  sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
74625 #endif
74626  sqlite3_mutex_enter(mutex);
74627  for(i=0; i<p->nVar; i++){
74628  sqlite3VdbeMemRelease(&p->aVar[i]);
74629  p->aVar[i].flags = MEM_Null;
74630  }
74631  if( p->isPrepareV2 && p->expmask ){
74632  p->expired = 1;
74633  }
74634  sqlite3_mutex_leave(mutex);
74635  return rc;
74636 }
74637 
74638 
74639 /**************************** sqlite3_value_ *******************************
74640 ** The following routines extract information from a Mem or sqlite3_value
74641 ** structure.
74642 */
74644  Mem *p = (Mem*)pVal;
74645  if( p->flags & (MEM_Blob|MEM_Str) ){
74647  assert( p->flags==MEM_Null && p->z==0 );
74648  return 0;
74649  }
74650  p->flags |= MEM_Blob;
74651  return p->n ? p->z : 0;
74652  }else{
74653  return sqlite3_value_text(pVal);
74654  }
74655 }
74657  return sqlite3ValueBytes(pVal, SQLITE_UTF8);
74658 }
74660  return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
74661 }
74663  return sqlite3VdbeRealValue((Mem*)pVal);
74664 }
74666  return (int)sqlite3VdbeIntValue((Mem*)pVal);
74667 }
74669  return sqlite3VdbeIntValue((Mem*)pVal);
74670 }
74672  Mem *pMem = (Mem*)pVal;
74673  return ((pMem->flags & MEM_Subtype) ? pMem->eSubtype : 0);
74674 }
74676  return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
74677 }
74678 #ifndef SQLITE_OMIT_UTF16
74680  return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
74681 }
74683  return sqlite3ValueText(pVal, SQLITE_UTF16BE);
74684 }
74686  return sqlite3ValueText(pVal, SQLITE_UTF16LE);
74687 }
74688 #endif /* SQLITE_OMIT_UTF16 */
74689 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
74690 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
74691 ** point number string BLOB NULL
74692 */
74694  static const u8 aType[] = {
74695  SQLITE_BLOB, /* 0x00 */
74696  SQLITE_NULL, /* 0x01 */
74697  SQLITE_TEXT, /* 0x02 */
74698  SQLITE_NULL, /* 0x03 */
74699  SQLITE_INTEGER, /* 0x04 */
74700  SQLITE_NULL, /* 0x05 */
74701  SQLITE_INTEGER, /* 0x06 */
74702  SQLITE_NULL, /* 0x07 */
74703  SQLITE_FLOAT, /* 0x08 */
74704  SQLITE_NULL, /* 0x09 */
74705  SQLITE_FLOAT, /* 0x0a */
74706  SQLITE_NULL, /* 0x0b */
74707  SQLITE_INTEGER, /* 0x0c */
74708  SQLITE_NULL, /* 0x0d */
74709  SQLITE_INTEGER, /* 0x0e */
74710  SQLITE_NULL, /* 0x0f */
74711  SQLITE_BLOB, /* 0x10 */
74712  SQLITE_NULL, /* 0x11 */
74713  SQLITE_TEXT, /* 0x12 */
74714  SQLITE_NULL, /* 0x13 */
74715  SQLITE_INTEGER, /* 0x14 */
74716  SQLITE_NULL, /* 0x15 */
74717  SQLITE_INTEGER, /* 0x16 */
74718  SQLITE_NULL, /* 0x17 */
74719  SQLITE_FLOAT, /* 0x18 */
74720  SQLITE_NULL, /* 0x19 */
74721  SQLITE_FLOAT, /* 0x1a */
74722  SQLITE_NULL, /* 0x1b */
74723  SQLITE_INTEGER, /* 0x1c */
74724  SQLITE_NULL, /* 0x1d */
74725  SQLITE_INTEGER, /* 0x1e */
74726  SQLITE_NULL, /* 0x1f */
74727  };
74728  return aType[pVal->flags&MEM_AffMask];
74729 }
74730 
74731 /* Make a copy of an sqlite3_value object
74732 */
74734  sqlite3_value *pNew;
74735  if( pOrig==0 ) return 0;
74736  pNew = sqlite3_malloc( sizeof(*pNew) );
74737  if( pNew==0 ) return 0;
74738  memset(pNew, 0, sizeof(*pNew));
74739  memcpy(pNew, pOrig, MEMCELLSIZE);
74740  pNew->flags &= ~MEM_Dyn;
74741  pNew->db = 0;
74742  if( pNew->flags&(MEM_Str|MEM_Blob) ){
74743  pNew->flags &= ~(MEM_Static|MEM_Dyn);
74744  pNew->flags |= MEM_Ephem;
74746  sqlite3ValueFree(pNew);
74747  pNew = 0;
74748  }
74749  }
74750  return pNew;
74751 }
74752 
74753 /* Destroy an sqlite3_value object previously obtained from
74754 ** sqlite3_value_dup().
74755 */
74757  sqlite3ValueFree(pOld);
74758 }
74759 
74760 
74761 /**************************** sqlite3_result_ *******************************
74762 ** The following routines are used by user-defined functions to specify
74763 ** the function result.
74764 **
74765 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
74766 ** result as a string or blob but if the string or blob is too large, it
74767 ** then sets the error code to SQLITE_TOOBIG
74768 **
74769 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
74770 ** on value P is not going to be used and need to be destroyed.
74771 */
74773  sqlite3_context *pCtx, /* Function context */
74774  const char *z, /* String pointer */
74775  int n, /* Bytes in string, or negative */
74776  u8 enc, /* Encoding of z. 0 for BLOBs */
74777  void (*xDel)(void*) /* Destructor function */
74778 ){
74779  if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
74781  }
74782 }
74784  const void *p, /* Value to destroy */
74785  void (*xDel)(void*), /* The destructor */
74786  sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
74787 ){
74788  assert( xDel!=SQLITE_DYNAMIC );
74789  if( xDel==0 ){
74790  /* noop */
74791  }else if( xDel==SQLITE_TRANSIENT ){
74792  /* noop */
74793  }else{
74794  xDel((void*)p);
74795  }
74796  if( pCtx ) sqlite3_result_error_toobig(pCtx);
74797  return SQLITE_TOOBIG;
74798 }
74800  sqlite3_context *pCtx,
74801  const void *z,
74802  int n,
74803  void (*xDel)(void *)
74804 ){
74805  assert( n>=0 );
74806  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74807  setResultStrOrError(pCtx, z, n, 0, xDel);
74808 }
74810  sqlite3_context *pCtx,
74811  const void *z,
74812  sqlite3_uint64 n,
74813  void (*xDel)(void *)
74814 ){
74815  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74816  assert( xDel!=SQLITE_DYNAMIC );
74817  if( n>0x7fffffff ){
74818  (void)invokeValueDestructor(z, xDel, pCtx);
74819  }else{
74820  setResultStrOrError(pCtx, z, (int)n, 0, xDel);
74821  }
74822 }
74824  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74825  sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
74826 }
74828  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74829  pCtx->isError = SQLITE_ERROR;
74830  pCtx->fErrorOrAux = 1;
74832 }
74833 #ifndef SQLITE_OMIT_UTF16
74835  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74836  pCtx->isError = SQLITE_ERROR;
74837  pCtx->fErrorOrAux = 1;
74839 }
74840 #endif
74842  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74843  sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
74844 }
74846  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74847  sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
74848 }
74850  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74851  sqlite3VdbeMemSetNull(pCtx->pOut);
74852 }
74854  Mem *pOut = pCtx->pOut;
74855  assert( sqlite3_mutex_held(pOut->db->mutex) );
74856  pOut->eSubtype = eSubtype & 0xff;
74857  pOut->flags |= MEM_Subtype;
74858 }
74860  sqlite3_context *pCtx,
74861  const char *z,
74862  int n,
74863  void (*xDel)(void *)
74864 ){
74865  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74866  setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
74867 }
74869  sqlite3_context *pCtx,
74870  const char *z,
74871  sqlite3_uint64 n,
74872  void (*xDel)(void *),
74873  unsigned char enc
74874 ){
74875  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74876  assert( xDel!=SQLITE_DYNAMIC );
74877  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
74878  if( n>0x7fffffff ){
74879  (void)invokeValueDestructor(z, xDel, pCtx);
74880  }else{
74881  setResultStrOrError(pCtx, z, (int)n, enc, xDel);
74882  }
74883 }
74884 #ifndef SQLITE_OMIT_UTF16
74886  sqlite3_context *pCtx,
74887  const void *z,
74888  int n,
74889  void (*xDel)(void *)
74890 ){
74891  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74892  setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
74893 }
74895  sqlite3_context *pCtx,
74896  const void *z,
74897  int n,
74898  void (*xDel)(void *)
74899 ){
74900  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74901  setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
74902 }
74904  sqlite3_context *pCtx,
74905  const void *z,
74906  int n,
74907  void (*xDel)(void *)
74908 ){
74909  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74910  setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
74911 }
74912 #endif /* SQLITE_OMIT_UTF16 */
74914  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74915  sqlite3VdbeMemCopy(pCtx->pOut, pValue);
74916 }
74918  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74919  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
74920 }
74922  Mem *pOut = pCtx->pOut;
74923  assert( sqlite3_mutex_held(pOut->db->mutex) );
74924  if( n>(u64)pOut->db->aLimit[SQLITE_LIMIT_LENGTH] ){
74925  return SQLITE_TOOBIG;
74926  }
74927  sqlite3VdbeMemSetZeroBlob(pCtx->pOut, (int)n);
74928  return SQLITE_OK;
74929 }
74931  pCtx->isError = errCode;
74932  pCtx->fErrorOrAux = 1;
74933 #ifdef SQLITE_DEBUG
74934  if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
74935 #endif
74936  if( pCtx->pOut->flags & MEM_Null ){
74937  sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
74939  }
74940 }
74941 
74942 /* Force an SQLITE_TOOBIG error. */
74944  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74945  pCtx->isError = SQLITE_TOOBIG;
74946  pCtx->fErrorOrAux = 1;
74947  sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
74949 }
74950 
74951 /* An SQLITE_NOMEM error. */
74953  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
74954  sqlite3VdbeMemSetNull(pCtx->pOut);
74955  pCtx->isError = SQLITE_NOMEM_BKPT;
74956  pCtx->fErrorOrAux = 1;
74957  sqlite3OomFault(pCtx->pOut->db);
74958 }
74959 
74960 /*
74961 ** This function is called after a transaction has been committed. It
74962 ** invokes callbacks registered with sqlite3_wal_hook() as required.
74963 */
74964 static int doWalCallbacks(sqlite3 *db){
74965  int rc = SQLITE_OK;
74966 #ifndef SQLITE_OMIT_WAL
74967  int i;
74968  for(i=0; i<db->nDb; i++){
74969  Btree *pBt = db->aDb[i].pBt;
74970  if( pBt ){
74971  int nEntry;
74972  sqlite3BtreeEnter(pBt);
74974  sqlite3BtreeLeave(pBt);
74975  if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
74976  rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
74977  }
74978  }
74979  }
74980 #endif
74981  return rc;
74982 }
74983 
74984 
74985 /*
74986 ** Execute the statement pStmt, either until a row of data is ready, the
74987 ** statement is completely executed or an error occurs.
74988 **
74989 ** This routine implements the bulk of the logic behind the sqlite_step()
74990 ** API. The only thing omitted is the automatic recompile if a
74991 ** schema change has occurred. That detail is handled by the
74992 ** outer sqlite3_step() wrapper procedure.
74993 */
74994 static int sqlite3Step(Vdbe *p){
74995  sqlite3 *db;
74996  int rc;
74997 
74998  assert(p);
74999  if( p->magic!=VDBE_MAGIC_RUN ){
75000  /* We used to require that sqlite3_reset() be called before retrying
75001  ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
75002  ** with version 3.7.0, we changed this so that sqlite3_reset() would
75003  ** be called automatically instead of throwing the SQLITE_MISUSE error.
75004  ** This "automatic-reset" change is not technically an incompatibility,
75005  ** since any application that receives an SQLITE_MISUSE is broken by
75006  ** definition.
75007  **
75008  ** Nevertheless, some published applications that were originally written
75009  ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
75010  ** returns, and those were broken by the automatic-reset change. As a
75011  ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
75012  ** legacy behavior of returning SQLITE_MISUSE for cases where the
75013  ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
75014  ** or SQLITE_BUSY error.
75015  */
75016 #ifdef SQLITE_OMIT_AUTORESET
75017  if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
75019  }else{
75020  return SQLITE_MISUSE_BKPT;
75021  }
75022 #else
75024 #endif
75025  }
75026 
75027  /* Check that malloc() has not failed. If it has, return early. */
75028  db = p->db;
75029  if( db->mallocFailed ){
75030  p->rc = SQLITE_NOMEM;
75031  return SQLITE_NOMEM_BKPT;
75032  }
75033 
75034  if( p->pc<=0 && p->expired ){
75035  p->rc = SQLITE_SCHEMA;
75036  rc = SQLITE_ERROR;
75037  goto end_of_step;
75038  }
75039  if( p->pc<0 ){
75040  /* If there are no other statements currently running, then
75041  ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
75042  ** from interrupting a statement that has not yet started.
75043  */
75044  if( db->nVdbeActive==0 ){
75045  db->u1.isInterrupted = 0;
75046  }
75047 
75048  assert( db->nVdbeWrite>0 || db->autoCommit==0
75049  || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
75050  );
75051 
75052 #ifndef SQLITE_OMIT_TRACE
75053  if( db->xProfile && !db->init.busy && p->zSql ){
75055  }else{
75056  assert( p->startTime==0 );
75057  }
75058 #endif
75059 
75060  db->nVdbeActive++;
75061  if( p->readOnly==0 ) db->nVdbeWrite++;
75062  if( p->bIsReader ) db->nVdbeRead++;
75063  p->pc = 0;
75064  }
75065 #ifdef SQLITE_DEBUG
75066  p->rcApp = SQLITE_OK;
75067 #endif
75068 #ifndef SQLITE_OMIT_EXPLAIN
75069  if( p->explain ){
75070  rc = sqlite3VdbeList(p);
75071  }else
75072 #endif /* SQLITE_OMIT_EXPLAIN */
75073  {
75074  db->nVdbeExec++;
75075  rc = sqlite3VdbeExec(p);
75076  db->nVdbeExec--;
75077  }
75078 
75079 #ifndef SQLITE_OMIT_TRACE
75080  /* If the statement completed successfully, invoke the profile callback */
75081  if( rc!=SQLITE_ROW ) checkProfileCallback(db, p);
75082 #endif
75083 
75084  if( rc==SQLITE_DONE ){
75085  assert( p->rc==SQLITE_OK );
75086  p->rc = doWalCallbacks(db);
75087  if( p->rc!=SQLITE_OK ){
75088  rc = SQLITE_ERROR;
75089  }
75090  }
75091 
75092  db->errCode = rc;
75093  if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
75094  p->rc = SQLITE_NOMEM_BKPT;
75095  }
75096 end_of_step:
75097  /* At this point local variable rc holds the value that should be
75098  ** returned if this statement was compiled using the legacy
75099  ** sqlite3_prepare() interface. According to the docs, this can only
75100  ** be one of the values in the first assert() below. Variable p->rc
75101  ** contains the value that would be returned if sqlite3_finalize()
75102  ** were called on statement p.
75103  */
75104  assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
75105  || (rc&0xff)==SQLITE_BUSY || rc==SQLITE_MISUSE
75106  );
75107  assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
75108  if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
75109  /* If this statement was prepared using sqlite3_prepare_v2(), and an
75110  ** error has occurred, then return the error code in p->rc to the
75111  ** caller. Set the error code in the database handle to the same value.
75112  */
75113  rc = sqlite3VdbeTransferError(p);
75114  }
75115  return (rc&db->errMask);
75116 }
75117 
75118 /*
75119 ** This is the top-level implementation of sqlite3_step(). Call
75120 ** sqlite3Step() to do most of the work. If a schema error occurs,
75121 ** call sqlite3Reprepare() and try again.
75122 */
75124  int rc = SQLITE_OK; /* Result from sqlite3Step() */
75125  int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
75126  Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
75127  int cnt = 0; /* Counter to prevent infinite loop of reprepares */
75128  sqlite3 *db; /* The database connection */
75129 
75130  if( vdbeSafetyNotNull(v) ){
75131  return SQLITE_MISUSE_BKPT;
75132  }
75133  db = v->db;
75135  v->doingRerun = 0;
75136  while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
75137  && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
75138  int savedPc = v->pc;
75139  rc2 = rc = sqlite3Reprepare(v);
75140  if( rc!=SQLITE_OK) break;
75141  sqlite3_reset(pStmt);
75142  if( savedPc>=0 ) v->doingRerun = 1;
75143  assert( v->expired==0 );
75144  }
75145  if( rc2!=SQLITE_OK ){
75146  /* This case occurs after failing to recompile an sql statement.
75147  ** The error message from the SQL compiler has already been loaded
75148  ** into the database handle. This block copies the error message
75149  ** from the database handle into the statement and sets the statement
75150  ** program counter to 0 to ensure that when the statement is
75151  ** finalized or reset the parser error message is available via
75152  ** sqlite3_errmsg() and sqlite3_errcode().
75153  */
75154  const char *zErr = (const char *)sqlite3_value_text(db->pErr);
75155  sqlite3DbFree(db, v->zErrMsg);
75156  if( !db->mallocFailed ){
75157  v->zErrMsg = sqlite3DbStrDup(db, zErr);
75158  v->rc = rc2;
75159  } else {
75160  v->zErrMsg = 0;
75161  v->rc = rc = SQLITE_NOMEM_BKPT;
75162  }
75163  }
75164  rc = sqlite3ApiExit(db, rc);
75166  return rc;
75167 }
75168 
75169 
75170 /*
75171 ** Extract the user data from a sqlite3_context structure and return a
75172 ** pointer to it.
75173 */
75175  assert( p && p->pFunc );
75176  return p->pFunc->pUserData;
75177 }
75178 
75179 /*
75180 ** Extract the user data from a sqlite3_context structure and return a
75181 ** pointer to it.
75182 **
75183 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
75184 ** returns a copy of the pointer to the database connection (the 1st
75185 ** parameter) of the sqlite3_create_function() and
75186 ** sqlite3_create_function16() routines that originally registered the
75187 ** application defined function.
75188 */
75190  assert( p && p->pOut );
75191  return p->pOut->db;
75192 }
75193 
75194 /*
75195 ** Return the current time for a statement. If the current time
75196 ** is requested more than once within the same run of a single prepared
75197 ** statement, the exact same time is returned for each invocation regardless
75198 ** of the amount of time that elapses between invocations. In other words,
75199 ** the time returned is always the time of the first call.
75200 */
75202  int rc;
75203 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
75204  sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
75205  assert( p->pVdbe!=0 );
75206 #else
75207  sqlite3_int64 iTime = 0;
75208  sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
75209 #endif
75210  if( *piTime==0 ){
75211  rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
75212  if( rc ) *piTime = 0;
75213  }
75214  return *piTime;
75215 }
75216 
75217 /*
75218 ** The following is the implementation of an SQL function that always
75219 ** fails with an error message stating that the function is used in the
75220 ** wrong context. The sqlite3_overload_function() API might construct
75221 ** SQL function that use this routine so that the functions will exist
75222 ** for name resolution but are actually overloaded by the xFindFunction
75223 ** method of virtual tables.
75224 */
75226  sqlite3_context *context, /* The function calling context */
75227  int NotUsed, /* Number of arguments to the function */
75228  sqlite3_value **NotUsed2 /* Value of each argument */
75229 ){
75230  const char *zName = context->pFunc->zName;
75231  char *zErr;
75232  UNUSED_PARAMETER2(NotUsed, NotUsed2);
75233  zErr = sqlite3_mprintf(
75234  "unable to use function %s in the requested context", zName);
75235  sqlite3_result_error(context, zErr, -1);
75236  sqlite3_free(zErr);
75237 }
75238 
75239 /*
75240 ** Create a new aggregate context for p and return a pointer to
75241 ** its pMem->z element.
75242 */
75244  Mem *pMem = p->pMem;
75245  assert( (pMem->flags & MEM_Agg)==0 );
75246  if( nByte<=0 ){
75247  sqlite3VdbeMemSetNull(pMem);
75248  pMem->z = 0;
75249  }else{
75250  sqlite3VdbeMemClearAndResize(pMem, nByte);
75251  pMem->flags = MEM_Agg;
75252  pMem->u.pDef = p->pFunc;
75253  if( pMem->z ){
75254  memset(pMem->z, 0, nByte);
75255  }
75256  }
75257  return (void*)pMem->z;
75258 }
75259 
75260 /*
75261 ** Allocate or return the aggregate context for a user function. A new
75262 ** context is allocated on the first call. Subsequent calls return the
75263 ** same context that was returned on prior calls.
75264 */
75266  assert( p && p->pFunc && p->pFunc->xFinalize );
75268  testcase( nByte<0 );
75269  if( (p->pMem->flags & MEM_Agg)==0 ){
75270  return createAggContext(p, nByte);
75271  }else{
75272  return (void*)p->pMem->z;
75273  }
75274 }
75275 
75276 /*
75277 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
75278 ** the user-function defined by pCtx.
75279 */
75281  AuxData *pAuxData;
75282 
75283  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75284 #if SQLITE_ENABLE_STAT3_OR_STAT4
75285  if( pCtx->pVdbe==0 ) return 0;
75286 #else
75287  assert( pCtx->pVdbe!=0 );
75288 #endif
75289  for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75290  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75291  }
75292 
75293  return (pAuxData ? pAuxData->pAux : 0);
75294 }
75295 
75296 /*
75297 ** Set the auxiliary data pointer and delete function, for the iArg'th
75298 ** argument to the user-function defined by pCtx. Any previous value is
75299 ** deleted by calling the delete function specified when it was set.
75300 */
75302  sqlite3_context *pCtx,
75303  int iArg,
75304  void *pAux,
75305  void (*xDelete)(void*)
75306 ){
75307  AuxData *pAuxData;
75308  Vdbe *pVdbe = pCtx->pVdbe;
75309 
75310  assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
75311  if( iArg<0 ) goto failed;
75312 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
75313  if( pVdbe==0 ) goto failed;
75314 #else
75315  assert( pVdbe!=0 );
75316 #endif
75317 
75318  for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
75319  if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
75320  }
75321  if( pAuxData==0 ){
75322  pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
75323  if( !pAuxData ) goto failed;
75324  pAuxData->iOp = pCtx->iOp;
75325  pAuxData->iArg = iArg;
75326  pAuxData->pNext = pVdbe->pAuxData;
75327  pVdbe->pAuxData = pAuxData;
75328  if( pCtx->fErrorOrAux==0 ){
75329  pCtx->isError = 0;
75330  pCtx->fErrorOrAux = 1;
75331  }
75332  }else if( pAuxData->xDelete ){
75333  pAuxData->xDelete(pAuxData->pAux);
75334  }
75335 
75336  pAuxData->pAux = pAux;
75337  pAuxData->xDelete = xDelete;
75338  return;
75339 
75340 failed:
75341  if( xDelete ){
75342  xDelete(pAux);
75343  }
75344 }
75345 
75346 #ifndef SQLITE_OMIT_DEPRECATED
75347 /*
75348 ** Return the number of times the Step function of an aggregate has been
75349 ** called.
75350 **
75351 ** This function is deprecated. Do not use it for new code. It is
75352 ** provide only to avoid breaking legacy code. New aggregate function
75353 ** implementations should keep their own counts within their aggregate
75354 ** context.
75355 */
75357  assert( p && p->pMem && p->pFunc && p->pFunc->xFinalize );
75358  return p->pMem->n;
75359 }
75360 #endif
75361 
75362 /*
75363 ** Return the number of columns in the result set for the statement pStmt.
75364 */
75366  Vdbe *pVm = (Vdbe *)pStmt;
75367  return pVm ? pVm->nResColumn : 0;
75368 }
75369 
75370 /*
75371 ** Return the number of values available from the current row of the
75372 ** currently executing statement pStmt.
75373 */
75375  Vdbe *pVm = (Vdbe *)pStmt;
75376  if( pVm==0 || pVm->pResultSet==0 ) return 0;
75377  return pVm->nResColumn;
75378 }
75379 
75380 /*
75381 ** Return a pointer to static memory containing an SQL NULL value.
75382 */
75383 static const Mem *columnNullValue(void){
75384  /* Even though the Mem structure contains an element
75385  ** of type i64, on certain architectures (x86) with certain compiler
75386  ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
75387  ** instead of an 8-byte one. This all works fine, except that when
75388  ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
75389  ** that a Mem structure is located on an 8-byte boundary. To prevent
75390  ** these assert()s from failing, when building with SQLITE_DEBUG defined
75391  ** using gcc, we force nullMem to be 8-byte aligned using the magical
75392  ** __attribute__((aligned(8))) macro. */
75393  static const Mem nullMem
75394 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
75395  __attribute__((aligned(8)))
75396 #endif
75397  = {
75398  /* .u = */ {0},
75399  /* .flags = */ (u16)MEM_Null,
75400  /* .enc = */ (u8)0,
75401  /* .eSubtype = */ (u8)0,
75402  /* .n = */ (int)0,
75403  /* .z = */ (char*)0,
75404  /* .zMalloc = */ (char*)0,
75405  /* .szMalloc = */ (int)0,
75406  /* .uTemp = */ (u32)0,
75407  /* .db = */ (sqlite3*)0,
75408  /* .xDel = */ (void(*)(void*))0,
75409 #ifdef SQLITE_DEBUG
75410  /* .pScopyFrom = */ (Mem*)0,
75411  /* .pFiller = */ (void*)0,
75412 #endif
75413  };
75414  return &nullMem;
75415 }
75416 
75417 /*
75418 ** Check to see if column iCol of the given statement is valid. If
75419 ** it is, return a pointer to the Mem for the value of that column.
75420 ** If iCol is not valid, return a pointer to a Mem which has a value
75421 ** of NULL.
75422 */
75423 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
75424  Vdbe *pVm;
75425  Mem *pOut;
75426 
75427  pVm = (Vdbe *)pStmt;
75428  if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
75429  sqlite3_mutex_enter(pVm->db->mutex);
75430  pOut = &pVm->pResultSet[i];
75431  }else{
75432  if( pVm && ALWAYS(pVm->db) ){
75433  sqlite3_mutex_enter(pVm->db->mutex);
75434  sqlite3Error(pVm->db, SQLITE_RANGE);
75435  }
75436  pOut = (Mem*)columnNullValue();
75437  }
75438  return pOut;
75439 }
75440 
75441 /*
75442 ** This function is called after invoking an sqlite3_value_XXX function on a
75443 ** column value (i.e. a value returned by evaluating an SQL expression in the
75444 ** select list of a SELECT statement) that may cause a malloc() failure. If
75445 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
75446 ** code of statement pStmt set to SQLITE_NOMEM.
75447 **
75448 ** Specifically, this is called from within:
75449 **
75450 ** sqlite3_column_int()
75451 ** sqlite3_column_int64()
75452 ** sqlite3_column_text()
75453 ** sqlite3_column_text16()
75454 ** sqlite3_column_real()
75455 ** sqlite3_column_bytes()
75456 ** sqlite3_column_bytes16()
75457 ** sqiite3_column_blob()
75458 */
75460 {
75461  /* If malloc() failed during an encoding conversion within an
75462  ** sqlite3_column_XXX API, then set the return code of the statement to
75463  ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
75464  ** and _finalize() will return NOMEM.
75465  */
75466  Vdbe *p = (Vdbe *)pStmt;
75467  if( p ){
75468  p->rc = sqlite3ApiExit(p->db, p->rc);
75470  }
75471 }
75472 
75473 /**************************** sqlite3_column_ *******************************
75474 ** The following routines are used to access elements of the current row
75475 ** in the result set.
75476 */
75478  const void *val;
75479  val = sqlite3_value_blob( columnMem(pStmt,i) );
75480  /* Even though there is no encoding conversion, value_blob() might
75481  ** need to call malloc() to expand the result of a zeroblob()
75482  ** expression.
75483  */
75484  columnMallocFailure(pStmt);
75485  return val;
75486 }
75488  int val = sqlite3_value_bytes( columnMem(pStmt,i) );
75489  columnMallocFailure(pStmt);
75490  return val;
75491 }
75493  int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
75494  columnMallocFailure(pStmt);
75495  return val;
75496 }
75498  double val = sqlite3_value_double( columnMem(pStmt,i) );
75499  columnMallocFailure(pStmt);
75500  return val;
75501 }
75503  int val = sqlite3_value_int( columnMem(pStmt,i) );
75504  columnMallocFailure(pStmt);
75505  return val;
75506 }
75508  sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
75509  columnMallocFailure(pStmt);
75510  return val;
75511 }
75512 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
75513  const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
75514  columnMallocFailure(pStmt);
75515  return val;
75516 }
75518  Mem *pOut = columnMem(pStmt, i);
75519  if( pOut->flags&MEM_Static ){
75520  pOut->flags &= ~MEM_Static;
75521  pOut->flags |= MEM_Ephem;
75522  }
75523  columnMallocFailure(pStmt);
75524  return (sqlite3_value *)pOut;
75525 }
75526 #ifndef SQLITE_OMIT_UTF16
75528  const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
75529  columnMallocFailure(pStmt);
75530  return val;
75531 }
75532 #endif /* SQLITE_OMIT_UTF16 */
75534  int iType = sqlite3_value_type( columnMem(pStmt,i) );
75535  columnMallocFailure(pStmt);
75536  return iType;
75537 }
75538 
75539 /*
75540 ** Convert the N-th element of pStmt->pColName[] into a string using
75541 ** xFunc() then return that string. If N is out of range, return 0.
75542 **
75543 ** There are up to 5 names for each column. useType determines which
75544 ** name is returned. Here are the names:
75545 **
75546 ** 0 The column name as it should be displayed for output
75547 ** 1 The datatype name for the column
75548 ** 2 The name of the database that the column derives from
75549 ** 3 The name of the table that the column derives from
75550 ** 4 The name of the table column that the result column derives from
75551 **
75552 ** If the result is not a simple column reference (if it is an expression
75553 ** or a constant) then useTypes 2, 3, and 4 return NULL.
75554 */
75555 static const void *columnName(
75556  sqlite3_stmt *pStmt,
75557  int N,
75558  const void *(*xFunc)(Mem*),
75559  int useType
75560 ){
75561  const void *ret;
75562  Vdbe *p;
75563  int n;
75564  sqlite3 *db;
75565 #ifdef SQLITE_ENABLE_API_ARMOR
75566  if( pStmt==0 ){
75568  return 0;
75569  }
75570 #endif
75571  ret = 0;
75572  p = (Vdbe *)pStmt;
75573  db = p->db;
75574  assert( db!=0 );
75575  n = sqlite3_column_count(pStmt);
75576  if( N<n && N>=0 ){
75577  N += useType*n;
75579  assert( db->mallocFailed==0 );
75580  ret = xFunc(&p->aColName[N]);
75581  /* A malloc may have failed inside of the xFunc() call. If this
75582  ** is the case, clear the mallocFailed flag and return NULL.
75583  */
75584  if( db->mallocFailed ){
75585  sqlite3OomClear(db);
75586  ret = 0;
75587  }
75589  }
75590  return ret;
75591 }
75592 
75593 /*
75594 ** Return the name of the Nth column of the result set returned by SQL
75595 ** statement pStmt.
75596 */
75598  return columnName(
75599  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
75600 }
75601 #ifndef SQLITE_OMIT_UTF16
75603  return columnName(
75604  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
75605 }
75606 #endif
75607 
75608 /*
75609 ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
75610 ** not define OMIT_DECLTYPE.
75611 */
75612 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
75613 # error "Must not define both SQLITE_OMIT_DECLTYPE \
75614  and SQLITE_ENABLE_COLUMN_METADATA"
75615 #endif
75616 
75617 #ifndef SQLITE_OMIT_DECLTYPE
75618 /*
75619 ** Return the column declaration type (if applicable) of the 'i'th column
75620 ** of the result set of SQL statement pStmt.
75621 */
75623  return columnName(
75624  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
75625 }
75626 #ifndef SQLITE_OMIT_UTF16
75628  return columnName(
75629  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
75630 }
75631 #endif /* SQLITE_OMIT_UTF16 */
75632 #endif /* SQLITE_OMIT_DECLTYPE */
75633 
75634 #ifdef SQLITE_ENABLE_COLUMN_METADATA
75635 /*
75636 ** Return the name of the database from which a result column derives.
75637 ** NULL is returned if the result column is an expression or constant or
75638 ** anything else which is not an unambiguous reference to a database column.
75639 */
75641  return columnName(
75642  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
75643 }
75644 #ifndef SQLITE_OMIT_UTF16
75646  return columnName(
75647  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
75648 }
75649 #endif /* SQLITE_OMIT_UTF16 */
75650 
75651 /*
75652 ** Return the name of the table from which a result column derives.
75653 ** NULL is returned if the result column is an expression or constant or
75654 ** anything else which is not an unambiguous reference to a database column.
75655 */
75657  return columnName(
75658  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
75659 }
75660 #ifndef SQLITE_OMIT_UTF16
75662  return columnName(
75663  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
75664 }
75665 #endif /* SQLITE_OMIT_UTF16 */
75666 
75667 /*
75668 ** Return the name of the table column from which a result column derives.
75669 ** NULL is returned if the result column is an expression or constant or
75670 ** anything else which is not an unambiguous reference to a database column.
75671 */
75673  return columnName(
75674  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
75675 }
75676 #ifndef SQLITE_OMIT_UTF16
75678  return columnName(
75679  pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
75680 }
75681 #endif /* SQLITE_OMIT_UTF16 */
75682 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
75683 
75684 
75685 /******************************* sqlite3_bind_ ***************************
75686 **
75687 ** Routines used to attach values to wildcards in a compiled SQL statement.
75688 */
75689 /*
75690 ** Unbind the value bound to variable i in virtual machine p. This is the
75691 ** the same as binding a NULL value to the column. If the "i" parameter is
75692 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
75693 **
75694 ** A successful evaluation of this routine acquires the mutex on p.
75695 ** the mutex is released if any kind of error occurs.
75696 **
75697 ** The error code stored in database p->db is overwritten with the return
75698 ** value in any case.
75699 */
75700 static int vdbeUnbind(Vdbe *p, int i){
75701  Mem *pVar;
75702  if( vdbeSafetyNotNull(p) ){
75703  return SQLITE_MISUSE_BKPT;
75704  }
75706  if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
75710  "bind on a busy prepared statement: [%s]", p->zSql);
75711  return SQLITE_MISUSE_BKPT;
75712  }
75713  if( i<1 || i>p->nVar ){
75716  return SQLITE_RANGE;
75717  }
75718  i--;
75719  pVar = &p->aVar[i];
75720  sqlite3VdbeMemRelease(pVar);
75721  pVar->flags = MEM_Null;
75722  sqlite3Error(p->db, SQLITE_OK);
75723 
75724  /* If the bit corresponding to this variable in Vdbe.expmask is set, then
75725  ** binding a new value to this variable invalidates the current query plan.
75726  **
75727  ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
75728  ** parameter in the WHERE clause might influence the choice of query plan
75729  ** for a statement, then the statement will be automatically recompiled,
75730  ** as if there had been a schema change, on the first sqlite3_step() call
75731  ** following any change to the bindings of that parameter.
75732  */
75733  if( p->isPrepareV2 &&
75734  ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
75735  ){
75736  p->expired = 1;
75737  }
75738  return SQLITE_OK;
75739 }
75740 
75741 /*
75742 ** Bind a text or BLOB value.
75743 */
75744 static int bindText(
75745  sqlite3_stmt *pStmt, /* The statement to bind against */
75746  int i, /* Index of the parameter to bind */
75747  const void *zData, /* Pointer to the data to be bound */
75748  int nData, /* Number of bytes of data to be bound */
75749  void (*xDel)(void*), /* Destructor for the data */
75750  u8 encoding /* Encoding for the data */
75751 ){
75752  Vdbe *p = (Vdbe *)pStmt;
75753  Mem *pVar;
75754  int rc;
75755 
75756  rc = vdbeUnbind(p, i);
75757  if( rc==SQLITE_OK ){
75758  if( zData!=0 ){
75759  pVar = &p->aVar[i-1];
75760  rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
75761  if( rc==SQLITE_OK && encoding!=0 ){
75762  rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
75763  }
75764  sqlite3Error(p->db, rc);
75765  rc = sqlite3ApiExit(p->db, rc);
75766  }
75768  }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
75769  xDel((void*)zData);
75770  }
75771  return rc;
75772 }
75773 
75774 
75775 /*
75776 ** Bind a blob value to an SQL statement variable.
75777 */
75779  sqlite3_stmt *pStmt,
75780  int i,
75781  const void *zData,
75782  int nData,
75783  void (*xDel)(void*)
75784 ){
75785 #ifdef SQLITE_ENABLE_API_ARMOR
75786  if( nData<0 ) return SQLITE_MISUSE_BKPT;
75787 #endif
75788  return bindText(pStmt, i, zData, nData, xDel, 0);
75789 }
75791  sqlite3_stmt *pStmt,
75792  int i,
75793  const void *zData,
75794  sqlite3_uint64 nData,
75795  void (*xDel)(void*)
75796 ){
75797  assert( xDel!=SQLITE_DYNAMIC );
75798  if( nData>0x7fffffff ){
75799  return invokeValueDestructor(zData, xDel, 0);
75800  }else{
75801  return bindText(pStmt, i, zData, (int)nData, xDel, 0);
75802  }
75803 }
75804 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
75805  int rc;
75806  Vdbe *p = (Vdbe *)pStmt;
75807  rc = vdbeUnbind(p, i);
75808  if( rc==SQLITE_OK ){
75809  sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
75811  }
75812  return rc;
75813 }
75815  return sqlite3_bind_int64(p, i, (i64)iValue);
75816 }
75817 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
75818  int rc;
75819  Vdbe *p = (Vdbe *)pStmt;
75820  rc = vdbeUnbind(p, i);
75821  if( rc==SQLITE_OK ){
75822  sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
75824  }
75825  return rc;
75826 }
75828  int rc;
75829  Vdbe *p = (Vdbe*)pStmt;
75830  rc = vdbeUnbind(p, i);
75831  if( rc==SQLITE_OK ){
75833  }
75834  return rc;
75835 }
75837  sqlite3_stmt *pStmt,
75838  int i,
75839  const char *zData,
75840  int nData,
75841  void (*xDel)(void*)
75842 ){
75843  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
75844 }
75846  sqlite3_stmt *pStmt,
75847  int i,
75848  const char *zData,
75849  sqlite3_uint64 nData,
75850  void (*xDel)(void*),
75851  unsigned char enc
75852 ){
75853  assert( xDel!=SQLITE_DYNAMIC );
75854  if( nData>0x7fffffff ){
75855  return invokeValueDestructor(zData, xDel, 0);
75856  }else{
75857  if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
75858  return bindText(pStmt, i, zData, (int)nData, xDel, enc);
75859  }
75860 }
75861 #ifndef SQLITE_OMIT_UTF16
75863  sqlite3_stmt *pStmt,
75864  int i,
75865  const void *zData,
75866  int nData,
75867  void (*xDel)(void*)
75868 ){
75869  return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
75870 }
75871 #endif /* SQLITE_OMIT_UTF16 */
75873  int rc;
75874  switch( sqlite3_value_type((sqlite3_value*)pValue) ){
75875  case SQLITE_INTEGER: {
75876  rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
75877  break;
75878  }
75879  case SQLITE_FLOAT: {
75880  rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
75881  break;
75882  }
75883  case SQLITE_BLOB: {
75884  if( pValue->flags & MEM_Zero ){
75885  rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
75886  }else{
75887  rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
75888  }
75889  break;
75890  }
75891  case SQLITE_TEXT: {
75892  rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
75893  pValue->enc);
75894  break;
75895  }
75896  default: {
75897  rc = sqlite3_bind_null(pStmt, i);
75898  break;
75899  }
75900  }
75901  return rc;
75902 }
75904  int rc;
75905  Vdbe *p = (Vdbe *)pStmt;
75906  rc = vdbeUnbind(p, i);
75907  if( rc==SQLITE_OK ){
75908  sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
75910  }
75911  return rc;
75912 }
75913 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *pStmt, int i, sqlite3_uint64 n){
75914  int rc;
75915  Vdbe *p = (Vdbe *)pStmt;
75917  if( n>(u64)p->db->aLimit[SQLITE_LIMIT_LENGTH] ){
75918  rc = SQLITE_TOOBIG;
75919  }else{
75920  assert( (n & 0x7FFFFFFF)==n );
75921  rc = sqlite3_bind_zeroblob(pStmt, i, n);
75922  }
75923  rc = sqlite3ApiExit(p->db, rc);
75925  return rc;
75926 }
75927 
75928 /*
75929 ** Return the number of wildcards that can be potentially bound to.
75930 ** This routine is added to support DBD::SQLite.
75931 */
75933  Vdbe *p = (Vdbe*)pStmt;
75934  return p ? p->nVar : 0;
75935 }
75936 
75937 /*
75938 ** Return the name of a wildcard parameter. Return NULL if the index
75939 ** is out of range or if the wildcard is unnamed.
75940 **
75941 ** The result is always UTF-8.
75942 */
75944  Vdbe *p = (Vdbe*)pStmt;
75945  if( p==0 || i<1 || i>p->nzVar ){
75946  return 0;
75947  }
75948  return p->azVar[i-1];
75949 }
75950 
75951 /*
75952 ** Given a wildcard parameter name, return the index of the variable
75953 ** with that name. If there is no variable with the given name,
75954 ** return 0.
75955 */
75956 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
75957  int i;
75958  if( p==0 ){
75959  return 0;
75960  }
75961  if( zName ){
75962  for(i=0; i<p->nzVar; i++){
75963  const char *z = p->azVar[i];
75964  if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
75965  return i+1;
75966  }
75967  }
75968  }
75969  return 0;
75970 }
75972  return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
75973 }
75974 
75975 /*
75976 ** Transfer all bindings from the first statement over to the second.
75977 */
75979  Vdbe *pFrom = (Vdbe*)pFromStmt;
75980  Vdbe *pTo = (Vdbe*)pToStmt;
75981  int i;
75982  assert( pTo->db==pFrom->db );
75983  assert( pTo->nVar==pFrom->nVar );
75984  sqlite3_mutex_enter(pTo->db->mutex);
75985  for(i=0; i<pFrom->nVar; i++){
75986  sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
75987  }
75988  sqlite3_mutex_leave(pTo->db->mutex);
75989  return SQLITE_OK;
75990 }
75991 
75992 #ifndef SQLITE_OMIT_DEPRECATED
75993 /*
75994 ** Deprecated external interface. Internal/core SQLite code
75995 ** should call sqlite3TransferBindings.
75996 **
75997 ** It is misuse to call this routine with statements from different
75998 ** database connections. But as this is a deprecated interface, we
75999 ** will not bother to check for that condition.
76000 **
76001 ** If the two statements contain a different number of bindings, then
76002 ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
76003 ** SQLITE_OK is returned.
76004 */
76006  Vdbe *pFrom = (Vdbe*)pFromStmt;
76007  Vdbe *pTo = (Vdbe*)pToStmt;
76008  if( pFrom->nVar!=pTo->nVar ){
76009  return SQLITE_ERROR;
76010  }
76011  if( pTo->isPrepareV2 && pTo->expmask ){
76012  pTo->expired = 1;
76013  }
76014  if( pFrom->isPrepareV2 && pFrom->expmask ){
76015  pFrom->expired = 1;
76016  }
76017  return sqlite3TransferBindings(pFromStmt, pToStmt);
76018 }
76019 #endif
76020 
76021 /*
76022 ** Return the sqlite3* database handle to which the prepared statement given
76023 ** in the argument belongs. This is the same database handle that was
76024 ** the first argument to the sqlite3_prepare() that was used to create
76025 ** the statement in the first place.
76026 */
76028  return pStmt ? ((Vdbe*)pStmt)->db : 0;
76029 }
76030 
76031 /*
76032 ** Return true if the prepared statement is guaranteed to not modify the
76033 ** database.
76034 */
76036  return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
76037 }
76038 
76039 /*
76040 ** Return true if the prepared statement is in need of being reset.
76041 */
76043  Vdbe *v = (Vdbe*)pStmt;
76044  return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
76045 }
76046 
76047 /*
76048 ** Return a pointer to the next prepared statement after pStmt associated
76049 ** with database connection pDb. If pStmt is NULL, return the first
76050 ** prepared statement for the database connection. Return NULL if there
76051 ** are no more.
76052 */
76054  sqlite3_stmt *pNext;
76055 #ifdef SQLITE_ENABLE_API_ARMOR
76056  if( !sqlite3SafetyCheckOk(pDb) ){
76058  return 0;
76059  }
76060 #endif
76061  sqlite3_mutex_enter(pDb->mutex);
76062  if( pStmt==0 ){
76063  pNext = (sqlite3_stmt*)pDb->pVdbe;
76064  }else{
76065  pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
76066  }
76067  sqlite3_mutex_leave(pDb->mutex);
76068  return pNext;
76069 }
76070 
76071 /*
76072 ** Return the value of a status counter for a prepared statement
76073 */
76074 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
76075  Vdbe *pVdbe = (Vdbe*)pStmt;
76076  u32 v;
76077 #ifdef SQLITE_ENABLE_API_ARMOR
76078  if( !pStmt ){
76080  return 0;
76081  }
76082 #endif
76083  v = pVdbe->aCounter[op];
76084  if( resetFlag ) pVdbe->aCounter[op] = 0;
76085  return (int)v;
76086 }
76087 
76088 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76089 /*
76090 ** Allocate and populate an UnpackedRecord structure based on the serialized
76091 ** record in nKey/pKey. Return a pointer to the new UnpackedRecord structure
76092 ** if successful, or a NULL pointer if an OOM error is encountered.
76093 */
76094 static UnpackedRecord *vdbeUnpackRecord(
76095  KeyInfo *pKeyInfo,
76096  int nKey,
76097  const void *pKey
76098 ){
76099  char *dummy; /* Dummy argument for AllocUnpackedRecord() */
76100  UnpackedRecord *pRet; /* Return value */
76101 
76102  pRet = sqlite3VdbeAllocUnpackedRecord(pKeyInfo, 0, 0, &dummy);
76103  if( pRet ){
76104  memset(pRet->aMem, 0, sizeof(Mem)*(pKeyInfo->nField+1));
76105  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, pRet);
76106  }
76107  return pRet;
76108 }
76109 
76110 /*
76111 ** This function is called from within a pre-update callback to retrieve
76112 ** a field of the row currently being updated or deleted.
76113 */
76115  PreUpdate *p = db->pPreUpdate;
76116  int rc = SQLITE_OK;
76117 
76118  /* Test that this call is being made from within an SQLITE_DELETE or
76119  ** SQLITE_UPDATE pre-update callback, and that iIdx is within range. */
76120  if( !p || p->op==SQLITE_INSERT ){
76121  rc = SQLITE_MISUSE_BKPT;
76122  goto preupdate_old_out;
76123  }
76124  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76125  rc = SQLITE_RANGE;
76126  goto preupdate_old_out;
76127  }
76128 
76129  /* If the old.* record has not yet been loaded into memory, do so now. */
76130  if( p->pUnpacked==0 ){
76131  u32 nRec;
76132  u8 *aRec;
76133 
76134  rc = sqlite3BtreeDataSize(p->pCsr->uc.pCursor, &nRec);
76135  if( rc!=SQLITE_OK ) goto preupdate_old_out;
76136  aRec = sqlite3DbMallocRaw(db, nRec);
76137  if( !aRec ) goto preupdate_old_out;
76138  rc = sqlite3BtreeData(p->pCsr->uc.pCursor, 0, nRec, aRec);
76139  if( rc==SQLITE_OK ){
76140  p->pUnpacked = vdbeUnpackRecord(&p->keyinfo, nRec, aRec);
76141  if( !p->pUnpacked ) rc = SQLITE_NOMEM;
76142  }
76143  if( rc!=SQLITE_OK ){
76144  sqlite3DbFree(db, aRec);
76145  goto preupdate_old_out;
76146  }
76147  p->aRecord = aRec;
76148  }
76149 
76150  if( iIdx>=p->pUnpacked->nField ){
76151  *ppValue = (sqlite3_value *)columnNullValue();
76152  }else{
76153  *ppValue = &p->pUnpacked->aMem[iIdx];
76154  if( iIdx==p->iPKey ){
76155  sqlite3VdbeMemSetInt64(*ppValue, p->iKey1);
76156  }
76157  }
76158 
76159  preupdate_old_out:
76160  sqlite3Error(db, rc);
76161  return sqlite3ApiExit(db, rc);
76162 }
76163 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76164 
76165 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76166 /*
76167 ** This function is called from within a pre-update callback to retrieve
76168 ** the number of columns in the row being updated, deleted or inserted.
76169 */
76171  PreUpdate *p = db->pPreUpdate;
76172  return (p ? p->keyinfo.nField : 0);
76173 }
76174 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76175 
76176 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76177 /*
76178 ** This function is designed to be called from within a pre-update callback
76179 ** only. It returns zero if the change that caused the callback was made
76180 ** immediately by a user SQL statement. Or, if the change was made by a
76181 ** trigger program, it returns the number of trigger programs currently
76182 ** on the stack (1 for a top-level trigger, 2 for a trigger fired by a
76183 ** top-level trigger etc.).
76184 **
76185 ** For the purposes of the previous paragraph, a foreign key CASCADE, SET NULL
76186 ** or SET DEFAULT action is considered a trigger.
76187 */
76189  PreUpdate *p = db->pPreUpdate;
76190  return (p ? p->v->nFrame : 0);
76191 }
76192 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76193 
76194 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76195 /*
76196 ** This function is called from within a pre-update callback to retrieve
76197 ** a field of the row currently being updated or inserted.
76198 */
76200  PreUpdate *p = db->pPreUpdate;
76201  int rc = SQLITE_OK;
76202  Mem *pMem;
76203 
76204  if( !p || p->op==SQLITE_DELETE ){
76205  rc = SQLITE_MISUSE_BKPT;
76206  goto preupdate_new_out;
76207  }
76208  if( iIdx>=p->pCsr->nField || iIdx<0 ){
76209  rc = SQLITE_RANGE;
76210  goto preupdate_new_out;
76211  }
76212 
76213  if( p->op==SQLITE_INSERT ){
76214  /* For an INSERT, memory cell p->iNewReg contains the serialized record
76215  ** that is being inserted. Deserialize it. */
76216  UnpackedRecord *pUnpack = p->pNewUnpacked;
76217  if( !pUnpack ){
76218  Mem *pData = &p->v->aMem[p->iNewReg];
76219  rc = sqlite3VdbeMemExpandBlob(pData);
76220  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76221  pUnpack = vdbeUnpackRecord(&p->keyinfo, pData->n, pData->z);
76222  if( !pUnpack ){
76223  rc = SQLITE_NOMEM;
76224  goto preupdate_new_out;
76225  }
76226  p->pNewUnpacked = pUnpack;
76227  }
76228  if( iIdx>=pUnpack->nField ){
76229  pMem = (sqlite3_value *)columnNullValue();
76230  }else{
76231  pMem = &pUnpack->aMem[iIdx];
76232  if( iIdx==p->iPKey ){
76233  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76234  }
76235  }
76236  }else{
76237  /* For an UPDATE, memory cell (p->iNewReg+1+iIdx) contains the required
76238  ** value. Make a copy of the cell contents and return a pointer to it.
76239  ** It is not safe to return a pointer to the memory cell itself as the
76240  ** caller may modify the value text encoding.
76241  */
76242  assert( p->op==SQLITE_UPDATE );
76243  if( !p->aNew ){
76244  p->aNew = (Mem *)sqlite3DbMallocZero(db, sizeof(Mem) * p->pCsr->nField);
76245  if( !p->aNew ){
76246  rc = SQLITE_NOMEM;
76247  goto preupdate_new_out;
76248  }
76249  }
76250  assert( iIdx>=0 && iIdx<p->pCsr->nField );
76251  pMem = &p->aNew[iIdx];
76252  if( pMem->flags==0 ){
76253  if( iIdx==p->iPKey ){
76254  sqlite3VdbeMemSetInt64(pMem, p->iKey2);
76255  }else{
76256  rc = sqlite3VdbeMemCopy(pMem, &p->v->aMem[p->iNewReg+1+iIdx]);
76257  if( rc!=SQLITE_OK ) goto preupdate_new_out;
76258  }
76259  }
76260  }
76261  *ppValue = pMem;
76262 
76263  preupdate_new_out:
76264  sqlite3Error(db, rc);
76265  return sqlite3ApiExit(db, rc);
76266 }
76267 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
76268 
76269 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76270 /*
76271 ** Return status data for a single loop within query pStmt.
76272 */
76274  sqlite3_stmt *pStmt, /* Prepared statement being queried */
76275  int idx, /* Index of loop to report on */
76276  int iScanStatusOp, /* Which metric to return */
76277  void *pOut /* OUT: Write the answer here */
76278 ){
76279  Vdbe *p = (Vdbe*)pStmt;
76280  ScanStatus *pScan;
76281  if( idx<0 || idx>=p->nScan ) return 1;
76282  pScan = &p->aScan[idx];
76283  switch( iScanStatusOp ){
76284  case SQLITE_SCANSTAT_NLOOP: {
76285  *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
76286  break;
76287  }
76288  case SQLITE_SCANSTAT_NVISIT: {
76289  *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
76290  break;
76291  }
76292  case SQLITE_SCANSTAT_EST: {
76293  double r = 1.0;
76294  LogEst x = pScan->nEst;
76295  while( x<100 ){
76296  x += 10;
76297  r *= 0.5;
76298  }
76299  *(double*)pOut = r*sqlite3LogEstToInt(x);
76300  break;
76301  }
76302  case SQLITE_SCANSTAT_NAME: {
76303  *(const char**)pOut = pScan->zName;
76304  break;
76305  }
76306  case SQLITE_SCANSTAT_EXPLAIN: {
76307  if( pScan->addrExplain ){
76308  *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
76309  }else{
76310  *(const char**)pOut = 0;
76311  }
76312  break;
76313  }
76314  case SQLITE_SCANSTAT_SELECTID: {
76315  if( pScan->addrExplain ){
76316  *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
76317  }else{
76318  *(int*)pOut = -1;
76319  }
76320  break;
76321  }
76322  default: {
76323  return 1;
76324  }
76325  }
76326  return 0;
76327 }
76328 
76329 /*
76330 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
76331 */
76333  Vdbe *p = (Vdbe*)pStmt;
76334  memset(p->anExec, 0, p->nOp * sizeof(i64));
76335 }
76336 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
76337 
76338 /************** End of vdbeapi.c *********************************************/
76339 /************** Begin file vdbetrace.c ***************************************/
76340 /*
76341 ** 2009 November 25
76342 **
76343 ** The author disclaims copyright to this source code. In place of
76344 ** a legal notice, here is a blessing:
76345 **
76346 ** May you do good and not evil.
76347 ** May you find forgiveness for yourself and forgive others.
76348 ** May you share freely, never taking more than you give.
76349 **
76350 *************************************************************************
76351 **
76352 ** This file contains code used to insert the values of host parameters
76353 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
76354 **
76355 ** The Vdbe parse-tree explainer is also found here.
76356 */
76357 /* #include "sqliteInt.h" */
76358 /* #include "vdbeInt.h" */
76359 
76360 #ifndef SQLITE_OMIT_TRACE
76361 
76362 /*
76363 ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
76364 ** bytes in this text up to but excluding the first character in
76365 ** a host parameter. If the text contains no host parameters, return
76366 ** the total number of bytes in the text.
76367 */
76368 static int findNextHostParameter(const char *zSql, int *pnToken){
76369  int tokenType;
76370  int nTotal = 0;
76371  int n;
76372 
76373  *pnToken = 0;
76374  while( zSql[0] ){
76375  n = sqlite3GetToken((u8*)zSql, &tokenType);
76376  assert( n>0 && tokenType!=TK_ILLEGAL );
76377  if( tokenType==TK_VARIABLE ){
76378  *pnToken = n;
76379  break;
76380  }
76381  nTotal += n;
76382  zSql += n;
76383  }
76384  return nTotal;
76385 }
76386 
76387 /*
76388 ** This function returns a pointer to a nul-terminated string in memory
76389 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
76390 ** string contains a copy of zRawSql but with host parameters expanded to
76391 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
76392 ** then the returned string holds a copy of zRawSql with "-- " prepended
76393 ** to each line of text.
76394 **
76395 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
76396 ** then long strings and blobs are truncated to that many bytes. This
76397 ** can be used to prevent unreasonably large trace strings when dealing
76398 ** with large (multi-megabyte) strings and blobs.
76399 **
76400 ** The calling function is responsible for making sure the memory returned
76401 ** is eventually freed.
76402 **
76403 ** ALGORITHM: Scan the input string looking for host parameters in any of
76404 ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
76405 ** string literals, quoted identifier names, and comments. For text forms,
76406 ** the host parameter index is found by scanning the prepared
76407 ** statement for the corresponding OP_Variable opcode. Once the host
76408 ** parameter index is known, locate the value in p->aVar[]. Then render
76409 ** the value as a literal in place of the host parameter name.
76410 */
76412  Vdbe *p, /* The prepared statement being evaluated */
76413  const char *zRawSql /* Raw text of the SQL statement */
76414 ){
76415  sqlite3 *db; /* The database connection */
76416  int idx = 0; /* Index of a host parameter */
76417  int nextIndex = 1; /* Index of next ? host parameter */
76418  int n; /* Length of a token prefix */
76419  int nToken; /* Length of the parameter token */
76420  int i; /* Loop counter */
76421  Mem *pVar; /* Value of a host parameter */
76422  StrAccum out; /* Accumulate the output here */
76423  char zBase[100]; /* Initial working space */
76424 
76425  db = p->db;
76426  sqlite3StrAccumInit(&out, db, zBase, sizeof(zBase),
76428  if( db->nVdbeExec>1 ){
76429  while( *zRawSql ){
76430  const char *zStart = zRawSql;
76431  while( *(zRawSql++)!='\n' && *zRawSql );
76432  sqlite3StrAccumAppend(&out, "-- ", 3);
76433  assert( (zRawSql - zStart) > 0 );
76434  sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
76435  }
76436  }else if( p->nVar==0 ){
76437  sqlite3StrAccumAppend(&out, zRawSql, sqlite3Strlen30(zRawSql));
76438  }else{
76439  while( zRawSql[0] ){
76440  n = findNextHostParameter(zRawSql, &nToken);
76441  assert( n>0 );
76442  sqlite3StrAccumAppend(&out, zRawSql, n);
76443  zRawSql += n;
76444  assert( zRawSql[0] || nToken==0 );
76445  if( nToken==0 ) break;
76446  if( zRawSql[0]=='?' ){
76447  if( nToken>1 ){
76448  assert( sqlite3Isdigit(zRawSql[1]) );
76449  sqlite3GetInt32(&zRawSql[1], &idx);
76450  }else{
76451  idx = nextIndex;
76452  }
76453  }else{
76454  assert( zRawSql[0]==':' || zRawSql[0]=='$' ||
76455  zRawSql[0]=='@' || zRawSql[0]=='#' );
76456  testcase( zRawSql[0]==':' );
76457  testcase( zRawSql[0]=='$' );
76458  testcase( zRawSql[0]=='@' );
76459  testcase( zRawSql[0]=='#' );
76460  idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
76461  assert( idx>0 );
76462  }
76463  zRawSql += nToken;
76464  nextIndex = idx + 1;
76465  assert( idx>0 && idx<=p->nVar );
76466  pVar = &p->aVar[idx-1];
76467  if( pVar->flags & MEM_Null ){
76468  sqlite3StrAccumAppend(&out, "NULL", 4);
76469  }else if( pVar->flags & MEM_Int ){
76470  sqlite3XPrintf(&out, "%lld", pVar->u.i);
76471  }else if( pVar->flags & MEM_Real ){
76472  sqlite3XPrintf(&out, "%!.15g", pVar->u.r);
76473  }else if( pVar->flags & MEM_Str ){
76474  int nOut; /* Number of bytes of the string text to include in output */
76475 #ifndef SQLITE_OMIT_UTF16
76476  u8 enc = ENC(db);
76477  Mem utf8;
76478  if( enc!=SQLITE_UTF8 ){
76479  memset(&utf8, 0, sizeof(utf8));
76480  utf8.db = db;
76481  sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
76483  pVar = &utf8;
76484  }
76485 #endif
76486  nOut = pVar->n;
76487 #ifdef SQLITE_TRACE_SIZE_LIMIT
76488  if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
76489  nOut = SQLITE_TRACE_SIZE_LIMIT;
76490  while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
76491  }
76492 #endif
76493  sqlite3XPrintf(&out, "'%.*q'", nOut, pVar->z);
76494 #ifdef SQLITE_TRACE_SIZE_LIMIT
76495  if( nOut<pVar->n ){
76496  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
76497  }
76498 #endif
76499 #ifndef SQLITE_OMIT_UTF16
76500  if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
76501 #endif
76502  }else if( pVar->flags & MEM_Zero ){
76503  sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
76504  }else{
76505  int nOut; /* Number of bytes of the blob to include in output */
76506  assert( pVar->flags & MEM_Blob );
76507  sqlite3StrAccumAppend(&out, "x'", 2);
76508  nOut = pVar->n;
76509 #ifdef SQLITE_TRACE_SIZE_LIMIT
76510  if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
76511 #endif
76512  for(i=0; i<nOut; i++){
76513  sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
76514  }
76515  sqlite3StrAccumAppend(&out, "'", 1);
76516 #ifdef SQLITE_TRACE_SIZE_LIMIT
76517  if( nOut<pVar->n ){
76518  sqlite3XPrintf(&out, "/*+%d bytes*/", pVar->n-nOut);
76519  }
76520 #endif
76521  }
76522  }
76523  }
76524  return sqlite3StrAccumFinish(&out);
76525 }
76526 
76527 #endif /* #ifndef SQLITE_OMIT_TRACE */
76528 
76529 /************** End of vdbetrace.c *******************************************/
76530 /************** Begin file vdbe.c ********************************************/
76531 /*
76532 ** 2001 September 15
76533 **
76534 ** The author disclaims copyright to this source code. In place of
76535 ** a legal notice, here is a blessing:
76536 **
76537 ** May you do good and not evil.
76538 ** May you find forgiveness for yourself and forgive others.
76539 ** May you share freely, never taking more than you give.
76540 **
76541 *************************************************************************
76542 ** The code in this file implements the function that runs the
76543 ** bytecode of a prepared statement.
76544 **
76545 ** Various scripts scan this source file in order to generate HTML
76546 ** documentation, headers files, or other derived files. The formatting
76547 ** of the code in this file is, therefore, important. See other comments
76548 ** in this file for details. If in doubt, do not deviate from existing
76549 ** commenting and indentation practices when changing or adding code.
76550 */
76551 /* #include "sqliteInt.h" */
76552 /* #include "vdbeInt.h" */
76553 
76554 /*
76555 ** Invoke this macro on memory cells just prior to changing the
76556 ** value of the cell. This macro verifies that shallow copies are
76557 ** not misused. A shallow copy of a string or blob just copies a
76558 ** pointer to the string or blob, not the content. If the original
76559 ** is changed while the copy is still in use, the string or blob might
76560 ** be changed out from under the copy. This macro verifies that nothing
76561 ** like that ever happens.
76562 */
76563 #ifdef SQLITE_DEBUG
76564 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
76565 #else
76566 # define memAboutToChange(P,M)
76567 #endif
76568 
76569 /*
76570 ** The following global variable is incremented every time a cursor
76571 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
76572 ** procedures use this information to make sure that indices are
76573 ** working correctly. This variable has no function other than to
76574 ** help verify the correct operation of the library.
76575 */
76576 #ifdef SQLITE_TEST
76577 SQLITE_API int sqlite3_search_count = 0;
76578 #endif
76579 
76580 /*
76581 ** When this global variable is positive, it gets decremented once before
76582 ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
76583 ** field of the sqlite3 structure is set in order to simulate an interrupt.
76584 **
76585 ** This facility is used for testing purposes only. It does not function
76586 ** in an ordinary build.
76587 */
76588 #ifdef SQLITE_TEST
76589 SQLITE_API int sqlite3_interrupt_count = 0;
76590 #endif
76591 
76592 /*
76593 ** The next global variable is incremented each type the OP_Sort opcode
76594 ** is executed. The test procedures use this information to make sure that
76595 ** sorting is occurring or not occurring at appropriate times. This variable
76596 ** has no function other than to help verify the correct operation of the
76597 ** library.
76598 */
76599 #ifdef SQLITE_TEST
76600 SQLITE_API int sqlite3_sort_count = 0;
76601 #endif
76602 
76603 /*
76604 ** The next global variable records the size of the largest MEM_Blob
76605 ** or MEM_Str that has been used by a VDBE opcode. The test procedures
76606 ** use this information to make sure that the zero-blob functionality
76607 ** is working correctly. This variable has no function other than to
76608 ** help verify the correct operation of the library.
76609 */
76610 #ifdef SQLITE_TEST
76611 SQLITE_API int sqlite3_max_blobsize = 0;
76612 static void updateMaxBlobsize(Mem *p){
76613  if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
76614  sqlite3_max_blobsize = p->n;
76615  }
76616 }
76617 #endif
76618 
76619 /*
76620 ** This macro evaluates to true if either the update hook or the preupdate
76621 ** hook are enabled for database connect DB.
76622 */
76623 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
76624 # define HAS_UPDATE_HOOK(DB) ((DB)->xPreUpdateCallback||(DB)->xUpdateCallback)
76625 #else
76626 # define HAS_UPDATE_HOOK(DB) ((DB)->xUpdateCallback)
76627 #endif
76628 
76629 /*
76630 ** The next global variable is incremented each time the OP_Found opcode
76631 ** is executed. This is used to test whether or not the foreign key
76632 ** operation implemented using OP_FkIsZero is working. This variable
76633 ** has no function other than to help verify the correct operation of the
76634 ** library.
76635 */
76636 #ifdef SQLITE_TEST
76637 SQLITE_API int sqlite3_found_count = 0;
76638 #endif
76639 
76640 /*
76641 ** Test a register to see if it exceeds the current maximum blob size.
76642 ** If it does, record the new maximum blob size.
76643 */
76644 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
76645 # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
76646 #else
76647 # define UPDATE_MAX_BLOBSIZE(P)
76648 #endif
76649 
76650 /*
76651 ** Invoke the VDBE coverage callback, if that callback is defined. This
76652 ** feature is used for test suite validation only and does not appear an
76653 ** production builds.
76654 **
76655 ** M is an integer, 2 or 3, that indices how many different ways the
76656 ** branch can go. It is usually 2. "I" is the direction the branch
76657 ** goes. 0 means falls through. 1 means branch is taken. 2 means the
76658 ** second alternative branch is taken.
76659 **
76660 ** iSrcLine is the source code line (from the __LINE__ macro) that
76661 ** generated the VDBE instruction. This instrumentation assumes that all
76662 ** source code is in a single file (the amalgamation). Special values 1
76663 ** and 2 for the iSrcLine parameter mean that this particular branch is
76664 ** always taken or never taken, respectively.
76665 */
76666 #if !defined(SQLITE_VDBE_COVERAGE)
76667 # define VdbeBranchTaken(I,M)
76668 #else
76669 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
76670  static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
76671  if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
76672  M = iSrcLine;
76673  /* Assert the truth of VdbeCoverageAlwaysTaken() and
76674  ** VdbeCoverageNeverTaken() */
76675  assert( (M & I)==I );
76676  }else{
76677  if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
76678  sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
76679  iSrcLine,I,M);
76680  }
76681  }
76682 #endif
76683 
76684 /*
76685 ** Convert the given register into a string if it isn't one
76686 ** already. Return non-zero if a malloc() fails.
76687 */
76688 #define Stringify(P, enc) \
76689  if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
76690  { goto no_mem; }
76691 
76692 /*
76693 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
76694 ** a pointer to a dynamically allocated string where some other entity
76695 ** is responsible for deallocating that string. Because the register
76696 ** does not control the string, it might be deleted without the register
76697 ** knowing it.
76698 **
76699 ** This routine converts an ephemeral string into a dynamically allocated
76700 ** string that the register itself controls. In other words, it
76701 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
76702 */
76703 #define Deephemeralize(P) \
76704  if( ((P)->flags&MEM_Ephem)!=0 \
76705  && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
76706 
76707 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
76708 #define isSorter(x) ((x)->eCurType==CURTYPE_SORTER)
76709 
76710 /*
76711 ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
76712 ** if we run out of memory.
76713 */
76715  Vdbe *p, /* The virtual machine */
76716  int iCur, /* Index of the new VdbeCursor */
76717  int nField, /* Number of fields in the table or index */
76718  int iDb, /* Database the cursor belongs to, or -1 */
76719  u8 eCurType /* Type of the new cursor */
76720 ){
76721  /* Find the memory cell that will be used to store the blob of memory
76722  ** required for this VdbeCursor structure. It is convenient to use a
76723  ** vdbe memory cell to manage the memory allocation required for a
76724  ** VdbeCursor structure for the following reasons:
76725  **
76726  ** * Sometimes cursor numbers are used for a couple of different
76727  ** purposes in a vdbe program. The different uses might require
76728  ** different sized allocations. Memory cells provide growable
76729  ** allocations.
76730  **
76731  ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
76732  ** be freed lazily via the sqlite3_release_memory() API. This
76733  ** minimizes the number of malloc calls made by the system.
76734  **
76735  ** The memory cell for cursor 0 is aMem[0]. The rest are allocated from
76736  ** the top of the register space. Cursor 1 is at Mem[p->nMem-1].
76737  ** Cursor 2 is at Mem[p->nMem-2]. And so forth.
76738  */
76739  Mem *pMem = iCur>0 ? &p->aMem[p->nMem-iCur] : p->aMem;
76740 
76741  int nByte;
76742  VdbeCursor *pCx = 0;
76743  nByte =
76744  ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
76745  (eCurType==CURTYPE_BTREE?sqlite3BtreeCursorSize():0);
76746 
76747  assert( iCur>=0 && iCur<p->nCursor );
76748  if( p->apCsr[iCur] ){ /*OPTIMIZATION-IF-FALSE*/
76749  sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
76750  p->apCsr[iCur] = 0;
76751  }
76752  if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
76753  p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
76754  memset(pCx, 0, sizeof(VdbeCursor));
76755  pCx->eCurType = eCurType;
76756  pCx->iDb = iDb;
76757  pCx->nField = nField;
76758  pCx->aOffset = &pCx->aType[nField];
76759  if( eCurType==CURTYPE_BTREE ){
76760  pCx->uc.pCursor = (BtCursor*)
76761  &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
76763  }
76764  }
76765  return pCx;
76766 }
76767 
76768 /*
76769 ** Try to convert a value into a numeric representation if we can
76770 ** do so without loss of information. In other words, if the string
76771 ** looks like a number, convert it into a number. If it does not
76772 ** look like a number, leave it alone.
76773 **
76774 ** If the bTryForInt flag is true, then extra effort is made to give
76775 ** an integer representation. Strings that look like floating point
76776 ** values but which have no fractional component (example: '48.00')
76777 ** will have a MEM_Int representation when bTryForInt is true.
76778 **
76779 ** If bTryForInt is false, then if the input string contains a decimal
76780 ** point or exponential notation, the result is only MEM_Real, even
76781 ** if there is an exact integer representation of the quantity.
76782 */
76783 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
76784  double rValue;
76785  i64 iValue;
76786  u8 enc = pRec->enc;
76787  assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
76788  if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
76789  if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
76790  pRec->u.i = iValue;
76791  pRec->flags |= MEM_Int;
76792  }else{
76793  pRec->u.r = rValue;
76794  pRec->flags |= MEM_Real;
76795  if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
76796  }
76797 }
76798 
76799 /*
76800 ** Processing is determine by the affinity parameter:
76801 **
76802 ** SQLITE_AFF_INTEGER:
76803 ** SQLITE_AFF_REAL:
76804 ** SQLITE_AFF_NUMERIC:
76805 ** Try to convert pRec to an integer representation or a
76806 ** floating-point representation if an integer representation
76807 ** is not possible. Note that the integer representation is
76808 ** always preferred, even if the affinity is REAL, because
76809 ** an integer representation is more space efficient on disk.
76810 **
76811 ** SQLITE_AFF_TEXT:
76812 ** Convert pRec to a text representation.
76813 **
76814 ** SQLITE_AFF_BLOB:
76815 ** No-op. pRec is unchanged.
76816 */
76817 static void applyAffinity(
76818  Mem *pRec, /* The value to apply affinity to */
76819  char affinity, /* The affinity to be applied */
76820  u8 enc /* Use this text encoding */
76821 ){
76822  if( affinity>=SQLITE_AFF_NUMERIC ){
76823  assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
76824  || affinity==SQLITE_AFF_NUMERIC );
76825  if( (pRec->flags & MEM_Int)==0 ){ /*OPTIMIZATION-IF-FALSE*/
76826  if( (pRec->flags & MEM_Real)==0 ){
76827  if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
76828  }else{
76830  }
76831  }
76832  }else if( affinity==SQLITE_AFF_TEXT ){
76833  /* Only attempt the conversion to TEXT if there is an integer or real
76834  ** representation (blob and NULL do not get converted) but no string
76835  ** representation. It would be harmless to repeat the conversion if
76836  ** there is already a string rep, but it is pointless to waste those
76837  ** CPU cycles. */
76838  if( 0==(pRec->flags&MEM_Str) ){ /*OPTIMIZATION-IF-FALSE*/
76839  if( (pRec->flags&(MEM_Real|MEM_Int)) ){
76840  sqlite3VdbeMemStringify(pRec, enc, 1);
76841  }
76842  }
76843  pRec->flags &= ~(MEM_Real|MEM_Int);
76844  }
76845 }
76846 
76847 /*
76848 ** Try to convert the type of a function argument or a result column
76849 ** into a numeric representation. Use either INTEGER or REAL whichever
76850 ** is appropriate. But only do the conversion if it is possible without
76851 ** loss of information and return the revised type of the argument.
76852 */
76854  int eType = sqlite3_value_type(pVal);
76855  if( eType==SQLITE_TEXT ){
76856  Mem *pMem = (Mem*)pVal;
76857  applyNumericAffinity(pMem, 0);
76858  eType = sqlite3_value_type(pVal);
76859  }
76860  return eType;
76861 }
76862 
76863 /*
76864 ** Exported version of applyAffinity(). This one works on sqlite3_value*,
76865 ** not the internal Mem* type.
76866 */
76868  sqlite3_value *pVal,
76869  u8 affinity,
76870  u8 enc
76871 ){
76872  applyAffinity((Mem *)pVal, affinity, enc);
76873 }
76874 
76875 /*
76876 ** pMem currently only holds a string type (or maybe a BLOB that we can
76877 ** interpret as a string if we want to). Compute its corresponding
76878 ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
76879 ** accordingly.
76880 */
76882  assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
76883  assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
76884  if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
76885  return 0;
76886  }
76887  if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
76888  return MEM_Int;
76889  }
76890  return MEM_Real;
76891 }
76892 
76893 /*
76894 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
76895 ** none.
76896 **
76897 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
76898 ** But it does set pMem->u.r and pMem->u.i appropriately.
76899 */
76900 static u16 numericType(Mem *pMem){
76901  if( pMem->flags & (MEM_Int|MEM_Real) ){
76902  return pMem->flags & (MEM_Int|MEM_Real);
76903  }
76904  if( pMem->flags & (MEM_Str|MEM_Blob) ){
76905  return computeNumericType(pMem);
76906  }
76907  return 0;
76908 }
76909 
76910 #ifdef SQLITE_DEBUG
76911 /*
76912 ** Write a nice string representation of the contents of cell pMem
76913 ** into buffer zBuf, length nBuf.
76914 */
76915 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
76916  char *zCsr = zBuf;
76917  int f = pMem->flags;
76918 
76919  static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
76920 
76921  if( f&MEM_Blob ){
76922  int i;
76923  char c;
76924  if( f & MEM_Dyn ){
76925  c = 'z';
76926  assert( (f & (MEM_Static|MEM_Ephem))==0 );
76927  }else if( f & MEM_Static ){
76928  c = 't';
76929  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
76930  }else if( f & MEM_Ephem ){
76931  c = 'e';
76932  assert( (f & (MEM_Static|MEM_Dyn))==0 );
76933  }else{
76934  c = 's';
76935  }
76936 
76937  sqlite3_snprintf(100, zCsr, "%c", c);
76938  zCsr += sqlite3Strlen30(zCsr);
76939  sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
76940  zCsr += sqlite3Strlen30(zCsr);
76941  for(i=0; i<16 && i<pMem->n; i++){
76942  sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
76943  zCsr += sqlite3Strlen30(zCsr);
76944  }
76945  for(i=0; i<16 && i<pMem->n; i++){
76946  char z = pMem->z[i];
76947  if( z<32 || z>126 ) *zCsr++ = '.';
76948  else *zCsr++ = z;
76949  }
76950 
76951  sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
76952  zCsr += sqlite3Strlen30(zCsr);
76953  if( f & MEM_Zero ){
76954  sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
76955  zCsr += sqlite3Strlen30(zCsr);
76956  }
76957  *zCsr = '\0';
76958  }else if( f & MEM_Str ){
76959  int j, k;
76960  zBuf[0] = ' ';
76961  if( f & MEM_Dyn ){
76962  zBuf[1] = 'z';
76963  assert( (f & (MEM_Static|MEM_Ephem))==0 );
76964  }else if( f & MEM_Static ){
76965  zBuf[1] = 't';
76966  assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
76967  }else if( f & MEM_Ephem ){
76968  zBuf[1] = 'e';
76969  assert( (f & (MEM_Static|MEM_Dyn))==0 );
76970  }else{
76971  zBuf[1] = 's';
76972  }
76973  k = 2;
76974  sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
76975  k += sqlite3Strlen30(&zBuf[k]);
76976  zBuf[k++] = '[';
76977  for(j=0; j<15 && j<pMem->n; j++){
76978  u8 c = pMem->z[j];
76979  if( c>=0x20 && c<0x7f ){
76980  zBuf[k++] = c;
76981  }else{
76982  zBuf[k++] = '.';
76983  }
76984  }
76985  zBuf[k++] = ']';
76986  sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
76987  k += sqlite3Strlen30(&zBuf[k]);
76988  zBuf[k++] = 0;
76989  }
76990 }
76991 #endif
76992 
76993 #ifdef SQLITE_DEBUG
76994 /*
76995 ** Print the value of a register for tracing purposes:
76996 */
76997 static void memTracePrint(Mem *p){
76998  if( p->flags & MEM_Undefined ){
76999  printf(" undefined");
77000  }else if( p->flags & MEM_Null ){
77001  printf(" NULL");
77002  }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
77003  printf(" si:%lld", p->u.i);
77004  }else if( p->flags & MEM_Int ){
77005  printf(" i:%lld", p->u.i);
77006 #ifndef SQLITE_OMIT_FLOATING_POINT
77007  }else if( p->flags & MEM_Real ){
77008  printf(" r:%g", p->u.r);
77009 #endif
77010  }else if( p->flags & MEM_RowSet ){
77011  printf(" (rowset)");
77012  }else{
77013  char zBuf[200];
77014  sqlite3VdbeMemPrettyPrint(p, zBuf);
77015  printf(" %s", zBuf);
77016  }
77017  if( p->flags & MEM_Subtype ) printf(" subtype=0x%02x", p->eSubtype);
77018 }
77019 static void registerTrace(int iReg, Mem *p){
77020  printf("REG[%d] = ", iReg);
77021  memTracePrint(p);
77022  printf("\n");
77023 }
77024 #endif
77025 
77026 #ifdef SQLITE_DEBUG
77027 # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
77028 #else
77029 # define REGISTER_TRACE(R,M)
77030 #endif
77031 
77032 
77033 #ifdef VDBE_PROFILE
77034 
77035 /*
77036 ** hwtime.h contains inline assembler code for implementing
77037 ** high-performance timing routines.
77038 */
77039 /************** Include hwtime.h in the middle of vdbe.c *********************/
77040 /************** Begin file hwtime.h ******************************************/
77041 /*
77042 ** 2008 May 27
77043 **
77044 ** The author disclaims copyright to this source code. In place of
77045 ** a legal notice, here is a blessing:
77046 **
77047 ** May you do good and not evil.
77048 ** May you find forgiveness for yourself and forgive others.
77049 ** May you share freely, never taking more than you give.
77050 **
77051 ******************************************************************************
77052 **
77053 ** This file contains inline asm code for retrieving "high-performance"
77054 ** counters for x86 class CPUs.
77055 */
77056 #ifndef _HWTIME_H_
77057 #define _HWTIME_H_
77058 
77059 /*
77060 ** The following routine only works on pentium-class (or newer) processors.
77061 ** It uses the RDTSC opcode to read the cycle count value out of the
77062 ** processor and returns that value. This can be used for high-res
77063 ** profiling.
77064 */
77065 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
77066  (defined(i386) || defined(__i386__) || defined(_M_IX86))
77067 
77068  #if defined(__GNUC__)
77069 
77070  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77071  unsigned int lo, hi;
77072  __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
77073  return (sqlite_uint64)hi << 32 | lo;
77074  }
77075 
77076  #elif defined(_MSC_VER)
77077 
77078  __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
77079  __asm {
77080  rdtsc
77081  ret ; return value at EDX:EAX
77082  }
77083  }
77084 
77085  #endif
77086 
77087 #elif (defined(__GNUC__) && defined(__x86_64__))
77088 
77089  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77090  unsigned long val;
77091  __asm__ __volatile__ ("rdtsc" : "=A" (val));
77092  return val;
77093  }
77094 
77095 #elif (defined(__GNUC__) && defined(__ppc__))
77096 
77097  __inline__ sqlite_uint64 sqlite3Hwtime(void){
77098  unsigned long long retval;
77099  unsigned long junk;
77100  __asm__ __volatile__ ("\n\
77101  1: mftbu %1\n\
77102  mftb %L0\n\
77103  mftbu %0\n\
77104  cmpw %0,%1\n\
77105  bne 1b"
77106  : "=r" (retval), "=r" (junk));
77107  return retval;
77108  }
77109 
77110 #else
77111 
77112  #error Need implementation of sqlite3Hwtime() for your platform.
77113 
77114  /*
77115  ** To compile without implementing sqlite3Hwtime() for your platform,
77116  ** you can remove the above #error and use the following
77117  ** stub function. You will lose timing support for many
77118  ** of the debugging and testing utilities, but it should at
77119  ** least compile and run.
77120  */
77121 SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
77122 
77123 #endif
77124 
77125 #endif /* !defined(_HWTIME_H_) */
77126 
77127 /************** End of hwtime.h **********************************************/
77128 /************** Continuing where we left off in vdbe.c ***********************/
77129 
77130 #endif
77131 
77132 #ifndef NDEBUG
77133 /*
77134 ** This function is only called from within an assert() expression. It
77135 ** checks that the sqlite3.nTransaction variable is correctly set to
77136 ** the number of non-transaction savepoints currently in the
77137 ** linked list starting at sqlite3.pSavepoint.
77138 **
77139 ** Usage:
77140 **
77141 ** assert( checkSavepointCount(db) );
77142 */
77143 static int checkSavepointCount(sqlite3 *db){
77144  int n = 0;
77145  Savepoint *p;
77146  for(p=db->pSavepoint; p; p=p->pNext) n++;
77147  assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
77148  return 1;
77149 }
77150 #endif
77151 
77152 /*
77153 ** Return the register of pOp->p2 after first preparing it to be
77154 ** overwritten with an integer value.
77155 */
77157  sqlite3VdbeMemSetNull(pOut);
77158  pOut->flags = MEM_Int;
77159  return pOut;
77160 }
77161 static Mem *out2Prerelease(Vdbe *p, VdbeOp *pOp){
77162  Mem *pOut;
77163  assert( pOp->p2>0 );
77164  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77165  pOut = &p->aMem[pOp->p2];
77166  memAboutToChange(p, pOut);
77167  if( VdbeMemDynamic(pOut) ){ /*OPTIMIZATION-IF-FALSE*/
77168  return out2PrereleaseWithClear(pOut);
77169  }else{
77170  pOut->flags = MEM_Int;
77171  return pOut;
77172  }
77173 }
77174 
77175 
77176 /*
77177 ** Execute as much of a VDBE program as we can.
77178 ** This is the core of sqlite3_step().
77179 */
77181  Vdbe *p /* The VDBE */
77182 ){
77183  Op *aOp = p->aOp; /* Copy of p->aOp */
77184  Op *pOp = aOp; /* Current operation */
77185 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77186  Op *pOrigOp; /* Value of pOp at the top of the loop */
77187 #endif
77188 #ifdef SQLITE_DEBUG
77189  int nExtraDelete = 0; /* Verifies FORDELETE and AUXDELETE flags */
77190 #endif
77191  int rc = SQLITE_OK; /* Value to return */
77192  sqlite3 *db = p->db; /* The database */
77193  u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
77194  u8 encoding = ENC(db); /* The database encoding */
77195  int iCompare = 0; /* Result of last OP_Compare operation */
77196  unsigned nVmStep = 0; /* Number of virtual machine steps */
77197 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77198  unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
77199 #endif
77200  Mem *aMem = p->aMem; /* Copy of p->aMem */
77201  Mem *pIn1 = 0; /* 1st input operand */
77202  Mem *pIn2 = 0; /* 2nd input operand */
77203  Mem *pIn3 = 0; /* 3rd input operand */
77204  Mem *pOut = 0; /* Output operand */
77205  int *aPermute = 0; /* Permutation of columns for OP_Compare */
77206  i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
77207 #ifdef VDBE_PROFILE
77208  u64 start; /* CPU clock count at start of opcode */
77209 #endif
77210  /*** INSERT STACK UNION HERE ***/
77211 
77212  assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
77213  sqlite3VdbeEnter(p);
77214  if( p->rc==SQLITE_NOMEM ){
77215  /* This happens if a malloc() inside a call to sqlite3_column_text() or
77216  ** sqlite3_column_text16() failed. */
77217  goto no_mem;
77218  }
77219  assert( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_BUSY );
77220  assert( p->bIsReader || p->readOnly!=0 );
77221  p->rc = SQLITE_OK;
77222  p->iCurrentTime = 0;
77223  assert( p->explain==0 );
77224  p->pResultSet = 0;
77225  db->busyHandler.nBusy = 0;
77226  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77228 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77229  if( db->xProgress ){
77230  u32 iPrior = p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
77231  assert( 0 < db->nProgressOps );
77232  nProgressLimit = db->nProgressOps - (iPrior % db->nProgressOps);
77233  }
77234 #endif
77235 #ifdef SQLITE_DEBUG
77237  if( p->pc==0
77239  ){
77240  int i;
77241  int once = 1;
77242  sqlite3VdbePrintSql(p);
77243  if( p->db->flags & SQLITE_VdbeListing ){
77244  printf("VDBE Program Listing:\n");
77245  for(i=0; i<p->nOp; i++){
77246  sqlite3VdbePrintOp(stdout, i, &aOp[i]);
77247  }
77248  }
77249  if( p->db->flags & SQLITE_VdbeEQP ){
77250  for(i=0; i<p->nOp; i++){
77251  if( aOp[i].opcode==OP_Explain ){
77252  if( once ) printf("VDBE Query Plan:\n");
77253  printf("%s\n", aOp[i].p4.z);
77254  once = 0;
77255  }
77256  }
77257  }
77258  if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
77259  }
77261 #endif
77262  for(pOp=&aOp[p->pc]; 1; pOp++){
77263  /* Errors are detected by individual opcodes, with an immediate
77264  ** jumps to abort_due_to_error. */
77265  assert( rc==SQLITE_OK );
77266 
77267  assert( pOp>=aOp && pOp<&aOp[p->nOp]);
77268 #ifdef VDBE_PROFILE
77269  start = sqlite3Hwtime();
77270 #endif
77271  nVmStep++;
77272 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
77273  if( p->anExec ) p->anExec[(int)(pOp-aOp)]++;
77274 #endif
77275 
77276  /* Only allow tracing if SQLITE_DEBUG is defined.
77277  */
77278 #ifdef SQLITE_DEBUG
77279  if( db->flags & SQLITE_VdbeTrace ){
77280  sqlite3VdbePrintOp(stdout, (int)(pOp - aOp), pOp);
77281  }
77282 #endif
77283 
77284 
77285  /* Check to see if we need to simulate an interrupt. This only happens
77286  ** if we have a special test build.
77287  */
77288 #ifdef SQLITE_TEST
77289  if( sqlite3_interrupt_count>0 ){
77290  sqlite3_interrupt_count--;
77291  if( sqlite3_interrupt_count==0 ){
77292  sqlite3_interrupt(db);
77293  }
77294  }
77295 #endif
77296 
77297  /* Sanity checking on other operands */
77298 #ifdef SQLITE_DEBUG
77299  {
77300  u8 opProperty = sqlite3OpcodeProperty[pOp->opcode];
77301  if( (opProperty & OPFLG_IN1)!=0 ){
77302  assert( pOp->p1>0 );
77303  assert( pOp->p1<=(p->nMem+1 - p->nCursor) );
77304  assert( memIsValid(&aMem[pOp->p1]) );
77305  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
77306  REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
77307  }
77308  if( (opProperty & OPFLG_IN2)!=0 ){
77309  assert( pOp->p2>0 );
77310  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77311  assert( memIsValid(&aMem[pOp->p2]) );
77312  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
77313  REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
77314  }
77315  if( (opProperty & OPFLG_IN3)!=0 ){
77316  assert( pOp->p3>0 );
77317  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77318  assert( memIsValid(&aMem[pOp->p3]) );
77319  assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
77320  REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
77321  }
77322  if( (opProperty & OPFLG_OUT2)!=0 ){
77323  assert( pOp->p2>0 );
77324  assert( pOp->p2<=(p->nMem+1 - p->nCursor) );
77325  memAboutToChange(p, &aMem[pOp->p2]);
77326  }
77327  if( (opProperty & OPFLG_OUT3)!=0 ){
77328  assert( pOp->p3>0 );
77329  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77330  memAboutToChange(p, &aMem[pOp->p3]);
77331  }
77332  }
77333 #endif
77334 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
77335  pOrigOp = pOp;
77336 #endif
77337 
77338  switch( pOp->opcode ){
77339 
77340 /*****************************************************************************
77341 ** What follows is a massive switch statement where each case implements a
77342 ** separate instruction in the virtual machine. If we follow the usual
77343 ** indentation conventions, each case should be indented by 6 spaces. But
77344 ** that is a lot of wasted space on the left margin. So the code within
77345 ** the switch statement will break with convention and be flush-left. Another
77346 ** big comment (similar to this one) will mark the point in the code where
77347 ** we transition back to normal indentation.
77348 **
77349 ** The formatting of each case is important. The makefile for SQLite
77350 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
77351 ** file looking for lines that begin with "case OP_". The opcodes.h files
77352 ** will be filled with #defines that give unique integer values to each
77353 ** opcode and the opcodes.c file is filled with an array of strings where
77354 ** each string is the symbolic name for the corresponding opcode. If the
77355 ** case statement is followed by a comment of the form "/# same as ... #/"
77356 ** that comment is used to determine the particular value of the opcode.
77357 **
77358 ** Other keywords in the comment that follows each case are used to
77359 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
77360 ** Keywords include: in1, in2, in3, out2, out3. See
77361 ** the mkopcodeh.awk script for additional information.
77362 **
77363 ** Documentation about VDBE opcodes is generated by scanning this file
77364 ** for lines of that contain "Opcode:". That line and all subsequent
77365 ** comment lines are used in the generation of the opcode.html documentation
77366 ** file.
77367 **
77368 ** SUMMARY:
77369 **
77370 ** Formatting is important to scripts that scan this file.
77371 ** Do not deviate from the formatting style currently in use.
77372 **
77373 *****************************************************************************/
77374 
77375 /* Opcode: Goto * P2 * * *
77376 **
77377 ** An unconditional jump to address P2.
77378 ** The next instruction executed will be
77379 ** the one at index P2 from the beginning of
77380 ** the program.
77381 **
77382 ** The P1 parameter is not actually used by this opcode. However, it
77383 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
77384 ** that this Goto is the bottom of a loop and that the lines from P2 down
77385 ** to the current line should be indented for EXPLAIN output.
77386 */
77387 case OP_Goto: { /* jump */
77388 jump_to_p2_and_check_for_interrupt:
77389  pOp = &aOp[pOp->p2 - 1];
77390 
77391  /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
77392  ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
77393  ** completion. Check to see if sqlite3_interrupt() has been called
77394  ** or if the progress callback needs to be invoked.
77395  **
77396  ** This code uses unstructured "goto" statements and does not look clean.
77397  ** But that is not due to sloppy coding habits. The code is written this
77398  ** way for performance, to avoid having to run the interrupt and progress
77399  ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
77400  ** faster according to "valgrind --tool=cachegrind" */
77401 check_for_interrupt:
77402  if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
77403 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77404  /* Call the progress callback if it is configured and the required number
77405  ** of VDBE ops have been executed (either since this invocation of
77406  ** sqlite3VdbeExec() or since last time the progress callback was called).
77407  ** If the progress callback returns non-zero, exit the virtual machine with
77408  ** a return code SQLITE_ABORT.
77409  */
77410  if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
77411  assert( db->nProgressOps!=0 );
77412  nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
77413  if( db->xProgress(db->pProgressArg) ){
77414  rc = SQLITE_INTERRUPT;
77415  goto abort_due_to_error;
77416  }
77417  }
77418 #endif
77419 
77420  break;
77421 }
77422 
77423 /* Opcode: Gosub P1 P2 * * *
77424 **
77425 ** Write the current address onto register P1
77426 ** and then jump to address P2.
77427 */
77428 case OP_Gosub: { /* jump */
77429  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77430  pIn1 = &aMem[pOp->p1];
77431  assert( VdbeMemDynamic(pIn1)==0 );
77432  memAboutToChange(p, pIn1);
77433  pIn1->flags = MEM_Int;
77434  pIn1->u.i = (int)(pOp-aOp);
77435  REGISTER_TRACE(pOp->p1, pIn1);
77436 
77437  /* Most jump operations do a goto to this spot in order to update
77438  ** the pOp pointer. */
77439 jump_to_p2:
77440  pOp = &aOp[pOp->p2 - 1];
77441  break;
77442 }
77443 
77444 /* Opcode: Return P1 * * * *
77445 **
77446 ** Jump to the next instruction after the address in register P1. After
77447 ** the jump, register P1 becomes undefined.
77448 */
77449 case OP_Return: { /* in1 */
77450  pIn1 = &aMem[pOp->p1];
77451  assert( pIn1->flags==MEM_Int );
77452  pOp = &aOp[pIn1->u.i];
77453  pIn1->flags = MEM_Undefined;
77454  break;
77455 }
77456 
77457 /* Opcode: InitCoroutine P1 P2 P3 * *
77458 **
77459 ** Set up register P1 so that it will Yield to the coroutine
77460 ** located at address P3.
77461 **
77462 ** If P2!=0 then the coroutine implementation immediately follows
77463 ** this opcode. So jump over the coroutine implementation to
77464 ** address P2.
77465 **
77466 ** See also: EndCoroutine
77467 */
77468 case OP_InitCoroutine: { /* jump */
77469  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77470  assert( pOp->p2>=0 && pOp->p2<p->nOp );
77471  assert( pOp->p3>=0 && pOp->p3<p->nOp );
77472  pOut = &aMem[pOp->p1];
77473  assert( !VdbeMemDynamic(pOut) );
77474  pOut->u.i = pOp->p3 - 1;
77475  pOut->flags = MEM_Int;
77476  if( pOp->p2 ) goto jump_to_p2;
77477  break;
77478 }
77479 
77480 /* Opcode: EndCoroutine P1 * * * *
77481 **
77482 ** The instruction at the address in register P1 is a Yield.
77483 ** Jump to the P2 parameter of that Yield.
77484 ** After the jump, register P1 becomes undefined.
77485 **
77486 ** See also: InitCoroutine
77487 */
77488 case OP_EndCoroutine: { /* in1 */
77489  VdbeOp *pCaller;
77490  pIn1 = &aMem[pOp->p1];
77491  assert( pIn1->flags==MEM_Int );
77492  assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
77493  pCaller = &aOp[pIn1->u.i];
77494  assert( pCaller->opcode==OP_Yield );
77495  assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
77496  pOp = &aOp[pCaller->p2 - 1];
77497  pIn1->flags = MEM_Undefined;
77498  break;
77499 }
77500 
77501 /* Opcode: Yield P1 P2 * * *
77502 **
77503 ** Swap the program counter with the value in register P1. This
77504 ** has the effect of yielding to a coroutine.
77505 **
77506 ** If the coroutine that is launched by this instruction ends with
77507 ** Yield or Return then continue to the next instruction. But if
77508 ** the coroutine launched by this instruction ends with
77509 ** EndCoroutine, then jump to P2 rather than continuing with the
77510 ** next instruction.
77511 **
77512 ** See also: InitCoroutine
77513 */
77514 case OP_Yield: { /* in1, jump */
77515  int pcDest;
77516  pIn1 = &aMem[pOp->p1];
77517  assert( VdbeMemDynamic(pIn1)==0 );
77518  pIn1->flags = MEM_Int;
77519  pcDest = (int)pIn1->u.i;
77520  pIn1->u.i = (int)(pOp - aOp);
77521  REGISTER_TRACE(pOp->p1, pIn1);
77522  pOp = &aOp[pcDest];
77523  break;
77524 }
77525 
77526 /* Opcode: HaltIfNull P1 P2 P3 P4 P5
77527 ** Synopsis: if r[P3]=null halt
77528 **
77529 ** Check the value in register P3. If it is NULL then Halt using
77530 ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
77531 ** value in register P3 is not NULL, then this routine is a no-op.
77532 ** The P5 parameter should be 1.
77533 */
77534 case OP_HaltIfNull: { /* in3 */
77535  pIn3 = &aMem[pOp->p3];
77536  if( (pIn3->flags & MEM_Null)==0 ) break;
77537  /* Fall through into OP_Halt */
77538 }
77539 
77540 /* Opcode: Halt P1 P2 * P4 P5
77541 **
77542 ** Exit immediately. All open cursors, etc are closed
77543 ** automatically.
77544 **
77545 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
77546 ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
77547 ** For errors, it can be some other value. If P1!=0 then P2 will determine
77548 ** whether or not to rollback the current transaction. Do not rollback
77549 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
77550 ** then back out all changes that have occurred during this execution of the
77551 ** VDBE, but do not rollback the transaction.
77552 **
77553 ** If P4 is not null then it is an error message string.
77554 **
77555 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
77556 **
77557 ** 0: (no change)
77558 ** 1: NOT NULL contraint failed: P4
77559 ** 2: UNIQUE constraint failed: P4
77560 ** 3: CHECK constraint failed: P4
77561 ** 4: FOREIGN KEY constraint failed: P4
77562 **
77563 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
77564 ** omitted.
77565 **
77566 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
77567 ** every program. So a jump past the last instruction of the program
77568 ** is the same as executing Halt.
77569 */
77570 case OP_Halt: {
77571  VdbeFrame *pFrame;
77572  int pcx;
77573 
77574  pcx = (int)(pOp - aOp);
77575  if( pOp->p1==SQLITE_OK && p->pFrame ){
77576  /* Halt the sub-program. Return control to the parent frame. */
77577  pFrame = p->pFrame;
77578  p->pFrame = pFrame->pParent;
77579  p->nFrame--;
77581  pcx = sqlite3VdbeFrameRestore(pFrame);
77582  lastRowid = db->lastRowid;
77583  if( pOp->p2==OE_Ignore ){
77584  /* Instruction pcx is the OP_Program that invoked the sub-program
77585  ** currently being halted. If the p2 instruction of this OP_Halt
77586  ** instruction is set to OE_Ignore, then the sub-program is throwing
77587  ** an IGNORE exception. In this case jump to the address specified
77588  ** as the p2 of the calling OP_Program. */
77589  pcx = p->aOp[pcx].p2-1;
77590  }
77591  aOp = p->aOp;
77592  aMem = p->aMem;
77593  pOp = &aOp[pcx];
77594  break;
77595  }
77596  p->rc = pOp->p1;
77597  p->errorAction = (u8)pOp->p2;
77598  p->pc = pcx;
77599  assert( pOp->p5>=0 && pOp->p5<=4 );
77600  if( p->rc ){
77601  if( pOp->p5 ){
77602  static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
77603  "FOREIGN KEY" };
77604  testcase( pOp->p5==1 );
77605  testcase( pOp->p5==2 );
77606  testcase( pOp->p5==3 );
77607  testcase( pOp->p5==4 );
77608  sqlite3VdbeError(p, "%s constraint failed", azType[pOp->p5-1]);
77609  if( pOp->p4.z ){
77610  p->zErrMsg = sqlite3MPrintf(db, "%z: %s", p->zErrMsg, pOp->p4.z);
77611  }
77612  }else{
77613  sqlite3VdbeError(p, "%s", pOp->p4.z);
77614  }
77615  sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pcx, p->zSql, p->zErrMsg);
77616  }
77617  rc = sqlite3VdbeHalt(p);
77618  assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
77619  if( rc==SQLITE_BUSY ){
77620  p->rc = SQLITE_BUSY;
77621  }else{
77622  assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
77623  assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
77624  rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
77625  }
77626  goto vdbe_return;
77627 }
77628 
77629 /* Opcode: Integer P1 P2 * * *
77630 ** Synopsis: r[P2]=P1
77631 **
77632 ** The 32-bit integer value P1 is written into register P2.
77633 */
77634 case OP_Integer: { /* out2 */
77635  pOut = out2Prerelease(p, pOp);
77636  pOut->u.i = pOp->p1;
77637  break;
77638 }
77639 
77640 /* Opcode: Int64 * P2 * P4 *
77641 ** Synopsis: r[P2]=P4
77642 **
77643 ** P4 is a pointer to a 64-bit integer value.
77644 ** Write that value into register P2.
77645 */
77646 case OP_Int64: { /* out2 */
77647  pOut = out2Prerelease(p, pOp);
77648  assert( pOp->p4.pI64!=0 );
77649  pOut->u.i = *pOp->p4.pI64;
77650  break;
77651 }
77652 
77653 #ifndef SQLITE_OMIT_FLOATING_POINT
77654 /* Opcode: Real * P2 * P4 *
77655 ** Synopsis: r[P2]=P4
77656 **
77657 ** P4 is a pointer to a 64-bit floating point value.
77658 ** Write that value into register P2.
77659 */
77660 case OP_Real: { /* same as TK_FLOAT, out2 */
77661  pOut = out2Prerelease(p, pOp);
77662  pOut->flags = MEM_Real;
77663  assert( !sqlite3IsNaN(*pOp->p4.pReal) );
77664  pOut->u.r = *pOp->p4.pReal;
77665  break;
77666 }
77667 #endif
77668 
77669 /* Opcode: String8 * P2 * P4 *
77670 ** Synopsis: r[P2]='P4'
77671 **
77672 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
77673 ** into a String opcode before it is executed for the first time. During
77674 ** this transformation, the length of string P4 is computed and stored
77675 ** as the P1 parameter.
77676 */
77677 case OP_String8: { /* same as TK_STRING, out2 */
77678  assert( pOp->p4.z!=0 );
77679  pOut = out2Prerelease(p, pOp);
77680  pOp->opcode = OP_String;
77681  pOp->p1 = sqlite3Strlen30(pOp->p4.z);
77682 
77683 #ifndef SQLITE_OMIT_UTF16
77684  if( encoding!=SQLITE_UTF8 ){
77685  rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
77686  assert( rc==SQLITE_OK || rc==SQLITE_TOOBIG );
77687  if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
77688  assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
77689  assert( VdbeMemDynamic(pOut)==0 );
77690  pOut->szMalloc = 0;
77691  pOut->flags |= MEM_Static;
77692  if( pOp->p4type==P4_DYNAMIC ){
77693  sqlite3DbFree(db, pOp->p4.z);
77694  }
77695  pOp->p4type = P4_DYNAMIC;
77696  pOp->p4.z = pOut->z;
77697  pOp->p1 = pOut->n;
77698  }
77699  testcase( rc==SQLITE_TOOBIG );
77700 #endif
77701  if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
77702  goto too_big;
77703  }
77704  assert( rc==SQLITE_OK );
77705  /* Fall through to the next case, OP_String */
77706 }
77707 
77708 /* Opcode: String P1 P2 P3 P4 P5
77709 ** Synopsis: r[P2]='P4' (len=P1)
77710 **
77711 ** The string value P4 of length P1 (bytes) is stored in register P2.
77712 **
77713 ** If P3 is not zero and the content of register P3 is equal to P5, then
77714 ** the datatype of the register P2 is converted to BLOB. The content is
77715 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
77716 ** of a string, as if it had been CAST. In other words:
77717 **
77718 ** if( P3!=0 and reg[P3]==P5 ) reg[P2] := CAST(reg[P2] as BLOB)
77719 */
77720 case OP_String: { /* out2 */
77721  assert( pOp->p4.z!=0 );
77722  pOut = out2Prerelease(p, pOp);
77723  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
77724  pOut->z = pOp->p4.z;
77725  pOut->n = pOp->p1;
77726  pOut->enc = encoding;
77727  UPDATE_MAX_BLOBSIZE(pOut);
77728 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
77729  if( pOp->p3>0 ){
77730  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77731  pIn3 = &aMem[pOp->p3];
77732  assert( pIn3->flags & MEM_Int );
77733  if( pIn3->u.i==pOp->p5 ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
77734  }
77735 #endif
77736  break;
77737 }
77738 
77739 /* Opcode: Null P1 P2 P3 * *
77740 ** Synopsis: r[P2..P3]=NULL
77741 **
77742 ** Write a NULL into registers P2. If P3 greater than P2, then also write
77743 ** NULL into register P3 and every register in between P2 and P3. If P3
77744 ** is less than P2 (typically P3 is zero) then only register P2 is
77745 ** set to NULL.
77746 **
77747 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
77748 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
77749 ** OP_Ne or OP_Eq.
77750 */
77751 case OP_Null: { /* out2 */
77752  int cnt;
77753  u16 nullFlag;
77754  pOut = out2Prerelease(p, pOp);
77755  cnt = pOp->p3-pOp->p2;
77756  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
77757  pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
77758  while( cnt>0 ){
77759  pOut++;
77760  memAboutToChange(p, pOut);
77761  sqlite3VdbeMemSetNull(pOut);
77762  pOut->flags = nullFlag;
77763  cnt--;
77764  }
77765  break;
77766 }
77767 
77768 /* Opcode: SoftNull P1 * * * *
77769 ** Synopsis: r[P1]=NULL
77770 **
77771 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
77772 ** instruction, but do not free any string or blob memory associated with
77773 ** the register, so that if the value was a string or blob that was
77774 ** previously copied using OP_SCopy, the copies will continue to be valid.
77775 */
77776 case OP_SoftNull: {
77777  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
77778  pOut = &aMem[pOp->p1];
77779  pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
77780  break;
77781 }
77782 
77783 /* Opcode: Blob P1 P2 * P4 *
77784 ** Synopsis: r[P2]=P4 (len=P1)
77785 **
77786 ** P4 points to a blob of data P1 bytes long. Store this
77787 ** blob in register P2.
77788 */
77789 case OP_Blob: { /* out2 */
77790  assert( pOp->p1 <= SQLITE_MAX_LENGTH );
77791  pOut = out2Prerelease(p, pOp);
77792  sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
77793  pOut->enc = encoding;
77794  UPDATE_MAX_BLOBSIZE(pOut);
77795  break;
77796 }
77797 
77798 /* Opcode: Variable P1 P2 * P4 *
77799 ** Synopsis: r[P2]=parameter(P1,P4)
77800 **
77801 ** Transfer the values of bound parameter P1 into register P2
77802 **
77803 ** If the parameter is named, then its name appears in P4.
77804 ** The P4 value is used by sqlite3_bind_parameter_name().
77805 */
77806 case OP_Variable: { /* out2 */
77807  Mem *pVar; /* Value being transferred */
77808 
77809  assert( pOp->p1>0 && pOp->p1<=p->nVar );
77810  assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
77811  pVar = &p->aVar[pOp->p1 - 1];
77812  if( sqlite3VdbeMemTooBig(pVar) ){
77813  goto too_big;
77814  }
77815  pOut = out2Prerelease(p, pOp);
77817  UPDATE_MAX_BLOBSIZE(pOut);
77818  break;
77819 }
77820 
77821 /* Opcode: Move P1 P2 P3 * *
77822 ** Synopsis: r[P2@P3]=r[P1@P3]
77823 **
77824 ** Move the P3 values in register P1..P1+P3-1 over into
77825 ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
77826 ** left holding a NULL. It is an error for register ranges
77827 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
77828 ** for P3 to be less than 1.
77829 */
77830 case OP_Move: {
77831  int n; /* Number of registers left to copy */
77832  int p1; /* Register to copy from */
77833  int p2; /* Register to copy to */
77834 
77835  n = pOp->p3;
77836  p1 = pOp->p1;
77837  p2 = pOp->p2;
77838  assert( n>0 && p1>0 && p2>0 );
77839  assert( p1+n<=p2 || p2+n<=p1 );
77840 
77841  pIn1 = &aMem[p1];
77842  pOut = &aMem[p2];
77843  do{
77844  assert( pOut<=&aMem[(p->nMem+1 - p->nCursor)] );
77845  assert( pIn1<=&aMem[(p->nMem+1 - p->nCursor)] );
77846  assert( memIsValid(pIn1) );
77847  memAboutToChange(p, pOut);
77848  sqlite3VdbeMemMove(pOut, pIn1);
77849 #ifdef SQLITE_DEBUG
77850  if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<pOut ){
77851  pOut->pScopyFrom += pOp->p2 - p1;
77852  }
77853 #endif
77854  Deephemeralize(pOut);
77855  REGISTER_TRACE(p2++, pOut);
77856  pIn1++;
77857  pOut++;
77858  }while( --n );
77859  break;
77860 }
77861 
77862 /* Opcode: Copy P1 P2 P3 * *
77863 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
77864 **
77865 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
77866 **
77867 ** This instruction makes a deep copy of the value. A duplicate
77868 ** is made of any string or blob constant. See also OP_SCopy.
77869 */
77870 case OP_Copy: {
77871  int n;
77872 
77873  n = pOp->p3;
77874  pIn1 = &aMem[pOp->p1];
77875  pOut = &aMem[pOp->p2];
77876  assert( pOut!=pIn1 );
77877  while( 1 ){
77878  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
77879  Deephemeralize(pOut);
77880 #ifdef SQLITE_DEBUG
77881  pOut->pScopyFrom = 0;
77882 #endif
77883  REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
77884  if( (n--)==0 ) break;
77885  pOut++;
77886  pIn1++;
77887  }
77888  break;
77889 }
77890 
77891 /* Opcode: SCopy P1 P2 * * *
77892 ** Synopsis: r[P2]=r[P1]
77893 **
77894 ** Make a shallow copy of register P1 into register P2.
77895 **
77896 ** This instruction makes a shallow copy of the value. If the value
77897 ** is a string or blob, then the copy is only a pointer to the
77898 ** original and hence if the original changes so will the copy.
77899 ** Worse, if the original is deallocated, the copy becomes invalid.
77900 ** Thus the program must guarantee that the original will not change
77901 ** during the lifetime of the copy. Use OP_Copy to make a complete
77902 ** copy.
77903 */
77904 case OP_SCopy: { /* out2 */
77905  pIn1 = &aMem[pOp->p1];
77906  pOut = &aMem[pOp->p2];
77907  assert( pOut!=pIn1 );
77908  sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
77909 #ifdef SQLITE_DEBUG
77910  if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
77911 #endif
77912  break;
77913 }
77914 
77915 /* Opcode: IntCopy P1 P2 * * *
77916 ** Synopsis: r[P2]=r[P1]
77917 **
77918 ** Transfer the integer value held in register P1 into register P2.
77919 **
77920 ** This is an optimized version of SCopy that works only for integer
77921 ** values.
77922 */
77923 case OP_IntCopy: { /* out2 */
77924  pIn1 = &aMem[pOp->p1];
77925  assert( (pIn1->flags & MEM_Int)!=0 );
77926  pOut = &aMem[pOp->p2];
77927  sqlite3VdbeMemSetInt64(pOut, pIn1->u.i);
77928  break;
77929 }
77930 
77931 /* Opcode: ResultRow P1 P2 * * *
77932 ** Synopsis: output=r[P1@P2]
77933 **
77934 ** The registers P1 through P1+P2-1 contain a single row of
77935 ** results. This opcode causes the sqlite3_step() call to terminate
77936 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
77937 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
77938 ** the result row.
77939 */
77940 case OP_ResultRow: {
77941  Mem *pMem;
77942  int i;
77943  assert( p->nResColumn==pOp->p2 );
77944  assert( pOp->p1>0 );
77945  assert( pOp->p1+pOp->p2<=(p->nMem+1 - p->nCursor)+1 );
77946 
77947 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
77948  /* Run the progress counter just before returning.
77949  */
77950  if( db->xProgress!=0
77951  && nVmStep>=nProgressLimit
77952  && db->xProgress(db->pProgressArg)!=0
77953  ){
77954  rc = SQLITE_INTERRUPT;
77955  goto abort_due_to_error;
77956  }
77957 #endif
77958 
77959  /* If this statement has violated immediate foreign key constraints, do
77960  ** not return the number of rows modified. And do not RELEASE the statement
77961  ** transaction. It needs to be rolled back. */
77962  if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
77963  assert( db->flags&SQLITE_CountRows );
77964  assert( p->usesStmtJournal );
77965  goto abort_due_to_error;
77966  }
77967 
77968  /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
77969  ** DML statements invoke this opcode to return the number of rows
77970  ** modified to the user. This is the only way that a VM that
77971  ** opens a statement transaction may invoke this opcode.
77972  **
77973  ** In case this is such a statement, close any statement transaction
77974  ** opened by this VM before returning control to the user. This is to
77975  ** ensure that statement-transactions are always nested, not overlapping.
77976  ** If the open statement-transaction is not closed here, then the user
77977  ** may step another VM that opens its own statement transaction. This
77978  ** may lead to overlapping statement transactions.
77979  **
77980  ** The statement transaction is never a top-level transaction. Hence
77981  ** the RELEASE call below can never fail.
77982  */
77983  assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
77985  assert( rc==SQLITE_OK );
77986 
77987  /* Invalidate all ephemeral cursor row caches */
77988  p->cacheCtr = (p->cacheCtr + 2)|1;
77989 
77990  /* Make sure the results of the current row are \000 terminated
77991  ** and have an assigned type. The results are de-ephemeralized as
77992  ** a side effect.
77993  */
77994  pMem = p->pResultSet = &aMem[pOp->p1];
77995  for(i=0; i<pOp->p2; i++){
77996  assert( memIsValid(&pMem[i]) );
77997  Deephemeralize(&pMem[i]);
77998  assert( (pMem[i].flags & MEM_Ephem)==0
77999  || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
78000  sqlite3VdbeMemNulTerminate(&pMem[i]);
78001  REGISTER_TRACE(pOp->p1+i, &pMem[i]);
78002  }
78003  if( db->mallocFailed ) goto no_mem;
78004 
78005  /* Return SQLITE_ROW
78006  */
78007  p->pc = (int)(pOp - aOp) + 1;
78008  rc = SQLITE_ROW;
78009  goto vdbe_return;
78010 }
78011 
78012 /* Opcode: Concat P1 P2 P3 * *
78013 ** Synopsis: r[P3]=r[P2]+r[P1]
78014 **
78015 ** Add the text in register P1 onto the end of the text in
78016 ** register P2 and store the result in register P3.
78017 ** If either the P1 or P2 text are NULL then store NULL in P3.
78018 **
78019 ** P3 = P2 || P1
78020 **
78021 ** It is illegal for P1 and P3 to be the same register. Sometimes,
78022 ** if P3 is the same register as P2, the implementation is able
78023 ** to avoid a memcpy().
78024 */
78025 case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
78026  i64 nByte;
78027 
78028  pIn1 = &aMem[pOp->p1];
78029  pIn2 = &aMem[pOp->p2];
78030  pOut = &aMem[pOp->p3];
78031  assert( pIn1!=pOut );
78032  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78033  sqlite3VdbeMemSetNull(pOut);
78034  break;
78035  }
78036  if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
78037  Stringify(pIn1, encoding);
78038  Stringify(pIn2, encoding);
78039  nByte = pIn1->n + pIn2->n;
78040  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
78041  goto too_big;
78042  }
78043  if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
78044  goto no_mem;
78045  }
78046  MemSetTypeFlag(pOut, MEM_Str);
78047  if( pOut!=pIn2 ){
78048  memcpy(pOut->z, pIn2->z, pIn2->n);
78049  }
78050  memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
78051  pOut->z[nByte]=0;
78052  pOut->z[nByte+1] = 0;
78053  pOut->flags |= MEM_Term;
78054  pOut->n = (int)nByte;
78055  pOut->enc = encoding;
78056  UPDATE_MAX_BLOBSIZE(pOut);
78057  break;
78058 }
78059 
78060 /* Opcode: Add P1 P2 P3 * *
78061 ** Synopsis: r[P3]=r[P1]+r[P2]
78062 **
78063 ** Add the value in register P1 to the value in register P2
78064 ** and store the result in register P3.
78065 ** If either input is NULL, the result is NULL.
78066 */
78067 /* Opcode: Multiply P1 P2 P3 * *
78068 ** Synopsis: r[P3]=r[P1]*r[P2]
78069 **
78070 **
78071 ** Multiply the value in register P1 by the value in register P2
78072 ** and store the result in register P3.
78073 ** If either input is NULL, the result is NULL.
78074 */
78075 /* Opcode: Subtract P1 P2 P3 * *
78076 ** Synopsis: r[P3]=r[P2]-r[P1]
78077 **
78078 ** Subtract the value in register P1 from the value in register P2
78079 ** and store the result in register P3.
78080 ** If either input is NULL, the result is NULL.
78081 */
78082 /* Opcode: Divide P1 P2 P3 * *
78083 ** Synopsis: r[P3]=r[P2]/r[P1]
78084 **
78085 ** Divide the value in register P1 by the value in register P2
78086 ** and store the result in register P3 (P3=P2/P1). If the value in
78087 ** register P1 is zero, then the result is NULL. If either input is
78088 ** NULL, the result is NULL.
78089 */
78090 /* Opcode: Remainder P1 P2 P3 * *
78091 ** Synopsis: r[P3]=r[P2]%r[P1]
78092 **
78093 ** Compute the remainder after integer register P2 is divided by
78094 ** register P1 and store the result in register P3.
78095 ** If the value in register P1 is zero the result is NULL.
78096 ** If either operand is NULL, the result is NULL.
78097 */
78098 case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
78099 case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
78100 case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
78101 case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
78102 case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
78103  char bIntint; /* Started out as two integer operands */
78104  u16 flags; /* Combined MEM_* flags from both inputs */
78105  u16 type1; /* Numeric type of left operand */
78106  u16 type2; /* Numeric type of right operand */
78107  i64 iA; /* Integer value of left operand */
78108  i64 iB; /* Integer value of right operand */
78109  double rA; /* Real value of left operand */
78110  double rB; /* Real value of right operand */
78111 
78112  pIn1 = &aMem[pOp->p1];
78113  type1 = numericType(pIn1);
78114  pIn2 = &aMem[pOp->p2];
78115  type2 = numericType(pIn2);
78116  pOut = &aMem[pOp->p3];
78117  flags = pIn1->flags | pIn2->flags;
78118  if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
78119  if( (type1 & type2 & MEM_Int)!=0 ){
78120  iA = pIn1->u.i;
78121  iB = pIn2->u.i;
78122  bIntint = 1;
78123  switch( pOp->opcode ){
78124  case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
78125  case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
78126  case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
78127  case OP_Divide: {
78128  if( iA==0 ) goto arithmetic_result_is_null;
78129  if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
78130  iB /= iA;
78131  break;
78132  }
78133  default: {
78134  if( iA==0 ) goto arithmetic_result_is_null;
78135  if( iA==-1 ) iA = 1;
78136  iB %= iA;
78137  break;
78138  }
78139  }
78140  pOut->u.i = iB;
78141  MemSetTypeFlag(pOut, MEM_Int);
78142  }else{
78143  bIntint = 0;
78144 fp_math:
78145  rA = sqlite3VdbeRealValue(pIn1);
78146  rB = sqlite3VdbeRealValue(pIn2);
78147  switch( pOp->opcode ){
78148  case OP_Add: rB += rA; break;
78149  case OP_Subtract: rB -= rA; break;
78150  case OP_Multiply: rB *= rA; break;
78151  case OP_Divide: {
78152  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
78153  if( rA==(double)0 ) goto arithmetic_result_is_null;
78154  rB /= rA;
78155  break;
78156  }
78157  default: {
78158  iA = (i64)rA;
78159  iB = (i64)rB;
78160  if( iA==0 ) goto arithmetic_result_is_null;
78161  if( iA==-1 ) iA = 1;
78162  rB = (double)(iB % iA);
78163  break;
78164  }
78165  }
78166 #ifdef SQLITE_OMIT_FLOATING_POINT
78167  pOut->u.i = rB;
78168  MemSetTypeFlag(pOut, MEM_Int);
78169 #else
78170  if( sqlite3IsNaN(rB) ){
78171  goto arithmetic_result_is_null;
78172  }
78173  pOut->u.r = rB;
78174  MemSetTypeFlag(pOut, MEM_Real);
78175  if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
78177  }
78178 #endif
78179  }
78180  break;
78181 
78182 arithmetic_result_is_null:
78183  sqlite3VdbeMemSetNull(pOut);
78184  break;
78185 }
78186 
78187 /* Opcode: CollSeq P1 * * P4
78188 **
78189 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
78190 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
78191 ** be returned. This is used by the built-in min(), max() and nullif()
78192 ** functions.
78193 **
78194 ** If P1 is not zero, then it is a register that a subsequent min() or
78195 ** max() aggregate will set to 1 if the current row is not the minimum or
78196 ** maximum. The P1 register is initialized to 0 by this instruction.
78197 **
78198 ** The interface used by the implementation of the aforementioned functions
78199 ** to retrieve the collation sequence set by this opcode is not available
78200 ** publicly. Only built-in functions have access to this feature.
78201 */
78202 case OP_CollSeq: {
78203  assert( pOp->p4type==P4_COLLSEQ );
78204  if( pOp->p1 ){
78205  sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
78206  }
78207  break;
78208 }
78209 
78210 /* Opcode: Function0 P1 P2 P3 P4 P5
78211 ** Synopsis: r[P3]=func(r[P2@P5])
78212 **
78213 ** Invoke a user function (P4 is a pointer to a FuncDef object that
78214 ** defines the function) with P5 arguments taken from register P2 and
78215 ** successors. The result of the function is stored in register P3.
78216 ** Register P3 must not be one of the function inputs.
78217 **
78218 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78219 ** function was determined to be constant at compile time. If the first
78220 ** argument was constant then bit 0 of P1 is set. This is used to determine
78221 ** whether meta data associated with a user function argument using the
78222 ** sqlite3_set_auxdata() API may be safely retained until the next
78223 ** invocation of this opcode.
78224 **
78225 ** See also: Function, AggStep, AggFinal
78226 */
78227 /* Opcode: Function P1 P2 P3 P4 P5
78228 ** Synopsis: r[P3]=func(r[P2@P5])
78229 **
78230 ** Invoke a user function (P4 is a pointer to an sqlite3_context object that
78231 ** contains a pointer to the function to be run) with P5 arguments taken
78232 ** from register P2 and successors. The result of the function is stored
78233 ** in register P3. Register P3 must not be one of the function inputs.
78234 **
78235 ** P1 is a 32-bit bitmask indicating whether or not each argument to the
78236 ** function was determined to be constant at compile time. If the first
78237 ** argument was constant then bit 0 of P1 is set. This is used to determine
78238 ** whether meta data associated with a user function argument using the
78239 ** sqlite3_set_auxdata() API may be safely retained until the next
78240 ** invocation of this opcode.
78241 **
78242 ** SQL functions are initially coded as OP_Function0 with P4 pointing
78243 ** to a FuncDef object. But on first evaluation, the P4 operand is
78244 ** automatically converted into an sqlite3_context object and the operation
78245 ** changed to this OP_Function opcode. In this way, the initialization of
78246 ** the sqlite3_context object occurs only once, rather than once for each
78247 ** evaluation of the function.
78248 **
78249 ** See also: Function0, AggStep, AggFinal
78250 */
78251 case OP_Function0: {
78252  int n;
78253  sqlite3_context *pCtx;
78254 
78255  assert( pOp->p4type==P4_FUNCDEF );
78256  n = pOp->p5;
78257  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
78258  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
78259  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
78260  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
78261  if( pCtx==0 ) goto no_mem;
78262  pCtx->pOut = 0;
78263  pCtx->pFunc = pOp->p4.pFunc;
78264  pCtx->iOp = (int)(pOp - aOp);
78265  pCtx->pVdbe = p;
78266  pCtx->argc = n;
78267  pOp->p4type = P4_FUNCCTX;
78268  pOp->p4.pCtx = pCtx;
78269  pOp->opcode = OP_Function;
78270  /* Fall through into OP_Function */
78271 }
78272 case OP_Function: {
78273  int i;
78274  sqlite3_context *pCtx;
78275 
78276  assert( pOp->p4type==P4_FUNCCTX );
78277  pCtx = pOp->p4.pCtx;
78278 
78279  /* If this function is inside of a trigger, the register array in aMem[]
78280  ** might change from one evaluation to the next. The next block of code
78281  ** checks to see if the register array has changed, and if so it
78282  ** reinitializes the relavant parts of the sqlite3_context object */
78283  pOut = &aMem[pOp->p3];
78284  if( pCtx->pOut != pOut ){
78285  pCtx->pOut = pOut;
78286  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
78287  }
78288 
78289  memAboutToChange(p, pCtx->pOut);
78290 #ifdef SQLITE_DEBUG
78291  for(i=0; i<pCtx->argc; i++){
78292  assert( memIsValid(pCtx->argv[i]) );
78293  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
78294  }
78295 #endif
78296  MemSetTypeFlag(pCtx->pOut, MEM_Null);
78297  pCtx->fErrorOrAux = 0;
78298  db->lastRowid = lastRowid;
78299  (*pCtx->pFunc->xSFunc)(pCtx, pCtx->argc, pCtx->argv);/* IMP: R-24505-23230 */
78300  lastRowid = db->lastRowid; /* Remember rowid changes made by xSFunc */
78301 
78302  /* If the function returned an error, throw an exception */
78303  if( pCtx->fErrorOrAux ){
78304  if( pCtx->isError ){
78305  sqlite3VdbeError(p, "%s", sqlite3_value_text(pCtx->pOut));
78306  rc = pCtx->isError;
78307  }
78308  sqlite3VdbeDeleteAuxData(db, &p->pAuxData, pCtx->iOp, pOp->p1);
78309  if( rc ) goto abort_due_to_error;
78310  }
78311 
78312  /* Copy the result of the function into register P3 */
78313  if( pOut->flags & (MEM_Str|MEM_Blob) ){
78314  sqlite3VdbeChangeEncoding(pCtx->pOut, encoding);
78315  if( sqlite3VdbeMemTooBig(pCtx->pOut) ) goto too_big;
78316  }
78317 
78318  REGISTER_TRACE(pOp->p3, pCtx->pOut);
78319  UPDATE_MAX_BLOBSIZE(pCtx->pOut);
78320  break;
78321 }
78322 
78323 /* Opcode: BitAnd P1 P2 P3 * *
78324 ** Synopsis: r[P3]=r[P1]&r[P2]
78325 **
78326 ** Take the bit-wise AND of the values in register P1 and P2 and
78327 ** store the result in register P3.
78328 ** If either input is NULL, the result is NULL.
78329 */
78330 /* Opcode: BitOr P1 P2 P3 * *
78331 ** Synopsis: r[P3]=r[P1]|r[P2]
78332 **
78333 ** Take the bit-wise OR of the values in register P1 and P2 and
78334 ** store the result in register P3.
78335 ** If either input is NULL, the result is NULL.
78336 */
78337 /* Opcode: ShiftLeft P1 P2 P3 * *
78338 ** Synopsis: r[P3]=r[P2]<<r[P1]
78339 **
78340 ** Shift the integer value in register P2 to the left by the
78341 ** number of bits specified by the integer in register P1.
78342 ** Store the result in register P3.
78343 ** If either input is NULL, the result is NULL.
78344 */
78345 /* Opcode: ShiftRight P1 P2 P3 * *
78346 ** Synopsis: r[P3]=r[P2]>>r[P1]
78347 **
78348 ** Shift the integer value in register P2 to the right by the
78349 ** number of bits specified by the integer in register P1.
78350 ** Store the result in register P3.
78351 ** If either input is NULL, the result is NULL.
78352 */
78353 case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
78354 case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
78355 case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
78356 case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
78357  i64 iA;
78358  u64 uA;
78359  i64 iB;
78360  u8 op;
78361 
78362  pIn1 = &aMem[pOp->p1];
78363  pIn2 = &aMem[pOp->p2];
78364  pOut = &aMem[pOp->p3];
78365  if( (pIn1->flags | pIn2->flags) & MEM_Null ){
78366  sqlite3VdbeMemSetNull(pOut);
78367  break;
78368  }
78369  iA = sqlite3VdbeIntValue(pIn2);
78370  iB = sqlite3VdbeIntValue(pIn1);
78371  op = pOp->opcode;
78372  if( op==OP_BitAnd ){
78373  iA &= iB;
78374  }else if( op==OP_BitOr ){
78375  iA |= iB;
78376  }else if( iB!=0 ){
78377  assert( op==OP_ShiftRight || op==OP_ShiftLeft );
78378 
78379  /* If shifting by a negative amount, shift in the other direction */
78380  if( iB<0 ){
78382  op = 2*OP_ShiftLeft + 1 - op;
78383  iB = iB>(-64) ? -iB : 64;
78384  }
78385 
78386  if( iB>=64 ){
78387  iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
78388  }else{
78389  memcpy(&uA, &iA, sizeof(uA));
78390  if( op==OP_ShiftLeft ){
78391  uA <<= iB;
78392  }else{
78393  uA >>= iB;
78394  /* Sign-extend on a right shift of a negative number */
78395  if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
78396  }
78397  memcpy(&iA, &uA, sizeof(iA));
78398  }
78399  }
78400  pOut->u.i = iA;
78401  MemSetTypeFlag(pOut, MEM_Int);
78402  break;
78403 }
78404 
78405 /* Opcode: AddImm P1 P2 * * *
78406 ** Synopsis: r[P1]=r[P1]+P2
78407 **
78408 ** Add the constant P2 to the value in register P1.
78409 ** The result is always an integer.
78410 **
78411 ** To force any register to be an integer, just add 0.
78412 */
78413 case OP_AddImm: { /* in1 */
78414  pIn1 = &aMem[pOp->p1];
78415  memAboutToChange(p, pIn1);
78417  pIn1->u.i += pOp->p2;
78418  break;
78419 }
78420 
78421 /* Opcode: MustBeInt P1 P2 * * *
78422 **
78423 ** Force the value in register P1 to be an integer. If the value
78424 ** in P1 is not an integer and cannot be converted into an integer
78425 ** without data loss, then jump immediately to P2, or if P2==0
78426 ** raise an SQLITE_MISMATCH exception.
78427 */
78428 case OP_MustBeInt: { /* jump, in1 */
78429  pIn1 = &aMem[pOp->p1];
78430  if( (pIn1->flags & MEM_Int)==0 ){
78431  applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
78432  VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
78433  if( (pIn1->flags & MEM_Int)==0 ){
78434  if( pOp->p2==0 ){
78435  rc = SQLITE_MISMATCH;
78436  goto abort_due_to_error;
78437  }else{
78438  goto jump_to_p2;
78439  }
78440  }
78441  }
78442  MemSetTypeFlag(pIn1, MEM_Int);
78443  break;
78444 }
78445 
78446 #ifndef SQLITE_OMIT_FLOATING_POINT
78447 /* Opcode: RealAffinity P1 * * * *
78448 **
78449 ** If register P1 holds an integer convert it to a real value.
78450 **
78451 ** This opcode is used when extracting information from a column that
78452 ** has REAL affinity. Such column values may still be stored as
78453 ** integers, for space efficiency, but after extraction we want them
78454 ** to have only a real value.
78455 */
78456 case OP_RealAffinity: { /* in1 */
78457  pIn1 = &aMem[pOp->p1];
78458  if( pIn1->flags & MEM_Int ){
78459  sqlite3VdbeMemRealify(pIn1);
78460  }
78461  break;
78462 }
78463 #endif
78464 
78465 #ifndef SQLITE_OMIT_CAST
78466 /* Opcode: Cast P1 P2 * * *
78467 ** Synopsis: affinity(r[P1])
78468 **
78469 ** Force the value in register P1 to be the type defined by P2.
78470 **
78471 ** <ul>
78472 ** <li value="97"> TEXT
78473 ** <li value="98"> BLOB
78474 ** <li value="99"> NUMERIC
78475 ** <li value="100"> INTEGER
78476 ** <li value="101"> REAL
78477 ** </ul>
78478 **
78479 ** A NULL value is not changed by this routine. It remains NULL.
78480 */
78481 case OP_Cast: { /* in1 */
78482  assert( pOp->p2>=SQLITE_AFF_BLOB && pOp->p2<=SQLITE_AFF_REAL );
78483  testcase( pOp->p2==SQLITE_AFF_TEXT );
78484  testcase( pOp->p2==SQLITE_AFF_BLOB );
78485  testcase( pOp->p2==SQLITE_AFF_NUMERIC );
78486  testcase( pOp->p2==SQLITE_AFF_INTEGER );
78487  testcase( pOp->p2==SQLITE_AFF_REAL );
78488  pIn1 = &aMem[pOp->p1];
78489  memAboutToChange(p, pIn1);
78490  rc = ExpandBlob(pIn1);
78491  sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
78492  UPDATE_MAX_BLOBSIZE(pIn1);
78493  if( rc ) goto abort_due_to_error;
78494  break;
78495 }
78496 #endif /* SQLITE_OMIT_CAST */
78497 
78498 /* Opcode: Lt P1 P2 P3 P4 P5
78499 ** Synopsis: if r[P1]<r[P3] goto P2
78500 **
78501 ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
78502 ** jump to address P2.
78503 **
78504 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
78505 ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
78506 ** bit is clear then fall through if either operand is NULL.
78507 **
78508 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
78509 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
78510 ** to coerce both inputs according to this affinity before the
78511 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
78512 ** affinity is used. Note that the affinity conversions are stored
78513 ** back into the input registers P1 and P3. So this opcode can cause
78514 ** persistent changes to registers P1 and P3.
78515 **
78516 ** Once any conversions have taken place, and neither value is NULL,
78517 ** the values are compared. If both values are blobs then memcmp() is
78518 ** used to determine the results of the comparison. If both values
78519 ** are text, then the appropriate collating function specified in
78520 ** P4 is used to do the comparison. If P4 is not specified then
78521 ** memcmp() is used to compare text string. If both values are
78522 ** numeric, then a numeric comparison is used. If the two values
78523 ** are of different types, then numbers are considered less than
78524 ** strings and strings are considered less than blobs.
78525 **
78526 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
78527 ** store a boolean result (either 0, or 1, or NULL) in register P2.
78528 **
78529 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
78530 ** equal to one another, provided that they do not have their MEM_Cleared
78531 ** bit set.
78532 */
78533 /* Opcode: Ne P1 P2 P3 P4 P5
78534 ** Synopsis: if r[P1]!=r[P3] goto P2
78535 **
78536 ** This works just like the Lt opcode except that the jump is taken if
78537 ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
78538 ** additional information.
78539 **
78540 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
78541 ** true or false and is never NULL. If both operands are NULL then the result
78542 ** of comparison is false. If either operand is NULL then the result is true.
78543 ** If neither operand is NULL the result is the same as it would be if
78544 ** the SQLITE_NULLEQ flag were omitted from P5.
78545 */
78546 /* Opcode: Eq P1 P2 P3 P4 P5
78547 ** Synopsis: if r[P1]==r[P3] goto P2
78548 **
78549 ** This works just like the Lt opcode except that the jump is taken if
78550 ** the operands in registers P1 and P3 are equal.
78551 ** See the Lt opcode for additional information.
78552 **
78553 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
78554 ** true or false and is never NULL. If both operands are NULL then the result
78555 ** of comparison is true. If either operand is NULL then the result is false.
78556 ** If neither operand is NULL the result is the same as it would be if
78557 ** the SQLITE_NULLEQ flag were omitted from P5.
78558 */
78559 /* Opcode: Le P1 P2 P3 P4 P5
78560 ** Synopsis: if r[P1]<=r[P3] goto P2
78561 **
78562 ** This works just like the Lt opcode except that the jump is taken if
78563 ** the content of register P3 is less than or equal to the content of
78564 ** register P1. See the Lt opcode for additional information.
78565 */
78566 /* Opcode: Gt P1 P2 P3 P4 P5
78567 ** Synopsis: if r[P1]>r[P3] goto P2
78568 **
78569 ** This works just like the Lt opcode except that the jump is taken if
78570 ** the content of register P3 is greater than the content of
78571 ** register P1. See the Lt opcode for additional information.
78572 */
78573 /* Opcode: Ge P1 P2 P3 P4 P5
78574 ** Synopsis: if r[P1]>=r[P3] goto P2
78575 **
78576 ** This works just like the Lt opcode except that the jump is taken if
78577 ** the content of register P3 is greater than or equal to the content of
78578 ** register P1. See the Lt opcode for additional information.
78579 */
78580 case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
78581 case OP_Ne: /* same as TK_NE, jump, in1, in3 */
78582 case OP_Lt: /* same as TK_LT, jump, in1, in3 */
78583 case OP_Le: /* same as TK_LE, jump, in1, in3 */
78584 case OP_Gt: /* same as TK_GT, jump, in1, in3 */
78585 case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
78586  int res; /* Result of the comparison of pIn1 against pIn3 */
78587  char affinity; /* Affinity to use for comparison */
78588  u16 flags1; /* Copy of initial value of pIn1->flags */
78589  u16 flags3; /* Copy of initial value of pIn3->flags */
78590 
78591  pIn1 = &aMem[pOp->p1];
78592  pIn3 = &aMem[pOp->p3];
78593  flags1 = pIn1->flags;
78594  flags3 = pIn3->flags;
78595  if( (flags1 | flags3)&MEM_Null ){
78596  /* One or both operands are NULL */
78597  if( pOp->p5 & SQLITE_NULLEQ ){
78598  /* If SQLITE_NULLEQ is set (which will only happen if the operator is
78599  ** OP_Eq or OP_Ne) then take the jump or not depending on whether
78600  ** or not both operands are null.
78601  */
78602  assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
78603  assert( (flags1 & MEM_Cleared)==0 );
78604  assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
78605  if( (flags1&MEM_Null)!=0
78606  && (flags3&MEM_Null)!=0
78607  && (flags3&MEM_Cleared)==0
78608  ){
78609  res = 0; /* Results are equal */
78610  }else{
78611  res = 1; /* Results are not equal */
78612  }
78613  }else{
78614  /* SQLITE_NULLEQ is clear and at least one operand is NULL,
78615  ** then the result is always NULL.
78616  ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
78617  */
78618  if( pOp->p5 & SQLITE_STOREP2 ){
78619  pOut = &aMem[pOp->p2];
78620  memAboutToChange(p, pOut);
78621  MemSetTypeFlag(pOut, MEM_Null);
78622  REGISTER_TRACE(pOp->p2, pOut);
78623  }else{
78624  VdbeBranchTaken(2,3);
78625  if( pOp->p5 & SQLITE_JUMPIFNULL ){
78626  goto jump_to_p2;
78627  }
78628  }
78629  break;
78630  }
78631  }else{
78632  /* Neither operand is NULL. Do a comparison. */
78633  affinity = pOp->p5 & SQLITE_AFF_MASK;
78634  if( affinity>=SQLITE_AFF_NUMERIC ){
78635  if( (flags1 | flags3)&MEM_Str ){
78636  if( (flags1 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78637  applyNumericAffinity(pIn1,0);
78638  }
78639  if( (flags3 & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
78640  applyNumericAffinity(pIn3,0);
78641  }
78642  }
78643  }else if( affinity==SQLITE_AFF_TEXT ){
78644  if( (flags1 & MEM_Str)==0 && (flags1 & (MEM_Int|MEM_Real))!=0 ){
78645  testcase( pIn1->flags & MEM_Int );
78646  testcase( pIn1->flags & MEM_Real );
78647  sqlite3VdbeMemStringify(pIn1, encoding, 1);
78648  testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
78649  flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
78650  }
78651  if( (flags3 & MEM_Str)==0 && (flags3 & (MEM_Int|MEM_Real))!=0 ){
78652  testcase( pIn3->flags & MEM_Int );
78653  testcase( pIn3->flags & MEM_Real );
78654  sqlite3VdbeMemStringify(pIn3, encoding, 1);
78655  testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
78656  flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
78657  }
78658  }
78659  assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
78660  if( flags1 & MEM_Zero ){
78662  flags1 &= ~MEM_Zero;
78663  }
78664  if( flags3 & MEM_Zero ){
78666  flags3 &= ~MEM_Zero;
78667  }
78668  res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
78669  }
78670  switch( pOp->opcode ){
78671  case OP_Eq: res = res==0; break;
78672  case OP_Ne: res = res!=0; break;
78673  case OP_Lt: res = res<0; break;
78674  case OP_Le: res = res<=0; break;
78675  case OP_Gt: res = res>0; break;
78676  default: res = res>=0; break;
78677  }
78678 
78679  /* Undo any changes made by applyAffinity() to the input registers. */
78680  assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
78681  pIn1->flags = flags1;
78682  assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
78683  pIn3->flags = flags3;
78684 
78685  if( pOp->p5 & SQLITE_STOREP2 ){
78686  pOut = &aMem[pOp->p2];
78687  memAboutToChange(p, pOut);
78688  MemSetTypeFlag(pOut, MEM_Int);
78689  pOut->u.i = res;
78690  REGISTER_TRACE(pOp->p2, pOut);
78691  }else{
78692  VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
78693  if( res ){
78694  goto jump_to_p2;
78695  }
78696  }
78697  break;
78698 }
78699 
78700 /* Opcode: Permutation * * * P4 *
78701 **
78702 ** Set the permutation used by the OP_Compare operator to be the array
78703 ** of integers in P4.
78704 **
78705 ** The permutation is only valid until the next OP_Compare that has
78706 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
78707 ** occur immediately prior to the OP_Compare.
78708 **
78709 ** The first integer in the P4 integer array is the length of the array
78710 ** and does not become part of the permutation.
78711 */
78712 case OP_Permutation: {
78713  assert( pOp->p4type==P4_INTARRAY );
78714  assert( pOp->p4.ai );
78715  aPermute = pOp->p4.ai + 1;
78716  break;
78717 }
78718 
78719 /* Opcode: Compare P1 P2 P3 P4 P5
78720 ** Synopsis: r[P1@P3] <-> r[P2@P3]
78721 **
78722 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
78723 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
78724 ** the comparison for use by the next OP_Jump instruct.
78725 **
78726 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
78727 ** determined by the most recent OP_Permutation operator. If the
78728 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
78729 ** order.
78730 **
78731 ** P4 is a KeyInfo structure that defines collating sequences and sort
78732 ** orders for the comparison. The permutation applies to registers
78733 ** only. The KeyInfo elements are used sequentially.
78734 **
78735 ** The comparison is a sort comparison, so NULLs compare equal,
78736 ** NULLs are less than numbers, numbers are less than strings,
78737 ** and strings are less than blobs.
78738 */
78739 case OP_Compare: {
78740  int n;
78741  int i;
78742  int p1;
78743  int p2;
78744  const KeyInfo *pKeyInfo;
78745  int idx;
78746  CollSeq *pColl; /* Collating sequence to use on this term */
78747  int bRev; /* True for DESCENDING sort order */
78748 
78749  if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
78750  n = pOp->p3;
78751  pKeyInfo = pOp->p4.pKeyInfo;
78752  assert( n>0 );
78753  assert( pKeyInfo!=0 );
78754  p1 = pOp->p1;
78755  p2 = pOp->p2;
78756 #if SQLITE_DEBUG
78757  if( aPermute ){
78758  int k, mx = 0;
78759  for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
78760  assert( p1>0 && p1+mx<=(p->nMem+1 - p->nCursor)+1 );
78761  assert( p2>0 && p2+mx<=(p->nMem+1 - p->nCursor)+1 );
78762  }else{
78763  assert( p1>0 && p1+n<=(p->nMem+1 - p->nCursor)+1 );
78764  assert( p2>0 && p2+n<=(p->nMem+1 - p->nCursor)+1 );
78765  }
78766 #endif /* SQLITE_DEBUG */
78767  for(i=0; i<n; i++){
78768  idx = aPermute ? aPermute[i] : i;
78769  assert( memIsValid(&aMem[p1+idx]) );
78770  assert( memIsValid(&aMem[p2+idx]) );
78771  REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
78772  REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
78773  assert( i<pKeyInfo->nField );
78774  pColl = pKeyInfo->aColl[i];
78775  bRev = pKeyInfo->aSortOrder[i];
78776  iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
78777  if( iCompare ){
78778  if( bRev ) iCompare = -iCompare;
78779  break;
78780  }
78781  }
78782  aPermute = 0;
78783  break;
78784 }
78785 
78786 /* Opcode: Jump P1 P2 P3 * *
78787 **
78788 ** Jump to the instruction at address P1, P2, or P3 depending on whether
78789 ** in the most recent OP_Compare instruction the P1 vector was less than
78790 ** equal to, or greater than the P2 vector, respectively.
78791 */
78792 case OP_Jump: { /* jump */
78793  if( iCompare<0 ){
78794  VdbeBranchTaken(0,3); pOp = &aOp[pOp->p1 - 1];
78795  }else if( iCompare==0 ){
78796  VdbeBranchTaken(1,3); pOp = &aOp[pOp->p2 - 1];
78797  }else{
78798  VdbeBranchTaken(2,3); pOp = &aOp[pOp->p3 - 1];
78799  }
78800  break;
78801 }
78802 
78803 /* Opcode: And P1 P2 P3 * *
78804 ** Synopsis: r[P3]=(r[P1] && r[P2])
78805 **
78806 ** Take the logical AND of the values in registers P1 and P2 and
78807 ** write the result into register P3.
78808 **
78809 ** If either P1 or P2 is 0 (false) then the result is 0 even if
78810 ** the other input is NULL. A NULL and true or two NULLs give
78811 ** a NULL output.
78812 */
78813 /* Opcode: Or P1 P2 P3 * *
78814 ** Synopsis: r[P3]=(r[P1] || r[P2])
78815 **
78816 ** Take the logical OR of the values in register P1 and P2 and
78817 ** store the answer in register P3.
78818 **
78819 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
78820 ** even if the other input is NULL. A NULL and false or two NULLs
78821 ** give a NULL output.
78822 */
78823 case OP_And: /* same as TK_AND, in1, in2, out3 */
78824 case OP_Or: { /* same as TK_OR, in1, in2, out3 */
78825  int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
78826  int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
78827 
78828  pIn1 = &aMem[pOp->p1];
78829  if( pIn1->flags & MEM_Null ){
78830  v1 = 2;
78831  }else{
78832  v1 = sqlite3VdbeIntValue(pIn1)!=0;
78833  }
78834  pIn2 = &aMem[pOp->p2];
78835  if( pIn2->flags & MEM_Null ){
78836  v2 = 2;
78837  }else{
78838  v2 = sqlite3VdbeIntValue(pIn2)!=0;
78839  }
78840  if( pOp->opcode==OP_And ){
78841  static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
78842  v1 = and_logic[v1*3+v2];
78843  }else{
78844  static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
78845  v1 = or_logic[v1*3+v2];
78846  }
78847  pOut = &aMem[pOp->p3];
78848  if( v1==2 ){
78849  MemSetTypeFlag(pOut, MEM_Null);
78850  }else{
78851  pOut->u.i = v1;
78852  MemSetTypeFlag(pOut, MEM_Int);
78853  }
78854  break;
78855 }
78856 
78857 /* Opcode: Not P1 P2 * * *
78858 ** Synopsis: r[P2]= !r[P1]
78859 **
78860 ** Interpret the value in register P1 as a boolean value. Store the
78861 ** boolean complement in register P2. If the value in register P1 is
78862 ** NULL, then a NULL is stored in P2.
78863 */
78864 case OP_Not: { /* same as TK_NOT, in1, out2 */
78865  pIn1 = &aMem[pOp->p1];
78866  pOut = &aMem[pOp->p2];
78867  sqlite3VdbeMemSetNull(pOut);
78868  if( (pIn1->flags & MEM_Null)==0 ){
78869  pOut->flags = MEM_Int;
78870  pOut->u.i = !sqlite3VdbeIntValue(pIn1);
78871  }
78872  break;
78873 }
78874 
78875 /* Opcode: BitNot P1 P2 * * *
78876 ** Synopsis: r[P1]= ~r[P1]
78877 **
78878 ** Interpret the content of register P1 as an integer. Store the
78879 ** ones-complement of the P1 value into register P2. If P1 holds
78880 ** a NULL then store a NULL in P2.
78881 */
78882 case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
78883  pIn1 = &aMem[pOp->p1];
78884  pOut = &aMem[pOp->p2];
78885  sqlite3VdbeMemSetNull(pOut);
78886  if( (pIn1->flags & MEM_Null)==0 ){
78887  pOut->flags = MEM_Int;
78888  pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
78889  }
78890  break;
78891 }
78892 
78893 /* Opcode: Once P1 P2 * * *
78894 **
78895 ** Check the "once" flag number P1. If it is set, jump to instruction P2.
78896 ** Otherwise, set the flag and fall through to the next instruction.
78897 ** In other words, this opcode causes all following opcodes up through P2
78898 ** (but not including P2) to run just once and to be skipped on subsequent
78899 ** times through the loop.
78900 **
78901 ** All "once" flags are initially cleared whenever a prepared statement
78902 ** first begins to run.
78903 */
78904 case OP_Once: { /* jump */
78905  assert( pOp->p1<p->nOnceFlag );
78906  VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
78907  if( p->aOnceFlag[pOp->p1] ){
78908  goto jump_to_p2;
78909  }else{
78910  p->aOnceFlag[pOp->p1] = 1;
78911  }
78912  break;
78913 }
78914 
78915 /* Opcode: If P1 P2 P3 * *
78916 **
78917 ** Jump to P2 if the value in register P1 is true. The value
78918 ** is considered true if it is numeric and non-zero. If the value
78919 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
78920 */
78921 /* Opcode: IfNot P1 P2 P3 * *
78922 **
78923 ** Jump to P2 if the value in register P1 is False. The value
78924 ** is considered false if it has a numeric value of zero. If the value
78925 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
78926 */
78927 case OP_If: /* jump, in1 */
78928 case OP_IfNot: { /* jump, in1 */
78929  int c;
78930  pIn1 = &aMem[pOp->p1];
78931  if( pIn1->flags & MEM_Null ){
78932  c = pOp->p3;
78933  }else{
78934 #ifdef SQLITE_OMIT_FLOATING_POINT
78935  c = sqlite3VdbeIntValue(pIn1)!=0;
78936 #else
78937  c = sqlite3VdbeRealValue(pIn1)!=0.0;
78938 #endif
78939  if( pOp->opcode==OP_IfNot ) c = !c;
78940  }
78941  VdbeBranchTaken(c!=0, 2);
78942  if( c ){
78943  goto jump_to_p2;
78944  }
78945  break;
78946 }
78947 
78948 /* Opcode: IsNull P1 P2 * * *
78949 ** Synopsis: if r[P1]==NULL goto P2
78950 **
78951 ** Jump to P2 if the value in register P1 is NULL.
78952 */
78953 case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
78954  pIn1 = &aMem[pOp->p1];
78955  VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
78956  if( (pIn1->flags & MEM_Null)!=0 ){
78957  goto jump_to_p2;
78958  }
78959  break;
78960 }
78961 
78962 /* Opcode: NotNull P1 P2 * * *
78963 ** Synopsis: if r[P1]!=NULL goto P2
78964 **
78965 ** Jump to P2 if the value in register P1 is not NULL.
78966 */
78967 case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
78968  pIn1 = &aMem[pOp->p1];
78969  VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
78970  if( (pIn1->flags & MEM_Null)==0 ){
78971  goto jump_to_p2;
78972  }
78973  break;
78974 }
78975 
78976 /* Opcode: Column P1 P2 P3 P4 P5
78977 ** Synopsis: r[P3]=PX
78978 **
78979 ** Interpret the data that cursor P1 points to as a structure built using
78980 ** the MakeRecord instruction. (See the MakeRecord opcode for additional
78981 ** information about the format of the data.) Extract the P2-th column
78982 ** from this record. If there are less that (P2+1)
78983 ** values in the record, extract a NULL.
78984 **
78985 ** The value extracted is stored in register P3.
78986 **
78987 ** If the column contains fewer than P2 fields, then extract a NULL. Or,
78988 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
78989 ** the result.
78990 **
78991 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
78992 ** then the cache of the cursor is reset prior to extracting the column.
78993 ** The first OP_Column against a pseudo-table after the value of the content
78994 ** register has changed should have this bit set.
78995 **
78996 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
78997 ** the result is guaranteed to only be used as the argument of a length()
78998 ** or typeof() function, respectively. The loading of large blobs can be
78999 ** skipped for length() and all content loading can be skipped for typeof().
79000 */
79001 case OP_Column: {
79002  i64 payloadSize64; /* Number of bytes in the record */
79003  int p2; /* column number to retrieve */
79004  VdbeCursor *pC; /* The VDBE cursor */
79005  BtCursor *pCrsr; /* The BTree cursor */
79006  u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
79007  int len; /* The length of the serialized data for the column */
79008  int i; /* Loop counter */
79009  Mem *pDest; /* Where to write the extracted value */
79010  Mem sMem; /* For storing the record being decoded */
79011  const u8 *zData; /* Part of the record being decoded */
79012  const u8 *zHdr; /* Next unparsed byte of the header */
79013  const u8 *zEndHdr; /* Pointer to first byte after the header */
79014  u32 offset; /* Offset into the data */
79015  u64 offset64; /* 64-bit offset */
79016  u32 avail; /* Number of bytes of available data */
79017  u32 t; /* A type code from the record header */
79018  Mem *pReg; /* PseudoTable input register */
79019 
79020  pC = p->apCsr[pOp->p1];
79021  p2 = pOp->p2;
79022 
79023  /* If the cursor cache is stale, bring it up-to-date */
79024  rc = sqlite3VdbeCursorMoveto(&pC, &p2);
79025 
79026  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79027  pDest = &aMem[pOp->p3];
79028  memAboutToChange(p, pDest);
79029  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
79030  assert( pC!=0 );
79031  assert( p2<pC->nField );
79032  aOffset = pC->aOffset;
79033  assert( pC->eCurType!=CURTYPE_VTAB );
79034  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
79035  assert( pC->eCurType!=CURTYPE_SORTER );
79036  pCrsr = pC->uc.pCursor;
79037 
79038  if( rc ) goto abort_due_to_error;
79039  if( pC->cacheStatus!=p->cacheCtr ){
79040  if( pC->nullRow ){
79041  if( pC->eCurType==CURTYPE_PSEUDO ){
79042  assert( pC->uc.pseudoTableReg>0 );
79043  pReg = &aMem[pC->uc.pseudoTableReg];
79044  assert( pReg->flags & MEM_Blob );
79045  assert( memIsValid(pReg) );
79046  pC->payloadSize = pC->szRow = avail = pReg->n;
79047  pC->aRow = (u8*)pReg->z;
79048  }else{
79049  sqlite3VdbeMemSetNull(pDest);
79050  goto op_column_out;
79051  }
79052  }else{
79053  assert( pC->eCurType==CURTYPE_BTREE );
79054  assert( pCrsr );
79055  if( pC->isTable==0 ){
79056  assert( sqlite3BtreeCursorIsValid(pCrsr) );
79057  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
79058  assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
79059  /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
79060  ** payload size, so it is impossible for payloadSize64 to be
79061  ** larger than 32 bits. */
79062  assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
79063  pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
79064  pC->payloadSize = (u32)payloadSize64;
79065  }else{
79066  assert( sqlite3BtreeCursorIsValid(pCrsr) );
79067  VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
79068  assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
79069  pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
79070  }
79071  assert( avail<=65536 ); /* Maximum page size is 64KiB */
79072  if( pC->payloadSize <= (u32)avail ){
79073  pC->szRow = pC->payloadSize;
79074  }else if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
79075  goto too_big;
79076  }else{
79077  pC->szRow = avail;
79078  }
79079  }
79080  pC->cacheStatus = p->cacheCtr;
79081  pC->iHdrOffset = getVarint32(pC->aRow, offset);
79082  pC->nHdrParsed = 0;
79083  aOffset[0] = offset;
79084 
79085 
79086  if( avail<offset ){
79087  /* pC->aRow does not have to hold the entire row, but it does at least
79088  ** need to cover the header of the record. If pC->aRow does not contain
79089  ** the complete header, then set it to zero, forcing the header to be
79090  ** dynamically allocated. */
79091  pC->aRow = 0;
79092  pC->szRow = 0;
79093 
79094  /* Make sure a corrupt database has not given us an oversize header.
79095  ** Do this now to avoid an oversize memory allocation.
79096  **
79097  ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
79098  ** types use so much data space that there can only be 4096 and 32 of
79099  ** them, respectively. So the maximum header length results from a
79100  ** 3-byte type for each of the maximum of 32768 columns plus three
79101  ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
79102  */
79103  if( offset > 98307 || offset > pC->payloadSize ){
79104  rc = SQLITE_CORRUPT_BKPT;
79105  goto abort_due_to_error;
79106  }
79107  }
79108 
79109  /* The following goto is an optimization. It can be omitted and
79110  ** everything will still work. But OP_Column is measurably faster
79111  ** by skipping the subsequent conditional, which is always true.
79112  */
79113  assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
79114  goto op_column_read_header;
79115  }
79116 
79117  /* Make sure at least the first p2+1 entries of the header have been
79118  ** parsed and valid information is in aOffset[] and pC->aType[].
79119  */
79120  if( pC->nHdrParsed<=p2 ){
79121  /* If there is more header available for parsing in the record, try
79122  ** to extract additional fields up through the p2+1-th field
79123  */
79124  op_column_read_header:
79125  if( pC->iHdrOffset<aOffset[0] ){
79126  /* Make sure zData points to enough of the record to cover the header. */
79127  if( pC->aRow==0 ){
79128  memset(&sMem, 0, sizeof(sMem));
79129  rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], !pC->isTable, &sMem);
79130  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79131  zData = (u8*)sMem.z;
79132  }else{
79133  zData = pC->aRow;
79134  }
79135 
79136  /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
79137  i = pC->nHdrParsed;
79138  offset64 = aOffset[i];
79139  zHdr = zData + pC->iHdrOffset;
79140  zEndHdr = zData + aOffset[0];
79141  assert( i<=p2 && zHdr<zEndHdr );
79142  do{
79143  if( (t = zHdr[0])<0x80 ){
79144  zHdr++;
79145  offset64 += sqlite3VdbeOneByteSerialTypeLen(t);
79146  }else{
79147  zHdr += sqlite3GetVarint32(zHdr, &t);
79148  offset64 += sqlite3VdbeSerialTypeLen(t);
79149  }
79150  pC->aType[i++] = t;
79151  aOffset[i] = (u32)(offset64 & 0xffffffff);
79152  }while( i<=p2 && zHdr<zEndHdr );
79153  pC->nHdrParsed = i;
79154  pC->iHdrOffset = (u32)(zHdr - zData);
79155 
79156  /* The record is corrupt if any of the following are true:
79157  ** (1) the bytes of the header extend past the declared header size
79158  ** (2) the entire header was used but not all data was used
79159  ** (3) the end of the data extends beyond the end of the record.
79160  */
79161  if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset64!=pC->payloadSize))
79162  || (offset64 > pC->payloadSize)
79163  ){
79164  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79165  rc = SQLITE_CORRUPT_BKPT;
79166  goto abort_due_to_error;
79167  }
79168  if( pC->aRow==0 ) sqlite3VdbeMemRelease(&sMem);
79169 
79170  }else{
79171  t = 0;
79172  }
79173 
79174  /* If after trying to extract new entries from the header, nHdrParsed is
79175  ** still not up to p2, that means that the record has fewer than p2
79176  ** columns. So the result will be either the default value or a NULL.
79177  */
79178  if( pC->nHdrParsed<=p2 ){
79179  if( pOp->p4type==P4_MEM ){
79181  }else{
79182  sqlite3VdbeMemSetNull(pDest);
79183  }
79184  goto op_column_out;
79185  }
79186  }else{
79187  t = pC->aType[p2];
79188  }
79189 
79190  /* Extract the content for the p2+1-th column. Control can only
79191  ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
79192  ** all valid.
79193  */
79194  assert( p2<pC->nHdrParsed );
79195  assert( rc==SQLITE_OK );
79196  assert( sqlite3VdbeCheckMemInvariants(pDest) );
79197  if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
79198  assert( t==pC->aType[p2] );
79199  pDest->enc = encoding;
79200  if( pC->szRow>=aOffset[p2+1] ){
79201  /* This is the common case where the desired content fits on the original
79202  ** page - where the content is not on an overflow page */
79203  zData = pC->aRow + aOffset[p2];
79204  if( t<12 ){
79205  sqlite3VdbeSerialGet(zData, t, pDest);
79206  }else{
79207  /* If the column value is a string, we need a persistent value, not
79208  ** a MEM_Ephem value. This branch is a fast short-cut that is equivalent
79209  ** to calling sqlite3VdbeSerialGet() and sqlite3VdbeDeephemeralize().
79210  */
79211  static const u16 aFlag[] = { MEM_Blob, MEM_Str|MEM_Term };
79212  pDest->n = len = (t-12)/2;
79213  if( pDest->szMalloc < len+2 ){
79214  pDest->flags = MEM_Null;
79215  if( sqlite3VdbeMemGrow(pDest, len+2, 0) ) goto no_mem;
79216  }else{
79217  pDest->z = pDest->zMalloc;
79218  }
79219  memcpy(pDest->z, zData, len);
79220  pDest->z[len] = 0;
79221  pDest->z[len+1] = 0;
79222  pDest->flags = aFlag[t&1];
79223  }
79224  }else{
79225  /* This branch happens only when content is on overflow pages */
79226  if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
79227  && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
79228  || (len = sqlite3VdbeSerialTypeLen(t))==0
79229  ){
79230  /* Content is irrelevant for
79231  ** 1. the typeof() function,
79232  ** 2. the length(X) function if X is a blob, and
79233  ** 3. if the content length is zero.
79234  ** So we might as well use bogus content rather than reading
79235  ** content from disk. */
79236  static u8 aZero[8]; /* This is the bogus content */
79237  sqlite3VdbeSerialGet(aZero, t, pDest);
79238  }else{
79239  rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
79240  pDest);
79241  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79242  sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
79243  pDest->flags &= ~MEM_Ephem;
79244  }
79245  }
79246 
79247 op_column_out:
79248  UPDATE_MAX_BLOBSIZE(pDest);
79249  REGISTER_TRACE(pOp->p3, pDest);
79250  break;
79251 }
79252 
79253 /* Opcode: Affinity P1 P2 * P4 *
79254 ** Synopsis: affinity(r[P1@P2])
79255 **
79256 ** Apply affinities to a range of P2 registers starting with P1.
79257 **
79258 ** P4 is a string that is P2 characters long. The nth character of the
79259 ** string indicates the column affinity that should be used for the nth
79260 ** memory cell in the range.
79261 */
79262 case OP_Affinity: {
79263  const char *zAffinity; /* The affinity to be applied */
79264  char cAff; /* A single character of affinity */
79265 
79266  zAffinity = pOp->p4.z;
79267  assert( zAffinity!=0 );
79268  assert( zAffinity[pOp->p2]==0 );
79269  pIn1 = &aMem[pOp->p1];
79270  while( (cAff = *(zAffinity++))!=0 ){
79271  assert( pIn1 <= &p->aMem[(p->nMem+1 - p->nCursor)] );
79272  assert( memIsValid(pIn1) );
79273  applyAffinity(pIn1, cAff, encoding);
79274  pIn1++;
79275  }
79276  break;
79277 }
79278 
79279 /* Opcode: MakeRecord P1 P2 P3 P4 *
79280 ** Synopsis: r[P3]=mkrec(r[P1@P2])
79281 **
79282 ** Convert P2 registers beginning with P1 into the [record format]
79283 ** use as a data record in a database table or as a key
79284 ** in an index. The OP_Column opcode can decode the record later.
79285 **
79286 ** P4 may be a string that is P2 characters long. The nth character of the
79287 ** string indicates the column affinity that should be used for the nth
79288 ** field of the index key.
79289 **
79290 ** The mapping from character to affinity is given by the SQLITE_AFF_
79291 ** macros defined in sqliteInt.h.
79292 **
79293 ** If P4 is NULL then all index fields have the affinity BLOB.
79294 */
79295 case OP_MakeRecord: {
79296  u8 *zNewRecord; /* A buffer to hold the data for the new record */
79297  Mem *pRec; /* The new record */
79298  u64 nData; /* Number of bytes of data space */
79299  int nHdr; /* Number of bytes of header space */
79300  i64 nByte; /* Data space required for this record */
79301  i64 nZero; /* Number of zero bytes at the end of the record */
79302  int nVarint; /* Number of bytes in a varint */
79303  u32 serial_type; /* Type field */
79304  Mem *pData0; /* First field to be combined into the record */
79305  Mem *pLast; /* Last field of the record */
79306  int nField; /* Number of fields in the record */
79307  char *zAffinity; /* The affinity string for the record */
79308  int file_format; /* File format to use for encoding */
79309  int i; /* Space used in zNewRecord[] header */
79310  int j; /* Space used in zNewRecord[] content */
79311  u32 len; /* Length of a field */
79312 
79313  /* Assuming the record contains N fields, the record format looks
79314  ** like this:
79315  **
79316  ** ------------------------------------------------------------------------
79317  ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
79318  ** ------------------------------------------------------------------------
79319  **
79320  ** Data(0) is taken from register P1. Data(1) comes from register P1+1
79321  ** and so forth.
79322  **
79323  ** Each type field is a varint representing the serial type of the
79324  ** corresponding data element (see sqlite3VdbeSerialType()). The
79325  ** hdr-size field is also a varint which is the offset from the beginning
79326  ** of the record to data0.
79327  */
79328  nData = 0; /* Number of bytes of data space */
79329  nHdr = 0; /* Number of bytes of header space */
79330  nZero = 0; /* Number of zero bytes at the end of the record */
79331  nField = pOp->p1;
79332  zAffinity = pOp->p4.z;
79333  assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem+1 - p->nCursor)+1 );
79334  pData0 = &aMem[nField];
79335  nField = pOp->p2;
79336  pLast = &pData0[nField-1];
79337  file_format = p->minWriteFileFormat;
79338 
79339  /* Identify the output register */
79340  assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
79341  pOut = &aMem[pOp->p3];
79342  memAboutToChange(p, pOut);
79343 
79344  /* Apply the requested affinity to all inputs
79345  */
79346  assert( pData0<=pLast );
79347  if( zAffinity ){
79348  pRec = pData0;
79349  do{
79350  applyAffinity(pRec++, *(zAffinity++), encoding);
79351  assert( zAffinity[0]==0 || pRec<=pLast );
79352  }while( zAffinity[0] );
79353  }
79354 
79355  /* Loop through the elements that will make up the record to figure
79356  ** out how much space is required for the new record.
79357  */
79358  pRec = pLast;
79359  do{
79360  assert( memIsValid(pRec) );
79361  pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format, &len);
79362  if( pRec->flags & MEM_Zero ){
79363  if( nData ){
79364  if( sqlite3VdbeMemExpandBlob(pRec) ) goto no_mem;
79365  }else{
79366  nZero += pRec->u.nZero;
79367  len -= pRec->u.nZero;
79368  }
79369  }
79370  nData += len;
79371  testcase( serial_type==127 );
79372  testcase( serial_type==128 );
79373  nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
79374  if( pRec==pData0 ) break;
79375  pRec--;
79376  }while(1);
79377 
79378  /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
79379  ** which determines the total number of bytes in the header. The varint
79380  ** value is the size of the header in bytes including the size varint
79381  ** itself. */
79382  testcase( nHdr==126 );
79383  testcase( nHdr==127 );
79384  if( nHdr<=126 ){
79385  /* The common case */
79386  nHdr += 1;
79387  }else{
79388  /* Rare case of a really large header */
79389  nVarint = sqlite3VarintLen(nHdr);
79390  nHdr += nVarint;
79391  if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
79392  }
79393  nByte = nHdr+nData;
79394  if( nByte+nZero>db->aLimit[SQLITE_LIMIT_LENGTH] ){
79395  goto too_big;
79396  }
79397 
79398  /* Make sure the output register has a buffer large enough to store
79399  ** the new record. The output register (pOp->p3) is not allowed to
79400  ** be one of the input registers (because the following call to
79401  ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
79402  */
79403  if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
79404  goto no_mem;
79405  }
79406  zNewRecord = (u8 *)pOut->z;
79407 
79408  /* Write the record */
79409  i = putVarint32(zNewRecord, nHdr);
79410  j = nHdr;
79411  assert( pData0<=pLast );
79412  pRec = pData0;
79413  do{
79414  serial_type = pRec->uTemp;
79415  /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
79416  ** additional varints, one per column. */
79417  i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
79418  /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
79419  ** immediately follow the header. */
79420  j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
79421  }while( (++pRec)<=pLast );
79422  assert( i==nHdr );
79423  assert( j==nByte );
79424 
79425  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
79426  pOut->n = (int)nByte;
79427  pOut->flags = MEM_Blob;
79428  if( nZero ){
79429  pOut->u.nZero = nZero;
79430  pOut->flags |= MEM_Zero;
79431  }
79432  pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
79433  REGISTER_TRACE(pOp->p3, pOut);
79434  UPDATE_MAX_BLOBSIZE(pOut);
79435  break;
79436 }
79437 
79438 /* Opcode: Count P1 P2 * * *
79439 ** Synopsis: r[P2]=count()
79440 **
79441 ** Store the number of entries (an integer value) in the table or index
79442 ** opened by cursor P1 in register P2
79443 */
79444 #ifndef SQLITE_OMIT_BTREECOUNT
79445 case OP_Count: { /* out2 */
79446  i64 nEntry;
79447  BtCursor *pCrsr;
79448 
79449  assert( p->apCsr[pOp->p1]->eCurType==CURTYPE_BTREE );
79450  pCrsr = p->apCsr[pOp->p1]->uc.pCursor;
79451  assert( pCrsr );
79452  nEntry = 0; /* Not needed. Only used to silence a warning. */
79453  rc = sqlite3BtreeCount(pCrsr, &nEntry);
79454  if( rc ) goto abort_due_to_error;
79455  pOut = out2Prerelease(p, pOp);
79456  pOut->u.i = nEntry;
79457  break;
79458 }
79459 #endif
79460 
79461 /* Opcode: Savepoint P1 * * P4 *
79462 **
79463 ** Open, release or rollback the savepoint named by parameter P4, depending
79464 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
79465 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
79466 */
79467 case OP_Savepoint: {
79468  int p1; /* Value of P1 operand */
79469  char *zName; /* Name of savepoint */
79470  int nName;
79471  Savepoint *pNew;
79472  Savepoint *pSavepoint;
79473  Savepoint *pTmp;
79474  int iSavepoint;
79475  int ii;
79476 
79477  p1 = pOp->p1;
79478  zName = pOp->p4.z;
79479 
79480  /* Assert that the p1 parameter is valid. Also that if there is no open
79481  ** transaction, then there cannot be any savepoints.
79482  */
79483  assert( db->pSavepoint==0 || db->autoCommit==0 );
79485  assert( db->pSavepoint || db->isTransactionSavepoint==0 );
79486  assert( checkSavepointCount(db) );
79487  assert( p->bIsReader );
79488 
79489  if( p1==SAVEPOINT_BEGIN ){
79490  if( db->nVdbeWrite>0 ){
79491  /* A new savepoint cannot be created if there are active write
79492  ** statements (i.e. open read/write incremental blob handles).
79493  */
79494  sqlite3VdbeError(p, "cannot open savepoint - SQL statements in progress");
79495  rc = SQLITE_BUSY;
79496  }else{
79497  nName = sqlite3Strlen30(zName);
79498 
79499 #ifndef SQLITE_OMIT_VIRTUALTABLE
79500  /* This call is Ok even if this savepoint is actually a transaction
79501  ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
79502  ** If this is a transaction savepoint being opened, it is guaranteed
79503  ** that the db->aVTrans[] array is empty. */
79504  assert( db->autoCommit==0 || db->nVTrans==0 );
79506  db->nStatement+db->nSavepoint);
79507  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79508 #endif
79509 
79510  /* Create a new savepoint structure. */
79511  pNew = sqlite3DbMallocRawNN(db, sizeof(Savepoint)+nName+1);
79512  if( pNew ){
79513  pNew->zName = (char *)&pNew[1];
79514  memcpy(pNew->zName, zName, nName+1);
79515 
79516  /* If there is no open transaction, then mark this as a special
79517  ** "transaction savepoint". */
79518  if( db->autoCommit ){
79519  db->autoCommit = 0;
79520  db->isTransactionSavepoint = 1;
79521  }else{
79522  db->nSavepoint++;
79523  }
79524 
79525  /* Link the new savepoint into the database handle's list. */
79526  pNew->pNext = db->pSavepoint;
79527  db->pSavepoint = pNew;
79528  pNew->nDeferredCons = db->nDeferredCons;
79529  pNew->nDeferredImmCons = db->nDeferredImmCons;
79530  }
79531  }
79532  }else{
79533  iSavepoint = 0;
79534 
79535  /* Find the named savepoint. If there is no such savepoint, then an
79536  ** an error is returned to the user. */
79537  for(
79538  pSavepoint = db->pSavepoint;
79539  pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
79540  pSavepoint = pSavepoint->pNext
79541  ){
79542  iSavepoint++;
79543  }
79544  if( !pSavepoint ){
79545  sqlite3VdbeError(p, "no such savepoint: %s", zName);
79546  rc = SQLITE_ERROR;
79547  }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
79548  /* It is not possible to release (commit) a savepoint if there are
79549  ** active write statements.
79550  */
79551  sqlite3VdbeError(p, "cannot release savepoint - "
79552  "SQL statements in progress");
79553  rc = SQLITE_BUSY;
79554  }else{
79555 
79556  /* Determine whether or not this is a transaction savepoint. If so,
79557  ** and this is a RELEASE command, then the current transaction
79558  ** is committed.
79559  */
79560  int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
79561  if( isTransaction && p1==SAVEPOINT_RELEASE ){
79562  if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
79563  goto vdbe_return;
79564  }
79565  db->autoCommit = 1;
79566  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
79567  p->pc = (int)(pOp - aOp);
79568  db->autoCommit = 0;
79569  p->rc = rc = SQLITE_BUSY;
79570  goto vdbe_return;
79571  }
79572  db->isTransactionSavepoint = 0;
79573  rc = p->rc;
79574  }else{
79575  int isSchemaChange;
79576  iSavepoint = db->nSavepoint - iSavepoint - 1;
79577  if( p1==SAVEPOINT_ROLLBACK ){
79578  isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
79579  for(ii=0; ii<db->nDb; ii++){
79580  rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
79582  isSchemaChange==0);
79583  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79584  }
79585  }else{
79586  isSchemaChange = 0;
79587  }
79588  for(ii=0; ii<db->nDb; ii++){
79589  rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
79590  if( rc!=SQLITE_OK ){
79591  goto abort_due_to_error;
79592  }
79593  }
79594  if( isSchemaChange ){
79597  db->flags = (db->flags | SQLITE_InternChanges);
79598  }
79599  }
79600 
79601  /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
79602  ** savepoints nested inside of the savepoint being operated on. */
79603  while( db->pSavepoint!=pSavepoint ){
79604  pTmp = db->pSavepoint;
79605  db->pSavepoint = pTmp->pNext;
79606  sqlite3DbFree(db, pTmp);
79607  db->nSavepoint--;
79608  }
79609 
79610  /* If it is a RELEASE, then destroy the savepoint being operated on
79611  ** too. If it is a ROLLBACK TO, then set the number of deferred
79612  ** constraint violations present in the database to the value stored
79613  ** when the savepoint was created. */
79614  if( p1==SAVEPOINT_RELEASE ){
79615  assert( pSavepoint==db->pSavepoint );
79616  db->pSavepoint = pSavepoint->pNext;
79617  sqlite3DbFree(db, pSavepoint);
79618  if( !isTransaction ){
79619  db->nSavepoint--;
79620  }
79621  }else{
79622  db->nDeferredCons = pSavepoint->nDeferredCons;
79623  db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
79624  }
79625 
79626  if( !isTransaction || p1==SAVEPOINT_ROLLBACK ){
79627  rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
79628  if( rc!=SQLITE_OK ) goto abort_due_to_error;
79629  }
79630  }
79631  }
79632  if( rc ) goto abort_due_to_error;
79633 
79634  break;
79635 }
79636 
79637 /* Opcode: AutoCommit P1 P2 * * *
79638 **
79639 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
79640 ** back any currently active btree transactions. If there are any active
79641 ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
79642 ** there are active writing VMs or active VMs that use shared cache.
79643 **
79644 ** This instruction causes the VM to halt.
79645 */
79646 case OP_AutoCommit: {
79647  int desiredAutoCommit;
79648  int iRollback;
79649 
79650  desiredAutoCommit = pOp->p1;
79651  iRollback = pOp->p2;
79652  assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
79653  assert( desiredAutoCommit==1 || iRollback==0 );
79654  assert( db->nVdbeActive>0 ); /* At least this one VM is active */
79655  assert( p->bIsReader );
79656 
79657  if( desiredAutoCommit!=db->autoCommit ){
79658  if( iRollback ){
79659  assert( desiredAutoCommit==1 );
79661  db->autoCommit = 1;
79662  }else if( desiredAutoCommit && db->nVdbeWrite>0 ){
79663  /* If this instruction implements a COMMIT and other VMs are writing
79664  ** return an error indicating that the other VMs must complete first.
79665  */
79666  sqlite3VdbeError(p, "cannot commit transaction - "
79667  "SQL statements in progress");
79668  rc = SQLITE_BUSY;
79669  goto abort_due_to_error;
79670  }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
79671  goto vdbe_return;
79672  }else{
79673  db->autoCommit = (u8)desiredAutoCommit;
79674  }
79675  if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
79676  p->pc = (int)(pOp - aOp);
79677  db->autoCommit = (u8)(1-desiredAutoCommit);
79678  p->rc = rc = SQLITE_BUSY;
79679  goto vdbe_return;
79680  }
79681  assert( db->nStatement==0 );
79683  if( p->rc==SQLITE_OK ){
79684  rc = SQLITE_DONE;
79685  }else{
79686  rc = SQLITE_ERROR;
79687  }
79688  goto vdbe_return;
79689  }else{
79690  sqlite3VdbeError(p,
79691  (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
79692  (iRollback)?"cannot rollback - no transaction is active":
79693  "cannot commit - no transaction is active"));
79694 
79695  rc = SQLITE_ERROR;
79696  goto abort_due_to_error;
79697  }
79698  break;
79699 }
79700 
79701 /* Opcode: Transaction P1 P2 P3 P4 P5
79702 **
79703 ** Begin a transaction on database P1 if a transaction is not already
79704 ** active.
79705 ** If P2 is non-zero, then a write-transaction is started, or if a
79706 ** read-transaction is already active, it is upgraded to a write-transaction.
79707 ** If P2 is zero, then a read-transaction is started.
79708 **
79709 ** P1 is the index of the database file on which the transaction is
79710 ** started. Index 0 is the main database file and index 1 is the
79711 ** file used for temporary tables. Indices of 2 or more are used for
79712 ** attached databases.
79713 **
79714 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
79715 ** true (this flag is set if the Vdbe may modify more than one row and may
79716 ** throw an ABORT exception), a statement transaction may also be opened.
79717 ** More specifically, a statement transaction is opened iff the database
79718 ** connection is currently not in autocommit mode, or if there are other
79719 ** active statements. A statement transaction allows the changes made by this
79720 ** VDBE to be rolled back after an error without having to roll back the
79721 ** entire transaction. If no error is encountered, the statement transaction
79722 ** will automatically commit when the VDBE halts.
79723 **
79724 ** If P5!=0 then this opcode also checks the schema cookie against P3
79725 ** and the schema generation counter against P4.
79726 ** The cookie changes its value whenever the database schema changes.
79727 ** This operation is used to detect when that the cookie has changed
79728 ** and that the current process needs to reread the schema. If the schema
79729 ** cookie in P3 differs from the schema cookie in the database header or
79730 ** if the schema generation counter in P4 differs from the current
79731 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
79732 ** halts. The sqlite3_step() wrapper function might then reprepare the
79733 ** statement and rerun it from the beginning.
79734 */
79735 case OP_Transaction: {
79736  Btree *pBt;
79737  int iMeta;
79738  int iGen;
79739 
79740  assert( p->bIsReader );
79741  assert( p->readOnly==0 || pOp->p2==0 );
79742  assert( pOp->p1>=0 && pOp->p1<db->nDb );
79743  assert( DbMaskTest(p->btreeMask, pOp->p1) );
79744  if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
79745  rc = SQLITE_READONLY;
79746  goto abort_due_to_error;
79747  }
79748  pBt = db->aDb[pOp->p1].pBt;
79749 
79750  if( pBt ){
79751  rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
79754  if( (rc&0xff)==SQLITE_BUSY ){
79755  p->pc = (int)(pOp - aOp);
79756  p->rc = rc;
79757  goto vdbe_return;
79758  }
79759  if( rc!=SQLITE_OK ){
79760  goto abort_due_to_error;
79761  }
79762 
79763  if( pOp->p2 && p->usesStmtJournal
79764  && (db->autoCommit==0 || db->nVdbeRead>1)
79765  ){
79766  assert( sqlite3BtreeIsInTrans(pBt) );
79767  if( p->iStatement==0 ){
79768  assert( db->nStatement>=0 && db->nSavepoint>=0 );
79769  db->nStatement++;
79770  p->iStatement = db->nSavepoint + db->nStatement;
79771  }
79772 
79774  if( rc==SQLITE_OK ){
79775  rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
79776  }
79777 
79778  /* Store the current value of the database handles deferred constraint
79779  ** counter. If the statement transaction needs to be rolled back,
79780  ** the value of this counter needs to be restored too. */
79781  p->nStmtDefCons = db->nDeferredCons;
79783  }
79784 
79785  /* Gather the schema version number for checking:
79786  ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
79787  ** each time a query is executed to ensure that the internal cache of the
79788  ** schema used when compiling the SQL query matches the schema of the
79789  ** database against which the compiled query is actually executed.
79790  */
79791  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
79792  iGen = db->aDb[pOp->p1].pSchema->iGeneration;
79793  }else{
79794  iGen = iMeta = 0;
79795  }
79796  assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
79797  if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
79798  sqlite3DbFree(db, p->zErrMsg);
79799  p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
79800  /* If the schema-cookie from the database file matches the cookie
79801  ** stored with the in-memory representation of the schema, do
79802  ** not reload the schema from the database file.
79803  **
79804  ** If virtual-tables are in use, this is not just an optimization.
79805  ** Often, v-tables store their data in other SQLite tables, which
79806  ** are queried from within xNext() and other v-table methods using
79807  ** prepared queries. If such a query is out-of-date, we do not want to
79808  ** discard the database schema, as the user code implementing the
79809  ** v-table would have to be ready for the sqlite3_vtab structure itself
79810  ** to be invalidated whenever sqlite3_step() is called from within
79811  ** a v-table method.
79812  */
79813  if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
79814  sqlite3ResetOneSchema(db, pOp->p1);
79815  }
79816  p->expired = 1;
79817  rc = SQLITE_SCHEMA;
79818  }
79819  if( rc ) goto abort_due_to_error;
79820  break;
79821 }
79822 
79823 /* Opcode: ReadCookie P1 P2 P3 * *
79824 **
79825 ** Read cookie number P3 from database P1 and write it into register P2.
79826 ** P3==1 is the schema version. P3==2 is the database format.
79827 ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
79828 ** the main database file and P1==1 is the database file used to store
79829 ** temporary tables.
79830 **
79831 ** There must be a read-lock on the database (either a transaction
79832 ** must be started or there must be an open cursor) before
79833 ** executing this instruction.
79834 */
79835 case OP_ReadCookie: { /* out2 */
79836  int iMeta;
79837  int iDb;
79838  int iCookie;
79839 
79840  assert( p->bIsReader );
79841  iDb = pOp->p1;
79842  iCookie = pOp->p3;
79843  assert( pOp->p3<SQLITE_N_BTREE_META );
79844  assert( iDb>=0 && iDb<db->nDb );
79845  assert( db->aDb[iDb].pBt!=0 );
79846  assert( DbMaskTest(p->btreeMask, iDb) );
79847 
79848  sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
79849  pOut = out2Prerelease(p, pOp);
79850  pOut->u.i = iMeta;
79851  break;
79852 }
79853 
79854 /* Opcode: SetCookie P1 P2 P3 * *
79855 **
79856 ** Write the integer value P3 into cookie number P2 of database P1.
79857 ** P2==1 is the schema version. P2==2 is the database format.
79858 ** P2==3 is the recommended pager cache
79859 ** size, and so forth. P1==0 is the main database file and P1==1 is the
79860 ** database file used to store temporary tables.
79861 **
79862 ** A transaction must be started before executing this opcode.
79863 */
79864 case OP_SetCookie: {
79865  Db *pDb;
79866  assert( pOp->p2<SQLITE_N_BTREE_META );
79867  assert( pOp->p1>=0 && pOp->p1<db->nDb );
79868  assert( DbMaskTest(p->btreeMask, pOp->p1) );
79869  assert( p->readOnly==0 );
79870  pDb = &db->aDb[pOp->p1];
79871  assert( pDb->pBt!=0 );
79872  assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
79873  /* See note about index shifting on OP_ReadCookie */
79874  rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, pOp->p3);
79875  if( pOp->p2==BTREE_SCHEMA_VERSION ){
79876  /* When the schema cookie changes, record the new cookie internally */
79877  pDb->pSchema->schema_cookie = pOp->p3;
79878  db->flags |= SQLITE_InternChanges;
79879  }else if( pOp->p2==BTREE_FILE_FORMAT ){
79880  /* Record changes in the file format */
79881  pDb->pSchema->file_format = pOp->p3;
79882  }
79883  if( pOp->p1==1 ){
79884  /* Invalidate all prepared statements whenever the TEMP database
79885  ** schema is changed. Ticket #1644 */
79887  p->expired = 0;
79888  }
79889  if( rc ) goto abort_due_to_error;
79890  break;
79891 }
79892 
79893 /* Opcode: OpenRead P1 P2 P3 P4 P5
79894 ** Synopsis: root=P2 iDb=P3
79895 **
79896 ** Open a read-only cursor for the database table whose root page is
79897 ** P2 in a database file. The database file is determined by P3.
79898 ** P3==0 means the main database, P3==1 means the database used for
79899 ** temporary tables, and P3>1 means used the corresponding attached
79900 ** database. Give the new cursor an identifier of P1. The P1
79901 ** values need not be contiguous but all P1 values should be small integers.
79902 ** It is an error for P1 to be negative.
79903 **
79904 ** If P5!=0 then use the content of register P2 as the root page, not
79905 ** the value of P2 itself.
79906 **
79907 ** There will be a read lock on the database whenever there is an
79908 ** open cursor. If the database was unlocked prior to this instruction
79909 ** then a read lock is acquired as part of this instruction. A read
79910 ** lock allows other processes to read the database but prohibits
79911 ** any other process from modifying the database. The read lock is
79912 ** released when all cursors are closed. If this instruction attempts
79913 ** to get a read lock but fails, the script terminates with an
79914 ** SQLITE_BUSY error code.
79915 **
79916 ** The P4 value may be either an integer (P4_INT32) or a pointer to
79917 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
79918 ** structure, then said structure defines the content and collating
79919 ** sequence of the index being opened. Otherwise, if P4 is an integer
79920 ** value, it is set to the number of columns in the table.
79921 **
79922 ** See also: OpenWrite, ReopenIdx
79923 */
79924 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
79925 ** Synopsis: root=P2 iDb=P3
79926 **
79927 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
79928 ** checks to see if the cursor on P1 is already open with a root page
79929 ** number of P2 and if it is this opcode becomes a no-op. In other words,
79930 ** if the cursor is already open, do not reopen it.
79931 **
79932 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
79933 ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
79934 ** every other ReopenIdx or OpenRead for the same cursor number.
79935 **
79936 ** See the OpenRead opcode documentation for additional information.
79937 */
79938 /* Opcode: OpenWrite P1 P2 P3 P4 P5
79939 ** Synopsis: root=P2 iDb=P3
79940 **
79941 ** Open a read/write cursor named P1 on the table or index whose root
79942 ** page is P2. Or if P5!=0 use the content of register P2 to find the
79943 ** root page.
79944 **
79945 ** The P4 value may be either an integer (P4_INT32) or a pointer to
79946 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
79947 ** structure, then said structure defines the content and collating
79948 ** sequence of the index being opened. Otherwise, if P4 is an integer
79949 ** value, it is set to the number of columns in the table, or to the
79950 ** largest index of any column of the table that is actually used.
79951 **
79952 ** This instruction works just like OpenRead except that it opens the cursor
79953 ** in read/write mode. For a given table, there can be one or more read-only
79954 ** cursors or a single read/write cursor but not both.
79955 **
79956 ** See also OpenRead.
79957 */
79958 case OP_ReopenIdx: {
79959  int nField;
79960  KeyInfo *pKeyInfo;
79961  int p2;
79962  int iDb;
79963  int wrFlag;
79964  Btree *pX;
79965  VdbeCursor *pCur;
79966  Db *pDb;
79967 
79968  assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
79969  assert( pOp->p4type==P4_KEYINFO );
79970  pCur = p->apCsr[pOp->p1];
79971  if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
79972  assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
79973  goto open_cursor_set_hints;
79974  }
79975  /* If the cursor is not currently open or is open on a different
79976  ** index, then fall through into OP_OpenRead to force a reopen */
79977 case OP_OpenRead:
79978 case OP_OpenWrite:
79979 
79980  assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
79981  assert( p->bIsReader );
79982  assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
79983  || p->readOnly==0 );
79984 
79985  if( p->expired ){
79986  rc = SQLITE_ABORT_ROLLBACK;
79987  goto abort_due_to_error;
79988  }
79989 
79990  nField = 0;
79991  pKeyInfo = 0;
79992  p2 = pOp->p2;
79993  iDb = pOp->p3;
79994  assert( iDb>=0 && iDb<db->nDb );
79995  assert( DbMaskTest(p->btreeMask, iDb) );
79996  pDb = &db->aDb[iDb];
79997  pX = pDb->pBt;
79998  assert( pX!=0 );
79999  if( pOp->opcode==OP_OpenWrite ){
80001  wrFlag = BTREE_WRCSR | (pOp->p5 & OPFLAG_FORDELETE);
80002  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
80003  if( pDb->pSchema->file_format < p->minWriteFileFormat ){
80005  }
80006  }else{
80007  wrFlag = 0;
80008  }
80009  if( pOp->p5 & OPFLAG_P2ISREG ){
80010  assert( p2>0 );
80011  assert( p2<=(p->nMem+1 - p->nCursor) );
80012  pIn2 = &aMem[p2];
80013  assert( memIsValid(pIn2) );
80014  assert( (pIn2->flags & MEM_Int)!=0 );
80016  p2 = (int)pIn2->u.i;
80017  /* The p2 value always comes from a prior OP_CreateTable opcode and
80018  ** that opcode will always set the p2 value to 2 or more or else fail.
80019  ** If there were a failure, the prepared statement would have halted
80020  ** before reaching this instruction. */
80021  assert( p2>=2 );
80022  }
80023  if( pOp->p4type==P4_KEYINFO ){
80024  pKeyInfo = pOp->p4.pKeyInfo;
80025  assert( pKeyInfo->enc==ENC(db) );
80026  assert( pKeyInfo->db==db );
80027  nField = pKeyInfo->nField+pKeyInfo->nXField;
80028  }else if( pOp->p4type==P4_INT32 ){
80029  nField = pOp->p4.i;
80030  }
80031  assert( pOp->p1>=0 );
80032  assert( nField>=0 );
80033  testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
80034  pCur = allocateCursor(p, pOp->p1, nField, iDb, CURTYPE_BTREE);
80035  if( pCur==0 ) goto no_mem;
80036  pCur->nullRow = 1;
80037  pCur->isOrdered = 1;
80038  pCur->pgnoRoot = p2;
80039 #ifdef SQLITE_DEBUG
80040  pCur->wrFlag = wrFlag;
80041 #endif
80042  rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->uc.pCursor);
80043  pCur->pKeyInfo = pKeyInfo;
80044  /* Set the VdbeCursor.isTable variable. Previous versions of
80045  ** SQLite used to check if the root-page flags were sane at this point
80046  ** and report database corruption if they were not, but this check has
80047  ** since moved into the btree layer. */
80048  pCur->isTable = pOp->p4type!=P4_KEYINFO;
80049 
80050 open_cursor_set_hints:
80053  testcase( pOp->p5 & OPFLAG_BULKCSR );
80054 #ifdef SQLITE_ENABLE_CURSOR_HINTS
80055  testcase( pOp->p2 & OPFLAG_SEEKEQ );
80056 #endif
80058  (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
80059  if( rc ) goto abort_due_to_error;
80060  break;
80061 }
80062 
80063 /* Opcode: OpenEphemeral P1 P2 * P4 P5
80064 ** Synopsis: nColumn=P2
80065 **
80066 ** Open a new cursor P1 to a transient table.
80067 ** The cursor is always opened read/write even if
80068 ** the main database is read-only. The ephemeral
80069 ** table is deleted automatically when the cursor is closed.
80070 **
80071 ** P2 is the number of columns in the ephemeral table.
80072 ** The cursor points to a BTree table if P4==0 and to a BTree index
80073 ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
80074 ** that defines the format of keys in the index.
80075 **
80076 ** The P5 parameter can be a mask of the BTREE_* flags defined
80077 ** in btree.h. These flags control aspects of the operation of
80078 ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
80079 ** added automatically.
80080 */
80081 /* Opcode: OpenAutoindex P1 P2 * P4 *
80082 ** Synopsis: nColumn=P2
80083 **
80084 ** This opcode works the same as OP_OpenEphemeral. It has a
80085 ** different name to distinguish its use. Tables created using
80086 ** by this opcode will be used for automatically created transient
80087 ** indices in joins.
80088 */
80089 case OP_OpenAutoindex:
80090 case OP_OpenEphemeral: {
80091  VdbeCursor *pCx;
80092  KeyInfo *pKeyInfo;
80093 
80094  static const int vfsFlags =
80100  assert( pOp->p1>=0 );
80101  assert( pOp->p2>=0 );
80102  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_BTREE);
80103  if( pCx==0 ) goto no_mem;
80104  pCx->nullRow = 1;
80105  pCx->isEphemeral = 1;
80106  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
80107  BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
80108  if( rc==SQLITE_OK ){
80109  rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
80110  }
80111  if( rc==SQLITE_OK ){
80112  /* If a transient index is required, create it by calling
80113  ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
80114  ** opening it. If a transient table is required, just use the
80115  ** automatically created table with root-page 1 (an BLOB_INTKEY table).
80116  */
80117  if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
80118  int pgno;
80119  assert( pOp->p4type==P4_KEYINFO );
80120  rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
80121  if( rc==SQLITE_OK ){
80122  assert( pgno==MASTER_ROOT+1 );
80123  assert( pKeyInfo->db==db );
80124  assert( pKeyInfo->enc==ENC(db) );
80125  pCx->pKeyInfo = pKeyInfo;
80126  rc = sqlite3BtreeCursor(pCx->pBt, pgno, BTREE_WRCSR,
80127  pKeyInfo, pCx->uc.pCursor);
80128  }
80129  pCx->isTable = 0;
80130  }else{
80132  0, pCx->uc.pCursor);
80133  pCx->isTable = 1;
80134  }
80135  }
80136  if( rc ) goto abort_due_to_error;
80137  pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
80138  break;
80139 }
80140 
80141 /* Opcode: SorterOpen P1 P2 P3 P4 *
80142 **
80143 ** This opcode works like OP_OpenEphemeral except that it opens
80144 ** a transient index that is specifically designed to sort large
80145 ** tables using an external merge-sort algorithm.
80146 **
80147 ** If argument P3 is non-zero, then it indicates that the sorter may
80148 ** assume that a stable sort considering the first P3 fields of each
80149 ** key is sufficient to produce the required results.
80150 */
80151 case OP_SorterOpen: {
80152  VdbeCursor *pCx;
80153 
80154  assert( pOp->p1>=0 );
80155  assert( pOp->p2>=0 );
80156  pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, CURTYPE_SORTER);
80157  if( pCx==0 ) goto no_mem;
80158  pCx->pKeyInfo = pOp->p4.pKeyInfo;
80159  assert( pCx->pKeyInfo->db==db );
80160  assert( pCx->pKeyInfo->enc==ENC(db) );
80161  rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
80162  if( rc ) goto abort_due_to_error;
80163  break;
80164 }
80165 
80166 /* Opcode: SequenceTest P1 P2 * * *
80167 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
80168 **
80169 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
80170 ** to P2. Regardless of whether or not the jump is taken, increment the
80171 ** the sequence value.
80172 */
80173 case OP_SequenceTest: {
80174  VdbeCursor *pC;
80175  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80176  pC = p->apCsr[pOp->p1];
80177  assert( isSorter(pC) );
80178  if( (pC->seqCount++)==0 ){
80179  goto jump_to_p2;
80180  }
80181  break;
80182 }
80183 
80184 /* Opcode: OpenPseudo P1 P2 P3 * *
80185 ** Synopsis: P3 columns in r[P2]
80186 **
80187 ** Open a new cursor that points to a fake table that contains a single
80188 ** row of data. The content of that one row is the content of memory
80189 ** register P2. In other words, cursor P1 becomes an alias for the
80190 ** MEM_Blob content contained in register P2.
80191 **
80192 ** A pseudo-table created by this opcode is used to hold a single
80193 ** row output from the sorter so that the row can be decomposed into
80194 ** individual columns using the OP_Column opcode. The OP_Column opcode
80195 ** is the only cursor opcode that works with a pseudo-table.
80196 **
80197 ** P3 is the number of fields in the records that will be stored by
80198 ** the pseudo-table.
80199 */
80200 case OP_OpenPseudo: {
80201  VdbeCursor *pCx;
80202 
80203  assert( pOp->p1>=0 );
80204  assert( pOp->p3>=0 );
80205  pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, CURTYPE_PSEUDO);
80206  if( pCx==0 ) goto no_mem;
80207  pCx->nullRow = 1;
80208  pCx->uc.pseudoTableReg = pOp->p2;
80209  pCx->isTable = 1;
80210  assert( pOp->p5==0 );
80211  break;
80212 }
80213 
80214 /* Opcode: Close P1 * * * *
80215 **
80216 ** Close a cursor previously opened as P1. If P1 is not
80217 ** currently open, this instruction is a no-op.
80218 */
80219 case OP_Close: {
80220  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80221  sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
80222  p->apCsr[pOp->p1] = 0;
80223  break;
80224 }
80225 
80226 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
80227 /* Opcode: ColumnsUsed P1 * * P4 *
80228 **
80229 ** This opcode (which only exists if SQLite was compiled with
80230 ** SQLITE_ENABLE_COLUMN_USED_MASK) identifies which columns of the
80231 ** table or index for cursor P1 are used. P4 is a 64-bit integer
80232 ** (P4_INT64) in which the first 63 bits are one for each of the
80233 ** first 63 columns of the table or index that are actually used
80234 ** by the cursor. The high-order bit is set if any column after
80235 ** the 64th is used.
80236 */
80237 case OP_ColumnsUsed: {
80238  VdbeCursor *pC;
80239  pC = p->apCsr[pOp->p1];
80240  assert( pC->eCurType==CURTYPE_BTREE );
80241  pC->maskUsed = *(u64*)pOp->p4.pI64;
80242  break;
80243 }
80244 #endif
80245 
80246 /* Opcode: SeekGE P1 P2 P3 P4 *
80247 ** Synopsis: key=r[P3@P4]
80248 **
80249 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80250 ** use the value in register P3 as the key. If cursor P1 refers
80251 ** to an SQL index, then P3 is the first in an array of P4 registers
80252 ** that are used as an unpacked index key.
80253 **
80254 ** Reposition cursor P1 so that it points to the smallest entry that
80255 ** is greater than or equal to the key value. If there are no records
80256 ** greater than or equal to the key and P2 is not zero, then jump to P2.
80257 **
80258 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80259 ** opcode will always land on a record that equally equals the key, or
80260 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
80261 ** opcode must be followed by an IdxLE opcode with the same arguments.
80262 ** The IdxLE opcode will be skipped if this opcode succeeds, but the
80263 ** IdxLE opcode will be used on subsequent loop iterations.
80264 **
80265 ** This opcode leaves the cursor configured to move in forward order,
80266 ** from the beginning toward the end. In other words, the cursor is
80267 ** configured to use Next, not Prev.
80268 **
80269 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
80270 */
80271 /* Opcode: SeekGT P1 P2 P3 P4 *
80272 ** Synopsis: key=r[P3@P4]
80273 **
80274 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80275 ** use the value in register P3 as a key. If cursor P1 refers
80276 ** to an SQL index, then P3 is the first in an array of P4 registers
80277 ** that are used as an unpacked index key.
80278 **
80279 ** Reposition cursor P1 so that it points to the smallest entry that
80280 ** is greater than the key value. If there are no records greater than
80281 ** the key and P2 is not zero, then jump to P2.
80282 **
80283 ** This opcode leaves the cursor configured to move in forward order,
80284 ** from the beginning toward the end. In other words, the cursor is
80285 ** configured to use Next, not Prev.
80286 **
80287 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
80288 */
80289 /* Opcode: SeekLT P1 P2 P3 P4 *
80290 ** Synopsis: key=r[P3@P4]
80291 **
80292 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80293 ** use the value in register P3 as a key. If cursor P1 refers
80294 ** to an SQL index, then P3 is the first in an array of P4 registers
80295 ** that are used as an unpacked index key.
80296 **
80297 ** Reposition cursor P1 so that it points to the largest entry that
80298 ** is less than the key value. If there are no records less than
80299 ** the key and P2 is not zero, then jump to P2.
80300 **
80301 ** This opcode leaves the cursor configured to move in reverse order,
80302 ** from the end toward the beginning. In other words, the cursor is
80303 ** configured to use Prev, not Next.
80304 **
80305 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
80306 */
80307 /* Opcode: SeekLE P1 P2 P3 P4 *
80308 ** Synopsis: key=r[P3@P4]
80309 **
80310 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
80311 ** use the value in register P3 as a key. If cursor P1 refers
80312 ** to an SQL index, then P3 is the first in an array of P4 registers
80313 ** that are used as an unpacked index key.
80314 **
80315 ** Reposition cursor P1 so that it points to the largest entry that
80316 ** is less than or equal to the key value. If there are no records
80317 ** less than or equal to the key and P2 is not zero, then jump to P2.
80318 **
80319 ** This opcode leaves the cursor configured to move in reverse order,
80320 ** from the end toward the beginning. In other words, the cursor is
80321 ** configured to use Prev, not Next.
80322 **
80323 ** If the cursor P1 was opened using the OPFLAG_SEEKEQ flag, then this
80324 ** opcode will always land on a record that equally equals the key, or
80325 ** else jump immediately to P2. When the cursor is OPFLAG_SEEKEQ, this
80326 ** opcode must be followed by an IdxGE opcode with the same arguments.
80327 ** The IdxGE opcode will be skipped if this opcode succeeds, but the
80328 ** IdxGE opcode will be used on subsequent loop iterations.
80329 **
80330 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
80331 */
80332 case OP_SeekLT: /* jump, in3 */
80333 case OP_SeekLE: /* jump, in3 */
80334 case OP_SeekGE: /* jump, in3 */
80335 case OP_SeekGT: { /* jump, in3 */
80336  int res; /* Comparison result */
80337  int oc; /* Opcode */
80338  VdbeCursor *pC; /* The cursor to seek */
80339  UnpackedRecord r; /* The key to seek for */
80340  int nField; /* Number of columns or fields in the key */
80341  i64 iKey; /* The rowid we are to seek to */
80342  int eqOnly; /* Only interested in == results */
80343 
80344  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80345  assert( pOp->p2!=0 );
80346  pC = p->apCsr[pOp->p1];
80347  assert( pC!=0 );
80348  assert( pC->eCurType==CURTYPE_BTREE );
80349  assert( OP_SeekLE == OP_SeekLT+1 );
80350  assert( OP_SeekGE == OP_SeekLT+2 );
80351  assert( OP_SeekGT == OP_SeekLT+3 );
80352  assert( pC->isOrdered );
80353  assert( pC->uc.pCursor!=0 );
80354  oc = pOp->opcode;
80355  eqOnly = 0;
80356  pC->nullRow = 0;
80357 #ifdef SQLITE_DEBUG
80358  pC->seekOp = pOp->opcode;
80359 #endif
80360 
80361  if( pC->isTable ){
80362  /* The BTREE_SEEK_EQ flag is only set on index cursors */
80364 
80365  /* The input value in P3 might be of any type: integer, real, string,
80366  ** blob, or NULL. But it needs to be an integer before we can do
80367  ** the seek, so convert it. */
80368  pIn3 = &aMem[pOp->p3];
80369  if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
80370  applyNumericAffinity(pIn3, 0);
80371  }
80372  iKey = sqlite3VdbeIntValue(pIn3);
80373 
80374  /* If the P3 value could not be converted into an integer without
80375  ** loss of information, then special processing is required... */
80376  if( (pIn3->flags & MEM_Int)==0 ){
80377  if( (pIn3->flags & MEM_Real)==0 ){
80378  /* If the P3 value cannot be converted into any kind of a number,
80379  ** then the seek is not possible, so jump to P2 */
80380  VdbeBranchTaken(1,2); goto jump_to_p2;
80381  break;
80382  }
80383 
80384  /* If the approximation iKey is larger than the actual real search
80385  ** term, substitute >= for > and < for <=. e.g. if the search term
80386  ** is 4.9 and the integer approximation 5:
80387  **
80388  ** (x > 4.9) -> (x >= 5)
80389  ** (x <= 4.9) -> (x < 5)
80390  */
80391  if( pIn3->u.r<(double)iKey ){
80392  assert( OP_SeekGE==(OP_SeekGT-1) );
80393  assert( OP_SeekLT==(OP_SeekLE-1) );
80394  assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
80395  if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
80396  }
80397 
80398  /* If the approximation iKey is smaller than the actual real search
80399  ** term, substitute <= for < and > for >=. */
80400  else if( pIn3->u.r>(double)iKey ){
80401  assert( OP_SeekLE==(OP_SeekLT+1) );
80402  assert( OP_SeekGT==(OP_SeekGE+1) );
80403  assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
80404  if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
80405  }
80406  }
80407  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)iKey, 0, &res);
80408  pC->movetoTarget = iKey; /* Used by OP_Delete */
80409  if( rc!=SQLITE_OK ){
80410  goto abort_due_to_error;
80411  }
80412  }else{
80413  /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
80414  ** OP_SeekLE opcodes are allowed, and these must be immediately followed
80415  ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
80416  */
80418  eqOnly = 1;
80419  assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
80420  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80421  assert( pOp[1].p1==pOp[0].p1 );
80422  assert( pOp[1].p2==pOp[0].p2 );
80423  assert( pOp[1].p3==pOp[0].p3 );
80424  assert( pOp[1].p4.i==pOp[0].p4.i );
80425  }
80426 
80427  nField = pOp->p4.i;
80428  assert( pOp->p4type==P4_INT32 );
80429  assert( nField>0 );
80430  r.pKeyInfo = pC->pKeyInfo;
80431  r.nField = (u16)nField;
80432 
80433  /* The next line of code computes as follows, only faster:
80434  ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
80435  ** r.default_rc = -1;
80436  ** }else{
80437  ** r.default_rc = +1;
80438  ** }
80439  */
80440  r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
80441  assert( oc!=OP_SeekGT || r.default_rc==-1 );
80442  assert( oc!=OP_SeekLE || r.default_rc==-1 );
80443  assert( oc!=OP_SeekGE || r.default_rc==+1 );
80444  assert( oc!=OP_SeekLT || r.default_rc==+1 );
80445 
80446  r.aMem = &aMem[pOp->p3];
80447 #ifdef SQLITE_DEBUG
80448  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
80449 #endif
80450  ExpandBlob(r.aMem);
80451  r.eqSeen = 0;
80452  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, &r, 0, 0, &res);
80453  if( rc!=SQLITE_OK ){
80454  goto abort_due_to_error;
80455  }
80456  if( eqOnly && r.eqSeen==0 ){
80457  assert( res!=0 );
80458  goto seek_not_found;
80459  }
80460  }
80461  pC->deferredMoveto = 0;
80462  pC->cacheStatus = CACHE_STALE;
80463 #ifdef SQLITE_TEST
80464  sqlite3_search_count++;
80465 #endif
80466  if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
80467  if( res<0 || (res==0 && oc==OP_SeekGT) ){
80468  res = 0;
80469  rc = sqlite3BtreeNext(pC->uc.pCursor, &res);
80470  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80471  }else{
80472  res = 0;
80473  }
80474  }else{
80475  assert( oc==OP_SeekLT || oc==OP_SeekLE );
80476  if( res>0 || (res==0 && oc==OP_SeekLT) ){
80477  res = 0;
80478  rc = sqlite3BtreePrevious(pC->uc.pCursor, &res);
80479  if( rc!=SQLITE_OK ) goto abort_due_to_error;
80480  }else{
80481  /* res might be negative because the table is empty. Check to
80482  ** see if this is the case.
80483  */
80484  res = sqlite3BtreeEof(pC->uc.pCursor);
80485  }
80486  }
80487 seek_not_found:
80488  assert( pOp->p2>0 );
80489  VdbeBranchTaken(res!=0,2);
80490  if( res ){
80491  goto jump_to_p2;
80492  }else if( eqOnly ){
80493  assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
80494  pOp++; /* Skip the OP_IdxLt or OP_IdxGT that follows */
80495  }
80496  break;
80497 }
80498 
80499 
80500 /* Opcode: Found P1 P2 P3 P4 *
80501 ** Synopsis: key=r[P3@P4]
80502 **
80503 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
80504 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
80505 ** record.
80506 **
80507 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
80508 ** is a prefix of any entry in P1 then a jump is made to P2 and
80509 ** P1 is left pointing at the matching entry.
80510 **
80511 ** This operation leaves the cursor in a state where it can be
80512 ** advanced in the forward direction. The Next instruction will work,
80513 ** but not the Prev instruction.
80514 **
80515 ** See also: NotFound, NoConflict, NotExists. SeekGe
80516 */
80517 /* Opcode: NotFound P1 P2 P3 P4 *
80518 ** Synopsis: key=r[P3@P4]
80519 **
80520 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
80521 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
80522 ** record.
80523 **
80524 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
80525 ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
80526 ** does contain an entry whose prefix matches the P3/P4 record then control
80527 ** falls through to the next instruction and P1 is left pointing at the
80528 ** matching entry.
80529 **
80530 ** This operation leaves the cursor in a state where it cannot be
80531 ** advanced in either direction. In other words, the Next and Prev
80532 ** opcodes do not work after this operation.
80533 **
80534 ** See also: Found, NotExists, NoConflict
80535 */
80536 /* Opcode: NoConflict P1 P2 P3 P4 *
80537 ** Synopsis: key=r[P3@P4]
80538 **
80539 ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
80540 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
80541 ** record.
80542 **
80543 ** Cursor P1 is on an index btree. If the record identified by P3 and P4
80544 ** contains any NULL value, jump immediately to P2. If all terms of the
80545 ** record are not-NULL then a check is done to determine if any row in the
80546 ** P1 index btree has a matching key prefix. If there are no matches, jump
80547 ** immediately to P2. If there is a match, fall through and leave the P1
80548 ** cursor pointing to the matching row.
80549 **
80550 ** This opcode is similar to OP_NotFound with the exceptions that the
80551 ** branch is always taken if any part of the search key input is NULL.
80552 **
80553 ** This operation leaves the cursor in a state where it cannot be
80554 ** advanced in either direction. In other words, the Next and Prev
80555 ** opcodes do not work after this operation.
80556 **
80557 ** See also: NotFound, Found, NotExists
80558 */
80559 case OP_NoConflict: /* jump, in3 */
80560 case OP_NotFound: /* jump, in3 */
80561 case OP_Found: { /* jump, in3 */
80562  int alreadyExists;
80563  int takeJump;
80564  int ii;
80565  VdbeCursor *pC;
80566  int res;
80567  char *pFree;
80568  UnpackedRecord *pIdxKey;
80569  UnpackedRecord r;
80570  char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
80571 
80572 #ifdef SQLITE_TEST
80573  if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
80574 #endif
80575 
80576  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80577  assert( pOp->p4type==P4_INT32 );
80578  pC = p->apCsr[pOp->p1];
80579  assert( pC!=0 );
80580 #ifdef SQLITE_DEBUG
80581  pC->seekOp = pOp->opcode;
80582 #endif
80583  pIn3 = &aMem[pOp->p3];
80584  assert( pC->eCurType==CURTYPE_BTREE );
80585  assert( pC->uc.pCursor!=0 );
80586  assert( pC->isTable==0 );
80587  pFree = 0;
80588  if( pOp->p4.i>0 ){
80589  r.pKeyInfo = pC->pKeyInfo;
80590  r.nField = (u16)pOp->p4.i;
80591  r.aMem = pIn3;
80592  for(ii=0; ii<r.nField; ii++){
80593  assert( memIsValid(&r.aMem[ii]) );
80594  ExpandBlob(&r.aMem[ii]);
80595 #ifdef SQLITE_DEBUG
80596  if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
80597 #endif
80598  }
80599  pIdxKey = &r;
80600  }else{
80602  pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
80603  );
80604  if( pIdxKey==0 ) goto no_mem;
80605  assert( pIn3->flags & MEM_Blob );
80606  ExpandBlob(pIn3);
80607  sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
80608  }
80609  pIdxKey->default_rc = 0;
80610  takeJump = 0;
80611  if( pOp->opcode==OP_NoConflict ){
80612  /* For the OP_NoConflict opcode, take the jump if any of the
80613  ** input fields are NULL, since any key with a NULL will not
80614  ** conflict */
80615  for(ii=0; ii<pIdxKey->nField; ii++){
80616  if( pIdxKey->aMem[ii].flags & MEM_Null ){
80617  takeJump = 1;
80618  break;
80619  }
80620  }
80621  }
80622  rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, pIdxKey, 0, 0, &res);
80623  sqlite3DbFree(db, pFree);
80624  if( rc!=SQLITE_OK ){
80625  goto abort_due_to_error;
80626  }
80627  pC->seekResult = res;
80628  alreadyExists = (res==0);
80629  pC->nullRow = 1-alreadyExists;
80630  pC->deferredMoveto = 0;
80631  pC->cacheStatus = CACHE_STALE;
80632  if( pOp->opcode==OP_Found ){
80633  VdbeBranchTaken(alreadyExists!=0,2);
80634  if( alreadyExists ) goto jump_to_p2;
80635  }else{
80636  VdbeBranchTaken(takeJump||alreadyExists==0,2);
80637  if( takeJump || !alreadyExists ) goto jump_to_p2;
80638  }
80639  break;
80640 }
80641 
80642 /* Opcode: NotExists P1 P2 P3 * *
80643 ** Synopsis: intkey=r[P3]
80644 **
80645 ** P1 is the index of a cursor open on an SQL table btree (with integer
80646 ** keys). P3 is an integer rowid. If P1 does not contain a record with
80647 ** rowid P3 then jump immediately to P2. Or, if P2 is 0, raise an
80648 ** SQLITE_CORRUPT error. If P1 does contain a record with rowid P3 then
80649 ** leave the cursor pointing at that record and fall through to the next
80650 ** instruction.
80651 **
80652 ** The OP_NotFound opcode performs the same operation on index btrees
80653 ** (with arbitrary multi-value keys).
80654 **
80655 ** This opcode leaves the cursor in a state where it cannot be advanced
80656 ** in either direction. In other words, the Next and Prev opcodes will
80657 ** not work following this opcode.
80658 **
80659 ** See also: Found, NotFound, NoConflict
80660 */
80661 case OP_NotExists: { /* jump, in3 */
80662  VdbeCursor *pC;
80663  BtCursor *pCrsr;
80664  int res;
80665  u64 iKey;
80666 
80667  pIn3 = &aMem[pOp->p3];
80668  assert( pIn3->flags & MEM_Int );
80669  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80670  pC = p->apCsr[pOp->p1];
80671  assert( pC!=0 );
80672 #ifdef SQLITE_DEBUG
80673  pC->seekOp = 0;
80674 #endif
80675  assert( pC->isTable );
80676  assert( pC->eCurType==CURTYPE_BTREE );
80677  pCrsr = pC->uc.pCursor;
80678  assert( pCrsr!=0 );
80679  res = 0;
80680  iKey = pIn3->u.i;
80681  rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
80682  assert( rc==SQLITE_OK || res==0 );
80683  pC->movetoTarget = iKey; /* Used by OP_Delete */
80684  pC->nullRow = 0;
80685  pC->cacheStatus = CACHE_STALE;
80686  pC->deferredMoveto = 0;
80687  VdbeBranchTaken(res!=0,2);
80688  pC->seekResult = res;
80689  if( res!=0 ){
80690  assert( rc==SQLITE_OK );
80691  if( pOp->p2==0 ){
80692  rc = SQLITE_CORRUPT_BKPT;
80693  }else{
80694  goto jump_to_p2;
80695  }
80696  }
80697  if( rc ) goto abort_due_to_error;
80698  break;
80699 }
80700 
80701 /* Opcode: Sequence P1 P2 * * *
80702 ** Synopsis: r[P2]=cursor[P1].ctr++
80703 **
80704 ** Find the next available sequence number for cursor P1.
80705 ** Write the sequence number into register P2.
80706 ** The sequence number on the cursor is incremented after this
80707 ** instruction.
80708 */
80709 case OP_Sequence: { /* out2 */
80710  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80711  assert( p->apCsr[pOp->p1]!=0 );
80712  assert( p->apCsr[pOp->p1]->eCurType!=CURTYPE_VTAB );
80713  pOut = out2Prerelease(p, pOp);
80714  pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
80715  break;
80716 }
80717 
80718 
80719 /* Opcode: NewRowid P1 P2 P3 * *
80720 ** Synopsis: r[P2]=rowid
80721 **
80722 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
80723 ** The record number is not previously used as a key in the database
80724 ** table that cursor P1 points to. The new record number is written
80725 ** written to register P2.
80726 **
80727 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
80728 ** the largest previously generated record number. No new record numbers are
80729 ** allowed to be less than this value. When this value reaches its maximum,
80730 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
80731 ** generated record number. This P3 mechanism is used to help implement the
80732 ** AUTOINCREMENT feature.
80733 */
80734 case OP_NewRowid: { /* out2 */
80735  i64 v; /* The new rowid */
80736  VdbeCursor *pC; /* Cursor of table to get the new rowid */
80737  int res; /* Result of an sqlite3BtreeLast() */
80738  int cnt; /* Counter to limit the number of searches */
80739  Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
80740  VdbeFrame *pFrame; /* Root frame of VDBE */
80741 
80742  v = 0;
80743  res = 0;
80744  pOut = out2Prerelease(p, pOp);
80745  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80746  pC = p->apCsr[pOp->p1];
80747  assert( pC!=0 );
80748  assert( pC->eCurType==CURTYPE_BTREE );
80749  assert( pC->uc.pCursor!=0 );
80750  {
80751  /* The next rowid or record number (different terms for the same
80752  ** thing) is obtained in a two-step algorithm.
80753  **
80754  ** First we attempt to find the largest existing rowid and add one
80755  ** to that. But if the largest existing rowid is already the maximum
80756  ** positive integer, we have to fall through to the second
80757  ** probabilistic algorithm
80758  **
80759  ** The second algorithm is to select a rowid at random and see if
80760  ** it already exists in the table. If it does not exist, we have
80761  ** succeeded. If the random rowid does exist, we select a new one
80762  ** and try again, up to 100 times.
80763  */
80764  assert( pC->isTable );
80765 
80766 #ifdef SQLITE_32BIT_ROWID
80767 # define MAX_ROWID 0x7fffffff
80768 #else
80769  /* Some compilers complain about constants of the form 0x7fffffffffffffff.
80770  ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
80771  ** to provide the constant while making all compilers happy.
80772  */
80773 # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
80774 #endif
80775 
80776  if( !pC->useRandomRowid ){
80777  rc = sqlite3BtreeLast(pC->uc.pCursor, &res);
80778  if( rc!=SQLITE_OK ){
80779  goto abort_due_to_error;
80780  }
80781  if( res ){
80782  v = 1; /* IMP: R-61914-48074 */
80783  }else{
80784  assert( sqlite3BtreeCursorIsValid(pC->uc.pCursor) );
80785  rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
80786  assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
80787  if( v>=MAX_ROWID ){
80788  pC->useRandomRowid = 1;
80789  }else{
80790  v++; /* IMP: R-29538-34987 */
80791  }
80792  }
80793  }
80794 
80795 #ifndef SQLITE_OMIT_AUTOINCREMENT
80796  if( pOp->p3 ){
80797  /* Assert that P3 is a valid memory cell. */
80798  assert( pOp->p3>0 );
80799  if( p->pFrame ){
80800  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
80801  /* Assert that P3 is a valid memory cell. */
80802  assert( pOp->p3<=pFrame->nMem );
80803  pMem = &pFrame->aMem[pOp->p3];
80804  }else{
80805  /* Assert that P3 is a valid memory cell. */
80806  assert( pOp->p3<=(p->nMem+1 - p->nCursor) );
80807  pMem = &aMem[pOp->p3];
80808  memAboutToChange(p, pMem);
80809  }
80810  assert( memIsValid(pMem) );
80811 
80812  REGISTER_TRACE(pOp->p3, pMem);
80814  assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
80815  if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
80816  rc = SQLITE_FULL; /* IMP: R-12275-61338 */
80817  goto abort_due_to_error;
80818  }
80819  if( v<pMem->u.i+1 ){
80820  v = pMem->u.i + 1;
80821  }
80822  pMem->u.i = v;
80823  }
80824 #endif
80825  if( pC->useRandomRowid ){
80826  /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
80827  ** largest possible integer (9223372036854775807) then the database
80828  ** engine starts picking positive candidate ROWIDs at random until
80829  ** it finds one that is not previously used. */
80830  assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
80831  ** an AUTOINCREMENT table. */
80832  cnt = 0;
80833  do{
80834  sqlite3_randomness(sizeof(v), &v);
80835  v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
80836  }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->uc.pCursor, 0, (u64)v,
80837  0, &res))==SQLITE_OK)
80838  && (res==0)
80839  && (++cnt<100));
80840  if( rc ) goto abort_due_to_error;
80841  if( res==0 ){
80842  rc = SQLITE_FULL; /* IMP: R-38219-53002 */
80843  goto abort_due_to_error;
80844  }
80845  assert( v>0 ); /* EV: R-40812-03570 */
80846  }
80847  pC->deferredMoveto = 0;
80848  pC->cacheStatus = CACHE_STALE;
80849  }
80850  pOut->u.i = v;
80851  break;
80852 }
80853 
80854 /* Opcode: Insert P1 P2 P3 P4 P5
80855 ** Synopsis: intkey=r[P3] data=r[P2]
80856 **
80857 ** Write an entry into the table of cursor P1. A new entry is
80858 ** created if it doesn't already exist or the data for an existing
80859 ** entry is overwritten. The data is the value MEM_Blob stored in register
80860 ** number P2. The key is stored in register P3. The key must
80861 ** be a MEM_Int.
80862 **
80863 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
80864 ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
80865 ** then rowid is stored for subsequent return by the
80866 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
80867 **
80868 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
80869 ** the last seek operation (OP_NotExists) was a success, then this
80870 ** operation will not attempt to find the appropriate row before doing
80871 ** the insert but will instead overwrite the row that the cursor is
80872 ** currently pointing to. Presumably, the prior OP_NotExists opcode
80873 ** has already positioned the cursor correctly. This is an optimization
80874 ** that boosts performance by avoiding redundant seeks.
80875 **
80876 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
80877 ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
80878 ** is part of an INSERT operation. The difference is only important to
80879 ** the update hook.
80880 **
80881 ** Parameter P4 may point to a Table structure, or may be NULL. If it is
80882 ** not NULL, then the update-hook (sqlite3.xUpdateCallback) is invoked
80883 ** following a successful insert.
80884 **
80885 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
80886 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
80887 ** and register P2 becomes ephemeral. If the cursor is changed, the
80888 ** value of register P2 will then change. Make sure this does not
80889 ** cause any problems.)
80890 **
80891 ** This instruction only works on tables. The equivalent instruction
80892 ** for indices is OP_IdxInsert.
80893 */
80894 /* Opcode: InsertInt P1 P2 P3 P4 P5
80895 ** Synopsis: intkey=P3 data=r[P2]
80896 **
80897 ** This works exactly like OP_Insert except that the key is the
80898 ** integer value P3, not the value of the integer stored in register P3.
80899 */
80900 case OP_Insert:
80901 case OP_InsertInt: {
80902  Mem *pData; /* MEM cell holding data for the record to be inserted */
80903  Mem *pKey; /* MEM cell holding key for the record */
80904  i64 iKey; /* The integer ROWID or key for the record to be inserted */
80905  VdbeCursor *pC; /* Cursor to table into which insert is written */
80906  int nZero; /* Number of zero-bytes to append */
80907  int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
80908  const char *zDb; /* database name - used by the update hook */
80909  Table *pTab; /* Table structure - used by update and pre-update hooks */
80910  int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
80911 
80912  op = 0;
80913  pData = &aMem[pOp->p2];
80914  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
80915  assert( memIsValid(pData) );
80916  pC = p->apCsr[pOp->p1];
80917  assert( pC!=0 );
80918  assert( pC->eCurType==CURTYPE_BTREE );
80919  assert( pC->uc.pCursor!=0 );
80920  assert( pC->isTable );
80921  assert( pOp->p4type==P4_TABLE || pOp->p4type>=P4_STATIC );
80922  REGISTER_TRACE(pOp->p2, pData);
80923 
80924  if( pOp->opcode==OP_Insert ){
80925  pKey = &aMem[pOp->p3];
80926  assert( pKey->flags & MEM_Int );
80927  assert( memIsValid(pKey) );
80928  REGISTER_TRACE(pOp->p3, pKey);
80929  iKey = pKey->u.i;
80930  }else{
80931  assert( pOp->opcode==OP_InsertInt );
80932  iKey = pOp->p3;
80933  }
80934 
80935  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
80936  assert( pC->isTable );
80937  assert( pC->iDb>=0 );
80938  zDb = db->aDb[pC->iDb].zName;
80939  pTab = pOp->p4.pTab;
80940  assert( HasRowid(pTab) );
80941  op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
80942  }else{
80943  pTab = 0; /* Not needed. Silence a comiler warning. */
80944  zDb = 0; /* Not needed. Silence a compiler warning. */
80945  }
80946 
80947 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
80948  /* Invoke the pre-update hook, if any */
80949  if( db->xPreUpdateCallback
80950  && pOp->p4type==P4_TABLE
80951  && !(pOp->p5 & OPFLAG_ISUPDATE)
80952  ){
80953  sqlite3VdbePreUpdateHook(p, pC, SQLITE_INSERT, zDb, pTab, iKey, pOp->p2);
80954  }
80955 #endif
80956 
80957  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
80958  if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
80959  if( pData->flags & MEM_Null ){
80960  pData->z = 0;
80961  pData->n = 0;
80962  }else{
80963  assert( pData->flags & (MEM_Blob|MEM_Str) );
80964  }
80965  seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
80966  if( pData->flags & MEM_Zero ){
80967  nZero = pData->u.nZero;
80968  }else{
80969  nZero = 0;
80970  }
80971  rc = sqlite3BtreeInsert(pC->uc.pCursor, 0, iKey,
80972  pData->z, pData->n, nZero,
80973  (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
80974  );
80975  pC->deferredMoveto = 0;
80976  pC->cacheStatus = CACHE_STALE;
80977 
80978  /* Invoke the update-hook if required. */
80979  if( rc ) goto abort_due_to_error;
80980  if( db->xUpdateCallback && op ){
80981  db->xUpdateCallback(db->pUpdateArg, op, zDb, pTab->zName, iKey);
80982  }
80983  break;
80984 }
80985 
80986 /* Opcode: Delete P1 P2 P3 P4 P5
80987 **
80988 ** Delete the record at which the P1 cursor is currently pointing.
80989 **
80990 ** If the OPFLAG_SAVEPOSITION bit of the P5 parameter is set, then
80991 ** the cursor will be left pointing at either the next or the previous
80992 ** record in the table. If it is left pointing at the next record, then
80993 ** the next Next instruction will be a no-op. As a result, in this case
80994 ** it is ok to delete a record from within a Next loop. If
80995 ** OPFLAG_SAVEPOSITION bit of P5 is clear, then the cursor will be
80996 ** left in an undefined state.
80997 **
80998 ** If the OPFLAG_AUXDELETE bit is set on P5, that indicates that this
80999 ** delete one of several associated with deleting a table row and all its
81000 ** associated index entries. Exactly one of those deletes is the "primary"
81001 ** delete. The others are all on OPFLAG_FORDELETE cursors or else are
81002 ** marked with the AUXDELETE flag.
81003 **
81004 ** If the OPFLAG_NCHANGE flag of P2 (NB: P2 not P5) is set, then the row
81005 ** change count is incremented (otherwise not).
81006 **
81007 ** P1 must not be pseudo-table. It has to be a real table with
81008 ** multiple rows.
81009 **
81010 ** If P4 is not NULL then it points to a Table struture. In this case either
81011 ** the update or pre-update hook, or both, may be invoked. The P1 cursor must
81012 ** have been positioned using OP_NotFound prior to invoking this opcode in
81013 ** this case. Specifically, if one is configured, the pre-update hook is
81014 ** invoked if P4 is not NULL. The update-hook is invoked if one is configured,
81015 ** P4 is not NULL, and the OPFLAG_NCHANGE flag is set in P2.
81016 **
81017 ** If the OPFLAG_ISUPDATE flag is set in P2, then P3 contains the address
81018 ** of the memory cell that contains the value that the rowid of the row will
81019 ** be set to by the update.
81020 */
81021 case OP_Delete: {
81022  VdbeCursor *pC;
81023  const char *zDb;
81024  Table *pTab;
81025  int opflags;
81026 
81027  opflags = pOp->p2;
81028  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81029  pC = p->apCsr[pOp->p1];
81030  assert( pC!=0 );
81031  assert( pC->eCurType==CURTYPE_BTREE );
81032  assert( pC->uc.pCursor!=0 );
81033  assert( pC->deferredMoveto==0 );
81034 
81035 #ifdef SQLITE_DEBUG
81036  if( pOp->p4type==P4_TABLE && HasRowid(pOp->p4.pTab) && pOp->p5==0 ){
81037  /* If p5 is zero, the seek operation that positioned the cursor prior to
81038  ** OP_Delete will have also set the pC->movetoTarget field to the rowid of
81039  ** the row that is being deleted */
81040  i64 iKey = 0;
81041  sqlite3BtreeKeySize(pC->uc.pCursor, &iKey);
81042  assert( pC->movetoTarget==iKey );
81043  }
81044 #endif
81045 
81046  /* If the update-hook or pre-update-hook will be invoked, set zDb to
81047  ** the name of the db to pass as to it. Also set local pTab to a copy
81048  ** of p4.pTab. Finally, if p5 is true, indicating that this cursor was
81049  ** last moved with OP_Next or OP_Prev, not Seek or NotFound, set
81050  ** VdbeCursor.movetoTarget to the current rowid. */
81051  if( pOp->p4type==P4_TABLE && HAS_UPDATE_HOOK(db) ){
81052  assert( pC->iDb>=0 );
81053  assert( pOp->p4.pTab!=0 );
81054  zDb = db->aDb[pC->iDb].zName;
81055  pTab = pOp->p4.pTab;
81056  if( (pOp->p5 & OPFLAG_SAVEPOSITION)!=0 && pC->isTable ){
81058  }
81059  }else{
81060  zDb = 0; /* Not needed. Silence a compiler warning. */
81061  pTab = 0; /* Not needed. Silence a compiler warning. */
81062  }
81063 
81064 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
81065  /* Invoke the pre-update-hook if required. */
81066  if( db->xPreUpdateCallback && pOp->p4.pTab && HasRowid(pTab) ){
81067  assert( !(opflags & OPFLAG_ISUPDATE) || (aMem[pOp->p3].flags & MEM_Int) );
81068  sqlite3VdbePreUpdateHook(p, pC,
81069  (opflags & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_DELETE,
81070  zDb, pTab, pC->movetoTarget,
81071  pOp->p3
81072  );
81073  }
81074  if( opflags & OPFLAG_ISNOOP ) break;
81075 #endif
81076 
81077  /* Only flags that can be set are SAVEPOISTION and AUXDELETE */
81078  assert( (pOp->p5 & ~(OPFLAG_SAVEPOSITION|OPFLAG_AUXDELETE))==0 );
81081 
81082 #ifdef SQLITE_DEBUG
81083  if( p->pFrame==0 ){
81084  if( pC->isEphemeral==0
81085  && (pOp->p5 & OPFLAG_AUXDELETE)==0
81086  && (pC->wrFlag & OPFLAG_FORDELETE)==0
81087  ){
81088  nExtraDelete++;
81089  }
81090  if( pOp->p2 & OPFLAG_NCHANGE ){
81091  nExtraDelete--;
81092  }
81093  }
81094 #endif
81095 
81096  rc = sqlite3BtreeDelete(pC->uc.pCursor, pOp->p5);
81097  pC->cacheStatus = CACHE_STALE;
81098  if( rc ) goto abort_due_to_error;
81099 
81100  /* Invoke the update-hook if required. */
81101  if( opflags & OPFLAG_NCHANGE ){
81102  p->nChange++;
81103  if( db->xUpdateCallback && HasRowid(pTab) ){
81104  db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, pTab->zName,
81105  pC->movetoTarget);
81106  assert( pC->iDb>=0 );
81107  }
81108  }
81109 
81110  break;
81111 }
81112 /* Opcode: ResetCount * * * * *
81113 **
81114 ** The value of the change counter is copied to the database handle
81115 ** change counter (returned by subsequent calls to sqlite3_changes()).
81116 ** Then the VMs internal change counter resets to 0.
81117 ** This is used by trigger programs.
81118 */
81119 case OP_ResetCount: {
81121  p->nChange = 0;
81122  break;
81123 }
81124 
81125 /* Opcode: SorterCompare P1 P2 P3 P4
81126 ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
81127 **
81128 ** P1 is a sorter cursor. This instruction compares a prefix of the
81129 ** record blob in register P3 against a prefix of the entry that
81130 ** the sorter cursor currently points to. Only the first P4 fields
81131 ** of r[P3] and the sorter record are compared.
81132 **
81133 ** If either P3 or the sorter contains a NULL in one of their significant
81134 ** fields (not counting the P4 fields at the end which are ignored) then
81135 ** the comparison is assumed to be equal.
81136 **
81137 ** Fall through to next instruction if the two records compare equal to
81138 ** each other. Jump to P2 if they are different.
81139 */
81140 case OP_SorterCompare: {
81141  VdbeCursor *pC;
81142  int res;
81143  int nKeyCol;
81144 
81145  pC = p->apCsr[pOp->p1];
81146  assert( isSorter(pC) );
81147  assert( pOp->p4type==P4_INT32 );
81148  pIn3 = &aMem[pOp->p3];
81149  nKeyCol = pOp->p4.i;
81150  res = 0;
81151  rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
81152  VdbeBranchTaken(res!=0,2);
81153  if( rc ) goto abort_due_to_error;
81154  if( res ) goto jump_to_p2;
81155  break;
81156 };
81157 
81158 /* Opcode: SorterData P1 P2 P3 * *
81159 ** Synopsis: r[P2]=data
81160 **
81161 ** Write into register P2 the current sorter data for sorter cursor P1.
81162 ** Then clear the column header cache on cursor P3.
81163 **
81164 ** This opcode is normally use to move a record out of the sorter and into
81165 ** a register that is the source for a pseudo-table cursor created using
81166 ** OpenPseudo. That pseudo-table cursor is the one that is identified by
81167 ** parameter P3. Clearing the P3 column cache as part of this opcode saves
81168 ** us from having to issue a separate NullRow instruction to clear that cache.
81169 */
81170 case OP_SorterData: {
81171  VdbeCursor *pC;
81172 
81173  pOut = &aMem[pOp->p2];
81174  pC = p->apCsr[pOp->p1];
81175  assert( isSorter(pC) );
81176  rc = sqlite3VdbeSorterRowkey(pC, pOut);
81177  assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
81178  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81179  if( rc ) goto abort_due_to_error;
81180  p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
81181  break;
81182 }
81183 
81184 /* Opcode: RowData P1 P2 * * *
81185 ** Synopsis: r[P2]=data
81186 **
81187 ** Write into register P2 the complete row data for cursor P1.
81188 ** There is no interpretation of the data.
81189 ** It is just copied onto the P2 register exactly as
81190 ** it is found in the database file.
81191 **
81192 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81193 ** of a real table, not a pseudo-table.
81194 */
81195 /* Opcode: RowKey P1 P2 * * *
81196 ** Synopsis: r[P2]=key
81197 **
81198 ** Write into register P2 the complete row key for cursor P1.
81199 ** There is no interpretation of the data.
81200 ** The key is copied onto the P2 register exactly as
81201 ** it is found in the database file.
81202 **
81203 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
81204 ** of a real table, not a pseudo-table.
81205 */
81206 case OP_RowKey:
81207 case OP_RowData: {
81208  VdbeCursor *pC;
81209  BtCursor *pCrsr;
81210  u32 n;
81211  i64 n64;
81212 
81213  pOut = &aMem[pOp->p2];
81214  memAboutToChange(p, pOut);
81215 
81216  /* Note that RowKey and RowData are really exactly the same instruction */
81217  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81218  pC = p->apCsr[pOp->p1];
81219  assert( pC!=0 );
81220  assert( pC->eCurType==CURTYPE_BTREE );
81221  assert( isSorter(pC)==0 );
81222  assert( pC->isTable || pOp->opcode!=OP_RowData );
81223  assert( pC->isTable==0 || pOp->opcode==OP_RowData );
81224  assert( pC->nullRow==0 );
81225  assert( pC->uc.pCursor!=0 );
81226  pCrsr = pC->uc.pCursor;
81227 
81228  /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
81229  ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
81230  ** the cursor. If this where not the case, on of the following assert()s
81231  ** would fail. Should this ever change (because of changes in the code
81232  ** generator) then the fix would be to insert a call to
81233  ** sqlite3VdbeCursorMoveto().
81234  */
81235  assert( pC->deferredMoveto==0 );
81236  assert( sqlite3BtreeCursorIsValid(pCrsr) );
81237 #if 0 /* Not required due to the previous to assert() statements */
81238  rc = sqlite3VdbeCursorMoveto(pC);
81239  if( rc!=SQLITE_OK ) goto abort_due_to_error;
81240 #endif
81241 
81242  if( pC->isTable==0 ){
81243  assert( !pC->isTable );
81244  VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
81245  assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
81246  if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
81247  goto too_big;
81248  }
81249  n = (u32)n64;
81250  }else{
81251  VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
81252  assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
81253  if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
81254  goto too_big;
81255  }
81256  }
81257  testcase( n==0 );
81258  if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
81259  goto no_mem;
81260  }
81261  pOut->n = n;
81262  MemSetTypeFlag(pOut, MEM_Blob);
81263  if( pC->isTable==0 ){
81264  rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
81265  }else{
81266  rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
81267  }
81268  if( rc ) goto abort_due_to_error;
81269  pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
81270  UPDATE_MAX_BLOBSIZE(pOut);
81271  REGISTER_TRACE(pOp->p2, pOut);
81272  break;
81273 }
81274 
81275 /* Opcode: Rowid P1 P2 * * *
81276 ** Synopsis: r[P2]=rowid
81277 **
81278 ** Store in register P2 an integer which is the key of the table entry that
81279 ** P1 is currently point to.
81280 **
81281 ** P1 can be either an ordinary table or a virtual table. There used to
81282 ** be a separate OP_VRowid opcode for use with virtual tables, but this
81283 ** one opcode now works for both table types.
81284 */
81285 case OP_Rowid: { /* out2 */
81286  VdbeCursor *pC;
81287  i64 v;
81288  sqlite3_vtab *pVtab;
81289  const sqlite3_module *pModule;
81290 
81291  pOut = out2Prerelease(p, pOp);
81292  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81293  pC = p->apCsr[pOp->p1];
81294  assert( pC!=0 );
81295  assert( pC->eCurType!=CURTYPE_PSEUDO || pC->nullRow );
81296  if( pC->nullRow ){
81297  pOut->flags = MEM_Null;
81298  break;
81299  }else if( pC->deferredMoveto ){
81300  v = pC->movetoTarget;
81301 #ifndef SQLITE_OMIT_VIRTUALTABLE
81302  }else if( pC->eCurType==CURTYPE_VTAB ){
81303  assert( pC->uc.pVCur!=0 );
81304  pVtab = pC->uc.pVCur->pVtab;
81305  pModule = pVtab->pModule;
81306  assert( pModule->xRowid );
81307  rc = pModule->xRowid(pC->uc.pVCur, &v);
81308  sqlite3VtabImportErrmsg(p, pVtab);
81309  if( rc ) goto abort_due_to_error;
81310 #endif /* SQLITE_OMIT_VIRTUALTABLE */
81311  }else{
81312  assert( pC->eCurType==CURTYPE_BTREE );
81313  assert( pC->uc.pCursor!=0 );
81314  rc = sqlite3VdbeCursorRestore(pC);
81315  if( rc ) goto abort_due_to_error;
81316  if( pC->nullRow ){
81317  pOut->flags = MEM_Null;
81318  break;
81319  }
81320  rc = sqlite3BtreeKeySize(pC->uc.pCursor, &v);
81321  assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
81322  }
81323  pOut->u.i = v;
81324  break;
81325 }
81326 
81327 /* Opcode: NullRow P1 * * * *
81328 **
81329 ** Move the cursor P1 to a null row. Any OP_Column operations
81330 ** that occur while the cursor is on the null row will always
81331 ** write a NULL.
81332 */
81333 case OP_NullRow: {
81334  VdbeCursor *pC;
81335 
81336  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81337  pC = p->apCsr[pOp->p1];
81338  assert( pC!=0 );
81339  pC->nullRow = 1;
81340  pC->cacheStatus = CACHE_STALE;
81341  if( pC->eCurType==CURTYPE_BTREE ){
81342  assert( pC->uc.pCursor!=0 );
81344  }
81345  break;
81346 }
81347 
81348 /* Opcode: Last P1 P2 P3 * *
81349 **
81350 ** The next use of the Rowid or Column or Prev instruction for P1
81351 ** will refer to the last entry in the database table or index.
81352 ** If the table or index is empty and P2>0, then jump immediately to P2.
81353 ** If P2 is 0 or if the table or index is not empty, fall through
81354 ** to the following instruction.
81355 **
81356 ** This opcode leaves the cursor configured to move in reverse order,
81357 ** from the end toward the beginning. In other words, the cursor is
81358 ** configured to use Prev, not Next.
81359 */
81360 case OP_Last: { /* jump */
81361  VdbeCursor *pC;
81362  BtCursor *pCrsr;
81363  int res;
81364 
81365  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81366  pC = p->apCsr[pOp->p1];
81367  assert( pC!=0 );
81368  assert( pC->eCurType==CURTYPE_BTREE );
81369  pCrsr = pC->uc.pCursor;
81370  res = 0;
81371  assert( pCrsr!=0 );
81372  rc = sqlite3BtreeLast(pCrsr, &res);
81373  pC->nullRow = (u8)res;
81374  pC->deferredMoveto = 0;
81375  pC->cacheStatus = CACHE_STALE;
81376  pC->seekResult = pOp->p3;
81377 #ifdef SQLITE_DEBUG
81378  pC->seekOp = OP_Last;
81379 #endif
81380  if( rc ) goto abort_due_to_error;
81381  if( pOp->p2>0 ){
81382  VdbeBranchTaken(res!=0,2);
81383  if( res ) goto jump_to_p2;
81384  }
81385  break;
81386 }
81387 
81388 
81389 /* Opcode: Sort P1 P2 * * *
81390 **
81391 ** This opcode does exactly the same thing as OP_Rewind except that
81392 ** it increments an undocumented global variable used for testing.
81393 **
81394 ** Sorting is accomplished by writing records into a sorting index,
81395 ** then rewinding that index and playing it back from beginning to
81396 ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
81397 ** rewinding so that the global variable will be incremented and
81398 ** regression tests can determine whether or not the optimizer is
81399 ** correctly optimizing out sorts.
81400 */
81401 case OP_SorterSort: /* jump */
81402 case OP_Sort: { /* jump */
81403 #ifdef SQLITE_TEST
81404  sqlite3_sort_count++;
81405  sqlite3_search_count--;
81406 #endif
81408  /* Fall through into OP_Rewind */
81409 }
81410 /* Opcode: Rewind P1 P2 * * *
81411 **
81412 ** The next use of the Rowid or Column or Next instruction for P1
81413 ** will refer to the first entry in the database table or index.
81414 ** If the table or index is empty, jump immediately to P2.
81415 ** If the table or index is not empty, fall through to the following
81416 ** instruction.
81417 **
81418 ** This opcode leaves the cursor configured to move in forward order,
81419 ** from the beginning toward the end. In other words, the cursor is
81420 ** configured to use Next, not Prev.
81421 */
81422 case OP_Rewind: { /* jump */
81423  VdbeCursor *pC;
81424  BtCursor *pCrsr;
81425  int res;
81426 
81427  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81428  pC = p->apCsr[pOp->p1];
81429  assert( pC!=0 );
81430  assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
81431  res = 1;
81432 #ifdef SQLITE_DEBUG
81433  pC->seekOp = OP_Rewind;
81434 #endif
81435  if( isSorter(pC) ){
81436  rc = sqlite3VdbeSorterRewind(pC, &res);
81437  }else{
81438  assert( pC->eCurType==CURTYPE_BTREE );
81439  pCrsr = pC->uc.pCursor;
81440  assert( pCrsr );
81441  rc = sqlite3BtreeFirst(pCrsr, &res);
81442  pC->deferredMoveto = 0;
81443  pC->cacheStatus = CACHE_STALE;
81444  }
81445  if( rc ) goto abort_due_to_error;
81446  pC->nullRow = (u8)res;
81447  assert( pOp->p2>0 && pOp->p2<p->nOp );
81448  VdbeBranchTaken(res!=0,2);
81449  if( res ) goto jump_to_p2;
81450  break;
81451 }
81452 
81453 /* Opcode: Next P1 P2 P3 P4 P5
81454 **
81455 ** Advance cursor P1 so that it points to the next key/data pair in its
81456 ** table or index. If there are no more key/value pairs then fall through
81457 ** to the following instruction. But if the cursor advance was successful,
81458 ** jump immediately to P2.
81459 **
81460 ** The Next opcode is only valid following an SeekGT, SeekGE, or
81461 ** OP_Rewind opcode used to position the cursor. Next is not allowed
81462 ** to follow SeekLT, SeekLE, or OP_Last.
81463 **
81464 ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
81465 ** been opened prior to this opcode or the program will segfault.
81466 **
81467 ** The P3 value is a hint to the btree implementation. If P3==1, that
81468 ** means P1 is an SQL index and that this instruction could have been
81469 ** omitted if that index had been unique. P3 is usually 0. P3 is
81470 ** always either 0 or 1.
81471 **
81472 ** P4 is always of type P4_ADVANCE. The function pointer points to
81473 ** sqlite3BtreeNext().
81474 **
81475 ** If P5 is positive and the jump is taken, then event counter
81476 ** number P5-1 in the prepared statement is incremented.
81477 **
81478 ** See also: Prev, NextIfOpen
81479 */
81480 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
81481 **
81482 ** This opcode works just like Next except that if cursor P1 is not
81483 ** open it behaves a no-op.
81484 */
81485 /* Opcode: Prev P1 P2 P3 P4 P5
81486 **
81487 ** Back up cursor P1 so that it points to the previous key/data pair in its
81488 ** table or index. If there is no previous key/value pairs then fall through
81489 ** to the following instruction. But if the cursor backup was successful,
81490 ** jump immediately to P2.
81491 **
81492 **
81493 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
81494 ** OP_Last opcode used to position the cursor. Prev is not allowed
81495 ** to follow SeekGT, SeekGE, or OP_Rewind.
81496 **
81497 ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
81498 ** not open then the behavior is undefined.
81499 **
81500 ** The P3 value is a hint to the btree implementation. If P3==1, that
81501 ** means P1 is an SQL index and that this instruction could have been
81502 ** omitted if that index had been unique. P3 is usually 0. P3 is
81503 ** always either 0 or 1.
81504 **
81505 ** P4 is always of type P4_ADVANCE. The function pointer points to
81506 ** sqlite3BtreePrevious().
81507 **
81508 ** If P5 is positive and the jump is taken, then event counter
81509 ** number P5-1 in the prepared statement is incremented.
81510 */
81511 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
81512 **
81513 ** This opcode works just like Prev except that if cursor P1 is not
81514 ** open it behaves a no-op.
81515 */
81516 case OP_SorterNext: { /* jump */
81517  VdbeCursor *pC;
81518  int res;
81519 
81520  pC = p->apCsr[pOp->p1];
81521  assert( isSorter(pC) );
81522  res = 0;
81523  rc = sqlite3VdbeSorterNext(db, pC, &res);
81524  goto next_tail;
81525 case OP_PrevIfOpen: /* jump */
81526 case OP_NextIfOpen: /* jump */
81527  if( p->apCsr[pOp->p1]==0 ) break;
81528  /* Fall through */
81529 case OP_Prev: /* jump */
81530 case OP_Next: /* jump */
81531  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81532  assert( pOp->p5<ArraySize(p->aCounter) );
81533  pC = p->apCsr[pOp->p1];
81534  res = pOp->p3;
81535  assert( pC!=0 );
81536  assert( pC->deferredMoveto==0 );
81537  assert( pC->eCurType==CURTYPE_BTREE );
81538  assert( res==0 || (res==1 && pC->isTable==0) );
81539  testcase( res==1 );
81540  assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
81544 
81545  /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
81546  ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
81547  assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
81548  || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
81549  || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
81550  assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
81551  || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
81552  || pC->seekOp==OP_Last );
81553 
81554  rc = pOp->p4.xAdvance(pC->uc.pCursor, &res);
81555 next_tail:
81556  pC->cacheStatus = CACHE_STALE;
81557  VdbeBranchTaken(res==0,2);
81558  if( rc ) goto abort_due_to_error;
81559  if( res==0 ){
81560  pC->nullRow = 0;
81561  p->aCounter[pOp->p5]++;
81562 #ifdef SQLITE_TEST
81563  sqlite3_search_count++;
81564 #endif
81565  goto jump_to_p2_and_check_for_interrupt;
81566  }else{
81567  pC->nullRow = 1;
81568  }
81569  goto check_for_interrupt;
81570 }
81571 
81572 /* Opcode: IdxInsert P1 P2 P3 * P5
81573 ** Synopsis: key=r[P2]
81574 **
81575 ** Register P2 holds an SQL index key made using the
81576 ** MakeRecord instructions. This opcode writes that key
81577 ** into the index P1. Data for the entry is nil.
81578 **
81579 ** P3 is a flag that provides a hint to the b-tree layer that this
81580 ** insert is likely to be an append.
81581 **
81582 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
81583 ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
81584 ** then the change counter is unchanged.
81585 **
81586 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
81587 ** just done a seek to the spot where the new entry is to be inserted.
81588 ** This flag avoids doing an extra seek.
81589 **
81590 ** This instruction only works for indices. The equivalent instruction
81591 ** for tables is OP_Insert.
81592 */
81593 case OP_SorterInsert: /* in2 */
81594 case OP_IdxInsert: { /* in2 */
81595  VdbeCursor *pC;
81596  int nKey;
81597  const char *zKey;
81598 
81599  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81600  pC = p->apCsr[pOp->p1];
81601  assert( pC!=0 );
81602  assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
81603  pIn2 = &aMem[pOp->p2];
81604  assert( pIn2->flags & MEM_Blob );
81605  if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
81607  assert( pC->isTable==0 );
81608  rc = ExpandBlob(pIn2);
81609  if( rc ) goto abort_due_to_error;
81610  if( pOp->opcode==OP_SorterInsert ){
81611  rc = sqlite3VdbeSorterWrite(pC, pIn2);
81612  }else{
81613  nKey = pIn2->n;
81614  zKey = pIn2->z;
81615  rc = sqlite3BtreeInsert(pC->uc.pCursor, zKey, nKey, "", 0, 0, pOp->p3,
81616  ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
81617  );
81618  assert( pC->deferredMoveto==0 );
81619  pC->cacheStatus = CACHE_STALE;
81620  }
81621  if( rc) goto abort_due_to_error;
81622  break;
81623 }
81624 
81625 /* Opcode: IdxDelete P1 P2 P3 * *
81626 ** Synopsis: key=r[P2@P3]
81627 **
81628 ** The content of P3 registers starting at register P2 form
81629 ** an unpacked index key. This opcode removes that entry from the
81630 ** index opened by cursor P1.
81631 */
81632 case OP_IdxDelete: {
81633  VdbeCursor *pC;
81634  BtCursor *pCrsr;
81635  int res;
81636  UnpackedRecord r;
81637 
81638  assert( pOp->p3>0 );
81639  assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem+1 - p->nCursor)+1 );
81640  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81641  pC = p->apCsr[pOp->p1];
81642  assert( pC!=0 );
81643  assert( pC->eCurType==CURTYPE_BTREE );
81644  pCrsr = pC->uc.pCursor;
81645  assert( pCrsr!=0 );
81646  assert( pOp->p5==0 );
81647  r.pKeyInfo = pC->pKeyInfo;
81648  r.nField = (u16)pOp->p3;
81649  r.default_rc = 0;
81650  r.aMem = &aMem[pOp->p2];
81651  rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
81652  if( rc ) goto abort_due_to_error;
81653  if( res==0 ){
81654  rc = sqlite3BtreeDelete(pCrsr, BTREE_AUXDELETE);
81655  if( rc ) goto abort_due_to_error;
81656  }
81657  assert( pC->deferredMoveto==0 );
81658  pC->cacheStatus = CACHE_STALE;
81659  break;
81660 }
81661 
81662 /* Opcode: Seek P1 * P3 P4 *
81663 ** Synopsis: Move P3 to P1.rowid
81664 **
81665 ** P1 is an open index cursor and P3 is a cursor on the corresponding
81666 ** table. This opcode does a deferred seek of the P3 table cursor
81667 ** to the row that corresponds to the current row of P1.
81668 **
81669 ** This is a deferred seek. Nothing actually happens until
81670 ** the cursor is used to read a record. That way, if no reads
81671 ** occur, no unnecessary I/O happens.
81672 **
81673 ** P4 may be an array of integers (type P4_INTARRAY) containing
81674 ** one entry for each column in the P3 table. If array entry a(i)
81675 ** is non-zero, then reading column a(i)-1 from cursor P3 is
81676 ** equivalent to performing the deferred seek and then reading column i
81677 ** from P1. This information is stored in P3 and used to redirect
81678 ** reads against P3 over to P1, thus possibly avoiding the need to
81679 ** seek and read cursor P3.
81680 */
81681 /* Opcode: IdxRowid P1 P2 * * *
81682 ** Synopsis: r[P2]=rowid
81683 **
81684 ** Write into register P2 an integer which is the last entry in the record at
81685 ** the end of the index key pointed to by cursor P1. This integer should be
81686 ** the rowid of the table entry to which this index entry points.
81687 **
81688 ** See also: Rowid, MakeRecord.
81689 */
81690 case OP_Seek:
81691 case OP_IdxRowid: { /* out2 */
81692  VdbeCursor *pC; /* The P1 index cursor */
81693  VdbeCursor *pTabCur; /* The P2 table cursor (OP_Seek only) */
81694  i64 rowid; /* Rowid that P1 current points to */
81695 
81696  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81697  pC = p->apCsr[pOp->p1];
81698  assert( pC!=0 );
81699  assert( pC->eCurType==CURTYPE_BTREE );
81700  assert( pC->uc.pCursor!=0 );
81701  assert( pC->isTable==0 );
81702  assert( pC->deferredMoveto==0 );
81703  assert( !pC->nullRow || pOp->opcode==OP_IdxRowid );
81704 
81705  /* The IdxRowid and Seek opcodes are combined because of the commonality
81706  ** of sqlite3VdbeCursorRestore() and sqlite3VdbeIdxRowid(). */
81707  rc = sqlite3VdbeCursorRestore(pC);
81708 
81709  /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
81710  ** out from under the cursor. That will never happens for an IdxRowid
81711  ** or Seek opcode */
81712  if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
81713 
81714  if( !pC->nullRow ){
81715  rowid = 0; /* Not needed. Only used to silence a warning. */
81716  rc = sqlite3VdbeIdxRowid(db, pC->uc.pCursor, &rowid);
81717  if( rc!=SQLITE_OK ){
81718  goto abort_due_to_error;
81719  }
81720  if( pOp->opcode==OP_Seek ){
81721  assert( pOp->p3>=0 && pOp->p3<p->nCursor );
81722  pTabCur = p->apCsr[pOp->p3];
81723  assert( pTabCur!=0 );
81724  assert( pTabCur->eCurType==CURTYPE_BTREE );
81725  assert( pTabCur->uc.pCursor!=0 );
81726  assert( pTabCur->isTable );
81727  pTabCur->nullRow = 0;
81728  pTabCur->movetoTarget = rowid;
81729  pTabCur->deferredMoveto = 1;
81730  assert( pOp->p4type==P4_INTARRAY || pOp->p4.ai==0 );
81731  pTabCur->aAltMap = pOp->p4.ai;
81732  pTabCur->pAltCursor = pC;
81733  }else{
81734  pOut = out2Prerelease(p, pOp);
81735  pOut->u.i = rowid;
81736  pOut->flags = MEM_Int;
81737  }
81738  }else{
81739  assert( pOp->opcode==OP_IdxRowid );
81740  sqlite3VdbeMemSetNull(&aMem[pOp->p2]);
81741  }
81742  break;
81743 }
81744 
81745 /* Opcode: IdxGE P1 P2 P3 P4 P5
81746 ** Synopsis: key=r[P3@P4]
81747 **
81748 ** The P4 register values beginning with P3 form an unpacked index
81749 ** key that omits the PRIMARY KEY. Compare this key value against the index
81750 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
81751 ** fields at the end.
81752 **
81753 ** If the P1 index entry is greater than or equal to the key value
81754 ** then jump to P2. Otherwise fall through to the next instruction.
81755 */
81756 /* Opcode: IdxGT P1 P2 P3 P4 P5
81757 ** Synopsis: key=r[P3@P4]
81758 **
81759 ** The P4 register values beginning with P3 form an unpacked index
81760 ** key that omits the PRIMARY KEY. Compare this key value against the index
81761 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
81762 ** fields at the end.
81763 **
81764 ** If the P1 index entry is greater than the key value
81765 ** then jump to P2. Otherwise fall through to the next instruction.
81766 */
81767 /* Opcode: IdxLT P1 P2 P3 P4 P5
81768 ** Synopsis: key=r[P3@P4]
81769 **
81770 ** The P4 register values beginning with P3 form an unpacked index
81771 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
81772 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
81773 ** ROWID on the P1 index.
81774 **
81775 ** If the P1 index entry is less than the key value then jump to P2.
81776 ** Otherwise fall through to the next instruction.
81777 */
81778 /* Opcode: IdxLE P1 P2 P3 P4 P5
81779 ** Synopsis: key=r[P3@P4]
81780 **
81781 ** The P4 register values beginning with P3 form an unpacked index
81782 ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
81783 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
81784 ** ROWID on the P1 index.
81785 **
81786 ** If the P1 index entry is less than or equal to the key value then jump
81787 ** to P2. Otherwise fall through to the next instruction.
81788 */
81789 case OP_IdxLE: /* jump */
81790 case OP_IdxGT: /* jump */
81791 case OP_IdxLT: /* jump */
81792 case OP_IdxGE: { /* jump */
81793  VdbeCursor *pC;
81794  int res;
81795  UnpackedRecord r;
81796 
81797  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81798  pC = p->apCsr[pOp->p1];
81799  assert( pC!=0 );
81800  assert( pC->isOrdered );
81801  assert( pC->eCurType==CURTYPE_BTREE );
81802  assert( pC->uc.pCursor!=0);
81803  assert( pC->deferredMoveto==0 );
81804  assert( pOp->p5==0 || pOp->p5==1 );
81805  assert( pOp->p4type==P4_INT32 );
81806  r.pKeyInfo = pC->pKeyInfo;
81807  r.nField = (u16)pOp->p4.i;
81808  if( pOp->opcode<OP_IdxLT ){
81809  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
81810  r.default_rc = -1;
81811  }else{
81812  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
81813  r.default_rc = 0;
81814  }
81815  r.aMem = &aMem[pOp->p3];
81816 #ifdef SQLITE_DEBUG
81817  { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
81818 #endif
81819  res = 0; /* Not needed. Only used to silence a warning. */
81820  rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
81821  assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
81822  if( (pOp->opcode&1)==(OP_IdxLT&1) ){
81823  assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
81824  res = -res;
81825  }else{
81826  assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
81827  res++;
81828  }
81829  VdbeBranchTaken(res>0,2);
81830  if( rc ) goto abort_due_to_error;
81831  if( res>0 ) goto jump_to_p2;
81832  break;
81833 }
81834 
81835 /* Opcode: Destroy P1 P2 P3 * *
81836 **
81837 ** Delete an entire database table or index whose root page in the database
81838 ** file is given by P1.
81839 **
81840 ** The table being destroyed is in the main database file if P3==0. If
81841 ** P3==1 then the table to be clear is in the auxiliary database file
81842 ** that is used to store tables create using CREATE TEMPORARY TABLE.
81843 **
81844 ** If AUTOVACUUM is enabled then it is possible that another root page
81845 ** might be moved into the newly deleted root page in order to keep all
81846 ** root pages contiguous at the beginning of the database. The former
81847 ** value of the root page that moved - its value before the move occurred -
81848 ** is stored in register P2. If no page
81849 ** movement was required (because the table being dropped was already
81850 ** the last one in the database) then a zero is stored in register P2.
81851 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
81852 **
81853 ** See also: Clear
81854 */
81855 case OP_Destroy: { /* out2 */
81856  int iMoved;
81857  int iDb;
81858 
81859  assert( p->readOnly==0 );
81860  assert( pOp->p1>1 );
81861  pOut = out2Prerelease(p, pOp);
81862  pOut->flags = MEM_Null;
81863  if( db->nVdbeRead > db->nVDestroy+1 ){
81864  rc = SQLITE_LOCKED;
81865  p->errorAction = OE_Abort;
81866  goto abort_due_to_error;
81867  }else{
81868  iDb = pOp->p3;
81869  assert( DbMaskTest(p->btreeMask, iDb) );
81870  iMoved = 0; /* Not needed. Only to silence a warning. */
81871  rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
81872  pOut->flags = MEM_Int;
81873  pOut->u.i = iMoved;
81874  if( rc ) goto abort_due_to_error;
81875 #ifndef SQLITE_OMIT_AUTOVACUUM
81876  if( iMoved!=0 ){
81877  sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
81878  /* All OP_Destroy operations occur on the same btree */
81879  assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
81880  resetSchemaOnFault = iDb+1;
81881  }
81882 #endif
81883  }
81884  break;
81885 }
81886 
81887 /* Opcode: Clear P1 P2 P3
81888 **
81889 ** Delete all contents of the database table or index whose root page
81890 ** in the database file is given by P1. But, unlike Destroy, do not
81891 ** remove the table or index from the database file.
81892 **
81893 ** The table being clear is in the main database file if P2==0. If
81894 ** P2==1 then the table to be clear is in the auxiliary database file
81895 ** that is used to store tables create using CREATE TEMPORARY TABLE.
81896 **
81897 ** If the P3 value is non-zero, then the table referred to must be an
81898 ** intkey table (an SQL table, not an index). In this case the row change
81899 ** count is incremented by the number of rows in the table being cleared.
81900 ** If P3 is greater than zero, then the value stored in register P3 is
81901 ** also incremented by the number of rows in the table being cleared.
81902 **
81903 ** See also: Destroy
81904 */
81905 case OP_Clear: {
81906  int nChange;
81907 
81908  nChange = 0;
81909  assert( p->readOnly==0 );
81910  assert( DbMaskTest(p->btreeMask, pOp->p2) );
81912  db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
81913  );
81914  if( pOp->p3 ){
81915  p->nChange += nChange;
81916  if( pOp->p3>0 ){
81917  assert( memIsValid(&aMem[pOp->p3]) );
81918  memAboutToChange(p, &aMem[pOp->p3]);
81919  aMem[pOp->p3].u.i += nChange;
81920  }
81921  }
81922  if( rc ) goto abort_due_to_error;
81923  break;
81924 }
81925 
81926 /* Opcode: ResetSorter P1 * * * *
81927 **
81928 ** Delete all contents from the ephemeral table or sorter
81929 ** that is open on cursor P1.
81930 **
81931 ** This opcode only works for cursors used for sorting and
81932 ** opened with OP_OpenEphemeral or OP_SorterOpen.
81933 */
81934 case OP_ResetSorter: {
81935  VdbeCursor *pC;
81936 
81937  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
81938  pC = p->apCsr[pOp->p1];
81939  assert( pC!=0 );
81940  if( isSorter(pC) ){
81942  }else{
81943  assert( pC->eCurType==CURTYPE_BTREE );
81944  assert( pC->isEphemeral );
81946  if( rc ) goto abort_due_to_error;
81947  }
81948  break;
81949 }
81950 
81951 /* Opcode: CreateTable P1 P2 * * *
81952 ** Synopsis: r[P2]=root iDb=P1
81953 **
81954 ** Allocate a new table in the main database file if P1==0 or in the
81955 ** auxiliary database file if P1==1 or in an attached database if
81956 ** P1>1. Write the root page number of the new table into
81957 ** register P2
81958 **
81959 ** The difference between a table and an index is this: A table must
81960 ** have a 4-byte integer key and can have arbitrary data. An index
81961 ** has an arbitrary key but no data.
81962 **
81963 ** See also: CreateIndex
81964 */
81965 /* Opcode: CreateIndex P1 P2 * * *
81966 ** Synopsis: r[P2]=root iDb=P1
81967 **
81968 ** Allocate a new index in the main database file if P1==0 or in the
81969 ** auxiliary database file if P1==1 or in an attached database if
81970 ** P1>1. Write the root page number of the new table into
81971 ** register P2.
81972 **
81973 ** See documentation on OP_CreateTable for additional information.
81974 */
81975 case OP_CreateIndex: /* out2 */
81976 case OP_CreateTable: { /* out2 */
81977  int pgno;
81978  int flags;
81979  Db *pDb;
81980 
81981  pOut = out2Prerelease(p, pOp);
81982  pgno = 0;
81983  assert( pOp->p1>=0 && pOp->p1<db->nDb );
81984  assert( DbMaskTest(p->btreeMask, pOp->p1) );
81985  assert( p->readOnly==0 );
81986  pDb = &db->aDb[pOp->p1];
81987  assert( pDb->pBt!=0 );
81988  if( pOp->opcode==OP_CreateTable ){
81989  /* flags = BTREE_INTKEY; */
81990  flags = BTREE_INTKEY;
81991  }else{
81992  flags = BTREE_BLOBKEY;
81993  }
81994  rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
81995  if( rc ) goto abort_due_to_error;
81996  pOut->u.i = pgno;
81997  break;
81998 }
81999 
82000 /* Opcode: ParseSchema P1 * * P4 *
82001 **
82002 ** Read and parse all entries from the SQLITE_MASTER table of database P1
82003 ** that match the WHERE clause P4.
82004 **
82005 ** This opcode invokes the parser to create a new virtual machine,
82006 ** then runs the new virtual machine. It is thus a re-entrant opcode.
82007 */
82008 case OP_ParseSchema: {
82009  int iDb;
82010  const char *zMaster;
82011  char *zSql;
82012  InitData initData;
82013 
82014  /* Any prepared statement that invokes this opcode will hold mutexes
82015  ** on every btree. This is a prerequisite for invoking
82016  ** sqlite3InitCallback().
82017  */
82018 #ifdef SQLITE_DEBUG
82019  for(iDb=0; iDb<db->nDb; iDb++){
82020  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
82021  }
82022 #endif
82023 
82024  iDb = pOp->p1;
82025  assert( iDb>=0 && iDb<db->nDb );
82026  assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
82027  /* Used to be a conditional */ {
82028  zMaster = SCHEMA_TABLE(iDb);
82029  initData.db = db;
82030  initData.iDb = pOp->p1;
82031  initData.pzErrMsg = &p->zErrMsg;
82032  zSql = sqlite3MPrintf(db,
82033  "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
82034  db->aDb[iDb].zName, zMaster, pOp->p4.z);
82035  if( zSql==0 ){
82036  rc = SQLITE_NOMEM_BKPT;
82037  }else{
82038  assert( db->init.busy==0 );
82039  db->init.busy = 1;
82040  initData.rc = SQLITE_OK;
82041  assert( !db->mallocFailed );
82042  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
82043  if( rc==SQLITE_OK ) rc = initData.rc;
82044  sqlite3DbFree(db, zSql);
82045  db->init.busy = 0;
82046  }
82047  }
82048  if( rc ){
82050  if( rc==SQLITE_NOMEM ){
82051  goto no_mem;
82052  }
82053  goto abort_due_to_error;
82054  }
82055  break;
82056 }
82057 
82058 #if !defined(SQLITE_OMIT_ANALYZE)
82059 /* Opcode: LoadAnalysis P1 * * * *
82060 **
82061 ** Read the sqlite_stat1 table for database P1 and load the content
82062 ** of that table into the internal index hash table. This will cause
82063 ** the analysis to be used when preparing all subsequent queries.
82064 */
82065 case OP_LoadAnalysis: {
82066  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82067  rc = sqlite3AnalysisLoad(db, pOp->p1);
82068  if( rc ) goto abort_due_to_error;
82069  break;
82070 }
82071 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
82072 
82073 /* Opcode: DropTable P1 * * P4 *
82074 **
82075 ** Remove the internal (in-memory) data structures that describe
82076 ** the table named P4 in database P1. This is called after a table
82077 ** is dropped from disk (using the Destroy opcode) in order to keep
82078 ** the internal representation of the
82079 ** schema consistent with what is on disk.
82080 */
82081 case OP_DropTable: {
82082  sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
82083  break;
82084 }
82085 
82086 /* Opcode: DropIndex P1 * * P4 *
82087 **
82088 ** Remove the internal (in-memory) data structures that describe
82089 ** the index named P4 in database P1. This is called after an index
82090 ** is dropped from disk (using the Destroy opcode)
82091 ** in order to keep the internal representation of the
82092 ** schema consistent with what is on disk.
82093 */
82094 case OP_DropIndex: {
82095  sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
82096  break;
82097 }
82098 
82099 /* Opcode: DropTrigger P1 * * P4 *
82100 **
82101 ** Remove the internal (in-memory) data structures that describe
82102 ** the trigger named P4 in database P1. This is called after a trigger
82103 ** is dropped from disk (using the Destroy opcode) in order to keep
82104 ** the internal representation of the
82105 ** schema consistent with what is on disk.
82106 */
82107 case OP_DropTrigger: {
82108  sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
82109  break;
82110 }
82111 
82112 
82113 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
82114 /* Opcode: IntegrityCk P1 P2 P3 P4 P5
82115 **
82116 ** Do an analysis of the currently open database. Store in
82117 ** register P1 the text of an error message describing any problems.
82118 ** If no problems are found, store a NULL in register P1.
82119 **
82120 ** The register P3 contains the maximum number of allowed errors.
82121 ** At most reg(P3) errors will be reported.
82122 ** In other words, the analysis stops as soon as reg(P1) errors are
82123 ** seen. Reg(P1) is updated with the number of errors remaining.
82124 **
82125 ** The root page numbers of all tables in the database are integers
82126 ** stored in P4_INTARRAY argument.
82127 **
82128 ** If P5 is not zero, the check is done on the auxiliary database
82129 ** file, not the main database file.
82130 **
82131 ** This opcode is used to implement the integrity_check pragma.
82132 */
82133 case OP_IntegrityCk: {
82134  int nRoot; /* Number of tables to check. (Number of root pages.) */
82135  int *aRoot; /* Array of rootpage numbers for tables to be checked */
82136  int nErr; /* Number of errors reported */
82137  char *z; /* Text of the error report */
82138  Mem *pnErr; /* Register keeping track of errors remaining */
82139 
82140  assert( p->bIsReader );
82141  nRoot = pOp->p2;
82142  aRoot = pOp->p4.ai;
82143  assert( nRoot>0 );
82144  assert( aRoot[nRoot]==0 );
82145  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82146  pnErr = &aMem[pOp->p3];
82147  assert( (pnErr->flags & MEM_Int)!=0 );
82148  assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
82149  pIn1 = &aMem[pOp->p1];
82150  assert( pOp->p5<db->nDb );
82151  assert( DbMaskTest(p->btreeMask, pOp->p5) );
82152  z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
82153  (int)pnErr->u.i, &nErr);
82154  pnErr->u.i -= nErr;
82155  sqlite3VdbeMemSetNull(pIn1);
82156  if( nErr==0 ){
82157  assert( z==0 );
82158  }else if( z==0 ){
82159  goto no_mem;
82160  }else{
82162  }
82163  UPDATE_MAX_BLOBSIZE(pIn1);
82164  sqlite3VdbeChangeEncoding(pIn1, encoding);
82165  break;
82166 }
82167 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
82168 
82169 /* Opcode: RowSetAdd P1 P2 * * *
82170 ** Synopsis: rowset(P1)=r[P2]
82171 **
82172 ** Insert the integer value held by register P2 into a boolean index
82173 ** held in register P1.
82174 **
82175 ** An assertion fails if P2 is not an integer.
82176 */
82177 case OP_RowSetAdd: { /* in1, in2 */
82178  pIn1 = &aMem[pOp->p1];
82179  pIn2 = &aMem[pOp->p2];
82180  assert( (pIn2->flags & MEM_Int)!=0 );
82181  if( (pIn1->flags & MEM_RowSet)==0 ){
82183  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82184  }
82185  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
82186  break;
82187 }
82188 
82189 /* Opcode: RowSetRead P1 P2 P3 * *
82190 ** Synopsis: r[P3]=rowset(P1)
82191 **
82192 ** Extract the smallest value from boolean index P1 and put that value into
82193 ** register P3. Or, if boolean index P1 is initially empty, leave P3
82194 ** unchanged and jump to instruction P2.
82195 */
82196 case OP_RowSetRead: { /* jump, in1, out3 */
82197  i64 val;
82198 
82199  pIn1 = &aMem[pOp->p1];
82200  if( (pIn1->flags & MEM_RowSet)==0
82201  || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
82202  ){
82203  /* The boolean index is empty */
82204  sqlite3VdbeMemSetNull(pIn1);
82205  VdbeBranchTaken(1,2);
82206  goto jump_to_p2_and_check_for_interrupt;
82207  }else{
82208  /* A value was pulled from the index */
82209  VdbeBranchTaken(0,2);
82210  sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
82211  }
82212  goto check_for_interrupt;
82213 }
82214 
82215 /* Opcode: RowSetTest P1 P2 P3 P4
82216 ** Synopsis: if r[P3] in rowset(P1) goto P2
82217 **
82218 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
82219 ** contains a RowSet object and that RowSet object contains
82220 ** the value held in P3, jump to register P2. Otherwise, insert the
82221 ** integer in P3 into the RowSet and continue on to the
82222 ** next opcode.
82223 **
82224 ** The RowSet object is optimized for the case where successive sets
82225 ** of integers, where each set contains no duplicates. Each set
82226 ** of values is identified by a unique P4 value. The first set
82227 ** must have P4==0, the final set P4=-1. P4 must be either -1 or
82228 ** non-negative. For non-negative values of P4 only the lower 4
82229 ** bits are significant.
82230 **
82231 ** This allows optimizations: (a) when P4==0 there is no need to test
82232 ** the rowset object for P3, as it is guaranteed not to contain it,
82233 ** (b) when P4==-1 there is no need to insert the value, as it will
82234 ** never be tested for, and (c) when a value that is part of set X is
82235 ** inserted, there is no need to search to see if the same value was
82236 ** previously inserted as part of set X (only if it was previously
82237 ** inserted as part of some other set).
82238 */
82239 case OP_RowSetTest: { /* jump, in1, in3 */
82240  int iSet;
82241  int exists;
82242 
82243  pIn1 = &aMem[pOp->p1];
82244  pIn3 = &aMem[pOp->p3];
82245  iSet = pOp->p4.i;
82246  assert( pIn3->flags&MEM_Int );
82247 
82248  /* If there is anything other than a rowset object in memory cell P1,
82249  ** delete it now and initialize P1 with an empty rowset
82250  */
82251  if( (pIn1->flags & MEM_RowSet)==0 ){
82253  if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
82254  }
82255 
82256  assert( pOp->p4type==P4_INT32 );
82257  assert( iSet==-1 || iSet>=0 );
82258  if( iSet ){
82259  exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
82260  VdbeBranchTaken(exists!=0,2);
82261  if( exists ) goto jump_to_p2;
82262  }
82263  if( iSet>=0 ){
82264  sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
82265  }
82266  break;
82267 }
82268 
82269 
82270 #ifndef SQLITE_OMIT_TRIGGER
82271 
82272 /* Opcode: Program P1 P2 P3 P4 P5
82273 **
82274 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
82275 **
82276 ** P1 contains the address of the memory cell that contains the first memory
82277 ** cell in an array of values used as arguments to the sub-program. P2
82278 ** contains the address to jump to if the sub-program throws an IGNORE
82279 ** exception using the RAISE() function. Register P3 contains the address
82280 ** of a memory cell in this (the parent) VM that is used to allocate the
82281 ** memory required by the sub-vdbe at runtime.
82282 **
82283 ** P4 is a pointer to the VM containing the trigger program.
82284 **
82285 ** If P5 is non-zero, then recursive program invocation is enabled.
82286 */
82287 case OP_Program: { /* jump */
82288  int nMem; /* Number of memory registers for sub-program */
82289  int nByte; /* Bytes of runtime space required for sub-program */
82290  Mem *pRt; /* Register to allocate runtime space */
82291  Mem *pMem; /* Used to iterate through memory cells */
82292  Mem *pEnd; /* Last memory cell in new array */
82293  VdbeFrame *pFrame; /* New vdbe frame to execute in */
82294  SubProgram *pProgram; /* Sub-program to execute */
82295  void *t; /* Token identifying trigger */
82296 
82297  pProgram = pOp->p4.pProgram;
82298  pRt = &aMem[pOp->p3];
82299  assert( pProgram->nOp>0 );
82300 
82301  /* If the p5 flag is clear, then recursive invocation of triggers is
82302  ** disabled for backwards compatibility (p5 is set if this sub-program
82303  ** is really a trigger, not a foreign key action, and the flag set
82304  ** and cleared by the "PRAGMA recursive_triggers" command is clear).
82305  **
82306  ** It is recursive invocation of triggers, at the SQL level, that is
82307  ** disabled. In some cases a single trigger may generate more than one
82308  ** SubProgram (if the trigger may be executed with more than one different
82309  ** ON CONFLICT algorithm). SubProgram structures associated with a
82310  ** single trigger all have the same value for the SubProgram.token
82311  ** variable. */
82312  if( pOp->p5 ){
82313  t = pProgram->token;
82314  for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
82315  if( pFrame ) break;
82316  }
82317 
82318  if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
82319  rc = SQLITE_ERROR;
82320  sqlite3VdbeError(p, "too many levels of trigger recursion");
82321  goto abort_due_to_error;
82322  }
82323 
82324  /* Register pRt is used to store the memory required to save the state
82325  ** of the current program, and the memory required at runtime to execute
82326  ** the trigger program. If this trigger has been fired before, then pRt
82327  ** is already allocated. Otherwise, it must be initialized. */
82328  if( (pRt->flags&MEM_Frame)==0 ){
82329  /* SubProgram.nMem is set to the number of memory cells used by the
82330  ** program stored in SubProgram.aOp. As well as these, one memory
82331  ** cell is required for each cursor used by the program. Set local
82332  ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
82333  */
82334  nMem = pProgram->nMem + pProgram->nCsr;
82335  assert( nMem>0 );
82336  if( pProgram->nCsr==0 ) nMem++;
82337  nByte = ROUND8(sizeof(VdbeFrame))
82338  + nMem * sizeof(Mem)
82339  + pProgram->nCsr * sizeof(VdbeCursor *)
82340  + pProgram->nOnce * sizeof(u8);
82341  pFrame = sqlite3DbMallocZero(db, nByte);
82342  if( !pFrame ){
82343  goto no_mem;
82344  }
82345  sqlite3VdbeMemRelease(pRt);
82346  pRt->flags = MEM_Frame;
82347  pRt->u.pFrame = pFrame;
82348 
82349  pFrame->v = p;
82350  pFrame->nChildMem = nMem;
82351  pFrame->nChildCsr = pProgram->nCsr;
82352  pFrame->pc = (int)(pOp - aOp);
82353  pFrame->aMem = p->aMem;
82354  pFrame->nMem = p->nMem;
82355  pFrame->apCsr = p->apCsr;
82356  pFrame->nCursor = p->nCursor;
82357  pFrame->aOp = p->aOp;
82358  pFrame->nOp = p->nOp;
82359  pFrame->token = pProgram->token;
82360  pFrame->aOnceFlag = p->aOnceFlag;
82361  pFrame->nOnceFlag = p->nOnceFlag;
82362 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82363  pFrame->anExec = p->anExec;
82364 #endif
82365 
82366  pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
82367  for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
82368  pMem->flags = MEM_Undefined;
82369  pMem->db = db;
82370  }
82371  }else{
82372  pFrame = pRt->u.pFrame;
82373  assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem
82374  || (pProgram->nCsr==0 && pProgram->nMem+1==pFrame->nChildMem) );
82375  assert( pProgram->nCsr==pFrame->nChildCsr );
82376  assert( (int)(pOp - aOp)==pFrame->pc );
82377  }
82378 
82379  p->nFrame++;
82380  pFrame->pParent = p->pFrame;
82381  pFrame->lastRowid = lastRowid;
82382  pFrame->nChange = p->nChange;
82383  pFrame->nDbChange = p->db->nChange;
82384  assert( pFrame->pAuxData==0 );
82385  pFrame->pAuxData = p->pAuxData;
82386  p->pAuxData = 0;
82387  p->nChange = 0;
82388  p->pFrame = pFrame;
82389  p->aMem = aMem = VdbeFrameMem(pFrame);
82390  p->nMem = pFrame->nChildMem;
82391  p->nCursor = (u16)pFrame->nChildCsr;
82392  p->apCsr = (VdbeCursor **)&aMem[p->nMem];
82393  p->aOp = aOp = pProgram->aOp;
82394  p->nOp = pProgram->nOp;
82395  p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
82396  p->nOnceFlag = pProgram->nOnce;
82397 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
82398  p->anExec = 0;
82399 #endif
82400  pOp = &aOp[-1];
82401  memset(p->aOnceFlag, 0, p->nOnceFlag);
82402 
82403  break;
82404 }
82405 
82406 /* Opcode: Param P1 P2 * * *
82407 **
82408 ** This opcode is only ever present in sub-programs called via the
82409 ** OP_Program instruction. Copy a value currently stored in a memory
82410 ** cell of the calling (parent) frame to cell P2 in the current frames
82411 ** address space. This is used by trigger programs to access the new.*
82412 ** and old.* values.
82413 **
82414 ** The address of the cell in the parent frame is determined by adding
82415 ** the value of the P1 argument to the value of the P1 argument to the
82416 ** calling OP_Program instruction.
82417 */
82418 case OP_Param: { /* out2 */
82419  VdbeFrame *pFrame;
82420  Mem *pIn;
82421  pOut = out2Prerelease(p, pOp);
82422  pFrame = p->pFrame;
82423  pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
82425  break;
82426 }
82427 
82428 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
82429 
82430 #ifndef SQLITE_OMIT_FOREIGN_KEY
82431 /* Opcode: FkCounter P1 P2 * * *
82432 ** Synopsis: fkctr[P1]+=P2
82433 **
82434 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
82435 ** If P1 is non-zero, the database constraint counter is incremented
82436 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
82437 ** statement counter is incremented (immediate foreign key constraints).
82438 */
82439 case OP_FkCounter: {
82440  if( db->flags & SQLITE_DeferFKs ){
82441  db->nDeferredImmCons += pOp->p2;
82442  }else if( pOp->p1 ){
82443  db->nDeferredCons += pOp->p2;
82444  }else{
82445  p->nFkConstraint += pOp->p2;
82446  }
82447  break;
82448 }
82449 
82450 /* Opcode: FkIfZero P1 P2 * * *
82451 ** Synopsis: if fkctr[P1]==0 goto P2
82452 **
82453 ** This opcode tests if a foreign key constraint-counter is currently zero.
82454 ** If so, jump to instruction P2. Otherwise, fall through to the next
82455 ** instruction.
82456 **
82457 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
82458 ** is zero (the one that counts deferred constraint violations). If P1 is
82459 ** zero, the jump is taken if the statement constraint-counter is zero
82460 ** (immediate foreign key constraint violations).
82461 */
82462 case OP_FkIfZero: { /* jump */
82463  if( pOp->p1 ){
82464  VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
82465  if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82466  }else{
82467  VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
82468  if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) goto jump_to_p2;
82469  }
82470  break;
82471 }
82472 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
82473 
82474 #ifndef SQLITE_OMIT_AUTOINCREMENT
82475 /* Opcode: MemMax P1 P2 * * *
82476 ** Synopsis: r[P1]=max(r[P1],r[P2])
82477 **
82478 ** P1 is a register in the root frame of this VM (the root frame is
82479 ** different from the current frame if this instruction is being executed
82480 ** within a sub-program). Set the value of register P1 to the maximum of
82481 ** its current value and the value in register P2.
82482 **
82483 ** This instruction throws an error if the memory cell is not initially
82484 ** an integer.
82485 */
82486 case OP_MemMax: { /* in2 */
82487  VdbeFrame *pFrame;
82488  if( p->pFrame ){
82489  for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
82490  pIn1 = &pFrame->aMem[pOp->p1];
82491  }else{
82492  pIn1 = &aMem[pOp->p1];
82493  }
82494  assert( memIsValid(pIn1) );
82496  pIn2 = &aMem[pOp->p2];
82498  if( pIn1->u.i<pIn2->u.i){
82499  pIn1->u.i = pIn2->u.i;
82500  }
82501  break;
82502 }
82503 #endif /* SQLITE_OMIT_AUTOINCREMENT */
82504 
82505 /* Opcode: IfPos P1 P2 P3 * *
82506 ** Synopsis: if r[P1]>0 then r[P1]-=P3, goto P2
82507 **
82508 ** Register P1 must contain an integer.
82509 ** If the value of register P1 is 1 or greater, subtract P3 from the
82510 ** value in P1 and jump to P2.
82511 **
82512 ** If the initial value of register P1 is less than 1, then the
82513 ** value is unchanged and control passes through to the next instruction.
82514 */
82515 case OP_IfPos: { /* jump, in1 */
82516  pIn1 = &aMem[pOp->p1];
82517  assert( pIn1->flags&MEM_Int );
82518  VdbeBranchTaken( pIn1->u.i>0, 2);
82519  if( pIn1->u.i>0 ){
82520  pIn1->u.i -= pOp->p3;
82521  goto jump_to_p2;
82522  }
82523  break;
82524 }
82525 
82526 /* Opcode: OffsetLimit P1 P2 P3 * *
82527 ** Synopsis: if r[P1]>0 then r[P2]=r[P1]+max(0,r[P3]) else r[P2]=(-1)
82528 **
82529 ** This opcode performs a commonly used computation associated with
82530 ** LIMIT and OFFSET process. r[P1] holds the limit counter. r[P3]
82531 ** holds the offset counter. The opcode computes the combined value
82532 ** of the LIMIT and OFFSET and stores that value in r[P2]. The r[P2]
82533 ** value computed is the total number of rows that will need to be
82534 ** visited in order to complete the query.
82535 **
82536 ** If r[P3] is zero or negative, that means there is no OFFSET
82537 ** and r[P2] is set to be the value of the LIMIT, r[P1].
82538 **
82539 ** if r[P1] is zero or negative, that means there is no LIMIT
82540 ** and r[P2] is set to -1.
82541 **
82542 ** Otherwise, r[P2] is set to the sum of r[P1] and r[P3].
82543 */
82544 case OP_OffsetLimit: { /* in1, out2, in3 */
82545  pIn1 = &aMem[pOp->p1];
82546  pIn3 = &aMem[pOp->p3];
82547  pOut = out2Prerelease(p, pOp);
82548  assert( pIn1->flags & MEM_Int );
82549  assert( pIn3->flags & MEM_Int );
82550  pOut->u.i = pIn1->u.i<=0 ? -1 : pIn1->u.i+(pIn3->u.i>0?pIn3->u.i:0);
82551  break;
82552 }
82553 
82554 /* Opcode: IfNotZero P1 P2 P3 * *
82555 ** Synopsis: if r[P1]!=0 then r[P1]-=P3, goto P2
82556 **
82557 ** Register P1 must contain an integer. If the content of register P1 is
82558 ** initially nonzero, then subtract P3 from the value in register P1 and
82559 ** jump to P2. If register P1 is initially zero, leave it unchanged
82560 ** and fall through.
82561 */
82562 case OP_IfNotZero: { /* jump, in1 */
82563  pIn1 = &aMem[pOp->p1];
82564  assert( pIn1->flags&MEM_Int );
82565  VdbeBranchTaken(pIn1->u.i<0, 2);
82566  if( pIn1->u.i ){
82567  pIn1->u.i -= pOp->p3;
82568  goto jump_to_p2;
82569  }
82570  break;
82571 }
82572 
82573 /* Opcode: DecrJumpZero P1 P2 * * *
82574 ** Synopsis: if (--r[P1])==0 goto P2
82575 **
82576 ** Register P1 must hold an integer. Decrement the value in register P1
82577 ** then jump to P2 if the new value is exactly zero.
82578 */
82579 case OP_DecrJumpZero: { /* jump, in1 */
82580  pIn1 = &aMem[pOp->p1];
82581  assert( pIn1->flags&MEM_Int );
82582  pIn1->u.i--;
82583  VdbeBranchTaken(pIn1->u.i==0, 2);
82584  if( pIn1->u.i==0 ) goto jump_to_p2;
82585  break;
82586 }
82587 
82588 
82589 /* Opcode: AggStep0 * P2 P3 P4 P5
82590 ** Synopsis: accum=r[P3] step(r[P2@P5])
82591 **
82592 ** Execute the step function for an aggregate. The
82593 ** function has P5 arguments. P4 is a pointer to the FuncDef
82594 ** structure that specifies the function. Register P3 is the
82595 ** accumulator.
82596 **
82597 ** The P5 arguments are taken from register P2 and its
82598 ** successors.
82599 */
82600 /* Opcode: AggStep * P2 P3 P4 P5
82601 ** Synopsis: accum=r[P3] step(r[P2@P5])
82602 **
82603 ** Execute the step function for an aggregate. The
82604 ** function has P5 arguments. P4 is a pointer to an sqlite3_context
82605 ** object that is used to run the function. Register P3 is
82606 ** as the accumulator.
82607 **
82608 ** The P5 arguments are taken from register P2 and its
82609 ** successors.
82610 **
82611 ** This opcode is initially coded as OP_AggStep0. On first evaluation,
82612 ** the FuncDef stored in P4 is converted into an sqlite3_context and
82613 ** the opcode is changed. In this way, the initialization of the
82614 ** sqlite3_context only happens once, instead of on each call to the
82615 ** step function.
82616 */
82617 case OP_AggStep0: {
82618  int n;
82619  sqlite3_context *pCtx;
82620 
82621  assert( pOp->p4type==P4_FUNCDEF );
82622  n = pOp->p5;
82623  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
82624  assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem+1 - p->nCursor)+1) );
82625  assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
82626  pCtx = sqlite3DbMallocRawNN(db, sizeof(*pCtx) + (n-1)*sizeof(sqlite3_value*));
82627  if( pCtx==0 ) goto no_mem;
82628  pCtx->pMem = 0;
82629  pCtx->pFunc = pOp->p4.pFunc;
82630  pCtx->iOp = (int)(pOp - aOp);
82631  pCtx->pVdbe = p;
82632  pCtx->argc = n;
82633  pOp->p4type = P4_FUNCCTX;
82634  pOp->p4.pCtx = pCtx;
82635  pOp->opcode = OP_AggStep;
82636  /* Fall through into OP_AggStep */
82637 }
82638 case OP_AggStep: {
82639  int i;
82640  sqlite3_context *pCtx;
82641  Mem *pMem;
82642  Mem t;
82643 
82644  assert( pOp->p4type==P4_FUNCCTX );
82645  pCtx = pOp->p4.pCtx;
82646  pMem = &aMem[pOp->p3];
82647 
82648  /* If this function is inside of a trigger, the register array in aMem[]
82649  ** might change from one evaluation to the next. The next block of code
82650  ** checks to see if the register array has changed, and if so it
82651  ** reinitializes the relavant parts of the sqlite3_context object */
82652  if( pCtx->pMem != pMem ){
82653  pCtx->pMem = pMem;
82654  for(i=pCtx->argc-1; i>=0; i--) pCtx->argv[i] = &aMem[pOp->p2+i];
82655  }
82656 
82657 #ifdef SQLITE_DEBUG
82658  for(i=0; i<pCtx->argc; i++){
82659  assert( memIsValid(pCtx->argv[i]) );
82660  REGISTER_TRACE(pOp->p2+i, pCtx->argv[i]);
82661  }
82662 #endif
82663 
82664  pMem->n++;
82665  sqlite3VdbeMemInit(&t, db, MEM_Null);
82666  pCtx->pOut = &t;
82667  pCtx->fErrorOrAux = 0;
82668  pCtx->skipFlag = 0;
82669  (pCtx->pFunc->xSFunc)(pCtx,pCtx->argc,pCtx->argv); /* IMP: R-24505-23230 */
82670  if( pCtx->fErrorOrAux ){
82671  if( pCtx->isError ){
82672  sqlite3VdbeError(p, "%s", sqlite3_value_text(&t));
82673  rc = pCtx->isError;
82674  }
82676  if( rc ) goto abort_due_to_error;
82677  }else{
82678  assert( t.flags==MEM_Null );
82679  }
82680  if( pCtx->skipFlag ){
82681  assert( pOp[-1].opcode==OP_CollSeq );
82682  i = pOp[-1].p1;
82683  if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
82684  }
82685  break;
82686 }
82687 
82688 /* Opcode: AggFinal P1 P2 * P4 *
82689 ** Synopsis: accum=r[P1] N=P2
82690 **
82691 ** Execute the finalizer function for an aggregate. P1 is
82692 ** the memory location that is the accumulator for the aggregate.
82693 **
82694 ** P2 is the number of arguments that the step function takes and
82695 ** P4 is a pointer to the FuncDef for this function. The P2
82696 ** argument is not used by this opcode. It is only there to disambiguate
82697 ** functions that can take varying numbers of arguments. The
82698 ** P4 argument is only needed for the degenerate case where
82699 ** the step function was not previously called.
82700 */
82701 case OP_AggFinal: {
82702  Mem *pMem;
82703  assert( pOp->p1>0 && pOp->p1<=(p->nMem+1 - p->nCursor) );
82704  pMem = &aMem[pOp->p1];
82705  assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
82706  rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
82707  if( rc ){
82708  sqlite3VdbeError(p, "%s", sqlite3_value_text(pMem));
82709  goto abort_due_to_error;
82710  }
82711  sqlite3VdbeChangeEncoding(pMem, encoding);
82712  UPDATE_MAX_BLOBSIZE(pMem);
82713  if( sqlite3VdbeMemTooBig(pMem) ){
82714  goto too_big;
82715  }
82716  break;
82717 }
82718 
82719 #ifndef SQLITE_OMIT_WAL
82720 /* Opcode: Checkpoint P1 P2 P3 * *
82721 **
82722 ** Checkpoint database P1. This is a no-op if P1 is not currently in
82723 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
82724 ** RESTART, or TRUNCATE. Write 1 or 0 into mem[P3] if the checkpoint returns
82725 ** SQLITE_BUSY or not, respectively. Write the number of pages in the
82726 ** WAL after the checkpoint into mem[P3+1] and the number of pages
82727 ** in the WAL that have been checkpointed after the checkpoint
82728 ** completes into mem[P3+2]. However on an error, mem[P3+1] and
82729 ** mem[P3+2] are initialized to -1.
82730 */
82731 case OP_Checkpoint: {
82732  int i; /* Loop counter */
82733  int aRes[3]; /* Results */
82734  Mem *pMem; /* Write results here */
82735 
82736  assert( p->readOnly==0 );
82737  aRes[0] = 0;
82738  aRes[1] = aRes[2] = -1;
82740  || pOp->p2==SQLITE_CHECKPOINT_FULL
82741  || pOp->p2==SQLITE_CHECKPOINT_RESTART
82743  );
82744  rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
82745  if( rc ){
82746  if( rc!=SQLITE_BUSY ) goto abort_due_to_error;
82747  rc = SQLITE_OK;
82748  aRes[0] = 1;
82749  }
82750  for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
82751  sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
82752  }
82753  break;
82754 };
82755 #endif
82756 
82757 #ifndef SQLITE_OMIT_PRAGMA
82758 /* Opcode: JournalMode P1 P2 P3 * *
82759 **
82760 ** Change the journal mode of database P1 to P3. P3 must be one of the
82761 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
82762 ** modes (delete, truncate, persist, off and memory), this is a simple
82763 ** operation. No IO is required.
82764 **
82765 ** If changing into or out of WAL mode the procedure is more complicated.
82766 **
82767 ** Write a string containing the final journal-mode to register P2.
82768 */
82769 case OP_JournalMode: { /* out2 */
82770  Btree *pBt; /* Btree to change journal mode of */
82771  Pager *pPager; /* Pager associated with pBt */
82772  int eNew; /* New journal mode */
82773  int eOld; /* The old journal mode */
82774 #ifndef SQLITE_OMIT_WAL
82775  const char *zFilename; /* Name of database file for pPager */
82776 #endif
82777 
82778  pOut = out2Prerelease(p, pOp);
82779  eNew = pOp->p3;
82781  || eNew==PAGER_JOURNALMODE_TRUNCATE
82782  || eNew==PAGER_JOURNALMODE_PERSIST
82783  || eNew==PAGER_JOURNALMODE_OFF
82784  || eNew==PAGER_JOURNALMODE_MEMORY
82785  || eNew==PAGER_JOURNALMODE_WAL
82786  || eNew==PAGER_JOURNALMODE_QUERY
82787  );
82788  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82789  assert( p->readOnly==0 );
82790 
82791  pBt = db->aDb[pOp->p1].pBt;
82792  pPager = sqlite3BtreePager(pBt);
82793  eOld = sqlite3PagerGetJournalMode(pPager);
82794  if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
82795  if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
82796 
82797 #ifndef SQLITE_OMIT_WAL
82798  zFilename = sqlite3PagerFilename(pPager, 1);
82799 
82800  /* Do not allow a transition to journal_mode=WAL for a database
82801  ** in temporary storage or if the VFS does not support shared memory
82802  */
82803  if( eNew==PAGER_JOURNALMODE_WAL
82804  && (sqlite3Strlen30(zFilename)==0 /* Temp file */
82805  || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
82806  ){
82807  eNew = eOld;
82808  }
82809 
82810  if( (eNew!=eOld)
82811  && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
82812  ){
82813  if( !db->autoCommit || db->nVdbeRead>1 ){
82814  rc = SQLITE_ERROR;
82815  sqlite3VdbeError(p,
82816  "cannot change %s wal mode from within a transaction",
82817  (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
82818  );
82819  goto abort_due_to_error;
82820  }else{
82821 
82822  if( eOld==PAGER_JOURNALMODE_WAL ){
82823  /* If leaving WAL mode, close the log file. If successful, the call
82824  ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
82825  ** file. An EXCLUSIVE lock may still be held on the database file
82826  ** after a successful return.
82827  */
82828  rc = sqlite3PagerCloseWal(pPager);
82829  if( rc==SQLITE_OK ){
82830  sqlite3PagerSetJournalMode(pPager, eNew);
82831  }
82832  }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
82833  /* Cannot transition directly from MEMORY to WAL. Use mode OFF
82834  ** as an intermediate */
82836  }
82837 
82838  /* Open a transaction on the database file. Regardless of the journal
82839  ** mode, this transaction always uses a rollback journal.
82840  */
82841  assert( sqlite3BtreeIsInTrans(pBt)==0 );
82842  if( rc==SQLITE_OK ){
82843  rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
82844  }
82845  }
82846  }
82847 #endif /* ifndef SQLITE_OMIT_WAL */
82848 
82849  if( rc ) eNew = eOld;
82850  eNew = sqlite3PagerSetJournalMode(pPager, eNew);
82851 
82852  pOut->flags = MEM_Str|MEM_Static|MEM_Term;
82853  pOut->z = (char *)sqlite3JournalModename(eNew);
82854  pOut->n = sqlite3Strlen30(pOut->z);
82855  pOut->enc = SQLITE_UTF8;
82856  sqlite3VdbeChangeEncoding(pOut, encoding);
82857  if( rc ) goto abort_due_to_error;
82858  break;
82859 };
82860 #endif /* SQLITE_OMIT_PRAGMA */
82861 
82862 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
82863 /* Opcode: Vacuum * * * * *
82864 **
82865 ** Vacuum the entire database. This opcode will cause other virtual
82866 ** machines to be created and run. It may not be called from within
82867 ** a transaction.
82868 */
82869 case OP_Vacuum: {
82870  assert( p->readOnly==0 );
82871  rc = sqlite3RunVacuum(&p->zErrMsg, db);
82872  if( rc ) goto abort_due_to_error;
82873  break;
82874 }
82875 #endif
82876 
82877 #if !defined(SQLITE_OMIT_AUTOVACUUM)
82878 /* Opcode: IncrVacuum P1 P2 * * *
82879 **
82880 ** Perform a single step of the incremental vacuum procedure on
82881 ** the P1 database. If the vacuum has finished, jump to instruction
82882 ** P2. Otherwise, fall through to the next instruction.
82883 */
82884 case OP_IncrVacuum: { /* jump */
82885  Btree *pBt;
82886 
82887  assert( pOp->p1>=0 && pOp->p1<db->nDb );
82888  assert( DbMaskTest(p->btreeMask, pOp->p1) );
82889  assert( p->readOnly==0 );
82890  pBt = db->aDb[pOp->p1].pBt;
82891  rc = sqlite3BtreeIncrVacuum(pBt);
82893  if( rc ){
82894  if( rc!=SQLITE_DONE ) goto abort_due_to_error;
82895  rc = SQLITE_OK;
82896  goto jump_to_p2;
82897  }
82898  break;
82899 }
82900 #endif
82901 
82902 /* Opcode: Expire P1 * * * *
82903 **
82904 ** Cause precompiled statements to expire. When an expired statement
82905 ** is executed using sqlite3_step() it will either automatically
82906 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
82907 ** or it will fail with SQLITE_SCHEMA.
82908 **
82909 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
82910 ** then only the currently executing statement is expired.
82911 */
82912 case OP_Expire: {
82913  if( !pOp->p1 ){
82915  }else{
82916  p->expired = 1;
82917  }
82918  break;
82919 }
82920 
82921 #ifndef SQLITE_OMIT_SHARED_CACHE
82922 /* Opcode: TableLock P1 P2 P3 P4 *
82923 ** Synopsis: iDb=P1 root=P2 write=P3
82924 **
82925 ** Obtain a lock on a particular table. This instruction is only used when
82926 ** the shared-cache feature is enabled.
82927 **
82928 ** P1 is the index of the database in sqlite3.aDb[] of the database
82929 ** on which the lock is acquired. A readlock is obtained if P3==0 or
82930 ** a write lock if P3==1.
82931 **
82932 ** P2 contains the root-page of the table to lock.
82933 **
82934 ** P4 contains a pointer to the name of the table being locked. This is only
82935 ** used to generate an error message if the lock cannot be obtained.
82936 */
82937 case OP_TableLock: {
82938  u8 isWriteLock = (u8)pOp->p3;
82939  if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
82940  int p1 = pOp->p1;
82941  assert( p1>=0 && p1<db->nDb );
82942  assert( DbMaskTest(p->btreeMask, p1) );
82943  assert( isWriteLock==0 || isWriteLock==1 );
82944  rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
82945  if( rc ){
82946  if( (rc&0xFF)==SQLITE_LOCKED ){
82947  const char *z = pOp->p4.z;
82948  sqlite3VdbeError(p, "database table is locked: %s", z);
82949  }
82950  goto abort_due_to_error;
82951  }
82952  }
82953  break;
82954 }
82955 #endif /* SQLITE_OMIT_SHARED_CACHE */
82956 
82957 #ifndef SQLITE_OMIT_VIRTUALTABLE
82958 /* Opcode: VBegin * * * P4 *
82959 **
82960 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
82961 ** xBegin method for that table.
82962 **
82963 ** Also, whether or not P4 is set, check that this is not being called from
82964 ** within a callback to a virtual table xSync() method. If it is, the error
82965 ** code will be set to SQLITE_LOCKED.
82966 */
82967 case OP_VBegin: {
82968  VTable *pVTab;
82969  pVTab = pOp->p4.pVtab;
82970  rc = sqlite3VtabBegin(db, pVTab);
82971  if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
82972  if( rc ) goto abort_due_to_error;
82973  break;
82974 }
82975 #endif /* SQLITE_OMIT_VIRTUALTABLE */
82976 
82977 #ifndef SQLITE_OMIT_VIRTUALTABLE
82978 /* Opcode: VCreate P1 P2 * * *
82979 **
82980 ** P2 is a register that holds the name of a virtual table in database
82981 ** P1. Call the xCreate method for that table.
82982 */
82983 case OP_VCreate: {
82984  Mem sMem; /* For storing the record being decoded */
82985  const char *zTab; /* Name of the virtual table */
82986 
82987  memset(&sMem, 0, sizeof(sMem));
82988  sMem.db = db;
82989  /* Because P2 is always a static string, it is impossible for the
82990  ** sqlite3VdbeMemCopy() to fail */
82991  assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
82992  assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
82993  rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
82994  assert( rc==SQLITE_OK );
82995  zTab = (const char*)sqlite3_value_text(&sMem);
82996  assert( zTab || db->mallocFailed );
82997  if( zTab ){
82998  rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
82999  }
83000  sqlite3VdbeMemRelease(&sMem);
83001  if( rc ) goto abort_due_to_error;
83002  break;
83003 }
83004 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83005 
83006 #ifndef SQLITE_OMIT_VIRTUALTABLE
83007 /* Opcode: VDestroy P1 * * P4 *
83008 **
83009 ** P4 is the name of a virtual table in database P1. Call the xDestroy method
83010 ** of that table.
83011 */
83012 case OP_VDestroy: {
83013  db->nVDestroy++;
83014  rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
83015  db->nVDestroy--;
83016  if( rc ) goto abort_due_to_error;
83017  break;
83018 }
83019 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83020 
83021 #ifndef SQLITE_OMIT_VIRTUALTABLE
83022 /* Opcode: VOpen P1 * * P4 *
83023 **
83024 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83025 ** P1 is a cursor number. This opcode opens a cursor to the virtual
83026 ** table and stores that cursor in P1.
83027 */
83028 case OP_VOpen: {
83029  VdbeCursor *pCur;
83030  sqlite3_vtab_cursor *pVCur;
83031  sqlite3_vtab *pVtab;
83032  const sqlite3_module *pModule;
83033 
83034  assert( p->bIsReader );
83035  pCur = 0;
83036  pVCur = 0;
83037  pVtab = pOp->p4.pVtab->pVtab;
83038  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83039  rc = SQLITE_LOCKED;
83040  goto abort_due_to_error;
83041  }
83042  pModule = pVtab->pModule;
83043  rc = pModule->xOpen(pVtab, &pVCur);
83044  sqlite3VtabImportErrmsg(p, pVtab);
83045  if( rc ) goto abort_due_to_error;
83046 
83047  /* Initialize sqlite3_vtab_cursor base class */
83048  pVCur->pVtab = pVtab;
83049 
83050  /* Initialize vdbe cursor object */
83051  pCur = allocateCursor(p, pOp->p1, 0, -1, CURTYPE_VTAB);
83052  if( pCur ){
83053  pCur->uc.pVCur = pVCur;
83054  pVtab->nRef++;
83055  }else{
83056  assert( db->mallocFailed );
83057  pModule->xClose(pVCur);
83058  goto no_mem;
83059  }
83060  break;
83061 }
83062 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83063 
83064 #ifndef SQLITE_OMIT_VIRTUALTABLE
83065 /* Opcode: VFilter P1 P2 P3 P4 *
83066 ** Synopsis: iplan=r[P3] zplan='P4'
83067 **
83068 ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
83069 ** the filtered result set is empty.
83070 **
83071 ** P4 is either NULL or a string that was generated by the xBestIndex
83072 ** method of the module. The interpretation of the P4 string is left
83073 ** to the module implementation.
83074 **
83075 ** This opcode invokes the xFilter method on the virtual table specified
83076 ** by P1. The integer query plan parameter to xFilter is stored in register
83077 ** P3. Register P3+1 stores the argc parameter to be passed to the
83078 ** xFilter method. Registers P3+2..P3+1+argc are the argc
83079 ** additional parameters which are passed to
83080 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
83081 **
83082 ** A jump is made to P2 if the result set after filtering would be empty.
83083 */
83084 case OP_VFilter: { /* jump */
83085  int nArg;
83086  int iQuery;
83087  const sqlite3_module *pModule;
83088  Mem *pQuery;
83089  Mem *pArgc;
83090  sqlite3_vtab_cursor *pVCur;
83091  sqlite3_vtab *pVtab;
83092  VdbeCursor *pCur;
83093  int res;
83094  int i;
83095  Mem **apArg;
83096 
83097  pQuery = &aMem[pOp->p3];
83098  pArgc = &pQuery[1];
83099  pCur = p->apCsr[pOp->p1];
83100  assert( memIsValid(pQuery) );
83101  REGISTER_TRACE(pOp->p3, pQuery);
83102  assert( pCur->eCurType==CURTYPE_VTAB );
83103  pVCur = pCur->uc.pVCur;
83104  pVtab = pVCur->pVtab;
83105  pModule = pVtab->pModule;
83106 
83107  /* Grab the index number and argc parameters */
83108  assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
83109  nArg = (int)pArgc->u.i;
83110  iQuery = (int)pQuery->u.i;
83111 
83112  /* Invoke the xFilter method */
83113  res = 0;
83114  apArg = p->apArg;
83115  for(i = 0; i<nArg; i++){
83116  apArg[i] = &pArgc[i+1];
83117  }
83118  rc = pModule->xFilter(pVCur, iQuery, pOp->p4.z, nArg, apArg);
83119  sqlite3VtabImportErrmsg(p, pVtab);
83120  if( rc ) goto abort_due_to_error;
83121  res = pModule->xEof(pVCur);
83122  pCur->nullRow = 0;
83123  VdbeBranchTaken(res!=0,2);
83124  if( res ) goto jump_to_p2;
83125  break;
83126 }
83127 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83128 
83129 #ifndef SQLITE_OMIT_VIRTUALTABLE
83130 /* Opcode: VColumn P1 P2 P3 * *
83131 ** Synopsis: r[P3]=vcolumn(P2)
83132 **
83133 ** Store the value of the P2-th column of
83134 ** the row of the virtual-table that the
83135 ** P1 cursor is pointing to into register P3.
83136 */
83137 case OP_VColumn: {
83138  sqlite3_vtab *pVtab;
83139  const sqlite3_module *pModule;
83140  Mem *pDest;
83141  sqlite3_context sContext;
83142 
83143  VdbeCursor *pCur = p->apCsr[pOp->p1];
83144  assert( pCur->eCurType==CURTYPE_VTAB );
83145  assert( pOp->p3>0 && pOp->p3<=(p->nMem+1 - p->nCursor) );
83146  pDest = &aMem[pOp->p3];
83147  memAboutToChange(p, pDest);
83148  if( pCur->nullRow ){
83149  sqlite3VdbeMemSetNull(pDest);
83150  break;
83151  }
83152  pVtab = pCur->uc.pVCur->pVtab;
83153  pModule = pVtab->pModule;
83154  assert( pModule->xColumn );
83155  memset(&sContext, 0, sizeof(sContext));
83156  sContext.pOut = pDest;
83157  MemSetTypeFlag(pDest, MEM_Null);
83158  rc = pModule->xColumn(pCur->uc.pVCur, &sContext, pOp->p2);
83159  sqlite3VtabImportErrmsg(p, pVtab);
83160  if( sContext.isError ){
83161  rc = sContext.isError;
83162  }
83163  sqlite3VdbeChangeEncoding(pDest, encoding);
83164  REGISTER_TRACE(pOp->p3, pDest);
83165  UPDATE_MAX_BLOBSIZE(pDest);
83166 
83167  if( sqlite3VdbeMemTooBig(pDest) ){
83168  goto too_big;
83169  }
83170  if( rc ) goto abort_due_to_error;
83171  break;
83172 }
83173 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83174 
83175 #ifndef SQLITE_OMIT_VIRTUALTABLE
83176 /* Opcode: VNext P1 P2 * * *
83177 **
83178 ** Advance virtual table P1 to the next row in its result set and
83179 ** jump to instruction P2. Or, if the virtual table has reached
83180 ** the end of its result set, then fall through to the next instruction.
83181 */
83182 case OP_VNext: { /* jump */
83183  sqlite3_vtab *pVtab;
83184  const sqlite3_module *pModule;
83185  int res;
83186  VdbeCursor *pCur;
83187 
83188  res = 0;
83189  pCur = p->apCsr[pOp->p1];
83190  assert( pCur->eCurType==CURTYPE_VTAB );
83191  if( pCur->nullRow ){
83192  break;
83193  }
83194  pVtab = pCur->uc.pVCur->pVtab;
83195  pModule = pVtab->pModule;
83196  assert( pModule->xNext );
83197 
83198  /* Invoke the xNext() method of the module. There is no way for the
83199  ** underlying implementation to return an error if one occurs during
83200  ** xNext(). Instead, if an error occurs, true is returned (indicating that
83201  ** data is available) and the error code returned when xColumn or
83202  ** some other method is next invoked on the save virtual table cursor.
83203  */
83204  rc = pModule->xNext(pCur->uc.pVCur);
83205  sqlite3VtabImportErrmsg(p, pVtab);
83206  if( rc ) goto abort_due_to_error;
83207  res = pModule->xEof(pCur->uc.pVCur);
83208  VdbeBranchTaken(!res,2);
83209  if( !res ){
83210  /* If there is data, jump to P2 */
83211  goto jump_to_p2_and_check_for_interrupt;
83212  }
83213  goto check_for_interrupt;
83214 }
83215 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83216 
83217 #ifndef SQLITE_OMIT_VIRTUALTABLE
83218 /* Opcode: VRename P1 * * P4 *
83219 **
83220 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83221 ** This opcode invokes the corresponding xRename method. The value
83222 ** in register P1 is passed as the zName argument to the xRename method.
83223 */
83224 case OP_VRename: {
83225  sqlite3_vtab *pVtab;
83226  Mem *pName;
83227 
83228  pVtab = pOp->p4.pVtab->pVtab;
83229  pName = &aMem[pOp->p1];
83230  assert( pVtab->pModule->xRename );
83231  assert( memIsValid(pName) );
83232  assert( p->readOnly==0 );
83233  REGISTER_TRACE(pOp->p1, pName);
83234  assert( pName->flags & MEM_Str );
83235  testcase( pName->enc==SQLITE_UTF8 );
83236  testcase( pName->enc==SQLITE_UTF16BE );
83237  testcase( pName->enc==SQLITE_UTF16LE );
83239  if( rc ) goto abort_due_to_error;
83240  rc = pVtab->pModule->xRename(pVtab, pName->z);
83241  sqlite3VtabImportErrmsg(p, pVtab);
83242  p->expired = 0;
83243  if( rc ) goto abort_due_to_error;
83244  break;
83245 }
83246 #endif
83247 
83248 #ifndef SQLITE_OMIT_VIRTUALTABLE
83249 /* Opcode: VUpdate P1 P2 P3 P4 P5
83250 ** Synopsis: data=r[P3@P2]
83251 **
83252 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
83253 ** This opcode invokes the corresponding xUpdate method. P2 values
83254 ** are contiguous memory cells starting at P3 to pass to the xUpdate
83255 ** invocation. The value in register (P3+P2-1) corresponds to the
83256 ** p2th element of the argv array passed to xUpdate.
83257 **
83258 ** The xUpdate method will do a DELETE or an INSERT or both.
83259 ** The argv[0] element (which corresponds to memory cell P3)
83260 ** is the rowid of a row to delete. If argv[0] is NULL then no
83261 ** deletion occurs. The argv[1] element is the rowid of the new
83262 ** row. This can be NULL to have the virtual table select the new
83263 ** rowid for itself. The subsequent elements in the array are
83264 ** the values of columns in the new row.
83265 **
83266 ** If P2==1 then no insert is performed. argv[0] is the rowid of
83267 ** a row to delete.
83268 **
83269 ** P1 is a boolean flag. If it is set to true and the xUpdate call
83270 ** is successful, then the value returned by sqlite3_last_insert_rowid()
83271 ** is set to the value of the rowid for the row just inserted.
83272 **
83273 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
83274 ** apply in the case of a constraint failure on an insert or update.
83275 */
83276 case OP_VUpdate: {
83277  sqlite3_vtab *pVtab;
83278  const sqlite3_module *pModule;
83279  int nArg;
83280  int i;
83281  sqlite_int64 rowid;
83282  Mem **apArg;
83283  Mem *pX;
83284 
83285  assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
83286  || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
83287  );
83288  assert( p->readOnly==0 );
83289  pVtab = pOp->p4.pVtab->pVtab;
83290  if( pVtab==0 || NEVER(pVtab->pModule==0) ){
83291  rc = SQLITE_LOCKED;
83292  goto abort_due_to_error;
83293  }
83294  pModule = pVtab->pModule;
83295  nArg = pOp->p2;
83296  assert( pOp->p4type==P4_VTAB );
83297  if( ALWAYS(pModule->xUpdate) ){
83298  u8 vtabOnConflict = db->vtabOnConflict;
83299  apArg = p->apArg;
83300  pX = &aMem[pOp->p3];
83301  for(i=0; i<nArg; i++){
83302  assert( memIsValid(pX) );
83303  memAboutToChange(p, pX);
83304  apArg[i] = pX;
83305  pX++;
83306  }
83307  db->vtabOnConflict = pOp->p5;
83308  rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
83309  db->vtabOnConflict = vtabOnConflict;
83310  sqlite3VtabImportErrmsg(p, pVtab);
83311  if( rc==SQLITE_OK && pOp->p1 ){
83312  assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
83313  db->lastRowid = lastRowid = rowid;
83314  }
83315  if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
83316  if( pOp->p5==OE_Ignore ){
83317  rc = SQLITE_OK;
83318  }else{
83319  p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
83320  }
83321  }else{
83322  p->nChange++;
83323  }
83324  if( rc ) goto abort_due_to_error;
83325  }
83326  break;
83327 }
83328 #endif /* SQLITE_OMIT_VIRTUALTABLE */
83329 
83330 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83331 /* Opcode: Pagecount P1 P2 * * *
83332 **
83333 ** Write the current number of pages in database P1 to memory cell P2.
83334 */
83335 case OP_Pagecount: { /* out2 */
83336  pOut = out2Prerelease(p, pOp);
83337  pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
83338  break;
83339 }
83340 #endif
83341 
83342 
83343 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
83344 /* Opcode: MaxPgcnt P1 P2 P3 * *
83345 **
83346 ** Try to set the maximum page count for database P1 to the value in P3.
83347 ** Do not let the maximum page count fall below the current page count and
83348 ** do not change the maximum page count value if P3==0.
83349 **
83350 ** Store the maximum page count after the change in register P2.
83351 */
83352 case OP_MaxPgcnt: { /* out2 */
83353  unsigned int newMax;
83354  Btree *pBt;
83355 
83356  pOut = out2Prerelease(p, pOp);
83357  pBt = db->aDb[pOp->p1].pBt;
83358  newMax = 0;
83359  if( pOp->p3 ){
83360  newMax = sqlite3BtreeLastPage(pBt);
83361  if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
83362  }
83363  pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
83364  break;
83365 }
83366 #endif
83367 
83368 
83369 /* Opcode: Init * P2 * P4 *
83370 ** Synopsis: Start at P2
83371 **
83372 ** Programs contain a single instance of this opcode as the very first
83373 ** opcode.
83374 **
83375 ** If tracing is enabled (by the sqlite3_trace()) interface, then
83376 ** the UTF-8 string contained in P4 is emitted on the trace callback.
83377 ** Or if P4 is blank, use the string returned by sqlite3_sql().
83378 **
83379 ** If P2 is not zero, jump to instruction P2.
83380 */
83381 case OP_Init: { /* jump */
83382  char *zTrace;
83383  char *z;
83384 
83385 #ifndef SQLITE_OMIT_TRACE
83386  if( db->xTrace
83387  && !p->doingRerun
83388  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83389  ){
83390  z = sqlite3VdbeExpandSql(p, zTrace);
83391  db->xTrace(db->pTraceArg, z);
83392  sqlite3DbFree(db, z);
83393  }
83394 #ifdef SQLITE_USE_FCNTL_TRACE
83395  zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
83396  if( zTrace ){
83397  int i;
83398  for(i=0; i<db->nDb; i++){
83399  if( DbMaskTest(p->btreeMask, i)==0 ) continue;
83400  sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
83401  }
83402  }
83403 #endif /* SQLITE_USE_FCNTL_TRACE */
83404 #ifdef SQLITE_DEBUG
83405  if( (db->flags & SQLITE_SqlTrace)!=0
83406  && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
83407  ){
83408  sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
83409  }
83410 #endif /* SQLITE_DEBUG */
83411 #endif /* SQLITE_OMIT_TRACE */
83412  if( pOp->p2 ) goto jump_to_p2;
83413  break;
83414 }
83415 
83416 #ifdef SQLITE_ENABLE_CURSOR_HINTS
83417 /* Opcode: CursorHint P1 * * P4 *
83418 **
83419 ** Provide a hint to cursor P1 that it only needs to return rows that
83420 ** satisfy the Expr in P4. TK_REGISTER terms in the P4 expression refer
83421 ** to values currently held in registers. TK_COLUMN terms in the P4
83422 ** expression refer to columns in the b-tree to which cursor P1 is pointing.
83423 */
83424 case OP_CursorHint: {
83425  VdbeCursor *pC;
83426 
83427  assert( pOp->p1>=0 && pOp->p1<p->nCursor );
83428  assert( pOp->p4type==P4_EXPR );
83429  pC = p->apCsr[pOp->p1];
83430  if( pC ){
83431  assert( pC->eCurType==CURTYPE_BTREE );
83432  sqlite3BtreeCursorHint(pC->uc.pCursor, BTREE_HINT_RANGE,
83433  pOp->p4.pExpr, aMem);
83434  }
83435  break;
83436 }
83437 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
83438 
83439 /* Opcode: Noop * * * * *
83440 **
83441 ** Do nothing. This instruction is often useful as a jump
83442 ** destination.
83443 */
83444 /*
83445 ** The magic Explain opcode are only inserted when explain==2 (which
83446 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
83447 ** This opcode records information from the optimizer. It is the
83448 ** the same as a no-op. This opcodesnever appears in a real VM program.
83449 */
83450 default: { /* This is really OP_Noop and OP_Explain */
83451  assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
83452  break;
83453 }
83454 
83455 /*****************************************************************************
83456 ** The cases of the switch statement above this line should all be indented
83457 ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
83458 ** readability. From this point on down, the normal indentation rules are
83459 ** restored.
83460 *****************************************************************************/
83461  }
83462 
83463 #ifdef VDBE_PROFILE
83464  {
83465  u64 endTime = sqlite3Hwtime();
83466  if( endTime>start ) pOrigOp->cycles += endTime - start;
83467  pOrigOp->cnt++;
83468  }
83469 #endif
83470 
83471  /* The following code adds nothing to the actual functionality
83472  ** of the program. It is only here for testing and debugging.
83473  ** On the other hand, it does burn CPU cycles every time through
83474  ** the evaluator loop. So we can leave it out when NDEBUG is defined.
83475  */
83476 #ifndef NDEBUG
83477  assert( pOp>=&aOp[-1] && pOp<&aOp[p->nOp-1] );
83478 
83479 #ifdef SQLITE_DEBUG
83480  if( db->flags & SQLITE_VdbeTrace ){
83481  u8 opProperty = sqlite3OpcodeProperty[pOrigOp->opcode];
83482  if( rc!=0 ) printf("rc=%d\n",rc);
83483  if( opProperty & (OPFLG_OUT2) ){
83484  registerTrace(pOrigOp->p2, &aMem[pOrigOp->p2]);
83485  }
83486  if( opProperty & OPFLG_OUT3 ){
83487  registerTrace(pOrigOp->p3, &aMem[pOrigOp->p3]);
83488  }
83489  }
83490 #endif /* SQLITE_DEBUG */
83491 #endif /* NDEBUG */
83492  } /* The end of the for(;;) loop the loops through opcodes */
83493 
83494  /* If we reach this point, it means that execution is finished with
83495  ** an error of some kind.
83496  */
83497 abort_due_to_error:
83498  if( db->mallocFailed ) rc = SQLITE_NOMEM_BKPT;
83499  assert( rc );
83500  if( p->zErrMsg==0 && rc!=SQLITE_IOERR_NOMEM ){
83501  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
83502  }
83503  p->rc = rc;
83504  sqlite3SystemError(db, rc);
83505  testcase( sqlite3GlobalConfig.xLog!=0 );
83506  sqlite3_log(rc, "statement aborts at %d: [%s] %s",
83507  (int)(pOp - aOp), p->zSql, p->zErrMsg);
83508  sqlite3VdbeHalt(p);
83509  if( rc==SQLITE_IOERR_NOMEM ) sqlite3OomFault(db);
83510  rc = SQLITE_ERROR;
83511  if( resetSchemaOnFault>0 ){
83512  sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
83513  }
83514 
83515  /* This is the only way out of this procedure. We have to
83516  ** release the mutexes on btrees that were acquired at the
83517  ** top. */
83518 vdbe_return:
83519  db->lastRowid = lastRowid;
83520  testcase( nVmStep>0 );
83521  p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
83522  sqlite3VdbeLeave(p);
83523  assert( rc!=SQLITE_OK || nExtraDelete==0
83524  || sqlite3_strlike("DELETE%",p->zSql,0)!=0
83525  );
83526  return rc;
83527 
83528  /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
83529  ** is encountered.
83530  */
83531 too_big:
83532  sqlite3VdbeError(p, "string or blob too big");
83533  rc = SQLITE_TOOBIG;
83534  goto abort_due_to_error;
83535 
83536  /* Jump to here if a malloc() fails.
83537  */
83538 no_mem:
83539  sqlite3OomFault(db);
83540  sqlite3VdbeError(p, "out of memory");
83541  rc = SQLITE_NOMEM_BKPT;
83542  goto abort_due_to_error;
83543 
83544  /* Jump to here if the sqlite3_interrupt() API sets the interrupt
83545  ** flag.
83546  */
83547 abort_due_to_interrupt:
83548  assert( db->u1.isInterrupted );
83550  p->rc = rc;
83551  sqlite3VdbeError(p, "%s", sqlite3ErrStr(rc));
83552  goto abort_due_to_error;
83553 }
83554 
83555 
83556 /************** End of vdbe.c ************************************************/
83557 /************** Begin file vdbeblob.c ****************************************/
83558 /*
83559 ** 2007 May 1
83560 **
83561 ** The author disclaims copyright to this source code. In place of
83562 ** a legal notice, here is a blessing:
83563 **
83564 ** May you do good and not evil.
83565 ** May you find forgiveness for yourself and forgive others.
83566 ** May you share freely, never taking more than you give.
83567 **
83568 *************************************************************************
83569 **
83570 ** This file contains code used to implement incremental BLOB I/O.
83571 */
83572 
83573 /* #include "sqliteInt.h" */
83574 /* #include "vdbeInt.h" */
83575 
83576 #ifndef SQLITE_OMIT_INCRBLOB
83577 
83578 /*
83579 ** Valid sqlite3_blob* handles point to Incrblob structures.
83580 */
83581 typedef struct Incrblob Incrblob;
83582 struct Incrblob {
83583  int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
83584  int nByte; /* Size of open blob, in bytes */
83585  int iOffset; /* Byte offset of blob in cursor data */
83586  int iCol; /* Table column this handle is open on */
83587  BtCursor *pCsr; /* Cursor pointing at blob row */
83588  sqlite3_stmt *pStmt; /* Statement holding cursor open */
83589  sqlite3 *db; /* The associated database */
83590  char *zDb; /* Database name */
83591  Table *pTab; /* Table object */
83592 };
83593 
83594 
83595 /*
83596 ** This function is used by both blob_open() and blob_reopen(). It seeks
83597 ** the b-tree cursor associated with blob handle p to point to row iRow.
83598 ** If successful, SQLITE_OK is returned and subsequent calls to
83599 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
83600 **
83601 ** If an error occurs, or if the specified row does not exist or does not
83602 ** contain a value of type TEXT or BLOB in the column nominated when the
83603 ** blob handle was opened, then an error code is returned and *pzErr may
83604 ** be set to point to a buffer containing an error message. It is the
83605 ** responsibility of the caller to free the error message buffer using
83606 ** sqlite3DbFree().
83607 **
83608 ** If an error does occur, then the b-tree cursor is closed. All subsequent
83609 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
83610 ** immediately return SQLITE_ABORT.
83611 */
83612 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
83613  int rc; /* Error code */
83614  char *zErr = 0; /* Error message */
83615  Vdbe *v = (Vdbe *)p->pStmt;
83616 
83617  /* Set the value of the SQL statements only variable to integer iRow.
83618  ** This is done directly instead of using sqlite3_bind_int64() to avoid
83619  ** triggering asserts related to mutexes.
83620  */
83621  assert( v->aVar[0].flags&MEM_Int );
83622  v->aVar[0].u.i = iRow;
83623 
83624  rc = sqlite3_step(p->pStmt);
83625  if( rc==SQLITE_ROW ){
83626  VdbeCursor *pC = v->apCsr[0];
83627  u32 type = pC->aType[p->iCol];
83628  if( type<12 ){
83629  zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
83630  type==0?"null": type==7?"real": "integer"
83631  );
83632  rc = SQLITE_ERROR;
83633  sqlite3_finalize(p->pStmt);
83634  p->pStmt = 0;
83635  }else{
83636  p->iOffset = pC->aType[p->iCol + pC->nField];
83637  p->nByte = sqlite3VdbeSerialTypeLen(type);
83638  p->pCsr = pC->uc.pCursor;
83640  }
83641  }
83642 
83643  if( rc==SQLITE_ROW ){
83644  rc = SQLITE_OK;
83645  }else if( p->pStmt ){
83646  rc = sqlite3_finalize(p->pStmt);
83647  p->pStmt = 0;
83648  if( rc==SQLITE_OK ){
83649  zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
83650  rc = SQLITE_ERROR;
83651  }else{
83652  zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
83653  }
83654  }
83655 
83656  assert( rc!=SQLITE_OK || zErr==0 );
83657  assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
83658 
83659  *pzErr = zErr;
83660  return rc;
83661 }
83662 
83663 /*
83664 ** Open a blob handle.
83665 */
83667  sqlite3* db, /* The database connection */
83668  const char *zDb, /* The attached database containing the blob */
83669  const char *zTable, /* The table containing the blob */
83670  const char *zColumn, /* The column containing the blob */
83671  sqlite_int64 iRow, /* The row containing the glob */
83672  int flags, /* True -> read/write access, false -> read-only */
83673  sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
83674 ){
83675  int nAttempt = 0;
83676  int iCol; /* Index of zColumn in row-record */
83677  int rc = SQLITE_OK;
83678  char *zErr = 0;
83679  Table *pTab;
83680  Parse *pParse = 0;
83681  Incrblob *pBlob = 0;
83682 
83683 #ifdef SQLITE_ENABLE_API_ARMOR
83684  if( ppBlob==0 ){
83685  return SQLITE_MISUSE_BKPT;
83686  }
83687 #endif
83688  *ppBlob = 0;
83689 #ifdef SQLITE_ENABLE_API_ARMOR
83690  if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
83691  return SQLITE_MISUSE_BKPT;
83692  }
83693 #endif
83694  flags = !!flags; /* flags = (flags ? 1 : 0); */
83695 
83697 
83698  pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
83699  if( !pBlob ) goto blob_open_out;
83700  pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
83701  if( !pParse ) goto blob_open_out;
83702 
83703  do {
83704  memset(pParse, 0, sizeof(Parse));
83705  pParse->db = db;
83706  sqlite3DbFree(db, zErr);
83707  zErr = 0;
83708 
83710  pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
83711  if( pTab && IsVirtual(pTab) ){
83712  pTab = 0;
83713  sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
83714  }
83715  if( pTab && !HasRowid(pTab) ){
83716  pTab = 0;
83717  sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
83718  }
83719 #ifndef SQLITE_OMIT_VIEW
83720  if( pTab && pTab->pSelect ){
83721  pTab = 0;
83722  sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
83723  }
83724 #endif
83725  if( !pTab ){
83726  if( pParse->zErrMsg ){
83727  sqlite3DbFree(db, zErr);
83728  zErr = pParse->zErrMsg;
83729  pParse->zErrMsg = 0;
83730  }
83731  rc = SQLITE_ERROR;
83733  goto blob_open_out;
83734  }
83735  pBlob->pTab = pTab;
83736  pBlob->zDb = db->aDb[sqlite3SchemaToIndex(db, pTab->pSchema)].zName;
83737 
83738  /* Now search pTab for the exact column. */
83739  for(iCol=0; iCol<pTab->nCol; iCol++) {
83740  if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
83741  break;
83742  }
83743  }
83744  if( iCol==pTab->nCol ){
83745  sqlite3DbFree(db, zErr);
83746  zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
83747  rc = SQLITE_ERROR;
83749  goto blob_open_out;
83750  }
83751 
83752  /* If the value is being opened for writing, check that the
83753  ** column is not indexed, and that it is not part of a foreign key.
83754  ** It is against the rules to open a column to which either of these
83755  ** descriptions applies for writing. */
83756  if( flags ){
83757  const char *zFault = 0;
83758  Index *pIdx;
83759 #ifndef SQLITE_OMIT_FOREIGN_KEY
83760  if( db->flags&SQLITE_ForeignKeys ){
83761  /* Check that the column is not part of an FK child key definition. It
83762  ** is not necessary to check if it is part of a parent key, as parent
83763  ** key columns must be indexed. The check below will pick up this
83764  ** case. */
83765  FKey *pFKey;
83766  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
83767  int j;
83768  for(j=0; j<pFKey->nCol; j++){
83769  if( pFKey->aCol[j].iFrom==iCol ){
83770  zFault = "foreign key";
83771  }
83772  }
83773  }
83774  }
83775 #endif
83776  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
83777  int j;
83778  for(j=0; j<pIdx->nKeyCol; j++){
83779  /* FIXME: Be smarter about indexes that use expressions */
83780  if( pIdx->aiColumn[j]==iCol || pIdx->aiColumn[j]==XN_EXPR ){
83781  zFault = "indexed";
83782  }
83783  }
83784  }
83785  if( zFault ){
83786  sqlite3DbFree(db, zErr);
83787  zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
83788  rc = SQLITE_ERROR;
83790  goto blob_open_out;
83791  }
83792  }
83793 
83794  pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
83795  assert( pBlob->pStmt || db->mallocFailed );
83796  if( pBlob->pStmt ){
83797 
83798  /* This VDBE program seeks a btree cursor to the identified
83799  ** db/table/row entry. The reason for using a vdbe program instead
83800  ** of writing code to use the b-tree layer directly is that the
83801  ** vdbe program will take advantage of the various transaction,
83802  ** locking and error handling infrastructure built into the vdbe.
83803  **
83804  ** After seeking the cursor, the vdbe executes an OP_ResultRow.
83805  ** Code external to the Vdbe then "borrows" the b-tree cursor and
83806  ** uses it to implement the blob_read(), blob_write() and
83807  ** blob_bytes() functions.
83808  **
83809  ** The sqlite3_blob_close() function finalizes the vdbe program,
83810  ** which closes the b-tree cursor and (possibly) commits the
83811  ** transaction.
83812  */
83813  static const int iLn = VDBE_OFFSET_LINENO(2);
83814  static const VdbeOpList openBlob[] = {
83815  {OP_TableLock, 0, 0, 0}, /* 0: Acquire a read or write lock */
83816  {OP_OpenRead, 0, 0, 0}, /* 1: Open a cursor */
83817  {OP_Variable, 1, 1, 0}, /* 2: Move ?1 into reg[1] */
83818  {OP_NotExists, 0, 7, 1}, /* 3: Seek the cursor */
83819  {OP_Column, 0, 0, 1}, /* 4 */
83820  {OP_ResultRow, 1, 0, 0}, /* 5 */
83821  {OP_Goto, 0, 2, 0}, /* 6 */
83822  {OP_Close, 0, 0, 0}, /* 7 */
83823  {OP_Halt, 0, 0, 0}, /* 8 */
83824  };
83825  Vdbe *v = (Vdbe *)pBlob->pStmt;
83826  int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
83827  VdbeOp *aOp;
83828 
83829  sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
83830  pTab->pSchema->schema_cookie,
83831  pTab->pSchema->iGeneration);
83832  sqlite3VdbeChangeP5(v, 1);
83833  aOp = sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
83834 
83835  /* Make sure a mutex is held on the table to be accessed */
83836  sqlite3VdbeUsesBtree(v, iDb);
83837 
83838  if( db->mallocFailed==0 ){
83839  assert( aOp!=0 );
83840  /* Configure the OP_TableLock instruction */
83841 #ifdef SQLITE_OMIT_SHARED_CACHE
83842  aOp[0].opcode = OP_Noop;
83843 #else
83844  aOp[0].p1 = iDb;
83845  aOp[0].p2 = pTab->tnum;
83846  aOp[0].p3 = flags;
83847  sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
83848  }
83849  if( db->mallocFailed==0 ){
83850 #endif
83851 
83852  /* Remove either the OP_OpenWrite or OpenRead. Set the P2
83853  ** parameter of the other to pTab->tnum. */
83854  if( flags ) aOp[1].opcode = OP_OpenWrite;
83855  aOp[1].p2 = pTab->tnum;
83856  aOp[1].p3 = iDb;
83857 
83858  /* Configure the number of columns. Configure the cursor to
83859  ** think that the table has one more column than it really
83860  ** does. An OP_Column to retrieve this imaginary column will
83861  ** always return an SQL NULL. This is useful because it means
83862  ** we can invoke OP_Column to fill in the vdbe cursors type
83863  ** and offset cache without causing any IO.
83864  */
83865  aOp[1].p4type = P4_INT32;
83866  aOp[1].p4.i = pTab->nCol+1;
83867  aOp[4].p2 = pTab->nCol;
83868 
83869  pParse->nVar = 1;
83870  pParse->nMem = 1;
83871  pParse->nTab = 1;
83872  sqlite3VdbeMakeReady(v, pParse);
83873  }
83874  }
83875 
83876  pBlob->flags = flags;
83877  pBlob->iCol = iCol;
83878  pBlob->db = db;
83880  if( db->mallocFailed ){
83881  goto blob_open_out;
83882  }
83883  sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
83884  rc = blobSeekToRow(pBlob, iRow, &zErr);
83885  } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
83886 
83887 blob_open_out:
83888  if( rc==SQLITE_OK && db->mallocFailed==0 ){
83889  *ppBlob = (sqlite3_blob *)pBlob;
83890  }else{
83891  if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
83892  sqlite3DbFree(db, pBlob);
83893  }
83894  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
83895  sqlite3DbFree(db, zErr);
83896  sqlite3ParserReset(pParse);
83897  sqlite3StackFree(db, pParse);
83898  rc = sqlite3ApiExit(db, rc);
83900  return rc;
83901 }
83902 
83903 /*
83904 ** Close a blob handle that was previously created using
83905 ** sqlite3_blob_open().
83906 */
83908  Incrblob *p = (Incrblob *)pBlob;
83909  int rc;
83910  sqlite3 *db;
83911 
83912  if( p ){
83913  db = p->db;
83915  rc = sqlite3_finalize(p->pStmt);
83916  sqlite3DbFree(db, p);
83918  }else{
83919  rc = SQLITE_OK;
83920  }
83921  return rc;
83922 }
83923 
83924 /*
83925 ** Perform a read or write operation on a blob
83926 */
83927 static int blobReadWrite(
83928  sqlite3_blob *pBlob,
83929  void *z,
83930  int n,
83931  int iOffset,
83932  int (*xCall)(BtCursor*, u32, u32, void*)
83933 ){
83934  int rc;
83935  Incrblob *p = (Incrblob *)pBlob;
83936  Vdbe *v;
83937  sqlite3 *db;
83938 
83939  if( p==0 ) return SQLITE_MISUSE_BKPT;
83940  db = p->db;
83942  v = (Vdbe*)p->pStmt;
83943 
83944  if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
83945  /* Request is out of range. Return a transient error. */
83946  rc = SQLITE_ERROR;
83947  }else if( v==0 ){
83948  /* If there is no statement handle, then the blob-handle has
83949  ** already been invalidated. Return SQLITE_ABORT in this case.
83950  */
83951  rc = SQLITE_ABORT;
83952  }else{
83953  /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
83954  ** returned, clean-up the statement handle.
83955  */
83956  assert( db == v->db );
83958 
83959 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
83960  if( xCall==sqlite3BtreePutData && db->xPreUpdateCallback ){
83961  /* If a pre-update hook is registered and this is a write cursor,
83962  ** invoke it here.
83963  **
83964  ** TODO: The preupdate-hook is passed SQLITE_DELETE, even though this
83965  ** operation should really be an SQLITE_UPDATE. This is probably
83966  ** incorrect, but is convenient because at this point the new.* values
83967  ** are not easily obtainable. And for the sessions module, an
83968  ** SQLITE_UPDATE where the PK columns do not change is handled in the
83969  ** same way as an SQLITE_DELETE (the SQLITE_DELETE code is actually
83970  ** slightly more efficient). Since you cannot write to a PK column
83971  ** using the incremental-blob API, this works. For the sessions module
83972  ** anyhow.
83973  */
83974  sqlite3_int64 iKey;
83975  sqlite3BtreeKeySize(p->pCsr, &iKey);
83976  sqlite3VdbePreUpdateHook(
83977  v, v->apCsr[0], SQLITE_DELETE, p->zDb, p->pTab, iKey, -1
83978  );
83979  }
83980 #endif
83981 
83982  rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
83984  if( rc==SQLITE_ABORT ){
83986  p->pStmt = 0;
83987  }else{
83988  v->rc = rc;
83989  }
83990  }
83991  sqlite3Error(db, rc);
83992  rc = sqlite3ApiExit(db, rc);
83994  return rc;
83995 }
83996 
83997 /*
83998 ** Read data from a blob handle.
83999 */
84000 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
84001  return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
84002 }
84003 
84004 /*
84005 ** Write data to a blob handle.
84006 */
84007 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
84008  return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
84009 }
84010 
84011 /*
84012 ** Query a blob handle for the size of the data.
84013 **
84014 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
84015 ** so no mutex is required for access.
84016 */
84018  Incrblob *p = (Incrblob *)pBlob;
84019  return (p && p->pStmt) ? p->nByte : 0;
84020 }
84021 
84022 /*
84023 ** Move an existing blob handle to point to a different row of the same
84024 ** database table.
84025 **
84026 ** If an error occurs, or if the specified row does not exist or does not
84027 ** contain a blob or text value, then an error code is returned and the
84028 ** database handle error code and message set. If this happens, then all
84029 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
84030 ** immediately return SQLITE_ABORT.
84031 */
84033  int rc;
84034  Incrblob *p = (Incrblob *)pBlob;
84035  sqlite3 *db;
84036 
84037  if( p==0 ) return SQLITE_MISUSE_BKPT;
84038  db = p->db;
84040 
84041  if( p->pStmt==0 ){
84042  /* If there is no statement handle, then the blob-handle has
84043  ** already been invalidated. Return SQLITE_ABORT in this case.
84044  */
84045  rc = SQLITE_ABORT;
84046  }else{
84047  char *zErr;
84048  rc = blobSeekToRow(p, iRow, &zErr);
84049  if( rc!=SQLITE_OK ){
84050  sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
84051  sqlite3DbFree(db, zErr);
84052  }
84053  assert( rc!=SQLITE_SCHEMA );
84054  }
84055 
84056  rc = sqlite3ApiExit(db, rc);
84057  assert( rc==SQLITE_OK || p->pStmt==0 );
84059  return rc;
84060 }
84061 
84062 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
84063 
84064 /************** End of vdbeblob.c ********************************************/
84065 /************** Begin file vdbesort.c ****************************************/
84066 /*
84067 ** 2011-07-09
84068 **
84069 ** The author disclaims copyright to this source code. In place of
84070 ** a legal notice, here is a blessing:
84071 **
84072 ** May you do good and not evil.
84073 ** May you find forgiveness for yourself and forgive others.
84074 ** May you share freely, never taking more than you give.
84075 **
84076 *************************************************************************
84077 ** This file contains code for the VdbeSorter object, used in concert with
84078 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
84079 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
84080 ** using indexes and without LIMIT clauses.
84081 **
84082 ** The VdbeSorter object implements a multi-threaded external merge sort
84083 ** algorithm that is efficient even if the number of elements being sorted
84084 ** exceeds the available memory.
84085 **
84086 ** Here is the (internal, non-API) interface between this module and the
84087 ** rest of the SQLite system:
84088 **
84089 ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
84090 **
84091 ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
84092 ** object. The row is a binary blob in the
84093 ** OP_MakeRecord format that contains both
84094 ** the ORDER BY key columns and result columns
84095 ** in the case of a SELECT w/ ORDER BY, or
84096 ** the complete record for an index entry
84097 ** in the case of a CREATE INDEX.
84098 **
84099 ** sqlite3VdbeSorterRewind() Sort all content previously added.
84100 ** Position the read cursor on the
84101 ** first sorted element.
84102 **
84103 ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
84104 ** element.
84105 **
84106 ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
84107 ** row currently under the read cursor.
84108 **
84109 ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
84110 ** currently under the read cursor against
84111 ** another binary blob X and report if
84112 ** X is strictly less than the read cursor.
84113 ** Used to enforce uniqueness in a
84114 ** CREATE UNIQUE INDEX statement.
84115 **
84116 ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
84117 ** all resources.
84118 **
84119 ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
84120 ** is like Close() followed by Init() only
84121 ** much faster.
84122 **
84123 ** The interfaces above must be called in a particular order. Write() can
84124 ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
84125 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
84126 **
84127 ** Init()
84128 ** for each record: Write()
84129 ** Rewind()
84130 ** Rowkey()/Compare()
84131 ** Next()
84132 ** Close()
84133 **
84134 ** Algorithm:
84135 **
84136 ** Records passed to the sorter via calls to Write() are initially held
84137 ** unsorted in main memory. Assuming the amount of memory used never exceeds
84138 ** a threshold, when Rewind() is called the set of records is sorted using
84139 ** an in-memory merge sort. In this case, no temporary files are required
84140 ** and subsequent calls to Rowkey(), Next() and Compare() read records
84141 ** directly from main memory.
84142 **
84143 ** If the amount of space used to store records in main memory exceeds the
84144 ** threshold, then the set of records currently in memory are sorted and
84145 ** written to a temporary file in "Packed Memory Array" (PMA) format.
84146 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
84147 ** of PMAs may be created by merging existing PMAs together - for example
84148 ** merging two or more level-0 PMAs together creates a level-1 PMA.
84149 **
84150 ** The threshold for the amount of main memory to use before flushing
84151 ** records to a PMA is roughly the same as the limit configured for the
84152 ** page-cache of the main database. Specifically, the threshold is set to
84153 ** the value returned by "PRAGMA main.page_size" multipled by
84154 ** that returned by "PRAGMA main.cache_size", in bytes.
84155 **
84156 ** If the sorter is running in single-threaded mode, then all PMAs generated
84157 ** are appended to a single temporary file. Or, if the sorter is running in
84158 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
84159 ** N is the configured number of worker threads. In this case, instead of
84160 ** sorting the records and writing the PMA to a temporary file itself, the
84161 ** calling thread usually launches a worker thread to do so. Except, if
84162 ** there are already N worker threads running, the main thread does the work
84163 ** itself.
84164 **
84165 ** The sorter is running in multi-threaded mode if (a) the library was built
84166 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
84167 ** than zero, and (b) worker threads have been enabled at runtime by calling
84168 ** "PRAGMA threads=N" with some value of N greater than 0.
84169 **
84170 ** When Rewind() is called, any data remaining in memory is flushed to a
84171 ** final PMA. So at this point the data is stored in some number of sorted
84172 ** PMAs within temporary files on disk.
84173 **
84174 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
84175 ** sorter is running in single-threaded mode, then these PMAs are merged
84176 ** incrementally as keys are retreived from the sorter by the VDBE. The
84177 ** MergeEngine object, described in further detail below, performs this
84178 ** merge.
84179 **
84180 ** Or, if running in multi-threaded mode, then a background thread is
84181 ** launched to merge the existing PMAs. Once the background thread has
84182 ** merged T bytes of data into a single sorted PMA, the main thread
84183 ** begins reading keys from that PMA while the background thread proceeds
84184 ** with merging the next T bytes of data. And so on.
84185 **
84186 ** Parameter T is set to half the value of the memory threshold used
84187 ** by Write() above to determine when to create a new PMA.
84188 **
84189 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
84190 ** Rewind() is called, then a hierarchy of incremental-merges is used.
84191 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
84192 ** disk are merged together. Then T bytes of data from the second set, and
84193 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
84194 ** PMAs at a time. This done is to improve locality.
84195 **
84196 ** If running in multi-threaded mode and there are more than
84197 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
84198 ** than one background thread may be created. Specifically, there may be
84199 ** one background thread for each temporary file on disk, and one background
84200 ** thread to merge the output of each of the others to a single PMA for
84201 ** the main thread to read from.
84202 */
84203 /* #include "sqliteInt.h" */
84204 /* #include "vdbeInt.h" */
84205 
84206 /*
84207 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
84208 ** messages to stderr that may be helpful in understanding the performance
84209 ** characteristics of the sorter in multi-threaded mode.
84210 */
84211 #if 0
84212 # define SQLITE_DEBUG_SORTER_THREADS 1
84213 #endif
84214 
84215 /*
84216 ** Hard-coded maximum amount of data to accumulate in memory before flushing
84217 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
84218 ** overflows. 512MiB.
84219 */
84220 #define SQLITE_MAX_PMASZ (1<<29)
84221 
84222 /*
84223 ** Private objects used by the sorter
84224 */
84225 typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
84226 typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
84227 typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
84228 typedef struct SorterRecord SorterRecord; /* A record being sorted */
84229 typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
84230 typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
84231 typedef struct SorterList SorterList; /* In-memory list of records */
84232 typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
84233 
84234 /*
84235 ** A container for a temp file handle and the current amount of data
84236 ** stored in the file.
84237 */
84238 struct SorterFile {
84239  sqlite3_file *pFd; /* File handle */
84240  i64 iEof; /* Bytes of data stored in pFd */
84241 };
84242 
84243 /*
84244 ** An in-memory list of objects to be sorted.
84245 **
84246 ** If aMemory==0 then each object is allocated separately and the objects
84247 ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
84248 ** are stored in the aMemory[] bulk memory, one right after the other, and
84249 ** are connected using SorterRecord.u.iNext.
84250 */
84251 struct SorterList {
84252  SorterRecord *pList; /* Linked list of records */
84253  u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
84254  int szPMA; /* Size of pList as PMA in bytes */
84255 };
84256 
84257 /*
84258 ** The MergeEngine object is used to combine two or more smaller PMAs into
84259 ** one big PMA using a merge operation. Separate PMAs all need to be
84260 ** combined into one big PMA in order to be able to step through the sorted
84261 ** records in order.
84262 **
84263 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
84264 ** merged. An aReadr[] object either points to a valid key or else is at EOF.
84265 ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
84266 ** For the purposes of the paragraphs below, we assume that the array is
84267 ** actually N elements in size, where N is the smallest power of 2 greater
84268 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
84269 ** are treated as if they are empty (always at EOF).
84270 **
84271 ** The aTree[] array is also N elements in size. The value of N is stored in
84272 ** the MergeEngine.nTree variable.
84273 **
84274 ** The final (N/2) elements of aTree[] contain the results of comparing
84275 ** pairs of PMA keys together. Element i contains the result of
84276 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
84277 ** aTree element is set to the index of it.
84278 **
84279 ** For the purposes of this comparison, EOF is considered greater than any
84280 ** other key value. If the keys are equal (only possible with two EOF
84281 ** values), it doesn't matter which index is stored.
84282 **
84283 ** The (N/4) elements of aTree[] that precede the final (N/2) described
84284 ** above contains the index of the smallest of each block of 4 PmaReaders
84285 ** And so on. So that aTree[1] contains the index of the PmaReader that
84286 ** currently points to the smallest key value. aTree[0] is unused.
84287 **
84288 ** Example:
84289 **
84290 ** aReadr[0] -> Banana
84291 ** aReadr[1] -> Feijoa
84292 ** aReadr[2] -> Elderberry
84293 ** aReadr[3] -> Currant
84294 ** aReadr[4] -> Grapefruit
84295 ** aReadr[5] -> Apple
84296 ** aReadr[6] -> Durian
84297 ** aReadr[7] -> EOF
84298 **
84299 ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
84300 **
84301 ** The current element is "Apple" (the value of the key indicated by
84302 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
84303 ** be advanced to the next key in its segment. Say the next key is
84304 ** "Eggplant":
84305 **
84306 ** aReadr[5] -> Eggplant
84307 **
84308 ** The contents of aTree[] are updated first by comparing the new PmaReader
84309 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
84310 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
84311 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
84312 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
84313 ** so the value written into element 1 of the array is 0. As follows:
84314 **
84315 ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
84316 **
84317 ** In other words, each time we advance to the next sorter element, log2(N)
84318 ** key comparison operations are required, where N is the number of segments
84319 ** being merged (rounded up to the next power of 2).
84320 */
84321 struct MergeEngine {
84322  int nTree; /* Used size of aTree/aReadr (power of 2) */
84323  SortSubtask *pTask; /* Used by this thread only */
84324  int *aTree; /* Current state of incremental merge */
84325  PmaReader *aReadr; /* Array of PmaReaders to merge data from */
84326 };
84327 
84328 /*
84329 ** This object represents a single thread of control in a sort operation.
84330 ** Exactly VdbeSorter.nTask instances of this object are allocated
84331 ** as part of each VdbeSorter object. Instances are never allocated any
84332 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
84333 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
84334 ** single-threaded operation, there is exactly one instance of this object
84335 ** and for multi-threaded operation there are two or more instances.
84336 **
84337 ** Essentially, this structure contains all those fields of the VdbeSorter
84338 ** structure for which each thread requires a separate instance. For example,
84339 ** each thread requries its own UnpackedRecord object to unpack records in
84340 ** as part of comparison operations.
84341 **
84342 ** Before a background thread is launched, variable bDone is set to 0. Then,
84343 ** right before it exits, the thread itself sets bDone to 1. This is used for
84344 ** two purposes:
84345 **
84346 ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
84347 ** attempt to select a SortSubtask for which there is not already an
84348 ** active background thread (since doing so causes the main thread
84349 ** to block until it finishes).
84350 **
84351 ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
84352 ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
84353 ** block provoke debugging output.
84354 **
84355 ** In both cases, the effects of the main thread seeing (bDone==0) even
84356 ** after the thread has finished are not dire. So we don't worry about
84357 ** memory barriers and such here.
84358 */
84359 typedef int (*SorterCompare)(SortSubtask*,int*,const void*,int,const void*,int);
84360 struct SortSubtask {
84361  SQLiteThread *pThread; /* Background thread, if any */
84362  int bDone; /* Set if thread is finished but not joined */
84363  VdbeSorter *pSorter; /* Sorter that owns this sub-task */
84364  UnpackedRecord *pUnpacked; /* Space to unpack a record */
84365  SorterList list; /* List for thread to write to a PMA */
84366  int nPMA; /* Number of PMAs currently in file */
84367  SorterCompare xCompare; /* Compare function to use */
84368  SorterFile file; /* Temp file for level-0 PMAs */
84369  SorterFile file2; /* Space for other PMAs */
84370 };
84371 
84372 
84373 /*
84374 ** Main sorter structure. A single instance of this is allocated for each
84375 ** sorter cursor created by the VDBE.
84376 **
84377 ** mxKeysize:
84378 ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
84379 ** this variable is updated so as to be set to the size on disk of the
84380 ** largest record in the sorter.
84381 */
84382 struct VdbeSorter {
84383  int mnPmaSize; /* Minimum PMA size, in bytes */
84384  int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
84385  int mxKeysize; /* Largest serialized key seen so far */
84386  int pgsz; /* Main database page size */
84387  PmaReader *pReader; /* Readr data from here after Rewind() */
84388  MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
84389  sqlite3 *db; /* Database connection */
84390  KeyInfo *pKeyInfo; /* How to compare records */
84391  UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
84392  SorterList list; /* List of in-memory records */
84393  int iMemory; /* Offset of free space in list.aMemory */
84394  int nMemory; /* Size of list.aMemory allocation in bytes */
84395  u8 bUsePMA; /* True if one or more PMAs created */
84396  u8 bUseThreads; /* True to use background threads */
84397  u8 iPrev; /* Previous thread used to flush PMA */
84398  u8 nTask; /* Size of aTask[] array */
84400  SortSubtask aTask[1]; /* One or more subtasks */
84401 };
84402 
84403 #define SORTER_TYPE_INTEGER 0x01
84404 #define SORTER_TYPE_TEXT 0x02
84405 
84406 /*
84407 ** An instance of the following object is used to read records out of a
84408 ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
84409 ** aKey might point into aMap or into aBuffer. If neither of those locations
84410 ** contain a contiguous representation of the key, then aAlloc is allocated
84411 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
84412 **
84413 ** pFd==0 at EOF.
84414 */
84415 struct PmaReader {
84416  i64 iReadOff; /* Current read offset */
84417  i64 iEof; /* 1 byte past EOF for this PmaReader */
84418  int nAlloc; /* Bytes of space at aAlloc */
84419  int nKey; /* Number of bytes in key */
84420  sqlite3_file *pFd; /* File handle we are reading from */
84421  u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
84422  u8 *aKey; /* Pointer to current key */
84423  u8 *aBuffer; /* Current read buffer */
84424  int nBuffer; /* Size of read buffer in bytes */
84425  u8 *aMap; /* Pointer to mapping of entire file */
84426  IncrMerger *pIncr; /* Incremental merger */
84427 };
84428 
84429 /*
84430 ** Normally, a PmaReader object iterates through an existing PMA stored
84431 ** within a temp file. However, if the PmaReader.pIncr variable points to
84432 ** an object of the following type, it may be used to iterate/merge through
84433 ** multiple PMAs simultaneously.
84434 **
84435 ** There are two types of IncrMerger object - single (bUseThread==0) and
84436 ** multi-threaded (bUseThread==1).
84437 **
84438 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
84439 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
84440 ** size. When the IncrMerger is initialized, it reads enough data from
84441 ** pMerger to populate aFile[0]. It then sets variables within the
84442 ** corresponding PmaReader object to read from that file and kicks off
84443 ** a background thread to populate aFile[1] with the next mxSz bytes of
84444 ** sorted record data from pMerger.
84445 **
84446 ** When the PmaReader reaches the end of aFile[0], it blocks until the
84447 ** background thread has finished populating aFile[1]. It then exchanges
84448 ** the contents of the aFile[0] and aFile[1] variables within this structure,
84449 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
84450 ** another background thread to populate the new aFile[1]. And so on, until
84451 ** the contents of pMerger are exhausted.
84452 **
84453 ** A single-threaded IncrMerger does not open any temporary files of its
84454 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
84455 ** at offset iStartOff of file pTask->file2. And instead of using a
84456 ** background thread to prepare data for the PmaReader, with a single
84457 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
84458 ** keys from pMerger by the calling thread whenever the PmaReader runs out
84459 ** of data.
84460 */
84461 struct IncrMerger {
84462  SortSubtask *pTask; /* Task that owns this merger */
84463  MergeEngine *pMerger; /* Merge engine thread reads data from */
84464  i64 iStartOff; /* Offset to start writing file at */
84465  int mxSz; /* Maximum bytes of data to store */
84466  int bEof; /* Set to true when merge is finished */
84467  int bUseThread; /* True to use a bg thread for this object */
84468  SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
84469 };
84470 
84471 /*
84472 ** An instance of this object is used for writing a PMA.
84473 **
84474 ** The PMA is written one record at a time. Each record is of an arbitrary
84475 ** size. But I/O is more efficient if it occurs in page-sized blocks where
84476 ** each block is aligned on a page boundary. This object caches writes to
84477 ** the PMA so that aligned, page-size blocks are written.
84478 */
84479 struct PmaWriter {
84480  int eFWErr; /* Non-zero if in an error state */
84481  u8 *aBuffer; /* Pointer to write buffer */
84482  int nBuffer; /* Size of write buffer in bytes */
84483  int iBufStart; /* First byte of buffer to write */
84484  int iBufEnd; /* Last byte of buffer to write */
84485  i64 iWriteOff; /* Offset of start of buffer in file */
84486  sqlite3_file *pFd; /* File handle to write to */
84487 };
84488 
84489 /*
84490 ** This object is the header on a single record while that record is being
84491 ** held in memory and prior to being written out as part of a PMA.
84492 **
84493 ** How the linked list is connected depends on how memory is being managed
84494 ** by this module. If using a separate allocation for each in-memory record
84495 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
84496 ** SorterRecord.u.pNext pointers.
84497 **
84498 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
84499 ** then while records are being accumulated the list is linked using the
84500 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
84501 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
84502 ** has finished passing records to the sorter, or when the in-memory buffer
84503 ** is full, the list is sorted. As part of the sorting process, it is
84504 ** converted to use the SorterRecord.u.pNext pointers. See function
84505 ** vdbeSorterSort() for details.
84506 */
84508  int nVal; /* Size of the record in bytes */
84509  union {
84510  SorterRecord *pNext; /* Pointer to next record in list */
84511  int iNext; /* Offset within aMemory of next record */
84512  } u;
84513  /* The data for the record immediately follows this header */
84514 };
84515 
84516 /* Return a pointer to the buffer containing the record data for SorterRecord
84517 ** object p. Should be used as if:
84518 **
84519 ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
84520 */
84521 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
84522 
84523 
84524 /* Maximum number of PMAs that a single MergeEngine can merge */
84525 #define SORTER_MAX_MERGE_COUNT 16
84526 
84527 static int vdbeIncrSwap(IncrMerger*);
84528 static void vdbeIncrFree(IncrMerger *);
84529 
84530 /*
84531 ** Free all memory belonging to the PmaReader object passed as the
84532 ** argument. All structure fields are set to zero before returning.
84533 */
84534 static void vdbePmaReaderClear(PmaReader *pReadr){
84535  sqlite3_free(pReadr->aAlloc);
84536  sqlite3_free(pReadr->aBuffer);
84537  if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
84538  vdbeIncrFree(pReadr->pIncr);
84539  memset(pReadr, 0, sizeof(PmaReader));
84540 }
84541 
84542 /*
84543 ** Read the next nByte bytes of data from the PMA p.
84544 ** If successful, set *ppOut to point to a buffer containing the data
84545 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
84546 ** error code.
84547 **
84548 ** The buffer returned in *ppOut is only valid until the
84549 ** next call to this function.
84550 */
84551 static int vdbePmaReadBlob(
84552  PmaReader *p, /* PmaReader from which to take the blob */
84553  int nByte, /* Bytes of data to read */
84554  u8 **ppOut /* OUT: Pointer to buffer containing data */
84555 ){
84556  int iBuf; /* Offset within buffer to read from */
84557  int nAvail; /* Bytes of data available in buffer */
84558 
84559  if( p->aMap ){
84560  *ppOut = &p->aMap[p->iReadOff];
84561  p->iReadOff += nByte;
84562  return SQLITE_OK;
84563  }
84564 
84565  assert( p->aBuffer );
84566 
84567  /* If there is no more data to be read from the buffer, read the next
84568  ** p->nBuffer bytes of data from the file into it. Or, if there are less
84569  ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
84570  iBuf = p->iReadOff % p->nBuffer;
84571  if( iBuf==0 ){
84572  int nRead; /* Bytes to read from disk */
84573  int rc; /* sqlite3OsRead() return code */
84574 
84575  /* Determine how many bytes of data to read. */
84576  if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
84577  nRead = p->nBuffer;
84578  }else{
84579  nRead = (int)(p->iEof - p->iReadOff);
84580  }
84581  assert( nRead>0 );
84582 
84583  /* Readr data from the file. Return early if an error occurs. */
84584  rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
84586  if( rc!=SQLITE_OK ) return rc;
84587  }
84588  nAvail = p->nBuffer - iBuf;
84589 
84590  if( nByte<=nAvail ){
84591  /* The requested data is available in the in-memory buffer. In this
84592  ** case there is no need to make a copy of the data, just return a
84593  ** pointer into the buffer to the caller. */
84594  *ppOut = &p->aBuffer[iBuf];
84595  p->iReadOff += nByte;
84596  }else{
84597  /* The requested data is not all available in the in-memory buffer.
84598  ** In this case, allocate space at p->aAlloc[] to copy the requested
84599  ** range into. Then return a copy of pointer p->aAlloc to the caller. */
84600  int nRem; /* Bytes remaining to copy */
84601 
84602  /* Extend the p->aAlloc[] allocation if required. */
84603  if( p->nAlloc<nByte ){
84604  u8 *aNew;
84605  int nNew = MAX(128, p->nAlloc*2);
84606  while( nByte>nNew ) nNew = nNew*2;
84607  aNew = sqlite3Realloc(p->aAlloc, nNew);
84608  if( !aNew ) return SQLITE_NOMEM_BKPT;
84609  p->nAlloc = nNew;
84610  p->aAlloc = aNew;
84611  }
84612 
84613  /* Copy as much data as is available in the buffer into the start of
84614  ** p->aAlloc[]. */
84615  memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
84616  p->iReadOff += nAvail;
84617  nRem = nByte - nAvail;
84618 
84619  /* The following loop copies up to p->nBuffer bytes per iteration into
84620  ** the p->aAlloc[] buffer. */
84621  while( nRem>0 ){
84622  int rc; /* vdbePmaReadBlob() return code */
84623  int nCopy; /* Number of bytes to copy */
84624  u8 *aNext; /* Pointer to buffer to copy data from */
84625 
84626  nCopy = nRem;
84627  if( nRem>p->nBuffer ) nCopy = p->nBuffer;
84628  rc = vdbePmaReadBlob(p, nCopy, &aNext);
84629  if( rc!=SQLITE_OK ) return rc;
84630  assert( aNext!=p->aAlloc );
84631  memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
84632  nRem -= nCopy;
84633  }
84634 
84635  *ppOut = p->aAlloc;
84636  }
84637 
84638  return SQLITE_OK;
84639 }
84640 
84641 /*
84642 ** Read a varint from the stream of data accessed by p. Set *pnOut to
84643 ** the value read.
84644 */
84645 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
84646  int iBuf;
84647 
84648  if( p->aMap ){
84649  p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
84650  }else{
84651  iBuf = p->iReadOff % p->nBuffer;
84652  if( iBuf && (p->nBuffer-iBuf)>=9 ){
84653  p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
84654  }else{
84655  u8 aVarint[16], *a;
84656  int i = 0, rc;
84657  do{
84658  rc = vdbePmaReadBlob(p, 1, &a);
84659  if( rc ) return rc;
84660  aVarint[(i++)&0xf] = a[0];
84661  }while( (a[0]&0x80)!=0 );
84662  sqlite3GetVarint(aVarint, pnOut);
84663  }
84664  }
84665 
84666  return SQLITE_OK;
84667 }
84668 
84669 /*
84670 ** Attempt to memory map file pFile. If successful, set *pp to point to the
84671 ** new mapping and return SQLITE_OK. If the mapping is not attempted
84672 ** (because the file is too large or the VFS layer is configured not to use
84673 ** mmap), return SQLITE_OK and set *pp to NULL.
84674 **
84675 ** Or, if an error occurs, return an SQLite error code. The final value of
84676 ** *pp is undefined in this case.
84677 */
84678 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
84679  int rc = SQLITE_OK;
84680  if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
84681  sqlite3_file *pFd = pFile->pFd;
84682  if( pFd->pMethods->iVersion>=3 ){
84683  rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
84684  testcase( rc!=SQLITE_OK );
84685  }
84686  }
84687  return rc;
84688 }
84689 
84690 /*
84691 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
84692 ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
84693 ** if successful, or an SQLite error code if an error occurs.
84694 */
84696  SortSubtask *pTask, /* Task context */
84697  PmaReader *pReadr, /* Reader whose cursor is to be moved */
84698  SorterFile *pFile, /* Sorter file to read from */
84699  i64 iOff /* Offset in pFile */
84700 ){
84701  int rc = SQLITE_OK;
84702 
84703  assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
84704 
84705  if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
84706  if( pReadr->aMap ){
84707  sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
84708  pReadr->aMap = 0;
84709  }
84710  pReadr->iReadOff = iOff;
84711  pReadr->iEof = pFile->iEof;
84712  pReadr->pFd = pFile->pFd;
84713 
84714  rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
84715  if( rc==SQLITE_OK && pReadr->aMap==0 ){
84716  int pgsz = pTask->pSorter->pgsz;
84717  int iBuf = pReadr->iReadOff % pgsz;
84718  if( pReadr->aBuffer==0 ){
84719  pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
84720  if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM_BKPT;
84721  pReadr->nBuffer = pgsz;
84722  }
84723  if( rc==SQLITE_OK && iBuf ){
84724  int nRead = pgsz - iBuf;
84725  if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
84726  nRead = (int)(pReadr->iEof - pReadr->iReadOff);
84727  }
84728  rc = sqlite3OsRead(
84729  pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
84730  );
84731  testcase( rc!=SQLITE_OK );
84732  }
84733  }
84734 
84735  return rc;
84736 }
84737 
84738 /*
84739 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
84740 ** no error occurs, or an SQLite error code if one does.
84741 */
84742 static int vdbePmaReaderNext(PmaReader *pReadr){
84743  int rc = SQLITE_OK; /* Return Code */
84744  u64 nRec = 0; /* Size of record in bytes */
84745 
84746 
84747  if( pReadr->iReadOff>=pReadr->iEof ){
84748  IncrMerger *pIncr = pReadr->pIncr;
84749  int bEof = 1;
84750  if( pIncr ){
84751  rc = vdbeIncrSwap(pIncr);
84752  if( rc==SQLITE_OK && pIncr->bEof==0 ){
84753  rc = vdbePmaReaderSeek(
84754  pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
84755  );
84756  bEof = 0;
84757  }
84758  }
84759 
84760  if( bEof ){
84761  /* This is an EOF condition */
84762  vdbePmaReaderClear(pReadr);
84763  testcase( rc!=SQLITE_OK );
84764  return rc;
84765  }
84766  }
84767 
84768  if( rc==SQLITE_OK ){
84769  rc = vdbePmaReadVarint(pReadr, &nRec);
84770  }
84771  if( rc==SQLITE_OK ){
84772  pReadr->nKey = (int)nRec;
84773  rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
84774  testcase( rc!=SQLITE_OK );
84775  }
84776 
84777  return rc;
84778 }
84779 
84780 /*
84781 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
84782 ** starting at offset iStart and ending at offset iEof-1. This function
84783 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
84784 ** PMA is empty).
84785 **
84786 ** If the pnByte parameter is NULL, then it is assumed that the file
84787 ** contains a single PMA, and that that PMA omits the initial length varint.
84788 */
84790  SortSubtask *pTask, /* Task context */
84791  SorterFile *pFile, /* Sorter file to read from */
84792  i64 iStart, /* Start offset in pFile */
84793  PmaReader *pReadr, /* PmaReader to populate */
84794  i64 *pnByte /* IN/OUT: Increment this value by PMA size */
84795 ){
84796  int rc;
84797 
84798  assert( pFile->iEof>iStart );
84799  assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
84800  assert( pReadr->aBuffer==0 );
84801  assert( pReadr->aMap==0 );
84802 
84803  rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
84804  if( rc==SQLITE_OK ){
84805  u64 nByte = 0; /* Size of PMA in bytes */
84806  rc = vdbePmaReadVarint(pReadr, &nByte);
84807  pReadr->iEof = pReadr->iReadOff + nByte;
84808  *pnByte += nByte;
84809  }
84810 
84811  if( rc==SQLITE_OK ){
84812  rc = vdbePmaReaderNext(pReadr);
84813  }
84814  return rc;
84815 }
84816 
84817 /*
84818 ** A version of vdbeSorterCompare() that assumes that it has already been
84819 ** determined that the first field of key1 is equal to the first field of
84820 ** key2.
84821 */
84823  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
84824  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
84825  const void *pKey1, int nKey1, /* Left side of comparison */
84826  const void *pKey2, int nKey2 /* Right side of comparison */
84827 ){
84828  UnpackedRecord *r2 = pTask->pUnpacked;
84829  if( *pbKey2Cached==0 ){
84830  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
84831  *pbKey2Cached = 1;
84832  }
84833  return sqlite3VdbeRecordCompareWithSkip(nKey1, pKey1, r2, 1);
84834 }
84835 
84836 /*
84837 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
84838 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
84839 ** used by the comparison. Return the result of the comparison.
84840 **
84841 ** If IN/OUT parameter *pbKey2Cached is true when this function is called,
84842 ** it is assumed that (pTask->pUnpacked) contains the unpacked version
84843 ** of key2. If it is false, (pTask->pUnpacked) is populated with the unpacked
84844 ** version of key2 and *pbKey2Cached set to true before returning.
84845 **
84846 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
84847 ** to SQLITE_NOMEM.
84848 */
84850  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
84851  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
84852  const void *pKey1, int nKey1, /* Left side of comparison */
84853  const void *pKey2, int nKey2 /* Right side of comparison */
84854 ){
84855  UnpackedRecord *r2 = pTask->pUnpacked;
84856  if( !*pbKey2Cached ){
84857  sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
84858  *pbKey2Cached = 1;
84859  }
84860  return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
84861 }
84862 
84863 /*
84864 ** A specially optimized version of vdbeSorterCompare() that assumes that
84865 ** the first field of each key is a TEXT value and that the collation
84866 ** sequence to compare them with is BINARY.
84867 */
84869  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
84870  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
84871  const void *pKey1, int nKey1, /* Left side of comparison */
84872  const void *pKey2, int nKey2 /* Right side of comparison */
84873 ){
84874  const u8 * const p1 = (const u8 * const)pKey1;
84875  const u8 * const p2 = (const u8 * const)pKey2;
84876  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
84877  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
84878 
84879  int n1;
84880  int n2;
84881  int res;
84882 
84883  getVarint32(&p1[1], n1); n1 = (n1 - 13) / 2;
84884  getVarint32(&p2[1], n2); n2 = (n2 - 13) / 2;
84885  res = memcmp(v1, v2, MIN(n1, n2));
84886  if( res==0 ){
84887  res = n1 - n2;
84888  }
84889 
84890  if( res==0 ){
84891  if( pTask->pSorter->pKeyInfo->nField>1 ){
84892  res = vdbeSorterCompareTail(
84893  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
84894  );
84895  }
84896  }else{
84897  if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
84898  res = res * -1;
84899  }
84900  }
84901 
84902  return res;
84903 }
84904 
84905 /*
84906 ** A specially optimized version of vdbeSorterCompare() that assumes that
84907 ** the first field of each key is an INTEGER value.
84908 */
84910  SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
84911  int *pbKey2Cached, /* True if pTask->pUnpacked is pKey2 */
84912  const void *pKey1, int nKey1, /* Left side of comparison */
84913  const void *pKey2, int nKey2 /* Right side of comparison */
84914 ){
84915  const u8 * const p1 = (const u8 * const)pKey1;
84916  const u8 * const p2 = (const u8 * const)pKey2;
84917  const int s1 = p1[1]; /* Left hand serial type */
84918  const int s2 = p2[1]; /* Right hand serial type */
84919  const u8 * const v1 = &p1[ p1[0] ]; /* Pointer to value 1 */
84920  const u8 * const v2 = &p2[ p2[0] ]; /* Pointer to value 2 */
84921  int res; /* Return value */
84922 
84923  assert( (s1>0 && s1<7) || s1==8 || s1==9 );
84924  assert( (s2>0 && s2<7) || s2==8 || s2==9 );
84925 
84926  if( s1>7 && s2>7 ){
84927  res = s1 - s2;
84928  }else{
84929  if( s1==s2 ){
84930  if( (*v1 ^ *v2) & 0x80 ){
84931  /* The two values have different signs */
84932  res = (*v1 & 0x80) ? -1 : +1;
84933  }else{
84934  /* The two values have the same sign. Compare using memcmp(). */
84935  static const u8 aLen[] = {0, 1, 2, 3, 4, 6, 8 };
84936  int i;
84937  res = 0;
84938  for(i=0; i<aLen[s1]; i++){
84939  if( (res = v1[i] - v2[i]) ) break;
84940  }
84941  }
84942  }else{
84943  if( s2>7 ){
84944  res = +1;
84945  }else if( s1>7 ){
84946  res = -1;
84947  }else{
84948  res = s1 - s2;
84949  }
84950  assert( res!=0 );
84951 
84952  if( res>0 ){
84953  if( *v1 & 0x80 ) res = -1;
84954  }else{
84955  if( *v2 & 0x80 ) res = +1;
84956  }
84957  }
84958  }
84959 
84960  if( res==0 ){
84961  if( pTask->pSorter->pKeyInfo->nField>1 ){
84962  res = vdbeSorterCompareTail(
84963  pTask, pbKey2Cached, pKey1, nKey1, pKey2, nKey2
84964  );
84965  }
84966  }else if( pTask->pSorter->pKeyInfo->aSortOrder[0] ){
84967  res = res * -1;
84968  }
84969 
84970  return res;
84971 }
84972 
84973 /*
84974 ** Initialize the temporary index cursor just opened as a sorter cursor.
84975 **
84976 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
84977 ** to determine the number of fields that should be compared from the
84978 ** records being sorted. However, if the value passed as argument nField
84979 ** is non-zero and the sorter is able to guarantee a stable sort, nField
84980 ** is used instead. This is used when sorting records for a CREATE INDEX
84981 ** statement. In this case, keys are always delivered to the sorter in
84982 ** order of the primary key, which happens to be make up the final part
84983 ** of the records being sorted. So if the sort is stable, there is never
84984 ** any reason to compare PK fields and they can be ignored for a small
84985 ** performance boost.
84986 **
84987 ** The sorter can guarantee a stable sort when running in single-threaded
84988 ** mode, but not in multi-threaded mode.
84989 **
84990 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
84991 */
84993  sqlite3 *db, /* Database connection (for malloc()) */
84994  int nField, /* Number of key fields in each record */
84995  VdbeCursor *pCsr /* Cursor that holds the new sorter */
84996 ){
84997  int pgsz; /* Page size of main database */
84998  int i; /* Used to iterate through aTask[] */
84999  VdbeSorter *pSorter; /* The new sorter */
85000  KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
85001  int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
85002  int sz; /* Size of pSorter in bytes */
85003  int rc = SQLITE_OK;
85004 #if SQLITE_MAX_WORKER_THREADS==0
85005 # define nWorker 0
85006 #else
85007  int nWorker;
85008 #endif
85009 
85010  /* Initialize the upper limit on the number of worker threads */
85011 #if SQLITE_MAX_WORKER_THREADS>0
85012  if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
85013  nWorker = 0;
85014  }else{
85015  nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
85016  }
85017 #endif
85018 
85019  /* Do not allow the total number of threads (main thread + all workers)
85020  ** to exceed the maximum merge count */
85021 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
85022  if( nWorker>=SORTER_MAX_MERGE_COUNT ){
85023  nWorker = SORTER_MAX_MERGE_COUNT-1;
85024  }
85025 #endif
85026 
85027  assert( pCsr->pKeyInfo && pCsr->pBt==0 );
85028  assert( pCsr->eCurType==CURTYPE_SORTER );
85029  szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
85030  sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
85031 
85032  pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
85033  pCsr->uc.pSorter = pSorter;
85034  if( pSorter==0 ){
85035  rc = SQLITE_NOMEM_BKPT;
85036  }else{
85037  pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
85038  memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
85039  pKeyInfo->db = 0;
85040  if( nField && nWorker==0 ){
85041  pKeyInfo->nXField += (pKeyInfo->nField - nField);
85042  pKeyInfo->nField = nField;
85043  }
85044  pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
85045  pSorter->nTask = nWorker + 1;
85046  pSorter->iPrev = (u8)(nWorker - 1);
85047  pSorter->bUseThreads = (pSorter->nTask>1);
85048  pSorter->db = db;
85049  for(i=0; i<pSorter->nTask; i++){
85050  SortSubtask *pTask = &pSorter->aTask[i];
85051  pTask->pSorter = pSorter;
85052  }
85053 
85054  if( !sqlite3TempInMemory(db) ){
85055  i64 mxCache; /* Cache size in bytes*/
85056  u32 szPma = sqlite3GlobalConfig.szPma;
85057  pSorter->mnPmaSize = szPma * pgsz;
85058 
85059  mxCache = db->aDb[0].pSchema->cache_size;
85060  if( mxCache<0 ){
85061  /* A negative cache-size value C indicates that the cache is abs(C)
85062  ** KiB in size. */
85063  mxCache = mxCache * -1024;
85064  }else{
85065  mxCache = mxCache * pgsz;
85066  }
85067  mxCache = MIN(mxCache, SQLITE_MAX_PMASZ);
85068  pSorter->mxPmaSize = MAX(pSorter->mnPmaSize, (int)mxCache);
85069 
85070  /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
85071  ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
85072  ** large heap allocations.
85073  */
85074  if( sqlite3GlobalConfig.pScratch==0 ){
85075  assert( pSorter->iMemory==0 );
85076  pSorter->nMemory = pgsz;
85077  pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
85078  if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM_BKPT;
85079  }
85080  }
85081 
85082  if( (pKeyInfo->nField+pKeyInfo->nXField)<13
85083  && (pKeyInfo->aColl[0]==0 || pKeyInfo->aColl[0]==db->pDfltColl)
85084  ){
85086  }
85087  }
85088 
85089  return rc;
85090 }
85091 #undef nWorker /* Defined at the top of this function */
85092 
85093 /*
85094 ** Free the list of sorted records starting at pRecord.
85095 */
85096 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
85097  SorterRecord *p;
85098  SorterRecord *pNext;
85099  for(p=pRecord; p; p=pNext){
85100  pNext = p->u.pNext;
85101  sqlite3DbFree(db, p);
85102  }
85103 }
85104 
85105 /*
85106 ** Free all resources owned by the object indicated by argument pTask. All
85107 ** fields of *pTask are zeroed before returning.
85108 */
85109 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
85110  sqlite3DbFree(db, pTask->pUnpacked);
85111 #if SQLITE_MAX_WORKER_THREADS>0
85112  /* pTask->list.aMemory can only be non-zero if it was handed memory
85113  ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
85114  if( pTask->list.aMemory ){
85115  sqlite3_free(pTask->list.aMemory);
85116  }else
85117 #endif
85118  {
85119  assert( pTask->list.aMemory==0 );
85120  vdbeSorterRecordFree(0, pTask->list.pList);
85121  }
85122  if( pTask->file.pFd ){
85123  sqlite3OsCloseFree(pTask->file.pFd);
85124  }
85125  if( pTask->file2.pFd ){
85126  sqlite3OsCloseFree(pTask->file2.pFd);
85127  }
85128  memset(pTask, 0, sizeof(SortSubtask));
85129 }
85130 
85131 #ifdef SQLITE_DEBUG_SORTER_THREADS
85132 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
85133  i64 t;
85134  int iTask = (pTask - pTask->pSorter->aTask);
85135  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85136  fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
85137 }
85138 static void vdbeSorterRewindDebug(const char *zEvent){
85139  i64 t;
85141  fprintf(stderr, "%lld:X %s\n", t, zEvent);
85142 }
85143 static void vdbeSorterPopulateDebug(
85144  SortSubtask *pTask,
85145  const char *zEvent
85146 ){
85147  i64 t;
85148  int iTask = (pTask - pTask->pSorter->aTask);
85149  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85150  fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
85151 }
85152 static void vdbeSorterBlockDebug(
85153  SortSubtask *pTask,
85154  int bBlocked,
85155  const char *zEvent
85156 ){
85157  if( bBlocked ){
85158  i64 t;
85159  sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
85160  fprintf(stderr, "%lld:main %s\n", t, zEvent);
85161  }
85162 }
85163 #else
85164 # define vdbeSorterWorkDebug(x,y)
85165 # define vdbeSorterRewindDebug(y)
85166 # define vdbeSorterPopulateDebug(x,y)
85167 # define vdbeSorterBlockDebug(x,y,z)
85168 #endif
85169 
85170 #if SQLITE_MAX_WORKER_THREADS>0
85171 /*
85172 ** Join thread pTask->thread.
85173 */
85174 static int vdbeSorterJoinThread(SortSubtask *pTask){
85175  int rc = SQLITE_OK;
85176  if( pTask->pThread ){
85177 #ifdef SQLITE_DEBUG_SORTER_THREADS
85178  int bDone = pTask->bDone;
85179 #endif
85180  void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
85181  vdbeSorterBlockDebug(pTask, !bDone, "enter");
85182  (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
85183  vdbeSorterBlockDebug(pTask, !bDone, "exit");
85184  rc = SQLITE_PTR_TO_INT(pRet);
85185  assert( pTask->bDone==1 );
85186  pTask->bDone = 0;
85187  pTask->pThread = 0;
85188  }
85189  return rc;
85190 }
85191 
85192 /*
85193 ** Launch a background thread to run xTask(pIn).
85194 */
85196  SortSubtask *pTask, /* Thread will use this task object */
85197  void *(*xTask)(void*), /* Routine to run in a separate thread */
85198  void *pIn /* Argument passed into xTask() */
85199 ){
85200  assert( pTask->pThread==0 && pTask->bDone==0 );
85201  return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
85202 }
85203 
85204 /*
85205 ** Join all outstanding threads launched by SorterWrite() to create
85206 ** level-0 PMAs.
85207 */
85208 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
85209  int rc = rcin;
85210  int i;
85211 
85212  /* This function is always called by the main user thread.
85213  **
85214  ** If this function is being called after SorterRewind() has been called,
85215  ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
85216  ** is currently attempt to join one of the other threads. To avoid a race
85217  ** condition where this thread also attempts to join the same object, join
85218  ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
85219  for(i=pSorter->nTask-1; i>=0; i--){
85220  SortSubtask *pTask = &pSorter->aTask[i];
85221  int rc2 = vdbeSorterJoinThread(pTask);
85222  if( rc==SQLITE_OK ) rc = rc2;
85223  }
85224  return rc;
85225 }
85226 #else
85227 # define vdbeSorterJoinAll(x,rcin) (rcin)
85228 # define vdbeSorterJoinThread(pTask) SQLITE_OK
85229 #endif
85230 
85231 /*
85232 ** Allocate a new MergeEngine object capable of handling up to
85233 ** nReader PmaReader inputs.
85234 **
85235 ** nReader is automatically rounded up to the next power of two.
85236 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
85237 */
85238 static MergeEngine *vdbeMergeEngineNew(int nReader){
85239  int N = 2; /* Smallest power of two >= nReader */
85240  int nByte; /* Total bytes of space to allocate */
85241  MergeEngine *pNew; /* Pointer to allocated object to return */
85242 
85243  assert( nReader<=SORTER_MAX_MERGE_COUNT );
85244 
85245  while( N<nReader ) N += N;
85246  nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
85247 
85248  pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
85249  if( pNew ){
85250  pNew->nTree = N;
85251  pNew->pTask = 0;
85252  pNew->aReadr = (PmaReader*)&pNew[1];
85253  pNew->aTree = (int*)&pNew->aReadr[N];
85254  }
85255  return pNew;
85256 }
85257 
85258 /*
85259 ** Free the MergeEngine object passed as the only argument.
85260 */
85261 static void vdbeMergeEngineFree(MergeEngine *pMerger){
85262  int i;
85263  if( pMerger ){
85264  for(i=0; i<pMerger->nTree; i++){
85265  vdbePmaReaderClear(&pMerger->aReadr[i]);
85266  }
85267  }
85268  sqlite3_free(pMerger);
85269 }
85270 
85271 /*
85272 ** Free all resources associated with the IncrMerger object indicated by
85273 ** the first argument.
85274 */
85275 static void vdbeIncrFree(IncrMerger *pIncr){
85276  if( pIncr ){
85277 #if SQLITE_MAX_WORKER_THREADS>0
85278  if( pIncr->bUseThread ){
85279  vdbeSorterJoinThread(pIncr->pTask);
85280  if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
85281  if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
85282  }
85283 #endif
85284  vdbeMergeEngineFree(pIncr->pMerger);
85285  sqlite3_free(pIncr);
85286  }
85287 }
85288 
85289 /*
85290 ** Reset a sorting cursor back to its original empty state.
85291 */
85293  int i;
85294  (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
85295  assert( pSorter->bUseThreads || pSorter->pReader==0 );
85296 #if SQLITE_MAX_WORKER_THREADS>0
85297  if( pSorter->pReader ){
85298  vdbePmaReaderClear(pSorter->pReader);
85299  sqlite3DbFree(db, pSorter->pReader);
85300  pSorter->pReader = 0;
85301  }
85302 #endif
85303  vdbeMergeEngineFree(pSorter->pMerger);
85304  pSorter->pMerger = 0;
85305  for(i=0; i<pSorter->nTask; i++){
85306  SortSubtask *pTask = &pSorter->aTask[i];
85307  vdbeSortSubtaskCleanup(db, pTask);
85308  pTask->pSorter = pSorter;
85309  }
85310  if( pSorter->list.aMemory==0 ){
85311  vdbeSorterRecordFree(0, pSorter->list.pList);
85312  }
85313  pSorter->list.pList = 0;
85314  pSorter->list.szPMA = 0;
85315  pSorter->bUsePMA = 0;
85316  pSorter->iMemory = 0;
85317  pSorter->mxKeysize = 0;
85318  sqlite3DbFree(db, pSorter->pUnpacked);
85319  pSorter->pUnpacked = 0;
85320 }
85321 
85322 /*
85323 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
85324 */
85326  VdbeSorter *pSorter;
85327  assert( pCsr->eCurType==CURTYPE_SORTER );
85328  pSorter = pCsr->uc.pSorter;
85329  if( pSorter ){
85330  sqlite3VdbeSorterReset(db, pSorter);
85331  sqlite3_free(pSorter->list.aMemory);
85332  sqlite3DbFree(db, pSorter);
85333  pCsr->uc.pSorter = 0;
85334  }
85335 }
85336 
85337 #if SQLITE_MAX_MMAP_SIZE>0
85338 /*
85339 ** The first argument is a file-handle open on a temporary file. The file
85340 ** is guaranteed to be nByte bytes or smaller in size. This function
85341 ** attempts to extend the file to nByte bytes in size and to ensure that
85342 ** the VFS has memory mapped it.
85343 **
85344 ** Whether or not the file does end up memory mapped of course depends on
85345 ** the specific VFS implementation.
85346 */
85347 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
85348  if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
85349  void *p = 0;
85350  int chunksize = 4*1024;
85353  sqlite3OsFetch(pFd, 0, (int)nByte, &p);
85354  sqlite3OsUnfetch(pFd, 0, p);
85355  }
85356 }
85357 #else
85358 # define vdbeSorterExtendFile(x,y,z)
85359 #endif
85360 
85361 /*
85362 ** Allocate space for a file-handle and open a temporary file. If successful,
85363 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
85364 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
85365 */
85367  sqlite3 *db, /* Database handle doing sort */
85368  i64 nExtend, /* Attempt to extend file to this size */
85369  sqlite3_file **ppFd
85370 ){
85371  int rc;
85372  if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
85373  rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
85377  );
85378  if( rc==SQLITE_OK ){
85379  i64 max = SQLITE_MAX_MMAP_SIZE;
85380  sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
85381  if( nExtend>0 ){
85382  vdbeSorterExtendFile(db, *ppFd, nExtend);
85383  }
85384  }
85385  return rc;
85386 }
85387 
85388 /*
85389 ** If it has not already been allocated, allocate the UnpackedRecord
85390 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
85391 ** if no allocation was required), or SQLITE_NOMEM otherwise.
85392 */
85393 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
85394  if( pTask->pUnpacked==0 ){
85395  char *pFree;
85397  pTask->pSorter->pKeyInfo, 0, 0, &pFree
85398  );
85399  assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
85400  if( pFree==0 ) return SQLITE_NOMEM_BKPT;
85401  pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
85402  pTask->pUnpacked->errCode = 0;
85403  }
85404  return SQLITE_OK;
85405 }
85406 
85407 
85408 /*
85409 ** Merge the two sorted lists p1 and p2 into a single list.
85410 ** Set *ppOut to the head of the new list.
85411 */
85412 static void vdbeSorterMerge(
85413  SortSubtask *pTask, /* Calling thread context */
85414  SorterRecord *p1, /* First list to merge */
85415  SorterRecord *p2, /* Second list to merge */
85416  SorterRecord **ppOut /* OUT: Head of merged list */
85417 ){
85418  SorterRecord *pFinal = 0;
85419  SorterRecord **pp = &pFinal;
85420  int bCached = 0;
85421 
85422  while( p1 && p2 ){
85423  int res;
85424  res = pTask->xCompare(
85425  pTask, &bCached, SRVAL(p1), p1->nVal, SRVAL(p2), p2->nVal
85426  );
85427 
85428  if( res<=0 ){
85429  *pp = p1;
85430  pp = &p1->u.pNext;
85431  p1 = p1->u.pNext;
85432  }else{
85433  *pp = p2;
85434  pp = &p2->u.pNext;
85435  p2 = p2->u.pNext;
85436  bCached = 0;
85437  }
85438  }
85439  *pp = p1 ? p1 : p2;
85440  *ppOut = pFinal;
85441 }
85442 
85443 /*
85444 ** Return the SorterCompare function to compare values collected by the
85445 ** sorter object passed as the only argument.
85446 */
85448  if( p->typeMask==SORTER_TYPE_INTEGER ){
85449  return vdbeSorterCompareInt;
85450  }else if( p->typeMask==SORTER_TYPE_TEXT ){
85451  return vdbeSorterCompareText;
85452  }
85453  return vdbeSorterCompare;
85454 }
85455 
85456 /*
85457 ** Sort the linked list of records headed at pTask->pList. Return
85458 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
85459 ** an error occurs.
85460 */
85461 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
85462  int i;
85463  SorterRecord **aSlot;
85464  SorterRecord *p;
85465  int rc;
85466 
85467  rc = vdbeSortAllocUnpacked(pTask);
85468  if( rc!=SQLITE_OK ) return rc;
85469 
85470  p = pList->pList;
85471  pTask->xCompare = vdbeSorterGetCompare(pTask->pSorter);
85472 
85473  aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
85474  if( !aSlot ){
85475  return SQLITE_NOMEM_BKPT;
85476  }
85477 
85478  while( p ){
85479  SorterRecord *pNext;
85480  if( pList->aMemory ){
85481  if( (u8*)p==pList->aMemory ){
85482  pNext = 0;
85483  }else{
85484  assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
85485  pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
85486  }
85487  }else{
85488  pNext = p->u.pNext;
85489  }
85490 
85491  p->u.pNext = 0;
85492  for(i=0; aSlot[i]; i++){
85493  vdbeSorterMerge(pTask, p, aSlot[i], &p);
85494  aSlot[i] = 0;
85495  }
85496  aSlot[i] = p;
85497  p = pNext;
85498  }
85499 
85500  p = 0;
85501  for(i=0; i<64; i++){
85502  vdbeSorterMerge(pTask, p, aSlot[i], &p);
85503  }
85504  pList->pList = p;
85505 
85506  sqlite3_free(aSlot);
85507  assert( pTask->pUnpacked->errCode==SQLITE_OK
85508  || pTask->pUnpacked->errCode==SQLITE_NOMEM
85509  );
85510  return pTask->pUnpacked->errCode;
85511 }
85512 
85513 /*
85514 ** Initialize a PMA-writer object.
85515 */
85516 static void vdbePmaWriterInit(
85517  sqlite3_file *pFd, /* File handle to write to */
85518  PmaWriter *p, /* Object to populate */
85519  int nBuf, /* Buffer size */
85520  i64 iStart /* Offset of pFd to begin writing at */
85521 ){
85522  memset(p, 0, sizeof(PmaWriter));
85523  p->aBuffer = (u8*)sqlite3Malloc(nBuf);
85524  if( !p->aBuffer ){
85526  }else{
85527  p->iBufEnd = p->iBufStart = (iStart % nBuf);
85528  p->iWriteOff = iStart - p->iBufStart;
85529  p->nBuffer = nBuf;
85530  p->pFd = pFd;
85531  }
85532 }
85533 
85534 /*
85535 ** Write nData bytes of data to the PMA. Return SQLITE_OK
85536 ** if successful, or an SQLite error code if an error occurs.
85537 */
85538 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
85539  int nRem = nData;
85540  while( nRem>0 && p->eFWErr==0 ){
85541  int nCopy = nRem;
85542  if( nCopy>(p->nBuffer - p->iBufEnd) ){
85543  nCopy = p->nBuffer - p->iBufEnd;
85544  }
85545 
85546  memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
85547  p->iBufEnd += nCopy;
85548  if( p->iBufEnd==p->nBuffer ){
85549  p->eFWErr = sqlite3OsWrite(p->pFd,
85550  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
85551  p->iWriteOff + p->iBufStart
85552  );
85553  p->iBufStart = p->iBufEnd = 0;
85554  p->iWriteOff += p->nBuffer;
85555  }
85556  assert( p->iBufEnd<p->nBuffer );
85557 
85558  nRem -= nCopy;
85559  }
85560 }
85561 
85562 /*
85563 ** Flush any buffered data to disk and clean up the PMA-writer object.
85564 ** The results of using the PMA-writer after this call are undefined.
85565 ** Return SQLITE_OK if flushing the buffered data succeeds or is not
85566 ** required. Otherwise, return an SQLite error code.
85567 **
85568 ** Before returning, set *piEof to the offset immediately following the
85569 ** last byte written to the file.
85570 */
85571 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
85572  int rc;
85573  if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
85574  p->eFWErr = sqlite3OsWrite(p->pFd,
85575  &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
85576  p->iWriteOff + p->iBufStart
85577  );
85578  }
85579  *piEof = (p->iWriteOff + p->iBufEnd);
85580  sqlite3_free(p->aBuffer);
85581  rc = p->eFWErr;
85582  memset(p, 0, sizeof(PmaWriter));
85583  return rc;
85584 }
85585 
85586 /*
85587 ** Write value iVal encoded as a varint to the PMA. Return
85588 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
85589 */
85590 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
85591  int nByte;
85592  u8 aByte[10];
85593  nByte = sqlite3PutVarint(aByte, iVal);
85594  vdbePmaWriteBlob(p, aByte, nByte);
85595 }
85596 
85597 /*
85598 ** Write the current contents of in-memory linked-list pList to a level-0
85599 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
85600 ** successful, or an SQLite error code otherwise.
85601 **
85602 ** The format of a PMA is:
85603 **
85604 ** * A varint. This varint contains the total number of bytes of content
85605 ** in the PMA (not including the varint itself).
85606 **
85607 ** * One or more records packed end-to-end in order of ascending keys.
85608 ** Each record consists of a varint followed by a blob of data (the
85609 ** key). The varint is the number of bytes in the blob of data.
85610 */
85611 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
85612  sqlite3 *db = pTask->pSorter->db;
85613  int rc = SQLITE_OK; /* Return code */
85614  PmaWriter writer; /* Object used to write to the file */
85615 
85616 #ifdef SQLITE_DEBUG
85617  /* Set iSz to the expected size of file pTask->file after writing the PMA.
85618  ** This is used by an assert() statement at the end of this function. */
85619  i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
85620 #endif
85621 
85622  vdbeSorterWorkDebug(pTask, "enter");
85623  memset(&writer, 0, sizeof(PmaWriter));
85624  assert( pList->szPMA>0 );
85625 
85626  /* If the first temporary PMA file has not been opened, open it now. */
85627  if( pTask->file.pFd==0 ){
85628  rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
85629  assert( rc!=SQLITE_OK || pTask->file.pFd );
85630  assert( pTask->file.iEof==0 );
85631  assert( pTask->nPMA==0 );
85632  }
85633 
85634  /* Try to get the file to memory map */
85635  if( rc==SQLITE_OK ){
85636  vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
85637  }
85638 
85639  /* Sort the list */
85640  if( rc==SQLITE_OK ){
85641  rc = vdbeSorterSort(pTask, pList);
85642  }
85643 
85644  if( rc==SQLITE_OK ){
85645  SorterRecord *p;
85646  SorterRecord *pNext = 0;
85647 
85648  vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
85649  pTask->file.iEof);
85650  pTask->nPMA++;
85651  vdbePmaWriteVarint(&writer, pList->szPMA);
85652  for(p=pList->pList; p; p=pNext){
85653  pNext = p->u.pNext;
85654  vdbePmaWriteVarint(&writer, p->nVal);
85655  vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
85656  if( pList->aMemory==0 ) sqlite3_free(p);
85657  }
85658  pList->pList = p;
85659  rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
85660  }
85661 
85662  vdbeSorterWorkDebug(pTask, "exit");
85663  assert( rc!=SQLITE_OK || pList->pList==0 );
85664  assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
85665  return rc;
85666 }
85667 
85668 /*
85669 ** Advance the MergeEngine to its next entry.
85670 ** Set *pbEof to true there is no next entry because
85671 ** the MergeEngine has reached the end of all its inputs.
85672 **
85673 ** Return SQLITE_OK if successful or an error code if an error occurs.
85674 */
85676  MergeEngine *pMerger, /* The merge engine to advance to the next row */
85677  int *pbEof /* Set TRUE at EOF. Set false for more content */
85678 ){
85679  int rc;
85680  int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
85681  SortSubtask *pTask = pMerger->pTask;
85682 
85683  /* Advance the current PmaReader */
85684  rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
85685 
85686  /* Update contents of aTree[] */
85687  if( rc==SQLITE_OK ){
85688  int i; /* Index of aTree[] to recalculate */
85689  PmaReader *pReadr1; /* First PmaReader to compare */
85690  PmaReader *pReadr2; /* Second PmaReader to compare */
85691  int bCached = 0;
85692 
85693  /* Find the first two PmaReaders to compare. The one that was just
85694  ** advanced (iPrev) and the one next to it in the array. */
85695  pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
85696  pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
85697 
85698  for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
85699  /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
85700  int iRes;
85701  if( pReadr1->pFd==0 ){
85702  iRes = +1;
85703  }else if( pReadr2->pFd==0 ){
85704  iRes = -1;
85705  }else{
85706  iRes = pTask->xCompare(pTask, &bCached,
85707  pReadr1->aKey, pReadr1->nKey, pReadr2->aKey, pReadr2->nKey
85708  );
85709  }
85710 
85711  /* If pReadr1 contained the smaller value, set aTree[i] to its index.
85712  ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
85713  ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
85714  ** pKey2 to point to the record belonging to pReadr2.
85715  **
85716  ** Alternatively, if pReadr2 contains the smaller of the two values,
85717  ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
85718  ** was actually called above, then pTask->pUnpacked now contains
85719  ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
85720  ** vdbeSorterCompare() from decoding pReadr2 again.
85721  **
85722  ** If the two values were equal, then the value from the oldest
85723  ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
85724  ** is sorted from oldest to newest, so pReadr1 contains older values
85725  ** than pReadr2 iff (pReadr1<pReadr2). */
85726  if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
85727  pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
85728  pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
85729  bCached = 0;
85730  }else{
85731  if( pReadr1->pFd ) bCached = 0;
85732  pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
85733  pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
85734  }
85735  }
85736  *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
85737  }
85738 
85739  return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
85740 }
85741 
85742 #if SQLITE_MAX_WORKER_THREADS>0
85743 /*
85744 ** The main routine for background threads that write level-0 PMAs.
85745 */
85746 static void *vdbeSorterFlushThread(void *pCtx){
85747  SortSubtask *pTask = (SortSubtask*)pCtx;
85748  int rc; /* Return code */
85749  assert( pTask->bDone==0 );
85750  rc = vdbeSorterListToPMA(pTask, &pTask->list);
85751  pTask->bDone = 1;
85752  return SQLITE_INT_TO_PTR(rc);
85753 }
85754 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
85755 
85756 /*
85757 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
85758 ** using a background thread.
85759 */
85760 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
85761 #if SQLITE_MAX_WORKER_THREADS==0
85762  pSorter->bUsePMA = 1;
85763  return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
85764 #else
85765  int rc = SQLITE_OK;
85766  int i;
85767  SortSubtask *pTask = 0; /* Thread context used to create new PMA */
85768  int nWorker = (pSorter->nTask-1);
85769 
85770  /* Set the flag to indicate that at least one PMA has been written.
85771  ** Or will be, anyhow. */
85772  pSorter->bUsePMA = 1;
85773 
85774  /* Select a sub-task to sort and flush the current list of in-memory
85775  ** records to disk. If the sorter is running in multi-threaded mode,
85776  ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
85777  ** the background thread from a sub-tasks previous turn is still running,
85778  ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
85779  ** fall back to using the final sub-task. The first (pSorter->nTask-1)
85780  ** sub-tasks are prefered as they use background threads - the final
85781  ** sub-task uses the main thread. */
85782  for(i=0; i<nWorker; i++){
85783  int iTest = (pSorter->iPrev + i + 1) % nWorker;
85784  pTask = &pSorter->aTask[iTest];
85785  if( pTask->bDone ){
85786  rc = vdbeSorterJoinThread(pTask);
85787  }
85788  if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
85789  }
85790 
85791  if( rc==SQLITE_OK ){
85792  if( i==nWorker ){
85793  /* Use the foreground thread for this operation */
85794  rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
85795  }else{
85796  /* Launch a background thread for this operation */
85797  u8 *aMem = pTask->list.aMemory;
85798  void *pCtx = (void*)pTask;
85799 
85800  assert( pTask->pThread==0 && pTask->bDone==0 );
85801  assert( pTask->list.pList==0 );
85802  assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
85803 
85804  pSorter->iPrev = (u8)(pTask - pSorter->aTask);
85805  pTask->list = pSorter->list;
85806  pSorter->list.pList = 0;
85807  pSorter->list.szPMA = 0;
85808  if( aMem ){
85809  pSorter->list.aMemory = aMem;
85810  pSorter->nMemory = sqlite3MallocSize(aMem);
85811  }else if( pSorter->list.aMemory ){
85812  pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
85813  if( !pSorter->list.aMemory ) return SQLITE_NOMEM_BKPT;
85814  }
85815 
85816  rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
85817  }
85818  }
85819 
85820  return rc;
85821 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
85822 }
85823 
85824 /*
85825 ** Add a record to the sorter.
85826 */
85828  const VdbeCursor *pCsr, /* Sorter cursor */
85829  Mem *pVal /* Memory cell containing record */
85830 ){
85831  VdbeSorter *pSorter;
85832  int rc = SQLITE_OK; /* Return Code */
85833  SorterRecord *pNew; /* New list element */
85834  int bFlush; /* True to flush contents of memory to PMA */
85835  int nReq; /* Bytes of memory required */
85836  int nPMA; /* Bytes of PMA space required */
85837  int t; /* serial type of first record field */
85838 
85839  assert( pCsr->eCurType==CURTYPE_SORTER );
85840  pSorter = pCsr->uc.pSorter;
85841  getVarint32((const u8*)&pVal->z[1], t);
85842  if( t>0 && t<10 && t!=7 ){
85843  pSorter->typeMask &= SORTER_TYPE_INTEGER;
85844  }else if( t>10 && (t & 0x01) ){
85845  pSorter->typeMask &= SORTER_TYPE_TEXT;
85846  }else{
85847  pSorter->typeMask = 0;
85848  }
85849 
85850  assert( pSorter );
85851 
85852  /* Figure out whether or not the current contents of memory should be
85853  ** flushed to a PMA before continuing. If so, do so.
85854  **
85855  ** If using the single large allocation mode (pSorter->aMemory!=0), then
85856  ** flush the contents of memory to a new PMA if (a) at least one value is
85857  ** already in memory and (b) the new value will not fit in memory.
85858  **
85859  ** Or, if using separate allocations for each record, flush the contents
85860  ** of memory to a PMA if either of the following are true:
85861  **
85862  ** * The total memory allocated for the in-memory list is greater
85863  ** than (page-size * cache-size), or
85864  **
85865  ** * The total memory allocated for the in-memory list is greater
85866  ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
85867  */
85868  nReq = pVal->n + sizeof(SorterRecord);
85869  nPMA = pVal->n + sqlite3VarintLen(pVal->n);
85870  if( pSorter->mxPmaSize ){
85871  if( pSorter->list.aMemory ){
85872  bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
85873  }else{
85874  bFlush = (
85875  (pSorter->list.szPMA > pSorter->mxPmaSize)
85876  || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
85877  );
85878  }
85879  if( bFlush ){
85880  rc = vdbeSorterFlushPMA(pSorter);
85881  pSorter->list.szPMA = 0;
85882  pSorter->iMemory = 0;
85883  assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
85884  }
85885  }
85886 
85887  pSorter->list.szPMA += nPMA;
85888  if( nPMA>pSorter->mxKeysize ){
85889  pSorter->mxKeysize = nPMA;
85890  }
85891 
85892  if( pSorter->list.aMemory ){
85893  int nMin = pSorter->iMemory + nReq;
85894 
85895  if( nMin>pSorter->nMemory ){
85896  u8 *aNew;
85897  int iListOff = (u8*)pSorter->list.pList - pSorter->list.aMemory;
85898  int nNew = pSorter->nMemory * 2;
85899  while( nNew < nMin ) nNew = nNew*2;
85900  if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
85901  if( nNew < nMin ) nNew = nMin;
85902 
85903  aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
85904  if( !aNew ) return SQLITE_NOMEM_BKPT;
85905  pSorter->list.pList = (SorterRecord*)&aNew[iListOff];
85906  pSorter->list.aMemory = aNew;
85907  pSorter->nMemory = nNew;
85908  }
85909 
85910  pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
85911  pSorter->iMemory += ROUND8(nReq);
85912  if( pSorter->list.pList ){
85913  pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
85914  }
85915  }else{
85916  pNew = (SorterRecord *)sqlite3Malloc(nReq);
85917  if( pNew==0 ){
85918  return SQLITE_NOMEM_BKPT;
85919  }
85920  pNew->u.pNext = pSorter->list.pList;
85921  }
85922 
85923  memcpy(SRVAL(pNew), pVal->z, pVal->n);
85924  pNew->nVal = pVal->n;
85925  pSorter->list.pList = pNew;
85926 
85927  return rc;
85928 }
85929 
85930 /*
85931 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
85932 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
85933 ** except that the number-of-bytes varint is omitted from the start.
85934 */
85935 static int vdbeIncrPopulate(IncrMerger *pIncr){
85936  int rc = SQLITE_OK;
85937  int rc2;
85938  i64 iStart = pIncr->iStartOff;
85939  SorterFile *pOut = &pIncr->aFile[1];
85940  SortSubtask *pTask = pIncr->pTask;
85941  MergeEngine *pMerger = pIncr->pMerger;
85942  PmaWriter writer;
85943  assert( pIncr->bEof==0 );
85944 
85945  vdbeSorterPopulateDebug(pTask, "enter");
85946 
85947  vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
85948  while( rc==SQLITE_OK ){
85949  int dummy;
85950  PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
85951  int nKey = pReader->nKey;
85952  i64 iEof = writer.iWriteOff + writer.iBufEnd;
85953 
85954  /* Check if the output file is full or if the input has been exhausted.
85955  ** In either case exit the loop. */
85956  if( pReader->pFd==0 ) break;
85957  if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
85958 
85959  /* Write the next key to the output. */
85960  vdbePmaWriteVarint(&writer, nKey);
85961  vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
85962  assert( pIncr->pMerger->pTask==pTask );
85963  rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
85964  }
85965 
85966  rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
85967  if( rc==SQLITE_OK ) rc = rc2;
85968  vdbeSorterPopulateDebug(pTask, "exit");
85969  return rc;
85970 }
85971 
85972 #if SQLITE_MAX_WORKER_THREADS>0
85973 /*
85974 ** The main routine for background threads that populate aFile[1] of
85975 ** multi-threaded IncrMerger objects.
85976 */
85977 static void *vdbeIncrPopulateThread(void *pCtx){
85978  IncrMerger *pIncr = (IncrMerger*)pCtx;
85979  void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
85980  pIncr->pTask->bDone = 1;
85981  return pRet;
85982 }
85983 
85984 /*
85985 ** Launch a background thread to populate aFile[1] of pIncr.
85986 */
85987 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
85988  void *p = (void*)pIncr;
85989  assert( pIncr->bUseThread );
85991 }
85992 #endif
85993 
85994 /*
85995 ** This function is called when the PmaReader corresponding to pIncr has
85996 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
85997 ** aFile[0] such that the PmaReader should start rereading it from the
85998 ** beginning.
85999 **
86000 ** For single-threaded objects, this is accomplished by literally reading
86001 ** keys from pIncr->pMerger and repopulating aFile[0].
86002 **
86003 ** For multi-threaded objects, all that is required is to wait until the
86004 ** background thread is finished (if it is not already) and then swap
86005 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
86006 ** been exhausted, this function also launches a new background thread
86007 ** to populate the new aFile[1].
86008 **
86009 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
86010 */
86011 static int vdbeIncrSwap(IncrMerger *pIncr){
86012  int rc = SQLITE_OK;
86013 
86014 #if SQLITE_MAX_WORKER_THREADS>0
86015  if( pIncr->bUseThread ){
86016  rc = vdbeSorterJoinThread(pIncr->pTask);
86017 
86018  if( rc==SQLITE_OK ){
86019  SorterFile f0 = pIncr->aFile[0];
86020  pIncr->aFile[0] = pIncr->aFile[1];
86021  pIncr->aFile[1] = f0;
86022  }
86023 
86024  if( rc==SQLITE_OK ){
86025  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86026  pIncr->bEof = 1;
86027  }else{
86028  rc = vdbeIncrBgPopulate(pIncr);
86029  }
86030  }
86031  }else
86032 #endif
86033  {
86034  rc = vdbeIncrPopulate(pIncr);
86035  pIncr->aFile[0] = pIncr->aFile[1];
86036  if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
86037  pIncr->bEof = 1;
86038  }
86039  }
86040 
86041  return rc;
86042 }
86043 
86044 /*
86045 ** Allocate and return a new IncrMerger object to read data from pMerger.
86046 **
86047 ** If an OOM condition is encountered, return NULL. In this case free the
86048 ** pMerger argument before returning.
86049 */
86051  SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
86052  MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
86053  IncrMerger **ppOut /* Write the new IncrMerger here */
86054 ){
86055  int rc = SQLITE_OK;
86056  IncrMerger *pIncr = *ppOut = (IncrMerger*)
86057  (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
86058  if( pIncr ){
86059  pIncr->pMerger = pMerger;
86060  pIncr->pTask = pTask;
86061  pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
86062  pTask->file2.iEof += pIncr->mxSz;
86063  }else{
86064  vdbeMergeEngineFree(pMerger);
86065  rc = SQLITE_NOMEM_BKPT;
86066  }
86067  return rc;
86068 }
86069 
86070 #if SQLITE_MAX_WORKER_THREADS>0
86071 /*
86072 ** Set the "use-threads" flag on object pIncr.
86073 */
86075  pIncr->bUseThread = 1;
86076  pIncr->pTask->file2.iEof -= pIncr->mxSz;
86077 }
86078 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
86079 
86080 
86081 
86082 /*
86083 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
86084 ** two PmaReaders that feed that entry. Neither of the PmaReaders
86085 ** are advanced. This routine merely does the comparison.
86086 */
86088  MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
86089  int iOut /* Store the result in pMerger->aTree[iOut] */
86090 ){
86091  int i1;
86092  int i2;
86093  int iRes;
86094  PmaReader *p1;
86095  PmaReader *p2;
86096 
86097  assert( iOut<pMerger->nTree && iOut>0 );
86098 
86099  if( iOut>=(pMerger->nTree/2) ){
86100  i1 = (iOut - pMerger->nTree/2) * 2;
86101  i2 = i1 + 1;
86102  }else{
86103  i1 = pMerger->aTree[iOut*2];
86104  i2 = pMerger->aTree[iOut*2+1];
86105  }
86106 
86107  p1 = &pMerger->aReadr[i1];
86108  p2 = &pMerger->aReadr[i2];
86109 
86110  if( p1->pFd==0 ){
86111  iRes = i2;
86112  }else if( p2->pFd==0 ){
86113  iRes = i1;
86114  }else{
86115  SortSubtask *pTask = pMerger->pTask;
86116  int bCached = 0;
86117  int res;
86118  assert( pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
86119  res = pTask->xCompare(
86120  pTask, &bCached, p1->aKey, p1->nKey, p2->aKey, p2->nKey
86121  );
86122  if( res<=0 ){
86123  iRes = i1;
86124  }else{
86125  iRes = i2;
86126  }
86127  }
86128 
86129  pMerger->aTree[iOut] = iRes;
86130 }
86131 
86132 /*
86133 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
86134 ** and vdbePmaReaderIncrMergeInit().
86135 **
86136 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
86137 ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
86138 ** when there exists one or more separate worker threads.
86139 */
86140 #define INCRINIT_NORMAL 0
86141 #define INCRINIT_TASK 1
86142 #define INCRINIT_ROOT 2
86143 
86144 /*
86145 ** Forward reference required as the vdbeIncrMergeInit() and
86146 ** vdbePmaReaderIncrInit() routines are called mutually recursively when
86147 ** building a merge tree.
86148 */
86149 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode);
86150 
86151 /*
86152 ** Initialize the MergeEngine object passed as the second argument. Once this
86153 ** function returns, the first key of merged data may be read from the
86154 ** MergeEngine object in the usual fashion.
86155 **
86156 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
86157 ** objects attached to the PmaReader objects that the merger reads from have
86158 ** already been populated, but that they have not yet populated aFile[0] and
86159 ** set the PmaReader objects up to read from it. In this case all that is
86160 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
86161 ** its first key.
86162 **
86163 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
86164 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
86165 ** to pMerger.
86166 **
86167 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86168 */
86170  SortSubtask *pTask, /* Thread that will run pMerger */
86171  MergeEngine *pMerger, /* MergeEngine to initialize */
86172  int eMode /* One of the INCRINIT_XXX constants */
86173 ){
86174  int rc = SQLITE_OK; /* Return code */
86175  int i; /* For looping over PmaReader objects */
86176  int nTree = pMerger->nTree;
86177 
86178  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86180 
86181  /* Verify that the MergeEngine is assigned to a single thread */
86182  assert( pMerger->pTask==0 );
86183  pMerger->pTask = pTask;
86184 
86185  for(i=0; i<nTree; i++){
86186  if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
86187  /* PmaReaders should be normally initialized in order, as if they are
86188  ** reading from the same temp file this makes for more linear file IO.
86189  ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
86190  ** in use it will block the vdbePmaReaderNext() call while it uses
86191  ** the main thread to fill its buffer. So calling PmaReaderNext()
86192  ** on this PmaReader before any of the multi-threaded PmaReaders takes
86193  ** better advantage of multi-processor hardware. */
86194  rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
86195  }else{
86196  rc = vdbePmaReaderIncrInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
86197  }
86198  if( rc!=SQLITE_OK ) return rc;
86199  }
86200 
86201  for(i=pMerger->nTree-1; i>0; i--){
86202  vdbeMergeEngineCompare(pMerger, i);
86203  }
86204  return pTask->pUnpacked->errCode;
86205 }
86206 
86207 /*
86208 ** The PmaReader passed as the first argument is guaranteed to be an
86209 ** incremental-reader (pReadr->pIncr!=0). This function serves to open
86210 ** and/or initialize the temp file related fields of the IncrMerge
86211 ** object at (pReadr->pIncr).
86212 **
86213 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
86214 ** in the sub-tree headed by pReadr are also initialized. Data is then
86215 ** loaded into the buffers belonging to pReadr and it is set to point to
86216 ** the first key in its range.
86217 **
86218 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
86219 ** to be a multi-threaded PmaReader and this function is being called in a
86220 ** background thread. In this case all PmaReaders in the sub-tree are
86221 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
86222 ** pReadr is populated. However, pReadr itself is not set up to point
86223 ** to its first key. A call to vdbePmaReaderNext() is still required to do
86224 ** that.
86225 **
86226 ** The reason this function does not call vdbePmaReaderNext() immediately
86227 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
86228 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
86229 ** this entire function is being run by thread (pTask->thread), that will
86230 ** lead to the current background thread attempting to join itself.
86231 **
86232 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
86233 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
86234 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
86235 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
86236 ** the current PmaReader set to point to the first key in its range.
86237 **
86238 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86239 */
86240 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
86241  int rc = SQLITE_OK;
86242  IncrMerger *pIncr = pReadr->pIncr;
86243  SortSubtask *pTask = pIncr->pTask;
86244  sqlite3 *db = pTask->pSorter->db;
86245 
86246  /* eMode is always INCRINIT_NORMAL in single-threaded mode */
86248 
86249  rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
86250 
86251  /* Set up the required files for pIncr. A multi-theaded IncrMerge object
86252  ** requires two temp files to itself, whereas a single-threaded object
86253  ** only requires a region of pTask->file2. */
86254  if( rc==SQLITE_OK ){
86255  int mxSz = pIncr->mxSz;
86256 #if SQLITE_MAX_WORKER_THREADS>0
86257  if( pIncr->bUseThread ){
86258  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
86259  if( rc==SQLITE_OK ){
86260  rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
86261  }
86262  }else
86263 #endif
86264  /*if( !pIncr->bUseThread )*/{
86265  if( pTask->file2.pFd==0 ){
86266  assert( pTask->file2.iEof>0 );
86267  rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
86268  pTask->file2.iEof = 0;
86269  }
86270  if( rc==SQLITE_OK ){
86271  pIncr->aFile[1].pFd = pTask->file2.pFd;
86272  pIncr->iStartOff = pTask->file2.iEof;
86273  pTask->file2.iEof += mxSz;
86274  }
86275  }
86276  }
86277 
86278 #if SQLITE_MAX_WORKER_THREADS>0
86279  if( rc==SQLITE_OK && pIncr->bUseThread ){
86280  /* Use the current thread to populate aFile[1], even though this
86281  ** PmaReader is multi-threaded. If this is an INCRINIT_TASK object,
86282  ** then this function is already running in background thread
86283  ** pIncr->pTask->thread.
86284  **
86285  ** If this is the INCRINIT_ROOT object, then it is running in the
86286  ** main VDBE thread. But that is Ok, as that thread cannot return
86287  ** control to the VDBE or proceed with anything useful until the
86288  ** first results are ready from this merger object anyway.
86289  */
86290  assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
86291  rc = vdbeIncrPopulate(pIncr);
86292  }
86293 #endif
86294 
86295  if( rc==SQLITE_OK && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK) ){
86296  rc = vdbePmaReaderNext(pReadr);
86297  }
86298 
86299  return rc;
86300 }
86301 
86302 #if SQLITE_MAX_WORKER_THREADS>0
86303 /*
86304 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
86305 ** background threads.
86306 */
86307 static void *vdbePmaReaderBgIncrInit(void *pCtx){
86308  PmaReader *pReader = (PmaReader*)pCtx;
86309  void *pRet = SQLITE_INT_TO_PTR(
86311  );
86312  pReader->pIncr->pTask->bDone = 1;
86313  return pRet;
86314 }
86315 #endif
86316 
86317 /*
86318 ** If the PmaReader passed as the first argument is not an incremental-reader
86319 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it invokes
86320 ** the vdbePmaReaderIncrMergeInit() function with the parameters passed to
86321 ** this routine to initialize the incremental merge.
86322 **
86323 ** If the IncrMerger object is multi-threaded (IncrMerger.bUseThread==1),
86324 ** then a background thread is launched to call vdbePmaReaderIncrMergeInit().
86325 ** Or, if the IncrMerger is single threaded, the same function is called
86326 ** using the current thread.
86327 */
86328 static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode){
86329  IncrMerger *pIncr = pReadr->pIncr; /* Incremental merger */
86330  int rc = SQLITE_OK; /* Return code */
86331  if( pIncr ){
86332 #if SQLITE_MAX_WORKER_THREADS>0
86333  assert( pIncr->bUseThread==0 || eMode==INCRINIT_TASK );
86334  if( pIncr->bUseThread ){
86335  void *pCtx = (void*)pReadr;
86337  }else
86338 #endif
86339  {
86340  rc = vdbePmaReaderIncrMergeInit(pReadr, eMode);
86341  }
86342  }
86343  return rc;
86344 }
86345 
86346 /*
86347 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
86348 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
86349 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
86350 ** to NULL and return an SQLite error code.
86351 **
86352 ** When this function is called, *piOffset is set to the offset of the
86353 ** first PMA to read from pTask->file. Assuming no error occurs, it is
86354 ** set to the offset immediately following the last byte of the last
86355 ** PMA before returning. If an error does occur, then the final value of
86356 ** *piOffset is undefined.
86357 */
86359  SortSubtask *pTask, /* Sorter task to read from */
86360  int nPMA, /* Number of PMAs to read */
86361  i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
86362  MergeEngine **ppOut /* OUT: New merge-engine */
86363 ){
86364  MergeEngine *pNew; /* Merge engine to return */
86365  i64 iOff = *piOffset;
86366  int i;
86367  int rc = SQLITE_OK;
86368 
86369  *ppOut = pNew = vdbeMergeEngineNew(nPMA);
86370  if( pNew==0 ) rc = SQLITE_NOMEM_BKPT;
86371 
86372  for(i=0; i<nPMA && rc==SQLITE_OK; i++){
86373  i64 nDummy = 0;
86374  PmaReader *pReadr = &pNew->aReadr[i];
86375  rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
86376  iOff = pReadr->iEof;
86377  }
86378 
86379  if( rc!=SQLITE_OK ){
86380  vdbeMergeEngineFree(pNew);
86381  *ppOut = 0;
86382  }
86383  *piOffset = iOff;
86384  return rc;
86385 }
86386 
86387 /*
86388 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
86389 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
86390 **
86391 ** i.e.
86392 **
86393 ** nPMA<=16 -> TreeDepth() == 0
86394 ** nPMA<=256 -> TreeDepth() == 1
86395 ** nPMA<=65536 -> TreeDepth() == 2
86396 */
86397 static int vdbeSorterTreeDepth(int nPMA){
86398  int nDepth = 0;
86399  i64 nDiv = SORTER_MAX_MERGE_COUNT;
86400  while( nDiv < (i64)nPMA ){
86401  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86402  nDepth++;
86403  }
86404  return nDepth;
86405 }
86406 
86407 /*
86408 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
86409 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
86410 ** tree, counting from zero. This function adds pLeaf to the tree.
86411 **
86412 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
86413 ** code is returned and pLeaf is freed.
86414 */
86416  SortSubtask *pTask, /* Task context */
86417  int nDepth, /* Depth of tree according to TreeDepth() */
86418  int iSeq, /* Sequence number of leaf within tree */
86419  MergeEngine *pRoot, /* Root of tree */
86420  MergeEngine *pLeaf /* Leaf to add to tree */
86421 ){
86422  int rc = SQLITE_OK;
86423  int nDiv = 1;
86424  int i;
86425  MergeEngine *p = pRoot;
86426  IncrMerger *pIncr;
86427 
86428  rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
86429 
86430  for(i=1; i<nDepth; i++){
86431  nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
86432  }
86433 
86434  for(i=1; i<nDepth && rc==SQLITE_OK; i++){
86435  int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
86436  PmaReader *pReadr = &p->aReadr[iIter];
86437 
86438  if( pReadr->pIncr==0 ){
86440  if( pNew==0 ){
86441  rc = SQLITE_NOMEM_BKPT;
86442  }else{
86443  rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
86444  }
86445  }
86446  if( rc==SQLITE_OK ){
86447  p = pReadr->pIncr->pMerger;
86448  nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
86449  }
86450  }
86451 
86452  if( rc==SQLITE_OK ){
86453  p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
86454  }else{
86455  vdbeIncrFree(pIncr);
86456  }
86457  return rc;
86458 }
86459 
86460 /*
86461 ** This function is called as part of a SorterRewind() operation on a sorter
86462 ** that has already written two or more level-0 PMAs to one or more temp
86463 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
86464 ** can be used to incrementally merge all PMAs on disk.
86465 **
86466 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
86467 ** MergeEngine object at the root of the tree before returning. Or, if an
86468 ** error occurs, an SQLite error code is returned and the final value
86469 ** of *ppOut is undefined.
86470 */
86472  VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
86473  MergeEngine **ppOut /* Write the MergeEngine here */
86474 ){
86475  MergeEngine *pMain = 0;
86476  int rc = SQLITE_OK;
86477  int iTask;
86478 
86479 #if SQLITE_MAX_WORKER_THREADS>0
86480  /* If the sorter uses more than one task, then create the top-level
86481  ** MergeEngine here. This MergeEngine will read data from exactly
86482  ** one PmaReader per sub-task. */
86483  assert( pSorter->bUseThreads || pSorter->nTask==1 );
86484  if( pSorter->nTask>1 ){
86485  pMain = vdbeMergeEngineNew(pSorter->nTask);
86486  if( pMain==0 ) rc = SQLITE_NOMEM_BKPT;
86487  }
86488 #endif
86489 
86490  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
86491  SortSubtask *pTask = &pSorter->aTask[iTask];
86492  assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
86493  if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
86494  MergeEngine *pRoot = 0; /* Root node of tree for this task */
86495  int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
86496  i64 iReadOff = 0;
86497 
86498  if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
86499  rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
86500  }else{
86501  int i;
86502  int iSeq = 0;
86504  if( pRoot==0 ) rc = SQLITE_NOMEM_BKPT;
86505  for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
86506  MergeEngine *pMerger = 0; /* New level-0 PMA merger */
86507  int nReader; /* Number of level-0 PMAs to merge */
86508 
86509  nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
86510  rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
86511  if( rc==SQLITE_OK ){
86512  rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
86513  }
86514  }
86515  }
86516 
86517  if( rc==SQLITE_OK ){
86518 #if SQLITE_MAX_WORKER_THREADS>0
86519  if( pMain!=0 ){
86520  rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
86521  }else
86522 #endif
86523  {
86524  assert( pMain==0 );
86525  pMain = pRoot;
86526  }
86527  }else{
86528  vdbeMergeEngineFree(pRoot);
86529  }
86530  }
86531  }
86532 
86533  if( rc!=SQLITE_OK ){
86534  vdbeMergeEngineFree(pMain);
86535  pMain = 0;
86536  }
86537  *ppOut = pMain;
86538  return rc;
86539 }
86540 
86541 /*
86542 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
86543 ** on a sorter that has written two or more PMAs to temporary files. It sets
86544 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
86545 ** (for multi-threaded sorters) so that it can be used to iterate through
86546 ** all records stored in the sorter.
86547 **
86548 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
86549 */
86550 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
86551  int rc; /* Return code */
86552  SortSubtask *pTask0 = &pSorter->aTask[0];
86553  MergeEngine *pMain = 0;
86554 #if SQLITE_MAX_WORKER_THREADS
86555  sqlite3 *db = pTask0->pSorter->db;
86556  int i;
86557  SorterCompare xCompare = vdbeSorterGetCompare(pSorter);
86558  for(i=0; i<pSorter->nTask; i++){
86559  pSorter->aTask[i].xCompare = xCompare;
86560  }
86561 #endif
86562 
86563  rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
86564  if( rc==SQLITE_OK ){
86565 #if SQLITE_MAX_WORKER_THREADS
86566  assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
86567  if( pSorter->bUseThreads ){
86568  int iTask;
86569  PmaReader *pReadr = 0;
86570  SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
86571  rc = vdbeSortAllocUnpacked(pLast);
86572  if( rc==SQLITE_OK ){
86573  pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
86574  pSorter->pReader = pReadr;
86575  if( pReadr==0 ) rc = SQLITE_NOMEM_BKPT;
86576  }
86577  if( rc==SQLITE_OK ){
86578  rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
86579  if( rc==SQLITE_OK ){
86581  for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
86582  IncrMerger *pIncr;
86583  if( (pIncr = pMain->aReadr[iTask].pIncr) ){
86584  vdbeIncrMergerSetThreads(pIncr);
86585  assert( pIncr->pTask!=pLast );
86586  }
86587  }
86588  for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
86589  /* Check that:
86590  **
86591  ** a) The incremental merge object is configured to use the
86592  ** right task, and
86593  ** b) If it is using task (nTask-1), it is configured to run
86594  ** in single-threaded mode. This is important, as the
86595  ** root merge (INCRINIT_ROOT) will be using the same task
86596  ** object.
86597  */
86598  PmaReader *p = &pMain->aReadr[iTask];
86599  assert( p->pIncr==0 || (
86600  (p->pIncr->pTask==&pSorter->aTask[iTask]) /* a */
86601  && (iTask!=pSorter->nTask-1 || p->pIncr->bUseThread==0) /* b */
86602  ));
86604  }
86605  }
86606  pMain = 0;
86607  }
86608  if( rc==SQLITE_OK ){
86610  }
86611  }else
86612 #endif
86613  {
86614  rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
86615  pSorter->pMerger = pMain;
86616  pMain = 0;
86617  }
86618  }
86619 
86620  if( rc!=SQLITE_OK ){
86621  vdbeMergeEngineFree(pMain);
86622  }
86623  return rc;
86624 }
86625 
86626 
86627 /*
86628 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
86629 ** this function is called to prepare for iterating through the records
86630 ** in sorted order.
86631 */
86633  VdbeSorter *pSorter;
86634  int rc = SQLITE_OK; /* Return code */
86635 
86636  assert( pCsr->eCurType==CURTYPE_SORTER );
86637  pSorter = pCsr->uc.pSorter;
86638  assert( pSorter );
86639 
86640  /* If no data has been written to disk, then do not do so now. Instead,
86641  ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
86642  ** from the in-memory list. */
86643  if( pSorter->bUsePMA==0 ){
86644  if( pSorter->list.pList ){
86645  *pbEof = 0;
86646  rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
86647  }else{
86648  *pbEof = 1;
86649  }
86650  return rc;
86651  }
86652 
86653  /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
86654  ** function flushes the contents of memory to disk, it immediately always
86655  ** creates a new list consisting of a single key immediately afterwards.
86656  ** So the list is never empty at this point. */
86657  assert( pSorter->list.pList );
86658  rc = vdbeSorterFlushPMA(pSorter);
86659 
86660  /* Join all threads */
86661  rc = vdbeSorterJoinAll(pSorter, rc);
86662 
86663  vdbeSorterRewindDebug("rewind");
86664 
86665  /* Assuming no errors have occurred, set up a merger structure to
86666  ** incrementally read and merge all remaining PMAs. */
86667  assert( pSorter->pReader==0 );
86668  if( rc==SQLITE_OK ){
86669  rc = vdbeSorterSetupMerge(pSorter);
86670  *pbEof = 0;
86671  }
86672 
86673  vdbeSorterRewindDebug("rewinddone");
86674  return rc;
86675 }
86676 
86677 /*
86678 ** Advance to the next element in the sorter.
86679 */
86680 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
86681  VdbeSorter *pSorter;
86682  int rc; /* Return code */
86683 
86684  assert( pCsr->eCurType==CURTYPE_SORTER );
86685  pSorter = pCsr->uc.pSorter;
86686  assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
86687  if( pSorter->bUsePMA ){
86688  assert( pSorter->pReader==0 || pSorter->pMerger==0 );
86689  assert( pSorter->bUseThreads==0 || pSorter->pReader );
86690  assert( pSorter->bUseThreads==1 || pSorter->pMerger );
86691 #if SQLITE_MAX_WORKER_THREADS>0
86692  if( pSorter->bUseThreads ){
86693  rc = vdbePmaReaderNext(pSorter->pReader);
86694  *pbEof = (pSorter->pReader->pFd==0);
86695  }else
86696 #endif
86697  /*if( !pSorter->bUseThreads )*/ {
86698  assert( pSorter->pMerger!=0 );
86699  assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
86700  rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
86701  }
86702  }else{
86703  SorterRecord *pFree = pSorter->list.pList;
86704  pSorter->list.pList = pFree->u.pNext;
86705  pFree->u.pNext = 0;
86706  if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
86707  *pbEof = !pSorter->list.pList;
86708  rc = SQLITE_OK;
86709  }
86710  return rc;
86711 }
86712 
86713 /*
86714 ** Return a pointer to a buffer owned by the sorter that contains the
86715 ** current key.
86716 */
86717 static void *vdbeSorterRowkey(
86718  const VdbeSorter *pSorter, /* Sorter object */
86719  int *pnKey /* OUT: Size of current key in bytes */
86720 ){
86721  void *pKey;
86722  if( pSorter->bUsePMA ){
86723  PmaReader *pReader;
86724 #if SQLITE_MAX_WORKER_THREADS>0
86725  if( pSorter->bUseThreads ){
86726  pReader = pSorter->pReader;
86727  }else
86728 #endif
86729  /*if( !pSorter->bUseThreads )*/{
86730  pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
86731  }
86732  *pnKey = pReader->nKey;
86733  pKey = pReader->aKey;
86734  }else{
86735  *pnKey = pSorter->list.pList->nVal;
86736  pKey = SRVAL(pSorter->list.pList);
86737  }
86738  return pKey;
86739 }
86740 
86741 /*
86742 ** Copy the current sorter key into the memory cell pOut.
86743 */
86745  VdbeSorter *pSorter;
86746  void *pKey; int nKey; /* Sorter key to copy into pOut */
86747 
86748  assert( pCsr->eCurType==CURTYPE_SORTER );
86749  pSorter = pCsr->uc.pSorter;
86750  pKey = vdbeSorterRowkey(pSorter, &nKey);
86751  if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
86752  return SQLITE_NOMEM_BKPT;
86753  }
86754  pOut->n = nKey;
86755  MemSetTypeFlag(pOut, MEM_Blob);
86756  memcpy(pOut->z, pKey, nKey);
86757 
86758  return SQLITE_OK;
86759 }
86760 
86761 /*
86762 ** Compare the key in memory cell pVal with the key that the sorter cursor
86763 ** passed as the first argument currently points to. For the purposes of
86764 ** the comparison, ignore the rowid field at the end of each record.
86765 **
86766 ** If the sorter cursor key contains any NULL values, consider it to be
86767 ** less than pVal. Even if pVal also contains NULL values.
86768 **
86769 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
86770 ** Otherwise, set *pRes to a negative, zero or positive value if the
86771 ** key in pVal is smaller than, equal to or larger than the current sorter
86772 ** key.
86773 **
86774 ** This routine forms the core of the OP_SorterCompare opcode, which in
86775 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
86776 */
86778  const VdbeCursor *pCsr, /* Sorter cursor */
86779  Mem *pVal, /* Value to compare to current sorter key */
86780  int nKeyCol, /* Compare this many columns */
86781  int *pRes /* OUT: Result of comparison */
86782 ){
86783  VdbeSorter *pSorter;
86784  UnpackedRecord *r2;
86785  KeyInfo *pKeyInfo;
86786  int i;
86787  void *pKey; int nKey; /* Sorter key to compare pVal with */
86788 
86789  assert( pCsr->eCurType==CURTYPE_SORTER );
86790  pSorter = pCsr->uc.pSorter;
86791  r2 = pSorter->pUnpacked;
86792  pKeyInfo = pCsr->pKeyInfo;
86793  if( r2==0 ){
86794  char *p;
86795  r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
86796  assert( pSorter->pUnpacked==(UnpackedRecord*)p );
86797  if( r2==0 ) return SQLITE_NOMEM_BKPT;
86798  r2->nField = nKeyCol;
86799  }
86800  assert( r2->nField==nKeyCol );
86801 
86802  pKey = vdbeSorterRowkey(pSorter, &nKey);
86803  sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
86804  for(i=0; i<nKeyCol; i++){
86805  if( r2->aMem[i].flags & MEM_Null ){
86806  *pRes = -1;
86807  return SQLITE_OK;
86808  }
86809  }
86810 
86811  *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
86812  return SQLITE_OK;
86813 }
86814 
86815 /************** End of vdbesort.c ********************************************/
86816 /************** Begin file memjournal.c **************************************/
86817 /*
86818 ** 2008 October 7
86819 **
86820 ** The author disclaims copyright to this source code. In place of
86821 ** a legal notice, here is a blessing:
86822 **
86823 ** May you do good and not evil.
86824 ** May you find forgiveness for yourself and forgive others.
86825 ** May you share freely, never taking more than you give.
86826 **
86827 *************************************************************************
86828 **
86829 ** This file contains code use to implement an in-memory rollback journal.
86830 ** The in-memory rollback journal is used to journal transactions for
86831 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
86832 **
86833 ** Update: The in-memory journal is also used to temporarily cache
86834 ** smaller journals that are not critical for power-loss recovery.
86835 ** For example, statement journals that are not too big will be held
86836 ** entirely in memory, thus reducing the number of file I/O calls, and
86837 ** more importantly, reducing temporary file creation events. If these
86838 ** journals become too large for memory, they are spilled to disk. But
86839 ** in the common case, they are usually small and no file I/O needs to
86840 ** occur.
86841 */
86842 /* #include "sqliteInt.h" */
86843 
86844 /* Forward references to internal structures */
86845 typedef struct MemJournal MemJournal;
86846 typedef struct FilePoint FilePoint;
86847 typedef struct FileChunk FileChunk;
86848 
86849 /*
86850 ** The rollback journal is composed of a linked list of these structures.
86851 **
86852 ** The zChunk array is always at least 8 bytes in size - usually much more.
86853 ** Its actual size is stored in the MemJournal.nChunkSize variable.
86854 */
86855 struct FileChunk {
86856  FileChunk *pNext; /* Next chunk in the journal */
86857  u8 zChunk[8]; /* Content of this chunk */
86858 };
86859 
86860 /*
86861 ** By default, allocate this many bytes of memory for each FileChunk object.
86862 */
86863 #define MEMJOURNAL_DFLT_FILECHUNKSIZE 1024
86864 
86865 /*
86866 ** For chunk size nChunkSize, return the number of bytes that should
86867 ** be allocated for each FileChunk structure.
86868 */
86869 #define fileChunkSize(nChunkSize) (sizeof(FileChunk) + ((nChunkSize)-8))
86870 
86871 /*
86872 ** An instance of this object serves as a cursor into the rollback journal.
86873 ** The cursor can be either for reading or writing.
86874 */
86875 struct FilePoint {
86876  sqlite3_int64 iOffset; /* Offset from the beginning of the file */
86877  FileChunk *pChunk; /* Specific chunk into which cursor points */
86878 };
86879 
86880 /*
86881 ** This structure is a subclass of sqlite3_file. Each open memory-journal
86882 ** is an instance of this class.
86883 */
86884 struct MemJournal {
86885  const sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
86886  int nChunkSize; /* In-memory chunk-size */
86887 
86888  int nSpill; /* Bytes of data before flushing */
86889  int nSize; /* Bytes of data currently in memory */
86890  FileChunk *pFirst; /* Head of in-memory chunk-list */
86891  FilePoint endpoint; /* Pointer to the end of the file */
86892  FilePoint readpoint; /* Pointer to the end of the last xRead() */
86893 
86894  int flags; /* xOpen flags */
86895  sqlite3_vfs *pVfs; /* The "real" underlying VFS */
86896  const char *zJournal; /* Name of the journal file */
86897 };
86898 
86899 /*
86900 ** Read data from the in-memory journal file. This is the implementation
86901 ** of the sqlite3_vfs.xRead method.
86902 */
86903 static int memjrnlRead(
86904  sqlite3_file *pJfd, /* The journal file from which to read */
86905  void *zBuf, /* Put the results here */
86906  int iAmt, /* Number of bytes to read */
86907  sqlite_int64 iOfst /* Begin reading at this offset */
86908 ){
86909  MemJournal *p = (MemJournal *)pJfd;
86910  u8 *zOut = zBuf;
86911  int nRead = iAmt;
86912  int iChunkOffset;
86913  FileChunk *pChunk;
86914 
86915 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
86916  if( (iAmt+iOfst)>p->endpoint.iOffset ){
86917  return SQLITE_IOERR_SHORT_READ;
86918  }
86919 #endif
86920 
86921  assert( (iAmt+iOfst)<=p->endpoint.iOffset );
86922  assert( p->readpoint.iOffset==0 || p->readpoint.pChunk!=0 );
86923  if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
86924  sqlite3_int64 iOff = 0;
86925  for(pChunk=p->pFirst;
86926  ALWAYS(pChunk) && (iOff+p->nChunkSize)<=iOfst;
86927  pChunk=pChunk->pNext
86928  ){
86929  iOff += p->nChunkSize;
86930  }
86931  }else{
86932  pChunk = p->readpoint.pChunk;
86933  assert( pChunk!=0 );
86934  }
86935 
86936  iChunkOffset = (int)(iOfst%p->nChunkSize);
86937  do {
86938  int iSpace = p->nChunkSize - iChunkOffset;
86939  int nCopy = MIN(nRead, (p->nChunkSize - iChunkOffset));
86940  memcpy(zOut, (u8*)pChunk->zChunk + iChunkOffset, nCopy);
86941  zOut += nCopy;
86942  nRead -= iSpace;
86943  iChunkOffset = 0;
86944  } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
86945  p->readpoint.iOffset = pChunk ? iOfst+iAmt : 0;
86946  p->readpoint.pChunk = pChunk;
86947 
86948  return SQLITE_OK;
86949 }
86950 
86951 /*
86952 ** Free the list of FileChunk structures headed at MemJournal.pFirst.
86953 */
86955  FileChunk *pIter;
86956  FileChunk *pNext;
86957  for(pIter=p->pFirst; pIter; pIter=pNext){
86958  pNext = pIter->pNext;
86959  sqlite3_free(pIter);
86960  }
86961  p->pFirst = 0;
86962 }
86963 
86964 /*
86965 ** Flush the contents of memory to a real file on disk.
86966 */
86968  int rc;
86969  sqlite3_file *pReal = (sqlite3_file*)p;
86970  MemJournal copy = *p;
86971 
86972  memset(p, 0, sizeof(MemJournal));
86973  rc = sqlite3OsOpen(copy.pVfs, copy.zJournal, pReal, copy.flags, 0);
86974  if( rc==SQLITE_OK ){
86975  int nChunk = copy.nChunkSize;
86976  i64 iOff = 0;
86977  FileChunk *pIter;
86978  for(pIter=copy.pFirst; pIter; pIter=pIter->pNext){
86979  if( iOff + nChunk > copy.endpoint.iOffset ){
86980  nChunk = copy.endpoint.iOffset - iOff;
86981  }
86982  rc = sqlite3OsWrite(pReal, (u8*)pIter->zChunk, nChunk, iOff);
86983  if( rc ) break;
86984  iOff += nChunk;
86985  }
86986  if( rc==SQLITE_OK ){
86987  /* No error has occurred. Free the in-memory buffers. */
86988  memjrnlFreeChunks(&copy);
86989  }
86990  }
86991  if( rc!=SQLITE_OK ){
86992  /* If an error occurred while creating or writing to the file, restore
86993  ** the original before returning. This way, SQLite uses the in-memory
86994  ** journal data to roll back changes made to the internal page-cache
86995  ** before this function was called. */
86996  sqlite3OsClose(pReal);
86997  *p = copy;
86998  }
86999  return rc;
87000 }
87001 
87002 
87003 /*
87004 ** Write data to the file.
87005 */
87006 static int memjrnlWrite(
87007  sqlite3_file *pJfd, /* The journal file into which to write */
87008  const void *zBuf, /* Take data to be written from here */
87009  int iAmt, /* Number of bytes to write */
87010  sqlite_int64 iOfst /* Begin writing at this offset into the file */
87011 ){
87012  MemJournal *p = (MemJournal *)pJfd;
87013  int nWrite = iAmt;
87014  u8 *zWrite = (u8 *)zBuf;
87015 
87016  /* If the file should be created now, create it and write the new data
87017  ** into the file on disk. */
87018  if( p->nSpill>0 && (iAmt+iOfst)>p->nSpill ){
87019  int rc = memjrnlCreateFile(p);
87020  if( rc==SQLITE_OK ){
87021  rc = sqlite3OsWrite(pJfd, zBuf, iAmt, iOfst);
87022  }
87023  return rc;
87024  }
87025 
87026  /* If the contents of this write should be stored in memory */
87027  else{
87028  /* An in-memory journal file should only ever be appended to. Random
87029  ** access writes are not required. The only exception to this is when
87030  ** the in-memory journal is being used by a connection using the
87031  ** atomic-write optimization. In this case the first 28 bytes of the
87032  ** journal file may be written as part of committing the transaction. */
87033  assert( iOfst==p->endpoint.iOffset || iOfst==0 );
87034 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87035  if( iOfst==0 && p->pFirst ){
87036  assert( p->nChunkSize>iAmt );
87037  memcpy((u8*)p->pFirst->zChunk, zBuf, iAmt);
87038  }else
87039 #else
87040  assert( iOfst>0 || p->pFirst==0 );
87041 #endif
87042  {
87043  while( nWrite>0 ){
87044  FileChunk *pChunk = p->endpoint.pChunk;
87045  int iChunkOffset = (int)(p->endpoint.iOffset%p->nChunkSize);
87046  int iSpace = MIN(nWrite, p->nChunkSize - iChunkOffset);
87047 
87048  if( iChunkOffset==0 ){
87049  /* New chunk is required to extend the file. */
87051  if( !pNew ){
87052  return SQLITE_IOERR_NOMEM_BKPT;
87053  }
87054  pNew->pNext = 0;
87055  if( pChunk ){
87056  assert( p->pFirst );
87057  pChunk->pNext = pNew;
87058  }else{
87059  assert( !p->pFirst );
87060  p->pFirst = pNew;
87061  }
87062  p->endpoint.pChunk = pNew;
87063  }
87064 
87065  memcpy((u8*)p->endpoint.pChunk->zChunk + iChunkOffset, zWrite, iSpace);
87066  zWrite += iSpace;
87067  nWrite -= iSpace;
87068  p->endpoint.iOffset += iSpace;
87069  }
87070  p->nSize = iAmt + iOfst;
87071  }
87072  }
87073 
87074  return SQLITE_OK;
87075 }
87076 
87077 /*
87078 ** Truncate the file.
87079 **
87080 ** If the journal file is already on disk, truncate it there. Or, if it
87081 ** is still in main memory but is being truncated to zero bytes in size,
87082 ** ignore
87083 */
87084 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
87085  MemJournal *p = (MemJournal *)pJfd;
87086  if( ALWAYS(size==0) ){
87087  memjrnlFreeChunks(p);
87088  p->nSize = 0;
87089  p->endpoint.pChunk = 0;
87090  p->endpoint.iOffset = 0;
87091  p->readpoint.pChunk = 0;
87092  p->readpoint.iOffset = 0;
87093  }
87094  return SQLITE_OK;
87095 }
87096 
87097 /*
87098 ** Close the file.
87099 */
87100 static int memjrnlClose(sqlite3_file *pJfd){
87101  MemJournal *p = (MemJournal *)pJfd;
87102  memjrnlFreeChunks(p);
87103  return SQLITE_OK;
87104 }
87105 
87106 /*
87107 ** Sync the file.
87108 **
87109 ** If the real file has been created, call its xSync method. Otherwise,
87110 ** syncing an in-memory journal is a no-op.
87111 */
87112 static int memjrnlSync(sqlite3_file *pJfd, int flags){
87113  UNUSED_PARAMETER2(pJfd, flags);
87114  return SQLITE_OK;
87115 }
87116 
87117 /*
87118 ** Query the size of the file in bytes.
87119 */
87120 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
87121  MemJournal *p = (MemJournal *)pJfd;
87122  *pSize = (sqlite_int64) p->endpoint.iOffset;
87123  return SQLITE_OK;
87124 }
87125 
87126 /*
87127 ** Table of methods for MemJournal sqlite3_file object.
87128 */
87129 static const struct sqlite3_io_methods MemJournalMethods = {
87130  1, /* iVersion */
87131  memjrnlClose, /* xClose */
87132  memjrnlRead, /* xRead */
87133  memjrnlWrite, /* xWrite */
87134  memjrnlTruncate, /* xTruncate */
87135  memjrnlSync, /* xSync */
87136  memjrnlFileSize, /* xFileSize */
87137  0, /* xLock */
87138  0, /* xUnlock */
87139  0, /* xCheckReservedLock */
87140  0, /* xFileControl */
87141  0, /* xSectorSize */
87142  0, /* xDeviceCharacteristics */
87143  0, /* xShmMap */
87144  0, /* xShmLock */
87145  0, /* xShmBarrier */
87146  0, /* xShmUnmap */
87147  0, /* xFetch */
87148  0 /* xUnfetch */
87149 };
87150 
87151 /*
87152 ** Open a journal file.
87153 **
87154 ** The behaviour of the journal file depends on the value of parameter
87155 ** nSpill. If nSpill is 0, then the journal file is always create and
87156 ** accessed using the underlying VFS. If nSpill is less than zero, then
87157 ** all content is always stored in main-memory. Finally, if nSpill is a
87158 ** positive value, then the journal file is initially created in-memory
87159 ** but may be flushed to disk later on. In this case the journal file is
87160 ** flushed to disk either when it grows larger than nSpill bytes in size,
87161 ** or when sqlite3JournalCreate() is called.
87162 */
87164  sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
87165  const char *zName, /* Name of the journal file */
87166  sqlite3_file *pJfd, /* Preallocated, blank file handle */
87167  int flags, /* Opening flags */
87168  int nSpill /* Bytes buffered before opening the file */
87169 ){
87170  MemJournal *p = (MemJournal*)pJfd;
87171 
87172  /* Zero the file-handle object. If nSpill was passed zero, initialize
87173  ** it using the sqlite3OsOpen() function of the underlying VFS. In this
87174  ** case none of the code in this module is executed as a result of calls
87175  ** made on the journal file-handle. */
87176  memset(p, 0, sizeof(MemJournal));
87177  if( nSpill==0 ){
87178  return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
87179  }
87180 
87181  if( nSpill>0 ){
87182  p->nChunkSize = nSpill;
87183  }else{
87186  }
87187 
87188  p->pMethod = (const sqlite3_io_methods*)&MemJournalMethods;
87189  p->nSpill = nSpill;
87190  p->flags = flags;
87191  p->zJournal = zName;
87192  p->pVfs = pVfs;
87193  return SQLITE_OK;
87194 }
87195 
87196 /*
87197 ** Open an in-memory journal file.
87198 */
87199 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
87200  sqlite3JournalOpen(0, 0, pJfd, 0, -1);
87201 }
87202 
87203 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
87204 /*
87205 ** If the argument p points to a MemJournal structure that is not an
87206 ** in-memory-only journal file (i.e. is one that was opened with a +ve
87207 ** nSpill parameter), and the underlying file has not yet been created,
87208 ** create it now.
87209 */
87210 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
87211  int rc = SQLITE_OK;
87212  if( p->pMethods==&MemJournalMethods && ((MemJournal*)p)->nSpill>0 ){
87213  rc = memjrnlCreateFile((MemJournal*)p);
87214  }
87215  return rc;
87216 }
87217 #endif
87218 
87219 /*
87220 ** The file-handle passed as the only argument is open on a journal file.
87221 ** Return true if this "journal file" is currently stored in heap memory,
87222 ** or false otherwise.
87223 */
87225  return p->pMethods==&MemJournalMethods;
87226 }
87227 
87228 /*
87229 ** Return the number of bytes required to store a JournalFile that uses vfs
87230 ** pVfs to create the underlying on-disk files.
87231 */
87232 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
87233  return MAX(pVfs->szOsFile, (int)sizeof(MemJournal));
87234 }
87235 
87236 /************** End of memjournal.c ******************************************/
87237 /************** Begin file walker.c ******************************************/
87238 /*
87239 ** 2008 August 16
87240 **
87241 ** The author disclaims copyright to this source code. In place of
87242 ** a legal notice, here is a blessing:
87243 **
87244 ** May you do good and not evil.
87245 ** May you find forgiveness for yourself and forgive others.
87246 ** May you share freely, never taking more than you give.
87247 **
87248 *************************************************************************
87249 ** This file contains routines used for walking the parser tree for
87250 ** an SQL statement.
87251 */
87252 /* #include "sqliteInt.h" */
87253 /* #include <stdlib.h> */
87254 /* #include <string.h> */
87255 
87256 
87257 /*
87258 ** Walk an expression tree. Invoke the callback once for each node
87259 ** of the expression, while descending. (In other words, the callback
87260 ** is invoked before visiting children.)
87261 **
87262 ** The return value from the callback should be one of the WRC_*
87263 ** constants to specify how to proceed with the walk.
87264 **
87265 ** WRC_Continue Continue descending down the tree.
87266 **
87267 ** WRC_Prune Do not descend into child nodes. But allow
87268 ** the walk to continue with sibling nodes.
87269 **
87270 ** WRC_Abort Do no more callbacks. Unwind the stack and
87271 ** return the top-level walk call.
87272 **
87273 ** The return value from this routine is WRC_Abort to abandon the tree walk
87274 ** and WRC_Continue to continue.
87275 */
87276 static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr){
87277  int rc;
87279  testcase( ExprHasProperty(pExpr, EP_Reduced) );
87280  rc = pWalker->xExprCallback(pWalker, pExpr);
87281  if( rc==WRC_Continue
87282  && !ExprHasProperty(pExpr,EP_TokenOnly) ){
87283  if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
87284  if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
87285  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
87286  if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
87287  }else{
87288  if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
87289  }
87290  }
87291  return rc & WRC_Abort;
87292 }
87294  return pExpr ? walkExpr(pWalker,pExpr) : WRC_Continue;
87295 }
87296 
87297 /*
87298 ** Call sqlite3WalkExpr() for every expression in list p or until
87299 ** an abort request is seen.
87300 */
87302  int i;
87303  struct ExprList_item *pItem;
87304  if( p ){
87305  for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
87306  if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
87307  }
87308  }
87309  return WRC_Continue;
87310 }
87311 
87312 /*
87313 ** Walk all expressions associated with SELECT statement p. Do
87314 ** not invoke the SELECT callback on p, but do (of course) invoke
87315 ** any expr callbacks and SELECT callbacks that come from subqueries.
87316 ** Return WRC_Abort or WRC_Continue.
87317 */
87319  if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
87320  if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
87321  if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
87322  if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
87323  if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
87324  if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
87325  if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
87326  return WRC_Continue;
87327 }
87328 
87329 /*
87330 ** Walk the parse trees associated with all subqueries in the
87331 ** FROM clause of SELECT statement p. Do not invoke the select
87332 ** callback on p, but do invoke it on each FROM clause subquery
87333 ** and on any subqueries further down in the tree. Return
87334 ** WRC_Abort or WRC_Continue;
87335 */
87337  SrcList *pSrc;
87338  int i;
87339  struct SrcList_item *pItem;
87340 
87341  pSrc = p->pSrc;
87342  if( ALWAYS(pSrc) ){
87343  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
87344  if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
87345  return WRC_Abort;
87346  }
87347  if( pItem->fg.isTabFunc
87348  && sqlite3WalkExprList(pWalker, pItem->u1.pFuncArg)
87349  ){
87350  return WRC_Abort;
87351  }
87352  }
87353  }
87354  return WRC_Continue;
87355 }
87356 
87357 /*
87358 ** Call sqlite3WalkExpr() for every expression in Select statement p.
87359 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
87360 ** on the compound select chain, p->pPrior.
87361 **
87362 ** If it is not NULL, the xSelectCallback() callback is invoked before
87363 ** the walk of the expressions and FROM clause. The xSelectCallback2()
87364 ** method, if it is not NULL, is invoked following the walk of the
87365 ** expressions and FROM clause.
87366 **
87367 ** Return WRC_Continue under normal conditions. Return WRC_Abort if
87368 ** there is an abort request.
87369 **
87370 ** If the Walker does not have an xSelectCallback() then this routine
87371 ** is a no-op returning WRC_Continue.
87372 */
87374  int rc;
87375  if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
87376  return WRC_Continue;
87377  }
87378  rc = WRC_Continue;
87379  pWalker->walkerDepth++;
87380  while( p ){
87381  if( pWalker->xSelectCallback ){
87382  rc = pWalker->xSelectCallback(pWalker, p);
87383  if( rc ) break;
87384  }
87385  if( sqlite3WalkSelectExpr(pWalker, p)
87386  || sqlite3WalkSelectFrom(pWalker, p)
87387  ){
87388  pWalker->walkerDepth--;
87389  return WRC_Abort;
87390  }
87391  if( pWalker->xSelectCallback2 ){
87392  pWalker->xSelectCallback2(pWalker, p);
87393  }
87394  p = p->pPrior;
87395  }
87396  pWalker->walkerDepth--;
87397  return rc & WRC_Abort;
87398 }
87399 
87400 /************** End of walker.c **********************************************/
87401 /************** Begin file resolve.c *****************************************/
87402 /*
87403 ** 2008 August 18
87404 **
87405 ** The author disclaims copyright to this source code. In place of
87406 ** a legal notice, here is a blessing:
87407 **
87408 ** May you do good and not evil.
87409 ** May you find forgiveness for yourself and forgive others.
87410 ** May you share freely, never taking more than you give.
87411 **
87412 *************************************************************************
87413 **
87414 ** This file contains routines used for walking the parser tree and
87415 ** resolve all identifiers by associating them with a particular
87416 ** table and column.
87417 */
87418 /* #include "sqliteInt.h" */
87419 /* #include <stdlib.h> */
87420 /* #include <string.h> */
87421 
87422 /*
87423 ** Walk the expression tree pExpr and increase the aggregate function
87424 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
87425 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
87426 ** outer query into an inner subquery.
87427 **
87428 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
87429 ** is a helper function - a callback for the tree walker.
87430 */
87431 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
87432  if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
87433  return WRC_Continue;
87434 }
87435 static void incrAggFunctionDepth(Expr *pExpr, int N){
87436  if( N>0 ){
87437  Walker w;
87438  memset(&w, 0, sizeof(w));
87440  w.u.n = N;
87441  sqlite3WalkExpr(&w, pExpr);
87442  }
87443 }
87444 
87445 /*
87446 ** Turn the pExpr expression into an alias for the iCol-th column of the
87447 ** result set in pEList.
87448 **
87449 ** If the reference is followed by a COLLATE operator, then make sure
87450 ** the COLLATE operator is preserved. For example:
87451 **
87452 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
87453 **
87454 ** Should be transformed into:
87455 **
87456 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
87457 **
87458 ** The nSubquery parameter specifies how many levels of subquery the
87459 ** alias is removed from the original expression. The usual value is
87460 ** zero but it might be more if the alias is contained within a subquery
87461 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
87462 ** structures must be increased by the nSubquery amount.
87463 */
87464 static void resolveAlias(
87465  Parse *pParse, /* Parsing context */
87466  ExprList *pEList, /* A result set */
87467  int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
87468  Expr *pExpr, /* Transform this into an alias to the result set */
87469  const char *zType, /* "GROUP" or "ORDER" or "" */
87470  int nSubquery /* Number of subqueries that the label is moving */
87471 ){
87472  Expr *pOrig; /* The iCol-th column of the result set */
87473  Expr *pDup; /* Copy of pOrig */
87474  sqlite3 *db; /* The database connection */
87475 
87476  assert( iCol>=0 && iCol<pEList->nExpr );
87477  pOrig = pEList->a[iCol].pExpr;
87478  assert( pOrig!=0 );
87479  db = pParse->db;
87480  pDup = sqlite3ExprDup(db, pOrig, 0);
87481  if( pDup==0 ) return;
87482  if( zType[0]!='G' ) incrAggFunctionDepth(pDup, nSubquery);
87483  if( pExpr->op==TK_COLLATE ){
87484  pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
87485  }
87486  ExprSetProperty(pDup, EP_Alias);
87487 
87488  /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
87489  ** prevents ExprDelete() from deleting the Expr structure itself,
87490  ** allowing it to be repopulated by the memcpy() on the following line.
87491  ** The pExpr->u.zToken might point into memory that will be freed by the
87492  ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
87493  ** make a copy of the token before doing the sqlite3DbFree().
87494  */
87495  ExprSetProperty(pExpr, EP_Static);
87496  sqlite3ExprDelete(db, pExpr);
87497  memcpy(pExpr, pDup, sizeof(*pExpr));
87498  if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
87499  assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
87500  pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
87501  pExpr->flags |= EP_MemToken;
87502  }
87503  sqlite3DbFree(db, pDup);
87504 }
87505 
87506 
87507 /*
87508 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
87509 **
87510 ** Return FALSE if the USING clause is NULL or if it does not contain
87511 ** zCol.
87512 */
87513 static int nameInUsingClause(IdList *pUsing, const char *zCol){
87514  if( pUsing ){
87515  int k;
87516  for(k=0; k<pUsing->nId; k++){
87517  if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
87518  }
87519  }
87520  return 0;
87521 }
87522 
87523 /*
87524 ** Subqueries stores the original database, table and column names for their
87525 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
87526 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
87527 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
87528 ** match anything.
87529 */
87531  const char *zSpan,
87532  const char *zCol,
87533  const char *zTab,
87534  const char *zDb
87535 ){
87536  int n;
87537  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
87538  if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
87539  return 0;
87540  }
87541  zSpan += n+1;
87542  for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
87543  if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
87544  return 0;
87545  }
87546  zSpan += n+1;
87547  if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
87548  return 0;
87549  }
87550  return 1;
87551 }
87552 
87553 /*
87554 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
87555 ** that name in the set of source tables in pSrcList and make the pExpr
87556 ** expression node refer back to that source column. The following changes
87557 ** are made to pExpr:
87558 **
87559 ** pExpr->iDb Set the index in db->aDb[] of the database X
87560 ** (even if X is implied).
87561 ** pExpr->iTable Set to the cursor number for the table obtained
87562 ** from pSrcList.
87563 ** pExpr->pTab Points to the Table structure of X.Y (even if
87564 ** X and/or Y are implied.)
87565 ** pExpr->iColumn Set to the column number within the table.
87566 ** pExpr->op Set to TK_COLUMN.
87567 ** pExpr->pLeft Any expression this points to is deleted
87568 ** pExpr->pRight Any expression this points to is deleted.
87569 **
87570 ** The zDb variable is the name of the database (the "X"). This value may be
87571 ** NULL meaning that name is of the form Y.Z or Z. Any available database
87572 ** can be used. The zTable variable is the name of the table (the "Y"). This
87573 ** value can be NULL if zDb is also NULL. If zTable is NULL it
87574 ** means that the form of the name is Z and that columns from any table
87575 ** can be used.
87576 **
87577 ** If the name cannot be resolved unambiguously, leave an error message
87578 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
87579 */
87580 static int lookupName(
87581  Parse *pParse, /* The parsing context */
87582  const char *zDb, /* Name of the database containing table, or NULL */
87583  const char *zTab, /* Name of table containing column, or NULL */
87584  const char *zCol, /* Name of the column. */
87585  NameContext *pNC, /* The name context used to resolve the name */
87586  Expr *pExpr /* Make this EXPR node point to the selected column */
87587 ){
87588  int i, j; /* Loop counters */
87589  int cnt = 0; /* Number of matching column names */
87590  int cntTab = 0; /* Number of matching table names */
87591  int nSubquery = 0; /* How many levels of subquery */
87592  sqlite3 *db = pParse->db; /* The database connection */
87593  struct SrcList_item *pItem; /* Use for looping over pSrcList items */
87594  struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
87595  NameContext *pTopNC = pNC; /* First namecontext in the list */
87596  Schema *pSchema = 0; /* Schema of the expression */
87597  int isTrigger = 0; /* True if resolved to a trigger column */
87598  Table *pTab = 0; /* Table hold the row */
87599  Column *pCol; /* A column of pTab */
87600 
87601  assert( pNC ); /* the name context cannot be NULL. */
87602  assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
87604 
87605  /* Initialize the node to no-match */
87606  pExpr->iTable = -1;
87607  pExpr->pTab = 0;
87609 
87610  /* Translate the schema name in zDb into a pointer to the corresponding
87611  ** schema. If not found, pSchema will remain NULL and nothing will match
87612  ** resulting in an appropriate error message toward the end of this routine
87613  */
87614  if( zDb ){
87615  testcase( pNC->ncFlags & NC_PartIdx );
87616  testcase( pNC->ncFlags & NC_IsCheck );
87617  if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
87618  /* Silently ignore database qualifiers inside CHECK constraints and
87619  ** partial indices. Do not raise errors because that might break
87620  ** legacy and because it does not hurt anything to just ignore the
87621  ** database name. */
87622  zDb = 0;
87623  }else{
87624  for(i=0; i<db->nDb; i++){
87625  assert( db->aDb[i].zName );
87626  if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
87627  pSchema = db->aDb[i].pSchema;
87628  break;
87629  }
87630  }
87631  }
87632  }
87633 
87634  /* Start at the inner-most context and move outward until a match is found */
87635  while( pNC && cnt==0 ){
87636  ExprList *pEList;
87637  SrcList *pSrcList = pNC->pSrcList;
87638 
87639  if( pSrcList ){
87640  for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
87641  pTab = pItem->pTab;
87642  assert( pTab!=0 && pTab->zName!=0 );
87643  assert( pTab->nCol>0 );
87644  if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
87645  int hit = 0;
87646  pEList = pItem->pSelect->pEList;
87647  for(j=0; j<pEList->nExpr; j++){
87648  if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
87649  cnt++;
87650  cntTab = 2;
87651  pMatch = pItem;
87652  pExpr->iColumn = j;
87653  hit = 1;
87654  }
87655  }
87656  if( hit || zTab==0 ) continue;
87657  }
87658  if( zDb && pTab->pSchema!=pSchema ){
87659  continue;
87660  }
87661  if( zTab ){
87662  const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
87663  assert( zTabName!=0 );
87664  if( sqlite3StrICmp(zTabName, zTab)!=0 ){
87665  continue;
87666  }
87667  }
87668  if( 0==(cntTab++) ){
87669  pMatch = pItem;
87670  }
87671  for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
87672  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
87673  /* If there has been exactly one prior match and this match
87674  ** is for the right-hand table of a NATURAL JOIN or is in a
87675  ** USING clause, then skip this match.
87676  */
87677  if( cnt==1 ){
87678  if( pItem->fg.jointype & JT_NATURAL ) continue;
87679  if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
87680  }
87681  cnt++;
87682  pMatch = pItem;
87683  /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
87684  pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
87685  break;
87686  }
87687  }
87688  }
87689  if( pMatch ){
87690  pExpr->iTable = pMatch->iCursor;
87691  pExpr->pTab = pMatch->pTab;
87692  /* RIGHT JOIN not (yet) supported */
87693  assert( (pMatch->fg.jointype & JT_RIGHT)==0 );
87694  if( (pMatch->fg.jointype & JT_LEFT)!=0 ){
87695  ExprSetProperty(pExpr, EP_CanBeNull);
87696  }
87697  pSchema = pExpr->pTab->pSchema;
87698  }
87699  } /* if( pSrcList ) */
87700 
87701 #ifndef SQLITE_OMIT_TRIGGER
87702  /* If we have not already resolved the name, then maybe
87703  ** it is a new.* or old.* trigger argument reference
87704  */
87705  if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
87706  int op = pParse->eTriggerOp;
87707  assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
87708  if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
87709  pExpr->iTable = 1;
87710  pTab = pParse->pTriggerTab;
87711  }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
87712  pExpr->iTable = 0;
87713  pTab = pParse->pTriggerTab;
87714  }else{
87715  pTab = 0;
87716  }
87717 
87718  if( pTab ){
87719  int iCol;
87720  pSchema = pTab->pSchema;
87721  cntTab++;
87722  for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
87723  if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
87724  if( iCol==pTab->iPKey ){
87725  iCol = -1;
87726  }
87727  break;
87728  }
87729  }
87730  if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
87731  /* IMP: R-51414-32910 */
87732  iCol = -1;
87733  }
87734  if( iCol<pTab->nCol ){
87735  cnt++;
87736  if( iCol<0 ){
87737  pExpr->affinity = SQLITE_AFF_INTEGER;
87738  }else if( pExpr->iTable==0 ){
87739  testcase( iCol==31 );
87740  testcase( iCol==32 );
87741  pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
87742  }else{
87743  testcase( iCol==31 );
87744  testcase( iCol==32 );
87745  pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
87746  }
87747  pExpr->iColumn = (i16)iCol;
87748  pExpr->pTab = pTab;
87749  isTrigger = 1;
87750  }
87751  }
87752  }
87753 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
87754 
87755  /*
87756  ** Perhaps the name is a reference to the ROWID
87757  */
87758  if( cnt==0
87759  && cntTab==1
87760  && pMatch
87761  && (pNC->ncFlags & NC_IdxExpr)==0
87762  && sqlite3IsRowid(zCol)
87763  && VisibleRowid(pMatch->pTab)
87764  ){
87765  cnt = 1;
87766  pExpr->iColumn = -1;
87767  pExpr->affinity = SQLITE_AFF_INTEGER;
87768  }
87769 
87770  /*
87771  ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
87772  ** might refer to an result-set alias. This happens, for example, when
87773  ** we are resolving names in the WHERE clause of the following command:
87774  **
87775  ** SELECT a+b AS x FROM table WHERE x<10;
87776  **
87777  ** In cases like this, replace pExpr with a copy of the expression that
87778  ** forms the result set entry ("a+b" in the example) and return immediately.
87779  ** Note that the expression in the result set should have already been
87780  ** resolved by the time the WHERE clause is resolved.
87781  **
87782  ** The ability to use an output result-set column in the WHERE, GROUP BY,
87783  ** or HAVING clauses, or as part of a larger expression in the ORDER BY
87784  ** clause is not standard SQL. This is a (goofy) SQLite extension, that
87785  ** is supported for backwards compatibility only. Hence, we issue a warning
87786  ** on sqlite3_log() whenever the capability is used.
87787  */
87788  if( (pEList = pNC->pEList)!=0
87789  && zTab==0
87790  && cnt==0
87791  ){
87792  for(j=0; j<pEList->nExpr; j++){
87793  char *zAs = pEList->a[j].zName;
87794  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
87795  Expr *pOrig;
87796  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
87797  assert( pExpr->x.pList==0 );
87798  assert( pExpr->x.pSelect==0 );
87799  pOrig = pEList->a[j].pExpr;
87800  if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
87801  sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
87802  return WRC_Abort;
87803  }
87804  resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
87805  cnt = 1;
87806  pMatch = 0;
87807  assert( zTab==0 && zDb==0 );
87808  goto lookupname_end;
87809  }
87810  }
87811  }
87812 
87813  /* Advance to the next name context. The loop will exit when either
87814  ** we have a match (cnt>0) or when we run out of name contexts.
87815  */
87816  if( cnt==0 ){
87817  pNC = pNC->pNext;
87818  nSubquery++;
87819  }
87820  }
87821 
87822  /*
87823  ** If X and Y are NULL (in other words if only the column name Z is
87824  ** supplied) and the value of Z is enclosed in double-quotes, then
87825  ** Z is a string literal if it doesn't match any column names. In that
87826  ** case, we need to return right away and not make any changes to
87827  ** pExpr.
87828  **
87829  ** Because no reference was made to outer contexts, the pNC->nRef
87830  ** fields are not changed in any context.
87831  */
87832  if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
87833  pExpr->op = TK_STRING;
87834  pExpr->pTab = 0;
87835  return WRC_Prune;
87836  }
87837 
87838  /*
87839  ** cnt==0 means there was not match. cnt>1 means there were two or
87840  ** more matches. Either way, we have an error.
87841  */
87842  if( cnt!=1 ){
87843  const char *zErr;
87844  zErr = cnt==0 ? "no such column" : "ambiguous column name";
87845  if( zDb ){
87846  sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
87847  }else if( zTab ){
87848  sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
87849  }else{
87850  sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
87851  }
87852  pParse->checkSchema = 1;
87853  pTopNC->nErr++;
87854  }
87855 
87856  /* If a column from a table in pSrcList is referenced, then record
87857  ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
87858  ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
87859  ** column number is greater than the number of bits in the bitmask
87860  ** then set the high-order bit of the bitmask.
87861  */
87862  if( pExpr->iColumn>=0 && pMatch!=0 ){
87863  int n = pExpr->iColumn;
87864  testcase( n==BMS-1 );
87865  if( n>=BMS ){
87866  n = BMS-1;
87867  }
87868  assert( pMatch->iCursor==pExpr->iTable );
87869  pMatch->colUsed |= ((Bitmask)1)<<n;
87870  }
87871 
87872  /* Clean up and return
87873  */
87874  sqlite3ExprDelete(db, pExpr->pLeft);
87875  pExpr->pLeft = 0;
87876  sqlite3ExprDelete(db, pExpr->pRight);
87877  pExpr->pRight = 0;
87878  pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
87879 lookupname_end:
87880  if( cnt==1 ){
87881  assert( pNC!=0 );
87882  if( !ExprHasProperty(pExpr, EP_Alias) ){
87883  sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
87884  }
87885  /* Increment the nRef value on all name contexts from TopNC up to
87886  ** the point where the name matched. */
87887  for(;;){
87888  assert( pTopNC!=0 );
87889  pTopNC->nRef++;
87890  if( pTopNC==pNC ) break;
87891  pTopNC = pTopNC->pNext;
87892  }
87893  return WRC_Prune;
87894  } else {
87895  return WRC_Abort;
87896  }
87897 }
87898 
87899 /*
87900 ** Allocate and return a pointer to an expression to load the column iCol
87901 ** from datasource iSrc in SrcList pSrc.
87902 */
87903 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
87904  Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
87905  if( p ){
87906  struct SrcList_item *pItem = &pSrc->a[iSrc];
87907  p->pTab = pItem->pTab;
87908  p->iTable = pItem->iCursor;
87909  if( p->pTab->iPKey==iCol ){
87910  p->iColumn = -1;
87911  }else{
87912  p->iColumn = (ynVar)iCol;
87913  testcase( iCol==BMS );
87914  testcase( iCol==BMS-1 );
87915  pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
87916  }
87918  }
87919  return p;
87920 }
87921 
87922 /*
87923 ** Report an error that an expression is not valid for some set of
87924 ** pNC->ncFlags values determined by validMask.
87925 */
87926 static void notValid(
87927  Parse *pParse, /* Leave error message here */
87928  NameContext *pNC, /* The name context */
87929  const char *zMsg, /* Type of error */
87930  int validMask /* Set of contexts for which prohibited */
87931 ){
87932  assert( (validMask&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr))==0 );
87933  if( (pNC->ncFlags & validMask)!=0 ){
87934  const char *zIn = "partial index WHERE clauses";
87935  if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
87936 #ifndef SQLITE_OMIT_CHECK
87937  else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
87938 #endif
87939  sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
87940  }
87941 }
87942 
87943 /*
87944 ** Expression p should encode a floating point value between 1.0 and 0.0.
87945 ** Return 1024 times this value. Or return -1 if p is not a floating point
87946 ** value between 1.0 and 0.0.
87947 */
87948 static int exprProbability(Expr *p){
87949  double r = -1.0;
87950  if( p->op!=TK_FLOAT ) return -1;
87952  assert( r>=0.0 );
87953  if( r>1.0 ) return -1;
87954  return (int)(r*134217728.0);
87955 }
87956 
87957 /*
87958 ** This routine is callback for sqlite3WalkExpr().
87959 **
87960 ** Resolve symbolic names into TK_COLUMN operators for the current
87961 ** node in the expression tree. Return 0 to continue the search down
87962 ** the tree or 2 to abort the tree walk.
87963 **
87964 ** This routine also does error checking and name resolution for
87965 ** function names. The operator for aggregate functions is changed
87966 ** to TK_AGG_FUNCTION.
87967 */
87968 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
87969  NameContext *pNC;
87970  Parse *pParse;
87971 
87972  pNC = pWalker->u.pNC;
87973  assert( pNC!=0 );
87974  pParse = pNC->pParse;
87975  assert( pParse==pWalker->pParse );
87976 
87977  if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
87978  ExprSetProperty(pExpr, EP_Resolved);
87979 #ifndef NDEBUG
87980  if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
87981  SrcList *pSrcList = pNC->pSrcList;
87982  int i;
87983  for(i=0; i<pNC->pSrcList->nSrc; i++){
87984  assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
87985  }
87986  }
87987 #endif
87988  switch( pExpr->op ){
87989 
87990 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
87991  /* The special operator TK_ROW means use the rowid for the first
87992  ** column in the FROM clause. This is used by the LIMIT and ORDER BY
87993  ** clause processing on UPDATE and DELETE statements.
87994  */
87995  case TK_ROW: {
87996  SrcList *pSrcList = pNC->pSrcList;
87997  struct SrcList_item *pItem;
87998  assert( pSrcList && pSrcList->nSrc==1 );
87999  pItem = pSrcList->a;
88000  pExpr->op = TK_COLUMN;
88001  pExpr->pTab = pItem->pTab;
88002  pExpr->iTable = pItem->iCursor;
88003  pExpr->iColumn = -1;
88004  pExpr->affinity = SQLITE_AFF_INTEGER;
88005  break;
88006  }
88007 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
88008  && !defined(SQLITE_OMIT_SUBQUERY) */
88009 
88010  /* A lone identifier is the name of a column.
88011  */
88012  case TK_ID: {
88013  return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
88014  }
88015 
88016  /* A table name and column name: ID.ID
88017  ** Or a database, table and column: ID.ID.ID
88018  */
88019  case TK_DOT: {
88020  const char *zColumn;
88021  const char *zTable;
88022  const char *zDb;
88023  Expr *pRight;
88024 
88025  /* if( pSrcList==0 ) break; */
88026  notValid(pParse, pNC, "the \".\" operator", NC_IdxExpr);
88027  /*notValid(pParse, pNC, "the \".\" operator", NC_PartIdx|NC_IsCheck, 1);*/
88028  pRight = pExpr->pRight;
88029  if( pRight->op==TK_ID ){
88030  zDb = 0;
88031  zTable = pExpr->pLeft->u.zToken;
88032  zColumn = pRight->u.zToken;
88033  }else{
88034  assert( pRight->op==TK_DOT );
88035  zDb = pExpr->pLeft->u.zToken;
88036  zTable = pRight->pLeft->u.zToken;
88037  zColumn = pRight->pRight->u.zToken;
88038  }
88039  return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
88040  }
88041 
88042  /* Resolve function names
88043  */
88044  case TK_FUNCTION: {
88045  ExprList *pList = pExpr->x.pList; /* The argument list */
88046  int n = pList ? pList->nExpr : 0; /* Number of arguments */
88047  int no_such_func = 0; /* True if no such function exists */
88048  int wrong_num_args = 0; /* True if wrong number of arguments */
88049  int is_agg = 0; /* True if is an aggregate function */
88050  int auth; /* Authorization to use the function */
88051  int nId; /* Number of characters in function name */
88052  const char *zId; /* The function name. */
88053  FuncDef *pDef; /* Information about the function */
88054  u8 enc = ENC(pParse->db); /* The database encoding */
88055 
88056  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
88057  notValid(pParse, pNC, "functions", NC_PartIdx);
88058  zId = pExpr->u.zToken;
88059  nId = sqlite3Strlen30(zId);
88060  pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
88061  if( pDef==0 ){
88062  pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
88063  if( pDef==0 ){
88064  no_such_func = 1;
88065  }else{
88066  wrong_num_args = 1;
88067  }
88068  }else{
88069  is_agg = pDef->xFinalize!=0;
88070  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
88072  if( n==2 ){
88073  pExpr->iTable = exprProbability(pList->a[1].pExpr);
88074  if( pExpr->iTable<0 ){
88075  sqlite3ErrorMsg(pParse,
88076  "second argument to likelihood() must be a "
88077  "constant between 0.0 and 1.0");
88078  pNC->nErr++;
88079  }
88080  }else{
88081  /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
88082  ** equivalent to likelihood(X, 0.0625).
88083  ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
88084  ** short-hand for likelihood(X,0.0625).
88085  ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
88086  ** for likelihood(X,0.9375).
88087  ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
88088  ** to likelihood(X,0.9375). */
88089  /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
88090  pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
88091  }
88092  }
88093 #ifndef SQLITE_OMIT_AUTHORIZATION
88094  auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
88095  if( auth!=SQLITE_OK ){
88096  if( auth==SQLITE_DENY ){
88097  sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
88098  pDef->zName);
88099  pNC->nErr++;
88100  }
88101  pExpr->op = TK_NULL;
88102  return WRC_Prune;
88103  }
88104 #endif
88106  /* For the purposes of the EP_ConstFunc flag, date and time
88107  ** functions and other functions that change slowly are considered
88108  ** constant because they are constant for the duration of one query */
88110  }
88111  if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
88112  /* Date/time functions that use 'now', and other functions like
88113  ** sqlite_version() that might change over time cannot be used
88114  ** in an index. */
88115  notValid(pParse, pNC, "non-deterministic functions", NC_IdxExpr);
88116  }
88117  }
88118  if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
88119  sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
88120  pNC->nErr++;
88121  is_agg = 0;
88122  }else if( no_such_func && pParse->db->init.busy==0 ){
88123  sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
88124  pNC->nErr++;
88125  }else if( wrong_num_args ){
88126  sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
88127  nId, zId);
88128  pNC->nErr++;
88129  }
88130  if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
88131  sqlite3WalkExprList(pWalker, pList);
88132  if( is_agg ){
88133  NameContext *pNC2 = pNC;
88134  pExpr->op = TK_AGG_FUNCTION;
88135  pExpr->op2 = 0;
88136  while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
88137  pExpr->op2++;
88138  pNC2 = pNC2->pNext;
88139  }
88140  assert( pDef!=0 );
88141  if( pNC2 ){
88143  testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
88144  pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
88145 
88146  }
88147  pNC->ncFlags |= NC_AllowAgg;
88148  }
88149  /* FIX ME: Compute pExpr->affinity based on the expected return
88150  ** type of the function
88151  */
88152  return WRC_Prune;
88153  }
88154 #ifndef SQLITE_OMIT_SUBQUERY
88155  case TK_SELECT:
88156  case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
88157 #endif
88158  case TK_IN: {
88159  testcase( pExpr->op==TK_IN );
88160  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88161  int nRef = pNC->nRef;
88162  notValid(pParse, pNC, "subqueries", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88163  sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
88164  assert( pNC->nRef>=nRef );
88165  if( nRef!=pNC->nRef ){
88166  ExprSetProperty(pExpr, EP_VarSelect);
88167  pNC->ncFlags |= NC_VarSelect;
88168  }
88169  }
88170  break;
88171  }
88172  case TK_VARIABLE: {
88173  notValid(pParse, pNC, "parameters", NC_IsCheck|NC_PartIdx|NC_IdxExpr);
88174  break;
88175  }
88176  }
88177  return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
88178 }
88179 
88180 /*
88181 ** pEList is a list of expressions which are really the result set of the
88182 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
88183 ** This routine checks to see if pE is a simple identifier which corresponds
88184 ** to the AS-name of one of the terms of the expression list. If it is,
88185 ** this routine return an integer between 1 and N where N is the number of
88186 ** elements in pEList, corresponding to the matching entry. If there is
88187 ** no match, or if pE is not a simple identifier, then this routine
88188 ** return 0.
88189 **
88190 ** pEList has been resolved. pE has not.
88191 */
88192 static int resolveAsName(
88193  Parse *pParse, /* Parsing context for error messages */
88194  ExprList *pEList, /* List of expressions to scan */
88195  Expr *pE /* Expression we are trying to match */
88196 ){
88197  int i; /* Loop counter */
88198 
88199  UNUSED_PARAMETER(pParse);
88200 
88201  if( pE->op==TK_ID ){
88202  char *zCol = pE->u.zToken;
88203  for(i=0; i<pEList->nExpr; i++){
88204  char *zAs = pEList->a[i].zName;
88205  if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
88206  return i+1;
88207  }
88208  }
88209  }
88210  return 0;
88211 }
88212 
88213 /*
88214 ** pE is a pointer to an expression which is a single term in the
88215 ** ORDER BY of a compound SELECT. The expression has not been
88216 ** name resolved.
88217 **
88218 ** At the point this routine is called, we already know that the
88219 ** ORDER BY term is not an integer index into the result set. That
88220 ** case is handled by the calling routine.
88221 **
88222 ** Attempt to match pE against result set columns in the left-most
88223 ** SELECT statement. Return the index i of the matching column,
88224 ** as an indication to the caller that it should sort by the i-th column.
88225 ** The left-most column is 1. In other words, the value returned is the
88226 ** same integer value that would be used in the SQL statement to indicate
88227 ** the column.
88228 **
88229 ** If there is no match, return 0. Return -1 if an error occurs.
88230 */
88232  Parse *pParse, /* Parsing context for error messages */
88233  Select *pSelect, /* The SELECT statement with the ORDER BY clause */
88234  Expr *pE /* The specific ORDER BY term */
88235 ){
88236  int i; /* Loop counter */
88237  ExprList *pEList; /* The columns of the result set */
88238  NameContext nc; /* Name context for resolving pE */
88239  sqlite3 *db; /* Database connection */
88240  int rc; /* Return code from subprocedures */
88241  u8 savedSuppErr; /* Saved value of db->suppressErr */
88242 
88243  assert( sqlite3ExprIsInteger(pE, &i)==0 );
88244  pEList = pSelect->pEList;
88245 
88246  /* Resolve all names in the ORDER BY term expression
88247  */
88248  memset(&nc, 0, sizeof(nc));
88249  nc.pParse = pParse;
88250  nc.pSrcList = pSelect->pSrc;
88251  nc.pEList = pEList;
88252  nc.ncFlags = NC_AllowAgg;
88253  nc.nErr = 0;
88254  db = pParse->db;
88255  savedSuppErr = db->suppressErr;
88256  db->suppressErr = 1;
88257  rc = sqlite3ResolveExprNames(&nc, pE);
88258  db->suppressErr = savedSuppErr;
88259  if( rc ) return 0;
88260 
88261  /* Try to match the ORDER BY expression against an expression
88262  ** in the result set. Return an 1-based index of the matching
88263  ** result-set entry.
88264  */
88265  for(i=0; i<pEList->nExpr; i++){
88266  if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
88267  return i+1;
88268  }
88269  }
88270 
88271  /* If no match, return 0. */
88272  return 0;
88273 }
88274 
88275 /*
88276 ** Generate an ORDER BY or GROUP BY term out-of-range error.
88277 */
88279  Parse *pParse, /* The error context into which to write the error */
88280  const char *zType, /* "ORDER" or "GROUP" */
88281  int i, /* The index (1-based) of the term out of range */
88282  int mx /* Largest permissible value of i */
88283 ){
88284  sqlite3ErrorMsg(pParse,
88285  "%r %s BY term out of range - should be "
88286  "between 1 and %d", i, zType, mx);
88287 }
88288 
88289 /*
88290 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
88291 ** each term of the ORDER BY clause is a constant integer between 1
88292 ** and N where N is the number of columns in the compound SELECT.
88293 **
88294 ** ORDER BY terms that are already an integer between 1 and N are
88295 ** unmodified. ORDER BY terms that are integers outside the range of
88296 ** 1 through N generate an error. ORDER BY terms that are expressions
88297 ** are matched against result set expressions of compound SELECT
88298 ** beginning with the left-most SELECT and working toward the right.
88299 ** At the first match, the ORDER BY expression is transformed into
88300 ** the integer column number.
88301 **
88302 ** Return the number of errors seen.
88303 */
88305  Parse *pParse, /* Parsing context. Leave error messages here */
88306  Select *pSelect /* The SELECT statement containing the ORDER BY */
88307 ){
88308  int i;
88309  ExprList *pOrderBy;
88310  ExprList *pEList;
88311  sqlite3 *db;
88312  int moreToDo = 1;
88313 
88314  pOrderBy = pSelect->pOrderBy;
88315  if( pOrderBy==0 ) return 0;
88316  db = pParse->db;
88317 #if SQLITE_MAX_COLUMN
88318  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88319  sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
88320  return 1;
88321  }
88322 #endif
88323  for(i=0; i<pOrderBy->nExpr; i++){
88324  pOrderBy->a[i].done = 0;
88325  }
88326  pSelect->pNext = 0;
88327  while( pSelect->pPrior ){
88328  pSelect->pPrior->pNext = pSelect;
88329  pSelect = pSelect->pPrior;
88330  }
88331  while( pSelect && moreToDo ){
88332  struct ExprList_item *pItem;
88333  moreToDo = 0;
88334  pEList = pSelect->pEList;
88335  assert( pEList!=0 );
88336  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88337  int iCol = -1;
88338  Expr *pE, *pDup;
88339  if( pItem->done ) continue;
88340  pE = sqlite3ExprSkipCollate(pItem->pExpr);
88341  if( sqlite3ExprIsInteger(pE, &iCol) ){
88342  if( iCol<=0 || iCol>pEList->nExpr ){
88343  resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
88344  return 1;
88345  }
88346  }else{
88347  iCol = resolveAsName(pParse, pEList, pE);
88348  if( iCol==0 ){
88349  pDup = sqlite3ExprDup(db, pE, 0);
88350  if( !db->mallocFailed ){
88351  assert(pDup);
88352  iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
88353  }
88354  sqlite3ExprDelete(db, pDup);
88355  }
88356  }
88357  if( iCol>0 ){
88358  /* Convert the ORDER BY term into an integer column number iCol,
88359  ** taking care to preserve the COLLATE clause if it exists */
88360  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
88361  if( pNew==0 ) return 1;
88362  pNew->flags |= EP_IntValue;
88363  pNew->u.iValue = iCol;
88364  if( pItem->pExpr==pE ){
88365  pItem->pExpr = pNew;
88366  }else{
88367  Expr *pParent = pItem->pExpr;
88368  assert( pParent->op==TK_COLLATE );
88369  while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
88370  assert( pParent->pLeft==pE );
88371  pParent->pLeft = pNew;
88372  }
88373  sqlite3ExprDelete(db, pE);
88374  pItem->u.x.iOrderByCol = (u16)iCol;
88375  pItem->done = 1;
88376  }else{
88377  moreToDo = 1;
88378  }
88379  }
88380  pSelect = pSelect->pNext;
88381  }
88382  for(i=0; i<pOrderBy->nExpr; i++){
88383  if( pOrderBy->a[i].done==0 ){
88384  sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
88385  "column in the result set", i+1);
88386  return 1;
88387  }
88388  }
88389  return 0;
88390 }
88391 
88392 /*
88393 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
88394 ** the SELECT statement pSelect. If any term is reference to a
88395 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
88396 ** field) then convert that term into a copy of the corresponding result set
88397 ** column.
88398 **
88399 ** If any errors are detected, add an error message to pParse and
88400 ** return non-zero. Return zero if no errors are seen.
88401 */
88403  Parse *pParse, /* Parsing context. Leave error messages here */
88404  Select *pSelect, /* The SELECT statement containing the clause */
88405  ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
88406  const char *zType /* "ORDER" or "GROUP" */
88407 ){
88408  int i;
88409  sqlite3 *db = pParse->db;
88410  ExprList *pEList;
88411  struct ExprList_item *pItem;
88412 
88413  if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
88414 #if SQLITE_MAX_COLUMN
88415  if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
88416  sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
88417  return 1;
88418  }
88419 #endif
88420  pEList = pSelect->pEList;
88421  assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
88422  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88423  if( pItem->u.x.iOrderByCol ){
88424  if( pItem->u.x.iOrderByCol>pEList->nExpr ){
88425  resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
88426  return 1;
88427  }
88428  resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
88429  zType,0);
88430  }
88431  }
88432  return 0;
88433 }
88434 
88435 /*
88436 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
88437 ** The Name context of the SELECT statement is pNC. zType is either
88438 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
88439 **
88440 ** This routine resolves each term of the clause into an expression.
88441 ** If the order-by term is an integer I between 1 and N (where N is the
88442 ** number of columns in the result set of the SELECT) then the expression
88443 ** in the resolution is a copy of the I-th result-set expression. If
88444 ** the order-by term is an identifier that corresponds to the AS-name of
88445 ** a result-set expression, then the term resolves to a copy of the
88446 ** result-set expression. Otherwise, the expression is resolved in
88447 ** the usual way - using sqlite3ResolveExprNames().
88448 **
88449 ** This routine returns the number of errors. If errors occur, then
88450 ** an appropriate error message might be left in pParse. (OOM errors
88451 ** excepted.)
88452 */
88454  NameContext *pNC, /* The name context of the SELECT statement */
88455  Select *pSelect, /* The SELECT statement holding pOrderBy */
88456  ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
88457  const char *zType /* Either "ORDER" or "GROUP", as appropriate */
88458 ){
88459  int i, j; /* Loop counters */
88460  int iCol; /* Column number */
88461  struct ExprList_item *pItem; /* A term of the ORDER BY clause */
88462  Parse *pParse; /* Parsing context */
88463  int nResult; /* Number of terms in the result set */
88464 
88465  if( pOrderBy==0 ) return 0;
88466  nResult = pSelect->pEList->nExpr;
88467  pParse = pNC->pParse;
88468  for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
88469  Expr *pE = pItem->pExpr;
88470  Expr *pE2 = sqlite3ExprSkipCollate(pE);
88471  if( zType[0]!='G' ){
88472  iCol = resolveAsName(pParse, pSelect->pEList, pE2);
88473  if( iCol>0 ){
88474  /* If an AS-name match is found, mark this ORDER BY column as being
88475  ** a copy of the iCol-th result-set column. The subsequent call to
88476  ** sqlite3ResolveOrderGroupBy() will convert the expression to a
88477  ** copy of the iCol-th result-set expression. */
88478  pItem->u.x.iOrderByCol = (u16)iCol;
88479  continue;
88480  }
88481  }
88482  if( sqlite3ExprIsInteger(pE2, &iCol) ){
88483  /* The ORDER BY term is an integer constant. Again, set the column
88484  ** number so that sqlite3ResolveOrderGroupBy() will convert the
88485  ** order-by term to a copy of the result-set expression */
88486  if( iCol<1 || iCol>0xffff ){
88487  resolveOutOfRangeError(pParse, zType, i+1, nResult);
88488  return 1;
88489  }
88490  pItem->u.x.iOrderByCol = (u16)iCol;
88491  continue;
88492  }
88493 
88494  /* Otherwise, treat the ORDER BY term as an ordinary expression */
88495  pItem->u.x.iOrderByCol = 0;
88496  if( sqlite3ResolveExprNames(pNC, pE) ){
88497  return 1;
88498  }
88499  for(j=0; j<pSelect->pEList->nExpr; j++){
88500  if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
88501  pItem->u.x.iOrderByCol = j+1;
88502  }
88503  }
88504  }
88505  return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
88506 }
88507 
88508 /*
88509 ** Resolve names in the SELECT statement p and all of its descendants.
88510 */
88511 static int resolveSelectStep(Walker *pWalker, Select *p){
88512  NameContext *pOuterNC; /* Context that contains this SELECT */
88513  NameContext sNC; /* Name context of this SELECT */
88514  int isCompound; /* True if p is a compound select */
88515  int nCompound; /* Number of compound terms processed so far */
88516  Parse *pParse; /* Parsing context */
88517  int i; /* Loop counter */
88518  ExprList *pGroupBy; /* The GROUP BY clause */
88519  Select *pLeftmost; /* Left-most of SELECT of a compound */
88520  sqlite3 *db; /* Database connection */
88521 
88522 
88523  assert( p!=0 );
88524  if( p->selFlags & SF_Resolved ){
88525  return WRC_Prune;
88526  }
88527  pOuterNC = pWalker->u.pNC;
88528  pParse = pWalker->pParse;
88529  db = pParse->db;
88530 
88531  /* Normally sqlite3SelectExpand() will be called first and will have
88532  ** already expanded this SELECT. However, if this is a subquery within
88533  ** an expression, sqlite3ResolveExprNames() will be called without a
88534  ** prior call to sqlite3SelectExpand(). When that happens, let
88535  ** sqlite3SelectPrep() do all of the processing for this SELECT.
88536  ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
88537  ** this routine in the correct order.
88538  */
88539  if( (p->selFlags & SF_Expanded)==0 ){
88540  sqlite3SelectPrep(pParse, p, pOuterNC);
88541  return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
88542  }
88543 
88544  isCompound = p->pPrior!=0;
88545  nCompound = 0;
88546  pLeftmost = p;
88547  while( p ){
88548  assert( (p->selFlags & SF_Expanded)!=0 );
88549  assert( (p->selFlags & SF_Resolved)==0 );
88550  p->selFlags |= SF_Resolved;
88551 
88552  /* Resolve the expressions in the LIMIT and OFFSET clauses. These
88553  ** are not allowed to refer to any names, so pass an empty NameContext.
88554  */
88555  memset(&sNC, 0, sizeof(sNC));
88556  sNC.pParse = pParse;
88557  if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
88558  sqlite3ResolveExprNames(&sNC, p->pOffset) ){
88559  return WRC_Abort;
88560  }
88561 
88562  /* If the SF_Converted flags is set, then this Select object was
88563  ** was created by the convertCompoundSelectToSubquery() function.
88564  ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
88565  ** as if it were part of the sub-query, not the parent. This block
88566  ** moves the pOrderBy down to the sub-query. It will be moved back
88567  ** after the names have been resolved. */
88568  if( p->selFlags & SF_Converted ){
88569  Select *pSub = p->pSrc->a[0].pSelect;
88570  assert( p->pSrc->nSrc==1 && p->pOrderBy );
88571  assert( pSub->pPrior && pSub->pOrderBy==0 );
88572  pSub->pOrderBy = p->pOrderBy;
88573  p->pOrderBy = 0;
88574  }
88575 
88576  /* Recursively resolve names in all subqueries
88577  */
88578  for(i=0; i<p->pSrc->nSrc; i++){
88579  struct SrcList_item *pItem = &p->pSrc->a[i];
88580  if( pItem->pSelect ){
88581  NameContext *pNC; /* Used to iterate name contexts */
88582  int nRef = 0; /* Refcount for pOuterNC and outer contexts */
88583  const char *zSavedContext = pParse->zAuthContext;
88584 
88585  /* Count the total number of references to pOuterNC and all of its
88586  ** parent contexts. After resolving references to expressions in
88587  ** pItem->pSelect, check if this value has changed. If so, then
88588  ** SELECT statement pItem->pSelect must be correlated. Set the
88589  ** pItem->fg.isCorrelated flag if this is the case. */
88590  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
88591 
88592  if( pItem->zName ) pParse->zAuthContext = pItem->zName;
88593  sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
88594  pParse->zAuthContext = zSavedContext;
88595  if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
88596 
88597  for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
88598  assert( pItem->fg.isCorrelated==0 && nRef<=0 );
88599  pItem->fg.isCorrelated = (nRef!=0);
88600  }
88601  }
88602 
88603  /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
88604  ** resolve the result-set expression list.
88605  */
88606  sNC.ncFlags = NC_AllowAgg;
88607  sNC.pSrcList = p->pSrc;
88608  sNC.pNext = pOuterNC;
88609 
88610  /* Resolve names in the result set. */
88611  if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
88612 
88613  /* If there are no aggregate functions in the result-set, and no GROUP BY
88614  ** expression, do not allow aggregates in any of the other expressions.
88615  */
88616  assert( (p->selFlags & SF_Aggregate)==0 );
88617  pGroupBy = p->pGroupBy;
88618  if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
88620  p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
88621  }else{
88622  sNC.ncFlags &= ~NC_AllowAgg;
88623  }
88624 
88625  /* If a HAVING clause is present, then there must be a GROUP BY clause.
88626  */
88627  if( p->pHaving && !pGroupBy ){
88628  sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
88629  return WRC_Abort;
88630  }
88631 
88632  /* Add the output column list to the name-context before parsing the
88633  ** other expressions in the SELECT statement. This is so that
88634  ** expressions in the WHERE clause (etc.) can refer to expressions by
88635  ** aliases in the result set.
88636  **
88637  ** Minor point: If this is the case, then the expression will be
88638  ** re-evaluated for each reference to it.
88639  */
88640  sNC.pEList = p->pEList;
88641  if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
88642  if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
88643 
88644  /* Resolve names in table-valued-function arguments */
88645  for(i=0; i<p->pSrc->nSrc; i++){
88646  struct SrcList_item *pItem = &p->pSrc->a[i];
88647  if( pItem->fg.isTabFunc
88648  && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
88649  ){
88650  return WRC_Abort;
88651  }
88652  }
88653 
88654  /* The ORDER BY and GROUP BY clauses may not refer to terms in
88655  ** outer queries
88656  */
88657  sNC.pNext = 0;
88658  sNC.ncFlags |= NC_AllowAgg;
88659 
88660  /* If this is a converted compound query, move the ORDER BY clause from
88661  ** the sub-query back to the parent query. At this point each term
88662  ** within the ORDER BY clause has been transformed to an integer value.
88663  ** These integers will be replaced by copies of the corresponding result
88664  ** set expressions by the call to resolveOrderGroupBy() below. */
88665  if( p->selFlags & SF_Converted ){
88666  Select *pSub = p->pSrc->a[0].pSelect;
88667  p->pOrderBy = pSub->pOrderBy;
88668  pSub->pOrderBy = 0;
88669  }
88670 
88671  /* Process the ORDER BY clause for singleton SELECT statements.
88672  ** The ORDER BY clause for compounds SELECT statements is handled
88673  ** below, after all of the result-sets for all of the elements of
88674  ** the compound have been resolved.
88675  **
88676  ** If there is an ORDER BY clause on a term of a compound-select other
88677  ** than the right-most term, then that is a syntax error. But the error
88678  ** is not detected until much later, and so we need to go ahead and
88679  ** resolve those symbols on the incorrect ORDER BY for consistency.
88680  */
88681  if( isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
88682  && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
88683  ){
88684  return WRC_Abort;
88685  }
88686  if( db->mallocFailed ){
88687  return WRC_Abort;
88688  }
88689 
88690  /* Resolve the GROUP BY clause. At the same time, make sure
88691  ** the GROUP BY clause does not contain aggregate functions.
88692  */
88693  if( pGroupBy ){
88694  struct ExprList_item *pItem;
88695 
88696  if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
88697  return WRC_Abort;
88698  }
88699  for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
88700  if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
88701  sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
88702  "the GROUP BY clause");
88703  return WRC_Abort;
88704  }
88705  }
88706  }
88707 
88708  /* If this is part of a compound SELECT, check that it has the right
88709  ** number of expressions in the select list. */
88710  if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
88712  return WRC_Abort;
88713  }
88714 
88715  /* Advance to the next term of the compound
88716  */
88717  p = p->pPrior;
88718  nCompound++;
88719  }
88720 
88721  /* Resolve the ORDER BY on a compound SELECT after all terms of
88722  ** the compound have been resolved.
88723  */
88724  if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
88725  return WRC_Abort;
88726  }
88727 
88728  return WRC_Prune;
88729 }
88730 
88731 /*
88732 ** This routine walks an expression tree and resolves references to
88733 ** table columns and result-set columns. At the same time, do error
88734 ** checking on function usage and set a flag if any aggregate functions
88735 ** are seen.
88736 **
88737 ** To resolve table columns references we look for nodes (or subtrees) of the
88738 ** form X.Y.Z or Y.Z or just Z where
88739 **
88740 ** X: The name of a database. Ex: "main" or "temp" or
88741 ** the symbolic name assigned to an ATTACH-ed database.
88742 **
88743 ** Y: The name of a table in a FROM clause. Or in a trigger
88744 ** one of the special names "old" or "new".
88745 **
88746 ** Z: The name of a column in table Y.
88747 **
88748 ** The node at the root of the subtree is modified as follows:
88749 **
88750 ** Expr.op Changed to TK_COLUMN
88751 ** Expr.pTab Points to the Table object for X.Y
88752 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
88753 ** Expr.iTable The VDBE cursor number for X.Y
88754 **
88755 **
88756 ** To resolve result-set references, look for expression nodes of the
88757 ** form Z (with no X and Y prefix) where the Z matches the right-hand
88758 ** size of an AS clause in the result-set of a SELECT. The Z expression
88759 ** is replaced by a copy of the left-hand side of the result-set expression.
88760 ** Table-name and function resolution occurs on the substituted expression
88761 ** tree. For example, in:
88762 **
88763 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
88764 **
88765 ** The "x" term of the order by is replaced by "a+b" to render:
88766 **
88767 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
88768 **
88769 ** Function calls are checked to make sure that the function is
88770 ** defined and that the correct number of arguments are specified.
88771 ** If the function is an aggregate function, then the NC_HasAgg flag is
88772 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
88773 ** If an expression contains aggregate functions then the EP_Agg
88774 ** property on the expression is set.
88775 **
88776 ** An error message is left in pParse if anything is amiss. The number
88777 ** if errors is returned.
88778 */
88780  NameContext *pNC, /* Namespace to resolve expressions in. */
88781  Expr *pExpr /* The expression to be analyzed. */
88782 ){
88783  u16 savedHasAgg;
88784  Walker w;
88785 
88786  if( pExpr==0 ) return 0;
88787 #if SQLITE_MAX_EXPR_DEPTH>0
88788  {
88789  Parse *pParse = pNC->pParse;
88790  if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
88791  return 1;
88792  }
88793  pParse->nHeight += pExpr->nHeight;
88794  }
88795 #endif
88796  savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
88797  pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
88798  w.pParse = pNC->pParse;
88801  w.xSelectCallback2 = 0;
88802  w.walkerDepth = 0;
88803  w.eCode = 0;
88804  w.u.pNC = pNC;
88805  sqlite3WalkExpr(&w, pExpr);
88806 #if SQLITE_MAX_EXPR_DEPTH>0
88807  pNC->pParse->nHeight -= pExpr->nHeight;
88808 #endif
88809  if( pNC->nErr>0 || w.pParse->nErr>0 ){
88810  ExprSetProperty(pExpr, EP_Error);
88811  }
88812  if( pNC->ncFlags & NC_HasAgg ){
88813  ExprSetProperty(pExpr, EP_Agg);
88814  }
88815  pNC->ncFlags |= savedHasAgg;
88816  return ExprHasProperty(pExpr, EP_Error);
88817 }
88818 
88819 /*
88820 ** Resolve all names for all expression in an expression list. This is
88821 ** just like sqlite3ResolveExprNames() except that it works for an expression
88822 ** list rather than a single expression.
88823 */
88825  NameContext *pNC, /* Namespace to resolve expressions in. */
88826  ExprList *pList /* The expression list to be analyzed. */
88827 ){
88828  int i;
88829  if( pList ){
88830  for(i=0; i<pList->nExpr; i++){
88831  if( sqlite3ResolveExprNames(pNC, pList->a[i].pExpr) ) return WRC_Abort;
88832  }
88833  }
88834  return WRC_Continue;
88835 }
88836 
88837 /*
88838 ** Resolve all names in all expressions of a SELECT and in all
88839 ** decendents of the SELECT, including compounds off of p->pPrior,
88840 ** subqueries in expressions, and subqueries used as FROM clause
88841 ** terms.
88842 **
88843 ** See sqlite3ResolveExprNames() for a description of the kinds of
88844 ** transformations that occur.
88845 **
88846 ** All SELECT statements should have been expanded using
88847 ** sqlite3SelectExpand() prior to invoking this routine.
88848 */
88850  Parse *pParse, /* The parser context */
88851  Select *p, /* The SELECT statement being coded. */
88852  NameContext *pOuterNC /* Name context for parent SELECT statement */
88853 ){
88854  Walker w;
88855 
88856  assert( p!=0 );
88857  memset(&w, 0, sizeof(w));
88860  w.pParse = pParse;
88861  w.u.pNC = pOuterNC;
88862  sqlite3WalkSelect(&w, p);
88863 }
88864 
88865 /*
88866 ** Resolve names in expressions that can only reference a single table:
88867 **
88868 ** * CHECK constraints
88869 ** * WHERE clauses on partial indices
88870 **
88871 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
88872 ** is set to -1 and the Expr.iColumn value is set to the column number.
88873 **
88874 ** Any errors cause an error message to be set in pParse.
88875 */
88877  Parse *pParse, /* Parsing context */
88878  Table *pTab, /* The table being referenced */
88879  int type, /* NC_IsCheck or NC_PartIdx or NC_IdxExpr */
88880  Expr *pExpr, /* Expression to resolve. May be NULL. */
88881  ExprList *pList /* Expression list to resolve. May be NUL. */
88882 ){
88883  SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
88884  NameContext sNC; /* Name context for pParse->pNewTable */
88885 
88886  assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr );
88887  memset(&sNC, 0, sizeof(sNC));
88888  memset(&sSrc, 0, sizeof(sSrc));
88889  sSrc.nSrc = 1;
88890  sSrc.a[0].zName = pTab->zName;
88891  sSrc.a[0].pTab = pTab;
88892  sSrc.a[0].iCursor = -1;
88893  sNC.pParse = pParse;
88894  sNC.pSrcList = &sSrc;
88895  sNC.ncFlags = type;
88896  if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
88897  if( pList ) sqlite3ResolveExprListNames(&sNC, pList);
88898 }
88899 
88900 /************** End of resolve.c *********************************************/
88901 /************** Begin file expr.c ********************************************/
88902 /*
88903 ** 2001 September 15
88904 **
88905 ** The author disclaims copyright to this source code. In place of
88906 ** a legal notice, here is a blessing:
88907 **
88908 ** May you do good and not evil.
88909 ** May you find forgiveness for yourself and forgive others.
88910 ** May you share freely, never taking more than you give.
88911 **
88912 *************************************************************************
88913 ** This file contains routines used for analyzing expressions and
88914 ** for generating VDBE code that evaluates expressions in SQLite.
88915 */
88916 /* #include "sqliteInt.h" */
88917 
88918 /*
88919 ** Return the 'affinity' of the expression pExpr if any.
88920 **
88921 ** If pExpr is a column, a reference to a column via an 'AS' alias,
88922 ** or a sub-select with a column as the return value, then the
88923 ** affinity of that column is returned. Otherwise, 0x00 is returned,
88924 ** indicating no affinity for the expression.
88925 **
88926 ** i.e. the WHERE clause expressions in the following statements all
88927 ** have an affinity:
88928 **
88929 ** CREATE TABLE t1(a);
88930 ** SELECT * FROM t1 WHERE a;
88931 ** SELECT a AS b FROM t1 WHERE b;
88932 ** SELECT * FROM t1 WHERE (select a from t1);
88933 */
88935  int op;
88936  pExpr = sqlite3ExprSkipCollate(pExpr);
88937  if( pExpr->flags & EP_Generic ) return 0;
88938  op = pExpr->op;
88939  if( op==TK_SELECT ){
88940  assert( pExpr->flags&EP_xIsSelect );
88941  return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
88942  }
88943 #ifndef SQLITE_OMIT_CAST
88944  if( op==TK_CAST ){
88945  assert( !ExprHasProperty(pExpr, EP_IntValue) );
88946  return sqlite3AffinityType(pExpr->u.zToken, 0);
88947  }
88948 #endif
88949  if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
88950  && pExpr->pTab!=0
88951  ){
88952  /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
88953  ** a TK_COLUMN but was previously evaluated and cached in a register */
88954  int j = pExpr->iColumn;
88955  if( j<0 ) return SQLITE_AFF_INTEGER;
88956  assert( pExpr->pTab && j<pExpr->pTab->nCol );
88957  return pExpr->pTab->aCol[j].affinity;
88958  }
88959  return pExpr->affinity;
88960 }
88961 
88962 /*
88963 ** Set the collating sequence for expression pExpr to be the collating
88964 ** sequence named by pToken. Return a pointer to a new Expr node that
88965 ** implements the COLLATE operator.
88966 **
88967 ** If a memory allocation error occurs, that fact is recorded in pParse->db
88968 ** and the pExpr parameter is returned unchanged.
88969 */
88971  Parse *pParse, /* Parsing context */
88972  Expr *pExpr, /* Add the "COLLATE" clause to this expression */
88973  const Token *pCollName, /* Name of collating sequence */
88974  int dequote /* True to dequote pCollName */
88975 ){
88976  if( pCollName->n>0 ){
88977  Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
88978  if( pNew ){
88979  pNew->pLeft = pExpr;
88980  pNew->flags |= EP_Collate|EP_Skip;
88981  pExpr = pNew;
88982  }
88983  }
88984  return pExpr;
88985 }
88986 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
88987  Token s;
88988  assert( zC!=0 );
88989  sqlite3TokenInit(&s, (char*)zC);
88990  return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
88991 }
88992 
88993 /*
88994 ** Skip over any TK_COLLATE operators and any unlikely()
88995 ** or likelihood() function at the root of an expression.
88996 */
88998  while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
88999  if( ExprHasProperty(pExpr, EP_Unlikely) ){
89000  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
89001  assert( pExpr->x.pList->nExpr>0 );
89002  assert( pExpr->op==TK_FUNCTION );
89003  pExpr = pExpr->x.pList->a[0].pExpr;
89004  }else{
89005  assert( pExpr->op==TK_COLLATE );
89006  pExpr = pExpr->pLeft;
89007  }
89008  }
89009  return pExpr;
89010 }
89011 
89012 /*
89013 ** Return the collation sequence for the expression pExpr. If
89014 ** there is no defined collating sequence, return NULL.
89015 **
89016 ** The collating sequence might be determined by a COLLATE operator
89017 ** or by the presence of a column with a defined collating sequence.
89018 ** COLLATE operators take first precedence. Left operands take
89019 ** precedence over right operands.
89020 */
89022  sqlite3 *db = pParse->db;
89023  CollSeq *pColl = 0;
89024  Expr *p = pExpr;
89025  while( p ){
89026  int op = p->op;
89027  if( p->flags & EP_Generic ) break;
89028  if( op==TK_CAST || op==TK_UPLUS ){
89029  p = p->pLeft;
89030  continue;
89031  }
89032  if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
89033  pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
89034  break;
89035  }
89036  if( (op==TK_AGG_COLUMN || op==TK_COLUMN
89037  || op==TK_REGISTER || op==TK_TRIGGER)
89038  && p->pTab!=0
89039  ){
89040  /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
89041  ** a TK_COLUMN but was previously evaluated and cached in a register */
89042  int j = p->iColumn;
89043  if( j>=0 ){
89044  const char *zColl = p->pTab->aCol[j].zColl;
89045  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
89046  }
89047  break;
89048  }
89049  if( p->flags & EP_Collate ){
89050  if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
89051  p = p->pLeft;
89052  }else{
89053  Expr *pNext = p->pRight;
89054  /* The Expr.x union is never used at the same time as Expr.pRight */
89055  assert( p->x.pList==0 || p->pRight==0 );
89056  /* p->flags holds EP_Collate and p->pLeft->flags does not. And
89057  ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
89058  ** least one EP_Collate. Thus the following two ALWAYS. */
89059  if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
89060  int i;
89061  for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
89062  if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
89063  pNext = p->x.pList->a[i].pExpr;
89064  break;
89065  }
89066  }
89067  }
89068  p = pNext;
89069  }
89070  }else{
89071  break;
89072  }
89073  }
89074  if( sqlite3CheckCollSeq(pParse, pColl) ){
89075  pColl = 0;
89076  }
89077  return pColl;
89078 }
89079 
89080 /*
89081 ** pExpr is an operand of a comparison operator. aff2 is the
89082 ** type affinity of the other operand. This routine returns the
89083 ** type affinity that should be used for the comparison operator.
89084 */
89086  char aff1 = sqlite3ExprAffinity(pExpr);
89087  if( aff1 && aff2 ){
89088  /* Both sides of the comparison are columns. If one has numeric
89089  ** affinity, use that. Otherwise use no affinity.
89090  */
89092  return SQLITE_AFF_NUMERIC;
89093  }else{
89094  return SQLITE_AFF_BLOB;
89095  }
89096  }else if( !aff1 && !aff2 ){
89097  /* Neither side of the comparison is a column. Compare the
89098  ** results directly.
89099  */
89100  return SQLITE_AFF_BLOB;
89101  }else{
89102  /* One side is a column, the other is not. Use the columns affinity. */
89103  assert( aff1==0 || aff2==0 );
89104  return (aff1 + aff2);
89105  }
89106 }
89107 
89108 /*
89109 ** pExpr is a comparison operator. Return the type affinity that should
89110 ** be applied to both operands prior to doing the comparison.
89111 */
89112 static char comparisonAffinity(Expr *pExpr){
89113  char aff;
89114  assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
89115  pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
89116  pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
89117  assert( pExpr->pLeft );
89118  aff = sqlite3ExprAffinity(pExpr->pLeft);
89119  if( pExpr->pRight ){
89120  aff = sqlite3CompareAffinity(pExpr->pRight, aff);
89121  }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
89122  aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
89123  }else if( !aff ){
89124  aff = SQLITE_AFF_BLOB;
89125  }
89126  return aff;
89127 }
89128 
89129 /*
89130 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
89131 ** idx_affinity is the affinity of an indexed column. Return true
89132 ** if the index with affinity idx_affinity may be used to implement
89133 ** the comparison in pExpr.
89134 */
89135 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
89136  char aff = comparisonAffinity(pExpr);
89137  switch( aff ){
89138  case SQLITE_AFF_BLOB:
89139  return 1;
89140  case SQLITE_AFF_TEXT:
89141  return idx_affinity==SQLITE_AFF_TEXT;
89142  default:
89143  return sqlite3IsNumericAffinity(idx_affinity);
89144  }
89145 }
89146 
89147 /*
89148 ** Return the P5 value that should be used for a binary comparison
89149 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
89150 */
89151 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
89152  u8 aff = (char)sqlite3ExprAffinity(pExpr2);
89153  aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
89154  return aff;
89155 }
89156 
89157 /*
89158 ** Return a pointer to the collation sequence that should be used by
89159 ** a binary comparison operator comparing pLeft and pRight.
89160 **
89161 ** If the left hand expression has a collating sequence type, then it is
89162 ** used. Otherwise the collation sequence for the right hand expression
89163 ** is used, or the default (BINARY) if neither expression has a collating
89164 ** type.
89165 **
89166 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
89167 ** it is not considered.
89168 */
89170  Parse *pParse,
89171  Expr *pLeft,
89172  Expr *pRight
89173 ){
89174  CollSeq *pColl;
89175  assert( pLeft );
89176  if( pLeft->flags & EP_Collate ){
89177  pColl = sqlite3ExprCollSeq(pParse, pLeft);
89178  }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
89179  pColl = sqlite3ExprCollSeq(pParse, pRight);
89180  }else{
89181  pColl = sqlite3ExprCollSeq(pParse, pLeft);
89182  if( !pColl ){
89183  pColl = sqlite3ExprCollSeq(pParse, pRight);
89184  }
89185  }
89186  return pColl;
89187 }
89188 
89189 /*
89190 ** Generate code for a comparison operator.
89191 */
89192 static int codeCompare(
89193  Parse *pParse, /* The parsing (and code generating) context */
89194  Expr *pLeft, /* The left operand */
89195  Expr *pRight, /* The right operand */
89196  int opcode, /* The comparison opcode */
89197  int in1, int in2, /* Register holding operands */
89198  int dest, /* Jump here if true. */
89199  int jumpIfNull /* If true, jump if either operand is NULL */
89200 ){
89201  int p5;
89202  int addr;
89203  CollSeq *p4;
89204 
89205  p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
89206  p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
89207  addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
89208  (void*)p4, P4_COLLSEQ);
89209  sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
89210  return addr;
89211 }
89212 
89213 #if SQLITE_MAX_EXPR_DEPTH>0
89214 /*
89215 ** Check that argument nHeight is less than or equal to the maximum
89216 ** expression depth allowed. If it is not, leave an error message in
89217 ** pParse.
89218 */
89219 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
89220  int rc = SQLITE_OK;
89221  int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
89222  if( nHeight>mxHeight ){
89223  sqlite3ErrorMsg(pParse,
89224  "Expression tree is too large (maximum depth %d)", mxHeight
89225  );
89226  rc = SQLITE_ERROR;
89227  }
89228  return rc;
89229 }
89230 
89231 /* The following three functions, heightOfExpr(), heightOfExprList()
89232 ** and heightOfSelect(), are used to determine the maximum height
89233 ** of any expression tree referenced by the structure passed as the
89234 ** first argument.
89235 **
89236 ** If this maximum height is greater than the current value pointed
89237 ** to by pnHeight, the second parameter, then set *pnHeight to that
89238 ** value.
89239 */
89240 static void heightOfExpr(Expr *p, int *pnHeight){
89241  if( p ){
89242  if( p->nHeight>*pnHeight ){
89243  *pnHeight = p->nHeight;
89244  }
89245  }
89246 }
89247 static void heightOfExprList(ExprList *p, int *pnHeight){
89248  if( p ){
89249  int i;
89250  for(i=0; i<p->nExpr; i++){
89251  heightOfExpr(p->a[i].pExpr, pnHeight);
89252  }
89253  }
89254 }
89255 static void heightOfSelect(Select *p, int *pnHeight){
89256  if( p ){
89257  heightOfExpr(p->pWhere, pnHeight);
89258  heightOfExpr(p->pHaving, pnHeight);
89259  heightOfExpr(p->pLimit, pnHeight);
89260  heightOfExpr(p->pOffset, pnHeight);
89261  heightOfExprList(p->pEList, pnHeight);
89262  heightOfExprList(p->pGroupBy, pnHeight);
89263  heightOfExprList(p->pOrderBy, pnHeight);
89264  heightOfSelect(p->pPrior, pnHeight);
89265  }
89266 }
89267 
89268 /*
89269 ** Set the Expr.nHeight variable in the structure passed as an
89270 ** argument. An expression with no children, Expr.pList or
89271 ** Expr.pSelect member has a height of 1. Any other expression
89272 ** has a height equal to the maximum height of any other
89273 ** referenced Expr plus one.
89274 **
89275 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
89276 ** if appropriate.
89277 */
89278 static void exprSetHeight(Expr *p){
89279  int nHeight = 0;
89280  heightOfExpr(p->pLeft, &nHeight);
89281  heightOfExpr(p->pRight, &nHeight);
89282  if( ExprHasProperty(p, EP_xIsSelect) ){
89283  heightOfSelect(p->x.pSelect, &nHeight);
89284  }else if( p->x.pList ){
89285  heightOfExprList(p->x.pList, &nHeight);
89287  }
89288  p->nHeight = nHeight + 1;
89289 }
89290 
89291 /*
89292 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
89293 ** the height is greater than the maximum allowed expression depth,
89294 ** leave an error in pParse.
89295 **
89296 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
89297 ** Expr.flags.
89298 */
89300  if( pParse->nErr ) return;
89301  exprSetHeight(p);
89302  sqlite3ExprCheckHeight(pParse, p->nHeight);
89303 }
89304 
89305 /*
89306 ** Return the maximum height of any expression tree referenced
89307 ** by the select statement passed as an argument.
89308 */
89310  int nHeight = 0;
89311  heightOfSelect(p, &nHeight);
89312  return nHeight;
89313 }
89314 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
89315 /*
89316 ** Propagate all EP_Propagate flags from the Expr.x.pList into
89317 ** Expr.flags.
89318 */
89320  if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
89322  }
89323 }
89324 #define exprSetHeight(y)
89325 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
89326 
89327 /*
89328 ** This routine is the core allocator for Expr nodes.
89329 **
89330 ** Construct a new expression node and return a pointer to it. Memory
89331 ** for this node and for the pToken argument is a single allocation
89332 ** obtained from sqlite3DbMalloc(). The calling function
89333 ** is responsible for making sure the node eventually gets freed.
89334 **
89335 ** If dequote is true, then the token (if it exists) is dequoted.
89336 ** If dequote is false, no dequoting is performed. The deQuote
89337 ** parameter is ignored if pToken is NULL or if the token does not
89338 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
89339 ** then the EP_DblQuoted flag is set on the expression node.
89340 **
89341 ** Special case: If op==TK_INTEGER and pToken points to a string that
89342 ** can be translated into a 32-bit integer, then the token is not
89343 ** stored in u.zToken. Instead, the integer values is written
89344 ** into u.iValue and the EP_IntValue flag is set. No extra storage
89345 ** is allocated to hold the integer text and the dequote flag is ignored.
89346 */
89348  sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
89349  int op, /* Expression opcode */
89350  const Token *pToken, /* Token argument. Might be NULL */
89351  int dequote /* True to dequote */
89352 ){
89353  Expr *pNew;
89354  int nExtra = 0;
89355  int iValue = 0;
89356 
89357  assert( db!=0 );
89358  if( pToken ){
89359  if( op!=TK_INTEGER || pToken->z==0
89360  || sqlite3GetInt32(pToken->z, &iValue)==0 ){
89361  nExtra = pToken->n+1;
89362  assert( iValue>=0 );
89363  }
89364  }
89365  pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
89366  if( pNew ){
89367  memset(pNew, 0, sizeof(Expr));
89368  pNew->op = (u8)op;
89369  pNew->iAgg = -1;
89370  if( pToken ){
89371  if( nExtra==0 ){
89372  pNew->flags |= EP_IntValue;
89373  pNew->u.iValue = iValue;
89374  }else{
89375  pNew->u.zToken = (char*)&pNew[1];
89376  assert( pToken->z!=0 || pToken->n==0 );
89377  if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
89378  pNew->u.zToken[pToken->n] = 0;
89379  if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
89380  if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
89381  sqlite3Dequote(pNew->u.zToken);
89382  }
89383  }
89384  }
89385 #if SQLITE_MAX_EXPR_DEPTH>0
89386  pNew->nHeight = 1;
89387 #endif
89388  }
89389  return pNew;
89390 }
89391 
89392 /*
89393 ** Allocate a new expression node from a zero-terminated token that has
89394 ** already been dequoted.
89395 */
89397  sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
89398  int op, /* Expression opcode */
89399  const char *zToken /* Token argument. Might be NULL */
89400 ){
89401  Token x;
89402  x.z = zToken;
89403  x.n = zToken ? sqlite3Strlen30(zToken) : 0;
89404  return sqlite3ExprAlloc(db, op, &x, 0);
89405 }
89406 
89407 /*
89408 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
89409 **
89410 ** If pRoot==NULL that means that a memory allocation error has occurred.
89411 ** In that case, delete the subtrees pLeft and pRight.
89412 */
89414  sqlite3 *db,
89415  Expr *pRoot,
89416  Expr *pLeft,
89417  Expr *pRight
89418 ){
89419  if( pRoot==0 ){
89420  assert( db->mallocFailed );
89421  sqlite3ExprDelete(db, pLeft);
89422  sqlite3ExprDelete(db, pRight);
89423  }else{
89424  if( pRight ){
89425  pRoot->pRight = pRight;
89426  pRoot->flags |= EP_Propagate & pRight->flags;
89427  }
89428  if( pLeft ){
89429  pRoot->pLeft = pLeft;
89430  pRoot->flags |= EP_Propagate & pLeft->flags;
89431  }
89432  exprSetHeight(pRoot);
89433  }
89434 }
89435 
89436 /*
89437 ** Allocate an Expr node which joins as many as two subtrees.
89438 **
89439 ** One or both of the subtrees can be NULL. Return a pointer to the new
89440 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
89441 ** free the subtrees and return NULL.
89442 */
89444  Parse *pParse, /* Parsing context */
89445  int op, /* Expression opcode */
89446  Expr *pLeft, /* Left operand */
89447  Expr *pRight, /* Right operand */
89448  const Token *pToken /* Argument token */
89449 ){
89450  Expr *p;
89451  if( op==TK_AND && pParse->nErr==0 ){
89452  /* Take advantage of short-circuit false optimization for AND */
89453  p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
89454  }else{
89455  p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
89456  sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
89457  }
89458  if( p ) {
89459  sqlite3ExprCheckHeight(pParse, p->nHeight);
89460  }
89461  return p;
89462 }
89463 
89464 /*
89465 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
89466 ** do a memory allocation failure) then delete the pSelect object.
89467 */
89468 SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
89469  if( pExpr ){
89470  pExpr->x.pSelect = pSelect;
89472  sqlite3ExprSetHeightAndFlags(pParse, pExpr);
89473  }else{
89474  assert( pParse->db->mallocFailed );
89475  sqlite3SelectDelete(pParse->db, pSelect);
89476  }
89477 }
89478 
89479 
89480 /*
89481 ** If the expression is always either TRUE or FALSE (respectively),
89482 ** then return 1. If one cannot determine the truth value of the
89483 ** expression at compile-time return 0.
89484 **
89485 ** This is an optimization. If is OK to return 0 here even if
89486 ** the expression really is always false or false (a false negative).
89487 ** But it is a bug to return 1 if the expression might have different
89488 ** boolean values in different circumstances (a false positive.)
89489 **
89490 ** Note that if the expression is part of conditional for a
89491 ** LEFT JOIN, then we cannot determine at compile-time whether or not
89492 ** is it true or false, so always return 0.
89493 */
89494 static int exprAlwaysTrue(Expr *p){
89495  int v = 0;
89496  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
89497  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
89498  return v!=0;
89499 }
89500 static int exprAlwaysFalse(Expr *p){
89501  int v = 0;
89502  if( ExprHasProperty(p, EP_FromJoin) ) return 0;
89503  if( !sqlite3ExprIsInteger(p, &v) ) return 0;
89504  return v==0;
89505 }
89506 
89507 /*
89508 ** Join two expressions using an AND operator. If either expression is
89509 ** NULL, then just return the other expression.
89510 **
89511 ** If one side or the other of the AND is known to be false, then instead
89512 ** of returning an AND expression, just return a constant expression with
89513 ** a value of false.
89514 */
89516  if( pLeft==0 ){
89517  return pRight;
89518  }else if( pRight==0 ){
89519  return pLeft;
89520  }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
89521  sqlite3ExprDelete(db, pLeft);
89522  sqlite3ExprDelete(db, pRight);
89523  return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
89524  }else{
89525  Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
89526  sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
89527  return pNew;
89528  }
89529 }
89530 
89531 /*
89532 ** Construct a new expression node for a function with multiple
89533 ** arguments.
89534 */
89536  Expr *pNew;
89537  sqlite3 *db = pParse->db;
89538  assert( pToken );
89539  pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
89540  if( pNew==0 ){
89541  sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
89542  return 0;
89543  }
89544  pNew->x.pList = pList;
89545  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
89546  sqlite3ExprSetHeightAndFlags(pParse, pNew);
89547  return pNew;
89548 }
89549 
89550 /*
89551 ** Assign a variable number to an expression that encodes a wildcard
89552 ** in the original SQL statement.
89553 **
89554 ** Wildcards consisting of a single "?" are assigned the next sequential
89555 ** variable number.
89556 **
89557 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
89558 ** sure "nnn" is not too be to avoid a denial of service attack when
89559 ** the SQL statement comes from an external source.
89560 **
89561 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
89562 ** as the previous instance of the same wildcard. Or if this is the first
89563 ** instance of the wildcard, the next sequential variable number is
89564 ** assigned.
89565 */
89567  sqlite3 *db = pParse->db;
89568  const char *z;
89569 
89570  if( pExpr==0 ) return;
89572  z = pExpr->u.zToken;
89573  assert( z!=0 );
89574  assert( z[0]!=0 );
89575  if( z[1]==0 ){
89576  /* Wildcard of the form "?". Assign the next variable number */
89577  assert( z[0]=='?' );
89578  pExpr->iColumn = (ynVar)(++pParse->nVar);
89579  }else{
89580  ynVar x = 0;
89581  u32 n = sqlite3Strlen30(z);
89582  if( z[0]=='?' ){
89583  /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
89584  ** use it as the variable number */
89585  i64 i;
89586  int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
89587  pExpr->iColumn = x = (ynVar)i;
89588  testcase( i==0 );
89589  testcase( i==1 );
89592  if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
89593  sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
89594  db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
89595  x = 0;
89596  }
89597  if( i>pParse->nVar ){
89598  pParse->nVar = (int)i;
89599  }
89600  }else{
89601  /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
89602  ** number as the prior appearance of the same name, or if the name
89603  ** has never appeared before, reuse the same variable number
89604  */
89605  ynVar i;
89606  for(i=0; i<pParse->nzVar; i++){
89607  if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
89608  pExpr->iColumn = x = (ynVar)i+1;
89609  break;
89610  }
89611  }
89612  if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
89613  }
89614  if( x>0 ){
89615  if( x>pParse->nzVar ){
89616  char **a;
89617  a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
89618  if( a==0 ){
89619  assert( db->mallocFailed ); /* Error reported through mallocFailed */
89620  return;
89621  }
89622  pParse->azVar = a;
89623  memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
89624  pParse->nzVar = x;
89625  }
89626  if( z[0]!='?' || pParse->azVar[x-1]==0 ){
89627  sqlite3DbFree(db, pParse->azVar[x-1]);
89628  pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
89629  }
89630  }
89631  }
89632  if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
89633  sqlite3ErrorMsg(pParse, "too many SQL variables");
89634  }
89635 }
89636 
89637 /*
89638 ** Recursively delete an expression tree.
89639 */
89641  assert( p!=0 );
89642  /* Sanity check: Assert that the IntValue is non-negative if it exists */
89643  assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
89644  if( !ExprHasProperty(p, EP_TokenOnly) ){
89645  /* The Expr.x union is never used at the same time as Expr.pRight */
89646  assert( p->x.pList==0 || p->pRight==0 );
89647  sqlite3ExprDelete(db, p->pLeft);
89648  sqlite3ExprDelete(db, p->pRight);
89649  if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
89650  if( ExprHasProperty(p, EP_xIsSelect) ){
89651  sqlite3SelectDelete(db, p->x.pSelect);
89652  }else{
89653  sqlite3ExprListDelete(db, p->x.pList);
89654  }
89655  }
89656  if( !ExprHasProperty(p, EP_Static) ){
89657  sqlite3DbFree(db, p);
89658  }
89659 }
89661  if( p ) sqlite3ExprDeleteNN(db, p);
89662 }
89663 
89664 /*
89665 ** Return the number of bytes allocated for the expression structure
89666 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
89667 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
89668 */
89669 static int exprStructSize(Expr *p){
89671  if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
89672  return EXPR_FULLSIZE;
89673 }
89674 
89675 /*
89676 ** The dupedExpr*Size() routines each return the number of bytes required
89677 ** to store a copy of an expression or expression tree. They differ in
89678 ** how much of the tree is measured.
89679 **
89680 ** dupedExprStructSize() Size of only the Expr structure
89681 ** dupedExprNodeSize() Size of Expr + space for token
89682 ** dupedExprSize() Expr + token + subtree components
89683 **
89684 ***************************************************************************
89685 **
89686 ** The dupedExprStructSize() function returns two values OR-ed together:
89687 ** (1) the space required for a copy of the Expr structure only and
89688 ** (2) the EP_xxx flags that indicate what the structure size should be.
89689 ** The return values is always one of:
89690 **
89691 ** EXPR_FULLSIZE
89692 ** EXPR_REDUCEDSIZE | EP_Reduced
89693 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
89694 **
89695 ** The size of the structure can be found by masking the return value
89696 ** of this routine with 0xfff. The flags can be found by masking the
89697 ** return value with EP_Reduced|EP_TokenOnly.
89698 **
89699 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
89700 ** (unreduced) Expr objects as they or originally constructed by the parser.
89701 ** During expression analysis, extra information is computed and moved into
89702 ** later parts of teh Expr object and that extra information might get chopped
89703 ** off if the expression is reduced. Note also that it does not work to
89704 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
89705 ** to reduce a pristine expression tree from the parser. The implementation
89706 ** of dupedExprStructSize() contain multiple assert() statements that attempt
89707 ** to enforce this constraint.
89708 */
89709 static int dupedExprStructSize(Expr *p, int flags){
89710  int nSize;
89711  assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
89712  assert( EXPR_FULLSIZE<=0xfff );
89713  assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
89714  if( 0==flags ){
89715  nSize = EXPR_FULLSIZE;
89716  }else{
89721  if( p->pLeft || p->x.pList ){
89722  nSize = EXPR_REDUCEDSIZE | EP_Reduced;
89723  }else{
89724  assert( p->pRight==0 );
89725  nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
89726  }
89727  }
89728  return nSize;
89729 }
89730 
89731 /*
89732 ** This function returns the space in bytes required to store the copy
89733 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
89734 ** string is defined.)
89735 */
89736 static int dupedExprNodeSize(Expr *p, int flags){
89737  int nByte = dupedExprStructSize(p, flags) & 0xfff;
89738  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89739  nByte += sqlite3Strlen30(p->u.zToken)+1;
89740  }
89741  return ROUND8(nByte);
89742 }
89743 
89744 /*
89745 ** Return the number of bytes required to create a duplicate of the
89746 ** expression passed as the first argument. The second argument is a
89747 ** mask containing EXPRDUP_XXX flags.
89748 **
89749 ** The value returned includes space to create a copy of the Expr struct
89750 ** itself and the buffer referred to by Expr.u.zToken, if any.
89751 **
89752 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
89753 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
89754 ** and Expr.pRight variables (but not for any structures pointed to or
89755 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
89756 */
89757 static int dupedExprSize(Expr *p, int flags){
89758  int nByte = 0;
89759  if( p ){
89760  nByte = dupedExprNodeSize(p, flags);
89761  if( flags&EXPRDUP_REDUCE ){
89762  nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
89763  }
89764  }
89765  return nByte;
89766 }
89767 
89768 /*
89769 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
89770 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
89771 ** to store the copy of expression p, the copies of p->u.zToken
89772 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
89773 ** if any. Before returning, *pzBuffer is set to the first byte past the
89774 ** portion of the buffer copied into by this function.
89775 */
89776 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
89777  Expr *pNew; /* Value to return */
89778  u8 *zAlloc; /* Memory space from which to build Expr object */
89779  u32 staticFlag; /* EP_Static if space not obtained from malloc */
89780 
89781  assert( db!=0 );
89782  assert( p );
89783  assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
89784  assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
89785 
89786  /* Figure out where to write the new Expr structure. */
89787  if( pzBuffer ){
89788  zAlloc = *pzBuffer;
89789  staticFlag = EP_Static;
89790  }else{
89791  zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
89792  staticFlag = 0;
89793  }
89794  pNew = (Expr *)zAlloc;
89795 
89796  if( pNew ){
89797  /* Set nNewSize to the size allocated for the structure pointed to
89798  ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
89799  ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
89800  ** by the copy of the p->u.zToken string (if any).
89801  */
89802  const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
89803  const int nNewSize = nStructSize & 0xfff;
89804  int nToken;
89805  if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
89806  nToken = sqlite3Strlen30(p->u.zToken) + 1;
89807  }else{
89808  nToken = 0;
89809  }
89810  if( dupFlags ){
89811  assert( ExprHasProperty(p, EP_Reduced)==0 );
89812  memcpy(zAlloc, p, nNewSize);
89813  }else{
89814  u32 nSize = (u32)exprStructSize(p);
89815  memcpy(zAlloc, p, nSize);
89816  if( nSize<EXPR_FULLSIZE ){
89817  memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
89818  }
89819  }
89820 
89821  /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
89823  pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
89824  pNew->flags |= staticFlag;
89825 
89826  /* Copy the p->u.zToken string, if any. */
89827  if( nToken ){
89828  char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
89829  memcpy(zToken, p->u.zToken, nToken);
89830  }
89831 
89832  if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
89833  /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
89834  if( ExprHasProperty(p, EP_xIsSelect) ){
89835  pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
89836  }else{
89837  pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
89838  }
89839  }
89840 
89841  /* Fill in pNew->pLeft and pNew->pRight. */
89843  zAlloc += dupedExprNodeSize(p, dupFlags);
89844  if( ExprHasProperty(pNew, EP_Reduced) ){
89845  pNew->pLeft = p->pLeft ?
89846  exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
89847  pNew->pRight = p->pRight ?
89848  exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
89849  }
89850  if( pzBuffer ){
89851  *pzBuffer = zAlloc;
89852  }
89853  }else{
89854  if( !ExprHasProperty(p, EP_TokenOnly) ){
89855  pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
89856  pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
89857  }
89858  }
89859  }
89860  return pNew;
89861 }
89862 
89863 /*
89864 ** Create and return a deep copy of the object passed as the second
89865 ** argument. If an OOM condition is encountered, NULL is returned
89866 ** and the db->mallocFailed flag set.
89867 */
89868 #ifndef SQLITE_OMIT_CTE
89869 static With *withDup(sqlite3 *db, With *p){
89870  With *pRet = 0;
89871  if( p ){
89872  int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
89873  pRet = sqlite3DbMallocZero(db, nByte);
89874  if( pRet ){
89875  int i;
89876  pRet->nCte = p->nCte;
89877  for(i=0; i<p->nCte; i++){
89878  pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
89879  pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
89880  pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
89881  }
89882  }
89883  }
89884  return pRet;
89885 }
89886 #else
89887 # define withDup(x,y) 0
89888 #endif
89889 
89890 /*
89891 ** The following group of routines make deep copies of expressions,
89892 ** expression lists, ID lists, and select statements. The copies can
89893 ** be deleted (by being passed to their respective ...Delete() routines)
89894 ** without effecting the originals.
89895 **
89896 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
89897 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
89898 ** by subsequent calls to sqlite*ListAppend() routines.
89899 **
89900 ** Any tables that the SrcList might point to are not duplicated.
89901 **
89902 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
89903 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
89904 ** truncated version of the usual Expr structure that will be stored as
89905 ** part of the in-memory representation of the database schema.
89906 */
89908  assert( flags==0 || flags==EXPRDUP_REDUCE );
89909  return p ? exprDup(db, p, flags, 0) : 0;
89910 }
89912  ExprList *pNew;
89913  struct ExprList_item *pItem, *pOldItem;
89914  int i;
89915  assert( db!=0 );
89916  if( p==0 ) return 0;
89917  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
89918  if( pNew==0 ) return 0;
89919  pNew->nExpr = i = p->nExpr;
89920  if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
89921  pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
89922  if( pItem==0 ){
89923  sqlite3DbFree(db, pNew);
89924  return 0;
89925  }
89926  pOldItem = p->a;
89927  for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
89928  Expr *pOldExpr = pOldItem->pExpr;
89929  pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
89930  pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
89931  pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
89932  pItem->sortOrder = pOldItem->sortOrder;
89933  pItem->done = 0;
89934  pItem->bSpanIsTab = pOldItem->bSpanIsTab;
89935  pItem->u = pOldItem->u;
89936  }
89937  return pNew;
89938 }
89939 
89940 /*
89941 ** If cursors, triggers, views and subqueries are all omitted from
89942 ** the build, then none of the following routines, except for
89943 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
89944 ** called with a NULL argument.
89945 */
89946 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
89947  || !defined(SQLITE_OMIT_SUBQUERY)
89949  SrcList *pNew;
89950  int i;
89951  int nByte;
89952  assert( db!=0 );
89953  if( p==0 ) return 0;
89954  nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
89955  pNew = sqlite3DbMallocRawNN(db, nByte );
89956  if( pNew==0 ) return 0;
89957  pNew->nSrc = pNew->nAlloc = p->nSrc;
89958  for(i=0; i<p->nSrc; i++){
89959  struct SrcList_item *pNewItem = &pNew->a[i];
89960  struct SrcList_item *pOldItem = &p->a[i];
89961  Table *pTab;
89962  pNewItem->pSchema = pOldItem->pSchema;
89963  pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
89964  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
89965  pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
89966  pNewItem->fg = pOldItem->fg;
89967  pNewItem->iCursor = pOldItem->iCursor;
89968  pNewItem->addrFillSub = pOldItem->addrFillSub;
89969  pNewItem->regReturn = pOldItem->regReturn;
89970  if( pNewItem->fg.isIndexedBy ){
89971  pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
89972  }
89973  pNewItem->pIBIndex = pOldItem->pIBIndex;
89974  if( pNewItem->fg.isTabFunc ){
89975  pNewItem->u1.pFuncArg =
89976  sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
89977  }
89978  pTab = pNewItem->pTab = pOldItem->pTab;
89979  if( pTab ){
89980  pTab->nRef++;
89981  }
89982  pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
89983  pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
89984  pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
89985  pNewItem->colUsed = pOldItem->colUsed;
89986  }
89987  return pNew;
89988 }
89990  IdList *pNew;
89991  int i;
89992  assert( db!=0 );
89993  if( p==0 ) return 0;
89994  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
89995  if( pNew==0 ) return 0;
89996  pNew->nId = p->nId;
89997  pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
89998  if( pNew->a==0 ){
89999  sqlite3DbFree(db, pNew);
90000  return 0;
90001  }
90002  /* Note that because the size of the allocation for p->a[] is not
90003  ** necessarily a power of two, sqlite3IdListAppend() may not be called
90004  ** on the duplicate created by this function. */
90005  for(i=0; i<p->nId; i++){
90006  struct IdList_item *pNewItem = &pNew->a[i];
90007  struct IdList_item *pOldItem = &p->a[i];
90008  pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
90009  pNewItem->idx = pOldItem->idx;
90010  }
90011  return pNew;
90012 }
90014  Select *pNew, *pPrior;
90015  assert( db!=0 );
90016  if( p==0 ) return 0;
90017  pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
90018  if( pNew==0 ) return 0;
90019  pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
90020  pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
90021  pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
90022  pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
90023  pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
90024  pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
90025  pNew->op = p->op;
90026  pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
90027  if( pPrior ) pPrior->pNext = pNew;
90028  pNew->pNext = 0;
90029  pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
90030  pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
90031  pNew->iLimit = 0;
90032  pNew->iOffset = 0;
90033  pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
90034  pNew->addrOpenEphm[0] = -1;
90035  pNew->addrOpenEphm[1] = -1;
90036  pNew->nSelectRow = p->nSelectRow;
90037  pNew->pWith = withDup(db, p->pWith);
90038  sqlite3SelectSetName(pNew, p->zSelName);
90039  return pNew;
90040 }
90041 #else
90042 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
90043  assert( p==0 );
90044  return 0;
90045 }
90046 #endif
90047 
90048 
90049 /*
90050 ** Add a new element to the end of an expression list. If pList is
90051 ** initially NULL, then create a new expression list.
90052 **
90053 ** If a memory allocation error occurs, the entire list is freed and
90054 ** NULL is returned. If non-NULL is returned, then it is guaranteed
90055 ** that the new entry was successfully appended.
90056 */
90058  Parse *pParse, /* Parsing context */
90059  ExprList *pList, /* List to which to append. Might be NULL */
90060  Expr *pExpr /* Expression to be appended. Might be NULL */
90061 ){
90062  sqlite3 *db = pParse->db;
90063  assert( db!=0 );
90064  if( pList==0 ){
90065  pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
90066  if( pList==0 ){
90067  goto no_mem;
90068  }
90069  pList->nExpr = 0;
90070  pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
90071  if( pList->a==0 ) goto no_mem;
90072  }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
90073  struct ExprList_item *a;
90074  assert( pList->nExpr>0 );
90075  a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
90076  if( a==0 ){
90077  goto no_mem;
90078  }
90079  pList->a = a;
90080  }
90081  assert( pList->a!=0 );
90082  if( 1 ){
90083  struct ExprList_item *pItem = &pList->a[pList->nExpr++];
90084  memset(pItem, 0, sizeof(*pItem));
90085  pItem->pExpr = pExpr;
90086  }
90087  return pList;
90088 
90089 no_mem:
90090  /* Avoid leaking memory if malloc has failed. */
90091  sqlite3ExprDelete(db, pExpr);
90092  sqlite3ExprListDelete(db, pList);
90093  return 0;
90094 }
90095 
90096 /*
90097 ** Set the sort order for the last element on the given ExprList.
90098 */
90100  if( p==0 ) return;
90101  assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
90102  assert( p->nExpr>0 );
90103  if( iSortOrder<0 ){
90104  assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
90105  return;
90106  }
90107  p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
90108 }
90109 
90110 /*
90111 ** Set the ExprList.a[].zName element of the most recently added item
90112 ** on the expression list.
90113 **
90114 ** pList might be NULL following an OOM error. But pName should never be
90115 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
90116 ** is set.
90117 */
90119  Parse *pParse, /* Parsing context */
90120  ExprList *pList, /* List to which to add the span. */
90121  Token *pName, /* Name to be added */
90122  int dequote /* True to cause the name to be dequoted */
90123 ){
90124  assert( pList!=0 || pParse->db->mallocFailed!=0 );
90125  if( pList ){
90126  struct ExprList_item *pItem;
90127  assert( pList->nExpr>0 );
90128  pItem = &pList->a[pList->nExpr-1];
90129  assert( pItem->zName==0 );
90130  pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
90131  if( dequote ) sqlite3Dequote(pItem->zName);
90132  }
90133 }
90134 
90135 /*
90136 ** Set the ExprList.a[].zSpan element of the most recently added item
90137 ** on the expression list.
90138 **
90139 ** pList might be NULL following an OOM error. But pSpan should never be
90140 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
90141 ** is set.
90142 */
90144  Parse *pParse, /* Parsing context */
90145  ExprList *pList, /* List to which to add the span. */
90146  ExprSpan *pSpan /* The span to be added */
90147 ){
90148  sqlite3 *db = pParse->db;
90149  assert( pList!=0 || db->mallocFailed!=0 );
90150  if( pList ){
90151  struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
90152  assert( pList->nExpr>0 );
90153  assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
90154  sqlite3DbFree(db, pItem->zSpan);
90155  pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
90156  (int)(pSpan->zEnd - pSpan->zStart));
90157  }
90158 }
90159 
90160 /*
90161 ** If the expression list pEList contains more than iLimit elements,
90162 ** leave an error message in pParse.
90163 */
90165  Parse *pParse,
90166  ExprList *pEList,
90167  const char *zObject
90168 ){
90169  int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
90170  testcase( pEList && pEList->nExpr==mx );
90171  testcase( pEList && pEList->nExpr==mx+1 );
90172  if( pEList && pEList->nExpr>mx ){
90173  sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
90174  }
90175 }
90176 
90177 /*
90178 ** Delete an entire expression list.
90179 */
90181  int i;
90182  struct ExprList_item *pItem;
90183  assert( pList->a!=0 || pList->nExpr==0 );
90184  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
90185  sqlite3ExprDelete(db, pItem->pExpr);
90186  sqlite3DbFree(db, pItem->zName);
90187  sqlite3DbFree(db, pItem->zSpan);
90188  }
90189  sqlite3DbFree(db, pList->a);
90190  sqlite3DbFree(db, pList);
90191 }
90193  if( pList ) exprListDeleteNN(db, pList);
90194 }
90195 
90196 /*
90197 ** Return the bitwise-OR of all Expr.flags fields in the given
90198 ** ExprList.
90199 */
90201  int i;
90202  u32 m = 0;
90203  if( pList ){
90204  for(i=0; i<pList->nExpr; i++){
90205  Expr *pExpr = pList->a[i].pExpr;
90206  assert( pExpr!=0 );
90207  m |= pExpr->flags;
90208  }
90209  }
90210  return m;
90211 }
90212 
90213 /*
90214 ** These routines are Walker callbacks used to check expressions to
90215 ** see if they are "constant" for some definition of constant. The
90216 ** Walker.eCode value determines the type of "constant" we are looking
90217 ** for.
90218 **
90219 ** These callback routines are used to implement the following:
90220 **
90221 ** sqlite3ExprIsConstant() pWalker->eCode==1
90222 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
90223 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
90224 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
90225 **
90226 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
90227 ** is found to not be a constant.
90228 **
90229 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
90230 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
90231 ** an existing schema and 4 when processing a new statement. A bound
90232 ** parameter raises an error for new statements, but is silently converted
90233 ** to NULL for existing schemas. This allows sqlite_master tables that
90234 ** contain a bound parameter because they were generated by older versions
90235 ** of SQLite to be parsed by newer versions of SQLite without raising a
90236 ** malformed schema error.
90237 */
90238 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
90239 
90240  /* If pWalker->eCode is 2 then any term of the expression that comes from
90241  ** the ON or USING clauses of a left join disqualifies the expression
90242  ** from being considered constant. */
90243  if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
90244  pWalker->eCode = 0;
90245  return WRC_Abort;
90246  }
90247 
90248  switch( pExpr->op ){
90249  /* Consider functions to be constant if all their arguments are constant
90250  ** and either pWalker->eCode==4 or 5 or the function has the
90251  ** SQLITE_FUNC_CONST flag. */
90252  case TK_FUNCTION:
90253  if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
90254  return WRC_Continue;
90255  }else{
90256  pWalker->eCode = 0;
90257  return WRC_Abort;
90258  }
90259  case TK_ID:
90260  case TK_COLUMN:
90261  case TK_AGG_FUNCTION:
90262  case TK_AGG_COLUMN:
90263  testcase( pExpr->op==TK_ID );
90264  testcase( pExpr->op==TK_COLUMN );
90265  testcase( pExpr->op==TK_AGG_FUNCTION );
90266  testcase( pExpr->op==TK_AGG_COLUMN );
90267  if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
90268  return WRC_Continue;
90269  }else{
90270  pWalker->eCode = 0;
90271  return WRC_Abort;
90272  }
90273  case TK_VARIABLE:
90274  if( pWalker->eCode==5 ){
90275  /* Silently convert bound parameters that appear inside of CREATE
90276  ** statements into a NULL when parsing the CREATE statement text out
90277  ** of the sqlite_master table */
90278  pExpr->op = TK_NULL;
90279  }else if( pWalker->eCode==4 ){
90280  /* A bound parameter in a CREATE statement that originates from
90281  ** sqlite3_prepare() causes an error */
90282  pWalker->eCode = 0;
90283  return WRC_Abort;
90284  }
90285  /* Fall through */
90286  default:
90287  testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
90288  testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
90289  return WRC_Continue;
90290  }
90291 }
90292 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
90293  UNUSED_PARAMETER(NotUsed);
90294  pWalker->eCode = 0;
90295  return WRC_Abort;
90296 }
90297 static int exprIsConst(Expr *p, int initFlag, int iCur){
90298  Walker w;
90299  memset(&w, 0, sizeof(w));
90300  w.eCode = initFlag;
90303  w.u.iCur = iCur;
90304  sqlite3WalkExpr(&w, p);
90305  return w.eCode;
90306 }
90307 
90308 /*
90309 ** Walk an expression tree. Return non-zero if the expression is constant
90310 ** and 0 if it involves variables or function calls.
90311 **
90312 ** For the purposes of this function, a double-quoted string (ex: "abc")
90313 ** is considered a variable but a single-quoted string (ex: 'abc') is
90314 ** a constant.
90315 */
90317  return exprIsConst(p, 1, 0);
90318 }
90319 
90320 /*
90321 ** Walk an expression tree. Return non-zero if the expression is constant
90322 ** that does no originate from the ON or USING clauses of a join.
90323 ** Return 0 if it involves variables or function calls or terms from
90324 ** an ON or USING clause.
90325 */
90327  return exprIsConst(p, 2, 0);
90328 }
90329 
90330 /*
90331 ** Walk an expression tree. Return non-zero if the expression is constant
90332 ** for any single row of the table with cursor iCur. In other words, the
90333 ** expression must not refer to any non-deterministic function nor any
90334 ** table other than iCur.
90335 */
90337  return exprIsConst(p, 3, iCur);
90338 }
90339 
90340 /*
90341 ** Walk an expression tree. Return non-zero if the expression is constant
90342 ** or a function call with constant arguments. Return and 0 if there
90343 ** are any variables.
90344 **
90345 ** For the purposes of this function, a double-quoted string (ex: "abc")
90346 ** is considered a variable but a single-quoted string (ex: 'abc') is
90347 ** a constant.
90348 */
90350  assert( isInit==0 || isInit==1 );
90351  return exprIsConst(p, 4+isInit, 0);
90352 }
90353 
90354 #ifdef SQLITE_ENABLE_CURSOR_HINTS
90355 /*
90356 ** Walk an expression tree. Return 1 if the expression contains a
90357 ** subquery of some kind. Return 0 if there are no subqueries.
90358 */
90359 SQLITE_PRIVATE int sqlite3ExprContainsSubquery(Expr *p){
90360  Walker w;
90361  memset(&w, 0, sizeof(w));
90362  w.eCode = 1;
90365  sqlite3WalkExpr(&w, p);
90366  return w.eCode==0;
90367 }
90368 #endif
90369 
90370 /*
90371 ** If the expression p codes a constant integer that is small enough
90372 ** to fit in a 32-bit integer, return 1 and put the value of the integer
90373 ** in *pValue. If the expression is not an integer or if it is too big
90374 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
90375 */
90377  int rc = 0;
90378 
90379  /* If an expression is an integer literal that fits in a signed 32-bit
90380  ** integer, then the EP_IntValue flag will have already been set */
90381  assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
90382  || sqlite3GetInt32(p->u.zToken, &rc)==0 );
90383 
90384  if( p->flags & EP_IntValue ){
90385  *pValue = p->u.iValue;
90386  return 1;
90387  }
90388  switch( p->op ){
90389  case TK_UPLUS: {
90390  rc = sqlite3ExprIsInteger(p->pLeft, pValue);
90391  break;
90392  }
90393  case TK_UMINUS: {
90394  int v;
90395  if( sqlite3ExprIsInteger(p->pLeft, &v) ){
90396  assert( v!=(-2147483647-1) );
90397  *pValue = -v;
90398  rc = 1;
90399  }
90400  break;
90401  }
90402  default: break;
90403  }
90404  return rc;
90405 }
90406 
90407 /*
90408 ** Return FALSE if there is no chance that the expression can be NULL.
90409 **
90410 ** If the expression might be NULL or if the expression is too complex
90411 ** to tell return TRUE.
90412 **
90413 ** This routine is used as an optimization, to skip OP_IsNull opcodes
90414 ** when we know that a value cannot be NULL. Hence, a false positive
90415 ** (returning TRUE when in fact the expression can never be NULL) might
90416 ** be a small performance hit but is otherwise harmless. On the other
90417 ** hand, a false negative (returning FALSE when the result could be NULL)
90418 ** will likely result in an incorrect answer. So when in doubt, return
90419 ** TRUE.
90420 */
90422  u8 op;
90423  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90424  op = p->op;
90425  if( op==TK_REGISTER ) op = p->op2;
90426  switch( op ){
90427  case TK_INTEGER:
90428  case TK_STRING:
90429  case TK_FLOAT:
90430  case TK_BLOB:
90431  return 0;
90432  case TK_COLUMN:
90433  assert( p->pTab!=0 );
90434  return ExprHasProperty(p, EP_CanBeNull) ||
90435  (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
90436  default:
90437  return 1;
90438  }
90439 }
90440 
90441 /*
90442 ** Return TRUE if the given expression is a constant which would be
90443 ** unchanged by OP_Affinity with the affinity given in the second
90444 ** argument.
90445 **
90446 ** This routine is used to determine if the OP_Affinity operation
90447 ** can be omitted. When in doubt return FALSE. A false negative
90448 ** is harmless. A false positive, however, can result in the wrong
90449 ** answer.
90450 */
90452  u8 op;
90453  if( aff==SQLITE_AFF_BLOB ) return 1;
90454  while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
90455  op = p->op;
90456  if( op==TK_REGISTER ) op = p->op2;
90457  switch( op ){
90458  case TK_INTEGER: {
90459  return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
90460  }
90461  case TK_FLOAT: {
90462  return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
90463  }
90464  case TK_STRING: {
90465  return aff==SQLITE_AFF_TEXT;
90466  }
90467  case TK_BLOB: {
90468  return 1;
90469  }
90470  case TK_COLUMN: {
90471  assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
90472  return p->iColumn<0
90473  && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
90474  }
90475  default: {
90476  return 0;
90477  }
90478  }
90479 }
90480 
90481 /*
90482 ** Return TRUE if the given string is a row-id column name.
90483 */
90484 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
90485  if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
90486  if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
90487  if( sqlite3StrICmp(z, "OID")==0 ) return 1;
90488  return 0;
90489 }
90490 
90491 /*
90492 ** pX is the RHS of an IN operator. If pX is a SELECT statement
90493 ** that can be simplified to a direct table access, then return
90494 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
90495 ** or if the SELECT statement needs to be manifested into a transient
90496 ** table, then return NULL.
90497 */
90498 #ifndef SQLITE_OMIT_SUBQUERY
90500  Select *p;
90501  SrcList *pSrc;
90502  ExprList *pEList;
90503  Expr *pRes;
90504  Table *pTab;
90505  if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
90506  if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
90507  p = pX->x.pSelect;
90508  if( p->pPrior ) return 0; /* Not a compound SELECT */
90509  if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
90512  return 0; /* No DISTINCT keyword and no aggregate functions */
90513  }
90514  assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
90515  if( p->pLimit ) return 0; /* Has no LIMIT clause */
90516  assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
90517  if( p->pWhere ) return 0; /* Has no WHERE clause */
90518  pSrc = p->pSrc;
90519  assert( pSrc!=0 );
90520  if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
90521  if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
90522  pTab = pSrc->a[0].pTab;
90523  assert( pTab!=0 );
90524  assert( pTab->pSelect==0 ); /* FROM clause is not a view */
90525  if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
90526  pEList = p->pEList;
90527  if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
90528  pRes = pEList->a[0].pExpr;
90529  if( pRes->op!=TK_COLUMN ) return 0; /* Result is a column */
90530  assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
90531  return p;
90532 }
90533 #endif /* SQLITE_OMIT_SUBQUERY */
90534 
90535 /*
90536 ** Code an OP_Once instruction and allocate space for its flag. Return the
90537 ** address of the new instruction.
90538 */
90540  Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
90541  return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
90542 }
90543 
90544 /*
90545 ** Generate code that checks the left-most column of index table iCur to see if
90546 ** it contains any NULL entries. Cause the register at regHasNull to be set
90547 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
90548 ** to be set to NULL if iCur contains one or more NULL values.
90549 */
90550 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
90551  int addr1;
90552  sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
90553  addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
90554  sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
90556  VdbeComment((v, "first_entry_in(%d)", iCur));
90557  sqlite3VdbeJumpHere(v, addr1);
90558 }
90559 
90560 
90561 #ifndef SQLITE_OMIT_SUBQUERY
90562 /*
90563 ** The argument is an IN operator with a list (not a subquery) on the
90564 ** right-hand side. Return TRUE if that list is constant.
90565 */
90566 static int sqlite3InRhsIsConstant(Expr *pIn){
90567  Expr *pLHS;
90568  int res;
90570  pLHS = pIn->pLeft;
90571  pIn->pLeft = 0;
90572  res = sqlite3ExprIsConstant(pIn);
90573  pIn->pLeft = pLHS;
90574  return res;
90575 }
90576 #endif
90577 
90578 /*
90579 ** This function is used by the implementation of the IN (...) operator.
90580 ** The pX parameter is the expression on the RHS of the IN operator, which
90581 ** might be either a list of expressions or a subquery.
90582 **
90583 ** The job of this routine is to find or create a b-tree object that can
90584 ** be used either to test for membership in the RHS set or to iterate through
90585 ** all members of the RHS set, skipping duplicates.
90586 **
90587 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
90588 ** and pX->iTable is set to the index of that cursor.
90589 **
90590 ** The returned value of this function indicates the b-tree type, as follows:
90591 **
90592 ** IN_INDEX_ROWID - The cursor was opened on a database table.
90593 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
90594 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
90595 ** IN_INDEX_EPH - The cursor was opened on a specially created and
90596 ** populated epheremal table.
90597 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
90598 ** implemented as a sequence of comparisons.
90599 **
90600 ** An existing b-tree might be used if the RHS expression pX is a simple
90601 ** subquery such as:
90602 **
90603 ** SELECT <column> FROM <table>
90604 **
90605 ** If the RHS of the IN operator is a list or a more complex subquery, then
90606 ** an ephemeral table might need to be generated from the RHS and then
90607 ** pX->iTable made to point to the ephemeral table instead of an
90608 ** existing table.
90609 **
90610 ** The inFlags parameter must contain exactly one of the bits
90611 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
90612 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
90613 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
90614 ** IN index will be used to loop over all values of the RHS of the
90615 ** IN operator.
90616 **
90617 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
90618 ** through the set members) then the b-tree must not contain duplicates.
90619 ** An epheremal table must be used unless the selected <column> is guaranteed
90620 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
90621 ** has a UNIQUE constraint or UNIQUE index.
90622 **
90623 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
90624 ** for fast set membership tests) then an epheremal table must
90625 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
90626 ** be found with <column> as its left-most column.
90627 **
90628 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
90629 ** if the RHS of the IN operator is a list (not a subquery) then this
90630 ** routine might decide that creating an ephemeral b-tree for membership
90631 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
90632 ** calling routine should implement the IN operator using a sequence
90633 ** of Eq or Ne comparison operations.
90634 **
90635 ** When the b-tree is being used for membership tests, the calling function
90636 ** might need to know whether or not the RHS side of the IN operator
90637 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
90638 ** if there is any chance that the (...) might contain a NULL value at
90639 ** runtime, then a register is allocated and the register number written
90640 ** to *prRhsHasNull. If there is no chance that the (...) contains a
90641 ** NULL value, then *prRhsHasNull is left unchanged.
90642 **
90643 ** If a register is allocated and its location stored in *prRhsHasNull, then
90644 ** the value in that register will be NULL if the b-tree contains one or more
90645 ** NULL values, and it will be some non-NULL value if the b-tree contains no
90646 ** NULL values.
90647 */
90648 #ifndef SQLITE_OMIT_SUBQUERY
90649 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
90650  Select *p; /* SELECT to the right of IN operator */
90651  int eType = 0; /* Type of RHS table. IN_INDEX_* */
90652  int iTab = pParse->nTab++; /* Cursor of the RHS table */
90653  int mustBeUnique; /* True if RHS must be unique */
90654  Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
90655 
90656  assert( pX->op==TK_IN );
90657  mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
90658 
90659  /* Check to see if an existing table or index can be used to
90660  ** satisfy the query. This is preferable to generating a new
90661  ** ephemeral table.
90662  */
90663  if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
90664  sqlite3 *db = pParse->db; /* Database connection */
90665  Table *pTab; /* Table <table>. */
90666  Expr *pExpr; /* Expression <column> */
90667  i16 iCol; /* Index of column <column> */
90668  i16 iDb; /* Database idx for pTab */
90669 
90670  assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
90671  assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
90672  assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
90673  pTab = p->pSrc->a[0].pTab;
90674  pExpr = p->pEList->a[0].pExpr;
90675  iCol = (i16)pExpr->iColumn;
90676 
90677  /* Code an OP_Transaction and OP_TableLock for <table>. */
90678  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
90679  sqlite3CodeVerifySchema(pParse, iDb);
90680  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
90681 
90682  /* This function is only called from two places. In both cases the vdbe
90683  ** has already been allocated. So assume sqlite3GetVdbe() is always
90684  ** successful here.
90685  */
90686  assert(v);
90687  if( iCol<0 ){
90688  int iAddr = sqlite3CodeOnce(pParse);
90689  VdbeCoverage(v);
90690 
90691  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
90692  eType = IN_INDEX_ROWID;
90693 
90694  sqlite3VdbeJumpHere(v, iAddr);
90695  }else{
90696  Index *pIdx; /* Iterator variable */
90697 
90698  /* The collation sequence used by the comparison. If an index is to
90699  ** be used in place of a temp-table, it must be ordered according
90700  ** to this collation sequence. */
90701  CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
90702 
90703  /* Check that the affinity that will be used to perform the
90704  ** comparison is the same as the affinity of the column. If
90705  ** it is not, it is not possible to use any index.
90706  */
90707  int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
90708 
90709  for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
90710  if( (pIdx->aiColumn[0]==iCol)
90711  && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
90712  && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
90713  ){
90714  int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
90715  sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
90716  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
90717  VdbeComment((v, "%s", pIdx->zName));
90719  eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
90720 
90721  if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
90722  *prRhsHasNull = ++pParse->nMem;
90723  sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
90724  }
90725  sqlite3VdbeJumpHere(v, iAddr);
90726  }
90727  }
90728  }
90729  }
90730 
90731  /* If no preexisting index is available for the IN clause
90732  ** and IN_INDEX_NOOP is an allowed reply
90733  ** and the RHS of the IN operator is a list, not a subquery
90734  ** and the RHS is not contant or has two or fewer terms,
90735  ** then it is not worth creating an ephemeral table to evaluate
90736  ** the IN operator so return IN_INDEX_NOOP.
90737  */
90738  if( eType==0
90739  && (inFlags & IN_INDEX_NOOP_OK)
90740  && !ExprHasProperty(pX, EP_xIsSelect)
90741  && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
90742  ){
90743  eType = IN_INDEX_NOOP;
90744  }
90745 
90746 
90747  if( eType==0 ){
90748  /* Could not find an existing table or index to use as the RHS b-tree.
90749  ** We will have to generate an ephemeral table to do the job.
90750  */
90751  u32 savedNQueryLoop = pParse->nQueryLoop;
90752  int rMayHaveNull = 0;
90753  eType = IN_INDEX_EPH;
90754  if( inFlags & IN_INDEX_LOOP ){
90755  pParse->nQueryLoop = 0;
90756  if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
90757  eType = IN_INDEX_ROWID;
90758  }
90759  }else if( prRhsHasNull ){
90760  *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
90761  }
90762  sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
90763  pParse->nQueryLoop = savedNQueryLoop;
90764  }else{
90765  pX->iTable = iTab;
90766  }
90767  return eType;
90768 }
90769 #endif
90770 
90771 /*
90772 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
90773 ** or IN operators. Examples:
90774 **
90775 ** (SELECT a FROM b) -- subquery
90776 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
90777 ** x IN (4,5,11) -- IN operator with list on right-hand side
90778 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
90779 **
90780 ** The pExpr parameter describes the expression that contains the IN
90781 ** operator or subquery.
90782 **
90783 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
90784 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
90785 ** to some integer key column of a table B-Tree. In this case, use an
90786 ** intkey B-Tree to store the set of IN(...) values instead of the usual
90787 ** (slower) variable length keys B-Tree.
90788 **
90789 ** If rMayHaveNull is non-zero, that means that the operation is an IN
90790 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
90791 ** All this routine does is initialize the register given by rMayHaveNull
90792 ** to NULL. Calling routines will take care of changing this register
90793 ** value to non-NULL if the RHS is NULL-free.
90794 **
90795 ** For a SELECT or EXISTS operator, return the register that holds the
90796 ** result. For IN operators or if an error occurs, the return value is 0.
90797 */
90798 #ifndef SQLITE_OMIT_SUBQUERY
90800  Parse *pParse, /* Parsing context */
90801  Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
90802  int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
90803  int isRowid /* If true, LHS of IN operator is a rowid */
90804 ){
90805  int jmpIfDynamic = -1; /* One-time test address */
90806  int rReg = 0; /* Register storing resulting */
90807  Vdbe *v = sqlite3GetVdbe(pParse);
90808  if( NEVER(v==0) ) return 0;
90809  sqlite3ExprCachePush(pParse);
90810 
90811  /* This code must be run in its entirety every time it is encountered
90812  ** if any of the following is true:
90813  **
90814  ** * The right-hand side is a correlated subquery
90815  ** * The right-hand side is an expression list containing variables
90816  ** * We are inside a trigger
90817  **
90818  ** If all of the above are false, then we can run this code just once
90819  ** save the results, and reuse the same result on subsequent invocations.
90820  */
90821  if( !ExprHasProperty(pExpr, EP_VarSelect) ){
90822  jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
90823  }
90824 
90825 #ifndef SQLITE_OMIT_EXPLAIN
90826  if( pParse->explain==2 ){
90827  char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
90828  jmpIfDynamic>=0?"":"CORRELATED ",
90829  pExpr->op==TK_IN?"LIST":"SCALAR",
90830  pParse->iNextSelectId
90831  );
90832  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
90833  }
90834 #endif
90835 
90836  switch( pExpr->op ){
90837  case TK_IN: {
90838  char affinity; /* Affinity of the LHS of the IN */
90839  int addr; /* Address of OP_OpenEphemeral instruction */
90840  Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
90841  KeyInfo *pKeyInfo = 0; /* Key information */
90842 
90843  affinity = sqlite3ExprAffinity(pLeft);
90844 
90845  /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
90846  ** expression it is handled the same way. An ephemeral table is
90847  ** filled with single-field index keys representing the results
90848  ** from the SELECT or the <exprlist>.
90849  **
90850  ** If the 'x' expression is a column value, or the SELECT...
90851  ** statement returns a column value, then the affinity of that
90852  ** column is used to build the index keys. If both 'x' and the
90853  ** SELECT... statement are columns, then numeric affinity is used
90854  ** if either column has NUMERIC or INTEGER affinity. If neither
90855  ** 'x' nor the SELECT... statement are columns, then numeric affinity
90856  ** is used.
90857  */
90858  pExpr->iTable = pParse->nTab++;
90859  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
90860  pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
90861 
90862  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90863  /* Case 1: expr IN (SELECT ...)
90864  **
90865  ** Generate code to write the results of the select into the temporary
90866  ** table allocated and opened above.
90867  */
90868  Select *pSelect = pExpr->x.pSelect;
90869  SelectDest dest;
90870  ExprList *pEList;
90871 
90872  assert( !isRowid );
90873  sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
90874  dest.affSdst = (u8)affinity;
90875  assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
90876  pSelect->iLimit = 0;
90877  testcase( pSelect->selFlags & SF_Distinct );
90878  testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
90879  if( sqlite3Select(pParse, pSelect, &dest) ){
90880  sqlite3KeyInfoUnref(pKeyInfo);
90881  return 0;
90882  }
90883  pEList = pSelect->pEList;
90884  assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
90885  assert( pEList!=0 );
90886  assert( pEList->nExpr>0 );
90887  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
90888  pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
90889  pEList->a[0].pExpr);
90890  }else if( ALWAYS(pExpr->x.pList!=0) ){
90891  /* Case 2: expr IN (exprlist)
90892  **
90893  ** For each expression, build an index key from the evaluation and
90894  ** store it in the temporary table. If <expr> is a column, then use
90895  ** that columns affinity when building index keys. If <expr> is not
90896  ** a column, use numeric affinity.
90897  */
90898  int i;
90899  ExprList *pList = pExpr->x.pList;
90900  struct ExprList_item *pItem;
90901  int r1, r2, r3;
90902 
90903  if( !affinity ){
90904  affinity = SQLITE_AFF_BLOB;
90905  }
90906  if( pKeyInfo ){
90907  assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
90908  pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
90909  }
90910 
90911  /* Loop through each expression in <exprlist>. */
90912  r1 = sqlite3GetTempReg(pParse);
90913  r2 = sqlite3GetTempReg(pParse);
90914  if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
90915  for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
90916  Expr *pE2 = pItem->pExpr;
90917  int iValToIns;
90918 
90919  /* If the expression is not constant then we will need to
90920  ** disable the test that was generated above that makes sure
90921  ** this code only executes once. Because for a non-constant
90922  ** expression we need to rerun this code each time.
90923  */
90924  if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
90925  sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
90926  jmpIfDynamic = -1;
90927  }
90928 
90929  /* Evaluate the expression and insert it into the temp table */
90930  if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
90931  sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
90932  }else{
90933  r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
90934  if( isRowid ){
90936  sqlite3VdbeCurrentAddr(v)+2);
90937  VdbeCoverage(v);
90938  sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
90939  }else{
90940  sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
90941  sqlite3ExprCacheAffinityChange(pParse, r3, 1);
90942  sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
90943  }
90944  }
90945  }
90946  sqlite3ReleaseTempReg(pParse, r1);
90947  sqlite3ReleaseTempReg(pParse, r2);
90948  }
90949  if( pKeyInfo ){
90950  sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
90951  }
90952  break;
90953  }
90954 
90955  case TK_EXISTS:
90956  case TK_SELECT:
90957  default: {
90958  /* If this has to be a scalar SELECT. Generate code to put the
90959  ** value of this select in a memory cell and record the number
90960  ** of the memory cell in iColumn. If this is an EXISTS, write
90961  ** an integer 0 (not exists) or 1 (exists) into a memory cell
90962  ** and record that memory cell in iColumn.
90963  */
90964  Select *pSel; /* SELECT statement to encode */
90965  SelectDest dest; /* How to deal with SELECt result */
90966 
90967  testcase( pExpr->op==TK_EXISTS );
90968  testcase( pExpr->op==TK_SELECT );
90969  assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
90970 
90971  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
90972  pSel = pExpr->x.pSelect;
90973  sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
90974  if( pExpr->op==TK_SELECT ){
90975  dest.eDest = SRT_Mem;
90976  dest.iSdst = dest.iSDParm;
90977  sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
90978  VdbeComment((v, "Init subquery result"));
90979  }else{
90980  dest.eDest = SRT_Exists;
90981  sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
90982  VdbeComment((v, "Init EXISTS result"));
90983  }
90984  sqlite3ExprDelete(pParse->db, pSel->pLimit);
90985  pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
90986  &sqlite3IntTokens[1]);
90987  pSel->iLimit = 0;
90988  pSel->selFlags &= ~SF_MultiValue;
90989  if( sqlite3Select(pParse, pSel, &dest) ){
90990  return 0;
90991  }
90992  rReg = dest.iSDParm;
90994  break;
90995  }
90996  }
90997 
90998  if( rHasNullFlag ){
90999  sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
91000  }
91001 
91002  if( jmpIfDynamic>=0 ){
91003  sqlite3VdbeJumpHere(v, jmpIfDynamic);
91004  }
91005  sqlite3ExprCachePop(pParse);
91006 
91007  return rReg;
91008 }
91009 #endif /* SQLITE_OMIT_SUBQUERY */
91010 
91011 #ifndef SQLITE_OMIT_SUBQUERY
91012 /*
91013 ** Generate code for an IN expression.
91014 **
91015 ** x IN (SELECT ...)
91016 ** x IN (value, value, ...)
91017 **
91018 ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
91019 ** is an array of zero or more values. The expression is true if the LHS is
91020 ** contained within the RHS. The value of the expression is unknown (NULL)
91021 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
91022 ** RHS contains one or more NULL values.
91023 **
91024 ** This routine generates code that jumps to destIfFalse if the LHS is not
91025 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
91026 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
91027 ** within the RHS then fall through.
91028 */
91029 static void sqlite3ExprCodeIN(
91030  Parse *pParse, /* Parsing and code generating context */
91031  Expr *pExpr, /* The IN expression */
91032  int destIfFalse, /* Jump here if LHS is not contained in the RHS */
91033  int destIfNull /* Jump here if the results are unknown due to NULLs */
91034 ){
91035  int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
91036  char affinity; /* Comparison affinity to use */
91037  int eType; /* Type of the RHS */
91038  int r1; /* Temporary use register */
91039  Vdbe *v; /* Statement under construction */
91040 
91041  /* Compute the RHS. After this step, the table with cursor
91042  ** pExpr->iTable will contains the values that make up the RHS.
91043  */
91044  v = pParse->pVdbe;
91045  assert( v!=0 ); /* OOM detected prior to this routine */
91046  VdbeNoopComment((v, "begin IN expr"));
91047  eType = sqlite3FindInIndex(pParse, pExpr,
91049  destIfFalse==destIfNull ? 0 : &rRhsHasNull);
91050 
91051  /* Figure out the affinity to use to create a key from the results
91052  ** of the expression. affinityStr stores a static string suitable for
91053  ** P4 of OP_MakeRecord.
91054  */
91055  affinity = comparisonAffinity(pExpr);
91056 
91057  /* Code the LHS, the <expr> from "<expr> IN (...)".
91058  */
91059  sqlite3ExprCachePush(pParse);
91060  r1 = sqlite3GetTempReg(pParse);
91061  sqlite3ExprCode(pParse, pExpr->pLeft, r1);
91062 
91063  /* If sqlite3FindInIndex() did not find or create an index that is
91064  ** suitable for evaluating the IN operator, then evaluate using a
91065  ** sequence of comparisons.
91066  */
91067  if( eType==IN_INDEX_NOOP ){
91068  ExprList *pList = pExpr->x.pList;
91069  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
91070  int labelOk = sqlite3VdbeMakeLabel(v);
91071  int r2, regToFree;
91072  int regCkNull = 0;
91073  int ii;
91074  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91075  if( destIfNull!=destIfFalse ){
91076  regCkNull = sqlite3GetTempReg(pParse);
91077  sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
91078  }
91079  for(ii=0; ii<pList->nExpr; ii++){
91080  r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
91081  if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
91082  sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
91083  }
91084  if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
91085  sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
91086  (void*)pColl, P4_COLLSEQ);
91087  VdbeCoverageIf(v, ii<pList->nExpr-1);
91088  VdbeCoverageIf(v, ii==pList->nExpr-1);
91089  sqlite3VdbeChangeP5(v, affinity);
91090  }else{
91091  assert( destIfNull==destIfFalse );
91092  sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
91093  (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
91094  sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
91095  }
91096  sqlite3ReleaseTempReg(pParse, regToFree);
91097  }
91098  if( regCkNull ){
91099  sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
91100  sqlite3VdbeGoto(v, destIfFalse);
91101  }
91102  sqlite3VdbeResolveLabel(v, labelOk);
91103  sqlite3ReleaseTempReg(pParse, regCkNull);
91104  }else{
91105 
91106  /* If the LHS is NULL, then the result is either false or NULL depending
91107  ** on whether the RHS is empty or not, respectively.
91108  */
91109  if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
91110  if( destIfNull==destIfFalse ){
91111  /* Shortcut for the common case where the false and NULL outcomes are
91112  ** the same. */
91113  sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
91114  }else{
91115  int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
91116  sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
91117  VdbeCoverage(v);
91118  sqlite3VdbeGoto(v, destIfNull);
91119  sqlite3VdbeJumpHere(v, addr1);
91120  }
91121  }
91122 
91123  if( eType==IN_INDEX_ROWID ){
91124  /* In this case, the RHS is the ROWID of table b-tree
91125  */
91126  sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
91127  sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
91128  VdbeCoverage(v);
91129  }else{
91130  /* In this case, the RHS is an index b-tree.
91131  */
91132  sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
91133 
91134  /* If the set membership test fails, then the result of the
91135  ** "x IN (...)" expression must be either 0 or NULL. If the set
91136  ** contains no NULL values, then the result is 0. If the set
91137  ** contains one or more NULL values, then the result of the
91138  ** expression is also NULL.
91139  */
91140  assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
91141  if( rRhsHasNull==0 ){
91142  /* This branch runs if it is known at compile time that the RHS
91143  ** cannot contain NULL values. This happens as the result
91144  ** of a "NOT NULL" constraint in the database schema.
91145  **
91146  ** Also run this branch if NULL is equivalent to FALSE
91147  ** for this particular IN operator.
91148  */
91149  sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
91150  VdbeCoverage(v);
91151  }else{
91152  /* In this branch, the RHS of the IN might contain a NULL and
91153  ** the presence of a NULL on the RHS makes a difference in the
91154  ** outcome.
91155  */
91156  int addr1;
91157 
91158  /* First check to see if the LHS is contained in the RHS. If so,
91159  ** then the answer is TRUE the presence of NULLs in the RHS does
91160  ** not matter. If the LHS is not contained in the RHS, then the
91161  ** answer is NULL if the RHS contains NULLs and the answer is
91162  ** FALSE if the RHS is NULL-free.
91163  */
91164  addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
91165  VdbeCoverage(v);
91166  sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
91167  VdbeCoverage(v);
91168  sqlite3VdbeGoto(v, destIfFalse);
91169  sqlite3VdbeJumpHere(v, addr1);
91170  }
91171  }
91172  }
91173  sqlite3ReleaseTempReg(pParse, r1);
91174  sqlite3ExprCachePop(pParse);
91175  VdbeComment((v, "end IN expr"));
91176 }
91177 #endif /* SQLITE_OMIT_SUBQUERY */
91178 
91179 #ifndef SQLITE_OMIT_FLOATING_POINT
91180 /*
91181 ** Generate an instruction that will put the floating point
91182 ** value described by z[0..n-1] into register iMem.
91183 **
91184 ** The z[] string will probably not be zero-terminated. But the
91185 ** z[n] character is guaranteed to be something that does not look
91186 ** like the continuation of the number.
91187 */
91188 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
91189  if( ALWAYS(z!=0) ){
91190  double value;
91191  sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
91192  assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
91193  if( negateFlag ) value = -value;
91194  sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
91195  }
91196 }
91197 #endif
91198 
91199 
91200 /*
91201 ** Generate an instruction that will put the integer describe by
91202 ** text z[0..n-1] into register iMem.
91203 **
91204 ** Expr.u.zToken is always UTF8 and zero-terminated.
91205 */
91206 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
91207  Vdbe *v = pParse->pVdbe;
91208  if( pExpr->flags & EP_IntValue ){
91209  int i = pExpr->u.iValue;
91210  assert( i>=0 );
91211  if( negFlag ) i = -i;
91212  sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
91213  }else{
91214  int c;
91215  i64 value;
91216  const char *z = pExpr->u.zToken;
91217  assert( z!=0 );
91218  c = sqlite3DecOrHexToI64(z, &value);
91219  if( c==0 || (c==2 && negFlag) ){
91220  if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
91221  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
91222  }else{
91223 #ifdef SQLITE_OMIT_FLOATING_POINT
91224  sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
91225 #else
91226 #ifndef SQLITE_OMIT_HEX_INTEGER
91227  if( sqlite3_strnicmp(z,"0x",2)==0 ){
91228  sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
91229  }else
91230 #endif
91231  {
91232  codeReal(v, z, negFlag, iMem);
91233  }
91234 #endif
91235  }
91236  }
91237 }
91238 
91239 #if defined(SQLITE_DEBUG)
91240 /*
91241 ** Verify the consistency of the column cache
91242 */
91243 static int cacheIsValid(Parse *pParse){
91244  int i, n;
91245  for(i=n=0; i<SQLITE_N_COLCACHE; i++){
91246  if( pParse->aColCache[i].iReg>0 ) n++;
91247  }
91248  return n==pParse->nColCache;
91249 }
91250 #endif
91251 
91252 /*
91253 ** Clear a cache entry.
91254 */
91255 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
91256  if( p->tempReg ){
91257  if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
91258  pParse->aTempReg[pParse->nTempReg++] = p->iReg;
91259  }
91260  p->tempReg = 0;
91261  }
91262  p->iReg = 0;
91263  pParse->nColCache--;
91264  assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91265 }
91266 
91267 
91268 /*
91269 ** Record in the column cache that a particular column from a
91270 ** particular table is stored in a particular register.
91271 */
91272 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
91273  int i;
91274  int minLru;
91275  int idxLru;
91276  struct yColCache *p;
91277 
91278  /* Unless an error has occurred, register numbers are always positive. */
91279  assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
91280  assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
91281 
91282  /* The SQLITE_ColumnCache flag disables the column cache. This is used
91283  ** for testing only - to verify that SQLite always gets the same answer
91284  ** with and without the column cache.
91285  */
91286  if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
91287 
91288  /* First replace any existing entry.
91289  **
91290  ** Actually, the way the column cache is currently used, we are guaranteed
91291  ** that the object will never already be in cache. Verify this guarantee.
91292  */
91293 #ifndef NDEBUG
91294  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91295  assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
91296  }
91297 #endif
91298 
91299  /* Find an empty slot and replace it */
91300  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91301  if( p->iReg==0 ){
91302  p->iLevel = pParse->iCacheLevel;
91303  p->iTable = iTab;
91304  p->iColumn = iCol;
91305  p->iReg = iReg;
91306  p->tempReg = 0;
91307  p->lru = pParse->iCacheCnt++;
91308  pParse->nColCache++;
91309  assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
91310  return;
91311  }
91312  }
91313 
91314  /* Replace the last recently used */
91315  minLru = 0x7fffffff;
91316  idxLru = -1;
91317  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91318  if( p->lru<minLru ){
91319  idxLru = i;
91320  minLru = p->lru;
91321  }
91322  }
91323  if( ALWAYS(idxLru>=0) ){
91324  p = &pParse->aColCache[idxLru];
91325  p->iLevel = pParse->iCacheLevel;
91326  p->iTable = iTab;
91327  p->iColumn = iCol;
91328  p->iReg = iReg;
91329  p->tempReg = 0;
91330  p->lru = pParse->iCacheCnt++;
91331  assert( cacheIsValid(pParse) );
91332  return;
91333  }
91334 }
91335 
91336 /*
91337 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
91338 ** Purge the range of registers from the column cache.
91339 */
91340 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
91341  struct yColCache *p;
91342  if( iReg<=0 || pParse->nColCache==0 ) return;
91343  p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
91344  while(1){
91345  if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
91346  if( p==pParse->aColCache ) break;
91347  p--;
91348  }
91349 }
91350 
91351 /*
91352 ** Remember the current column cache context. Any new entries added
91353 ** added to the column cache after this call are removed when the
91354 ** corresponding pop occurs.
91355 */
91357  pParse->iCacheLevel++;
91358 #ifdef SQLITE_DEBUG
91359  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91360  printf("PUSH to %d\n", pParse->iCacheLevel);
91361  }
91362 #endif
91363 }
91364 
91365 /*
91366 ** Remove from the column cache any entries that were added since the
91367 ** the previous sqlite3ExprCachePush operation. In other words, restore
91368 ** the cache to the state it was in prior the most recent Push.
91369 */
91371  int i;
91372  struct yColCache *p;
91373  assert( pParse->iCacheLevel>=1 );
91374  pParse->iCacheLevel--;
91375 #ifdef SQLITE_DEBUG
91376  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91377  printf("POP to %d\n", pParse->iCacheLevel);
91378  }
91379 #endif
91380  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91381  if( p->iReg && p->iLevel>pParse->iCacheLevel ){
91382  cacheEntryClear(pParse, p);
91383  }
91384  }
91385 }
91386 
91387 /*
91388 ** When a cached column is reused, make sure that its register is
91389 ** no longer available as a temp register. ticket #3879: that same
91390 ** register might be in the cache in multiple places, so be sure to
91391 ** get them all.
91392 */
91393 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
91394  int i;
91395  struct yColCache *p;
91396  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91397  if( p->iReg==iReg ){
91398  p->tempReg = 0;
91399  }
91400  }
91401 }
91402 
91403 /* Generate code that will load into register regOut a value that is
91404 ** appropriate for the iIdxCol-th column of index pIdx.
91405 */
91407  Parse *pParse, /* The parsing context */
91408  Index *pIdx, /* The index whose column is to be loaded */
91409  int iTabCur, /* Cursor pointing to a table row */
91410  int iIdxCol, /* The column of the index to be loaded */
91411  int regOut /* Store the index column value in this register */
91412 ){
91413  i16 iTabCol = pIdx->aiColumn[iIdxCol];
91414  if( iTabCol==XN_EXPR ){
91415  assert( pIdx->aColExpr );
91416  assert( pIdx->aColExpr->nExpr>iIdxCol );
91417  pParse->iSelfTab = iTabCur;
91418  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
91419  }else{
91420  sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
91421  iTabCol, regOut);
91422  }
91423 }
91424 
91425 /*
91426 ** Generate code to extract the value of the iCol-th column of a table.
91427 */
91429  Vdbe *v, /* The VDBE under construction */
91430  Table *pTab, /* The table containing the value */
91431  int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
91432  int iCol, /* Index of the column to extract */
91433  int regOut /* Extract the value into this register */
91434 ){
91435  if( iCol<0 || iCol==pTab->iPKey ){
91436  sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
91437  }else{
91438  int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
91439  int x = iCol;
91440  if( !HasRowid(pTab) ){
91442  }
91443  sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
91444  }
91445  if( iCol>=0 ){
91446  sqlite3ColumnDefault(v, pTab, iCol, regOut);
91447  }
91448 }
91449 
91450 /*
91451 ** Generate code that will extract the iColumn-th column from
91452 ** table pTab and store the column value in a register.
91453 **
91454 ** An effort is made to store the column value in register iReg. This
91455 ** is not garanteeed for GetColumn() - the result can be stored in
91456 ** any register. But the result is guaranteed to land in register iReg
91457 ** for GetColumnToReg().
91458 **
91459 ** There must be an open cursor to pTab in iTable when this routine
91460 ** is called. If iColumn<0 then code is generated that extracts the rowid.
91461 */
91463  Parse *pParse, /* Parsing and code generating context */
91464  Table *pTab, /* Description of the table we are reading from */
91465  int iColumn, /* Index of the table column */
91466  int iTable, /* The cursor pointing to the table */
91467  int iReg, /* Store results here */
91468  u8 p5 /* P5 value for OP_Column + FLAGS */
91469 ){
91470  Vdbe *v = pParse->pVdbe;
91471  int i;
91472  struct yColCache *p;
91473 
91474  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91475  if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
91476  p->lru = pParse->iCacheCnt++;
91477  sqlite3ExprCachePinRegister(pParse, p->iReg);
91478  return p->iReg;
91479  }
91480  }
91481  assert( v!=0 );
91482  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
91483  if( p5 ){
91484  sqlite3VdbeChangeP5(v, p5);
91485  }else{
91486  sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
91487  }
91488  return iReg;
91489 }
91491  Parse *pParse, /* Parsing and code generating context */
91492  Table *pTab, /* Description of the table we are reading from */
91493  int iColumn, /* Index of the table column */
91494  int iTable, /* The cursor pointing to the table */
91495  int iReg /* Store results here */
91496 ){
91497  int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
91498  if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
91499 }
91500 
91501 
91502 /*
91503 ** Clear all column cache entries.
91504 */
91506  int i;
91507  struct yColCache *p;
91508 
91509 #if SQLITE_DEBUG
91510  if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
91511  printf("CLEAR\n");
91512  }
91513 #endif
91514  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91515  if( p->iReg ){
91516  cacheEntryClear(pParse, p);
91517  }
91518  }
91519 }
91520 
91521 /*
91522 ** Record the fact that an affinity change has occurred on iCount
91523 ** registers starting with iStart.
91524 */
91525 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
91526  sqlite3ExprCacheRemove(pParse, iStart, iCount);
91527 }
91528 
91529 /*
91530 ** Generate code to move content from registers iFrom...iFrom+nReg-1
91531 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
91532 */
91533 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
91534  assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
91535  sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
91536  sqlite3ExprCacheRemove(pParse, iFrom, nReg);
91537 }
91538 
91539 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
91540 /*
91541 ** Return true if any register in the range iFrom..iTo (inclusive)
91542 ** is used as part of the column cache.
91543 **
91544 ** This routine is used within assert() and testcase() macros only
91545 ** and does not appear in a normal build.
91546 */
91547 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
91548  int i;
91549  struct yColCache *p;
91550  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
91551  int r = p->iReg;
91552  if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
91553  }
91554  return 0;
91555 }
91556 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
91557 
91558 
91559 /*
91560 ** Convert an expression node to a TK_REGISTER
91561 */
91562 static void exprToRegister(Expr *p, int iReg){
91563  p->op2 = p->op;
91564  p->op = TK_REGISTER;
91565  p->iTable = iReg;
91567 }
91568 
91569 /*
91570 ** Generate code into the current Vdbe to evaluate the given
91571 ** expression. Attempt to store the results in register "target".
91572 ** Return the register where results are stored.
91573 **
91574 ** With this routine, there is no guarantee that results will
91575 ** be stored in target. The result might be stored in some other
91576 ** register if it is convenient to do so. The calling function
91577 ** must check the return code and move the results to the desired
91578 ** register.
91579 */
91581  Vdbe *v = pParse->pVdbe; /* The VM under construction */
91582  int op; /* The opcode being coded */
91583  int inReg = target; /* Results stored in register inReg */
91584  int regFree1 = 0; /* If non-zero free this temporary register */
91585  int regFree2 = 0; /* If non-zero free this temporary register */
91586  int r1, r2, r3, r4; /* Various register numbers */
91587  sqlite3 *db = pParse->db; /* The database connection */
91588  Expr tempX; /* Temporary expression node */
91589 
91590  assert( target>0 && target<=pParse->nMem );
91591  if( v==0 ){
91592  assert( pParse->db->mallocFailed );
91593  return 0;
91594  }
91595 
91596  if( pExpr==0 ){
91597  op = TK_NULL;
91598  }else{
91599  op = pExpr->op;
91600  }
91601  switch( op ){
91602  case TK_AGG_COLUMN: {
91603  AggInfo *pAggInfo = pExpr->pAggInfo;
91604  struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
91605  if( !pAggInfo->directMode ){
91606  assert( pCol->iMem>0 );
91607  inReg = pCol->iMem;
91608  break;
91609  }else if( pAggInfo->useSortingIdx ){
91611  pCol->iSorterColumn, target);
91612  break;
91613  }
91614  /* Otherwise, fall thru into the TK_COLUMN case */
91615  }
91616  case TK_COLUMN: {
91617  int iTab = pExpr->iTable;
91618  if( iTab<0 ){
91619  if( pParse->ckBase>0 ){
91620  /* Generating CHECK constraints or inserting into partial index */
91621  inReg = pExpr->iColumn + pParse->ckBase;
91622  break;
91623  }else{
91624  /* Coding an expression that is part of an index where column names
91625  ** in the index refer to the table to which the index belongs */
91626  iTab = pParse->iSelfTab;
91627  }
91628  }
91629  inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
91630  pExpr->iColumn, iTab, target,
91631  pExpr->op2);
91632  break;
91633  }
91634  case TK_INTEGER: {
91635  codeInteger(pParse, pExpr, 0, target);
91636  break;
91637  }
91638 #ifndef SQLITE_OMIT_FLOATING_POINT
91639  case TK_FLOAT: {
91640  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91641  codeReal(v, pExpr->u.zToken, 0, target);
91642  break;
91643  }
91644 #endif
91645  case TK_STRING: {
91646  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91647  sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
91648  break;
91649  }
91650  case TK_NULL: {
91651  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
91652  break;
91653  }
91654 #ifndef SQLITE_OMIT_BLOB_LITERAL
91655  case TK_BLOB: {
91656  int n;
91657  const char *z;
91658  char *zBlob;
91659  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91660  assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
91661  assert( pExpr->u.zToken[1]=='\'' );
91662  z = &pExpr->u.zToken[2];
91663  n = sqlite3Strlen30(z) - 1;
91664  assert( z[n]=='\'' );
91665  zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
91666  sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
91667  break;
91668  }
91669 #endif
91670  case TK_VARIABLE: {
91671  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91672  assert( pExpr->u.zToken!=0 );
91673  assert( pExpr->u.zToken[0]!=0 );
91674  sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
91675  if( pExpr->u.zToken[1]!=0 ){
91676  assert( pExpr->u.zToken[0]=='?'
91677  || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
91678  sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
91679  }
91680  break;
91681  }
91682  case TK_REGISTER: {
91683  inReg = pExpr->iTable;
91684  break;
91685  }
91686 #ifndef SQLITE_OMIT_CAST
91687  case TK_CAST: {
91688  /* Expressions of the form: CAST(pLeft AS token) */
91689  inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
91690  if( inReg!=target ){
91691  sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
91692  inReg = target;
91693  }
91694  sqlite3VdbeAddOp2(v, OP_Cast, target,
91695  sqlite3AffinityType(pExpr->u.zToken, 0));
91696  testcase( usedAsColumnCache(pParse, inReg, inReg) );
91697  sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
91698  break;
91699  }
91700 #endif /* SQLITE_OMIT_CAST */
91701  case TK_LT:
91702  case TK_LE:
91703  case TK_GT:
91704  case TK_GE:
91705  case TK_NE:
91706  case TK_EQ: {
91707  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
91708  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
91709  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
91710  r1, r2, inReg, SQLITE_STOREP2);
91717  testcase( regFree1==0 );
91718  testcase( regFree2==0 );
91719  break;
91720  }
91721  case TK_IS:
91722  case TK_ISNOT: {
91723  testcase( op==TK_IS );
91724  testcase( op==TK_ISNOT );
91725  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
91726  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
91727  op = (op==TK_IS) ? TK_EQ : TK_NE;
91728  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
91729  r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
91730  VdbeCoverageIf(v, op==TK_EQ);
91731  VdbeCoverageIf(v, op==TK_NE);
91732  testcase( regFree1==0 );
91733  testcase( regFree2==0 );
91734  break;
91735  }
91736  case TK_AND:
91737  case TK_OR:
91738  case TK_PLUS:
91739  case TK_STAR:
91740  case TK_MINUS:
91741  case TK_REM:
91742  case TK_BITAND:
91743  case TK_BITOR:
91744  case TK_SLASH:
91745  case TK_LSHIFT:
91746  case TK_RSHIFT:
91747  case TK_CONCAT: {
91748  assert( TK_AND==OP_And ); testcase( op==TK_AND );
91749  assert( TK_OR==OP_Or ); testcase( op==TK_OR );
91750  assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
91759  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
91760  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
91761  sqlite3VdbeAddOp3(v, op, r2, r1, target);
91762  testcase( regFree1==0 );
91763  testcase( regFree2==0 );
91764  break;
91765  }
91766  case TK_UMINUS: {
91767  Expr *pLeft = pExpr->pLeft;
91768  assert( pLeft );
91769  if( pLeft->op==TK_INTEGER ){
91770  codeInteger(pParse, pLeft, 1, target);
91771 #ifndef SQLITE_OMIT_FLOATING_POINT
91772  }else if( pLeft->op==TK_FLOAT ){
91773  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91774  codeReal(v, pLeft->u.zToken, 1, target);
91775 #endif
91776  }else{
91777  tempX.op = TK_INTEGER;
91778  tempX.flags = EP_IntValue|EP_TokenOnly;
91779  tempX.u.iValue = 0;
91780  r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
91781  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
91782  sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
91783  testcase( regFree2==0 );
91784  }
91785  inReg = target;
91786  break;
91787  }
91788  case TK_BITNOT:
91789  case TK_NOT: {
91791  assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
91792  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
91793  testcase( regFree1==0 );
91794  inReg = target;
91795  sqlite3VdbeAddOp2(v, op, r1, inReg);
91796  break;
91797  }
91798  case TK_ISNULL:
91799  case TK_NOTNULL: {
91800  int addr;
91803  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
91804  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
91805  testcase( regFree1==0 );
91806  addr = sqlite3VdbeAddOp1(v, op, r1);
91807  VdbeCoverageIf(v, op==TK_ISNULL);
91808  VdbeCoverageIf(v, op==TK_NOTNULL);
91809  sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
91810  sqlite3VdbeJumpHere(v, addr);
91811  break;
91812  }
91813  case TK_AGG_FUNCTION: {
91814  AggInfo *pInfo = pExpr->pAggInfo;
91815  if( pInfo==0 ){
91816  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91817  sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
91818  }else{
91819  inReg = pInfo->aFunc[pExpr->iAgg].iMem;
91820  }
91821  break;
91822  }
91823  case TK_FUNCTION: {
91824  ExprList *pFarg; /* List of function arguments */
91825  int nFarg; /* Number of function arguments */
91826  FuncDef *pDef; /* The function definition object */
91827  const char *zId; /* The function name */
91828  u32 constMask = 0; /* Mask of function arguments that are constant */
91829  int i; /* Loop counter */
91830  u8 enc = ENC(db); /* The text encoding used by this database */
91831  CollSeq *pColl = 0; /* A collating sequence */
91832 
91833  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
91834  if( ExprHasProperty(pExpr, EP_TokenOnly) ){
91835  pFarg = 0;
91836  }else{
91837  pFarg = pExpr->x.pList;
91838  }
91839  nFarg = pFarg ? pFarg->nExpr : 0;
91840  assert( !ExprHasProperty(pExpr, EP_IntValue) );
91841  zId = pExpr->u.zToken;
91842  pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
91843  if( pDef==0 || pDef->xFinalize!=0 ){
91844  sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
91845  break;
91846  }
91847 
91848  /* Attempt a direct implementation of the built-in COALESCE() and
91849  ** IFNULL() functions. This avoids unnecessary evaluation of
91850  ** arguments past the first non-NULL argument.
91851  */
91852  if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
91853  int endCoalesce = sqlite3VdbeMakeLabel(v);
91854  assert( nFarg>=2 );
91855  sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
91856  for(i=1; i<nFarg; i++){
91857  sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
91858  VdbeCoverage(v);
91859  sqlite3ExprCacheRemove(pParse, target, 1);
91860  sqlite3ExprCachePush(pParse);
91861  sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
91862  sqlite3ExprCachePop(pParse);
91863  }
91864  sqlite3VdbeResolveLabel(v, endCoalesce);
91865  break;
91866  }
91867 
91868  /* The UNLIKELY() function is a no-op. The result is the value
91869  ** of the first argument.
91870  */
91871  if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
91872  assert( nFarg>=1 );
91873  inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
91874  break;
91875  }
91876 
91877  for(i=0; i<nFarg; i++){
91878  if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
91879  testcase( i==31 );
91880  constMask |= MASKBIT32(i);
91881  }
91882  if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
91883  pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
91884  }
91885  }
91886  if( pFarg ){
91887  if( constMask ){
91888  r1 = pParse->nMem+1;
91889  pParse->nMem += nFarg;
91890  }else{
91891  r1 = sqlite3GetTempRange(pParse, nFarg);
91892  }
91893 
91894  /* For length() and typeof() functions with a column argument,
91895  ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
91896  ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
91897  ** loading.
91898  */
91899  if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
91900  u8 exprOp;
91901  assert( nFarg==1 );
91902  assert( pFarg->a[0].pExpr!=0 );
91903  exprOp = pFarg->a[0].pExpr->op;
91904  if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
91907  testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
91908  pFarg->a[0].pExpr->op2 =
91910  }
91911  }
91912 
91913  sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
91914  sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
91916  sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
91917  }else{
91918  r1 = 0;
91919  }
91920 #ifndef SQLITE_OMIT_VIRTUALTABLE
91921  /* Possibly overload the function if the first argument is
91922  ** a virtual table column.
91923  **
91924  ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
91925  ** second argument, not the first, as the argument to test to
91926  ** see if it is a column in a virtual table. This is done because
91927  ** the left operand of infix functions (the operand we want to
91928  ** control overloading) ends up as the second argument to the
91929  ** function. The expression "A glob B" is equivalent to
91930  ** "glob(B,A). We want to use the A in "A glob B" to test
91931  ** for function overloading. But we use the B term in "glob(B,A)".
91932  */
91933  if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
91934  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
91935  }else if( nFarg>0 ){
91936  pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
91937  }
91938 #endif
91939  if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
91940  if( !pColl ) pColl = db->pDfltColl;
91941  sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
91942  }
91943  sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
91944  (char*)pDef, P4_FUNCDEF);
91945  sqlite3VdbeChangeP5(v, (u8)nFarg);
91946  if( nFarg && constMask==0 ){
91947  sqlite3ReleaseTempRange(pParse, r1, nFarg);
91948  }
91949  break;
91950  }
91951 #ifndef SQLITE_OMIT_SUBQUERY
91952  case TK_EXISTS:
91953  case TK_SELECT: {
91954  testcase( op==TK_EXISTS );
91955  testcase( op==TK_SELECT );
91956  inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
91957  break;
91958  }
91959  case TK_IN: {
91960  int destIfFalse = sqlite3VdbeMakeLabel(v);
91961  int destIfNull = sqlite3VdbeMakeLabel(v);
91962  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
91963  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
91964  sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
91965  sqlite3VdbeResolveLabel(v, destIfFalse);
91966  sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
91967  sqlite3VdbeResolveLabel(v, destIfNull);
91968  break;
91969  }
91970 #endif /* SQLITE_OMIT_SUBQUERY */
91971 
91972 
91973  /*
91974  ** x BETWEEN y AND z
91975  **
91976  ** This is equivalent to
91977  **
91978  ** x>=y AND x<=z
91979  **
91980  ** X is stored in pExpr->pLeft.
91981  ** Y is stored in pExpr->pList->a[0].pExpr.
91982  ** Z is stored in pExpr->pList->a[1].pExpr.
91983  */
91984  case TK_BETWEEN: {
91985  Expr *pLeft = pExpr->pLeft;
91986  struct ExprList_item *pLItem = pExpr->x.pList->a;
91987  Expr *pRight = pLItem->pExpr;
91988 
91989  r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
91990  r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
91991  testcase( regFree1==0 );
91992  testcase( regFree2==0 );
91993  r3 = sqlite3GetTempReg(pParse);
91994  r4 = sqlite3GetTempReg(pParse);
91995  codeCompare(pParse, pLeft, pRight, OP_Ge,
91996  r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
91997  pLItem++;
91998  pRight = pLItem->pExpr;
91999  sqlite3ReleaseTempReg(pParse, regFree2);
92000  r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
92001  testcase( regFree2==0 );
92002  codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
92003  VdbeCoverage(v);
92004  sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
92005  sqlite3ReleaseTempReg(pParse, r3);
92006  sqlite3ReleaseTempReg(pParse, r4);
92007  break;
92008  }
92009  case TK_SPAN:
92010  case TK_COLLATE:
92011  case TK_UPLUS: {
92012  inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
92013  break;
92014  }
92015 
92016  case TK_TRIGGER: {
92017  /* If the opcode is TK_TRIGGER, then the expression is a reference
92018  ** to a column in the new.* or old.* pseudo-tables available to
92019  ** trigger programs. In this case Expr.iTable is set to 1 for the
92020  ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
92021  ** is set to the column of the pseudo-table to read, or to -1 to
92022  ** read the rowid field.
92023  **
92024  ** The expression is implemented using an OP_Param opcode. The p1
92025  ** parameter is set to 0 for an old.rowid reference, or to (i+1)
92026  ** to reference another column of the old.* pseudo-table, where
92027  ** i is the index of the column. For a new.rowid reference, p1 is
92028  ** set to (n+1), where n is the number of columns in each pseudo-table.
92029  ** For a reference to any other column in the new.* pseudo-table, p1
92030  ** is set to (n+2+i), where n and i are as defined previously. For
92031  ** example, if the table on which triggers are being fired is
92032  ** declared as:
92033  **
92034  ** CREATE TABLE t1(a, b);
92035  **
92036  ** Then p1 is interpreted as follows:
92037  **
92038  ** p1==0 -> old.rowid p1==3 -> new.rowid
92039  ** p1==1 -> old.a p1==4 -> new.a
92040  ** p1==2 -> old.b p1==5 -> new.b
92041  */
92042  Table *pTab = pExpr->pTab;
92043  int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
92044 
92045  assert( pExpr->iTable==0 || pExpr->iTable==1 );
92046  assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
92047  assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
92048  assert( p1>=0 && p1<(pTab->nCol*2+2) );
92049 
92050  sqlite3VdbeAddOp2(v, OP_Param, p1, target);
92051  VdbeComment((v, "%s.%s -> $%d",
92052  (pExpr->iTable ? "new" : "old"),
92053  (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
92054  target
92055  ));
92056 
92057 #ifndef SQLITE_OMIT_FLOATING_POINT
92058  /* If the column has REAL affinity, it may currently be stored as an
92059  ** integer. Use OP_RealAffinity to make sure it is really real.
92060  **
92061  ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
92062  ** floating point when extracting it from the record. */
92063  if( pExpr->iColumn>=0
92064  && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
92065  ){
92066  sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
92067  }
92068 #endif
92069  break;
92070  }
92071 
92072 
92073  /*
92074  ** Form A:
92075  ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92076  **
92077  ** Form B:
92078  ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
92079  **
92080  ** Form A is can be transformed into the equivalent form B as follows:
92081  ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
92082  ** WHEN x=eN THEN rN ELSE y END
92083  **
92084  ** X (if it exists) is in pExpr->pLeft.
92085  ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
92086  ** odd. The Y is also optional. If the number of elements in x.pList
92087  ** is even, then Y is omitted and the "otherwise" result is NULL.
92088  ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
92089  **
92090  ** The result of the expression is the Ri for the first matching Ei,
92091  ** or if there is no matching Ei, the ELSE term Y, or if there is
92092  ** no ELSE term, NULL.
92093  */
92094  default: assert( op==TK_CASE ); {
92095  int endLabel; /* GOTO label for end of CASE stmt */
92096  int nextCase; /* GOTO label for next WHEN clause */
92097  int nExpr; /* 2x number of WHEN terms */
92098  int i; /* Loop counter */
92099  ExprList *pEList; /* List of WHEN terms */
92100  struct ExprList_item *aListelem; /* Array of WHEN terms */
92101  Expr opCompare; /* The X==Ei expression */
92102  Expr *pX; /* The X expression */
92103  Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
92104  VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
92105 
92106  assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
92107  assert(pExpr->x.pList->nExpr > 0);
92108  pEList = pExpr->x.pList;
92109  aListelem = pEList->a;
92110  nExpr = pEList->nExpr;
92111  endLabel = sqlite3VdbeMakeLabel(v);
92112  if( (pX = pExpr->pLeft)!=0 ){
92113  tempX = *pX;
92114  testcase( pX->op==TK_COLUMN );
92115  exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
92116  testcase( regFree1==0 );
92117  opCompare.op = TK_EQ;
92118  opCompare.pLeft = &tempX;
92119  pTest = &opCompare;
92120  /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
92121  ** The value in regFree1 might get SCopy-ed into the file result.
92122  ** So make sure that the regFree1 register is not reused for other
92123  ** purposes and possibly overwritten. */
92124  regFree1 = 0;
92125  }
92126  for(i=0; i<nExpr-1; i=i+2){
92127  sqlite3ExprCachePush(pParse);
92128  if( pX ){
92129  assert( pTest!=0 );
92130  opCompare.pRight = aListelem[i].pExpr;
92131  }else{
92132  pTest = aListelem[i].pExpr;
92133  }
92134  nextCase = sqlite3VdbeMakeLabel(v);
92135  testcase( pTest->op==TK_COLUMN );
92136  sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
92137  testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
92138  sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
92139  sqlite3VdbeGoto(v, endLabel);
92140  sqlite3ExprCachePop(pParse);
92141  sqlite3VdbeResolveLabel(v, nextCase);
92142  }
92143  if( (nExpr&1)!=0 ){
92144  sqlite3ExprCachePush(pParse);
92145  sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
92146  sqlite3ExprCachePop(pParse);
92147  }else{
92148  sqlite3VdbeAddOp2(v, OP_Null, 0, target);
92149  }
92150  assert( db->mallocFailed || pParse->nErr>0
92151  || pParse->iCacheLevel==iCacheLevel );
92152  sqlite3VdbeResolveLabel(v, endLabel);
92153  break;
92154  }
92155 #ifndef SQLITE_OMIT_TRIGGER
92156  case TK_RAISE: {
92157  assert( pExpr->affinity==OE_Rollback
92158  || pExpr->affinity==OE_Abort
92159  || pExpr->affinity==OE_Fail
92160  || pExpr->affinity==OE_Ignore
92161  );
92162  if( !pParse->pTriggerTab ){
92163  sqlite3ErrorMsg(pParse,
92164  "RAISE() may only be used within a trigger-program");
92165  return 0;
92166  }
92167  if( pExpr->affinity==OE_Abort ){
92168  sqlite3MayAbort(pParse);
92169  }
92170  assert( !ExprHasProperty(pExpr, EP_IntValue) );
92171  if( pExpr->affinity==OE_Ignore ){
92173  v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
92174  VdbeCoverage(v);
92175  }else{
92177  pExpr->affinity, pExpr->u.zToken, 0, 0);
92178  }
92179 
92180  break;
92181  }
92182 #endif
92183  }
92184  sqlite3ReleaseTempReg(pParse, regFree1);
92185  sqlite3ReleaseTempReg(pParse, regFree2);
92186  return inReg;
92187 }
92188 
92189 /*
92190 ** Factor out the code of the given expression to initialization time.
92191 */
92193  Parse *pParse, /* Parsing context */
92194  Expr *pExpr, /* The expression to code when the VDBE initializes */
92195  int regDest, /* Store the value in this register */
92196  u8 reusable /* True if this expression is reusable */
92197 ){
92198  ExprList *p;
92199  assert( ConstFactorOk(pParse) );
92200  p = pParse->pConstExpr;
92201  pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
92202  p = sqlite3ExprListAppend(pParse, p, pExpr);
92203  if( p ){
92204  struct ExprList_item *pItem = &p->a[p->nExpr-1];
92205  pItem->u.iConstExprReg = regDest;
92206  pItem->reusable = reusable;
92207  }
92208  pParse->pConstExpr = p;
92209 }
92210 
92211 /*
92212 ** Generate code to evaluate an expression and store the results
92213 ** into a register. Return the register number where the results
92214 ** are stored.
92215 **
92216 ** If the register is a temporary register that can be deallocated,
92217 ** then write its number into *pReg. If the result register is not
92218 ** a temporary, then set *pReg to zero.
92219 **
92220 ** If pExpr is a constant, then this routine might generate this
92221 ** code to fill the register in the initialization section of the
92222 ** VDBE program, in order to factor it out of the evaluation loop.
92223 */
92224 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
92225  int r2;
92226  pExpr = sqlite3ExprSkipCollate(pExpr);
92227  if( ConstFactorOk(pParse)
92228  && pExpr->op!=TK_REGISTER
92230  ){
92231  ExprList *p = pParse->pConstExpr;
92232  int i;
92233  *pReg = 0;
92234  if( p ){
92235  struct ExprList_item *pItem;
92236  for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
92237  if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
92238  return pItem->u.iConstExprReg;
92239  }
92240  }
92241  }
92242  r2 = ++pParse->nMem;
92243  sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
92244  }else{
92245  int r1 = sqlite3GetTempReg(pParse);
92246  r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
92247  if( r2==r1 ){
92248  *pReg = r1;
92249  }else{
92250  sqlite3ReleaseTempReg(pParse, r1);
92251  *pReg = 0;
92252  }
92253  }
92254  return r2;
92255 }
92256 
92257 /*
92258 ** Generate code that will evaluate expression pExpr and store the
92259 ** results in register target. The results are guaranteed to appear
92260 ** in register target.
92261 */
92262 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
92263  int inReg;
92264 
92265  assert( target>0 && target<=pParse->nMem );
92266  if( pExpr && pExpr->op==TK_REGISTER ){
92267  sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
92268  }else{
92269  inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
92270  assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
92271  if( inReg!=target && pParse->pVdbe ){
92272  sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
92273  }
92274  }
92275 }
92276 
92277 /*
92278 ** Make a transient copy of expression pExpr and then code it using
92279 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
92280 ** except that the input expression is guaranteed to be unchanged.
92281 */
92283  sqlite3 *db = pParse->db;
92284  pExpr = sqlite3ExprDup(db, pExpr, 0);
92285  if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
92286  sqlite3ExprDelete(db, pExpr);
92287 }
92288 
92289 /*
92290 ** Generate code that will evaluate expression pExpr and store the
92291 ** results in register target. The results are guaranteed to appear
92292 ** in register target. If the expression is constant, then this routine
92293 ** might choose to code the expression at initialization time.
92294 */
92296  if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
92297  sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
92298  }else{
92299  sqlite3ExprCode(pParse, pExpr, target);
92300  }
92301 }
92302 
92303 /*
92304 ** Generate code that evaluates the given expression and puts the result
92305 ** in register target.
92306 **
92307 ** Also make a copy of the expression results into another "cache" register
92308 ** and modify the expression so that the next time it is evaluated,
92309 ** the result is a copy of the cache register.
92310 **
92311 ** This routine is used for expressions that are used multiple
92312 ** times. They are evaluated once and the results of the expression
92313 ** are reused.
92314 */
92316  Vdbe *v = pParse->pVdbe;
92317  int iMem;
92318 
92319  assert( target>0 );
92320  assert( pExpr->op!=TK_REGISTER );
92321  sqlite3ExprCode(pParse, pExpr, target);
92322  iMem = ++pParse->nMem;
92323  sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
92324  exprToRegister(pExpr, iMem);
92325 }
92326 
92327 /*
92328 ** Generate code that pushes the value of every element of the given
92329 ** expression list into a sequence of registers beginning at target.
92330 **
92331 ** Return the number of elements evaluated.
92332 **
92333 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
92334 ** filled using OP_SCopy. OP_Copy must be used instead.
92335 **
92336 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
92337 ** factored out into initialization code.
92338 **
92339 ** The SQLITE_ECEL_REF flag means that expressions in the list with
92340 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
92341 ** in registers at srcReg, and so the value can be copied from there.
92342 */
92344  Parse *pParse, /* Parsing context */
92345  ExprList *pList, /* The expression list to be coded */
92346  int target, /* Where to write results */
92347  int srcReg, /* Source registers if SQLITE_ECEL_REF */
92348  u8 flags /* SQLITE_ECEL_* flags */
92349 ){
92350  struct ExprList_item *pItem;
92351  int i, j, n;
92352  u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
92353  Vdbe *v = pParse->pVdbe;
92354  assert( pList!=0 );
92355  assert( target>0 );
92356  assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
92357  n = pList->nExpr;
92358  if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
92359  for(pItem=pList->a, i=0; i<n; i++, pItem++){
92360  Expr *pExpr = pItem->pExpr;
92361  if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
92362  sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
92363  }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
92364  sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
92365  }else{
92366  int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
92367  if( inReg!=target+i ){
92368  VdbeOp *pOp;
92369  if( copyOp==OP_Copy
92370  && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
92371  && pOp->p1+pOp->p3+1==inReg
92372  && pOp->p2+pOp->p3+1==target+i
92373  ){
92374  pOp->p3++;
92375  }else{
92376  sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
92377  }
92378  }
92379  }
92380  }
92381  return n;
92382 }
92383 
92384 /*
92385 ** Generate code for a BETWEEN operator.
92386 **
92387 ** x BETWEEN y AND z
92388 **
92389 ** The above is equivalent to
92390 **
92391 ** x>=y AND x<=z
92392 **
92393 ** Code it as such, taking care to do the common subexpression
92394 ** elimination of x.
92395 */
92396 static void exprCodeBetween(
92397  Parse *pParse, /* Parsing and code generating context */
92398  Expr *pExpr, /* The BETWEEN expression */
92399  int dest, /* Jump here if the jump is taken */
92400  int jumpIfTrue, /* Take the jump if the BETWEEN is true */
92401  int jumpIfNull /* Take the jump if the BETWEEN is NULL */
92402 ){
92403  Expr exprAnd; /* The AND operator in x>=y AND x<=z */
92404  Expr compLeft; /* The x>=y term */
92405  Expr compRight; /* The x<=z term */
92406  Expr exprX; /* The x subexpression */
92407  int regFree1 = 0; /* Temporary use register */
92408 
92409  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
92410  exprX = *pExpr->pLeft;
92411  exprAnd.op = TK_AND;
92412  exprAnd.pLeft = &compLeft;
92413  exprAnd.pRight = &compRight;
92414  compLeft.op = TK_GE;
92415  compLeft.pLeft = &exprX;
92416  compLeft.pRight = pExpr->x.pList->a[0].pExpr;
92417  compRight.op = TK_LE;
92418  compRight.pLeft = &exprX;
92419  compRight.pRight = pExpr->x.pList->a[1].pExpr;
92420  exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
92421  if( jumpIfTrue ){
92422  sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
92423  }else{
92424  sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
92425  }
92426  sqlite3ReleaseTempReg(pParse, regFree1);
92427 
92428  /* Ensure adequate test coverage */
92429  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
92430  testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
92431  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
92432  testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
92433  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
92434  testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
92435  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
92436  testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
92437 }
92438 
92439 /*
92440 ** Generate code for a boolean expression such that a jump is made
92441 ** to the label "dest" if the expression is true but execution
92442 ** continues straight thru if the expression is false.
92443 **
92444 ** If the expression evaluates to NULL (neither true nor false), then
92445 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
92446 **
92447 ** This code depends on the fact that certain token values (ex: TK_EQ)
92448 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
92449 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
92450 ** the make process cause these values to align. Assert()s in the code
92451 ** below verify that the numbers are aligned correctly.
92452 */
92453 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
92454  Vdbe *v = pParse->pVdbe;
92455  int op = 0;
92456  int regFree1 = 0;
92457  int regFree2 = 0;
92458  int r1, r2;
92459 
92460  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
92461  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
92462  if( NEVER(pExpr==0) ) return; /* No way this can happen */
92463  op = pExpr->op;
92464  switch( op ){
92465  case TK_AND: {
92466  int d2 = sqlite3VdbeMakeLabel(v);
92467  testcase( jumpIfNull==0 );
92468  sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
92469  sqlite3ExprCachePush(pParse);
92470  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
92471  sqlite3VdbeResolveLabel(v, d2);
92472  sqlite3ExprCachePop(pParse);
92473  break;
92474  }
92475  case TK_OR: {
92476  testcase( jumpIfNull==0 );
92477  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
92478  sqlite3ExprCachePush(pParse);
92479  sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
92480  sqlite3ExprCachePop(pParse);
92481  break;
92482  }
92483  case TK_NOT: {
92484  testcase( jumpIfNull==0 );
92485  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
92486  break;
92487  }
92488  case TK_IS:
92489  case TK_ISNOT:
92490  testcase( op==TK_IS );
92491  testcase( op==TK_ISNOT );
92492  op = (op==TK_IS) ? TK_EQ : TK_NE;
92493  jumpIfNull = SQLITE_NULLEQ;
92494  /* Fall thru */
92495  case TK_LT:
92496  case TK_LE:
92497  case TK_GT:
92498  case TK_GE:
92499  case TK_NE:
92500  case TK_EQ: {
92501  testcase( jumpIfNull==0 );
92502  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92503  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92504  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92505  r1, r2, dest, jumpIfNull);
92510  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
92511  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
92512  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
92513  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
92514  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
92515  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
92516  testcase( regFree1==0 );
92517  testcase( regFree2==0 );
92518  break;
92519  }
92520  case TK_ISNULL:
92521  case TK_NOTNULL: {
92524  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92525  sqlite3VdbeAddOp2(v, op, r1, dest);
92526  VdbeCoverageIf(v, op==TK_ISNULL);
92527  VdbeCoverageIf(v, op==TK_NOTNULL);
92528  testcase( regFree1==0 );
92529  break;
92530  }
92531  case TK_BETWEEN: {
92532  testcase( jumpIfNull==0 );
92533  exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
92534  break;
92535  }
92536 #ifndef SQLITE_OMIT_SUBQUERY
92537  case TK_IN: {
92538  int destIfFalse = sqlite3VdbeMakeLabel(v);
92539  int destIfNull = jumpIfNull ? dest : destIfFalse;
92540  sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
92541  sqlite3VdbeGoto(v, dest);
92542  sqlite3VdbeResolveLabel(v, destIfFalse);
92543  break;
92544  }
92545 #endif
92546  default: {
92547  if( exprAlwaysTrue(pExpr) ){
92548  sqlite3VdbeGoto(v, dest);
92549  }else if( exprAlwaysFalse(pExpr) ){
92550  /* No-op */
92551  }else{
92552  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
92553  sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
92554  VdbeCoverage(v);
92555  testcase( regFree1==0 );
92556  testcase( jumpIfNull==0 );
92557  }
92558  break;
92559  }
92560  }
92561  sqlite3ReleaseTempReg(pParse, regFree1);
92562  sqlite3ReleaseTempReg(pParse, regFree2);
92563 }
92564 
92565 /*
92566 ** Generate code for a boolean expression such that a jump is made
92567 ** to the label "dest" if the expression is false but execution
92568 ** continues straight thru if the expression is true.
92569 **
92570 ** If the expression evaluates to NULL (neither true nor false) then
92571 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
92572 ** is 0.
92573 */
92574 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
92575  Vdbe *v = pParse->pVdbe;
92576  int op = 0;
92577  int regFree1 = 0;
92578  int regFree2 = 0;
92579  int r1, r2;
92580 
92581  assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
92582  if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
92583  if( pExpr==0 ) return;
92584 
92585  /* The value of pExpr->op and op are related as follows:
92586  **
92587  ** pExpr->op op
92588  ** --------- ----------
92589  ** TK_ISNULL OP_NotNull
92590  ** TK_NOTNULL OP_IsNull
92591  ** TK_NE OP_Eq
92592  ** TK_EQ OP_Ne
92593  ** TK_GT OP_Le
92594  ** TK_LE OP_Gt
92595  ** TK_GE OP_Lt
92596  ** TK_LT OP_Ge
92597  **
92598  ** For other values of pExpr->op, op is undefined and unused.
92599  ** The value of TK_ and OP_ constants are arranged such that we
92600  ** can compute the mapping above using the following expression.
92601  ** Assert()s verify that the computation is correct.
92602  */
92603  op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
92604 
92605  /* Verify correct alignment of TK_ and OP_ constants
92606  */
92607  assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
92608  assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
92609  assert( pExpr->op!=TK_NE || op==OP_Eq );
92610  assert( pExpr->op!=TK_EQ || op==OP_Ne );
92611  assert( pExpr->op!=TK_LT || op==OP_Ge );
92612  assert( pExpr->op!=TK_LE || op==OP_Gt );
92613  assert( pExpr->op!=TK_GT || op==OP_Le );
92614  assert( pExpr->op!=TK_GE || op==OP_Lt );
92615 
92616  switch( pExpr->op ){
92617  case TK_AND: {
92618  testcase( jumpIfNull==0 );
92619  sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
92620  sqlite3ExprCachePush(pParse);
92621  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
92622  sqlite3ExprCachePop(pParse);
92623  break;
92624  }
92625  case TK_OR: {
92626  int d2 = sqlite3VdbeMakeLabel(v);
92627  testcase( jumpIfNull==0 );
92628  sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
92629  sqlite3ExprCachePush(pParse);
92630  sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
92631  sqlite3VdbeResolveLabel(v, d2);
92632  sqlite3ExprCachePop(pParse);
92633  break;
92634  }
92635  case TK_NOT: {
92636  testcase( jumpIfNull==0 );
92637  sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
92638  break;
92639  }
92640  case TK_IS:
92641  case TK_ISNOT:
92642  testcase( pExpr->op==TK_IS );
92643  testcase( pExpr->op==TK_ISNOT );
92644  op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
92645  jumpIfNull = SQLITE_NULLEQ;
92646  /* Fall thru */
92647  case TK_LT:
92648  case TK_LE:
92649  case TK_GT:
92650  case TK_GE:
92651  case TK_NE:
92652  case TK_EQ: {
92653  testcase( jumpIfNull==0 );
92654  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92655  r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
92656  codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
92657  r1, r2, dest, jumpIfNull);
92662  assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
92663  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
92664  VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
92665  assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
92666  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
92667  VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
92668  testcase( regFree1==0 );
92669  testcase( regFree2==0 );
92670  break;
92671  }
92672  case TK_ISNULL:
92673  case TK_NOTNULL: {
92674  r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
92675  sqlite3VdbeAddOp2(v, op, r1, dest);
92676  testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
92677  testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
92678  testcase( regFree1==0 );
92679  break;
92680  }
92681  case TK_BETWEEN: {
92682  testcase( jumpIfNull==0 );
92683  exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
92684  break;
92685  }
92686 #ifndef SQLITE_OMIT_SUBQUERY
92687  case TK_IN: {
92688  if( jumpIfNull ){
92689  sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
92690  }else{
92691  int destIfNull = sqlite3VdbeMakeLabel(v);
92692  sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
92693  sqlite3VdbeResolveLabel(v, destIfNull);
92694  }
92695  break;
92696  }
92697 #endif
92698  default: {
92699  if( exprAlwaysFalse(pExpr) ){
92700  sqlite3VdbeGoto(v, dest);
92701  }else if( exprAlwaysTrue(pExpr) ){
92702  /* no-op */
92703  }else{
92704  r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
92705  sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
92706  VdbeCoverage(v);
92707  testcase( regFree1==0 );
92708  testcase( jumpIfNull==0 );
92709  }
92710  break;
92711  }
92712  }
92713  sqlite3ReleaseTempReg(pParse, regFree1);
92714  sqlite3ReleaseTempReg(pParse, regFree2);
92715 }
92716 
92717 /*
92718 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
92719 ** code generation, and that copy is deleted after code generation. This
92720 ** ensures that the original pExpr is unchanged.
92721 */
92722 SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
92723  sqlite3 *db = pParse->db;
92724  Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
92725  if( db->mallocFailed==0 ){
92726  sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
92727  }
92728  sqlite3ExprDelete(db, pCopy);
92729 }
92730 
92731 
92732 /*
92733 ** Do a deep comparison of two expression trees. Return 0 if the two
92734 ** expressions are completely identical. Return 1 if they differ only
92735 ** by a COLLATE operator at the top level. Return 2 if there are differences
92736 ** other than the top-level COLLATE operator.
92737 **
92738 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
92739 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
92740 **
92741 ** The pA side might be using TK_REGISTER. If that is the case and pB is
92742 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
92743 **
92744 ** Sometimes this routine will return 2 even if the two expressions
92745 ** really are equivalent. If we cannot prove that the expressions are
92746 ** identical, we return 2 just to be safe. So if this routine
92747 ** returns 2, then you do not really know for certain if the two
92748 ** expressions are the same. But if you get a 0 or 1 return, then you
92749 ** can be sure the expressions are the same. In the places where
92750 ** this routine is used, it does not hurt to get an extra 2 - that
92751 ** just might result in some slightly slower code. But returning
92752 ** an incorrect 0 or 1 could lead to a malfunction.
92753 */
92754 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
92755  u32 combinedFlags;
92756  if( pA==0 || pB==0 ){
92757  return pB==pA ? 0 : 2;
92758  }
92759  combinedFlags = pA->flags | pB->flags;
92760  if( combinedFlags & EP_IntValue ){
92761  if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
92762  return 0;
92763  }
92764  return 2;
92765  }
92766  if( pA->op!=pB->op ){
92767  if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
92768  return 1;
92769  }
92770  if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
92771  return 1;
92772  }
92773  return 2;
92774  }
92775  if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
92776  if( pA->op==TK_FUNCTION ){
92777  if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
92778  }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
92779  return pA->op==TK_COLLATE ? 1 : 2;
92780  }
92781  }
92782  if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
92783  if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
92784  if( combinedFlags & EP_xIsSelect ) return 2;
92785  if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
92786  if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
92787  if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
92788  if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
92789  if( pA->iColumn!=pB->iColumn ) return 2;
92790  if( pA->iTable!=pB->iTable
92791  && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
92792  }
92793  }
92794  return 0;
92795 }
92796 
92797 /*
92798 ** Compare two ExprList objects. Return 0 if they are identical and
92799 ** non-zero if they differ in any way.
92800 **
92801 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
92802 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
92803 **
92804 ** This routine might return non-zero for equivalent ExprLists. The
92805 ** only consequence will be disabled optimizations. But this routine
92806 ** must never return 0 if the two ExprList objects are different, or
92807 ** a malfunction will result.
92808 **
92809 ** Two NULL pointers are considered to be the same. But a NULL pointer
92810 ** always differs from a non-NULL pointer.
92811 */
92813  int i;
92814  if( pA==0 && pB==0 ) return 0;
92815  if( pA==0 || pB==0 ) return 1;
92816  if( pA->nExpr!=pB->nExpr ) return 1;
92817  for(i=0; i<pA->nExpr; i++){
92818  Expr *pExprA = pA->a[i].pExpr;
92819  Expr *pExprB = pB->a[i].pExpr;
92820  if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
92821  if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
92822  }
92823  return 0;
92824 }
92825 
92826 /*
92827 ** Return true if we can prove the pE2 will always be true if pE1 is
92828 ** true. Return false if we cannot complete the proof or if pE2 might
92829 ** be false. Examples:
92830 **
92831 ** pE1: x==5 pE2: x==5 Result: true
92832 ** pE1: x>0 pE2: x==5 Result: false
92833 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
92834 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
92835 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
92836 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
92837 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
92838 **
92839 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
92840 ** Expr.iTable<0 then assume a table number given by iTab.
92841 **
92842 ** When in doubt, return false. Returning true might give a performance
92843 ** improvement. Returning false might cause a performance reduction, but
92844 ** it will always give the correct answer and is hence always safe.
92845 */
92847  if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
92848  return 1;
92849  }
92850  if( pE2->op==TK_OR
92851  && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
92852  || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
92853  ){
92854  return 1;
92855  }
92856  if( pE2->op==TK_NOTNULL
92857  && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
92858  && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
92859  ){
92860  return 1;
92861  }
92862  return 0;
92863 }
92864 
92865 /*
92866 ** An instance of the following structure is used by the tree walker
92867 ** to count references to table columns in the arguments of an
92868 ** aggregate function, in order to implement the
92869 ** sqlite3FunctionThisSrc() routine.
92870 */
92871 struct SrcCount {
92872  SrcList *pSrc; /* One particular FROM clause in a nested query */
92873  int nThis; /* Number of references to columns in pSrcList */
92874  int nOther; /* Number of references to columns in other FROM clauses */
92875 };
92876 
92877 /*
92878 ** Count the number of references to columns.
92879 */
92880 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
92881  /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
92882  ** is always called before sqlite3ExprAnalyzeAggregates() and so the
92883  ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
92884  ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
92885  ** NEVER() will need to be removed. */
92886  if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
92887  int i;
92888  struct SrcCount *p = pWalker->u.pSrcCount;
92889  SrcList *pSrc = p->pSrc;
92890  int nSrc = pSrc ? pSrc->nSrc : 0;
92891  for(i=0; i<nSrc; i++){
92892  if( pExpr->iTable==pSrc->a[i].iCursor ) break;
92893  }
92894  if( i<nSrc ){
92895  p->nThis++;
92896  }else{
92897  p->nOther++;
92898  }
92899  }
92900  return WRC_Continue;
92901 }
92902 
92903 /*
92904 ** Determine if any of the arguments to the pExpr Function reference
92905 ** pSrcList. Return true if they do. Also return true if the function
92906 ** has no arguments or has only constant arguments. Return false if pExpr
92907 ** references columns but not columns of tables found in pSrcList.
92908 */
92910  Walker w;
92911  struct SrcCount cnt;
92912  assert( pExpr->op==TK_AGG_FUNCTION );
92913  memset(&w, 0, sizeof(w));
92915  w.u.pSrcCount = &cnt;
92916  cnt.pSrc = pSrcList;
92917  cnt.nThis = 0;
92918  cnt.nOther = 0;
92919  sqlite3WalkExprList(&w, pExpr->x.pList);
92920  return cnt.nThis>0 || cnt.nOther==0;
92921 }
92922 
92923 /*
92924 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
92925 ** the new element. Return a negative number if malloc fails.
92926 */
92927 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
92928  int i;
92929  pInfo->aCol = sqlite3ArrayAllocate(
92930  db,
92931  pInfo->aCol,
92932  sizeof(pInfo->aCol[0]),
92933  &pInfo->nColumn,
92934  &i
92935  );
92936  return i;
92937 }
92938 
92939 /*
92940 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
92941 ** the new element. Return a negative number if malloc fails.
92942 */
92943 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
92944  int i;
92945  pInfo->aFunc = sqlite3ArrayAllocate(
92946  db,
92947  pInfo->aFunc,
92948  sizeof(pInfo->aFunc[0]),
92949  &pInfo->nFunc,
92950  &i
92951  );
92952  return i;
92953 }
92954 
92955 /*
92956 ** This is the xExprCallback for a tree walker. It is used to
92957 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
92958 ** for additional information.
92959 */
92960 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
92961  int i;
92962  NameContext *pNC = pWalker->u.pNC;
92963  Parse *pParse = pNC->pParse;
92964  SrcList *pSrcList = pNC->pSrcList;
92965  AggInfo *pAggInfo = pNC->pAggInfo;
92966 
92967  switch( pExpr->op ){
92968  case TK_AGG_COLUMN:
92969  case TK_COLUMN: {
92970  testcase( pExpr->op==TK_AGG_COLUMN );
92971  testcase( pExpr->op==TK_COLUMN );
92972  /* Check to see if the column is in one of the tables in the FROM
92973  ** clause of the aggregate query */
92974  if( ALWAYS(pSrcList!=0) ){
92975  struct SrcList_item *pItem = pSrcList->a;
92976  for(i=0; i<pSrcList->nSrc; i++, pItem++){
92977  struct AggInfo_col *pCol;
92979  if( pExpr->iTable==pItem->iCursor ){
92980  /* If we reach this point, it means that pExpr refers to a table
92981  ** that is in the FROM clause of the aggregate query.
92982  **
92983  ** Make an entry for the column in pAggInfo->aCol[] if there
92984  ** is not an entry there already.
92985  */
92986  int k;
92987  pCol = pAggInfo->aCol;
92988  for(k=0; k<pAggInfo->nColumn; k++, pCol++){
92989  if( pCol->iTable==pExpr->iTable &&
92990  pCol->iColumn==pExpr->iColumn ){
92991  break;
92992  }
92993  }
92994  if( (k>=pAggInfo->nColumn)
92995  && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
92996  ){
92997  pCol = &pAggInfo->aCol[k];
92998  pCol->pTab = pExpr->pTab;
92999  pCol->iTable = pExpr->iTable;
93000  pCol->iColumn = pExpr->iColumn;
93001  pCol->iMem = ++pParse->nMem;
93002  pCol->iSorterColumn = -1;
93003  pCol->pExpr = pExpr;
93004  if( pAggInfo->pGroupBy ){
93005  int j, n;
93006  ExprList *pGB = pAggInfo->pGroupBy;
93007  struct ExprList_item *pTerm = pGB->a;
93008  n = pGB->nExpr;
93009  for(j=0; j<n; j++, pTerm++){
93010  Expr *pE = pTerm->pExpr;
93011  if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
93012  pE->iColumn==pExpr->iColumn ){
93013  pCol->iSorterColumn = j;
93014  break;
93015  }
93016  }
93017  }
93018  if( pCol->iSorterColumn<0 ){
93019  pCol->iSorterColumn = pAggInfo->nSortingColumn++;
93020  }
93021  }
93022  /* There is now an entry for pExpr in pAggInfo->aCol[] (either
93023  ** because it was there before or because we just created it).
93024  ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
93025  ** pAggInfo->aCol[] entry.
93026  */
93028  pExpr->pAggInfo = pAggInfo;
93029  pExpr->op = TK_AGG_COLUMN;
93030  pExpr->iAgg = (i16)k;
93031  break;
93032  } /* endif pExpr->iTable==pItem->iCursor */
93033  } /* end loop over pSrcList */
93034  }
93035  return WRC_Prune;
93036  }
93037  case TK_AGG_FUNCTION: {
93038  if( (pNC->ncFlags & NC_InAggFunc)==0
93039  && pWalker->walkerDepth==pExpr->op2
93040  ){
93041  /* Check to see if pExpr is a duplicate of another aggregate
93042  ** function that is already in the pAggInfo structure
93043  */
93044  struct AggInfo_func *pItem = pAggInfo->aFunc;
93045  for(i=0; i<pAggInfo->nFunc; i++, pItem++){
93046  if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
93047  break;
93048  }
93049  }
93050  if( i>=pAggInfo->nFunc ){
93051  /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
93052  */
93053  u8 enc = ENC(pParse->db);
93054  i = addAggInfoFunc(pParse->db, pAggInfo);
93055  if( i>=0 ){
93056  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
93057  pItem = &pAggInfo->aFunc[i];
93058  pItem->pExpr = pExpr;
93059  pItem->iMem = ++pParse->nMem;
93060  assert( !ExprHasProperty(pExpr, EP_IntValue) );
93061  pItem->pFunc = sqlite3FindFunction(pParse->db,
93062  pExpr->u.zToken,
93063  pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
93064  if( pExpr->flags & EP_Distinct ){
93065  pItem->iDistinct = pParse->nTab++;
93066  }else{
93067  pItem->iDistinct = -1;
93068  }
93069  }
93070  }
93071  /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
93072  */
93075  pExpr->iAgg = (i16)i;
93076  pExpr->pAggInfo = pAggInfo;
93077  return WRC_Prune;
93078  }else{
93079  return WRC_Continue;
93080  }
93081  }
93082  }
93083  return WRC_Continue;
93084 }
93085 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
93086  UNUSED_PARAMETER(pWalker);
93087  UNUSED_PARAMETER(pSelect);
93088  return WRC_Continue;
93089 }
93090 
93091 /*
93092 ** Analyze the pExpr expression looking for aggregate functions and
93093 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
93094 ** points to. Additional entries are made on the AggInfo object as
93095 ** necessary.
93096 **
93097 ** This routine should only be called after the expression has been
93098 ** analyzed by sqlite3ResolveExprNames().
93099 */
93101  Walker w;
93102  memset(&w, 0, sizeof(w));
93105  w.u.pNC = pNC;
93106  assert( pNC->pSrcList!=0 );
93107  sqlite3WalkExpr(&w, pExpr);
93108 }
93109 
93110 /*
93111 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
93112 ** expression list. Return the number of errors.
93113 **
93114 ** If an error is found, the analysis is cut short.
93115 */
93117  struct ExprList_item *pItem;
93118  int i;
93119  if( pList ){
93120  for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
93121  sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
93122  }
93123  }
93124 }
93125 
93126 /*
93127 ** Allocate a single new register for use to hold some intermediate result.
93128 */
93130  if( pParse->nTempReg==0 ){
93131  return ++pParse->nMem;
93132  }
93133  return pParse->aTempReg[--pParse->nTempReg];
93134 }
93135 
93136 /*
93137 ** Deallocate a register, making available for reuse for some other
93138 ** purpose.
93139 **
93140 ** If a register is currently being used by the column cache, then
93141 ** the deallocation is deferred until the column cache line that uses
93142 ** the register becomes stale.
93143 */
93145  if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
93146  int i;
93147  struct yColCache *p;
93148  for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
93149  if( p->iReg==iReg ){
93150  p->tempReg = 1;
93151  return;
93152  }
93153  }
93154  pParse->aTempReg[pParse->nTempReg++] = iReg;
93155  }
93156 }
93157 
93158 /*
93159 ** Allocate or deallocate a block of nReg consecutive registers
93160 */
93162  int i, n;
93163  i = pParse->iRangeReg;
93164  n = pParse->nRangeReg;
93165  if( nReg<=n ){
93166  assert( !usedAsColumnCache(pParse, i, i+n-1) );
93167  pParse->iRangeReg += nReg;
93168  pParse->nRangeReg -= nReg;
93169  }else{
93170  i = pParse->nMem+1;
93171  pParse->nMem += nReg;
93172  }
93173  return i;
93174 }
93175 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
93176  sqlite3ExprCacheRemove(pParse, iReg, nReg);
93177  if( nReg>pParse->nRangeReg ){
93178  pParse->nRangeReg = nReg;
93179  pParse->iRangeReg = iReg;
93180  }
93181 }
93182 
93183 /*
93184 ** Mark all temporary registers as being unavailable for reuse.
93185 */
93187  pParse->nTempReg = 0;
93188  pParse->nRangeReg = 0;
93189 }
93190 
93191 /*
93192 ** Validate that no temporary register falls within the range of
93193 ** iFirst..iLast, inclusive. This routine is only call from within assert()
93194 ** statements.
93195 */
93196 #ifdef SQLITE_DEBUG
93197 SQLITE_PRIVATE int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
93198  int i;
93199  if( pParse->nRangeReg>0
93200  && pParse->iRangeReg+pParse->nRangeReg<iLast
93201  && pParse->iRangeReg>=iFirst
93202  ){
93203  return 0;
93204  }
93205  for(i=0; i<pParse->nTempReg; i++){
93206  if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
93207  return 0;
93208  }
93209  }
93210  return 1;
93211 }
93212 #endif /* SQLITE_DEBUG */
93213 
93214 /************** End of expr.c ************************************************/
93215 /************** Begin file alter.c *******************************************/
93216 /*
93217 ** 2005 February 15
93218 **
93219 ** The author disclaims copyright to this source code. In place of
93220 ** a legal notice, here is a blessing:
93221 **
93222 ** May you do good and not evil.
93223 ** May you find forgiveness for yourself and forgive others.
93224 ** May you share freely, never taking more than you give.
93225 **
93226 *************************************************************************
93227 ** This file contains C code routines that used to generate VDBE code
93228 ** that implements the ALTER TABLE command.
93229 */
93230 /* #include "sqliteInt.h" */
93231 
93232 /*
93233 ** The code in this file only exists if we are not omitting the
93234 ** ALTER TABLE logic from the build.
93235 */
93236 #ifndef SQLITE_OMIT_ALTERTABLE
93237 
93238 
93239 /*
93240 ** This function is used by SQL generated to implement the
93241 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
93242 ** CREATE INDEX command. The second is a table name. The table name in
93243 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
93244 ** argument and the result returned. Examples:
93245 **
93246 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
93247 ** -> 'CREATE TABLE def(a, b, c)'
93248 **
93249 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
93250 ** -> 'CREATE INDEX i ON def(a, b, c)'
93251 */
93252 static void renameTableFunc(
93253  sqlite3_context *context,
93254  int NotUsed,
93255  sqlite3_value **argv
93256 ){
93257  unsigned char const *zSql = sqlite3_value_text(argv[0]);
93258  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93259 
93260  int token;
93261  Token tname;
93262  unsigned char const *zCsr = zSql;
93263  int len = 0;
93264  char *zRet;
93265 
93266  sqlite3 *db = sqlite3_context_db_handle(context);
93267 
93268  UNUSED_PARAMETER(NotUsed);
93269 
93270  /* The principle used to locate the table name in the CREATE TABLE
93271  ** statement is that the table name is the first non-space token that
93272  ** is immediately followed by a TK_LP or TK_USING token.
93273  */
93274  if( zSql ){
93275  do {
93276  if( !*zCsr ){
93277  /* Ran out of input before finding an opening bracket. Return NULL. */
93278  return;
93279  }
93280 
93281  /* Store the token that zCsr points to in tname. */
93282  tname.z = (char*)zCsr;
93283  tname.n = len;
93284 
93285  /* Advance zCsr to the next token. Store that token type in 'token',
93286  ** and its length in 'len' (to be used next iteration of this loop).
93287  */
93288  do {
93289  zCsr += len;
93290  len = sqlite3GetToken(zCsr, &token);
93291  } while( token==TK_SPACE );
93292  assert( len>0 );
93293  } while( token!=TK_LP && token!=TK_USING );
93294 
93295  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
93296  zSql, zTableName, tname.z+tname.n);
93297  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
93298  }
93299 }
93300 
93301 /*
93302 ** This C function implements an SQL user function that is used by SQL code
93303 ** generated by the ALTER TABLE ... RENAME command to modify the definition
93304 ** of any foreign key constraints that use the table being renamed as the
93305 ** parent table. It is passed three arguments:
93306 **
93307 ** 1) The complete text of the CREATE TABLE statement being modified,
93308 ** 2) The old name of the table being renamed, and
93309 ** 3) The new name of the table being renamed.
93310 **
93311 ** It returns the new CREATE TABLE statement. For example:
93312 **
93313 ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
93314 ** -> 'CREATE TABLE t1(a REFERENCES t3)'
93315 */
93316 #ifndef SQLITE_OMIT_FOREIGN_KEY
93317 static void renameParentFunc(
93318  sqlite3_context *context,
93319  int NotUsed,
93320  sqlite3_value **argv
93321 ){
93322  sqlite3 *db = sqlite3_context_db_handle(context);
93323  char *zOutput = 0;
93324  char *zResult;
93325  unsigned char const *zInput = sqlite3_value_text(argv[0]);
93326  unsigned char const *zOld = sqlite3_value_text(argv[1]);
93327  unsigned char const *zNew = sqlite3_value_text(argv[2]);
93328 
93329  unsigned const char *z; /* Pointer to token */
93330  int n; /* Length of token z */
93331  int token; /* Type of token */
93332 
93333  UNUSED_PARAMETER(NotUsed);
93334  if( zInput==0 || zOld==0 ) return;
93335  for(z=zInput; *z; z=z+n){
93336  n = sqlite3GetToken(z, &token);
93337  if( token==TK_REFERENCES ){
93338  char *zParent;
93339  do {
93340  z += n;
93341  n = sqlite3GetToken(z, &token);
93342  }while( token==TK_SPACE );
93343 
93344  if( token==TK_ILLEGAL ) break;
93345  zParent = sqlite3DbStrNDup(db, (const char *)z, n);
93346  if( zParent==0 ) break;
93347  sqlite3Dequote(zParent);
93348  if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
93349  char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
93350  (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
93351  );
93352  sqlite3DbFree(db, zOutput);
93353  zOutput = zOut;
93354  zInput = &z[n];
93355  }
93356  sqlite3DbFree(db, zParent);
93357  }
93358  }
93359 
93360  zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
93361  sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
93362  sqlite3DbFree(db, zOutput);
93363 }
93364 #endif
93365 
93366 #ifndef SQLITE_OMIT_TRIGGER
93367 /* This function is used by SQL generated to implement the
93368 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
93369 ** statement. The second is a table name. The table name in the CREATE
93370 ** TRIGGER statement is replaced with the third argument and the result
93371 ** returned. This is analagous to renameTableFunc() above, except for CREATE
93372 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
93373 */
93374 static void renameTriggerFunc(
93375  sqlite3_context *context,
93376  int NotUsed,
93377  sqlite3_value **argv
93378 ){
93379  unsigned char const *zSql = sqlite3_value_text(argv[0]);
93380  unsigned char const *zTableName = sqlite3_value_text(argv[1]);
93381 
93382  int token;
93383  Token tname;
93384  int dist = 3;
93385  unsigned char const *zCsr = zSql;
93386  int len = 0;
93387  char *zRet;
93388  sqlite3 *db = sqlite3_context_db_handle(context);
93389 
93390  UNUSED_PARAMETER(NotUsed);
93391 
93392  /* The principle used to locate the table name in the CREATE TRIGGER
93393  ** statement is that the table name is the first token that is immediately
93394  ** preceded by either TK_ON or TK_DOT and immediately followed by one
93395  ** of TK_WHEN, TK_BEGIN or TK_FOR.
93396  */
93397  if( zSql ){
93398  do {
93399 
93400  if( !*zCsr ){
93401  /* Ran out of input before finding the table name. Return NULL. */
93402  return;
93403  }
93404 
93405  /* Store the token that zCsr points to in tname. */
93406  tname.z = (char*)zCsr;
93407  tname.n = len;
93408 
93409  /* Advance zCsr to the next token. Store that token type in 'token',
93410  ** and its length in 'len' (to be used next iteration of this loop).
93411  */
93412  do {
93413  zCsr += len;
93414  len = sqlite3GetToken(zCsr, &token);
93415  }while( token==TK_SPACE );
93416  assert( len>0 );
93417 
93418  /* Variable 'dist' stores the number of tokens read since the most
93419  ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
93420  ** token is read and 'dist' equals 2, the condition stated above
93421  ** to be met.
93422  **
93423  ** Note that ON cannot be a database, table or column name, so
93424  ** there is no need to worry about syntax like
93425  ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
93426  */
93427  dist++;
93428  if( token==TK_DOT || token==TK_ON ){
93429  dist = 0;
93430  }
93431  } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
93432 
93433  /* Variable tname now contains the token that is the old table-name
93434  ** in the CREATE TRIGGER statement.
93435  */
93436  zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
93437  zSql, zTableName, tname.z+tname.n);
93438  sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
93439  }
93440 }
93441 #endif /* !SQLITE_OMIT_TRIGGER */
93442 
93443 /*
93444 ** Register built-in functions used to help implement ALTER TABLE
93445 */
93447  static FuncDef aAlterTableFuncs[] = {
93448  FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
93449 #ifndef SQLITE_OMIT_TRIGGER
93450  FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
93451 #endif
93452 #ifndef SQLITE_OMIT_FOREIGN_KEY
93453  FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
93454 #endif
93455  };
93456  sqlite3InsertBuiltinFuncs(aAlterTableFuncs, ArraySize(aAlterTableFuncs));
93457 }
93458 
93459 /*
93460 ** This function is used to create the text of expressions of the form:
93461 **
93462 ** name=<constant1> OR name=<constant2> OR ...
93463 **
93464 ** If argument zWhere is NULL, then a pointer string containing the text
93465 ** "name=<constant>" is returned, where <constant> is the quoted version
93466 ** of the string passed as argument zConstant. The returned buffer is
93467 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
93468 ** caller to ensure that it is eventually freed.
93469 **
93470 ** If argument zWhere is not NULL, then the string returned is
93471 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
93472 ** In this case zWhere is passed to sqlite3DbFree() before returning.
93473 **
93474 */
93475 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
93476  char *zNew;
93477  if( !zWhere ){
93478  zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
93479  }else{
93480  zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
93481  sqlite3DbFree(db, zWhere);
93482  }
93483  return zNew;
93484 }
93485 
93486 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93487 /*
93488 ** Generate the text of a WHERE expression which can be used to select all
93489 ** tables that have foreign key constraints that refer to table pTab (i.e.
93490 ** constraints for which pTab is the parent table) from the sqlite_master
93491 ** table.
93492 */
93493 static char *whereForeignKeys(Parse *pParse, Table *pTab){
93494  FKey *p;
93495  char *zWhere = 0;
93496  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
93497  zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
93498  }
93499  return zWhere;
93500 }
93501 #endif
93502 
93503 /*
93504 ** Generate the text of a WHERE expression which can be used to select all
93505 ** temporary triggers on table pTab from the sqlite_temp_master table. If
93506 ** table pTab has no temporary triggers, or is itself stored in the
93507 ** temporary database, NULL is returned.
93508 */
93509 static char *whereTempTriggers(Parse *pParse, Table *pTab){
93510  Trigger *pTrig;
93511  char *zWhere = 0;
93512  const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
93513 
93514  /* If the table is not located in the temp-db (in which case NULL is
93515  ** returned, loop through the tables list of triggers. For each trigger
93516  ** that is not part of the temp-db schema, add a clause to the WHERE
93517  ** expression being built up in zWhere.
93518  */
93519  if( pTab->pSchema!=pTempSchema ){
93520  sqlite3 *db = pParse->db;
93521  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
93522  if( pTrig->pSchema==pTempSchema ){
93523  zWhere = whereOrName(db, zWhere, pTrig->zName);
93524  }
93525  }
93526  }
93527  if( zWhere ){
93528  char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
93529  sqlite3DbFree(pParse->db, zWhere);
93530  zWhere = zNew;
93531  }
93532  return zWhere;
93533 }
93534 
93535 /*
93536 ** Generate code to drop and reload the internal representation of table
93537 ** pTab from the database, including triggers and temporary triggers.
93538 ** Argument zName is the name of the table in the database schema at
93539 ** the time the generated code is executed. This can be different from
93540 ** pTab->zName if this function is being called to code part of an
93541 ** "ALTER TABLE RENAME TO" statement.
93542 */
93543 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
93544  Vdbe *v;
93545  char *zWhere;
93546  int iDb; /* Index of database containing pTab */
93547 #ifndef SQLITE_OMIT_TRIGGER
93548  Trigger *pTrig;
93549 #endif
93550 
93551  v = sqlite3GetVdbe(pParse);
93552  if( NEVER(v==0) ) return;
93553  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
93554  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93555  assert( iDb>=0 );
93556 
93557 #ifndef SQLITE_OMIT_TRIGGER
93558  /* Drop any table triggers from the internal schema. */
93559  for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
93560  int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
93561  assert( iTrigDb==iDb || iTrigDb==1 );
93562  sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
93563  }
93564 #endif
93565 
93566  /* Drop the table and index from the internal schema. */
93567  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
93568 
93569  /* Reload the table, index and permanent trigger schemas. */
93570  zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
93571  if( !zWhere ) return;
93572  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
93573 
93574 #ifndef SQLITE_OMIT_TRIGGER
93575  /* Now, if the table is not stored in the temp database, reload any temp
93576  ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
93577  */
93578  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
93579  sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
93580  }
93581 #endif
93582 }
93583 
93584 /*
93585 ** Parameter zName is the name of a table that is about to be altered
93586 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
93587 ** If the table is a system table, this function leaves an error message
93588 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
93589 **
93590 ** Or, if zName is not a system table, zero is returned.
93591 */
93592 static int isSystemTable(Parse *pParse, const char *zName){
93593  if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
93594  sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
93595  return 1;
93596  }
93597  return 0;
93598 }
93599 
93600 /*
93601 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
93602 ** command.
93603 */
93605  Parse *pParse, /* Parser context. */
93606  SrcList *pSrc, /* The table to rename. */
93607  Token *pName /* The new table name. */
93608 ){
93609  int iDb; /* Database that contains the table */
93610  char *zDb; /* Name of database iDb */
93611  Table *pTab; /* Table being renamed */
93612  char *zName = 0; /* NULL-terminated version of pName */
93613  sqlite3 *db = pParse->db; /* Database connection */
93614  int nTabName; /* Number of UTF-8 characters in zTabName */
93615  const char *zTabName; /* Original name of the table */
93616  Vdbe *v;
93617 #ifndef SQLITE_OMIT_TRIGGER
93618  char *zWhere = 0; /* Where clause to locate temp triggers */
93619 #endif
93620  VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
93621  int savedDbFlags; /* Saved value of db->flags */
93622 
93623  savedDbFlags = db->flags;
93624  if( NEVER(db->mallocFailed) ) goto exit_rename_table;
93625  assert( pSrc->nSrc==1 );
93626  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
93627 
93628  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
93629  if( !pTab ) goto exit_rename_table;
93630  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
93631  zDb = db->aDb[iDb].zName;
93632  db->flags |= SQLITE_PreferBuiltin;
93633 
93634  /* Get a NULL terminated version of the new table name. */
93635  zName = sqlite3NameFromToken(db, pName);
93636  if( !zName ) goto exit_rename_table;
93637 
93638  /* Check that a table or index named 'zName' does not already exist
93639  ** in database iDb. If so, this is an error.
93640  */
93641  if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
93642  sqlite3ErrorMsg(pParse,
93643  "there is already another table or index with this name: %s", zName);
93644  goto exit_rename_table;
93645  }
93646 
93647  /* Make sure it is not a system table being altered, or a reserved name
93648  ** that the table is being renamed to.
93649  */
93650  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
93651  goto exit_rename_table;
93652  }
93653  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
93654  exit_rename_table;
93655  }
93656 
93657 #ifndef SQLITE_OMIT_VIEW
93658  if( pTab->pSelect ){
93659  sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
93660  goto exit_rename_table;
93661  }
93662 #endif
93663 
93664 #ifndef SQLITE_OMIT_AUTHORIZATION
93665  /* Invoke the authorization callback. */
93666  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
93667  goto exit_rename_table;
93668  }
93669 #endif
93670 
93671 #ifndef SQLITE_OMIT_VIRTUALTABLE
93672  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
93673  goto exit_rename_table;
93674  }
93675  if( IsVirtual(pTab) ){
93676  pVTab = sqlite3GetVTable(db, pTab);
93677  if( pVTab->pVtab->pModule->xRename==0 ){
93678  pVTab = 0;
93679  }
93680  }
93681 #endif
93682 
93683  /* Begin a transaction for database iDb.
93684  ** Then modify the schema cookie (since the ALTER TABLE modifies the
93685  ** schema). Open a statement transaction if the table is a virtual
93686  ** table.
93687  */
93688  v = sqlite3GetVdbe(pParse);
93689  if( v==0 ){
93690  goto exit_rename_table;
93691  }
93692  sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
93693  sqlite3ChangeCookie(pParse, iDb);
93694 
93695  /* If this is a virtual table, invoke the xRename() function if
93696  ** one is defined. The xRename() callback will modify the names
93697  ** of any resources used by the v-table implementation (including other
93698  ** SQLite tables) that are identified by the name of the virtual table.
93699  */
93700 #ifndef SQLITE_OMIT_VIRTUALTABLE
93701  if( pVTab ){
93702  int i = ++pParse->nMem;
93703  sqlite3VdbeLoadString(v, i, zName);
93704  sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
93705  sqlite3MayAbort(pParse);
93706  }
93707 #endif
93708 
93709  /* figure out how many UTF-8 characters are in zName */
93710  zTabName = pTab->zName;
93711  nTabName = sqlite3Utf8CharLen(zTabName, -1);
93712 
93713 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93714  if( db->flags&SQLITE_ForeignKeys ){
93715  /* If foreign-key support is enabled, rewrite the CREATE TABLE
93716  ** statements corresponding to all child tables of foreign key constraints
93717  ** for which the renamed table is the parent table. */
93718  if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
93719  sqlite3NestedParse(pParse,
93720  "UPDATE \"%w\".%s SET "
93721  "sql = sqlite_rename_parent(sql, %Q, %Q) "
93722  "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
93723  sqlite3DbFree(db, zWhere);
93724  }
93725  }
93726 #endif
93727 
93728  /* Modify the sqlite_master table to use the new table name. */
93729  sqlite3NestedParse(pParse,
93730  "UPDATE %Q.%s SET "
93731 #ifdef SQLITE_OMIT_TRIGGER
93732  "sql = sqlite_rename_table(sql, %Q), "
93733 #else
93734  "sql = CASE "
93735  "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
93736  "ELSE sqlite_rename_table(sql, %Q) END, "
93737 #endif
93738  "tbl_name = %Q, "
93739  "name = CASE "
93740  "WHEN type='table' THEN %Q "
93741  "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
93742  "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
93743  "ELSE name END "
93744  "WHERE tbl_name=%Q COLLATE nocase AND "
93745  "(type='table' OR type='index' OR type='trigger');",
93746  zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
93747 #ifndef SQLITE_OMIT_TRIGGER
93748  zName,
93749 #endif
93750  zName, nTabName, zTabName
93751  );
93752 
93753 #ifndef SQLITE_OMIT_AUTOINCREMENT
93754  /* If the sqlite_sequence table exists in this database, then update
93755  ** it with the new table name.
93756  */
93757  if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
93758  sqlite3NestedParse(pParse,
93759  "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
93760  zDb, zName, pTab->zName);
93761  }
93762 #endif
93763 
93764 #ifndef SQLITE_OMIT_TRIGGER
93765  /* If there are TEMP triggers on this table, modify the sqlite_temp_master
93766  ** table. Don't do this if the table being ALTERed is itself located in
93767  ** the temp database.
93768  */
93769  if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
93770  sqlite3NestedParse(pParse,
93771  "UPDATE sqlite_temp_master SET "
93772  "sql = sqlite_rename_trigger(sql, %Q), "
93773  "tbl_name = %Q "
93774  "WHERE %s;", zName, zName, zWhere);
93775  sqlite3DbFree(db, zWhere);
93776  }
93777 #endif
93778 
93779 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
93780  if( db->flags&SQLITE_ForeignKeys ){
93781  FKey *p;
93782  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
93783  Table *pFrom = p->pFrom;
93784  if( pFrom!=pTab ){
93785  reloadTableSchema(pParse, p->pFrom, pFrom->zName);
93786  }
93787  }
93788  }
93789 #endif
93790 
93791  /* Drop and reload the internal table schema. */
93792  reloadTableSchema(pParse, pTab, zName);
93793 
93794 exit_rename_table:
93795  sqlite3SrcListDelete(db, pSrc);
93796  sqlite3DbFree(db, zName);
93797  db->flags = savedDbFlags;
93798 }
93799 
93800 /*
93801 ** This function is called after an "ALTER TABLE ... ADD" statement
93802 ** has been parsed. Argument pColDef contains the text of the new
93803 ** column definition.
93804 **
93805 ** The Table structure pParse->pNewTable was extended to include
93806 ** the new column during parsing.
93807 */
93809  Table *pNew; /* Copy of pParse->pNewTable */
93810  Table *pTab; /* Table being altered */
93811  int iDb; /* Database number */
93812  const char *zDb; /* Database name */
93813  const char *zTab; /* Table name */
93814  char *zCol; /* Null-terminated column definition */
93815  Column *pCol; /* The new column */
93816  Expr *pDflt; /* Default value for the new column */
93817  sqlite3 *db; /* The database connection; */
93818  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
93819 
93820  db = pParse->db;
93821  if( pParse->nErr || db->mallocFailed ) return;
93822  assert( v!=0 );
93823  pNew = pParse->pNewTable;
93824  assert( pNew );
93825 
93826  assert( sqlite3BtreeHoldsAllMutexes(db) );
93827  iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
93828  zDb = db->aDb[iDb].zName;
93829  zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
93830  pCol = &pNew->aCol[pNew->nCol-1];
93831  pDflt = pCol->pDflt;
93832  pTab = sqlite3FindTable(db, zTab, zDb);
93833  assert( pTab );
93834 
93835 #ifndef SQLITE_OMIT_AUTHORIZATION
93836  /* Invoke the authorization callback. */
93837  if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
93838  return;
93839  }
93840 #endif
93841 
93842  /* If the default value for the new column was specified with a
93843  ** literal NULL, then set pDflt to 0. This simplifies checking
93844  ** for an SQL NULL default below.
93845  */
93846  assert( pDflt==0 || pDflt->op==TK_SPAN );
93847  if( pDflt && pDflt->pLeft->op==TK_NULL ){
93848  pDflt = 0;
93849  }
93850 
93851  /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
93852  ** If there is a NOT NULL constraint, then the default value for the
93853  ** column must not be NULL.
93854  */
93855  if( pCol->colFlags & COLFLAG_PRIMKEY ){
93856  sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
93857  return;
93858  }
93859  if( pNew->pIndex ){
93860  sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
93861  return;
93862  }
93863  if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
93864  sqlite3ErrorMsg(pParse,
93865  "Cannot add a REFERENCES column with non-NULL default value");
93866  return;
93867  }
93868  if( pCol->notNull && !pDflt ){
93869  sqlite3ErrorMsg(pParse,
93870  "Cannot add a NOT NULL column with default value NULL");
93871  return;
93872  }
93873 
93874  /* Ensure the default expression is something that sqlite3ValueFromExpr()
93875  ** can handle (i.e. not CURRENT_TIME etc.)
93876  */
93877  if( pDflt ){
93878  sqlite3_value *pVal = 0;
93879  int rc;
93880  rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_BLOB, &pVal);
93881  assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
93882  if( rc!=SQLITE_OK ){
93883  assert( db->mallocFailed == 1 );
93884  return;
93885  }
93886  if( !pVal ){
93887  sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
93888  return;
93889  }
93890  sqlite3ValueFree(pVal);
93891  }
93892 
93893  /* Modify the CREATE TABLE statement. */
93894  zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
93895  if( zCol ){
93896  char *zEnd = &zCol[pColDef->n-1];
93897  int savedDbFlags = db->flags;
93898  while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
93899  *zEnd-- = '\0';
93900  }
93901  db->flags |= SQLITE_PreferBuiltin;
93902  sqlite3NestedParse(pParse,
93903  "UPDATE \"%w\".%s SET "
93904  "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
93905  "WHERE type = 'table' AND name = %Q",
93906  zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
93907  zTab
93908  );
93909  sqlite3DbFree(db, zCol);
93910  db->flags = savedDbFlags;
93911  }
93912 
93913  /* If the default value of the new column is NULL, then the file
93914  ** format to 2. If the default value of the new column is not NULL,
93915  ** the file format be 3. Back when this feature was first added
93916  ** in 2006, we went to the trouble to upgrade the file format to the
93917  ** minimum support values. But 10-years on, we can assume that all
93918  ** extent versions of SQLite support file-format 4, so we always and
93919  ** unconditionally upgrade to 4.
93920  */
93923 
93924  /* Reload the schema of the modified table. */
93925  reloadTableSchema(pParse, pTab, pTab->zName);
93926 }
93927 
93928 /*
93929 ** This function is called by the parser after the table-name in
93930 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
93931 ** pSrc is the full-name of the table being altered.
93932 **
93933 ** This routine makes a (partial) copy of the Table structure
93934 ** for the table being altered and sets Parse.pNewTable to point
93935 ** to it. Routines called by the parser as the column definition
93936 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
93937 ** the copy. The copy of the Table structure is deleted by tokenize.c
93938 ** after parsing is finished.
93939 **
93940 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
93941 ** coding the "ALTER TABLE ... ADD" statement.
93942 */
93944  Table *pNew;
93945  Table *pTab;
93946  Vdbe *v;
93947  int iDb;
93948  int i;
93949  int nAlloc;
93950  sqlite3 *db = pParse->db;
93951 
93952  /* Look up the table being altered. */
93953  assert( pParse->pNewTable==0 );
93954  assert( sqlite3BtreeHoldsAllMutexes(db) );
93955  if( db->mallocFailed ) goto exit_begin_add_column;
93956  pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
93957  if( !pTab ) goto exit_begin_add_column;
93958 
93959 #ifndef SQLITE_OMIT_VIRTUALTABLE
93960  if( IsVirtual(pTab) ){
93961  sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
93962  goto exit_begin_add_column;
93963  }
93964 #endif
93965 
93966  /* Make sure this is not an attempt to ALTER a view. */
93967  if( pTab->pSelect ){
93968  sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
93969  goto exit_begin_add_column;
93970  }
93971  if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
93972  goto exit_begin_add_column;
93973  }
93974 
93975  assert( pTab->addColOffset>0 );
93976  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93977 
93978  /* Put a copy of the Table struct in Parse.pNewTable for the
93979  ** sqlite3AddColumn() function and friends to modify. But modify
93980  ** the name by adding an "sqlite_altertab_" prefix. By adding this
93981  ** prefix, we insure that the name will not collide with an existing
93982  ** table because user table are not allowed to have the "sqlite_"
93983  ** prefix on their name.
93984  */
93985  pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
93986  if( !pNew ) goto exit_begin_add_column;
93987  pParse->pNewTable = pNew;
93988  pNew->nRef = 1;
93989  pNew->nCol = pTab->nCol;
93990  assert( pNew->nCol>0 );
93991  nAlloc = (((pNew->nCol-1)/8)*8)+8;
93992  assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
93993  pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
93994  pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
93995  if( !pNew->aCol || !pNew->zName ){
93996  assert( db->mallocFailed );
93997  goto exit_begin_add_column;
93998  }
93999  memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
94000  for(i=0; i<pNew->nCol; i++){
94001  Column *pCol = &pNew->aCol[i];
94002  pCol->zName = sqlite3DbStrDup(db, pCol->zName);
94003  pCol->zColl = 0;
94004  pCol->pDflt = 0;
94005  }
94006  pNew->pSchema = db->aDb[iDb].pSchema;
94007  pNew->addColOffset = pTab->addColOffset;
94008  pNew->nRef = 1;
94009 
94010  /* Begin a transaction and increment the schema cookie. */
94011  sqlite3BeginWriteOperation(pParse, 0, iDb);
94012  v = sqlite3GetVdbe(pParse);
94013  if( !v ) goto exit_begin_add_column;
94014  sqlite3ChangeCookie(pParse, iDb);
94015 
94016 exit_begin_add_column:
94017  sqlite3SrcListDelete(db, pSrc);
94018  return;
94019 }
94020 #endif /* SQLITE_ALTER_TABLE */
94021 
94022 /************** End of alter.c ***********************************************/
94023 /************** Begin file analyze.c *****************************************/
94024 /*
94025 ** 2005-07-08
94026 **
94027 ** The author disclaims copyright to this source code. In place of
94028 ** a legal notice, here is a blessing:
94029 **
94030 ** May you do good and not evil.
94031 ** May you find forgiveness for yourself and forgive others.
94032 ** May you share freely, never taking more than you give.
94033 **
94034 *************************************************************************
94035 ** This file contains code associated with the ANALYZE command.
94036 **
94037 ** The ANALYZE command gather statistics about the content of tables
94038 ** and indices. These statistics are made available to the query planner
94039 ** to help it make better decisions about how to perform queries.
94040 **
94041 ** The following system tables are or have been supported:
94042 **
94043 ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
94044 ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
94045 ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
94046 ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
94047 **
94048 ** Additional tables might be added in future releases of SQLite.
94049 ** The sqlite_stat2 table is not created or used unless the SQLite version
94050 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
94051 ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
94052 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
94053 ** created and used by SQLite versions 3.7.9 and later and with
94054 ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
94055 ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
94056 ** version of sqlite_stat3 and is only available when compiled with
94057 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
94058 ** not possible to enable both STAT3 and STAT4 at the same time. If they
94059 ** are both enabled, then STAT4 takes precedence.
94060 **
94061 ** For most applications, sqlite_stat1 provides all the statistics required
94062 ** for the query planner to make good choices.
94063 **
94064 ** Format of sqlite_stat1:
94065 **
94066 ** There is normally one row per index, with the index identified by the
94067 ** name in the idx column. The tbl column is the name of the table to
94068 ** which the index belongs. In each such row, the stat column will be
94069 ** a string consisting of a list of integers. The first integer in this
94070 ** list is the number of rows in the index. (This is the same as the
94071 ** number of rows in the table, except for partial indices.) The second
94072 ** integer is the average number of rows in the index that have the same
94073 ** value in the first column of the index. The third integer is the average
94074 ** number of rows in the index that have the same value for the first two
94075 ** columns. The N-th integer (for N>1) is the average number of rows in
94076 ** the index which have the same value for the first N-1 columns. For
94077 ** a K-column index, there will be K+1 integers in the stat column. If
94078 ** the index is unique, then the last integer will be 1.
94079 **
94080 ** The list of integers in the stat column can optionally be followed
94081 ** by the keyword "unordered". The "unordered" keyword, if it is present,
94082 ** must be separated from the last integer by a single space. If the
94083 ** "unordered" keyword is present, then the query planner assumes that
94084 ** the index is unordered and will not use the index for a range query.
94085 **
94086 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
94087 ** column contains a single integer which is the (estimated) number of
94088 ** rows in the table identified by sqlite_stat1.tbl.
94089 **
94090 ** Format of sqlite_stat2:
94091 **
94092 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
94093 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
94094 ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
94095 ** about the distribution of keys within an index. The index is identified by
94096 ** the "idx" column and the "tbl" column is the name of the table to which
94097 ** the index belongs. There are usually 10 rows in the sqlite_stat2
94098 ** table for each index.
94099 **
94100 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
94101 ** inclusive are samples of the left-most key value in the index taken at
94102 ** evenly spaced points along the index. Let the number of samples be S
94103 ** (10 in the standard build) and let C be the number of rows in the index.
94104 ** Then the sampled rows are given by:
94105 **
94106 ** rownumber = (i*C*2 + C)/(S*2)
94107 **
94108 ** For i between 0 and S-1. Conceptually, the index space is divided into
94109 ** S uniform buckets and the samples are the middle row from each bucket.
94110 **
94111 ** The format for sqlite_stat2 is recorded here for legacy reference. This
94112 ** version of SQLite does not support sqlite_stat2. It neither reads nor
94113 ** writes the sqlite_stat2 table. This version of SQLite only supports
94114 ** sqlite_stat3.
94115 **
94116 ** Format for sqlite_stat3:
94117 **
94118 ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
94119 ** sqlite_stat4 format will be described first. Further information
94120 ** about sqlite_stat3 follows the sqlite_stat4 description.
94121 **
94122 ** Format for sqlite_stat4:
94123 **
94124 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
94125 ** to aid the query planner in choosing good indices based on the values
94126 ** that indexed columns are compared against in the WHERE clauses of
94127 ** queries.
94128 **
94129 ** The sqlite_stat4 table contains multiple entries for each index.
94130 ** The idx column names the index and the tbl column is the table of the
94131 ** index. If the idx and tbl columns are the same, then the sample is
94132 ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
94133 ** binary encoding of a key from the index. The nEq column is a
94134 ** list of integers. The first integer is the approximate number
94135 ** of entries in the index whose left-most column exactly matches
94136 ** the left-most column of the sample. The second integer in nEq
94137 ** is the approximate number of entries in the index where the
94138 ** first two columns match the first two columns of the sample.
94139 ** And so forth. nLt is another list of integers that show the approximate
94140 ** number of entries that are strictly less than the sample. The first
94141 ** integer in nLt contains the number of entries in the index where the
94142 ** left-most column is less than the left-most column of the sample.
94143 ** The K-th integer in the nLt entry is the number of index entries
94144 ** where the first K columns are less than the first K columns of the
94145 ** sample. The nDLt column is like nLt except that it contains the
94146 ** number of distinct entries in the index that are less than the
94147 ** sample.
94148 **
94149 ** There can be an arbitrary number of sqlite_stat4 entries per index.
94150 ** The ANALYZE command will typically generate sqlite_stat4 tables
94151 ** that contain between 10 and 40 samples which are distributed across
94152 ** the key space, though not uniformly, and which include samples with
94153 ** large nEq values.
94154 **
94155 ** Format for sqlite_stat3 redux:
94156 **
94157 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
94158 ** looks at the left-most column of the index. The sqlite_stat3.sample
94159 ** column contains the actual value of the left-most column instead
94160 ** of a blob encoding of the complete index key as is found in
94161 ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
94162 ** all contain just a single integer which is the same as the first
94163 ** integer in the equivalent columns in sqlite_stat4.
94164 */
94165 #ifndef SQLITE_OMIT_ANALYZE
94166 /* #include "sqliteInt.h" */
94167 
94168 #if defined(SQLITE_ENABLE_STAT4)
94169 # define IsStat4 1
94170 # define IsStat3 0
94171 #elif defined(SQLITE_ENABLE_STAT3)
94172 # define IsStat4 0
94173 # define IsStat3 1
94174 #else
94175 # define IsStat4 0
94176 # define IsStat3 0
94177 # undef SQLITE_STAT4_SAMPLES
94178 # define SQLITE_STAT4_SAMPLES 1
94179 #endif
94180 #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
94181 
94182 /*
94183 ** This routine generates code that opens the sqlite_statN tables.
94184 ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
94185 ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
94186 ** appropriate compile-time options are provided.
94187 **
94188 ** If the sqlite_statN tables do not previously exist, it is created.
94189 **
94190 ** Argument zWhere may be a pointer to a buffer containing a table name,
94191 ** or it may be a NULL pointer. If it is not NULL, then all entries in
94192 ** the sqlite_statN tables associated with the named table are deleted.
94193 ** If zWhere==0, then code is generated to delete all stat table entries.
94194 */
94195 static void openStatTable(
94196  Parse *pParse, /* Parsing context */
94197  int iDb, /* The database we are looking in */
94198  int iStatCur, /* Open the sqlite_stat1 table on this cursor */
94199  const char *zWhere, /* Delete entries for this table or index */
94200  const char *zWhereType /* Either "tbl" or "idx" */
94201 ){
94202  static const struct {
94203  const char *zName;
94204  const char *zCols;
94205  } aTable[] = {
94206  { "sqlite_stat1", "tbl,idx,stat" },
94207 #if defined(SQLITE_ENABLE_STAT4)
94208  { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
94209  { "sqlite_stat3", 0 },
94210 #elif defined(SQLITE_ENABLE_STAT3)
94211  { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
94212  { "sqlite_stat4", 0 },
94213 #else
94214  { "sqlite_stat3", 0 },
94215  { "sqlite_stat4", 0 },
94216 #endif
94217  };
94218  int i;
94219  sqlite3 *db = pParse->db;
94220  Db *pDb;
94221  Vdbe *v = sqlite3GetVdbe(pParse);
94222  int aRoot[ArraySize(aTable)];
94223  u8 aCreateTbl[ArraySize(aTable)];
94224 
94225  if( v==0 ) return;
94226  assert( sqlite3BtreeHoldsAllMutexes(db) );
94227  assert( sqlite3VdbeDb(v)==db );
94228  pDb = &db->aDb[iDb];
94229 
94230  /* Create new statistic tables if they do not exist, or clear them
94231  ** if they do already exist.
94232  */
94233  for(i=0; i<ArraySize(aTable); i++){
94234  const char *zTab = aTable[i].zName;
94235  Table *pStat;
94236  if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
94237  if( aTable[i].zCols ){
94238  /* The sqlite_statN table does not exist. Create it. Note that a
94239  ** side-effect of the CREATE TABLE statement is to leave the rootpage
94240  ** of the new table in register pParse->regRoot. This is important
94241  ** because the OpenWrite opcode below will be needing it. */
94242  sqlite3NestedParse(pParse,
94243  "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
94244  );
94245  aRoot[i] = pParse->regRoot;
94246  aCreateTbl[i] = OPFLAG_P2ISREG;
94247  }
94248  }else{
94249  /* The table already exists. If zWhere is not NULL, delete all entries
94250  ** associated with the table zWhere. If zWhere is NULL, delete the
94251  ** entire contents of the table. */
94252  aRoot[i] = pStat->tnum;
94253  aCreateTbl[i] = 0;
94254  sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
94255  if( zWhere ){
94256  sqlite3NestedParse(pParse,
94257  "DELETE FROM %Q.%s WHERE %s=%Q",
94258  pDb->zName, zTab, zWhereType, zWhere
94259  );
94260  }else{
94261  /* The sqlite_stat[134] table already exists. Delete all rows. */
94262  sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
94263  }
94264  }
94265  }
94266 
94267  /* Open the sqlite_stat[134] tables for writing. */
94268  for(i=0; aTable[i].zCols; i++){
94269  assert( i<ArraySize(aTable) );
94270  sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
94271  sqlite3VdbeChangeP5(v, aCreateTbl[i]);
94272  VdbeComment((v, aTable[i].zName));
94273  }
94274 }
94275 
94276 /*
94277 ** Recommended number of samples for sqlite_stat4
94278 */
94279 #ifndef SQLITE_STAT4_SAMPLES
94280 # define SQLITE_STAT4_SAMPLES 24
94281 #endif
94282 
94283 /*
94284 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
94285 ** share an instance of the following structure to hold their state
94286 ** information.
94287 */
94288 typedef struct Stat4Accum Stat4Accum;
94289 typedef struct Stat4Sample Stat4Sample;
94290 struct Stat4Sample {
94291  tRowcnt *anEq; /* sqlite_stat4.nEq */
94292  tRowcnt *anDLt; /* sqlite_stat4.nDLt */
94293 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94294  tRowcnt *anLt; /* sqlite_stat4.nLt */
94295  union {
94296  i64 iRowid; /* Rowid in main table of the key */
94297  u8 *aRowid; /* Key for WITHOUT ROWID tables */
94298  } u;
94299  u32 nRowid; /* Sizeof aRowid[] */
94300  u8 isPSample; /* True if a periodic sample */
94301  int iCol; /* If !isPSample, the reason for inclusion */
94302  u32 iHash; /* Tiebreaker hash */
94303 #endif
94304 };
94305 struct Stat4Accum {
94306  tRowcnt nRow; /* Number of rows in the entire table */
94307  tRowcnt nPSample; /* How often to do a periodic sample */
94308  int nCol; /* Number of columns in index + pk/rowid */
94309  int nKeyCol; /* Number of index columns w/o the pk/rowid */
94310  int mxSample; /* Maximum number of samples to accumulate */
94311  Stat4Sample current; /* Current row as a Stat4Sample */
94312  u32 iPrn; /* Pseudo-random number used for sampling */
94313  Stat4Sample *aBest; /* Array of nCol best samples */
94314  int iMin; /* Index in a[] of entry with minimum score */
94315  int nSample; /* Current number of samples */
94316  int iGet; /* Index of current sample accessed by stat_get() */
94317  Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
94318  sqlite3 *db; /* Database connection, for malloc() */
94319 };
94320 
94321 /* Reclaim memory used by a Stat4Sample
94322 */
94323 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94324 static void sampleClear(sqlite3 *db, Stat4Sample *p){
94325  assert( db!=0 );
94326  if( p->nRowid ){
94327  sqlite3DbFree(db, p->u.aRowid);
94328  p->nRowid = 0;
94329  }
94330 }
94331 #endif
94332 
94333 /* Initialize the BLOB value of a ROWID
94334 */
94335 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94336 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
94337  assert( db!=0 );
94338  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94339  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
94340  if( p->u.aRowid ){
94341  p->nRowid = n;
94342  memcpy(p->u.aRowid, pData, n);
94343  }else{
94344  p->nRowid = 0;
94345  }
94346 }
94347 #endif
94348 
94349 /* Initialize the INTEGER value of a ROWID.
94350 */
94351 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94352 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
94353  assert( db!=0 );
94354  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
94355  p->nRowid = 0;
94356  p->u.iRowid = iRowid;
94357 }
94358 #endif
94359 
94360 
94361 /*
94362 ** Copy the contents of object (*pFrom) into (*pTo).
94363 */
94364 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94365 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
94366  pTo->isPSample = pFrom->isPSample;
94367  pTo->iCol = pFrom->iCol;
94368  pTo->iHash = pFrom->iHash;
94369  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
94370  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
94371  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
94372  if( pFrom->nRowid ){
94373  sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
94374  }else{
94375  sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
94376  }
94377 }
94378 #endif
94379 
94380 /*
94381 ** Reclaim all memory of a Stat4Accum structure.
94382 */
94383 static void stat4Destructor(void *pOld){
94384  Stat4Accum *p = (Stat4Accum*)pOld;
94385 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94386  int i;
94387  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
94388  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
94389  sampleClear(p->db, &p->current);
94390 #endif
94391  sqlite3DbFree(p->db, p);
94392 }
94393 
94394 /*
94395 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
94396 ** are:
94397 ** N: The number of columns in the index including the rowid/pk (note 1)
94398 ** K: The number of columns in the index excluding the rowid/pk.
94399 ** C: The number of rows in the index (note 2)
94400 **
94401 ** Note 1: In the special case of the covering index that implements a
94402 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
94403 ** total number of columns in the table.
94404 **
94405 ** Note 2: C is only used for STAT3 and STAT4.
94406 **
94407 ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
94408 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
94409 ** PRIMARY KEY of the table. The covering index that implements the
94410 ** original WITHOUT ROWID table as N==K as a special case.
94411 **
94412 ** This routine allocates the Stat4Accum object in heap memory. The return
94413 ** value is a pointer to the Stat4Accum object. The datatype of the
94414 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
94415 ** object.
94416 */
94417 static void statInit(
94418  sqlite3_context *context,
94419  int argc,
94420  sqlite3_value **argv
94421 ){
94422  Stat4Accum *p;
94423  int nCol; /* Number of columns in index being sampled */
94424  int nKeyCol; /* Number of key columns */
94425  int nColUp; /* nCol rounded up for alignment */
94426  int n; /* Bytes of space to allocate */
94427  sqlite3 *db; /* Database connection */
94428 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94429  int mxSample = SQLITE_STAT4_SAMPLES;
94430 #endif
94431 
94432  /* Decode the three function arguments */
94433  UNUSED_PARAMETER(argc);
94434  nCol = sqlite3_value_int(argv[0]);
94435  assert( nCol>0 );
94436  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
94437  nKeyCol = sqlite3_value_int(argv[1]);
94438  assert( nKeyCol<=nCol );
94439  assert( nKeyCol>0 );
94440 
94441  /* Allocate the space required for the Stat4Accum object */
94442  n = sizeof(*p)
94443  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
94444  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
94445 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94446  + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
94447  + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
94448  + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
94449 #endif
94450  ;
94451  db = sqlite3_context_db_handle(context);
94452  p = sqlite3DbMallocZero(db, n);
94453  if( p==0 ){
94454  sqlite3_result_error_nomem(context);
94455  return;
94456  }
94457 
94458  p->db = db;
94459  p->nRow = 0;
94460  p->nCol = nCol;
94461  p->nKeyCol = nKeyCol;
94462  p->current.anDLt = (tRowcnt*)&p[1];
94463  p->current.anEq = &p->current.anDLt[nColUp];
94464 
94465 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94466  {
94467  u8 *pSpace; /* Allocated space not yet assigned */
94468  int i; /* Used to iterate through p->aSample[] */
94469 
94470  p->iGet = -1;
94471  p->mxSample = mxSample;
94472  p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
94473  p->current.anLt = &p->current.anEq[nColUp];
94474  p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
94475 
94476  /* Set up the Stat4Accum.a[] and aBest[] arrays */
94477  p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
94478  p->aBest = &p->a[mxSample];
94479  pSpace = (u8*)(&p->a[mxSample+nCol]);
94480  for(i=0; i<(mxSample+nCol); i++){
94481  p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
94482  p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
94483  p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
94484  }
94485  assert( (pSpace - (u8*)p)==n );
94486 
94487  for(i=0; i<nCol; i++){
94488  p->aBest[i].iCol = i;
94489  }
94490  }
94491 #endif
94492 
94493  /* Return a pointer to the allocated object to the caller. Note that
94494  ** only the pointer (the 2nd parameter) matters. The size of the object
94495  ** (given by the 3rd parameter) is never used and can be any positive
94496  ** value. */
94497  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
94498 }
94499 static const FuncDef statInitFuncdef = {
94500  2+IsStat34, /* nArg */
94501  SQLITE_UTF8, /* funcFlags */
94502  0, /* pUserData */
94503  0, /* pNext */
94504  statInit, /* xSFunc */
94505  0, /* xFinalize */
94506  "stat_init", /* zName */
94507  {0}
94508 };
94509 
94510 #ifdef SQLITE_ENABLE_STAT4
94511 /*
94512 ** pNew and pOld are both candidate non-periodic samples selected for
94513 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
94514 ** considering only any trailing columns and the sample hash value, this
94515 ** function returns true if sample pNew is to be preferred over pOld.
94516 ** In other words, if we assume that the cardinalities of the selected
94517 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
94518 **
94519 ** This function assumes that for each argument sample, the contents of
94520 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
94521 */
94522 static int sampleIsBetterPost(
94523  Stat4Accum *pAccum,
94524  Stat4Sample *pNew,
94525  Stat4Sample *pOld
94526 ){
94527  int nCol = pAccum->nCol;
94528  int i;
94529  assert( pNew->iCol==pOld->iCol );
94530  for(i=pNew->iCol+1; i<nCol; i++){
94531  if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
94532  if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
94533  }
94534  if( pNew->iHash>pOld->iHash ) return 1;
94535  return 0;
94536 }
94537 #endif
94538 
94539 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94540 /*
94541 ** Return true if pNew is to be preferred over pOld.
94542 **
94543 ** This function assumes that for each argument sample, the contents of
94544 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
94545 */
94546 static int sampleIsBetter(
94547  Stat4Accum *pAccum,
94548  Stat4Sample *pNew,
94549  Stat4Sample *pOld
94550 ){
94551  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
94552  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
94553 
94554  assert( pOld->isPSample==0 && pNew->isPSample==0 );
94555  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
94556 
94557  if( (nEqNew>nEqOld) ) return 1;
94558 #ifdef SQLITE_ENABLE_STAT4
94559  if( nEqNew==nEqOld ){
94560  if( pNew->iCol<pOld->iCol ) return 1;
94561  return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
94562  }
94563  return 0;
94564 #else
94565  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
94566 #endif
94567 }
94568 
94569 /*
94570 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
94571 ** remove the least desirable sample from p->a[] to make room.
94572 */
94573 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
94574  Stat4Sample *pSample = 0;
94575  int i;
94576 
94577  assert( IsStat4 || nEqZero==0 );
94578 
94579 #ifdef SQLITE_ENABLE_STAT4
94580  if( pNew->isPSample==0 ){
94581  Stat4Sample *pUpgrade = 0;
94582  assert( pNew->anEq[pNew->iCol]>0 );
94583 
94584  /* This sample is being added because the prefix that ends in column
94585  ** iCol occurs many times in the table. However, if we have already
94586  ** added a sample that shares this prefix, there is no need to add
94587  ** this one. Instead, upgrade the priority of the highest priority
94588  ** existing sample that shares this prefix. */
94589  for(i=p->nSample-1; i>=0; i--){
94590  Stat4Sample *pOld = &p->a[i];
94591  if( pOld->anEq[pNew->iCol]==0 ){
94592  if( pOld->isPSample ) return;
94593  assert( pOld->iCol>pNew->iCol );
94594  assert( sampleIsBetter(p, pNew, pOld) );
94595  if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
94596  pUpgrade = pOld;
94597  }
94598  }
94599  }
94600  if( pUpgrade ){
94601  pUpgrade->iCol = pNew->iCol;
94602  pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
94603  goto find_new_min;
94604  }
94605  }
94606 #endif
94607 
94608  /* If necessary, remove sample iMin to make room for the new sample. */
94609  if( p->nSample>=p->mxSample ){
94610  Stat4Sample *pMin = &p->a[p->iMin];
94611  tRowcnt *anEq = pMin->anEq;
94612  tRowcnt *anLt = pMin->anLt;
94613  tRowcnt *anDLt = pMin->anDLt;
94614  sampleClear(p->db, pMin);
94615  memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
94616  pSample = &p->a[p->nSample-1];
94617  pSample->nRowid = 0;
94618  pSample->anEq = anEq;
94619  pSample->anDLt = anDLt;
94620  pSample->anLt = anLt;
94621  p->nSample = p->mxSample-1;
94622  }
94623 
94624  /* The "rows less-than" for the rowid column must be greater than that
94625  ** for the last sample in the p->a[] array. Otherwise, the samples would
94626  ** be out of order. */
94627 #ifdef SQLITE_ENABLE_STAT4
94628  assert( p->nSample==0
94629  || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
94630 #endif
94631 
94632  /* Insert the new sample */
94633  pSample = &p->a[p->nSample];
94634  sampleCopy(p, pSample, pNew);
94635  p->nSample++;
94636 
94637  /* Zero the first nEqZero entries in the anEq[] array. */
94638  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
94639 
94640 #ifdef SQLITE_ENABLE_STAT4
94641  find_new_min:
94642 #endif
94643  if( p->nSample>=p->mxSample ){
94644  int iMin = -1;
94645  for(i=0; i<p->mxSample; i++){
94646  if( p->a[i].isPSample ) continue;
94647  if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
94648  iMin = i;
94649  }
94650  }
94651  assert( iMin>=0 );
94652  p->iMin = iMin;
94653  }
94654 }
94655 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
94656 
94657 /*
94658 ** Field iChng of the index being scanned has changed. So at this point
94659 ** p->current contains a sample that reflects the previous row of the
94660 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
94661 ** correct at this point.
94662 */
94663 static void samplePushPrevious(Stat4Accum *p, int iChng){
94664 #ifdef SQLITE_ENABLE_STAT4
94665  int i;
94666 
94667  /* Check if any samples from the aBest[] array should be pushed
94668  ** into IndexSample.a[] at this point. */
94669  for(i=(p->nCol-2); i>=iChng; i--){
94670  Stat4Sample *pBest = &p->aBest[i];
94671  pBest->anEq[i] = p->current.anEq[i];
94672  if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
94673  sampleInsert(p, pBest, i);
94674  }
94675  }
94676 
94677  /* Update the anEq[] fields of any samples already collected. */
94678  for(i=p->nSample-1; i>=0; i--){
94679  int j;
94680  for(j=iChng; j<p->nCol; j++){
94681  if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
94682  }
94683  }
94684 #endif
94685 
94686 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
94687  if( iChng==0 ){
94688  tRowcnt nLt = p->current.anLt[0];
94689  tRowcnt nEq = p->current.anEq[0];
94690 
94691  /* Check if this is to be a periodic sample. If so, add it. */
94692  if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
94693  p->current.isPSample = 1;
94694  sampleInsert(p, &p->current, 0);
94695  p->current.isPSample = 0;
94696  }else
94697 
94698  /* Or if it is a non-periodic sample. Add it in this case too. */
94699  if( p->nSample<p->mxSample
94700  || sampleIsBetter(p, &p->current, &p->a[p->iMin])
94701  ){
94702  sampleInsert(p, &p->current, 0);
94703  }
94704  }
94705 #endif
94706 
94707 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
94708  UNUSED_PARAMETER( p );
94709  UNUSED_PARAMETER( iChng );
94710 #endif
94711 }
94712 
94713 /*
94714 ** Implementation of the stat_push SQL function: stat_push(P,C,R)
94715 ** Arguments:
94716 **
94717 ** P Pointer to the Stat4Accum object created by stat_init()
94718 ** C Index of left-most column to differ from previous row
94719 ** R Rowid for the current row. Might be a key record for
94720 ** WITHOUT ROWID tables.
94721 **
94722 ** This SQL function always returns NULL. It's purpose it to accumulate
94723 ** statistical data and/or samples in the Stat4Accum object about the
94724 ** index being analyzed. The stat_get() SQL function will later be used to
94725 ** extract relevant information for constructing the sqlite_statN tables.
94726 **
94727 ** The R parameter is only used for STAT3 and STAT4
94728 */
94729 static void statPush(
94730  sqlite3_context *context,
94731  int argc,
94732  sqlite3_value **argv
94733 ){
94734  int i;
94735 
94736  /* The three function arguments */
94737  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
94738  int iChng = sqlite3_value_int(argv[1]);
94739 
94740  UNUSED_PARAMETER( argc );
94741  UNUSED_PARAMETER( context );
94742  assert( p->nCol>0 );
94743  assert( iChng<p->nCol );
94744 
94745  if( p->nRow==0 ){
94746  /* This is the first call to this function. Do initialization. */
94747  for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
94748  }else{
94749  /* Second and subsequent calls get processed here */
94750  samplePushPrevious(p, iChng);
94751 
94752  /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
94753  ** to the current row of the index. */
94754  for(i=0; i<iChng; i++){
94755  p->current.anEq[i]++;
94756  }
94757  for(i=iChng; i<p->nCol; i++){
94758  p->current.anDLt[i]++;
94759 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94760  p->current.anLt[i] += p->current.anEq[i];
94761 #endif
94762  p->current.anEq[i] = 1;
94763  }
94764  }
94765  p->nRow++;
94766 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94767  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
94768  sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
94769  }else{
94770  sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
94771  sqlite3_value_blob(argv[2]));
94772  }
94773  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
94774 #endif
94775 
94776 #ifdef SQLITE_ENABLE_STAT4
94777  {
94778  tRowcnt nLt = p->current.anLt[p->nCol-1];
94779 
94780  /* Check if this is to be a periodic sample. If so, add it. */
94781  if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
94782  p->current.isPSample = 1;
94783  p->current.iCol = 0;
94784  sampleInsert(p, &p->current, p->nCol-1);
94785  p->current.isPSample = 0;
94786  }
94787 
94788  /* Update the aBest[] array. */
94789  for(i=0; i<(p->nCol-1); i++){
94790  p->current.iCol = i;
94791  if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
94792  sampleCopy(p, &p->aBest[i], &p->current);
94793  }
94794  }
94795  }
94796 #endif
94797 }
94798 static const FuncDef statPushFuncdef = {
94799  2+IsStat34, /* nArg */
94800  SQLITE_UTF8, /* funcFlags */
94801  0, /* pUserData */
94802  0, /* pNext */
94803  statPush, /* xSFunc */
94804  0, /* xFinalize */
94805  "stat_push", /* zName */
94806  {0}
94807 };
94808 
94809 #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
94810 #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
94811 #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
94812 #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
94813 #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
94814 
94815 /*
94816 ** Implementation of the stat_get(P,J) SQL function. This routine is
94817 ** used to query statistical information that has been gathered into
94818 ** the Stat4Accum object by prior calls to stat_push(). The P parameter
94819 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
94820 ** The content to returned is determined by the parameter J
94821 ** which is one of the STAT_GET_xxxx values defined above.
94822 **
94823 ** If neither STAT3 nor STAT4 are enabled, then J is always
94824 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
94825 ** a one-parameter function, stat_get(P), that always returns the
94826 ** stat1 table entry information.
94827 */
94828 static void statGet(
94829  sqlite3_context *context,
94830  int argc,
94831  sqlite3_value **argv
94832 ){
94833  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
94834 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94835  /* STAT3 and STAT4 have a parameter on this routine. */
94836  int eCall = sqlite3_value_int(argv[1]);
94837  assert( argc==2 );
94838  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
94839  || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
94840  || eCall==STAT_GET_NDLT
94841  );
94842  if( eCall==STAT_GET_STAT1 )
94843 #else
94844  assert( argc==1 );
94845 #endif
94846  {
94847  /* Return the value to store in the "stat" column of the sqlite_stat1
94848  ** table for this index.
94849  **
94850  ** The value is a string composed of a list of integers describing
94851  ** the index. The first integer in the list is the total number of
94852  ** entries in the index. There is one additional integer in the list
94853  ** for each indexed column. This additional integer is an estimate of
94854  ** the number of rows matched by a stabbing query on the index using
94855  ** a key with the corresponding number of fields. In other words,
94856  ** if the index is on columns (a,b) and the sqlite_stat1 value is
94857  ** "100 10 2", then SQLite estimates that:
94858  **
94859  ** * the index contains 100 rows,
94860  ** * "WHERE a=?" matches 10 rows, and
94861  ** * "WHERE a=? AND b=?" matches 2 rows.
94862  **
94863  ** If D is the count of distinct values and K is the total number of
94864  ** rows, then each estimate is computed as:
94865  **
94866  ** I = (K+D-1)/D
94867  */
94868  char *z;
94869  int i;
94870 
94871  char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
94872  if( zRet==0 ){
94873  sqlite3_result_error_nomem(context);
94874  return;
94875  }
94876 
94877  sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
94878  z = zRet + sqlite3Strlen30(zRet);
94879  for(i=0; i<p->nKeyCol; i++){
94880  u64 nDistinct = p->current.anDLt[i] + 1;
94881  u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
94882  sqlite3_snprintf(24, z, " %llu", iVal);
94883  z += sqlite3Strlen30(z);
94884  assert( p->current.anEq[i] );
94885  }
94886  assert( z[0]=='\0' && z>zRet );
94887 
94888  sqlite3_result_text(context, zRet, -1, sqlite3_free);
94889  }
94890 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94891  else if( eCall==STAT_GET_ROWID ){
94892  if( p->iGet<0 ){
94893  samplePushPrevious(p, 0);
94894  p->iGet = 0;
94895  }
94896  if( p->iGet<p->nSample ){
94897  Stat4Sample *pS = p->a + p->iGet;
94898  if( pS->nRowid==0 ){
94899  sqlite3_result_int64(context, pS->u.iRowid);
94900  }else{
94901  sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
94903  }
94904  }
94905  }else{
94906  tRowcnt *aCnt = 0;
94907 
94908  assert( p->iGet<p->nSample );
94909  switch( eCall ){
94910  case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
94911  case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
94912  default: {
94913  aCnt = p->a[p->iGet].anDLt;
94914  p->iGet++;
94915  break;
94916  }
94917  }
94918 
94919  if( IsStat3 ){
94920  sqlite3_result_int64(context, (i64)aCnt[0]);
94921  }else{
94922  char *zRet = sqlite3MallocZero(p->nCol * 25);
94923  if( zRet==0 ){
94924  sqlite3_result_error_nomem(context);
94925  }else{
94926  int i;
94927  char *z = zRet;
94928  for(i=0; i<p->nCol; i++){
94929  sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
94930  z += sqlite3Strlen30(z);
94931  }
94932  assert( z[0]=='\0' && z>zRet );
94933  z[-1] = '\0';
94934  sqlite3_result_text(context, zRet, -1, sqlite3_free);
94935  }
94936  }
94937  }
94938 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
94939 #ifndef SQLITE_DEBUG
94940  UNUSED_PARAMETER( argc );
94941 #endif
94942 }
94943 static const FuncDef statGetFuncdef = {
94944  1+IsStat34, /* nArg */
94945  SQLITE_UTF8, /* funcFlags */
94946  0, /* pUserData */
94947  0, /* pNext */
94948  statGet, /* xSFunc */
94949  0, /* xFinalize */
94950  "stat_get", /* zName */
94951  {0}
94952 };
94953 
94954 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
94955  assert( regOut!=regStat4 && regOut!=regStat4+1 );
94956 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94957  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
94958 #elif SQLITE_DEBUG
94959  assert( iParam==STAT_GET_STAT1 );
94960 #else
94961  UNUSED_PARAMETER( iParam );
94962 #endif
94963  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
94964  (char*)&statGetFuncdef, P4_FUNCDEF);
94965  sqlite3VdbeChangeP5(v, 1 + IsStat34);
94966 }
94967 
94968 /*
94969 ** Generate code to do an analysis of all indices associated with
94970 ** a single table.
94971 */
94972 static void analyzeOneTable(
94973  Parse *pParse, /* Parser context */
94974  Table *pTab, /* Table whose indices are to be analyzed */
94975  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
94976  int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
94977  int iMem, /* Available memory locations begin here */
94978  int iTab /* Next available cursor */
94979 ){
94980  sqlite3 *db = pParse->db; /* Database handle */
94981  Index *pIdx; /* An index to being analyzed */
94982  int iIdxCur; /* Cursor open on index being analyzed */
94983  int iTabCur; /* Table cursor */
94984  Vdbe *v; /* The virtual machine being built up */
94985  int i; /* Loop counter */
94986  int jZeroRows = -1; /* Jump from here if number of rows is zero */
94987  int iDb; /* Index of database containing pTab */
94988  u8 needTableCnt = 1; /* True to count the table */
94989  int regNewRowid = iMem++; /* Rowid for the inserted record */
94990  int regStat4 = iMem++; /* Register to hold Stat4Accum object */
94991  int regChng = iMem++; /* Index of changed index field */
94992 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
94993  int regRowid = iMem++; /* Rowid argument passed to stat_push() */
94994 #endif
94995  int regTemp = iMem++; /* Temporary use register */
94996  int regTabname = iMem++; /* Register containing table name */
94997  int regIdxname = iMem++; /* Register containing index name */
94998  int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
94999  int regPrev = iMem; /* MUST BE LAST (see below) */
95000 
95001  pParse->nMem = MAX(pParse->nMem, iMem);
95002  v = sqlite3GetVdbe(pParse);
95003  if( v==0 || NEVER(pTab==0) ){
95004  return;
95005  }
95006  if( pTab->tnum==0 ){
95007  /* Do not gather statistics on views or virtual tables */
95008  return;
95009  }
95010  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
95011  /* Do not gather statistics on system tables */
95012  return;
95013  }
95014  assert( sqlite3BtreeHoldsAllMutexes(db) );
95015  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95016  assert( iDb>=0 );
95017  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95018 #ifndef SQLITE_OMIT_AUTHORIZATION
95019  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
95020  db->aDb[iDb].zName ) ){
95021  return;
95022  }
95023 #endif
95024 
95025  /* Establish a read-lock on the table at the shared-cache level.
95026  ** Open a read-only cursor on the table. Also allocate a cursor number
95027  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
95028  ** this time though. */
95029  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
95030  iTabCur = iTab++;
95031  iIdxCur = iTab++;
95032  pParse->nTab = MAX(pParse->nTab, iTab);
95033  sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
95034  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
95035 
95036  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95037  int nCol; /* Number of columns in pIdx. "N" */
95038  int addrRewind; /* Address of "OP_Rewind iIdxCur" */
95039  int addrNextRow; /* Address of "next_row:" */
95040  const char *zIdxName; /* Name of the index */
95041  int nColTest; /* Number of columns to test for changes */
95042 
95043  if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
95044  if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
95045  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
95046  nCol = pIdx->nKeyCol;
95047  zIdxName = pTab->zName;
95048  nColTest = nCol - 1;
95049  }else{
95050  nCol = pIdx->nColumn;
95051  zIdxName = pIdx->zName;
95052  nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
95053  }
95054 
95055  /* Populate the register containing the index name. */
95056  sqlite3VdbeLoadString(v, regIdxname, zIdxName);
95057  VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
95058 
95059  /*
95060  ** Pseudo-code for loop that calls stat_push():
95061  **
95062  ** Rewind csr
95063  ** if eof(csr) goto end_of_scan;
95064  ** regChng = 0
95065  ** goto chng_addr_0;
95066  **
95067  ** next_row:
95068  ** regChng = 0
95069  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
95070  ** regChng = 1
95071  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
95072  ** ...
95073  ** regChng = N
95074  ** goto chng_addr_N
95075  **
95076  ** chng_addr_0:
95077  ** regPrev(0) = idx(0)
95078  ** chng_addr_1:
95079  ** regPrev(1) = idx(1)
95080  ** ...
95081  **
95082  ** endDistinctTest:
95083  ** regRowid = idx(rowid)
95084  ** stat_push(P, regChng, regRowid)
95085  ** Next csr
95086  ** if !eof(csr) goto next_row;
95087  **
95088  ** end_of_scan:
95089  */
95090 
95091  /* Make sure there are enough memory cells allocated to accommodate
95092  ** the regPrev array and a trailing rowid (the rowid slot is required
95093  ** when building a record to insert into the sample column of
95094  ** the sqlite_stat4 table. */
95095  pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
95096 
95097  /* Open a read-only cursor on the index being analyzed. */
95098  assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
95099  sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
95100  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
95101  VdbeComment((v, "%s", pIdx->zName));
95102 
95103  /* Invoke the stat_init() function. The arguments are:
95104  **
95105  ** (1) the number of columns in the index including the rowid
95106  ** (or for a WITHOUT ROWID table, the number of PK columns),
95107  ** (2) the number of columns in the key without the rowid/pk
95108  ** (3) the number of rows in the index,
95109  **
95110  **
95111  ** The third argument is only used for STAT3 and STAT4
95112  */
95113 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95114  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
95115 #endif
95116  sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
95117  sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
95118  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
95119  (char*)&statInitFuncdef, P4_FUNCDEF);
95121 
95122  /* Implementation of the following:
95123  **
95124  ** Rewind csr
95125  ** if eof(csr) goto end_of_scan;
95126  ** regChng = 0
95127  ** goto next_push_0;
95128  **
95129  */
95130  addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
95131  VdbeCoverage(v);
95132  sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
95133  addrNextRow = sqlite3VdbeCurrentAddr(v);
95134 
95135  if( nColTest>0 ){
95136  int endDistinctTest = sqlite3VdbeMakeLabel(v);
95137  int *aGotoChng; /* Array of jump instruction addresses */
95138  aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
95139  if( aGotoChng==0 ) continue;
95140 
95141  /*
95142  ** next_row:
95143  ** regChng = 0
95144  ** if( idx(0) != regPrev(0) ) goto chng_addr_0
95145  ** regChng = 1
95146  ** if( idx(1) != regPrev(1) ) goto chng_addr_1
95147  ** ...
95148  ** regChng = N
95149  ** goto endDistinctTest
95150  */
95152  addrNextRow = sqlite3VdbeCurrentAddr(v);
95153  if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
95154  /* For a single-column UNIQUE index, once we have found a non-NULL
95155  ** row, we know that all the rest will be distinct, so skip
95156  ** subsequent distinctness tests. */
95157  sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
95158  VdbeCoverage(v);
95159  }
95160  for(i=0; i<nColTest; i++){
95161  char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
95162  sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
95163  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
95164  aGotoChng[i] =
95165  sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
95167  VdbeCoverage(v);
95168  }
95169  sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
95170  sqlite3VdbeGoto(v, endDistinctTest);
95171 
95172 
95173  /*
95174  ** chng_addr_0:
95175  ** regPrev(0) = idx(0)
95176  ** chng_addr_1:
95177  ** regPrev(1) = idx(1)
95178  ** ...
95179  */
95180  sqlite3VdbeJumpHere(v, addrNextRow-1);
95181  for(i=0; i<nColTest; i++){
95182  sqlite3VdbeJumpHere(v, aGotoChng[i]);
95183  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
95184  }
95185  sqlite3VdbeResolveLabel(v, endDistinctTest);
95186  sqlite3DbFree(db, aGotoChng);
95187  }
95188 
95189  /*
95190  ** chng_addr_N:
95191  ** regRowid = idx(rowid) // STAT34 only
95192  ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
95193  ** Next csr
95194  ** if !eof(csr) goto next_row;
95195  */
95196 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95197  assert( regRowid==(regStat4+2) );
95198  if( HasRowid(pTab) ){
95199  sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
95200  }else{
95201  Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
95202  int j, k, regKey;
95203  regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
95204  for(j=0; j<pPk->nKeyCol; j++){
95205  k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
95206  assert( k>=0 && k<pTab->nCol );
95207  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
95208  VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
95209  }
95210  sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
95211  sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
95212  }
95213 #endif
95214  assert( regChng==(regStat4+1) );
95215  sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
95216  (char*)&statPushFuncdef, P4_FUNCDEF);
95218  sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
95219 
95220  /* Add the entry to the stat1 table. */
95221  callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
95222  assert( "BBB"[0]==SQLITE_AFF_TEXT );
95223  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95224  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95225  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95227 
95228  /* Add the entries to the stat3 or stat4 table. */
95229 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95230  {
95231  int regEq = regStat1;
95232  int regLt = regStat1+1;
95233  int regDLt = regStat1+2;
95234  int regSample = regStat1+3;
95235  int regCol = regStat1+4;
95236  int regSampleRowid = regCol + nCol;
95237  int addrNext;
95238  int addrIsNull;
95239  u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
95240 
95241  pParse->nMem = MAX(pParse->nMem, regCol+nCol);
95242 
95243  addrNext = sqlite3VdbeCurrentAddr(v);
95244  callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
95245  addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
95246  VdbeCoverage(v);
95247  callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
95248  callStatGet(v, regStat4, STAT_GET_NLT, regLt);
95249  callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
95250  sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
95251  /* We know that the regSampleRowid row exists because it was read by
95252  ** the previous loop. Thus the not-found jump of seekOp will never
95253  ** be taken */
95255 #ifdef SQLITE_ENABLE_STAT3
95256  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
95257 #else
95258  for(i=0; i<nCol; i++){
95259  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
95260  }
95261  sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
95262 #endif
95263  sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
95264  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
95265  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
95266  sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
95267  sqlite3VdbeJumpHere(v, addrIsNull);
95268  }
95269 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95270 
95271  /* End of analysis */
95272  sqlite3VdbeJumpHere(v, addrRewind);
95273  }
95274 
95275 
95276  /* Create a single sqlite_stat1 entry containing NULL as the index
95277  ** name and the row count as the content.
95278  */
95279  if( pOnlyIdx==0 && needTableCnt ){
95280  VdbeComment((v, "%s", pTab->zName));
95281  sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
95282  jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
95283  sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
95284  assert( "BBB"[0]==SQLITE_AFF_TEXT );
95285  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
95286  sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
95287  sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
95289  sqlite3VdbeJumpHere(v, jZeroRows);
95290  }
95291 }
95292 
95293 
95294 /*
95295 ** Generate code that will cause the most recent index analysis to
95296 ** be loaded into internal hash tables where is can be used.
95297 */
95298 static void loadAnalysis(Parse *pParse, int iDb){
95299  Vdbe *v = sqlite3GetVdbe(pParse);
95300  if( v ){
95302  }
95303 }
95304 
95305 /*
95306 ** Generate code that will do an analysis of an entire database
95307 */
95308 static void analyzeDatabase(Parse *pParse, int iDb){
95309  sqlite3 *db = pParse->db;
95310  Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
95311  HashElem *k;
95312  int iStatCur;
95313  int iMem;
95314  int iTab;
95315 
95316  sqlite3BeginWriteOperation(pParse, 0, iDb);
95317  iStatCur = pParse->nTab;
95318  pParse->nTab += 3;
95319  openStatTable(pParse, iDb, iStatCur, 0, 0);
95320  iMem = pParse->nMem+1;
95321  iTab = pParse->nTab;
95322  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95323  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
95324  Table *pTab = (Table*)sqliteHashData(k);
95325  analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
95326  }
95327  loadAnalysis(pParse, iDb);
95328 }
95329 
95330 /*
95331 ** Generate code that will do an analysis of a single table in
95332 ** a database. If pOnlyIdx is not NULL then it is a single index
95333 ** in pTab that should be analyzed.
95334 */
95335 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
95336  int iDb;
95337  int iStatCur;
95338 
95339  assert( pTab!=0 );
95340  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95341  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
95342  sqlite3BeginWriteOperation(pParse, 0, iDb);
95343  iStatCur = pParse->nTab;
95344  pParse->nTab += 3;
95345  if( pOnlyIdx ){
95346  openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
95347  }else{
95348  openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
95349  }
95350  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
95351  loadAnalysis(pParse, iDb);
95352 }
95353 
95354 /*
95355 ** Generate code for the ANALYZE command. The parser calls this routine
95356 ** when it recognizes an ANALYZE command.
95357 **
95358 ** ANALYZE -- 1
95359 ** ANALYZE <database> -- 2
95360 ** ANALYZE ?<database>.?<tablename> -- 3
95361 **
95362 ** Form 1 causes all indices in all attached databases to be analyzed.
95363 ** Form 2 analyzes all indices the single database named.
95364 ** Form 3 analyzes all indices associated with the named table.
95365 */
95366 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
95367  sqlite3 *db = pParse->db;
95368  int iDb;
95369  int i;
95370  char *z, *zDb;
95371  Table *pTab;
95372  Index *pIdx;
95373  Token *pTableName;
95374  Vdbe *v;
95375 
95376  /* Read the database schema. If an error occurs, leave an error message
95377  ** and code in pParse and return NULL. */
95378  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
95379  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
95380  return;
95381  }
95382 
95383  assert( pName2!=0 || pName1==0 );
95384  if( pName1==0 ){
95385  /* Form 1: Analyze everything */
95386  for(i=0; i<db->nDb; i++){
95387  if( i==1 ) continue; /* Do not analyze the TEMP database */
95388  analyzeDatabase(pParse, i);
95389  }
95390  }else if( pName2->n==0 ){
95391  /* Form 2: Analyze the database or table named */
95392  iDb = sqlite3FindDb(db, pName1);
95393  if( iDb>=0 ){
95394  analyzeDatabase(pParse, iDb);
95395  }else{
95396  z = sqlite3NameFromToken(db, pName1);
95397  if( z ){
95398  if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
95399  analyzeTable(pParse, pIdx->pTable, pIdx);
95400  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
95401  analyzeTable(pParse, pTab, 0);
95402  }
95403  sqlite3DbFree(db, z);
95404  }
95405  }
95406  }else{
95407  /* Form 3: Analyze the fully qualified table name */
95408  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
95409  if( iDb>=0 ){
95410  zDb = db->aDb[iDb].zName;
95411  z = sqlite3NameFromToken(db, pTableName);
95412  if( z ){
95413  if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
95414  analyzeTable(pParse, pIdx->pTable, pIdx);
95415  }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
95416  analyzeTable(pParse, pTab, 0);
95417  }
95418  sqlite3DbFree(db, z);
95419  }
95420  }
95421  }
95422  v = sqlite3GetVdbe(pParse);
95423  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
95424 }
95425 
95426 /*
95427 ** Used to pass information from the analyzer reader through to the
95428 ** callback routine.
95429 */
95433  const char *zDatabase;
95434 };
95435 
95436 /*
95437 ** The first argument points to a nul-terminated string containing a
95438 ** list of space separated integers. Read the first nOut of these into
95439 ** the array aOut[].
95440 */
95441 static void decodeIntArray(
95442  char *zIntArray, /* String containing int array to decode */
95443  int nOut, /* Number of slots in aOut[] */
95444  tRowcnt *aOut, /* Store integers here */
95445  LogEst *aLog, /* Or, if aOut==0, here */
95446  Index *pIndex /* Handle extra flags for this index, if not NULL */
95447 ){
95448  char *z = zIntArray;
95449  int c;
95450  int i;
95451  tRowcnt v;
95452 
95453 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95454  if( z==0 ) z = "";
95455 #else
95456  assert( z!=0 );
95457 #endif
95458  for(i=0; *z && i<nOut; i++){
95459  v = 0;
95460  while( (c=z[0])>='0' && c<='9' ){
95461  v = v*10 + c - '0';
95462  z++;
95463  }
95464 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95465  if( aOut ) aOut[i] = v;
95466  if( aLog ) aLog[i] = sqlite3LogEst(v);
95467 #else
95468  assert( aOut==0 );
95469  UNUSED_PARAMETER(aOut);
95470  assert( aLog!=0 );
95471  aLog[i] = sqlite3LogEst(v);
95472 #endif
95473  if( *z==' ' ) z++;
95474  }
95475 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
95476  assert( pIndex!=0 ); {
95477 #else
95478  if( pIndex ){
95479 #endif
95480  pIndex->bUnordered = 0;
95481  pIndex->noSkipScan = 0;
95482  while( z[0] ){
95483  if( sqlite3_strglob("unordered*", z)==0 ){
95484  pIndex->bUnordered = 1;
95485  }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
95486  pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
95487  }else if( sqlite3_strglob("noskipscan*", z)==0 ){
95488  pIndex->noSkipScan = 1;
95489  }
95490 #ifdef SQLITE_ENABLE_COSTMULT
95491  else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
95492  pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
95493  }
95494 #endif
95495  while( z[0]!=0 && z[0]!=' ' ) z++;
95496  while( z[0]==' ' ) z++;
95497  }
95498  }
95499 }
95500 
95501 /*
95502 ** This callback is invoked once for each index when reading the
95503 ** sqlite_stat1 table.
95504 **
95505 ** argv[0] = name of the table
95506 ** argv[1] = name of the index (might be NULL)
95507 ** argv[2] = results of analysis - on integer for each column
95508 **
95509 ** Entries for which argv[1]==NULL simply record the number of rows in
95510 ** the table.
95511 */
95512 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
95513  analysisInfo *pInfo = (analysisInfo*)pData;
95514  Index *pIndex;
95515  Table *pTable;
95516  const char *z;
95517 
95518  assert( argc==3 );
95519  UNUSED_PARAMETER2(NotUsed, argc);
95520 
95521  if( argv==0 || argv[0]==0 || argv[2]==0 ){
95522  return 0;
95523  }
95524  pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
95525  if( pTable==0 ){
95526  return 0;
95527  }
95528  if( argv[1]==0 ){
95529  pIndex = 0;
95530  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
95531  pIndex = sqlite3PrimaryKeyIndex(pTable);
95532  }else{
95533  pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
95534  }
95535  z = argv[2];
95536 
95537  if( pIndex ){
95538  tRowcnt *aiRowEst = 0;
95539  int nCol = pIndex->nKeyCol+1;
95540 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95541  /* Index.aiRowEst may already be set here if there are duplicate
95542  ** sqlite_stat1 entries for this index. In that case just clobber
95543  ** the old data with the new instead of allocating a new array. */
95544  if( pIndex->aiRowEst==0 ){
95545  pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
95546  if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
95547  }
95548  aiRowEst = pIndex->aiRowEst;
95549 #endif
95550  pIndex->bUnordered = 0;
95551  decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
95552  if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
95553  }else{
95554  Index fakeIdx;
95555  fakeIdx.szIdxRow = pTable->szTabRow;
95556 #ifdef SQLITE_ENABLE_COSTMULT
95557  fakeIdx.pTable = pTable;
95558 #endif
95559  decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
95560  pTable->szTabRow = fakeIdx.szIdxRow;
95561  }
95562 
95563  return 0;
95564 }
95565 
95566 /*
95567 ** If the Index.aSample variable is not NULL, delete the aSample[] array
95568 ** and its contents.
95569 */
95571 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95572  if( pIdx->aSample ){
95573  int j;
95574  for(j=0; j<pIdx->nSample; j++){
95575  IndexSample *p = &pIdx->aSample[j];
95576  sqlite3DbFree(db, p->p);
95577  }
95578  sqlite3DbFree(db, pIdx->aSample);
95579  }
95580  if( db && db->pnBytesFreed==0 ){
95581  pIdx->nSample = 0;
95582  pIdx->aSample = 0;
95583  }
95584 #else
95585  UNUSED_PARAMETER(db);
95586  UNUSED_PARAMETER(pIdx);
95587 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95588 }
95589 
95590 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95591 /*
95592 ** Populate the pIdx->aAvgEq[] array based on the samples currently
95593 ** stored in pIdx->aSample[].
95594 */
95595 static void initAvgEq(Index *pIdx){
95596  if( pIdx ){
95597  IndexSample *aSample = pIdx->aSample;
95598  IndexSample *pFinal = &aSample[pIdx->nSample-1];
95599  int iCol;
95600  int nCol = 1;
95601  if( pIdx->nSampleCol>1 ){
95602  /* If this is stat4 data, then calculate aAvgEq[] values for all
95603  ** sample columns except the last. The last is always set to 1, as
95604  ** once the trailing PK fields are considered all index keys are
95605  ** unique. */
95606  nCol = pIdx->nSampleCol-1;
95607  pIdx->aAvgEq[nCol] = 1;
95608  }
95609  for(iCol=0; iCol<nCol; iCol++){
95610  int nSample = pIdx->nSample;
95611  int i; /* Used to iterate through samples */
95612  tRowcnt sumEq = 0; /* Sum of the nEq values */
95613  tRowcnt avgEq = 0;
95614  tRowcnt nRow; /* Number of rows in index */
95615  i64 nSum100 = 0; /* Number of terms contributing to sumEq */
95616  i64 nDist100; /* Number of distinct values in index */
95617 
95618  if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
95619  nRow = pFinal->anLt[iCol];
95620  nDist100 = (i64)100 * pFinal->anDLt[iCol];
95621  nSample--;
95622  }else{
95623  nRow = pIdx->aiRowEst[0];
95624  nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
95625  }
95626  pIdx->nRowEst0 = nRow;
95627 
95628  /* Set nSum to the number of distinct (iCol+1) field prefixes that
95629  ** occur in the stat4 table for this index. Set sumEq to the sum of
95630  ** the nEq values for column iCol for the same set (adding the value
95631  ** only once where there exist duplicate prefixes). */
95632  for(i=0; i<nSample; i++){
95633  if( i==(pIdx->nSample-1)
95634  || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
95635  ){
95636  sumEq += aSample[i].anEq[iCol];
95637  nSum100 += 100;
95638  }
95639  }
95640 
95641  if( nDist100>nSum100 ){
95642  avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
95643  }
95644  if( avgEq==0 ) avgEq = 1;
95645  pIdx->aAvgEq[iCol] = avgEq;
95646  }
95647  }
95648 }
95649 
95650 /*
95651 ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
95652 ** is supplied instead, find the PRIMARY KEY index for that table.
95653 */
95654 static Index *findIndexOrPrimaryKey(
95655  sqlite3 *db,
95656  const char *zName,
95657  const char *zDb
95658 ){
95659  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
95660  if( pIdx==0 ){
95661  Table *pTab = sqlite3FindTable(db, zName, zDb);
95662  if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
95663  }
95664  return pIdx;
95665 }
95666 
95667 /*
95668 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
95669 ** into the relevant Index.aSample[] arrays.
95670 **
95671 ** Arguments zSql1 and zSql2 must point to SQL statements that return
95672 ** data equivalent to the following (statements are different for stat3,
95673 ** see the caller of this function for details):
95674 **
95675 ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
95676 ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
95677 **
95678 ** where %Q is replaced with the database name before the SQL is executed.
95679 */
95680 static int loadStatTbl(
95681  sqlite3 *db, /* Database handle */
95682  int bStat3, /* Assume single column records only */
95683  const char *zSql1, /* SQL statement 1 (see above) */
95684  const char *zSql2, /* SQL statement 2 (see above) */
95685  const char *zDb /* Database name (e.g. "main") */
95686 ){
95687  int rc; /* Result codes from subroutines */
95688  sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
95689  char *zSql; /* Text of the SQL statement */
95690  Index *pPrevIdx = 0; /* Previous index in the loop */
95691  IndexSample *pSample; /* A slot in pIdx->aSample[] */
95692 
95693  assert( db->lookaside.bDisable );
95694  zSql = sqlite3MPrintf(db, zSql1, zDb);
95695  if( !zSql ){
95696  return SQLITE_NOMEM_BKPT;
95697  }
95698  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
95699  sqlite3DbFree(db, zSql);
95700  if( rc ) return rc;
95701 
95702  while( sqlite3_step(pStmt)==SQLITE_ROW ){
95703  int nIdxCol = 1; /* Number of columns in stat4 records */
95704 
95705  char *zIndex; /* Index name */
95706  Index *pIdx; /* Pointer to the index object */
95707  int nSample; /* Number of samples */
95708  int nByte; /* Bytes of space required */
95709  int i; /* Bytes of space required */
95710  tRowcnt *pSpace;
95711 
95712  zIndex = (char *)sqlite3_column_text(pStmt, 0);
95713  if( zIndex==0 ) continue;
95714  nSample = sqlite3_column_int(pStmt, 1);
95715  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
95716  assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
95717  /* Index.nSample is non-zero at this point if data has already been
95718  ** loaded from the stat4 table. In this case ignore stat3 data. */
95719  if( pIdx==0 || pIdx->nSample ) continue;
95720  if( bStat3==0 ){
95721  assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
95722  if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
95723  nIdxCol = pIdx->nKeyCol;
95724  }else{
95725  nIdxCol = pIdx->nColumn;
95726  }
95727  }
95728  pIdx->nSampleCol = nIdxCol;
95729  nByte = sizeof(IndexSample) * nSample;
95730  nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
95731  nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
95732 
95733  pIdx->aSample = sqlite3DbMallocZero(db, nByte);
95734  if( pIdx->aSample==0 ){
95735  sqlite3_finalize(pStmt);
95736  return SQLITE_NOMEM_BKPT;
95737  }
95738  pSpace = (tRowcnt*)&pIdx->aSample[nSample];
95739  pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
95740  for(i=0; i<nSample; i++){
95741  pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
95742  pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
95743  pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
95744  }
95745  assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
95746  }
95747  rc = sqlite3_finalize(pStmt);
95748  if( rc ) return rc;
95749 
95750  zSql = sqlite3MPrintf(db, zSql2, zDb);
95751  if( !zSql ){
95752  return SQLITE_NOMEM_BKPT;
95753  }
95754  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
95755  sqlite3DbFree(db, zSql);
95756  if( rc ) return rc;
95757 
95758  while( sqlite3_step(pStmt)==SQLITE_ROW ){
95759  char *zIndex; /* Index name */
95760  Index *pIdx; /* Pointer to the index object */
95761  int nCol = 1; /* Number of columns in index */
95762 
95763  zIndex = (char *)sqlite3_column_text(pStmt, 0);
95764  if( zIndex==0 ) continue;
95765  pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
95766  if( pIdx==0 ) continue;
95767  /* This next condition is true if data has already been loaded from
95768  ** the sqlite_stat4 table. In this case ignore stat3 data. */
95769  nCol = pIdx->nSampleCol;
95770  if( bStat3 && nCol>1 ) continue;
95771  if( pIdx!=pPrevIdx ){
95772  initAvgEq(pPrevIdx);
95773  pPrevIdx = pIdx;
95774  }
95775  pSample = &pIdx->aSample[pIdx->nSample];
95776  decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
95777  decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
95778  decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
95779 
95780  /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
95781  ** This is in case the sample record is corrupted. In that case, the
95782  ** sqlite3VdbeRecordCompare() may read up to two varints past the
95783  ** end of the allocated buffer before it realizes it is dealing with
95784  ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
95785  ** a buffer overread. */
95786  pSample->n = sqlite3_column_bytes(pStmt, 4);
95787  pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
95788  if( pSample->p==0 ){
95789  sqlite3_finalize(pStmt);
95790  return SQLITE_NOMEM_BKPT;
95791  }
95792  memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
95793  pIdx->nSample++;
95794  }
95795  rc = sqlite3_finalize(pStmt);
95796  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
95797  return rc;
95798 }
95799 
95800 /*
95801 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
95802 ** the Index.aSample[] arrays of all indices.
95803 */
95804 static int loadStat4(sqlite3 *db, const char *zDb){
95805  int rc = SQLITE_OK; /* Result codes from subroutines */
95806 
95807  assert( db->lookaside.bDisable );
95808  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
95809  rc = loadStatTbl(db, 0,
95810  "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
95811  "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
95812  zDb
95813  );
95814  }
95815 
95816  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
95817  rc = loadStatTbl(db, 1,
95818  "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
95819  "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
95820  zDb
95821  );
95822  }
95823 
95824  return rc;
95825 }
95826 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
95827 
95828 /*
95829 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
95830 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
95831 ** arrays. The contents of sqlite_stat3/4 are used to populate the
95832 ** Index.aSample[] arrays.
95833 **
95834 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
95835 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
95836 ** during compilation and the sqlite_stat3/4 table is present, no data is
95837 ** read from it.
95838 **
95839 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
95840 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
95841 ** returned. However, in this case, data is read from the sqlite_stat1
95842 ** table (if it is present) before returning.
95843 **
95844 ** If an OOM error occurs, this function always sets db->mallocFailed.
95845 ** This means if the caller does not care about other errors, the return
95846 ** code may be ignored.
95847 */
95849  analysisInfo sInfo;
95850  HashElem *i;
95851  char *zSql;
95852  int rc = SQLITE_OK;
95853 
95854  assert( iDb>=0 && iDb<db->nDb );
95855  assert( db->aDb[iDb].pBt!=0 );
95856 
95857  /* Clear any prior statistics */
95858  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95859  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95860  Index *pIdx = sqliteHashData(i);
95861  pIdx->aiRowLogEst[0] = 0;
95862 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95863  sqlite3DeleteIndexSamples(db, pIdx);
95864  pIdx->aSample = 0;
95865 #endif
95866  }
95867 
95868  /* Load new statistics out of the sqlite_stat1 table */
95869  sInfo.db = db;
95870  sInfo.zDatabase = db->aDb[iDb].zName;
95871  if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
95872  zSql = sqlite3MPrintf(db,
95873  "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
95874  if( zSql==0 ){
95875  rc = SQLITE_NOMEM_BKPT;
95876  }else{
95877  rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
95878  sqlite3DbFree(db, zSql);
95879  }
95880  }
95881 
95882  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
95883  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
95884  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95885  Index *pIdx = sqliteHashData(i);
95886  if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
95887  }
95888 
95889  /* Load the statistics from the sqlite_stat4 table. */
95890 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
95891  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
95892  db->lookaside.bDisable++;
95893  rc = loadStat4(db, sInfo.zDatabase);
95894  db->lookaside.bDisable--;
95895  }
95896  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
95897  Index *pIdx = sqliteHashData(i);
95898  sqlite3_free(pIdx->aiRowEst);
95899  pIdx->aiRowEst = 0;
95900  }
95901 #endif
95902 
95903  if( rc==SQLITE_NOMEM ){
95904  sqlite3OomFault(db);
95905  }
95906  return rc;
95907 }
95908 
95909 
95910 #endif /* SQLITE_OMIT_ANALYZE */
95911 
95912 /************** End of analyze.c *********************************************/
95913 /************** Begin file attach.c ******************************************/
95914 /*
95915 ** 2003 April 6
95916 **
95917 ** The author disclaims copyright to this source code. In place of
95918 ** a legal notice, here is a blessing:
95919 **
95920 ** May you do good and not evil.
95921 ** May you find forgiveness for yourself and forgive others.
95922 ** May you share freely, never taking more than you give.
95923 **
95924 *************************************************************************
95925 ** This file contains code used to implement the ATTACH and DETACH commands.
95926 */
95927 /* #include "sqliteInt.h" */
95928 
95929 #ifndef SQLITE_OMIT_ATTACH
95930 /*
95931 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
95932 ** is slightly different from resolving a normal SQL expression, because simple
95933 ** identifiers are treated as strings, not possible column names or aliases.
95934 **
95935 ** i.e. if the parser sees:
95936 **
95937 ** ATTACH DATABASE abc AS def
95938 **
95939 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
95940 ** looking for columns of the same name.
95941 **
95942 ** This only applies to the root node of pExpr, so the statement:
95943 **
95944 ** ATTACH DATABASE abc||def AS 'db2'
95945 **
95946 ** will fail because neither abc or def can be resolved.
95947 */
95948 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
95949 {
95950  int rc = SQLITE_OK;
95951  if( pExpr ){
95952  if( pExpr->op!=TK_ID ){
95953  rc = sqlite3ResolveExprNames(pName, pExpr);
95954  }else{
95955  pExpr->op = TK_STRING;
95956  }
95957  }
95958  return rc;
95959 }
95960 
95961 /*
95962 ** An SQL user-function registered to do the work of an ATTACH statement. The
95963 ** three arguments to the function come directly from an attach statement:
95964 **
95965 ** ATTACH DATABASE x AS y KEY z
95966 **
95967 ** SELECT sqlite_attach(x, y, z)
95968 **
95969 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
95970 ** third argument.
95971 */
95972 static void attachFunc(
95973  sqlite3_context *context,
95974  int NotUsed,
95975  sqlite3_value **argv
95976 ){
95977  int i;
95978  int rc = 0;
95979  sqlite3 *db = sqlite3_context_db_handle(context);
95980  const char *zName;
95981  const char *zFile;
95982  char *zPath = 0;
95983  char *zErr = 0;
95984  unsigned int flags;
95985  Db *aNew;
95986  char *zErrDyn = 0;
95987  sqlite3_vfs *pVfs;
95988 
95989  UNUSED_PARAMETER(NotUsed);
95990 
95991  zFile = (const char *)sqlite3_value_text(argv[0]);
95992  zName = (const char *)sqlite3_value_text(argv[1]);
95993  if( zFile==0 ) zFile = "";
95994  if( zName==0 ) zName = "";
95995 
95996  /* Check for the following errors:
95997  **
95998  ** * Too many attached databases,
95999  ** * Transaction currently open
96000  ** * Specified database name already being used.
96001  */
96002  if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
96003  zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
96005  );
96006  goto attach_error;
96007  }
96008  if( !db->autoCommit ){
96009  zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
96010  goto attach_error;
96011  }
96012  for(i=0; i<db->nDb; i++){
96013  char *z = db->aDb[i].zName;
96014  assert( z && zName );
96015  if( sqlite3StrICmp(z, zName)==0 ){
96016  zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
96017  goto attach_error;
96018  }
96019  }
96020 
96021  /* Allocate the new entry in the db->aDb[] array and initialize the schema
96022  ** hash tables.
96023  */
96024  if( db->aDb==db->aDbStatic ){
96025  aNew = sqlite3DbMallocRawNN(db, sizeof(db->aDb[0])*3 );
96026  if( aNew==0 ) return;
96027  memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
96028  }else{
96029  aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
96030  if( aNew==0 ) return;
96031  }
96032  db->aDb = aNew;
96033  aNew = &db->aDb[db->nDb];
96034  memset(aNew, 0, sizeof(*aNew));
96035 
96036  /* Open the database file. If the btree is successfully opened, use
96037  ** it to obtain the database schema. At this point the schema may
96038  ** or may not be initialized.
96039  */
96040  flags = db->openFlags;
96041  rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
96042  if( rc!=SQLITE_OK ){
96043  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
96044  sqlite3_result_error(context, zErr, -1);
96045  sqlite3_free(zErr);
96046  return;
96047  }
96048  assert( pVfs );
96049  flags |= SQLITE_OPEN_MAIN_DB;
96050  rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
96051  sqlite3_free( zPath );
96052  db->nDb++;
96053  if( rc==SQLITE_CONSTRAINT ){
96054  rc = SQLITE_ERROR;
96055  zErrDyn = sqlite3MPrintf(db, "database is already attached");
96056  }else if( rc==SQLITE_OK ){
96057  Pager *pPager;
96058  aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
96059  if( !aNew->pSchema ){
96060  rc = SQLITE_NOMEM_BKPT;
96061  }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
96062  zErrDyn = sqlite3MPrintf(db,
96063  "attached databases must use the same text encoding as main database");
96064  rc = SQLITE_ERROR;
96065  }
96066  sqlite3BtreeEnter(aNew->pBt);
96067  pPager = sqlite3BtreePager(aNew->pBt);
96070  sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
96071 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
96074 #endif
96075  sqlite3BtreeLeave(aNew->pBt);
96076  }
96078  aNew->zName = sqlite3DbStrDup(db, zName);
96079  if( rc==SQLITE_OK && aNew->zName==0 ){
96080  rc = SQLITE_NOMEM_BKPT;
96081  }
96082 
96083 
96084 #ifdef SQLITE_HAS_CODEC
96085  if( rc==SQLITE_OK ){
96086  extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
96087  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
96088  int nKey;
96089  char *zKey;
96090  int t = sqlite3_value_type(argv[2]);
96091  switch( t ){
96092  case SQLITE_INTEGER:
96093  case SQLITE_FLOAT:
96094  zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
96095  rc = SQLITE_ERROR;
96096  break;
96097 
96098  case SQLITE_TEXT:
96099  case SQLITE_BLOB:
96100  nKey = sqlite3_value_bytes(argv[2]);
96101  zKey = (char *)sqlite3_value_blob(argv[2]);
96102  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96103  break;
96104 
96105  case SQLITE_NULL:
96106  /* No key specified. Use the key from the main database */
96107  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
96108  if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
96109  rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
96110  }
96111  break;
96112  }
96113  }
96114 #endif
96115 
96116  /* If the file was opened successfully, read the schema for the new database.
96117  ** If this fails, or if opening the file failed, then close the file and
96118  ** remove the entry from the db->aDb[] array. i.e. put everything back the way
96119  ** we found it.
96120  */
96121  if( rc==SQLITE_OK ){
96123  rc = sqlite3Init(db, &zErrDyn);
96125  }
96126 #ifdef SQLITE_USER_AUTHENTICATION
96127  if( rc==SQLITE_OK ){
96128  u8 newAuth = 0;
96129  rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
96130  if( newAuth<db->auth.authLevel ){
96131  rc = SQLITE_AUTH_USER;
96132  }
96133  }
96134 #endif
96135  if( rc ){
96136  int iDb = db->nDb - 1;
96137  assert( iDb>=2 );
96138  if( db->aDb[iDb].pBt ){
96139  sqlite3BtreeClose(db->aDb[iDb].pBt);
96140  db->aDb[iDb].pBt = 0;
96141  db->aDb[iDb].pSchema = 0;
96142  }
96144  db->nDb = iDb;
96145  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
96146  sqlite3OomFault(db);
96147  sqlite3DbFree(db, zErrDyn);
96148  zErrDyn = sqlite3MPrintf(db, "out of memory");
96149  }else if( zErrDyn==0 ){
96150  zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
96151  }
96152  goto attach_error;
96153  }
96154 
96155  return;
96156 
96157 attach_error:
96158  /* Return an error if we get here */
96159  if( zErrDyn ){
96160  sqlite3_result_error(context, zErrDyn, -1);
96161  sqlite3DbFree(db, zErrDyn);
96162  }
96163  if( rc ) sqlite3_result_error_code(context, rc);
96164 }
96165 
96166 /*
96167 ** An SQL user-function registered to do the work of an DETACH statement. The
96168 ** three arguments to the function come directly from a detach statement:
96169 **
96170 ** DETACH DATABASE x
96171 **
96172 ** SELECT sqlite_detach(x)
96173 */
96174 static void detachFunc(
96175  sqlite3_context *context,
96176  int NotUsed,
96177  sqlite3_value **argv
96178 ){
96179  const char *zName = (const char *)sqlite3_value_text(argv[0]);
96180  sqlite3 *db = sqlite3_context_db_handle(context);
96181  int i;
96182  Db *pDb = 0;
96183  char zErr[128];
96184 
96185  UNUSED_PARAMETER(NotUsed);
96186 
96187  if( zName==0 ) zName = "";
96188  for(i=0; i<db->nDb; i++){
96189  pDb = &db->aDb[i];
96190  if( pDb->pBt==0 ) continue;
96191  if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
96192  }
96193 
96194  if( i>=db->nDb ){
96195  sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
96196  goto detach_error;
96197  }
96198  if( i<2 ){
96199  sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
96200  goto detach_error;
96201  }
96202  if( !db->autoCommit ){
96203  sqlite3_snprintf(sizeof(zErr), zErr,
96204  "cannot DETACH database within transaction");
96205  goto detach_error;
96206  }
96208  sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
96209  goto detach_error;
96210  }
96211 
96212  sqlite3BtreeClose(pDb->pBt);
96213  pDb->pBt = 0;
96214  pDb->pSchema = 0;
96216  return;
96217 
96218 detach_error:
96219  sqlite3_result_error(context, zErr, -1);
96220 }
96221 
96222 /*
96223 ** This procedure generates VDBE code for a single invocation of either the
96224 ** sqlite_detach() or sqlite_attach() SQL user functions.
96225 */
96226 static void codeAttach(
96227  Parse *pParse, /* The parser context */
96228  int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
96229  FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
96230  Expr *pAuthArg, /* Expression to pass to authorization callback */
96231  Expr *pFilename, /* Name of database file */
96232  Expr *pDbname, /* Name of the database to use internally */
96233  Expr *pKey /* Database key for encryption extension */
96234 ){
96235  int rc;
96236  NameContext sName;
96237  Vdbe *v;
96238  sqlite3* db = pParse->db;
96239  int regArgs;
96240 
96241  memset(&sName, 0, sizeof(NameContext));
96242  sName.pParse = pParse;
96243 
96244  if(
96245  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
96246  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
96247  SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
96248  ){
96249  goto attach_end;
96250  }
96251 
96252 #ifndef SQLITE_OMIT_AUTHORIZATION
96253  if( pAuthArg ){
96254  char *zAuthArg;
96255  if( pAuthArg->op==TK_STRING ){
96256  zAuthArg = pAuthArg->u.zToken;
96257  }else{
96258  zAuthArg = 0;
96259  }
96260  rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
96261  if(rc!=SQLITE_OK ){
96262  goto attach_end;
96263  }
96264  }
96265 #endif /* SQLITE_OMIT_AUTHORIZATION */
96266 
96267 
96268  v = sqlite3GetVdbe(pParse);
96269  regArgs = sqlite3GetTempRange(pParse, 4);
96270  sqlite3ExprCode(pParse, pFilename, regArgs);
96271  sqlite3ExprCode(pParse, pDbname, regArgs+1);
96272  sqlite3ExprCode(pParse, pKey, regArgs+2);
96273 
96274  assert( v || db->mallocFailed );
96275  if( v ){
96276  sqlite3VdbeAddOp4(v, OP_Function0, 0, regArgs+3-pFunc->nArg, regArgs+3,
96277  (char *)pFunc, P4_FUNCDEF);
96278  assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
96279  sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
96280 
96281  /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
96282  ** statement only). For DETACH, set it to false (expire all existing
96283  ** statements).
96284  */
96286  }
96287 
96288 attach_end:
96289  sqlite3ExprDelete(db, pFilename);
96290  sqlite3ExprDelete(db, pDbname);
96291  sqlite3ExprDelete(db, pKey);
96292 }
96293 
96294 /*
96295 ** Called by the parser to compile a DETACH statement.
96296 **
96297 ** DETACH pDbname
96298 */
96299 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
96300  static const FuncDef detach_func = {
96301  1, /* nArg */
96302  SQLITE_UTF8, /* funcFlags */
96303  0, /* pUserData */
96304  0, /* pNext */
96305  detachFunc, /* xSFunc */
96306  0, /* xFinalize */
96307  "sqlite_detach", /* zName */
96308  {0}
96309  };
96310  codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
96311 }
96312 
96313 /*
96314 ** Called by the parser to compile an ATTACH statement.
96315 **
96316 ** ATTACH p AS pDbname KEY pKey
96317 */
96318 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
96319  static const FuncDef attach_func = {
96320  3, /* nArg */
96321  SQLITE_UTF8, /* funcFlags */
96322  0, /* pUserData */
96323  0, /* pNext */
96324  attachFunc, /* xSFunc */
96325  0, /* xFinalize */
96326  "sqlite_attach", /* zName */
96327  {0}
96328  };
96329  codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
96330 }
96331 #endif /* SQLITE_OMIT_ATTACH */
96332 
96333 /*
96334 ** Initialize a DbFixer structure. This routine must be called prior
96335 ** to passing the structure to one of the sqliteFixAAAA() routines below.
96336 */
96338  DbFixer *pFix, /* The fixer to be initialized */
96339  Parse *pParse, /* Error messages will be written here */
96340  int iDb, /* This is the database that must be used */
96341  const char *zType, /* "view", "trigger", or "index" */
96342  const Token *pName /* Name of the view, trigger, or index */
96343 ){
96344  sqlite3 *db;
96345 
96346  db = pParse->db;
96347  assert( db->nDb>iDb );
96348  pFix->pParse = pParse;
96349  pFix->zDb = db->aDb[iDb].zName;
96350  pFix->pSchema = db->aDb[iDb].pSchema;
96351  pFix->zType = zType;
96352  pFix->pName = pName;
96353  pFix->bVarOnly = (iDb==1);
96354 }
96355 
96356 /*
96357 ** The following set of routines walk through the parse tree and assign
96358 ** a specific database to all table references where the database name
96359 ** was left unspecified in the original SQL statement. The pFix structure
96360 ** must have been initialized by a prior call to sqlite3FixInit().
96361 **
96362 ** These routines are used to make sure that an index, trigger, or
96363 ** view in one database does not refer to objects in a different database.
96364 ** (Exception: indices, triggers, and views in the TEMP database are
96365 ** allowed to refer to anything.) If a reference is explicitly made
96366 ** to an object in a different database, an error message is added to
96367 ** pParse->zErrMsg and these routines return non-zero. If everything
96368 ** checks out, these routines return 0.
96369 */
96371  DbFixer *pFix, /* Context of the fixation */
96372  SrcList *pList /* The Source list to check and modify */
96373 ){
96374  int i;
96375  const char *zDb;
96376  struct SrcList_item *pItem;
96377 
96378  if( NEVER(pList==0) ) return 0;
96379  zDb = pFix->zDb;
96380  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
96381  if( pFix->bVarOnly==0 ){
96382  if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
96383  sqlite3ErrorMsg(pFix->pParse,
96384  "%s %T cannot reference objects in database %s",
96385  pFix->zType, pFix->pName, pItem->zDatabase);
96386  return 1;
96387  }
96388  sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
96389  pItem->zDatabase = 0;
96390  pItem->pSchema = pFix->pSchema;
96391  }
96392 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
96393  if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
96394  if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
96395 #endif
96396  }
96397  return 0;
96398 }
96399 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
96401  DbFixer *pFix, /* Context of the fixation */
96402  Select *pSelect /* The SELECT statement to be fixed to one database */
96403 ){
96404  while( pSelect ){
96405  if( sqlite3FixExprList(pFix, pSelect->pEList) ){
96406  return 1;
96407  }
96408  if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
96409  return 1;
96410  }
96411  if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
96412  return 1;
96413  }
96414  if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
96415  return 1;
96416  }
96417  if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
96418  return 1;
96419  }
96420  if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
96421  return 1;
96422  }
96423  if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
96424  return 1;
96425  }
96426  if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
96427  return 1;
96428  }
96429  pSelect = pSelect->pPrior;
96430  }
96431  return 0;
96432 }
96434  DbFixer *pFix, /* Context of the fixation */
96435  Expr *pExpr /* The expression to be fixed to one database */
96436 ){
96437  while( pExpr ){
96438  if( pExpr->op==TK_VARIABLE ){
96439  if( pFix->pParse->db->init.busy ){
96440  pExpr->op = TK_NULL;
96441  }else{
96442  sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
96443  return 1;
96444  }
96445  }
96446  if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
96447  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
96448  if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
96449  }else{
96450  if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
96451  }
96452  if( sqlite3FixExpr(pFix, pExpr->pRight) ){
96453  return 1;
96454  }
96455  pExpr = pExpr->pLeft;
96456  }
96457  return 0;
96458 }
96460  DbFixer *pFix, /* Context of the fixation */
96461  ExprList *pList /* The expression to be fixed to one database */
96462 ){
96463  int i;
96464  struct ExprList_item *pItem;
96465  if( pList==0 ) return 0;
96466  for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
96467  if( sqlite3FixExpr(pFix, pItem->pExpr) ){
96468  return 1;
96469  }
96470  }
96471  return 0;
96472 }
96473 #endif
96474 
96475 #ifndef SQLITE_OMIT_TRIGGER
96477  DbFixer *pFix, /* Context of the fixation */
96478  TriggerStep *pStep /* The trigger step be fixed to one database */
96479 ){
96480  while( pStep ){
96481  if( sqlite3FixSelect(pFix, pStep->pSelect) ){
96482  return 1;
96483  }
96484  if( sqlite3FixExpr(pFix, pStep->pWhere) ){
96485  return 1;
96486  }
96487  if( sqlite3FixExprList(pFix, pStep->pExprList) ){
96488  return 1;
96489  }
96490  pStep = pStep->pNext;
96491  }
96492  return 0;
96493 }
96494 #endif
96495 
96496 /************** End of attach.c **********************************************/
96497 /************** Begin file auth.c ********************************************/
96498 /*
96499 ** 2003 January 11
96500 **
96501 ** The author disclaims copyright to this source code. In place of
96502 ** a legal notice, here is a blessing:
96503 **
96504 ** May you do good and not evil.
96505 ** May you find forgiveness for yourself and forgive others.
96506 ** May you share freely, never taking more than you give.
96507 **
96508 *************************************************************************
96509 ** This file contains code used to implement the sqlite3_set_authorizer()
96510 ** API. This facility is an optional feature of the library. Embedded
96511 ** systems that do not need this facility may omit it by recompiling
96512 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
96513 */
96514 /* #include "sqliteInt.h" */
96515 
96516 /*
96517 ** All of the code in this file may be omitted by defining a single
96518 ** macro.
96519 */
96520 #ifndef SQLITE_OMIT_AUTHORIZATION
96521 
96522 /*
96523 ** Set or clear the access authorization function.
96524 **
96525 ** The access authorization function is be called during the compilation
96526 ** phase to verify that the user has read and/or write access permission on
96527 ** various fields of the database. The first argument to the auth function
96528 ** is a copy of the 3rd argument to this routine. The second argument
96529 ** to the auth function is one of these constants:
96530 **
96531 ** SQLITE_CREATE_INDEX
96532 ** SQLITE_CREATE_TABLE
96533 ** SQLITE_CREATE_TEMP_INDEX
96534 ** SQLITE_CREATE_TEMP_TABLE
96535 ** SQLITE_CREATE_TEMP_TRIGGER
96536 ** SQLITE_CREATE_TEMP_VIEW
96537 ** SQLITE_CREATE_TRIGGER
96538 ** SQLITE_CREATE_VIEW
96539 ** SQLITE_DELETE
96540 ** SQLITE_DROP_INDEX
96541 ** SQLITE_DROP_TABLE
96542 ** SQLITE_DROP_TEMP_INDEX
96543 ** SQLITE_DROP_TEMP_TABLE
96544 ** SQLITE_DROP_TEMP_TRIGGER
96545 ** SQLITE_DROP_TEMP_VIEW
96546 ** SQLITE_DROP_TRIGGER
96547 ** SQLITE_DROP_VIEW
96548 ** SQLITE_INSERT
96549 ** SQLITE_PRAGMA
96550 ** SQLITE_READ
96551 ** SQLITE_SELECT
96552 ** SQLITE_TRANSACTION
96553 ** SQLITE_UPDATE
96554 **
96555 ** The third and fourth arguments to the auth function are the name of
96556 ** the table and the column that are being accessed. The auth function
96557 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
96558 ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
96559 ** means that the SQL statement will never-run - the sqlite3_exec() call
96560 ** will return with an error. SQLITE_IGNORE means that the SQL statement
96561 ** should run but attempts to read the specified column will return NULL
96562 ** and attempts to write the column will be ignored.
96563 **
96564 ** Setting the auth function to NULL disables this hook. The default
96565 ** setting of the auth function is NULL.
96566 */
96568  sqlite3 *db,
96569  int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
96570  void *pArg
96571 ){
96572 #ifdef SQLITE_ENABLE_API_ARMOR
96573  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
96574 #endif
96576  db->xAuth = (sqlite3_xauth)xAuth;
96577  db->pAuthArg = pArg;
96580  return SQLITE_OK;
96581 }
96582 
96583 /*
96584 ** Write an error message into pParse->zErrMsg that explains that the
96585 ** user-supplied authorization function returned an illegal value.
96586 */
96587 static void sqliteAuthBadReturnCode(Parse *pParse){
96588  sqlite3ErrorMsg(pParse, "authorizer malfunction");
96589  pParse->rc = SQLITE_ERROR;
96590 }
96591 
96592 /*
96593 ** Invoke the authorization callback for permission to read column zCol from
96594 ** table zTab in database zDb. This function assumes that an authorization
96595 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
96596 **
96597 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
96598 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
96599 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
96600 */
96602  Parse *pParse, /* The parser context */
96603  const char *zTab, /* Table name */
96604  const char *zCol, /* Column name */
96605  int iDb /* Index of containing database. */
96606 ){
96607  sqlite3 *db = pParse->db; /* Database handle */
96608  char *zDb = db->aDb[iDb].zName; /* Name of attached database */
96609  int rc; /* Auth callback return code */
96610 
96611  rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
96612 #ifdef SQLITE_USER_AUTHENTICATION
96613  ,db->auth.zAuthUser
96614 #endif
96615  );
96616  if( rc==SQLITE_DENY ){
96617  if( db->nDb>2 || iDb!=0 ){
96618  sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
96619  }else{
96620  sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
96621  }
96622  pParse->rc = SQLITE_AUTH;
96623  }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
96624  sqliteAuthBadReturnCode(pParse);
96625  }
96626  return rc;
96627 }
96628 
96629 /*
96630 ** The pExpr should be a TK_COLUMN expression. The table referred to
96631 ** is in pTabList or else it is the NEW or OLD table of a trigger.
96632 ** Check to see if it is OK to read this particular column.
96633 **
96634 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
96635 ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
96636 ** then generate an error.
96637 */
96639  Parse *pParse, /* The parser context */
96640  Expr *pExpr, /* The expression to check authorization on */
96641  Schema *pSchema, /* The schema of the expression */
96642  SrcList *pTabList /* All table that pExpr might refer to */
96643 ){
96644  sqlite3 *db = pParse->db;
96645  Table *pTab = 0; /* The table being read */
96646  const char *zCol; /* Name of the column of the table */
96647  int iSrc; /* Index in pTabList->a[] of table being read */
96648  int iDb; /* The index of the database the expression refers to */
96649  int iCol; /* Index of column in table */
96650 
96651  if( db->xAuth==0 ) return;
96652  iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
96653  if( iDb<0 ){
96654  /* An attempt to read a column out of a subquery or other
96655  ** temporary table. */
96656  return;
96657  }
96658 
96659  assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
96660  if( pExpr->op==TK_TRIGGER ){
96661  pTab = pParse->pTriggerTab;
96662  }else{
96663  assert( pTabList );
96664  for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
96665  if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
96666  pTab = pTabList->a[iSrc].pTab;
96667  break;
96668  }
96669  }
96670  }
96671  iCol = pExpr->iColumn;
96672  if( NEVER(pTab==0) ) return;
96673 
96674  if( iCol>=0 ){
96675  assert( iCol<pTab->nCol );
96676  zCol = pTab->aCol[iCol].zName;
96677  }else if( pTab->iPKey>=0 ){
96678  assert( pTab->iPKey<pTab->nCol );
96679  zCol = pTab->aCol[pTab->iPKey].zName;
96680  }else{
96681  zCol = "ROWID";
96682  }
96683  assert( iDb>=0 && iDb<db->nDb );
96684  if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
96685  pExpr->op = TK_NULL;
96686  }
96687 }
96688 
96689 /*
96690 ** Do an authorization check using the code and arguments given. Return
96691 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
96692 ** is returned, then the error count and error message in pParse are
96693 ** modified appropriately.
96694 */
96696  Parse *pParse,
96697  int code,
96698  const char *zArg1,
96699  const char *zArg2,
96700  const char *zArg3
96701 ){
96702  sqlite3 *db = pParse->db;
96703  int rc;
96704 
96705  /* Don't do any authorization checks if the database is initialising
96706  ** or if the parser is being invoked from within sqlite3_declare_vtab.
96707  */
96708  if( db->init.busy || IN_DECLARE_VTAB ){
96709  return SQLITE_OK;
96710  }
96711 
96712  if( db->xAuth==0 ){
96713  return SQLITE_OK;
96714  }
96715  rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
96716 #ifdef SQLITE_USER_AUTHENTICATION
96717  ,db->auth.zAuthUser
96718 #endif
96719  );
96720  if( rc==SQLITE_DENY ){
96721  sqlite3ErrorMsg(pParse, "not authorized");
96722  pParse->rc = SQLITE_AUTH;
96723  }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
96724  rc = SQLITE_DENY;
96725  sqliteAuthBadReturnCode(pParse);
96726  }
96727  return rc;
96728 }
96729 
96730 /*
96731 ** Push an authorization context. After this routine is called, the
96732 ** zArg3 argument to authorization callbacks will be zContext until
96733 ** popped. Or if pParse==0, this routine is a no-op.
96734 */
96736  Parse *pParse,
96737  AuthContext *pContext,
96738  const char *zContext
96739 ){
96740  assert( pParse );
96741  pContext->pParse = pParse;
96742  pContext->zAuthContext = pParse->zAuthContext;
96743  pParse->zAuthContext = zContext;
96744 }
96745 
96746 /*
96747 ** Pop an authorization context that was previously pushed
96748 ** by sqlite3AuthContextPush
96749 */
96751  if( pContext->pParse ){
96752  pContext->pParse->zAuthContext = pContext->zAuthContext;
96753  pContext->pParse = 0;
96754  }
96755 }
96756 
96757 #endif /* SQLITE_OMIT_AUTHORIZATION */
96758 
96759 /************** End of auth.c ************************************************/
96760 /************** Begin file build.c *******************************************/
96761 /*
96762 ** 2001 September 15
96763 **
96764 ** The author disclaims copyright to this source code. In place of
96765 ** a legal notice, here is a blessing:
96766 **
96767 ** May you do good and not evil.
96768 ** May you find forgiveness for yourself and forgive others.
96769 ** May you share freely, never taking more than you give.
96770 **
96771 *************************************************************************
96772 ** This file contains C code routines that are called by the SQLite parser
96773 ** when syntax rules are reduced. The routines in this file handle the
96774 ** following kinds of SQL syntax:
96775 **
96776 ** CREATE TABLE
96777 ** DROP TABLE
96778 ** CREATE INDEX
96779 ** DROP INDEX
96780 ** creating ID lists
96781 ** BEGIN TRANSACTION
96782 ** COMMIT
96783 ** ROLLBACK
96784 */
96785 /* #include "sqliteInt.h" */
96786 
96787 #ifndef SQLITE_OMIT_SHARED_CACHE
96788 /*
96789 ** The TableLock structure is only used by the sqlite3TableLock() and
96790 ** codeTableLocks() functions.
96791 */
96792 struct TableLock {
96793  int iDb; /* The database containing the table to be locked */
96794  int iTab; /* The root page of the table to be locked */
96795  u8 isWriteLock; /* True for write lock. False for a read lock */
96796  const char *zName; /* Name of the table */
96797 };
96798 
96799 /*
96800 ** Record the fact that we want to lock a table at run-time.
96801 **
96802 ** The table to be locked has root page iTab and is found in database iDb.
96803 ** A read or a write lock can be taken depending on isWritelock.
96804 **
96805 ** This routine just records the fact that the lock is desired. The
96806 ** code to make the lock occur is generated by a later call to
96807 ** codeTableLocks() which occurs during sqlite3FinishCoding().
96808 */
96810  Parse *pParse, /* Parsing context */
96811  int iDb, /* Index of the database containing the table to lock */
96812  int iTab, /* Root page number of the table to be locked */
96813  u8 isWriteLock, /* True for a write lock */
96814  const char *zName /* Name of the table to be locked */
96815 ){
96816  Parse *pToplevel = sqlite3ParseToplevel(pParse);
96817  int i;
96818  int nBytes;
96819  TableLock *p;
96820  assert( iDb>=0 );
96821 
96822  for(i=0; i<pToplevel->nTableLock; i++){
96823  p = &pToplevel->aTableLock[i];
96824  if( p->iDb==iDb && p->iTab==iTab ){
96825  p->isWriteLock = (p->isWriteLock || isWriteLock);
96826  return;
96827  }
96828  }
96829 
96830  nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
96831  pToplevel->aTableLock =
96832  sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
96833  if( pToplevel->aTableLock ){
96834  p = &pToplevel->aTableLock[pToplevel->nTableLock++];
96835  p->iDb = iDb;
96836  p->iTab = iTab;
96837  p->isWriteLock = isWriteLock;
96838  p->zName = zName;
96839  }else{
96840  pToplevel->nTableLock = 0;
96841  sqlite3OomFault(pToplevel->db);
96842  }
96843 }
96844 
96845 /*
96846 ** Code an OP_TableLock instruction for each table locked by the
96847 ** statement (configured by calls to sqlite3TableLock()).
96848 */
96849 static void codeTableLocks(Parse *pParse){
96850  int i;
96851  Vdbe *pVdbe;
96852 
96853  pVdbe = sqlite3GetVdbe(pParse);
96854  assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
96855 
96856  for(i=0; i<pParse->nTableLock; i++){
96857  TableLock *p = &pParse->aTableLock[i];
96858  int p1 = p->iDb;
96859  sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
96860  p->zName, P4_STATIC);
96861  }
96862 }
96863 #else
96864  #define codeTableLocks(x)
96865 #endif
96866 
96867 /*
96868 ** Return TRUE if the given yDbMask object is empty - if it contains no
96869 ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
96870 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
96871 */
96872 #if SQLITE_MAX_ATTACHED>30
96873 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
96874  int i;
96875  for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
96876  return 1;
96877 }
96878 #endif
96879 
96880 /*
96881 ** This routine is called after a single SQL statement has been
96882 ** parsed and a VDBE program to execute that statement has been
96883 ** prepared. This routine puts the finishing touches on the
96884 ** VDBE program and resets the pParse structure for the next
96885 ** parse.
96886 **
96887 ** Note that if an error occurred, it might be the case that
96888 ** no VDBE code was generated.
96889 */
96891  sqlite3 *db;
96892  Vdbe *v;
96893 
96894  assert( pParse->pToplevel==0 );
96895  db = pParse->db;
96896  if( pParse->nested ) return;
96897  if( db->mallocFailed || pParse->nErr ){
96898  if( pParse->rc==SQLITE_OK ) pParse->rc = SQLITE_ERROR;
96899  return;
96900  }
96901 
96902  /* Begin by generating some termination code at the end of the
96903  ** vdbe program
96904  */
96905  v = sqlite3GetVdbe(pParse);
96906  assert( !pParse->isMultiWrite
96907  || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
96908  if( v ){
96909  while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
96911 
96912 #if SQLITE_USER_AUTHENTICATION
96913  if( pParse->nTableLock>0 && db->init.busy==0 ){
96914  sqlite3UserAuthInit(db);
96915  if( db->auth.authLevel<UAUTH_User ){
96916  pParse->rc = SQLITE_AUTH_USER;
96917  sqlite3ErrorMsg(pParse, "user not authenticated");
96918  return;
96919  }
96920  }
96921 #endif
96922 
96923  /* The cookie mask contains one bit for each database file open.
96924  ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
96925  ** set for each database that is used. Generate code to start a
96926  ** transaction on each used database and to verify the schema cookie
96927  ** on each used database.
96928  */
96929  if( db->mallocFailed==0
96930  && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
96931  ){
96932  int iDb, i;
96933  assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
96934  sqlite3VdbeJumpHere(v, 0);
96935  for(iDb=0; iDb<db->nDb; iDb++){
96936  if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
96937  sqlite3VdbeUsesBtree(v, iDb);
96939  OP_Transaction, /* Opcode */
96940  iDb, /* P1 */
96941  DbMaskTest(pParse->writeMask,iDb), /* P2 */
96942  pParse->cookieValue[iDb], /* P3 */
96943  db->aDb[iDb].pSchema->iGeneration /* P4 */
96944  );
96945  if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
96946  VdbeComment((v,
96947  "usesStmtJournal=%d", pParse->mayAbort && pParse->isMultiWrite));
96948  }
96949 #ifndef SQLITE_OMIT_VIRTUALTABLE
96950  for(i=0; i<pParse->nVtabLock; i++){
96951  char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
96952  sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
96953  }
96954  pParse->nVtabLock = 0;
96955 #endif
96956 
96957  /* Once all the cookies have been verified and transactions opened,
96958  ** obtain the required table-locks. This is a no-op unless the
96959  ** shared-cache feature is enabled.
96960  */
96961  codeTableLocks(pParse);
96962 
96963  /* Initialize any AUTOINCREMENT data structures required.
96964  */
96965  sqlite3AutoincrementBegin(pParse);
96966 
96967  /* Code constant expressions that where factored out of inner loops */
96968  if( pParse->pConstExpr ){
96969  ExprList *pEL = pParse->pConstExpr;
96970  pParse->okConstFactor = 0;
96971  for(i=0; i<pEL->nExpr; i++){
96972  sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
96973  }
96974  }
96975 
96976  /* Finally, jump back to the beginning of the executable code. */
96977  sqlite3VdbeGoto(v, 1);
96978  }
96979  }
96980 
96981 
96982  /* Get the VDBE program ready for execution
96983  */
96984  if( v && pParse->nErr==0 && !db->mallocFailed ){
96985  assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
96986  /* A minimum of one cursor is required if autoincrement is used
96987  * See ticket [a696379c1f08866] */
96988  if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
96989  sqlite3VdbeMakeReady(v, pParse);
96990  pParse->rc = SQLITE_DONE;
96991  }else{
96992  pParse->rc = SQLITE_ERROR;
96993  }
96994 
96995  /* We are done with this Parse object. There is no need to de-initialize it */
96996 #if 0
96997  pParse->colNamesSet = 0;
96998  pParse->nTab = 0;
96999  pParse->nMem = 0;
97000  pParse->nSet = 0;
97001  pParse->nVar = 0;
97002  DbMaskZero(pParse->cookieMask);
97003 #endif
97004 }
97005 
97006 /*
97007 ** Run the parser and code generator recursively in order to generate
97008 ** code for the SQL statement given onto the end of the pParse context
97009 ** currently under construction. When the parser is run recursively
97010 ** this way, the final OP_Halt is not appended and other initialization
97011 ** and finalization steps are omitted because those are handling by the
97012 ** outermost parser.
97013 **
97014 ** Not everything is nestable. This facility is designed to permit
97015 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
97016 ** care if you decide to try to use this routine for some other purposes.
97017 */
97018 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
97019  va_list ap;
97020  char *zSql;
97021  char *zErrMsg = 0;
97022  sqlite3 *db = pParse->db;
97023 # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
97024  char saveBuf[SAVE_SZ];
97025 
97026  if( pParse->nErr ) return;
97027  assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
97028  va_start(ap, zFormat);
97029  zSql = sqlite3VMPrintf(db, zFormat, ap);
97030  va_end(ap);
97031  if( zSql==0 ){
97032  return; /* A malloc must have failed */
97033  }
97034  pParse->nested++;
97035  memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
97036  memset(&pParse->nVar, 0, SAVE_SZ);
97037  sqlite3RunParser(pParse, zSql, &zErrMsg);
97038  sqlite3DbFree(db, zErrMsg);
97039  sqlite3DbFree(db, zSql);
97040  memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
97041  pParse->nested--;
97042 }
97043 
97044 #if SQLITE_USER_AUTHENTICATION
97045 /*
97046 ** Return TRUE if zTable is the name of the system table that stores the
97047 ** list of users and their access credentials.
97048 */
97049 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
97050  return sqlite3_stricmp(zTable, "sqlite_user")==0;
97051 }
97052 #endif
97053 
97054 /*
97055 ** Locate the in-memory structure that describes a particular database
97056 ** table given the name of that table and (optionally) the name of the
97057 ** database containing the table. Return NULL if not found.
97058 **
97059 ** If zDatabase is 0, all databases are searched for the table and the
97060 ** first matching table is returned. (No checking for duplicate table
97061 ** names is done.) The search order is TEMP first, then MAIN, then any
97062 ** auxiliary databases added using the ATTACH command.
97063 **
97064 ** See also sqlite3LocateTable().
97065 */
97066 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
97067  Table *p = 0;
97068  int i;
97069 
97070  /* All mutexes are required for schema access. Make sure we hold them. */
97071  assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97072 #if SQLITE_USER_AUTHENTICATION
97073  /* Only the admin user is allowed to know that the sqlite_user table
97074  ** exists */
97075  if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
97076  return 0;
97077  }
97078 #endif
97079  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97080  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
97081  if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
97082  assert( sqlite3SchemaMutexHeld(db, j, 0) );
97083  p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
97084  if( p ) break;
97085  }
97086  return p;
97087 }
97088 
97089 /*
97090 ** Locate the in-memory structure that describes a particular database
97091 ** table given the name of that table and (optionally) the name of the
97092 ** database containing the table. Return NULL if not found. Also leave an
97093 ** error message in pParse->zErrMsg.
97094 **
97095 ** The difference between this routine and sqlite3FindTable() is that this
97096 ** routine leaves an error message in pParse->zErrMsg where
97097 ** sqlite3FindTable() does not.
97098 */
97100  Parse *pParse, /* context in which to report errors */
97101  int isView, /* True if looking for a VIEW rather than a TABLE */
97102  const char *zName, /* Name of the table we are looking for */
97103  const char *zDbase /* Name of the database. Might be NULL */
97104 ){
97105  Table *p;
97106 
97107  /* Read the database schema. If an error occurs, leave an error message
97108  ** and code in pParse and return NULL. */
97109  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97110  return 0;
97111  }
97112 
97113  p = sqlite3FindTable(pParse->db, zName, zDbase);
97114  if( p==0 ){
97115  const char *zMsg = isView ? "no such view" : "no such table";
97116 #ifndef SQLITE_OMIT_VIRTUALTABLE
97117  if( sqlite3FindDbName(pParse->db, zDbase)<1 ){
97118  /* If zName is the not the name of a table in the schema created using
97119  ** CREATE, then check to see if it is the name of an virtual table that
97120  ** can be an eponymous virtual table. */
97121  Module *pMod = (Module*)sqlite3HashFind(&pParse->db->aModule, zName);
97122  if( pMod && sqlite3VtabEponymousTableInit(pParse, pMod) ){
97123  return pMod->pEpoTab;
97124  }
97125  }
97126 #endif
97127  if( zDbase ){
97128  sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
97129  }else{
97130  sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
97131  }
97132  pParse->checkSchema = 1;
97133  }
97134 
97135  return p;
97136 }
97137 
97138 /*
97139 ** Locate the table identified by *p.
97140 **
97141 ** This is a wrapper around sqlite3LocateTable(). The difference between
97142 ** sqlite3LocateTable() and this function is that this function restricts
97143 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
97144 ** non-NULL if it is part of a view or trigger program definition. See
97145 ** sqlite3FixSrcList() for details.
97146 */
97148  Parse *pParse,
97149  int isView,
97150  struct SrcList_item *p
97151 ){
97152  const char *zDb;
97153  assert( p->pSchema==0 || p->zDatabase==0 );
97154  if( p->pSchema ){
97155  int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
97156  zDb = pParse->db->aDb[iDb].zName;
97157  }else{
97158  zDb = p->zDatabase;
97159  }
97160  return sqlite3LocateTable(pParse, isView, p->zName, zDb);
97161 }
97162 
97163 /*
97164 ** Locate the in-memory structure that describes
97165 ** a particular index given the name of that index
97166 ** and the name of the database that contains the index.
97167 ** Return NULL if not found.
97168 **
97169 ** If zDatabase is 0, all databases are searched for the
97170 ** table and the first matching index is returned. (No checking
97171 ** for duplicate index names is done.) The search order is
97172 ** TEMP first, then MAIN, then any auxiliary databases added
97173 ** using the ATTACH command.
97174 */
97175 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
97176  Index *p = 0;
97177  int i;
97178  /* All mutexes are required for schema access. Make sure we hold them. */
97179  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
97180  for(i=OMIT_TEMPDB; i<db->nDb; i++){
97181  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
97182  Schema *pSchema = db->aDb[j].pSchema;
97183  assert( pSchema );
97184  if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
97185  assert( sqlite3SchemaMutexHeld(db, j, 0) );
97186  p = sqlite3HashFind(&pSchema->idxHash, zName);
97187  if( p ) break;
97188  }
97189  return p;
97190 }
97191 
97192 /*
97193 ** Reclaim the memory used by an index
97194 */
97195 static void freeIndex(sqlite3 *db, Index *p){
97196 #ifndef SQLITE_OMIT_ANALYZE
97198 #endif
97201  sqlite3DbFree(db, p->zColAff);
97202  if( p->isResized ) sqlite3DbFree(db, (void *)p->azColl);
97203 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
97204  sqlite3_free(p->aiRowEst);
97205 #endif
97206  sqlite3DbFree(db, p);
97207 }
97208 
97209 /*
97210 ** For the index called zIdxName which is found in the database iDb,
97211 ** unlike that index from its Table then remove the index from
97212 ** the index hash table and free all memory structures associated
97213 ** with the index.
97214 */
97215 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
97216  Index *pIndex;
97217  Hash *pHash;
97218 
97219  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97220  pHash = &db->aDb[iDb].pSchema->idxHash;
97221  pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
97222  if( ALWAYS(pIndex) ){
97223  if( pIndex->pTable->pIndex==pIndex ){
97224  pIndex->pTable->pIndex = pIndex->pNext;
97225  }else{
97226  Index *p;
97227  /* Justification of ALWAYS(); The index must be on the list of
97228  ** indices. */
97229  p = pIndex->pTable->pIndex;
97230  while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
97231  if( ALWAYS(p && p->pNext==pIndex) ){
97232  p->pNext = pIndex->pNext;
97233  }
97234  }
97235  freeIndex(db, pIndex);
97236  }
97237  db->flags |= SQLITE_InternChanges;
97238 }
97239 
97240 /*
97241 ** Look through the list of open database files in db->aDb[] and if
97242 ** any have been closed, remove them from the list. Reallocate the
97243 ** db->aDb[] structure to a smaller size, if possible.
97244 **
97245 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
97246 ** are never candidates for being collapsed.
97247 */
97249  int i, j;
97250  for(i=j=2; i<db->nDb; i++){
97251  struct Db *pDb = &db->aDb[i];
97252  if( pDb->pBt==0 ){
97253  sqlite3DbFree(db, pDb->zName);
97254  pDb->zName = 0;
97255  continue;
97256  }
97257  if( j<i ){
97258  db->aDb[j] = db->aDb[i];
97259  }
97260  j++;
97261  }
97262  db->nDb = j;
97263  if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
97264  memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
97265  sqlite3DbFree(db, db->aDb);
97266  db->aDb = db->aDbStatic;
97267  }
97268 }
97269 
97270 /*
97271 ** Reset the schema for the database at index iDb. Also reset the
97272 ** TEMP schema.
97273 */
97275  Db *pDb;
97276  assert( iDb<db->nDb );
97277 
97278  /* Case 1: Reset the single schema identified by iDb */
97279  pDb = &db->aDb[iDb];
97280  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97281  assert( pDb->pSchema!=0 );
97283 
97284  /* If any database other than TEMP is reset, then also reset TEMP
97285  ** since TEMP might be holding triggers that reference tables in the
97286  ** other database.
97287  */
97288  if( iDb!=1 ){
97289  pDb = &db->aDb[1];
97290  assert( pDb->pSchema!=0 );
97292  }
97293  return;
97294 }
97295 
97296 /*
97297 ** Erase all schema information from all attached databases (including
97298 ** "main" and "temp") for a single database connection.
97299 */
97301  int i;
97303  for(i=0; i<db->nDb; i++){
97304  Db *pDb = &db->aDb[i];
97305  if( pDb->pSchema ){
97307  }
97308  }
97309  db->flags &= ~SQLITE_InternChanges;
97313 }
97314 
97315 /*
97316 ** This routine is called when a commit occurs.
97317 */
97319  db->flags &= ~SQLITE_InternChanges;
97320 }
97321 
97322 /*
97323 ** Delete memory allocated for the column names of a table or view (the
97324 ** Table.aCol[] array).
97325 */
97327  int i;
97328  Column *pCol;
97329  assert( pTable!=0 );
97330  if( (pCol = pTable->aCol)!=0 ){
97331  for(i=0; i<pTable->nCol; i++, pCol++){
97332  sqlite3DbFree(db, pCol->zName);
97333  sqlite3ExprDelete(db, pCol->pDflt);
97334  sqlite3DbFree(db, pCol->zColl);
97335  }
97336  sqlite3DbFree(db, pTable->aCol);
97337  }
97338 }
97339 
97340 /*
97341 ** Remove the memory data structures associated with the given
97342 ** Table. No changes are made to disk by this routine.
97343 **
97344 ** This routine just deletes the data structure. It does not unlink
97345 ** the table data structure from the hash table. But it does destroy
97346 ** memory structures of the indices and foreign keys associated with
97347 ** the table.
97348 **
97349 ** The db parameter is optional. It is needed if the Table object
97350 ** contains lookaside memory. (Table objects in the schema do not use
97351 ** lookaside memory, but some ephemeral Table objects do.) Or the
97352 ** db parameter can be used with db->pnBytesFreed to measure the memory
97353 ** used by the Table object.
97354 */
97355 static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable){
97356  Index *pIndex, *pNext;
97357  TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
97358 
97359  /* Record the number of outstanding lookaside allocations in schema Tables
97360  ** prior to doing any free() operations. Since schema Tables do not use
97361  ** lookaside, this number should not change. */
97362  TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
97363  db->lookaside.nOut : 0 );
97364 
97365  /* Delete all indices associated with this table. */
97366  for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
97367  pNext = pIndex->pNext;
97368  assert( pIndex->pSchema==pTable->pSchema );
97369  if( !db || db->pnBytesFreed==0 ){
97370  char *zName = pIndex->zName;
97371  TESTONLY ( Index *pOld = ) sqlite3HashInsert(
97372  &pIndex->pSchema->idxHash, zName, 0
97373  );
97374  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
97375  assert( pOld==pIndex || pOld==0 );
97376  }
97377  freeIndex(db, pIndex);
97378  }
97379 
97380  /* Delete any foreign keys attached to this table. */
97381  sqlite3FkDelete(db, pTable);
97382 
97383  /* Delete the Table structure itself.
97384  */
97385  sqlite3DeleteColumnNames(db, pTable);
97386  sqlite3DbFree(db, pTable->zName);
97387  sqlite3DbFree(db, pTable->zColAff);
97388  sqlite3SelectDelete(db, pTable->pSelect);
97389  sqlite3ExprListDelete(db, pTable->pCheck);
97390 #ifndef SQLITE_OMIT_VIRTUALTABLE
97391  sqlite3VtabClear(db, pTable);
97392 #endif
97393  sqlite3DbFree(db, pTable);
97394 
97395  /* Verify that no lookaside memory was used by schema tables */
97396  assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
97397 }
97399  /* Do not delete the table until the reference count reaches zero. */
97400  if( !pTable ) return;
97401  if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
97402  deleteTable(db, pTable);
97403 }
97404 
97405 
97406 /*
97407 ** Unlink the given table from the hash tables and the delete the
97408 ** table structure with all its indices and foreign keys.
97409 */
97410 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
97411  Table *p;
97412  Db *pDb;
97413 
97414  assert( db!=0 );
97415  assert( iDb>=0 && iDb<db->nDb );
97416  assert( zTabName );
97417  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97418  testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
97419  pDb = &db->aDb[iDb];
97420  p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
97421  sqlite3DeleteTable(db, p);
97422  db->flags |= SQLITE_InternChanges;
97423 }
97424 
97425 /*
97426 ** Given a token, return a string that consists of the text of that
97427 ** token. Space to hold the returned string
97428 ** is obtained from sqliteMalloc() and must be freed by the calling
97429 ** function.
97430 **
97431 ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
97432 ** surround the body of the token are removed.
97433 **
97434 ** Tokens are often just pointers into the original SQL text and so
97435 ** are not \000 terminated and are not persistent. The returned string
97436 ** is \000 terminated and is persistent.
97437 */
97439  char *zName;
97440  if( pName ){
97441  zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
97442  sqlite3Dequote(zName);
97443  }else{
97444  zName = 0;
97445  }
97446  return zName;
97447 }
97448 
97449 /*
97450 ** Open the sqlite_master table stored in database number iDb for
97451 ** writing. The table is opened using cursor 0.
97452 */
97454  Vdbe *v = sqlite3GetVdbe(p);
97455  sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
97457  if( p->nTab==0 ){
97458  p->nTab = 1;
97459  }
97460 }
97461 
97462 /*
97463 ** Parameter zName points to a nul-terminated buffer containing the name
97464 ** of a database ("main", "temp" or the name of an attached db). This
97465 ** function returns the index of the named database in db->aDb[], or
97466 ** -1 if the named db cannot be found.
97467 */
97468 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
97469  int i = -1; /* Database number */
97470  if( zName ){
97471  Db *pDb;
97472  for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
97473  if( 0==sqlite3StrICmp(pDb->zName, zName) ) break;
97474  }
97475  }
97476  return i;
97477 }
97478 
97479 /*
97480 ** The token *pName contains the name of a database (either "main" or
97481 ** "temp" or the name of an attached db). This routine returns the
97482 ** index of the named database in db->aDb[], or -1 if the named db
97483 ** does not exist.
97484 */
97486  int i; /* Database number */
97487  char *zName; /* Name we are searching for */
97488  zName = sqlite3NameFromToken(db, pName);
97489  i = sqlite3FindDbName(db, zName);
97490  sqlite3DbFree(db, zName);
97491  return i;
97492 }
97493 
97494 /* The table or view or trigger name is passed to this routine via tokens
97495 ** pName1 and pName2. If the table name was fully qualified, for example:
97496 **
97497 ** CREATE TABLE xxx.yyy (...);
97498 **
97499 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
97500 ** the table name is not fully qualified, i.e.:
97501 **
97502 ** CREATE TABLE yyy(...);
97503 **
97504 ** Then pName1 is set to "yyy" and pName2 is "".
97505 **
97506 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
97507 ** pName2) that stores the unqualified table name. The index of the
97508 ** database "xxx" is returned.
97509 */
97511  Parse *pParse, /* Parsing and code generating context */
97512  Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
97513  Token *pName2, /* The "yyy" in the name "xxx.yyy" */
97514  Token **pUnqual /* Write the unqualified object name here */
97515 ){
97516  int iDb; /* Database holding the object */
97517  sqlite3 *db = pParse->db;
97518 
97519  assert( pName2!=0 );
97520  if( pName2->n>0 ){
97521  if( db->init.busy ) {
97522  sqlite3ErrorMsg(pParse, "corrupt database");
97523  return -1;
97524  }
97525  *pUnqual = pName2;
97526  iDb = sqlite3FindDb(db, pName1);
97527  if( iDb<0 ){
97528  sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
97529  return -1;
97530  }
97531  }else{
97532  assert( db->init.iDb==0 || db->init.busy );
97533  iDb = db->init.iDb;
97534  *pUnqual = pName1;
97535  }
97536  return iDb;
97537 }
97538 
97539 /*
97540 ** This routine is used to check if the UTF-8 string zName is a legal
97541 ** unqualified name for a new schema object (table, index, view or
97542 ** trigger). All names are legal except those that begin with the string
97543 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
97544 ** is reserved for internal use.
97545 */
97546 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
97547  if( !pParse->db->init.busy && pParse->nested==0
97548  && (pParse->db->flags & SQLITE_WriteSchema)==0
97549  && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
97550  sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
97551  return SQLITE_ERROR;
97552  }
97553  return SQLITE_OK;
97554 }
97555 
97556 /*
97557 ** Return the PRIMARY KEY index of a table
97558 */
97560  Index *p;
97561  for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
97562  return p;
97563 }
97564 
97565 /*
97566 ** Return the column of index pIdx that corresponds to table
97567 ** column iCol. Return -1 if not found.
97568 */
97570  int i;
97571  for(i=0; i<pIdx->nColumn; i++){
97572  if( iCol==pIdx->aiColumn[i] ) return i;
97573  }
97574  return -1;
97575 }
97576 
97577 /*
97578 ** Begin constructing a new table representation in memory. This is
97579 ** the first of several action routines that get called in response
97580 ** to a CREATE TABLE statement. In particular, this routine is called
97581 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
97582 ** flag is true if the table should be stored in the auxiliary database
97583 ** file instead of in the main database file. This is normally the case
97584 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
97585 ** CREATE and TABLE.
97586 **
97587 ** The new table record is initialized and put in pParse->pNewTable.
97588 ** As more of the CREATE TABLE statement is parsed, additional action
97589 ** routines will be called to add more information to this record.
97590 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
97591 ** is called to complete the construction of the new table record.
97592 */
97594  Parse *pParse, /* Parser context */
97595  Token *pName1, /* First part of the name of the table or view */
97596  Token *pName2, /* Second part of the name of the table or view */
97597  int isTemp, /* True if this is a TEMP table */
97598  int isView, /* True if this is a VIEW */
97599  int isVirtual, /* True if this is a VIRTUAL table */
97600  int noErr /* Do nothing if table already exists */
97601 ){
97602  Table *pTable;
97603  char *zName = 0; /* The name of the new table */
97604  sqlite3 *db = pParse->db;
97605  Vdbe *v;
97606  int iDb; /* Database number to create the table in */
97607  Token *pName; /* Unqualified name of the table to create */
97608 
97609  if( db->init.busy && db->init.newTnum==1 ){
97610  /* Special case: Parsing the sqlite_master or sqlite_temp_master schema */
97611  iDb = db->init.iDb;
97612  zName = sqlite3DbStrDup(db, SCHEMA_TABLE(iDb));
97613  pName = pName1;
97614  }else{
97615  /* The common case */
97616  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
97617  if( iDb<0 ) return;
97618  if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
97619  /* If creating a temp table, the name may not be qualified. Unless
97620  ** the database name is "temp" anyway. */
97621  sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
97622  return;
97623  }
97624  if( !OMIT_TEMPDB && isTemp ) iDb = 1;
97625  zName = sqlite3NameFromToken(db, pName);
97626  }
97627  pParse->sNameToken = *pName;
97628  if( zName==0 ) return;
97629  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
97630  goto begin_table_error;
97631  }
97632  if( db->init.iDb==1 ) isTemp = 1;
97633 #ifndef SQLITE_OMIT_AUTHORIZATION
97634  assert( isTemp==0 || isTemp==1 );
97635  assert( isView==0 || isView==1 );
97636  {
97637  static const u8 aCode[] = {
97642  };
97643  char *zDb = db->aDb[iDb].zName;
97644  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
97645  goto begin_table_error;
97646  }
97647  if( !isVirtual && sqlite3AuthCheck(pParse, (int)aCode[isTemp+2*isView],
97648  zName, 0, zDb) ){
97649  goto begin_table_error;
97650  }
97651  }
97652 #endif
97653 
97654  /* Make sure the new table name does not collide with an existing
97655  ** index or table name in the same database. Issue an error message if
97656  ** it does. The exception is if the statement being parsed was passed
97657  ** to an sqlite3_declare_vtab() call. In that case only the column names
97658  ** and types will be used, so there is no need to test for namespace
97659  ** collisions.
97660  */
97661  if( !IN_DECLARE_VTAB ){
97662  char *zDb = db->aDb[iDb].zName;
97663  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
97664  goto begin_table_error;
97665  }
97666  pTable = sqlite3FindTable(db, zName, zDb);
97667  if( pTable ){
97668  if( !noErr ){
97669  sqlite3ErrorMsg(pParse, "table %T already exists", pName);
97670  }else{
97671  assert( !db->init.busy || CORRUPT_DB );
97672  sqlite3CodeVerifySchema(pParse, iDb);
97673  }
97674  goto begin_table_error;
97675  }
97676  if( sqlite3FindIndex(db, zName, zDb)!=0 ){
97677  sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
97678  goto begin_table_error;
97679  }
97680  }
97681 
97682  pTable = sqlite3DbMallocZero(db, sizeof(Table));
97683  if( pTable==0 ){
97684  assert( db->mallocFailed );
97685  pParse->rc = SQLITE_NOMEM_BKPT;
97686  pParse->nErr++;
97687  goto begin_table_error;
97688  }
97689  pTable->zName = zName;
97690  pTable->iPKey = -1;
97691  pTable->pSchema = db->aDb[iDb].pSchema;
97692  pTable->nRef = 1;
97693  pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
97694  assert( pParse->pNewTable==0 );
97695  pParse->pNewTable = pTable;
97696 
97697  /* If this is the magic sqlite_sequence table used by autoincrement,
97698  ** then record a pointer to this table in the main database structure
97699  ** so that INSERT can find the table easily.
97700  */
97701 #ifndef SQLITE_OMIT_AUTOINCREMENT
97702  if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
97703  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
97704  pTable->pSchema->pSeqTab = pTable;
97705  }
97706 #endif
97707 
97708  /* Begin generating the code that will insert the table record into
97709  ** the SQLITE_MASTER table. Note in particular that we must go ahead
97710  ** and allocate the record number for the table entry now. Before any
97711  ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
97712  ** indices to be created and the table record must come before the
97713  ** indices. Hence, the record number for the table must be allocated
97714  ** now.
97715  */
97716  if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
97717  int addr1;
97718  int fileFormat;
97719  int reg1, reg2, reg3;
97720  /* nullRow[] is an OP_Record encoding of a row containing 5 NULLs */
97721  static const char nullRow[] = { 6, 0, 0, 0, 0, 0 };
97722  sqlite3BeginWriteOperation(pParse, 1, iDb);
97723 
97724 #ifndef SQLITE_OMIT_VIRTUALTABLE
97725  if( isVirtual ){
97727  }
97728 #endif
97729 
97730  /* If the file format and encoding in the database have not been set,
97731  ** set them now.
97732  */
97733  reg1 = pParse->regRowid = ++pParse->nMem;
97734  reg2 = pParse->regRoot = ++pParse->nMem;
97735  reg3 = ++pParse->nMem;
97737  sqlite3VdbeUsesBtree(v, iDb);
97738  addr1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
97739  fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
97741  sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, fileFormat);
97743  sqlite3VdbeJumpHere(v, addr1);
97744 
97745  /* This just creates a place-holder record in the sqlite_master table.
97746  ** The record created does not contain anything yet. It will be replaced
97747  ** by the real entry in code generated at sqlite3EndTable().
97748  **
97749  ** The rowid for the new entry is left in register pParse->regRowid.
97750  ** The root page number of the new table is left in reg pParse->regRoot.
97751  ** The rowid and root page number values are needed by the code that
97752  ** sqlite3EndTable will generate.
97753  */
97754 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
97755  if( isView || isVirtual ){
97756  sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
97757  }else
97758 #endif
97759  {
97760  pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
97761  }
97762  sqlite3OpenMasterTable(pParse, iDb);
97763  sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
97764  sqlite3VdbeAddOp4(v, OP_Blob, 6, reg3, 0, nullRow, P4_STATIC);
97765  sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
97768  }
97769 
97770  /* Normal (non-error) return. */
97771  return;
97772 
97773  /* If an error occurs, we jump here */
97774 begin_table_error:
97775  sqlite3DbFree(db, zName);
97776  return;
97777 }
97778 
97779 /* Set properties of a table column based on the (magical)
97780 ** name of the column.
97781 */
97782 #if SQLITE_ENABLE_HIDDEN_COLUMNS
97784  if( sqlite3_strnicmp(pCol->zName, "__hidden__", 10)==0 ){
97785  pCol->colFlags |= COLFLAG_HIDDEN;
97786  }else if( pTab && pCol!=pTab->aCol && (pCol[-1].colFlags & COLFLAG_HIDDEN) ){
97787  pTab->tabFlags |= TF_OOOHidden;
97788  }
97789 }
97790 #endif
97791 
97792 
97793 /*
97794 ** Add a new column to the table currently being constructed.
97795 **
97796 ** The parser calls this routine once for each column declaration
97797 ** in a CREATE TABLE statement. sqlite3StartTable() gets called
97798 ** first to get things going. Then this routine is called for each
97799 ** column.
97800 */
97801 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName, Token *pType){
97802  Table *p;
97803  int i;
97804  char *z;
97805  char *zType;
97806  Column *pCol;
97807  sqlite3 *db = pParse->db;
97808  if( (p = pParse->pNewTable)==0 ) return;
97809 #if SQLITE_MAX_COLUMN
97810  if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
97811  sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
97812  return;
97813  }
97814 #endif
97815  z = sqlite3DbMallocRaw(db, pName->n + pType->n + 2);
97816  if( z==0 ) return;
97817  memcpy(z, pName->z, pName->n);
97818  z[pName->n] = 0;
97819  sqlite3Dequote(z);
97820  for(i=0; i<p->nCol; i++){
97821  if( sqlite3_stricmp(z, p->aCol[i].zName)==0 ){
97822  sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
97823  sqlite3DbFree(db, z);
97824  return;
97825  }
97826  }
97827  if( (p->nCol & 0x7)==0 ){
97828  Column *aNew;
97829  aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
97830  if( aNew==0 ){
97831  sqlite3DbFree(db, z);
97832  return;
97833  }
97834  p->aCol = aNew;
97835  }
97836  pCol = &p->aCol[p->nCol];
97837  memset(pCol, 0, sizeof(p->aCol[0]));
97838  pCol->zName = z;
97840 
97841  if( pType->n==0 ){
97842  /* If there is no type specified, columns have the default affinity
97843  ** 'BLOB'. */
97844  pCol->affinity = SQLITE_AFF_BLOB;
97845  pCol->szEst = 1;
97846  }else{
97847  zType = z + sqlite3Strlen30(z) + 1;
97848  memcpy(zType, pType->z, pType->n);
97849  zType[pType->n] = 0;
97850  sqlite3Dequote(zType);
97851  pCol->affinity = sqlite3AffinityType(zType, &pCol->szEst);
97852  pCol->colFlags |= COLFLAG_HASTYPE;
97853  }
97854  p->nCol++;
97855  pParse->constraintName.n = 0;
97856 }
97857 
97858 /*
97859 ** This routine is called by the parser while in the middle of
97860 ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
97861 ** been seen on a column. This routine sets the notNull flag on
97862 ** the column currently under construction.
97863 */
97864 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
97865  Table *p;
97866  p = pParse->pNewTable;
97867  if( p==0 || NEVER(p->nCol<1) ) return;
97868  p->aCol[p->nCol-1].notNull = (u8)onError;
97869 }
97870 
97871 /*
97872 ** Scan the column type name zType (length nType) and return the
97873 ** associated affinity type.
97874 **
97875 ** This routine does a case-independent search of zType for the
97876 ** substrings in the following table. If one of the substrings is
97877 ** found, the corresponding affinity is returned. If zType contains
97878 ** more than one of the substrings, entries toward the top of
97879 ** the table take priority. For example, if zType is 'BLOBINT',
97880 ** SQLITE_AFF_INTEGER is returned.
97881 **
97882 ** Substring | Affinity
97883 ** --------------------------------
97884 ** 'INT' | SQLITE_AFF_INTEGER
97885 ** 'CHAR' | SQLITE_AFF_TEXT
97886 ** 'CLOB' | SQLITE_AFF_TEXT
97887 ** 'TEXT' | SQLITE_AFF_TEXT
97888 ** 'BLOB' | SQLITE_AFF_BLOB
97889 ** 'REAL' | SQLITE_AFF_REAL
97890 ** 'FLOA' | SQLITE_AFF_REAL
97891 ** 'DOUB' | SQLITE_AFF_REAL
97892 **
97893 ** If none of the substrings in the above table are found,
97894 ** SQLITE_AFF_NUMERIC is returned.
97895 */
97896 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
97897  u32 h = 0;
97898  char aff = SQLITE_AFF_NUMERIC;
97899  const char *zChar = 0;
97900 
97901  assert( zIn!=0 );
97902  while( zIn[0] ){
97903  h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
97904  zIn++;
97905  if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
97906  aff = SQLITE_AFF_TEXT;
97907  zChar = zIn;
97908  }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
97909  aff = SQLITE_AFF_TEXT;
97910  }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
97911  aff = SQLITE_AFF_TEXT;
97912  }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
97913  && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
97914  aff = SQLITE_AFF_BLOB;
97915  if( zIn[0]=='(' ) zChar = zIn;
97916 #ifndef SQLITE_OMIT_FLOATING_POINT
97917  }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
97918  && aff==SQLITE_AFF_NUMERIC ){
97919  aff = SQLITE_AFF_REAL;
97920  }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
97921  && aff==SQLITE_AFF_NUMERIC ){
97922  aff = SQLITE_AFF_REAL;
97923  }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
97924  && aff==SQLITE_AFF_NUMERIC ){
97925  aff = SQLITE_AFF_REAL;
97926 #endif
97927  }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
97928  aff = SQLITE_AFF_INTEGER;
97929  break;
97930  }
97931  }
97932 
97933  /* If pszEst is not NULL, store an estimate of the field size. The
97934  ** estimate is scaled so that the size of an integer is 1. */
97935  if( pszEst ){
97936  *pszEst = 1; /* default size is approx 4 bytes */
97937  if( aff<SQLITE_AFF_NUMERIC ){
97938  if( zChar ){
97939  while( zChar[0] ){
97940  if( sqlite3Isdigit(zChar[0]) ){
97941  int v = 0;
97942  sqlite3GetInt32(zChar, &v);
97943  v = v/4 + 1;
97944  if( v>255 ) v = 255;
97945  *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
97946  break;
97947  }
97948  zChar++;
97949  }
97950  }else{
97951  *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
97952  }
97953  }
97954  }
97955  return aff;
97956 }
97957 
97958 /*
97959 ** The expression is the default value for the most recently added column
97960 ** of the table currently under construction.
97961 **
97962 ** Default value expressions must be constant. Raise an exception if this
97963 ** is not the case.
97964 **
97965 ** This routine is called by the parser while in the middle of
97966 ** parsing a CREATE TABLE statement.
97967 */
97969  Table *p;
97970  Column *pCol;
97971  sqlite3 *db = pParse->db;
97972  p = pParse->pNewTable;
97973  if( p!=0 ){
97974  pCol = &(p->aCol[p->nCol-1]);
97975  if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
97976  sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
97977  pCol->zName);
97978  }else{
97979  /* A copy of pExpr is used instead of the original, as pExpr contains
97980  ** tokens that point to volatile memory. The 'span' of the expression
97981  ** is required by pragma table_info.
97982  */
97983  Expr x;
97984  sqlite3ExprDelete(db, pCol->pDflt);
97985  memset(&x, 0, sizeof(x));
97986  x.op = TK_SPAN;
97987  x.u.zToken = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
97988  (int)(pSpan->zEnd - pSpan->zStart));
97989  x.pLeft = pSpan->pExpr;
97990  x.flags = EP_Skip;
97991  pCol->pDflt = sqlite3ExprDup(db, &x, EXPRDUP_REDUCE);
97992  sqlite3DbFree(db, x.u.zToken);
97993  }
97994  }
97995  sqlite3ExprDelete(db, pSpan->pExpr);
97996 }
97997 
97998 /*
97999 ** Backwards Compatibility Hack:
98000 **
98001 ** Historical versions of SQLite accepted strings as column names in
98002 ** indexes and PRIMARY KEY constraints and in UNIQUE constraints. Example:
98003 **
98004 ** CREATE TABLE xyz(a,b,c,d,e,PRIMARY KEY('a'),UNIQUE('b','c' COLLATE trim)
98005 ** CREATE INDEX abc ON xyz('c','d' DESC,'e' COLLATE nocase DESC);
98006 **
98007 ** This is goofy. But to preserve backwards compatibility we continue to
98008 ** accept it. This routine does the necessary conversion. It converts
98009 ** the expression given in its argument from a TK_STRING into a TK_ID
98010 ** if the expression is just a TK_STRING with an optional COLLATE clause.
98011 ** If the epxression is anything other than TK_STRING, the expression is
98012 ** unchanged.
98013 */
98014 static void sqlite3StringToId(Expr *p){
98015  if( p->op==TK_STRING ){
98016  p->op = TK_ID;
98017  }else if( p->op==TK_COLLATE && p->pLeft->op==TK_STRING ){
98018  p->pLeft->op = TK_ID;
98019  }
98020 }
98021 
98022 /*
98023 ** Designate the PRIMARY KEY for the table. pList is a list of names
98024 ** of columns that form the primary key. If pList is NULL, then the
98025 ** most recently added column of the table is the primary key.
98026 **
98027 ** A table can have at most one primary key. If the table already has
98028 ** a primary key (and this is the second primary key) then create an
98029 ** error.
98030 **
98031 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
98032 ** then we will try to use that column as the rowid. Set the Table.iPKey
98033 ** field of the table under construction to be the index of the
98034 ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
98035 ** no INTEGER PRIMARY KEY.
98036 **
98037 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
98038 ** index for the key. No index is created for INTEGER PRIMARY KEYs.
98039 */
98041  Parse *pParse, /* Parsing context */
98042  ExprList *pList, /* List of field names to be indexed */
98043  int onError, /* What to do with a uniqueness conflict */
98044  int autoInc, /* True if the AUTOINCREMENT keyword is present */
98045  int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
98046 ){
98047  Table *pTab = pParse->pNewTable;
98048  Column *pCol = 0;
98049  int iCol = -1, i;
98050  int nTerm;
98051  if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
98052  if( pTab->tabFlags & TF_HasPrimaryKey ){
98053  sqlite3ErrorMsg(pParse,
98054  "table \"%s\" has more than one primary key", pTab->zName);
98055  goto primary_key_exit;
98056  }
98057  pTab->tabFlags |= TF_HasPrimaryKey;
98058  if( pList==0 ){
98059  iCol = pTab->nCol - 1;
98060  pCol = &pTab->aCol[iCol];
98061  pCol->colFlags |= COLFLAG_PRIMKEY;
98062  nTerm = 1;
98063  }else{
98064  nTerm = pList->nExpr;
98065  for(i=0; i<nTerm; i++){
98066  Expr *pCExpr = sqlite3ExprSkipCollate(pList->a[i].pExpr);
98067  assert( pCExpr!=0 );
98068  sqlite3StringToId(pCExpr);
98069  if( pCExpr->op==TK_ID ){
98070  const char *zCName = pCExpr->u.zToken;
98071  for(iCol=0; iCol<pTab->nCol; iCol++){
98072  if( sqlite3StrICmp(zCName, pTab->aCol[iCol].zName)==0 ){
98073  pCol = &pTab->aCol[iCol];
98074  pCol->colFlags |= COLFLAG_PRIMKEY;
98075  break;
98076  }
98077  }
98078  }
98079  }
98080  }
98081  if( nTerm==1
98082  && pCol
98083  && sqlite3StrICmp(sqlite3ColumnType(pCol,""), "INTEGER")==0
98084  && sortOrder!=SQLITE_SO_DESC
98085  ){
98086  pTab->iPKey = iCol;
98087  pTab->keyConf = (u8)onError;
98088  assert( autoInc==0 || autoInc==1 );
98089  pTab->tabFlags |= autoInc*TF_Autoincrement;
98090  if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
98091  }else if( autoInc ){
98092 #ifndef SQLITE_OMIT_AUTOINCREMENT
98093  sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
98094  "INTEGER PRIMARY KEY");
98095 #endif
98096  }else{
98097  Index *p;
98098  p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
98099  0, sortOrder, 0);
98100  if( p ){
98102  }
98103  pList = 0;
98104  }
98105 
98106 primary_key_exit:
98107  sqlite3ExprListDelete(pParse->db, pList);
98108  return;
98109 }
98110 
98111 /*
98112 ** Add a new CHECK constraint to the table currently under construction.
98113 */
98115  Parse *pParse, /* Parsing context */
98116  Expr *pCheckExpr /* The check expression */
98117 ){
98118 #ifndef SQLITE_OMIT_CHECK
98119  Table *pTab = pParse->pNewTable;
98120  sqlite3 *db = pParse->db;
98121  if( pTab && !IN_DECLARE_VTAB
98122  && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
98123  ){
98124  pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
98125  if( pParse->constraintName.n ){
98126  sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
98127  }
98128  }else
98129 #endif
98130  {
98131  sqlite3ExprDelete(pParse->db, pCheckExpr);
98132  }
98133 }
98134 
98135 /*
98136 ** Set the collation function of the most recently parsed table column
98137 ** to the CollSeq given.
98138 */
98140  Table *p;
98141  int i;
98142  char *zColl; /* Dequoted name of collation sequence */
98143  sqlite3 *db;
98144 
98145  if( (p = pParse->pNewTable)==0 ) return;
98146  i = p->nCol-1;
98147  db = pParse->db;
98148  zColl = sqlite3NameFromToken(db, pToken);
98149  if( !zColl ) return;
98150 
98151  if( sqlite3LocateCollSeq(pParse, zColl) ){
98152  Index *pIdx;
98153  sqlite3DbFree(db, p->aCol[i].zColl);
98154  p->aCol[i].zColl = zColl;
98155 
98156  /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
98157  ** then an index may have been created on this column before the
98158  ** collation type was added. Correct this if it is the case.
98159  */
98160  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
98161  assert( pIdx->nKeyCol==1 );
98162  if( pIdx->aiColumn[0]==i ){
98163  pIdx->azColl[0] = p->aCol[i].zColl;
98164  }
98165  }
98166  }else{
98167  sqlite3DbFree(db, zColl);
98168  }
98169 }
98170 
98171 /*
98172 ** This function returns the collation sequence for database native text
98173 ** encoding identified by the string zName, length nName.
98174 **
98175 ** If the requested collation sequence is not available, or not available
98176 ** in the database native encoding, the collation factory is invoked to
98177 ** request it. If the collation factory does not supply such a sequence,
98178 ** and the sequence is available in another text encoding, then that is
98179 ** returned instead.
98180 **
98181 ** If no versions of the requested collations sequence are available, or
98182 ** another error occurs, NULL is returned and an error message written into
98183 ** pParse.
98184 **
98185 ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
98186 ** invokes the collation factory if the named collation cannot be found
98187 ** and generates an error message.
98188 **
98189 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
98190 */
98191 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
98192  sqlite3 *db = pParse->db;
98193  u8 enc = ENC(db);
98194  u8 initbusy = db->init.busy;
98195  CollSeq *pColl;
98196 
98197  pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
98198  if( !initbusy && (!pColl || !pColl->xCmp) ){
98199  pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
98200  }
98201 
98202  return pColl;
98203 }
98204 
98205 
98206 /*
98207 ** Generate code that will increment the schema cookie.
98208 **
98209 ** The schema cookie is used to determine when the schema for the
98210 ** database changes. After each schema change, the cookie value
98211 ** changes. When a process first reads the schema it records the
98212 ** cookie. Thereafter, whenever it goes to access the database,
98213 ** it checks the cookie to make sure the schema has not changed
98214 ** since it was last read.
98215 **
98216 ** This plan is not completely bullet-proof. It is possible for
98217 ** the schema to change multiple times and for the cookie to be
98218 ** set back to prior value. But schema changes are infrequent
98219 ** and the probability of hitting the same cookie value is only
98220 ** 1 chance in 2^32. So we're safe enough.
98221 */
98223  sqlite3 *db = pParse->db;
98224  Vdbe *v = pParse->pVdbe;
98225  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98227  db->aDb[iDb].pSchema->schema_cookie+1);
98228 }
98229 
98230 /*
98231 ** Measure the number of characters needed to output the given
98232 ** identifier. The number returned includes any quotes used
98233 ** but does not include the null terminator.
98234 **
98235 ** The estimate is conservative. It might be larger that what is
98236 ** really needed.
98237 */
98238 static int identLength(const char *z){
98239  int n;
98240  for(n=0; *z; n++, z++){
98241  if( *z=='"' ){ n++; }
98242  }
98243  return n + 2;
98244 }
98245 
98246 /*
98247 ** The first parameter is a pointer to an output buffer. The second
98248 ** parameter is a pointer to an integer that contains the offset at
98249 ** which to write into the output buffer. This function copies the
98250 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
98251 ** to the specified offset in the buffer and updates *pIdx to refer
98252 ** to the first byte after the last byte written before returning.
98253 **
98254 ** If the string zSignedIdent consists entirely of alpha-numeric
98255 ** characters, does not begin with a digit and is not an SQL keyword,
98256 ** then it is copied to the output buffer exactly as it is. Otherwise,
98257 ** it is quoted using double-quotes.
98258 */
98259 static void identPut(char *z, int *pIdx, char *zSignedIdent){
98260  unsigned char *zIdent = (unsigned char*)zSignedIdent;
98261  int i, j, needQuote;
98262  i = *pIdx;
98263 
98264  for(j=0; zIdent[j]; j++){
98265  if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
98266  }
98267  needQuote = sqlite3Isdigit(zIdent[0])
98268  || sqlite3KeywordCode(zIdent, j)!=TK_ID
98269  || zIdent[j]!=0
98270  || j==0;
98271 
98272  if( needQuote ) z[i++] = '"';
98273  for(j=0; zIdent[j]; j++){
98274  z[i++] = zIdent[j];
98275  if( zIdent[j]=='"' ) z[i++] = '"';
98276  }
98277  if( needQuote ) z[i++] = '"';
98278  z[i] = 0;
98279  *pIdx = i;
98280 }
98281 
98282 /*
98283 ** Generate a CREATE TABLE statement appropriate for the given
98284 ** table. Memory to hold the text of the statement is obtained
98285 ** from sqliteMalloc() and must be freed by the calling function.
98286 */
98287 static char *createTableStmt(sqlite3 *db, Table *p){
98288  int i, k, n;
98289  char *zStmt;
98290  char *zSep, *zSep2, *zEnd;
98291  Column *pCol;
98292  n = 0;
98293  for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
98294  n += identLength(pCol->zName) + 5;
98295  }
98296  n += identLength(p->zName);
98297  if( n<50 ){
98298  zSep = "";
98299  zSep2 = ",";
98300  zEnd = ")";
98301  }else{
98302  zSep = "\n ";
98303  zSep2 = ",\n ";
98304  zEnd = "\n)";
98305  }
98306  n += 35 + 6*p->nCol;
98307  zStmt = sqlite3DbMallocRaw(0, n);
98308  if( zStmt==0 ){
98309  sqlite3OomFault(db);
98310  return 0;
98311  }
98312  sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
98313  k = sqlite3Strlen30(zStmt);
98314  identPut(zStmt, &k, p->zName);
98315  zStmt[k++] = '(';
98316  for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
98317  static const char * const azType[] = {
98318  /* SQLITE_AFF_BLOB */ "",
98319  /* SQLITE_AFF_TEXT */ " TEXT",
98320  /* SQLITE_AFF_NUMERIC */ " NUM",
98321  /* SQLITE_AFF_INTEGER */ " INT",
98322  /* SQLITE_AFF_REAL */ " REAL"
98323  };
98324  int len;
98325  const char *zType;
98326 
98327  sqlite3_snprintf(n-k, &zStmt[k], zSep);
98328  k += sqlite3Strlen30(&zStmt[k]);
98329  zSep = zSep2;
98330  identPut(zStmt, &k, pCol->zName);
98331  assert( pCol->affinity-SQLITE_AFF_BLOB >= 0 );
98332  assert( pCol->affinity-SQLITE_AFF_BLOB < ArraySize(azType) );
98333  testcase( pCol->affinity==SQLITE_AFF_BLOB );
98334  testcase( pCol->affinity==SQLITE_AFF_TEXT );
98337  testcase( pCol->affinity==SQLITE_AFF_REAL );
98338 
98339  zType = azType[pCol->affinity - SQLITE_AFF_BLOB];
98340  len = sqlite3Strlen30(zType);
98342  || pCol->affinity==sqlite3AffinityType(zType, 0) );
98343  memcpy(&zStmt[k], zType, len);
98344  k += len;
98345  assert( k<=n );
98346  }
98347  sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
98348  return zStmt;
98349 }
98350 
98351 /*
98352 ** Resize an Index object to hold N columns total. Return SQLITE_OK
98353 ** on success and SQLITE_NOMEM on an OOM error.
98354 */
98355 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
98356  char *zExtra;
98357  int nByte;
98358  if( pIdx->nColumn>=N ) return SQLITE_OK;
98359  assert( pIdx->isResized==0 );
98360  nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
98361  zExtra = sqlite3DbMallocZero(db, nByte);
98362  if( zExtra==0 ) return SQLITE_NOMEM_BKPT;
98363  memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
98364  pIdx->azColl = (const char**)zExtra;
98365  zExtra += sizeof(char*)*N;
98366  memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
98367  pIdx->aiColumn = (i16*)zExtra;
98368  zExtra += sizeof(i16)*N;
98369  memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
98370  pIdx->aSortOrder = (u8*)zExtra;
98371  pIdx->nColumn = N;
98372  pIdx->isResized = 1;
98373  return SQLITE_OK;
98374 }
98375 
98376 /*
98377 ** Estimate the total row width for a table.
98378 */
98379 static void estimateTableWidth(Table *pTab){
98380  unsigned wTable = 0;
98381  const Column *pTabCol;
98382  int i;
98383  for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
98384  wTable += pTabCol->szEst;
98385  }
98386  if( pTab->iPKey<0 ) wTable++;
98387  pTab->szTabRow = sqlite3LogEst(wTable*4);
98388 }
98389 
98390 /*
98391 ** Estimate the average size of a row for an index.
98392 */
98393 static void estimateIndexWidth(Index *pIdx){
98394  unsigned wIndex = 0;
98395  int i;
98396  const Column *aCol = pIdx->pTable->aCol;
98397  for(i=0; i<pIdx->nColumn; i++){
98398  i16 x = pIdx->aiColumn[i];
98399  assert( x<pIdx->pTable->nCol );
98400  wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
98401  }
98402  pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
98403 }
98404 
98405 /* Return true if value x is found any of the first nCol entries of aiCol[]
98406 */
98407 static int hasColumn(const i16 *aiCol, int nCol, int x){
98408  while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
98409  return 0;
98410 }
98411 
98412 /*
98413 ** This routine runs at the end of parsing a CREATE TABLE statement that
98414 ** has a WITHOUT ROWID clause. The job of this routine is to convert both
98415 ** internal schema data structures and the generated VDBE code so that they
98416 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
98417 ** Changes include:
98418 **
98419 ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
98420 ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
98421 ** data storage is a covering index btree.
98422 ** (2) Bypass the creation of the sqlite_master table entry
98423 ** for the PRIMARY KEY as the primary key index is now
98424 ** identified by the sqlite_master table entry of the table itself.
98425 ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
98426 ** schema to the rootpage from the main table.
98427 ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
98428 ** (5) Add all table columns to the PRIMARY KEY Index object
98429 ** so that the PRIMARY KEY is a covering index. The surplus
98430 ** columns are part of KeyInfo.nXField and are not used for
98431 ** sorting or lookup or uniqueness checks.
98432 ** (6) Replace the rowid tail on all automatically generated UNIQUE
98433 ** indices with the PRIMARY KEY columns.
98434 */
98435 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
98436  Index *pIdx;
98437  Index *pPk;
98438  int nPk;
98439  int i, j;
98440  sqlite3 *db = pParse->db;
98441  Vdbe *v = pParse->pVdbe;
98442 
98443  /* Convert the OP_CreateTable opcode that would normally create the
98444  ** root-page for the table into an OP_CreateIndex opcode. The index
98445  ** created will become the PRIMARY KEY index.
98446  */
98447  if( pParse->addrCrTab ){
98448  assert( v );
98450  }
98451 
98452  /* Locate the PRIMARY KEY index. Or, if this table was originally
98453  ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
98454  */
98455  if( pTab->iPKey>=0 ){
98456  ExprList *pList;
98457  Token ipkToken;
98458  sqlite3TokenInit(&ipkToken, pTab->aCol[pTab->iPKey].zName);
98459  pList = sqlite3ExprListAppend(pParse, 0,
98460  sqlite3ExprAlloc(db, TK_ID, &ipkToken, 0));
98461  if( pList==0 ) return;
98462  pList->a[0].sortOrder = pParse->iPkSortOrder;
98463  assert( pParse->pNewTable==pTab );
98464  pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
98465  if( pPk==0 ) return;
98467  pTab->iPKey = -1;
98468  }else{
98469  pPk = sqlite3PrimaryKeyIndex(pTab);
98470 
98471  /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
98472  ** table entry. This is only required if currently generating VDBE
98473  ** code for a CREATE TABLE (not when parsing one as part of reading
98474  ** a database schema). */
98475  if( v ){
98476  assert( db->init.busy==0 );
98478  }
98479 
98480  /*
98481  ** Remove all redundant columns from the PRIMARY KEY. For example, change
98482  ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)". Later
98483  ** code assumes the PRIMARY KEY contains no repeated columns.
98484  */
98485  for(i=j=1; i<pPk->nKeyCol; i++){
98486  if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
98487  pPk->nColumn--;
98488  }else{
98489  pPk->aiColumn[j++] = pPk->aiColumn[i];
98490  }
98491  }
98492  pPk->nKeyCol = j;
98493  }
98494  pPk->isCovering = 1;
98495  assert( pPk!=0 );
98496  nPk = pPk->nKeyCol;
98497 
98498  /* Make sure every column of the PRIMARY KEY is NOT NULL. (Except,
98499  ** do not enforce this for imposter tables.) */
98500  if( !db->init.imposterTable ){
98501  for(i=0; i<nPk; i++){
98502  pTab->aCol[pPk->aiColumn[i]].notNull = OE_Abort;
98503  }
98504  pPk->uniqNotNull = 1;
98505  }
98506 
98507  /* The root page of the PRIMARY KEY is the table root page */
98508  pPk->tnum = pTab->tnum;
98509 
98510  /* Update the in-memory representation of all UNIQUE indices by converting
98511  ** the final rowid column into one or more columns of the PRIMARY KEY.
98512  */
98513  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
98514  int n;
98515  if( IsPrimaryKeyIndex(pIdx) ) continue;
98516  for(i=n=0; i<nPk; i++){
98517  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
98518  }
98519  if( n==0 ){
98520  /* This index is a superset of the primary key */
98521  pIdx->nColumn = pIdx->nKeyCol;
98522  continue;
98523  }
98524  if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
98525  for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
98526  if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
98527  pIdx->aiColumn[j] = pPk->aiColumn[i];
98528  pIdx->azColl[j] = pPk->azColl[i];
98529  j++;
98530  }
98531  }
98532  assert( pIdx->nColumn>=pIdx->nKeyCol+n );
98533  assert( pIdx->nColumn>=j );
98534  }
98535 
98536  /* Add all table columns to the PRIMARY KEY index
98537  */
98538  if( nPk<pTab->nCol ){
98539  if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
98540  for(i=0, j=nPk; i<pTab->nCol; i++){
98541  if( !hasColumn(pPk->aiColumn, j, i) ){
98542  assert( j<pPk->nColumn );
98543  pPk->aiColumn[j] = i;
98544  pPk->azColl[j] = sqlite3StrBINARY;
98545  j++;
98546  }
98547  }
98548  assert( pPk->nColumn==j );
98549  assert( pTab->nCol==j );
98550  }else{
98551  pPk->nColumn = pTab->nCol;
98552  }
98553 }
98554 
98555 /*
98556 ** This routine is called to report the final ")" that terminates
98557 ** a CREATE TABLE statement.
98558 **
98559 ** The table structure that other action routines have been building
98560 ** is added to the internal hash tables, assuming no errors have
98561 ** occurred.
98562 **
98563 ** An entry for the table is made in the master table on disk, unless
98564 ** this is a temporary table or db->init.busy==1. When db->init.busy==1
98565 ** it means we are reading the sqlite_master table because we just
98566 ** connected to the database or because the sqlite_master table has
98567 ** recently changed, so the entry for this table already exists in
98568 ** the sqlite_master table. We do not want to create it again.
98569 **
98570 ** If the pSelect argument is not NULL, it means that this routine
98571 ** was called to create a table generated from a
98572 ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
98573 ** the new table will match the result set of the SELECT.
98574 */
98576  Parse *pParse, /* Parse context */
98577  Token *pCons, /* The ',' token after the last column defn. */
98578  Token *pEnd, /* The ')' before options in the CREATE TABLE */
98579  u8 tabOpts, /* Extra table options. Usually 0. */
98580  Select *pSelect /* Select from a "CREATE ... AS SELECT" */
98581 ){
98582  Table *p; /* The new table */
98583  sqlite3 *db = pParse->db; /* The database connection */
98584  int iDb; /* Database in which the table lives */
98585  Index *pIdx; /* An implied index of the table */
98586 
98587  if( pEnd==0 && pSelect==0 ){
98588  return;
98589  }
98590  assert( !db->mallocFailed );
98591  p = pParse->pNewTable;
98592  if( p==0 ) return;
98593 
98594  assert( !db->init.busy || !pSelect );
98595 
98596  /* If the db->init.busy is 1 it means we are reading the SQL off the
98597  ** "sqlite_master" or "sqlite_temp_master" table on the disk.
98598  ** So do not write to the disk again. Extract the root page number
98599  ** for the table from the db->init.newTnum field. (The page number
98600  ** should have been put there by the sqliteOpenCb routine.)
98601  **
98602  ** If the root page number is 1, that means this is the sqlite_master
98603  ** table itself. So mark it read-only.
98604  */
98605  if( db->init.busy ){
98606  p->tnum = db->init.newTnum;
98607  if( p->tnum==1 ) p->tabFlags |= TF_Readonly;
98608  }
98609 
98610  /* Special processing for WITHOUT ROWID Tables */
98611  if( tabOpts & TF_WithoutRowid ){
98612  if( (p->tabFlags & TF_Autoincrement) ){
98613  sqlite3ErrorMsg(pParse,
98614  "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
98615  return;
98616  }
98617  if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
98618  sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
98619  }else{
98620  p->tabFlags |= TF_WithoutRowid | TF_NoVisibleRowid;
98621  convertToWithoutRowidTable(pParse, p);
98622  }
98623  }
98624 
98625  iDb = sqlite3SchemaToIndex(db, p->pSchema);
98626 
98627 #ifndef SQLITE_OMIT_CHECK
98628  /* Resolve names in all CHECK constraint expressions.
98629  */
98630  if( p->pCheck ){
98631  sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
98632  }
98633 #endif /* !defined(SQLITE_OMIT_CHECK) */
98634 
98635  /* Estimate the average row size for the table and for all implied indices */
98636  estimateTableWidth(p);
98637  for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
98638  estimateIndexWidth(pIdx);
98639  }
98640 
98641  /* If not initializing, then create a record for the new table
98642  ** in the SQLITE_MASTER table of the database.
98643  **
98644  ** If this is a TEMPORARY table, write the entry into the auxiliary
98645  ** file instead of into the main database file.
98646  */
98647  if( !db->init.busy ){
98648  int n;
98649  Vdbe *v;
98650  char *zType; /* "view" or "table" */
98651  char *zType2; /* "VIEW" or "TABLE" */
98652  char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
98653 
98654  v = sqlite3GetVdbe(pParse);
98655  if( NEVER(v==0) ) return;
98656 
98657  sqlite3VdbeAddOp1(v, OP_Close, 0);
98658 
98659  /*
98660  ** Initialize zType for the new view or table.
98661  */
98662  if( p->pSelect==0 ){
98663  /* A regular table */
98664  zType = "table";
98665  zType2 = "TABLE";
98666 #ifndef SQLITE_OMIT_VIEW
98667  }else{
98668  /* A view */
98669  zType = "view";
98670  zType2 = "VIEW";
98671 #endif
98672  }
98673 
98674  /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
98675  ** statement to populate the new table. The root-page number for the
98676  ** new table is in register pParse->regRoot.
98677  **
98678  ** Once the SELECT has been coded by sqlite3Select(), it is in a
98679  ** suitable state to query for the column names and types to be used
98680  ** by the new table.
98681  **
98682  ** A shared-cache write-lock is not required to write to the new table,
98683  ** as a schema-lock must have already been obtained to create it. Since
98684  ** a schema-lock excludes all other database users, the write-lock would
98685  ** be redundant.
98686  */
98687  if( pSelect ){
98688  SelectDest dest; /* Where the SELECT should store results */
98689  int regYield; /* Register holding co-routine entry-point */
98690  int addrTop; /* Top of the co-routine */
98691  int regRec; /* A record to be insert into the new table */
98692  int regRowid; /* Rowid of the next row to insert */
98693  int addrInsLoop; /* Top of the loop for inserting rows */
98694  Table *pSelTab; /* A table that describes the SELECT results */
98695 
98696  regYield = ++pParse->nMem;
98697  regRec = ++pParse->nMem;
98698  regRowid = ++pParse->nMem;
98699  assert(pParse->nTab==1);
98700  sqlite3MayAbort(pParse);
98701  sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
98703  pParse->nTab = 2;
98704  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
98705  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
98706  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
98707  sqlite3Select(pParse, pSelect, &dest);
98708  sqlite3VdbeEndCoroutine(v, regYield);
98709  sqlite3VdbeJumpHere(v, addrTop - 1);
98710  if( pParse->nErr ) return;
98711  pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
98712  if( pSelTab==0 ) return;
98713  assert( p->aCol==0 );
98714  p->nCol = pSelTab->nCol;
98715  p->aCol = pSelTab->aCol;
98716  pSelTab->nCol = 0;
98717  pSelTab->aCol = 0;
98718  sqlite3DeleteTable(db, pSelTab);
98719  addrInsLoop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
98720  VdbeCoverage(v);
98721  sqlite3VdbeAddOp3(v, OP_MakeRecord, dest.iSdst, dest.nSdst, regRec);
98722  sqlite3TableAffinity(v, p, 0);
98723  sqlite3VdbeAddOp2(v, OP_NewRowid, 1, regRowid);
98724  sqlite3VdbeAddOp3(v, OP_Insert, 1, regRec, regRowid);
98725  sqlite3VdbeGoto(v, addrInsLoop);
98726  sqlite3VdbeJumpHere(v, addrInsLoop);
98727  sqlite3VdbeAddOp1(v, OP_Close, 1);
98728  }
98729 
98730  /* Compute the complete text of the CREATE statement */
98731  if( pSelect ){
98732  zStmt = createTableStmt(db, p);
98733  }else{
98734  Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
98735  n = (int)(pEnd2->z - pParse->sNameToken.z);
98736  if( pEnd2->z[0]!=';' ) n += pEnd2->n;
98737  zStmt = sqlite3MPrintf(db,
98738  "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
98739  );
98740  }
98741 
98742  /* A slot for the record has already been allocated in the
98743  ** SQLITE_MASTER table. We just need to update that slot with all
98744  ** the information we've collected.
98745  */
98746  sqlite3NestedParse(pParse,
98747  "UPDATE %Q.%s "
98748  "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
98749  "WHERE rowid=#%d",
98750  db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
98751  zType,
98752  p->zName,
98753  p->zName,
98754  pParse->regRoot,
98755  zStmt,
98756  pParse->regRowid
98757  );
98758  sqlite3DbFree(db, zStmt);
98759  sqlite3ChangeCookie(pParse, iDb);
98760 
98761 #ifndef SQLITE_OMIT_AUTOINCREMENT
98762  /* Check to see if we need to create an sqlite_sequence table for
98763  ** keeping track of autoincrement keys.
98764  */
98765  if( p->tabFlags & TF_Autoincrement ){
98766  Db *pDb = &db->aDb[iDb];
98767  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98768  if( pDb->pSchema->pSeqTab==0 ){
98769  sqlite3NestedParse(pParse,
98770  "CREATE TABLE %Q.sqlite_sequence(name,seq)",
98771  pDb->zName
98772  );
98773  }
98774  }
98775 #endif
98776 
98777  /* Reparse everything to update our internal data structures */
98779  sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
98780  }
98781 
98782 
98783  /* Add the table to the in-memory representation of the database.
98784  */
98785  if( db->init.busy ){
98786  Table *pOld;
98787  Schema *pSchema = p->pSchema;
98788  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
98789  pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
98790  if( pOld ){
98791  assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
98792  sqlite3OomFault(db);
98793  return;
98794  }
98795  pParse->pNewTable = 0;
98796  db->flags |= SQLITE_InternChanges;
98797 
98798 #ifndef SQLITE_OMIT_ALTERTABLE
98799  if( !p->pSelect ){
98800  const char *zName = (const char *)pParse->sNameToken.z;
98801  int nName;
98802  assert( !pSelect && pCons && pEnd );
98803  if( pCons->z==0 ){
98804  pCons = pEnd;
98805  }
98806  nName = (int)((const char *)pCons->z - zName);
98807  p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
98808  }
98809 #endif
98810  }
98811 }
98812 
98813 #ifndef SQLITE_OMIT_VIEW
98814 /*
98815 ** The parser calls this routine in order to create a new VIEW
98816 */
98818  Parse *pParse, /* The parsing context */
98819  Token *pBegin, /* The CREATE token that begins the statement */
98820  Token *pName1, /* The token that holds the name of the view */
98821  Token *pName2, /* The token that holds the name of the view */
98822  ExprList *pCNames, /* Optional list of view column names */
98823  Select *pSelect, /* A SELECT statement that will become the new view */
98824  int isTemp, /* TRUE for a TEMPORARY view */
98825  int noErr /* Suppress error messages if VIEW already exists */
98826 ){
98827  Table *p;
98828  int n;
98829  const char *z;
98830  Token sEnd;
98831  DbFixer sFix;
98832  Token *pName = 0;
98833  int iDb;
98834  sqlite3 *db = pParse->db;
98835 
98836  if( pParse->nVar>0 ){
98837  sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
98838  goto create_view_fail;
98839  }
98840  sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
98841  p = pParse->pNewTable;
98842  if( p==0 || pParse->nErr ) goto create_view_fail;
98843  sqlite3TwoPartName(pParse, pName1, pName2, &pName);
98844  iDb = sqlite3SchemaToIndex(db, p->pSchema);
98845  sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
98846  if( sqlite3FixSelect(&sFix, pSelect) ) goto create_view_fail;
98847 
98848  /* Make a copy of the entire SELECT statement that defines the view.
98849  ** This will force all the Expr.token.z values to be dynamically
98850  ** allocated rather than point to the input string - which means that
98851  ** they will persist after the current sqlite3_exec() call returns.
98852  */
98853  p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
98854  p->pCheck = sqlite3ExprListDup(db, pCNames, EXPRDUP_REDUCE);
98855  if( db->mallocFailed ) goto create_view_fail;
98856 
98857  /* Locate the end of the CREATE VIEW statement. Make sEnd point to
98858  ** the end.
98859  */
98860  sEnd = pParse->sLastToken;
98861  assert( sEnd.z[0]!=0 );
98862  if( sEnd.z[0]!=';' ){
98863  sEnd.z += sEnd.n;
98864  }
98865  sEnd.n = 0;
98866  n = (int)(sEnd.z - pBegin->z);
98867  assert( n>0 );
98868  z = pBegin->z;
98869  while( sqlite3Isspace(z[n-1]) ){ n--; }
98870  sEnd.z = &z[n-1];
98871  sEnd.n = 1;
98872 
98873  /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
98874  sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
98875 
98876 create_view_fail:
98877  sqlite3SelectDelete(db, pSelect);
98878  sqlite3ExprListDelete(db, pCNames);
98879  return;
98880 }
98881 #endif /* SQLITE_OMIT_VIEW */
98882 
98883 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
98884 /*
98885 ** The Table structure pTable is really a VIEW. Fill in the names of
98886 ** the columns of the view in the pTable structure. Return the number
98887 ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
98888 */
98890  Table *pSelTab; /* A fake table from which we get the result set */
98891  Select *pSel; /* Copy of the SELECT that implements the view */
98892  int nErr = 0; /* Number of errors encountered */
98893  int n; /* Temporarily holds the number of cursors assigned */
98894  sqlite3 *db = pParse->db; /* Database connection for malloc errors */
98895  sqlite3_xauth xAuth; /* Saved xAuth pointer */
98896 
98897  assert( pTable );
98898 
98899 #ifndef SQLITE_OMIT_VIRTUALTABLE
98900  if( sqlite3VtabCallConnect(pParse, pTable) ){
98901  return SQLITE_ERROR;
98902  }
98903  if( IsVirtual(pTable) ) return 0;
98904 #endif
98905 
98906 #ifndef SQLITE_OMIT_VIEW
98907  /* A positive nCol means the columns names for this view are
98908  ** already known.
98909  */
98910  if( pTable->nCol>0 ) return 0;
98911 
98912  /* A negative nCol is a special marker meaning that we are currently
98913  ** trying to compute the column names. If we enter this routine with
98914  ** a negative nCol, it means two or more views form a loop, like this:
98915  **
98916  ** CREATE VIEW one AS SELECT * FROM two;
98917  ** CREATE VIEW two AS SELECT * FROM one;
98918  **
98919  ** Actually, the error above is now caught prior to reaching this point.
98920  ** But the following test is still important as it does come up
98921  ** in the following:
98922  **
98923  ** CREATE TABLE main.ex1(a);
98924  ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
98925  ** SELECT * FROM temp.ex1;
98926  */
98927  if( pTable->nCol<0 ){
98928  sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
98929  return 1;
98930  }
98931  assert( pTable->nCol>=0 );
98932 
98933  /* If we get this far, it means we need to compute the table names.
98934  ** Note that the call to sqlite3ResultSetOfSelect() will expand any
98935  ** "*" elements in the results set of the view and will assign cursors
98936  ** to the elements of the FROM clause. But we do not want these changes
98937  ** to be permanent. So the computation is done on a copy of the SELECT
98938  ** statement that defines the view.
98939  */
98940  assert( pTable->pSelect );
98941  pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
98942  if( pSel ){
98943  n = pParse->nTab;
98944  sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
98945  pTable->nCol = -1;
98946  db->lookaside.bDisable++;
98947 #ifndef SQLITE_OMIT_AUTHORIZATION
98948  xAuth = db->xAuth;
98949  db->xAuth = 0;
98950  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
98951  db->xAuth = xAuth;
98952 #else
98953  pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
98954 #endif
98955  pParse->nTab = n;
98956  if( pTable->pCheck ){
98957  /* CREATE VIEW name(arglist) AS ...
98958  ** The names of the columns in the table are taken from
98959  ** arglist which is stored in pTable->pCheck. The pCheck field
98960  ** normally holds CHECK constraints on an ordinary table, but for
98961  ** a VIEW it holds the list of column names.
98962  */
98963  sqlite3ColumnsFromExprList(pParse, pTable->pCheck,
98964  &pTable->nCol, &pTable->aCol);
98965  if( db->mallocFailed==0
98966  && pParse->nErr==0
98967  && pTable->nCol==pSel->pEList->nExpr
98968  ){
98969  sqlite3SelectAddColumnTypeAndCollation(pParse, pTable, pSel);
98970  }
98971  }else if( pSelTab ){
98972  /* CREATE VIEW name AS... without an argument list. Construct
98973  ** the column names from the SELECT statement that defines the view.
98974  */
98975  assert( pTable->aCol==0 );
98976  pTable->nCol = pSelTab->nCol;
98977  pTable->aCol = pSelTab->aCol;
98978  pSelTab->nCol = 0;
98979  pSelTab->aCol = 0;
98980  assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
98981  }else{
98982  pTable->nCol = 0;
98983  nErr++;
98984  }
98985  sqlite3DeleteTable(db, pSelTab);
98986  sqlite3SelectDelete(db, pSel);
98987  db->lookaside.bDisable--;
98988  } else {
98989  nErr++;
98990  }
98991  pTable->pSchema->schemaFlags |= DB_UnresetViews;
98992 #endif /* SQLITE_OMIT_VIEW */
98993  return nErr;
98994 }
98995 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
98996 
98997 #ifndef SQLITE_OMIT_VIEW
98998 /*
98999 ** Clear the column names from every VIEW in database idx.
99000 */
99001 static void sqliteViewResetAll(sqlite3 *db, int idx){
99002  HashElem *i;
99003  assert( sqlite3SchemaMutexHeld(db, idx, 0) );
99004  if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
99005  for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
99006  Table *pTab = sqliteHashData(i);
99007  if( pTab->pSelect ){
99008  sqlite3DeleteColumnNames(db, pTab);
99009  pTab->aCol = 0;
99010  pTab->nCol = 0;
99011  }
99012  }
99013  DbClearProperty(db, idx, DB_UnresetViews);
99014 }
99015 #else
99016 # define sqliteViewResetAll(A,B)
99017 #endif /* SQLITE_OMIT_VIEW */
99018 
99019 /*
99020 ** This function is called by the VDBE to adjust the internal schema
99021 ** used by SQLite when the btree layer moves a table root page. The
99022 ** root-page of a table or index in database iDb has changed from iFrom
99023 ** to iTo.
99024 **
99025 ** Ticket #1728: The symbol table might still contain information
99026 ** on tables and/or indices that are the process of being deleted.
99027 ** If you are unlucky, one of those deleted indices or tables might
99028 ** have the same rootpage number as the real table or index that is
99029 ** being moved. So we cannot stop searching after the first match
99030 ** because the first match might be for one of the deleted indices
99031 ** or tables and not the table/index that is actually being moved.
99032 ** We must continue looping until all tables and indices with
99033 ** rootpage==iFrom have been converted to have a rootpage of iTo
99034 ** in order to be certain that we got the right one.
99035 */
99036 #ifndef SQLITE_OMIT_AUTOVACUUM
99037 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
99038  HashElem *pElem;
99039  Hash *pHash;
99040  Db *pDb;
99041 
99042  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99043  pDb = &db->aDb[iDb];
99044  pHash = &pDb->pSchema->tblHash;
99045  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99046  Table *pTab = sqliteHashData(pElem);
99047  if( pTab->tnum==iFrom ){
99048  pTab->tnum = iTo;
99049  }
99050  }
99051  pHash = &pDb->pSchema->idxHash;
99052  for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
99053  Index *pIdx = sqliteHashData(pElem);
99054  if( pIdx->tnum==iFrom ){
99055  pIdx->tnum = iTo;
99056  }
99057  }
99058 }
99059 #endif
99060 
99061 /*
99062 ** Write code to erase the table with root-page iTable from database iDb.
99063 ** Also write code to modify the sqlite_master table and internal schema
99064 ** if a root-page of another table is moved by the btree-layer whilst
99065 ** erasing iTable (this can happen with an auto-vacuum database).
99066 */
99067 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
99068  Vdbe *v = sqlite3GetVdbe(pParse);
99069  int r1 = sqlite3GetTempReg(pParse);
99070  assert( iTable>1 );
99071  sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
99072  sqlite3MayAbort(pParse);
99073 #ifndef SQLITE_OMIT_AUTOVACUUM
99074  /* OP_Destroy stores an in integer r1. If this integer
99075  ** is non-zero, then it is the root page number of a table moved to
99076  ** location iTable. The following code modifies the sqlite_master table to
99077  ** reflect this.
99078  **
99079  ** The "#NNN" in the SQL is a special constant that means whatever value
99080  ** is in register NNN. See grammar rules associated with the TK_REGISTER
99081  ** token for additional information.
99082  */
99083  sqlite3NestedParse(pParse,
99084  "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
99085  pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
99086 #endif
99087  sqlite3ReleaseTempReg(pParse, r1);
99088 }
99089 
99090 /*
99091 ** Write VDBE code to erase table pTab and all associated indices on disk.
99092 ** Code to update the sqlite_master tables and internal schema definitions
99093 ** in case a root-page belonging to another table is moved by the btree layer
99094 ** is also added (this can happen with an auto-vacuum database).
99095 */
99096 static void destroyTable(Parse *pParse, Table *pTab){
99097 #ifdef SQLITE_OMIT_AUTOVACUUM
99098  Index *pIdx;
99099  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99100  destroyRootPage(pParse, pTab->tnum, iDb);
99101  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99102  destroyRootPage(pParse, pIdx->tnum, iDb);
99103  }
99104 #else
99105  /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
99106  ** is not defined), then it is important to call OP_Destroy on the
99107  ** table and index root-pages in order, starting with the numerically
99108  ** largest root-page number. This guarantees that none of the root-pages
99109  ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
99110  ** following were coded:
99111  **
99112  ** OP_Destroy 4 0
99113  ** ...
99114  ** OP_Destroy 5 0
99115  **
99116  ** and root page 5 happened to be the largest root-page number in the
99117  ** database, then root page 5 would be moved to page 4 by the
99118  ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
99119  ** a free-list page.
99120  */
99121  int iTab = pTab->tnum;
99122  int iDestroyed = 0;
99123 
99124  while( 1 ){
99125  Index *pIdx;
99126  int iLargest = 0;
99127 
99128  if( iDestroyed==0 || iTab<iDestroyed ){
99129  iLargest = iTab;
99130  }
99131  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
99132  int iIdx = pIdx->tnum;
99133  assert( pIdx->pSchema==pTab->pSchema );
99134  if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
99135  iLargest = iIdx;
99136  }
99137  }
99138  if( iLargest==0 ){
99139  return;
99140  }else{
99141  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
99142  assert( iDb>=0 && iDb<pParse->db->nDb );
99143  destroyRootPage(pParse, iLargest, iDb);
99144  iDestroyed = iLargest;
99145  }
99146  }
99147 #endif
99148 }
99149 
99150 /*
99151 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
99152 ** after a DROP INDEX or DROP TABLE command.
99153 */
99155  Parse *pParse, /* The parsing context */
99156  int iDb, /* The database number */
99157  const char *zType, /* "idx" or "tbl" */
99158  const char *zName /* Name of index or table */
99159 ){
99160  int i;
99161  const char *zDbName = pParse->db->aDb[iDb].zName;
99162  for(i=1; i<=4; i++){
99163  char zTab[24];
99164  sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
99165  if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
99166  sqlite3NestedParse(pParse,
99167  "DELETE FROM %Q.%s WHERE %s=%Q",
99168  zDbName, zTab, zType, zName
99169  );
99170  }
99171  }
99172 }
99173 
99174 /*
99175 ** Generate code to drop a table.
99176 */
99177 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
99178  Vdbe *v;
99179  sqlite3 *db = pParse->db;
99180  Trigger *pTrigger;
99181  Db *pDb = &db->aDb[iDb];
99182 
99183  v = sqlite3GetVdbe(pParse);
99184  assert( v!=0 );
99185  sqlite3BeginWriteOperation(pParse, 1, iDb);
99186 
99187 #ifndef SQLITE_OMIT_VIRTUALTABLE
99188  if( IsVirtual(pTab) ){
99190  }
99191 #endif
99192 
99193  /* Drop all triggers associated with the table being dropped. Code
99194  ** is generated to remove entries from sqlite_master and/or
99195  ** sqlite_temp_master if required.
99196  */
99197  pTrigger = sqlite3TriggerList(pParse, pTab);
99198  while( pTrigger ){
99199  assert( pTrigger->pSchema==pTab->pSchema ||
99200  pTrigger->pSchema==db->aDb[1].pSchema );
99201  sqlite3DropTriggerPtr(pParse, pTrigger);
99202  pTrigger = pTrigger->pNext;
99203  }
99204 
99205 #ifndef SQLITE_OMIT_AUTOINCREMENT
99206  /* Remove any entries of the sqlite_sequence table associated with
99207  ** the table being dropped. This is done before the table is dropped
99208  ** at the btree level, in case the sqlite_sequence table needs to
99209  ** move as a result of the drop (can happen in auto-vacuum mode).
99210  */
99211  if( pTab->tabFlags & TF_Autoincrement ){
99212  sqlite3NestedParse(pParse,
99213  "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
99214  pDb->zName, pTab->zName
99215  );
99216  }
99217 #endif
99218 
99219  /* Drop all SQLITE_MASTER table and index entries that refer to the
99220  ** table. The program name loops through the master table and deletes
99221  ** every row that refers to a table of the same name as the one being
99222  ** dropped. Triggers are handled separately because a trigger can be
99223  ** created in the temp database that refers to a table in another
99224  ** database.
99225  */
99226  sqlite3NestedParse(pParse,
99227  "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
99228  pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
99229  if( !isView && !IsVirtual(pTab) ){
99230  destroyTable(pParse, pTab);
99231  }
99232 
99233  /* Remove the table entry from SQLite's internal schema and modify
99234  ** the schema cookie.
99235  */
99236  if( IsVirtual(pTab) ){
99237  sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
99238  }
99239  sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
99240  sqlite3ChangeCookie(pParse, iDb);
99241  sqliteViewResetAll(db, iDb);
99242 }
99243 
99244 /*
99245 ** This routine is called to do the work of a DROP TABLE statement.
99246 ** pName is the name of the table to be dropped.
99247 */
99248 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
99249  Table *pTab;
99250  Vdbe *v;
99251  sqlite3 *db = pParse->db;
99252  int iDb;
99253 
99254  if( db->mallocFailed ){
99255  goto exit_drop_table;
99256  }
99257  assert( pParse->nErr==0 );
99258  assert( pName->nSrc==1 );
99259  if( sqlite3ReadSchema(pParse) ) goto exit_drop_table;
99260  if( noErr ) db->suppressErr++;
99261  pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
99262  if( noErr ) db->suppressErr--;
99263 
99264  if( pTab==0 ){
99265  if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
99266  goto exit_drop_table;
99267  }
99268  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99269  assert( iDb>=0 && iDb<db->nDb );
99270 
99271  /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
99272  ** it is initialized.
99273  */
99274  if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
99275  goto exit_drop_table;
99276  }
99277 #ifndef SQLITE_OMIT_AUTHORIZATION
99278  {
99279  int code;
99280  const char *zTab = SCHEMA_TABLE(iDb);
99281  const char *zDb = db->aDb[iDb].zName;
99282  const char *zArg2 = 0;
99283  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
99284  goto exit_drop_table;
99285  }
99286  if( isView ){
99287  if( !OMIT_TEMPDB && iDb==1 ){
99288  code = SQLITE_DROP_TEMP_VIEW;
99289  }else{
99290  code = SQLITE_DROP_VIEW;
99291  }
99292 #ifndef SQLITE_OMIT_VIRTUALTABLE
99293  }else if( IsVirtual(pTab) ){
99294  code = SQLITE_DROP_VTABLE;
99295  zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
99296 #endif
99297  }else{
99298  if( !OMIT_TEMPDB && iDb==1 ){
99299  code = SQLITE_DROP_TEMP_TABLE;
99300  }else{
99301  code = SQLITE_DROP_TABLE;
99302  }
99303  }
99304  if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
99305  goto exit_drop_table;
99306  }
99307  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
99308  goto exit_drop_table;
99309  }
99310  }
99311 #endif
99312  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
99313  && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
99314  sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
99315  goto exit_drop_table;
99316  }
99317 
99318 #ifndef SQLITE_OMIT_VIEW
99319  /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
99320  ** on a table.
99321  */
99322  if( isView && pTab->pSelect==0 ){
99323  sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
99324  goto exit_drop_table;
99325  }
99326  if( !isView && pTab->pSelect ){
99327  sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
99328  goto exit_drop_table;
99329  }
99330 #endif
99331 
99332  /* Generate code to remove the table from the master table
99333  ** on disk.
99334  */
99335  v = sqlite3GetVdbe(pParse);
99336  if( v ){
99337  sqlite3BeginWriteOperation(pParse, 1, iDb);
99338  sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
99339  sqlite3FkDropTable(pParse, pName, pTab);
99340  sqlite3CodeDropTable(pParse, pTab, iDb, isView);
99341  }
99342 
99343 exit_drop_table:
99344  sqlite3SrcListDelete(db, pName);
99345 }
99346 
99347 /*
99348 ** This routine is called to create a new foreign key on the table
99349 ** currently under construction. pFromCol determines which columns
99350 ** in the current table point to the foreign key. If pFromCol==0 then
99351 ** connect the key to the last column inserted. pTo is the name of
99352 ** the table referred to (a.k.a the "parent" table). pToCol is a list
99353 ** of tables in the parent pTo table. flags contains all
99354 ** information about the conflict resolution algorithms specified
99355 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
99356 **
99357 ** An FKey structure is created and added to the table currently
99358 ** under construction in the pParse->pNewTable field.
99359 **
99360 ** The foreign key is set for IMMEDIATE processing. A subsequent call
99361 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
99362 */
99364  Parse *pParse, /* Parsing context */
99365  ExprList *pFromCol, /* Columns in this table that point to other table */
99366  Token *pTo, /* Name of the other table */
99367  ExprList *pToCol, /* Columns in the other table */
99368  int flags /* Conflict resolution algorithms. */
99369 ){
99370  sqlite3 *db = pParse->db;
99371 #ifndef SQLITE_OMIT_FOREIGN_KEY
99372  FKey *pFKey = 0;
99373  FKey *pNextTo;
99374  Table *p = pParse->pNewTable;
99375  int nByte;
99376  int i;
99377  int nCol;
99378  char *z;
99379 
99380  assert( pTo!=0 );
99381  if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
99382  if( pFromCol==0 ){
99383  int iCol = p->nCol-1;
99384  if( NEVER(iCol<0) ) goto fk_end;
99385  if( pToCol && pToCol->nExpr!=1 ){
99386  sqlite3ErrorMsg(pParse, "foreign key on %s"
99387  " should reference only one column of table %T",
99388  p->aCol[iCol].zName, pTo);
99389  goto fk_end;
99390  }
99391  nCol = 1;
99392  }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
99393  sqlite3ErrorMsg(pParse,
99394  "number of columns in foreign key does not match the number of "
99395  "columns in the referenced table");
99396  goto fk_end;
99397  }else{
99398  nCol = pFromCol->nExpr;
99399  }
99400  nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
99401  if( pToCol ){
99402  for(i=0; i<pToCol->nExpr; i++){
99403  nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
99404  }
99405  }
99406  pFKey = sqlite3DbMallocZero(db, nByte );
99407  if( pFKey==0 ){
99408  goto fk_end;
99409  }
99410  pFKey->pFrom = p;
99411  pFKey->pNextFrom = p->pFKey;
99412  z = (char*)&pFKey->aCol[nCol];
99413  pFKey->zTo = z;
99414  memcpy(z, pTo->z, pTo->n);
99415  z[pTo->n] = 0;
99416  sqlite3Dequote(z);
99417  z += pTo->n+1;
99418  pFKey->nCol = nCol;
99419  if( pFromCol==0 ){
99420  pFKey->aCol[0].iFrom = p->nCol-1;
99421  }else{
99422  for(i=0; i<nCol; i++){
99423  int j;
99424  for(j=0; j<p->nCol; j++){
99425  if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
99426  pFKey->aCol[i].iFrom = j;
99427  break;
99428  }
99429  }
99430  if( j>=p->nCol ){
99431  sqlite3ErrorMsg(pParse,
99432  "unknown column \"%s\" in foreign key definition",
99433  pFromCol->a[i].zName);
99434  goto fk_end;
99435  }
99436  }
99437  }
99438  if( pToCol ){
99439  for(i=0; i<nCol; i++){
99440  int n = sqlite3Strlen30(pToCol->a[i].zName);
99441  pFKey->aCol[i].zCol = z;
99442  memcpy(z, pToCol->a[i].zName, n);
99443  z[n] = 0;
99444  z += n+1;
99445  }
99446  }
99447  pFKey->isDeferred = 0;
99448  pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
99449  pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
99450 
99451  assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
99452  pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
99453  pFKey->zTo, (void *)pFKey
99454  );
99455  if( pNextTo==pFKey ){
99456  sqlite3OomFault(db);
99457  goto fk_end;
99458  }
99459  if( pNextTo ){
99460  assert( pNextTo->pPrevTo==0 );
99461  pFKey->pNextTo = pNextTo;
99462  pNextTo->pPrevTo = pFKey;
99463  }
99464 
99465  /* Link the foreign key to the table as the last step.
99466  */
99467  p->pFKey = pFKey;
99468  pFKey = 0;
99469 
99470 fk_end:
99471  sqlite3DbFree(db, pFKey);
99472 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
99473  sqlite3ExprListDelete(db, pFromCol);
99474  sqlite3ExprListDelete(db, pToCol);
99475 }
99476 
99477 /*
99478 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
99479 ** clause is seen as part of a foreign key definition. The isDeferred
99480 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
99481 ** The behavior of the most recently created foreign key is adjusted
99482 ** accordingly.
99483 */
99484 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
99485 #ifndef SQLITE_OMIT_FOREIGN_KEY
99486  Table *pTab;
99487  FKey *pFKey;
99488  if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
99489  assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
99490  pFKey->isDeferred = (u8)isDeferred;
99491 #endif
99492 }
99493 
99494 /*
99495 ** Generate code that will erase and refill index *pIdx. This is
99496 ** used to initialize a newly created index or to recompute the
99497 ** content of an index in response to a REINDEX command.
99498 **
99499 ** if memRootPage is not negative, it means that the index is newly
99500 ** created. The register specified by memRootPage contains the
99501 ** root page number of the index. If memRootPage is negative, then
99502 ** the index already exists and must be cleared before being refilled and
99503 ** the root page number of the index is taken from pIndex->tnum.
99504 */
99505 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
99506  Table *pTab = pIndex->pTable; /* The table that is indexed */
99507  int iTab = pParse->nTab++; /* Btree cursor used for pTab */
99508  int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
99509  int iSorter; /* Cursor opened by OpenSorter (if in use) */
99510  int addr1; /* Address of top of loop */
99511  int addr2; /* Address to jump to for next iteration */
99512  int tnum; /* Root page of index */
99513  int iPartIdxLabel; /* Jump to this label to skip a row */
99514  Vdbe *v; /* Generate code into this virtual machine */
99515  KeyInfo *pKey; /* KeyInfo for index */
99516  int regRecord; /* Register holding assembled index record */
99517  sqlite3 *db = pParse->db; /* The database connection */
99518  int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
99519 
99520 #ifndef SQLITE_OMIT_AUTHORIZATION
99521  if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
99522  db->aDb[iDb].zName ) ){
99523  return;
99524  }
99525 #endif
99526 
99527  /* Require a write-lock on the table to perform this operation */
99528  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
99529 
99530  v = sqlite3GetVdbe(pParse);
99531  if( v==0 ) return;
99532  if( memRootPage>=0 ){
99533  tnum = memRootPage;
99534  }else{
99535  tnum = pIndex->tnum;
99536  }
99537  pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
99538  assert( pKey!=0 || db->mallocFailed || pParse->nErr );
99539 
99540  /* Open the sorter cursor if we are to use one. */
99541  iSorter = pParse->nTab++;
99542  sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
99543  sqlite3KeyInfoRef(pKey), P4_KEYINFO);
99544 
99545  /* Open the table. Loop through all rows of the table, inserting index
99546  ** records into the sorter. */
99547  sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
99548  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
99549  regRecord = sqlite3GetTempReg(pParse);
99550 
99551  sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
99552  sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
99553  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
99554  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
99555  sqlite3VdbeJumpHere(v, addr1);
99556  if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
99557  sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
99558  (char *)pKey, P4_KEYINFO);
99559  sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
99560 
99561  addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
99562  if( IsUniqueIndex(pIndex) ){
99563  int j2 = sqlite3VdbeCurrentAddr(v) + 3;
99564  sqlite3VdbeGoto(v, j2);
99565  addr2 = sqlite3VdbeCurrentAddr(v);
99566  sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
99567  pIndex->nKeyCol); VdbeCoverage(v);
99568  sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
99569  }else{
99570  addr2 = sqlite3VdbeCurrentAddr(v);
99571  }
99572  sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
99573  sqlite3VdbeAddOp3(v, OP_Last, iIdx, 0, -1);
99574  sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 0);
99576  sqlite3ReleaseTempReg(pParse, regRecord);
99577  sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
99578  sqlite3VdbeJumpHere(v, addr1);
99579 
99580  sqlite3VdbeAddOp1(v, OP_Close, iTab);
99581  sqlite3VdbeAddOp1(v, OP_Close, iIdx);
99582  sqlite3VdbeAddOp1(v, OP_Close, iSorter);
99583 }
99584 
99585 /*
99586 ** Allocate heap space to hold an Index object with nCol columns.
99587 **
99588 ** Increase the allocation size to provide an extra nExtra bytes
99589 ** of 8-byte aligned space after the Index object and return a
99590 ** pointer to this extra space in *ppExtra.
99591 */
99593  sqlite3 *db, /* Database connection */
99594  i16 nCol, /* Total number of columns in the index */
99595  int nExtra, /* Number of bytes of extra space to alloc */
99596  char **ppExtra /* Pointer to the "extra" space */
99597 ){
99598  Index *p; /* Allocated index object */
99599  int nByte; /* Bytes of space for Index object + arrays */
99600 
99601  nByte = ROUND8(sizeof(Index)) + /* Index structure */
99602  ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
99603  ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
99604  sizeof(i16)*nCol + /* Index.aiColumn */
99605  sizeof(u8)*nCol); /* Index.aSortOrder */
99606  p = sqlite3DbMallocZero(db, nByte + nExtra);
99607  if( p ){
99608  char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
99609  p->azColl = (const char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
99610  p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
99611  p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
99612  p->aSortOrder = (u8*)pExtra;
99613  p->nColumn = nCol;
99614  p->nKeyCol = nCol - 1;
99615  *ppExtra = ((char*)p) + nByte;
99616  }
99617  return p;
99618 }
99619 
99620 /*
99621 ** Create a new index for an SQL table. pName1.pName2 is the name of the index
99622 ** and pTblList is the name of the table that is to be indexed. Both will
99623 ** be NULL for a primary key or an index that is created to satisfy a
99624 ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
99625 ** as the table to be indexed. pParse->pNewTable is a table that is
99626 ** currently being constructed by a CREATE TABLE statement.
99627 **
99628 ** pList is a list of columns to be indexed. pList will be NULL if this
99629 ** is a primary key or unique-constraint on the most recent column added
99630 ** to the table currently under construction.
99631 **
99632 ** If the index is created successfully, return a pointer to the new Index
99633 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
99634 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
99635 */
99637  Parse *pParse, /* All information about this parse */
99638  Token *pName1, /* First part of index name. May be NULL */
99639  Token *pName2, /* Second part of index name. May be NULL */
99640  SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
99641  ExprList *pList, /* A list of columns to be indexed */
99642  int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
99643  Token *pStart, /* The CREATE token that begins this statement */
99644  Expr *pPIWhere, /* WHERE clause for partial indices */
99645  int sortOrder, /* Sort order of primary key when pList==NULL */
99646  int ifNotExist /* Omit error if index already exists */
99647 ){
99648  Index *pRet = 0; /* Pointer to return */
99649  Table *pTab = 0; /* Table to be indexed */
99650  Index *pIndex = 0; /* The index to be created */
99651  char *zName = 0; /* Name of the index */
99652  int nName; /* Number of characters in zName */
99653  int i, j;
99654  DbFixer sFix; /* For assigning database names to pTable */
99655  int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
99656  sqlite3 *db = pParse->db;
99657  Db *pDb; /* The specific table containing the indexed database */
99658  int iDb; /* Index of the database that is being written */
99659  Token *pName = 0; /* Unqualified name of the index to create */
99660  struct ExprList_item *pListItem; /* For looping over pList */
99661  int nExtra = 0; /* Space allocated for zExtra[] */
99662  int nExtraCol; /* Number of extra columns needed */
99663  char *zExtra = 0; /* Extra space after the Index object */
99664  Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
99665 
99666  if( db->mallocFailed || IN_DECLARE_VTAB || pParse->nErr>0 ){
99667  goto exit_create_index;
99668  }
99669  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
99670  goto exit_create_index;
99671  }
99672 
99673  /*
99674  ** Find the table that is to be indexed. Return early if not found.
99675  */
99676  if( pTblName!=0 ){
99677 
99678  /* Use the two-part index name to determine the database
99679  ** to search for the table. 'Fix' the table name to this db
99680  ** before looking up the table.
99681  */
99682  assert( pName1 && pName2 );
99683  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
99684  if( iDb<0 ) goto exit_create_index;
99685  assert( pName && pName->z );
99686 
99687 #ifndef SQLITE_OMIT_TEMPDB
99688  /* If the index name was unqualified, check if the table
99689  ** is a temp table. If so, set the database to 1. Do not do this
99690  ** if initialising a database schema.
99691  */
99692  if( !db->init.busy ){
99693  pTab = sqlite3SrcListLookup(pParse, pTblName);
99694  if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
99695  iDb = 1;
99696  }
99697  }
99698 #endif
99699 
99700  sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
99701  if( sqlite3FixSrcList(&sFix, pTblName) ){
99702  /* Because the parser constructs pTblName from a single identifier,
99703  ** sqlite3FixSrcList can never fail. */
99704  assert(0);
99705  }
99706  pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
99707  assert( db->mallocFailed==0 || pTab==0 );
99708  if( pTab==0 ) goto exit_create_index;
99709  if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
99710  sqlite3ErrorMsg(pParse,
99711  "cannot create a TEMP index on non-TEMP table \"%s\"",
99712  pTab->zName);
99713  goto exit_create_index;
99714  }
99715  if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
99716  }else{
99717  assert( pName==0 );
99718  assert( pStart==0 );
99719  pTab = pParse->pNewTable;
99720  if( !pTab ) goto exit_create_index;
99721  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99722  }
99723  pDb = &db->aDb[iDb];
99724 
99725  assert( pTab!=0 );
99726  assert( pParse->nErr==0 );
99727  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
99728  && db->init.busy==0
99729 #if SQLITE_USER_AUTHENTICATION
99730  && sqlite3UserAuthTable(pTab->zName)==0
99731 #endif
99732  && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
99733  sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
99734  goto exit_create_index;
99735  }
99736 #ifndef SQLITE_OMIT_VIEW
99737  if( pTab->pSelect ){
99738  sqlite3ErrorMsg(pParse, "views may not be indexed");
99739  goto exit_create_index;
99740  }
99741 #endif
99742 #ifndef SQLITE_OMIT_VIRTUALTABLE
99743  if( IsVirtual(pTab) ){
99744  sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
99745  goto exit_create_index;
99746  }
99747 #endif
99748 
99749  /*
99750  ** Find the name of the index. Make sure there is not already another
99751  ** index or table with the same name.
99752  **
99753  ** Exception: If we are reading the names of permanent indices from the
99754  ** sqlite_master table (because some other process changed the schema) and
99755  ** one of the index names collides with the name of a temporary table or
99756  ** index, then we will continue to process this index.
99757  **
99758  ** If pName==0 it means that we are
99759  ** dealing with a primary key or UNIQUE constraint. We have to invent our
99760  ** own name.
99761  */
99762  if( pName ){
99763  zName = sqlite3NameFromToken(db, pName);
99764  if( zName==0 ) goto exit_create_index;
99765  assert( pName->z!=0 );
99766  if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
99767  goto exit_create_index;
99768  }
99769  if( !db->init.busy ){
99770  if( sqlite3FindTable(db, zName, 0)!=0 ){
99771  sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
99772  goto exit_create_index;
99773  }
99774  }
99775  if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
99776  if( !ifNotExist ){
99777  sqlite3ErrorMsg(pParse, "index %s already exists", zName);
99778  }else{
99779  assert( !db->init.busy );
99780  sqlite3CodeVerifySchema(pParse, iDb);
99781  }
99782  goto exit_create_index;
99783  }
99784  }else{
99785  int n;
99786  Index *pLoop;
99787  for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
99788  zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
99789  if( zName==0 ){
99790  goto exit_create_index;
99791  }
99792  }
99793 
99794  /* Check for authorization to create an index.
99795  */
99796 #ifndef SQLITE_OMIT_AUTHORIZATION
99797  {
99798  const char *zDb = pDb->zName;
99799  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
99800  goto exit_create_index;
99801  }
99802  i = SQLITE_CREATE_INDEX;
99803  if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
99804  if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
99805  goto exit_create_index;
99806  }
99807  }
99808 #endif
99809 
99810  /* If pList==0, it means this routine was called to make a primary
99811  ** key out of the last column added to the table under construction.
99812  ** So create a fake list to simulate this.
99813  */
99814  if( pList==0 ){
99815  Token prevCol;
99816  sqlite3TokenInit(&prevCol, pTab->aCol[pTab->nCol-1].zName);
99817  pList = sqlite3ExprListAppend(pParse, 0,
99818  sqlite3ExprAlloc(db, TK_ID, &prevCol, 0));
99819  if( pList==0 ) goto exit_create_index;
99820  assert( pList->nExpr==1 );
99821  sqlite3ExprListSetSortOrder(pList, sortOrder);
99822  }else{
99823  sqlite3ExprListCheckLength(pParse, pList, "index");
99824  }
99825 
99826  /* Figure out how many bytes of space are required to store explicitly
99827  ** specified collation sequence names.
99828  */
99829  for(i=0; i<pList->nExpr; i++){
99830  Expr *pExpr = pList->a[i].pExpr;
99831  assert( pExpr!=0 );
99832  if( pExpr->op==TK_COLLATE ){
99833  nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
99834  }
99835  }
99836 
99837  /*
99838  ** Allocate the index structure.
99839  */
99840  nName = sqlite3Strlen30(zName);
99841  nExtraCol = pPk ? pPk->nKeyCol : 1;
99842  pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
99843  nName + nExtra + 1, &zExtra);
99844  if( db->mallocFailed ){
99845  goto exit_create_index;
99846  }
99848  assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
99849  pIndex->zName = zExtra;
99850  zExtra += nName + 1;
99851  memcpy(pIndex->zName, zName, nName+1);
99852  pIndex->pTable = pTab;
99853  pIndex->onError = (u8)onError;
99854  pIndex->uniqNotNull = onError!=OE_None;
99856  pIndex->pSchema = db->aDb[iDb].pSchema;
99857  pIndex->nKeyCol = pList->nExpr;
99858  if( pPIWhere ){
99859  sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
99860  pIndex->pPartIdxWhere = pPIWhere;
99861  pPIWhere = 0;
99862  }
99863  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
99864 
99865  /* Check to see if we should honor DESC requests on index columns
99866  */
99867  if( pDb->pSchema->file_format>=4 ){
99868  sortOrderMask = -1; /* Honor DESC */
99869  }else{
99870  sortOrderMask = 0; /* Ignore DESC */
99871  }
99872 
99873  /* Analyze the list of expressions that form the terms of the index and
99874  ** report any errors. In the common case where the expression is exactly
99875  ** a table column, store that column in aiColumn[]. For general expressions,
99876  ** populate pIndex->aColExpr and store XN_EXPR (-2) in aiColumn[].
99877  **
99878  ** TODO: Issue a warning if two or more columns of the index are identical.
99879  ** TODO: Issue a warning if the table primary key is used as part of the
99880  ** index key.
99881  */
99882  for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
99883  Expr *pCExpr; /* The i-th index expression */
99884  int requestedSortOrder; /* ASC or DESC on the i-th expression */
99885  const char *zColl; /* Collation sequence name */
99886 
99887  sqlite3StringToId(pListItem->pExpr);
99888  sqlite3ResolveSelfReference(pParse, pTab, NC_IdxExpr, pListItem->pExpr, 0);
99889  if( pParse->nErr ) goto exit_create_index;
99890  pCExpr = sqlite3ExprSkipCollate(pListItem->pExpr);
99891  if( pCExpr->op!=TK_COLUMN ){
99892  if( pTab==pParse->pNewTable ){
99893  sqlite3ErrorMsg(pParse, "expressions prohibited in PRIMARY KEY and "
99894  "UNIQUE constraints");
99895  goto exit_create_index;
99896  }
99897  if( pIndex->aColExpr==0 ){
99898  ExprList *pCopy = sqlite3ExprListDup(db, pList, 0);
99899  pIndex->aColExpr = pCopy;
99900  if( !db->mallocFailed ){
99901  assert( pCopy!=0 );
99902  pListItem = &pCopy->a[i];
99903  }
99904  }
99905  j = XN_EXPR;
99906  pIndex->aiColumn[i] = XN_EXPR;
99907  pIndex->uniqNotNull = 0;
99908  }else{
99909  j = pCExpr->iColumn;
99910  assert( j<=0x7fff );
99911  if( j<0 ){
99912  j = pTab->iPKey;
99913  }else if( pTab->aCol[j].notNull==0 ){
99914  pIndex->uniqNotNull = 0;
99915  }
99916  pIndex->aiColumn[i] = (i16)j;
99917  }
99918  zColl = 0;
99919  if( pListItem->pExpr->op==TK_COLLATE ){
99920  int nColl;
99921  zColl = pListItem->pExpr->u.zToken;
99922  nColl = sqlite3Strlen30(zColl) + 1;
99923  assert( nExtra>=nColl );
99924  memcpy(zExtra, zColl, nColl);
99925  zColl = zExtra;
99926  zExtra += nColl;
99927  nExtra -= nColl;
99928  }else if( j>=0 ){
99929  zColl = pTab->aCol[j].zColl;
99930  }
99931  if( !zColl ) zColl = sqlite3StrBINARY;
99932  if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
99933  goto exit_create_index;
99934  }
99935  pIndex->azColl[i] = zColl;
99936  requestedSortOrder = pListItem->sortOrder & sortOrderMask;
99937  pIndex->aSortOrder[i] = (u8)requestedSortOrder;
99938  }
99939 
99940  /* Append the table key to the end of the index. For WITHOUT ROWID
99941  ** tables (when pPk!=0) this will be the declared PRIMARY KEY. For
99942  ** normal tables (when pPk==0) this will be the rowid.
99943  */
99944  if( pPk ){
99945  for(j=0; j<pPk->nKeyCol; j++){
99946  int x = pPk->aiColumn[j];
99947  assert( x>=0 );
99948  if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
99949  pIndex->nColumn--;
99950  }else{
99951  pIndex->aiColumn[i] = x;
99952  pIndex->azColl[i] = pPk->azColl[j];
99953  pIndex->aSortOrder[i] = pPk->aSortOrder[j];
99954  i++;
99955  }
99956  }
99957  assert( i==pIndex->nColumn );
99958  }else{
99959  pIndex->aiColumn[i] = XN_ROWID;
99960  pIndex->azColl[i] = sqlite3StrBINARY;
99961  }
99962  sqlite3DefaultRowEst(pIndex);
99963  if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
99964 
99965  /* If this index contains every column of its table, then mark
99966  ** it as a covering index */
99967  assert( HasRowid(pTab)
99968  || pTab->iPKey<0 || sqlite3ColumnOfIndex(pIndex, pTab->iPKey)>=0 );
99969  if( pTblName!=0 && pIndex->nColumn>=pTab->nCol ){
99970  pIndex->isCovering = 1;
99971  for(j=0; j<pTab->nCol; j++){
99972  if( j==pTab->iPKey ) continue;
99973  if( sqlite3ColumnOfIndex(pIndex,j)>=0 ) continue;
99974  pIndex->isCovering = 0;
99975  break;
99976  }
99977  }
99978 
99979  if( pTab==pParse->pNewTable ){
99980  /* This routine has been called to create an automatic index as a
99981  ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
99982  ** a PRIMARY KEY or UNIQUE clause following the column definitions.
99983  ** i.e. one of:
99984  **
99985  ** CREATE TABLE t(x PRIMARY KEY, y);
99986  ** CREATE TABLE t(x, y, UNIQUE(x, y));
99987  **
99988  ** Either way, check to see if the table already has such an index. If
99989  ** so, don't bother creating this one. This only applies to
99990  ** automatically created indices. Users can do as they wish with
99991  ** explicit indices.
99992  **
99993  ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
99994  ** (and thus suppressing the second one) even if they have different
99995  ** sort orders.
99996  **
99997  ** If there are different collating sequences or if the columns of
99998  ** the constraint occur in different orders, then the constraints are
99999  ** considered distinct and both result in separate indices.
100000  */
100001  Index *pIdx;
100002  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100003  int k;
100004  assert( IsUniqueIndex(pIdx) );
100006  assert( IsUniqueIndex(pIndex) );
100007 
100008  if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
100009  for(k=0; k<pIdx->nKeyCol; k++){
100010  const char *z1;
100011  const char *z2;
100012  assert( pIdx->aiColumn[k]>=0 );
100013  if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
100014  z1 = pIdx->azColl[k];
100015  z2 = pIndex->azColl[k];
100016  if( sqlite3StrICmp(z1, z2) ) break;
100017  }
100018  if( k==pIdx->nKeyCol ){
100019  if( pIdx->onError!=pIndex->onError ){
100020  /* This constraint creates the same index as a previous
100021  ** constraint specified somewhere in the CREATE TABLE statement.
100022  ** However the ON CONFLICT clauses are different. If both this
100023  ** constraint and the previous equivalent constraint have explicit
100024  ** ON CONFLICT clauses this is an error. Otherwise, use the
100025  ** explicitly specified behavior for the index.
100026  */
100027  if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
100028  sqlite3ErrorMsg(pParse,
100029  "conflicting ON CONFLICT clauses specified", 0);
100030  }
100031  if( pIdx->onError==OE_Default ){
100032  pIdx->onError = pIndex->onError;
100033  }
100034  }
100035  pRet = pIdx;
100036  goto exit_create_index;
100037  }
100038  }
100039  }
100040 
100041  /* Link the new Index structure to its table and to the other
100042  ** in-memory database structures.
100043  */
100044  assert( pParse->nErr==0 );
100045  if( db->init.busy ){
100046  Index *p;
100047  assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
100048  p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
100049  pIndex->zName, pIndex);
100050  if( p ){
100051  assert( p==pIndex ); /* Malloc must have failed */
100052  sqlite3OomFault(db);
100053  goto exit_create_index;
100054  }
100055  db->flags |= SQLITE_InternChanges;
100056  if( pTblName!=0 ){
100057  pIndex->tnum = db->init.newTnum;
100058  }
100059  }
100060 
100061  /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
100062  ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
100063  ** emit code to allocate the index rootpage on disk and make an entry for
100064  ** the index in the sqlite_master table and populate the index with
100065  ** content. But, do not do this if we are simply reading the sqlite_master
100066  ** table to parse the schema, or if this index is the PRIMARY KEY index
100067  ** of a WITHOUT ROWID table.
100068  **
100069  ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
100070  ** or UNIQUE index in a CREATE TABLE statement. Since the table
100071  ** has just been created, it contains no data and the index initialization
100072  ** step can be skipped.
100073  */
100074  else if( HasRowid(pTab) || pTblName!=0 ){
100075  Vdbe *v;
100076  char *zStmt;
100077  int iMem = ++pParse->nMem;
100078 
100079  v = sqlite3GetVdbe(pParse);
100080  if( v==0 ) goto exit_create_index;
100081 
100082  sqlite3BeginWriteOperation(pParse, 1, iDb);
100083 
100084  /* Create the rootpage for the index using CreateIndex. But before
100085  ** doing so, code a Noop instruction and store its address in
100086  ** Index.tnum. This is required in case this index is actually a
100087  ** PRIMARY KEY and the table is actually a WITHOUT ROWID table. In
100088  ** that case the convertToWithoutRowidTable() routine will replace
100089  ** the Noop with a Goto to jump over the VDBE code generated below. */
100090  pIndex->tnum = sqlite3VdbeAddOp0(v, OP_Noop);
100091  sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
100092 
100093  /* Gather the complete text of the CREATE INDEX statement into
100094  ** the zStmt variable
100095  */
100096  if( pStart ){
100097  int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
100098  if( pName->z[n-1]==';' ) n--;
100099  /* A named index with an explicit CREATE INDEX statement */
100100  zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
100101  onError==OE_None ? "" : " UNIQUE", n, pName->z);
100102  }else{
100103  /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
100104  /* zStmt = sqlite3MPrintf(""); */
100105  zStmt = 0;
100106  }
100107 
100108  /* Add an entry in sqlite_master for this index
100109  */
100110  sqlite3NestedParse(pParse,
100111  "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
100112  db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
100113  pIndex->zName,
100114  pTab->zName,
100115  iMem,
100116  zStmt
100117  );
100118  sqlite3DbFree(db, zStmt);
100119 
100120  /* Fill the index with data and reparse the schema. Code an OP_Expire
100121  ** to invalidate all pre-compiled statements.
100122  */
100123  if( pTblName ){
100124  sqlite3RefillIndex(pParse, pIndex, iMem);
100125  sqlite3ChangeCookie(pParse, iDb);
100127  sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
100128  sqlite3VdbeAddOp1(v, OP_Expire, 0);
100129  }
100130 
100131  sqlite3VdbeJumpHere(v, pIndex->tnum);
100132  }
100133 
100134  /* When adding an index to the list of indices for a table, make
100135  ** sure all indices labeled OE_Replace come after all those labeled
100136  ** OE_Ignore. This is necessary for the correct constraint check
100137  ** processing (in sqlite3GenerateConstraintChecks()) as part of
100138  ** UPDATE and INSERT statements.
100139  */
100140  if( db->init.busy || pTblName==0 ){
100141  if( onError!=OE_Replace || pTab->pIndex==0
100142  || pTab->pIndex->onError==OE_Replace){
100143  pIndex->pNext = pTab->pIndex;
100144  pTab->pIndex = pIndex;
100145  }else{
100146  Index *pOther = pTab->pIndex;
100147  while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
100148  pOther = pOther->pNext;
100149  }
100150  pIndex->pNext = pOther->pNext;
100151  pOther->pNext = pIndex;
100152  }
100153  pRet = pIndex;
100154  pIndex = 0;
100155  }
100156 
100157  /* Clean up before exiting */
100158 exit_create_index:
100159  if( pIndex ) freeIndex(db, pIndex);
100160  sqlite3ExprDelete(db, pPIWhere);
100161  sqlite3ExprListDelete(db, pList);
100162  sqlite3SrcListDelete(db, pTblName);
100163  sqlite3DbFree(db, zName);
100164  return pRet;
100165 }
100166 
100167 /*
100168 ** Fill the Index.aiRowEst[] array with default information - information
100169 ** to be used when we have not run the ANALYZE command.
100170 **
100171 ** aiRowEst[0] is supposed to contain the number of elements in the index.
100172 ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
100173 ** number of rows in the table that match any particular value of the
100174 ** first column of the index. aiRowEst[2] is an estimate of the number
100175 ** of rows that match any particular combination of the first 2 columns
100176 ** of the index. And so forth. It must always be the case that
100177 *
100178 ** aiRowEst[N]<=aiRowEst[N-1]
100179 ** aiRowEst[N]>=1
100180 **
100181 ** Apart from that, we have little to go on besides intuition as to
100182 ** how aiRowEst[] should be initialized. The numbers generated here
100183 ** are based on typical values found in actual indices.
100184 */
100186  /* 10, 9, 8, 7, 6 */
100187  LogEst aVal[] = { 33, 32, 30, 28, 26 };
100188  LogEst *a = pIdx->aiRowLogEst;
100189  int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
100190  int i;
100191 
100192  /* Set the first entry (number of rows in the index) to the estimated
100193  ** number of rows in the table. Or 10, if the estimated number of rows
100194  ** in the table is less than that. */
100195  a[0] = pIdx->pTable->nRowLogEst;
100196  if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
100197 
100198  /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
100199  ** 6 and each subsequent value (if any) is 5. */
100200  memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
100201  for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
100202  a[i] = 23; assert( 23==sqlite3LogEst(5) );
100203  }
100204 
100205  assert( 0==sqlite3LogEst(1) );
100206  if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
100207 }
100208 
100209 /*
100210 ** This routine will drop an existing named index. This routine
100211 ** implements the DROP INDEX statement.
100212 */
100213 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
100214  Index *pIndex;
100215  Vdbe *v;
100216  sqlite3 *db = pParse->db;
100217  int iDb;
100218 
100219  assert( pParse->nErr==0 ); /* Never called with prior errors */
100220  if( db->mallocFailed ){
100221  goto exit_drop_index;
100222  }
100223  assert( pName->nSrc==1 );
100224  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
100225  goto exit_drop_index;
100226  }
100227  pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
100228  if( pIndex==0 ){
100229  if( !ifExists ){
100230  sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
100231  }else{
100232  sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
100233  }
100234  pParse->checkSchema = 1;
100235  goto exit_drop_index;
100236  }
100237  if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
100238  sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
100239  "or PRIMARY KEY constraint cannot be dropped", 0);
100240  goto exit_drop_index;
100241  }
100242  iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
100243 #ifndef SQLITE_OMIT_AUTHORIZATION
100244  {
100245  int code = SQLITE_DROP_INDEX;
100246  Table *pTab = pIndex->pTable;
100247  const char *zDb = db->aDb[iDb].zName;
100248  const char *zTab = SCHEMA_TABLE(iDb);
100249  if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
100250  goto exit_drop_index;
100251  }
100252  if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
100253  if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
100254  goto exit_drop_index;
100255  }
100256  }
100257 #endif
100258 
100259  /* Generate code to remove the index and from the master table */
100260  v = sqlite3GetVdbe(pParse);
100261  if( v ){
100262  sqlite3BeginWriteOperation(pParse, 1, iDb);
100263  sqlite3NestedParse(pParse,
100264  "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
100265  db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
100266  );
100267  sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
100268  sqlite3ChangeCookie(pParse, iDb);
100269  destroyRootPage(pParse, pIndex->tnum, iDb);
100270  sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
100271  }
100272 
100273 exit_drop_index:
100274  sqlite3SrcListDelete(db, pName);
100275 }
100276 
100277 /*
100278 ** pArray is a pointer to an array of objects. Each object in the
100279 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
100280 ** to extend the array so that there is space for a new object at the end.
100281 **
100282 ** When this function is called, *pnEntry contains the current size of
100283 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
100284 ** in total).
100285 **
100286 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
100287 ** space allocated for the new object is zeroed, *pnEntry updated to
100288 ** reflect the new size of the array and a pointer to the new allocation
100289 ** returned. *pIdx is set to the index of the new array entry in this case.
100290 **
100291 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
100292 ** unchanged and a copy of pArray returned.
100293 */
100295  sqlite3 *db, /* Connection to notify of malloc failures */
100296  void *pArray, /* Array of objects. Might be reallocated */
100297  int szEntry, /* Size of each object in the array */
100298  int *pnEntry, /* Number of objects currently in use */
100299  int *pIdx /* Write the index of a new slot here */
100300 ){
100301  char *z;
100302  int n = *pnEntry;
100303  if( (n & (n-1))==0 ){
100304  int sz = (n==0) ? 1 : 2*n;
100305  void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
100306  if( pNew==0 ){
100307  *pIdx = -1;
100308  return pArray;
100309  }
100310  pArray = pNew;
100311  }
100312  z = (char*)pArray;
100313  memset(&z[n * szEntry], 0, szEntry);
100314  *pIdx = n;
100315  ++*pnEntry;
100316  return pArray;
100317 }
100318 
100319 /*
100320 ** Append a new element to the given IdList. Create a new IdList if
100321 ** need be.
100322 **
100323 ** A new IdList is returned, or NULL if malloc() fails.
100324 */
100326  int i;
100327  if( pList==0 ){
100328  pList = sqlite3DbMallocZero(db, sizeof(IdList) );
100329  if( pList==0 ) return 0;
100330  }
100331  pList->a = sqlite3ArrayAllocate(
100332  db,
100333  pList->a,
100334  sizeof(pList->a[0]),
100335  &pList->nId,
100336  &i
100337  );
100338  if( i<0 ){
100339  sqlite3IdListDelete(db, pList);
100340  return 0;
100341  }
100342  pList->a[i].zName = sqlite3NameFromToken(db, pToken);
100343  return pList;
100344 }
100345 
100346 /*
100347 ** Delete an IdList.
100348 */
100350  int i;
100351  if( pList==0 ) return;
100352  for(i=0; i<pList->nId; i++){
100353  sqlite3DbFree(db, pList->a[i].zName);
100354  }
100355  sqlite3DbFree(db, pList->a);
100356  sqlite3DbFree(db, pList);
100357 }
100358 
100359 /*
100360 ** Return the index in pList of the identifier named zId. Return -1
100361 ** if not found.
100362 */
100363 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
100364  int i;
100365  if( pList==0 ) return -1;
100366  for(i=0; i<pList->nId; i++){
100367  if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
100368  }
100369  return -1;
100370 }
100371 
100372 /*
100373 ** Expand the space allocated for the given SrcList object by
100374 ** creating nExtra new slots beginning at iStart. iStart is zero based.
100375 ** New slots are zeroed.
100376 **
100377 ** For example, suppose a SrcList initially contains two entries: A,B.
100378 ** To append 3 new entries onto the end, do this:
100379 **
100380 ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
100381 **
100382 ** After the call above it would contain: A, B, nil, nil, nil.
100383 ** If the iStart argument had been 1 instead of 2, then the result
100384 ** would have been: A, nil, nil, nil, B. To prepend the new slots,
100385 ** the iStart value would be 0. The result then would
100386 ** be: nil, nil, nil, A, B.
100387 **
100388 ** If a memory allocation fails the SrcList is unchanged. The
100389 ** db->mallocFailed flag will be set to true.
100390 */
100392  sqlite3 *db, /* Database connection to notify of OOM errors */
100393  SrcList *pSrc, /* The SrcList to be enlarged */
100394  int nExtra, /* Number of new slots to add to pSrc->a[] */
100395  int iStart /* Index in pSrc->a[] of first new slot */
100396 ){
100397  int i;
100398 
100399  /* Sanity checking on calling parameters */
100400  assert( iStart>=0 );
100401  assert( nExtra>=1 );
100402  assert( pSrc!=0 );
100403  assert( iStart<=pSrc->nSrc );
100404 
100405  /* Allocate additional space if needed */
100406  if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
100407  SrcList *pNew;
100408  int nAlloc = pSrc->nSrc+nExtra;
100409  int nGot;
100410  pNew = sqlite3DbRealloc(db, pSrc,
100411  sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
100412  if( pNew==0 ){
100413  assert( db->mallocFailed );
100414  return pSrc;
100415  }
100416  pSrc = pNew;
100417  nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
100418  pSrc->nAlloc = nGot;
100419  }
100420 
100421  /* Move existing slots that come after the newly inserted slots
100422  ** out of the way */
100423  for(i=pSrc->nSrc-1; i>=iStart; i--){
100424  pSrc->a[i+nExtra] = pSrc->a[i];
100425  }
100426  pSrc->nSrc += nExtra;
100427 
100428  /* Zero the newly allocated slots */
100429  memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
100430  for(i=iStart; i<iStart+nExtra; i++){
100431  pSrc->a[i].iCursor = -1;
100432  }
100433 
100434  /* Return a pointer to the enlarged SrcList */
100435  return pSrc;
100436 }
100437 
100438 
100439 /*
100440 ** Append a new table name to the given SrcList. Create a new SrcList if
100441 ** need be. A new entry is created in the SrcList even if pTable is NULL.
100442 **
100443 ** A SrcList is returned, or NULL if there is an OOM error. The returned
100444 ** SrcList might be the same as the SrcList that was input or it might be
100445 ** a new one. If an OOM error does occurs, then the prior value of pList
100446 ** that is input to this routine is automatically freed.
100447 **
100448 ** If pDatabase is not null, it means that the table has an optional
100449 ** database name prefix. Like this: "database.table". The pDatabase
100450 ** points to the table name and the pTable points to the database name.
100451 ** The SrcList.a[].zName field is filled with the table name which might
100452 ** come from pTable (if pDatabase is NULL) or from pDatabase.
100453 ** SrcList.a[].zDatabase is filled with the database name from pTable,
100454 ** or with NULL if no database is specified.
100455 **
100456 ** In other words, if call like this:
100457 **
100458 ** sqlite3SrcListAppend(D,A,B,0);
100459 **
100460 ** Then B is a table name and the database name is unspecified. If called
100461 ** like this:
100462 **
100463 ** sqlite3SrcListAppend(D,A,B,C);
100464 **
100465 ** Then C is the table name and B is the database name. If C is defined
100466 ** then so is B. In other words, we never have a case where:
100467 **
100468 ** sqlite3SrcListAppend(D,A,0,C);
100469 **
100470 ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
100471 ** before being added to the SrcList.
100472 */
100474  sqlite3 *db, /* Connection to notify of malloc failures */
100475  SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
100476  Token *pTable, /* Table to append */
100477  Token *pDatabase /* Database of the table */
100478 ){
100479  struct SrcList_item *pItem;
100480  assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
100481  assert( db!=0 );
100482  if( pList==0 ){
100483  pList = sqlite3DbMallocRawNN(db, sizeof(SrcList) );
100484  if( pList==0 ) return 0;
100485  pList->nAlloc = 1;
100486  pList->nSrc = 0;
100487  }
100488  pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
100489  if( db->mallocFailed ){
100490  sqlite3SrcListDelete(db, pList);
100491  return 0;
100492  }
100493  pItem = &pList->a[pList->nSrc-1];
100494  if( pDatabase && pDatabase->z==0 ){
100495  pDatabase = 0;
100496  }
100497  if( pDatabase ){
100498  Token *pTemp = pDatabase;
100499  pDatabase = pTable;
100500  pTable = pTemp;
100501  }
100502  pItem->zName = sqlite3NameFromToken(db, pTable);
100503  pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
100504  return pList;
100505 }
100506 
100507 /*
100508 ** Assign VdbeCursor index numbers to all tables in a SrcList
100509 */
100511  int i;
100512  struct SrcList_item *pItem;
100513  assert(pList || pParse->db->mallocFailed );
100514  if( pList ){
100515  for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
100516  if( pItem->iCursor>=0 ) break;
100517  pItem->iCursor = pParse->nTab++;
100518  if( pItem->pSelect ){
100519  sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
100520  }
100521  }
100522  }
100523 }
100524 
100525 /*
100526 ** Delete an entire SrcList including all its substructure.
100527 */
100529  int i;
100530  struct SrcList_item *pItem;
100531  if( pList==0 ) return;
100532  for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
100533  sqlite3DbFree(db, pItem->zDatabase);
100534  sqlite3DbFree(db, pItem->zName);
100535  sqlite3DbFree(db, pItem->zAlias);
100536  if( pItem->fg.isIndexedBy ) sqlite3DbFree(db, pItem->u1.zIndexedBy);
100537  if( pItem->fg.isTabFunc ) sqlite3ExprListDelete(db, pItem->u1.pFuncArg);
100538  sqlite3DeleteTable(db, pItem->pTab);
100539  sqlite3SelectDelete(db, pItem->pSelect);
100540  sqlite3ExprDelete(db, pItem->pOn);
100541  sqlite3IdListDelete(db, pItem->pUsing);
100542  }
100543  sqlite3DbFree(db, pList);
100544 }
100545 
100546 /*
100547 ** This routine is called by the parser to add a new term to the
100548 ** end of a growing FROM clause. The "p" parameter is the part of
100549 ** the FROM clause that has already been constructed. "p" is NULL
100550 ** if this is the first term of the FROM clause. pTable and pDatabase
100551 ** are the name of the table and database named in the FROM clause term.
100552 ** pDatabase is NULL if the database name qualifier is missing - the
100553 ** usual case. If the term has an alias, then pAlias points to the
100554 ** alias token. If the term is a subquery, then pSubquery is the
100555 ** SELECT statement that the subquery encodes. The pTable and
100556 ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
100557 ** parameters are the content of the ON and USING clauses.
100558 **
100559 ** Return a new SrcList which encodes is the FROM with the new
100560 ** term added.
100561 */
100563  Parse *pParse, /* Parsing context */
100564  SrcList *p, /* The left part of the FROM clause already seen */
100565  Token *pTable, /* Name of the table to add to the FROM clause */
100566  Token *pDatabase, /* Name of the database containing pTable */
100567  Token *pAlias, /* The right-hand side of the AS subexpression */
100568  Select *pSubquery, /* A subquery used in place of a table name */
100569  Expr *pOn, /* The ON clause of a join */
100570  IdList *pUsing /* The USING clause of a join */
100571 ){
100572  struct SrcList_item *pItem;
100573  sqlite3 *db = pParse->db;
100574  if( !p && (pOn || pUsing) ){
100575  sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
100576  (pOn ? "ON" : "USING")
100577  );
100578  goto append_from_error;
100579  }
100580  p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
100581  if( p==0 || NEVER(p->nSrc==0) ){
100582  goto append_from_error;
100583  }
100584  pItem = &p->a[p->nSrc-1];
100585  assert( pAlias!=0 );
100586  if( pAlias->n ){
100587  pItem->zAlias = sqlite3NameFromToken(db, pAlias);
100588  }
100589  pItem->pSelect = pSubquery;
100590  pItem->pOn = pOn;
100591  pItem->pUsing = pUsing;
100592  return p;
100593 
100594  append_from_error:
100595  assert( p==0 );
100596  sqlite3ExprDelete(db, pOn);
100597  sqlite3IdListDelete(db, pUsing);
100598  sqlite3SelectDelete(db, pSubquery);
100599  return 0;
100600 }
100601 
100602 /*
100603 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
100604 ** element of the source-list passed as the second argument.
100605 */
100607  assert( pIndexedBy!=0 );
100608  if( p && ALWAYS(p->nSrc>0) ){
100609  struct SrcList_item *pItem = &p->a[p->nSrc-1];
100610  assert( pItem->fg.notIndexed==0 );
100611  assert( pItem->fg.isIndexedBy==0 );
100612  assert( pItem->fg.isTabFunc==0 );
100613  if( pIndexedBy->n==1 && !pIndexedBy->z ){
100614  /* A "NOT INDEXED" clause was supplied. See parse.y
100615  ** construct "indexed_opt" for details. */
100616  pItem->fg.notIndexed = 1;
100617  }else{
100618  pItem->u1.zIndexedBy = sqlite3NameFromToken(pParse->db, pIndexedBy);
100619  pItem->fg.isIndexedBy = (pItem->u1.zIndexedBy!=0);
100620  }
100621  }
100622 }
100623 
100624 /*
100625 ** Add the list of function arguments to the SrcList entry for a
100626 ** table-valued-function.
100627 */
100629  if( p ){
100630  struct SrcList_item *pItem = &p->a[p->nSrc-1];
100631  assert( pItem->fg.notIndexed==0 );
100632  assert( pItem->fg.isIndexedBy==0 );
100633  assert( pItem->fg.isTabFunc==0 );
100634  pItem->u1.pFuncArg = pList;
100635  pItem->fg.isTabFunc = 1;
100636  }else{
100637  sqlite3ExprListDelete(pParse->db, pList);
100638  }
100639 }
100640 
100641 /*
100642 ** When building up a FROM clause in the parser, the join operator
100643 ** is initially attached to the left operand. But the code generator
100644 ** expects the join operator to be on the right operand. This routine
100645 ** Shifts all join operators from left to right for an entire FROM
100646 ** clause.
100647 **
100648 ** Example: Suppose the join is like this:
100649 **
100650 ** A natural cross join B
100651 **
100652 ** The operator is "natural cross join". The A and B operands are stored
100653 ** in p->a[0] and p->a[1], respectively. The parser initially stores the
100654 ** operator with A. This routine shifts that operator over to B.
100655 */
100657  if( p ){
100658  int i;
100659  for(i=p->nSrc-1; i>0; i--){
100660  p->a[i].fg.jointype = p->a[i-1].fg.jointype;
100661  }
100662  p->a[0].fg.jointype = 0;
100663  }
100664 }
100665 
100666 /*
100667 ** Generate VDBE code for a BEGIN statement.
100668 */
100670  sqlite3 *db;
100671  Vdbe *v;
100672  int i;
100673 
100674  assert( pParse!=0 );
100675  db = pParse->db;
100676  assert( db!=0 );
100677  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
100678  return;
100679  }
100680  v = sqlite3GetVdbe(pParse);
100681  if( !v ) return;
100682  if( type!=TK_DEFERRED ){
100683  for(i=0; i<db->nDb; i++){
100684  sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
100685  sqlite3VdbeUsesBtree(v, i);
100686  }
100687  }
100689 }
100690 
100691 /*
100692 ** Generate VDBE code for a COMMIT statement.
100693 */
100695  Vdbe *v;
100696 
100697  assert( pParse!=0 );
100698  assert( pParse->db!=0 );
100699  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
100700  return;
100701  }
100702  v = sqlite3GetVdbe(pParse);
100703  if( v ){
100705  }
100706 }
100707 
100708 /*
100709 ** Generate VDBE code for a ROLLBACK statement.
100710 */
100712  Vdbe *v;
100713 
100714  assert( pParse!=0 );
100715  assert( pParse->db!=0 );
100716  if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
100717  return;
100718  }
100719  v = sqlite3GetVdbe(pParse);
100720  if( v ){
100721  sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
100722  }
100723 }
100724 
100725 /*
100726 ** This function is called by the parser when it parses a command to create,
100727 ** release or rollback an SQL savepoint.
100728 */
100729 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
100730  char *zName = sqlite3NameFromToken(pParse->db, pName);
100731  if( zName ){
100732  Vdbe *v = sqlite3GetVdbe(pParse);
100733 #ifndef SQLITE_OMIT_AUTHORIZATION
100734  static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
100736 #endif
100737  if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
100738  sqlite3DbFree(pParse->db, zName);
100739  return;
100740  }
100741  sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
100742  }
100743 }
100744 
100745 /*
100746 ** Make sure the TEMP database is open and available for use. Return
100747 ** the number of errors. Leave any error messages in the pParse structure.
100748 */
100750  sqlite3 *db = pParse->db;
100751  if( db->aDb[1].pBt==0 && !pParse->explain ){
100752  int rc;
100753  Btree *pBt;
100754  static const int flags =
100760 
100761  rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
100762  if( rc!=SQLITE_OK ){
100763  sqlite3ErrorMsg(pParse, "unable to open a temporary database "
100764  "file for storing temporary tables");
100765  pParse->rc = rc;
100766  return 1;
100767  }
100768  db->aDb[1].pBt = pBt;
100769  assert( db->aDb[1].pSchema );
100770  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
100771  sqlite3OomFault(db);
100772  return 1;
100773  }
100774  }
100775  return 0;
100776 }
100777 
100778 /*
100779 ** Record the fact that the schema cookie will need to be verified
100780 ** for database iDb. The code to actually verify the schema cookie
100781 ** will occur at the end of the top-level VDBE and will be generated
100782 ** later, by sqlite3FinishCoding().
100783 */
100785  Parse *pToplevel = sqlite3ParseToplevel(pParse);
100786  sqlite3 *db = pToplevel->db;
100787 
100788  assert( iDb>=0 && iDb<db->nDb );
100789  assert( db->aDb[iDb].pBt!=0 || iDb==1 );
100790  assert( iDb<SQLITE_MAX_ATTACHED+2 );
100791  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
100792  if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
100793  DbMaskSet(pToplevel->cookieMask, iDb);
100794  pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
100795  if( !OMIT_TEMPDB && iDb==1 ){
100796  sqlite3OpenTempDatabase(pToplevel);
100797  }
100798  }
100799 }
100800 
100801 /*
100802 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
100803 ** attached database. Otherwise, invoke it for the database named zDb only.
100804 */
100805 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
100806  sqlite3 *db = pParse->db;
100807  int i;
100808  for(i=0; i<db->nDb; i++){
100809  Db *pDb = &db->aDb[i];
100810  if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
100811  sqlite3CodeVerifySchema(pParse, i);
100812  }
100813  }
100814 }
100815 
100816 /*
100817 ** Generate VDBE code that prepares for doing an operation that
100818 ** might change the database.
100819 **
100820 ** This routine starts a new transaction if we are not already within
100821 ** a transaction. If we are already within a transaction, then a checkpoint
100822 ** is set if the setStatement parameter is true. A checkpoint should
100823 ** be set for operations that might fail (due to a constraint) part of
100824 ** the way through and which will need to undo some writes without having to
100825 ** rollback the whole transaction. For operations where all constraints
100826 ** can be checked before any changes are made to the database, it is never
100827 ** necessary to undo a write and the checkpoint should not be set.
100828 */
100829 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
100830  Parse *pToplevel = sqlite3ParseToplevel(pParse);
100831  sqlite3CodeVerifySchema(pParse, iDb);
100832  DbMaskSet(pToplevel->writeMask, iDb);
100833  pToplevel->isMultiWrite |= setStatement;
100834 }
100835 
100836 /*
100837 ** Indicate that the statement currently under construction might write
100838 ** more than one entry (example: deleting one row then inserting another,
100839 ** inserting multiple rows in a table, or inserting a row and index entries.)
100840 ** If an abort occurs after some of these writes have completed, then it will
100841 ** be necessary to undo the completed writes.
100842 */
100844  Parse *pToplevel = sqlite3ParseToplevel(pParse);
100845  pToplevel->isMultiWrite = 1;
100846 }
100847 
100848 /*
100849 ** The code generator calls this routine if is discovers that it is
100850 ** possible to abort a statement prior to completion. In order to
100851 ** perform this abort without corrupting the database, we need to make
100852 ** sure that the statement is protected by a statement transaction.
100853 **
100854 ** Technically, we only need to set the mayAbort flag if the
100855 ** isMultiWrite flag was previously set. There is a time dependency
100856 ** such that the abort must occur after the multiwrite. This makes
100857 ** some statements involving the REPLACE conflict resolution algorithm
100858 ** go a little faster. But taking advantage of this time dependency
100859 ** makes it more difficult to prove that the code is correct (in
100860 ** particular, it prevents us from writing an effective
100861 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
100862 ** to take the safe route and skip the optimization.
100863 */
100865  Parse *pToplevel = sqlite3ParseToplevel(pParse);
100866  pToplevel->mayAbort = 1;
100867 }
100868 
100869 /*
100870 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
100871 ** error. The onError parameter determines which (if any) of the statement
100872 ** and/or current transaction is rolled back.
100873 */
100875  Parse *pParse, /* Parsing context */
100876  int errCode, /* extended error code */
100877  int onError, /* Constraint type */
100878  char *p4, /* Error message */
100879  i8 p4type, /* P4_STATIC or P4_TRANSIENT */
100880  u8 p5Errmsg /* P5_ErrMsg type */
100881 ){
100882  Vdbe *v = sqlite3GetVdbe(pParse);
100883  assert( (errCode&0xff)==SQLITE_CONSTRAINT );
100884  if( onError==OE_Abort ){
100885  sqlite3MayAbort(pParse);
100886  }
100887  sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
100888  sqlite3VdbeChangeP5(v, p5Errmsg);
100889 }
100890 
100891 /*
100892 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
100893 */
100895  Parse *pParse, /* Parsing context */
100896  int onError, /* Constraint type */
100897  Index *pIdx /* The index that triggers the constraint */
100898 ){
100899  char *zErr;
100900  int j;
100901  StrAccum errMsg;
100902  Table *pTab = pIdx->pTable;
100903 
100904  sqlite3StrAccumInit(&errMsg, pParse->db, 0, 0, 200);
100905  if( pIdx->aColExpr ){
100906  sqlite3XPrintf(&errMsg, "index '%q'", pIdx->zName);
100907  }else{
100908  for(j=0; j<pIdx->nKeyCol; j++){
100909  char *zCol;
100910  assert( pIdx->aiColumn[j]>=0 );
100911  zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
100912  if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
100913  sqlite3XPrintf(&errMsg, "%s.%s", pTab->zName, zCol);
100914  }
100915  }
100916  zErr = sqlite3StrAccumFinish(&errMsg);
100917  sqlite3HaltConstraint(pParse,
100920  onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
100921 }
100922 
100923 
100924 /*
100925 ** Code an OP_Halt due to non-unique rowid.
100926 */
100928  Parse *pParse, /* Parsing context */
100929  int onError, /* Conflict resolution algorithm */
100930  Table *pTab /* The table with the non-unique rowid */
100931 ){
100932  char *zMsg;
100933  int rc;
100934  if( pTab->iPKey>=0 ){
100935  zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
100936  pTab->aCol[pTab->iPKey].zName);
100938  }else{
100939  zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
100941  }
100942  sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
100944 }
100945 
100946 /*
100947 ** Check to see if pIndex uses the collating sequence pColl. Return
100948 ** true if it does and false if it does not.
100949 */
100950 #ifndef SQLITE_OMIT_REINDEX
100951 static int collationMatch(const char *zColl, Index *pIndex){
100952  int i;
100953  assert( zColl!=0 );
100954  for(i=0; i<pIndex->nColumn; i++){
100955  const char *z = pIndex->azColl[i];
100956  assert( z!=0 || pIndex->aiColumn[i]<0 );
100957  if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
100958  return 1;
100959  }
100960  }
100961  return 0;
100962 }
100963 #endif
100964 
100965 /*
100966 ** Recompute all indices of pTab that use the collating sequence pColl.
100967 ** If pColl==0 then recompute all indices of pTab.
100968 */
100969 #ifndef SQLITE_OMIT_REINDEX
100970 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
100971  Index *pIndex; /* An index associated with pTab */
100972 
100973  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
100974  if( zColl==0 || collationMatch(zColl, pIndex) ){
100975  int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100976  sqlite3BeginWriteOperation(pParse, 0, iDb);
100977  sqlite3RefillIndex(pParse, pIndex, -1);
100978  }
100979  }
100980 }
100981 #endif
100982 
100983 /*
100984 ** Recompute all indices of all tables in all databases where the
100985 ** indices use the collating sequence pColl. If pColl==0 then recompute
100986 ** all indices everywhere.
100987 */
100988 #ifndef SQLITE_OMIT_REINDEX
100989 static void reindexDatabases(Parse *pParse, char const *zColl){
100990  Db *pDb; /* A single database */
100991  int iDb; /* The database index number */
100992  sqlite3 *db = pParse->db; /* The database connection */
100993  HashElem *k; /* For looping over tables in pDb */
100994  Table *pTab; /* A table in the database */
100995 
100996  assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
100997  for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
100998  assert( pDb!=0 );
100999  for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
101000  pTab = (Table*)sqliteHashData(k);
101001  reindexTable(pParse, pTab, zColl);
101002  }
101003  }
101004 }
101005 #endif
101006 
101007 /*
101008 ** Generate code for the REINDEX command.
101009 **
101010 ** REINDEX -- 1
101011 ** REINDEX <collation> -- 2
101012 ** REINDEX ?<database>.?<tablename> -- 3
101013 ** REINDEX ?<database>.?<indexname> -- 4
101014 **
101015 ** Form 1 causes all indices in all attached databases to be rebuilt.
101016 ** Form 2 rebuilds all indices in all databases that use the named
101017 ** collating function. Forms 3 and 4 rebuild the named index or all
101018 ** indices associated with the named table.
101019 */
101020 #ifndef SQLITE_OMIT_REINDEX
101021 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
101022  CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
101023  char *z; /* Name of a table or index */
101024  const char *zDb; /* Name of the database */
101025  Table *pTab; /* A table in the database */
101026  Index *pIndex; /* An index associated with pTab */
101027  int iDb; /* The database index number */
101028  sqlite3 *db = pParse->db; /* The database connection */
101029  Token *pObjName; /* Name of the table or index to be reindexed */
101030 
101031  /* Read the database schema. If an error occurs, leave an error message
101032  ** and code in pParse and return NULL. */
101033  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
101034  return;
101035  }
101036 
101037  if( pName1==0 ){
101038  reindexDatabases(pParse, 0);
101039  return;
101040  }else if( NEVER(pName2==0) || pName2->z==0 ){
101041  char *zColl;
101042  assert( pName1->z );
101043  zColl = sqlite3NameFromToken(pParse->db, pName1);
101044  if( !zColl ) return;
101045  pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
101046  if( pColl ){
101047  reindexDatabases(pParse, zColl);
101048  sqlite3DbFree(db, zColl);
101049  return;
101050  }
101051  sqlite3DbFree(db, zColl);
101052  }
101053  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
101054  if( iDb<0 ) return;
101055  z = sqlite3NameFromToken(db, pObjName);
101056  if( z==0 ) return;
101057  zDb = db->aDb[iDb].zName;
101058  pTab = sqlite3FindTable(db, z, zDb);
101059  if( pTab ){
101060  reindexTable(pParse, pTab, 0);
101061  sqlite3DbFree(db, z);
101062  return;
101063  }
101064  pIndex = sqlite3FindIndex(db, z, zDb);
101065  sqlite3DbFree(db, z);
101066  if( pIndex ){
101067  sqlite3BeginWriteOperation(pParse, 0, iDb);
101068  sqlite3RefillIndex(pParse, pIndex, -1);
101069  return;
101070  }
101071  sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
101072 }
101073 #endif
101074 
101075 /*
101076 ** Return a KeyInfo structure that is appropriate for the given Index.
101077 **
101078 ** The KeyInfo structure for an index is cached in the Index object.
101079 ** So there might be multiple references to the returned pointer. The
101080 ** caller should not try to modify the KeyInfo object.
101081 **
101082 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
101083 ** when it has finished using it.
101084 */
101086  int i;
101087  int nCol = pIdx->nColumn;
101088  int nKey = pIdx->nKeyCol;
101089  KeyInfo *pKey;
101090  if( pParse->nErr ) return 0;
101091  if( pIdx->uniqNotNull ){
101092  pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
101093  }else{
101094  pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
101095  }
101096  if( pKey ){
101097  assert( sqlite3KeyInfoIsWriteable(pKey) );
101098  for(i=0; i<nCol; i++){
101099  const char *zColl = pIdx->azColl[i];
101100  pKey->aColl[i] = zColl==sqlite3StrBINARY ? 0 :
101101  sqlite3LocateCollSeq(pParse, zColl);
101102  pKey->aSortOrder[i] = pIdx->aSortOrder[i];
101103  }
101104  if( pParse->nErr ){
101105  sqlite3KeyInfoUnref(pKey);
101106  pKey = 0;
101107  }
101108  }
101109  return pKey;
101110 }
101111 
101112 #ifndef SQLITE_OMIT_CTE
101113 /*
101114 ** This routine is invoked once per CTE by the parser while parsing a
101115 ** WITH clause.
101116 */
101118  Parse *pParse, /* Parsing context */
101119  With *pWith, /* Existing WITH clause, or NULL */
101120  Token *pName, /* Name of the common-table */
101121  ExprList *pArglist, /* Optional column name list for the table */
101122  Select *pQuery /* Query used to initialize the table */
101123 ){
101124  sqlite3 *db = pParse->db;
101125  With *pNew;
101126  char *zName;
101127 
101128  /* Check that the CTE name is unique within this WITH clause. If
101129  ** not, store an error in the Parse structure. */
101130  zName = sqlite3NameFromToken(pParse->db, pName);
101131  if( zName && pWith ){
101132  int i;
101133  for(i=0; i<pWith->nCte; i++){
101134  if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
101135  sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
101136  }
101137  }
101138  }
101139 
101140  if( pWith ){
101141  int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
101142  pNew = sqlite3DbRealloc(db, pWith, nByte);
101143  }else{
101144  pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
101145  }
101146  assert( (pNew!=0 && zName!=0) || db->mallocFailed );
101147 
101148  if( db->mallocFailed ){
101149  sqlite3ExprListDelete(db, pArglist);
101150  sqlite3SelectDelete(db, pQuery);
101151  sqlite3DbFree(db, zName);
101152  pNew = pWith;
101153  }else{
101154  pNew->a[pNew->nCte].pSelect = pQuery;
101155  pNew->a[pNew->nCte].pCols = pArglist;
101156  pNew->a[pNew->nCte].zName = zName;
101157  pNew->a[pNew->nCte].zCteErr = 0;
101158  pNew->nCte++;
101159  }
101160 
101161  return pNew;
101162 }
101163 
101164 /*
101165 ** Free the contents of the With object passed as the second argument.
101166 */
101168  if( pWith ){
101169  int i;
101170  for(i=0; i<pWith->nCte; i++){
101171  struct Cte *pCte = &pWith->a[i];
101172  sqlite3ExprListDelete(db, pCte->pCols);
101173  sqlite3SelectDelete(db, pCte->pSelect);
101174  sqlite3DbFree(db, pCte->zName);
101175  }
101176  sqlite3DbFree(db, pWith);
101177  }
101178 }
101179 #endif /* !defined(SQLITE_OMIT_CTE) */
101180 
101181 /************** End of build.c ***********************************************/
101182 /************** Begin file callback.c ****************************************/
101183 /*
101184 ** 2005 May 23
101185 **
101186 ** The author disclaims copyright to this source code. In place of
101187 ** a legal notice, here is a blessing:
101188 **
101189 ** May you do good and not evil.
101190 ** May you find forgiveness for yourself and forgive others.
101191 ** May you share freely, never taking more than you give.
101192 **
101193 *************************************************************************
101194 **
101195 ** This file contains functions used to access the internal hash tables
101196 ** of user defined functions and collation sequences.
101197 */
101198 
101199 /* #include "sqliteInt.h" */
101200 
101201 /*
101202 ** Invoke the 'collation needed' callback to request a collation sequence
101203 ** in the encoding enc of name zName, length nName.
101204 */
101205 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
101206  assert( !db->xCollNeeded || !db->xCollNeeded16 );
101207  if( db->xCollNeeded ){
101208  char *zExternal = sqlite3DbStrDup(db, zName);
101209  if( !zExternal ) return;
101210  db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
101211  sqlite3DbFree(db, zExternal);
101212  }
101213 #ifndef SQLITE_OMIT_UTF16
101214  if( db->xCollNeeded16 ){
101215  char const *zExternal;
101216  sqlite3_value *pTmp = sqlite3ValueNew(db);
101217  sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
101218  zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
101219  if( zExternal ){
101220  db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
101221  }
101222  sqlite3ValueFree(pTmp);
101223  }
101224 #endif
101225 }
101226 
101227 /*
101228 ** This routine is called if the collation factory fails to deliver a
101229 ** collation function in the best encoding but there may be other versions
101230 ** of this collation function (for other text encodings) available. Use one
101231 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
101232 ** possible.
101233 */
101234 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
101235  CollSeq *pColl2;
101236  char *z = pColl->zName;
101237  int i;
101238  static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
101239  for(i=0; i<3; i++){
101240  pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
101241  if( pColl2->xCmp!=0 ){
101242  memcpy(pColl, pColl2, sizeof(CollSeq));
101243  pColl->xDel = 0; /* Do not copy the destructor */
101244  return SQLITE_OK;
101245  }
101246  }
101247  return SQLITE_ERROR;
101248 }
101249 
101250 /*
101251 ** This function is responsible for invoking the collation factory callback
101252 ** or substituting a collation sequence of a different encoding when the
101253 ** requested collation sequence is not available in the desired encoding.
101254 **
101255 ** If it is not NULL, then pColl must point to the database native encoding
101256 ** collation sequence with name zName, length nName.
101257 **
101258 ** The return value is either the collation sequence to be used in database
101259 ** db for collation type name zName, length nName, or NULL, if no collation
101260 ** sequence can be found. If no collation is found, leave an error message.
101261 **
101262 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
101263 */
101265  Parse *pParse, /* Parsing context */
101266  u8 enc, /* The desired encoding for the collating sequence */
101267  CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
101268  const char *zName /* Collating sequence name */
101269 ){
101270  CollSeq *p;
101271  sqlite3 *db = pParse->db;
101272 
101273  p = pColl;
101274  if( !p ){
101275  p = sqlite3FindCollSeq(db, enc, zName, 0);
101276  }
101277  if( !p || !p->xCmp ){
101278  /* No collation sequence of this type for this encoding is registered.
101279  ** Call the collation factory to see if it can supply us with one.
101280  */
101281  callCollNeeded(db, enc, zName);
101282  p = sqlite3FindCollSeq(db, enc, zName, 0);
101283  }
101284  if( p && !p->xCmp && synthCollSeq(db, p) ){
101285  p = 0;
101286  }
101287  assert( !p || p->xCmp );
101288  if( p==0 ){
101289  sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
101290  }
101291  return p;
101292 }
101293 
101294 /*
101295 ** This routine is called on a collation sequence before it is used to
101296 ** check that it is defined. An undefined collation sequence exists when
101297 ** a database is loaded that contains references to collation sequences
101298 ** that have not been defined by sqlite3_create_collation() etc.
101299 **
101300 ** If required, this routine calls the 'collation needed' callback to
101301 ** request a definition of the collating sequence. If this doesn't work,
101302 ** an equivalent collating sequence that uses a text encoding different
101303 ** from the main database is substituted, if one is available.
101304 */
101306  if( pColl ){
101307  const char *zName = pColl->zName;
101308  sqlite3 *db = pParse->db;
101309  CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
101310  if( !p ){
101311  return SQLITE_ERROR;
101312  }
101313  assert( p==pColl );
101314  }
101315  return SQLITE_OK;
101316 }
101317 
101318 
101319 
101320 /*
101321 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
101322 ** specified by zName and nName is not found and parameter 'create' is
101323 ** true, then create a new entry. Otherwise return NULL.
101324 **
101325 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
101326 ** array of three CollSeq structures. The first is the collation sequence
101327 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
101328 **
101329 ** Stored immediately after the three collation sequences is a copy of
101330 ** the collation sequence name. A pointer to this string is stored in
101331 ** each collation sequence structure.
101332 */
101334  sqlite3 *db, /* Database connection */
101335  const char *zName, /* Name of the collating sequence */
101336  int create /* Create a new entry if true */
101337 ){
101338  CollSeq *pColl;
101339  pColl = sqlite3HashFind(&db->aCollSeq, zName);
101340 
101341  if( 0==pColl && create ){
101342  int nName = sqlite3Strlen30(zName);
101343  pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
101344  if( pColl ){
101345  CollSeq *pDel = 0;
101346  pColl[0].zName = (char*)&pColl[3];
101347  pColl[0].enc = SQLITE_UTF8;
101348  pColl[1].zName = (char*)&pColl[3];
101349  pColl[1].enc = SQLITE_UTF16LE;
101350  pColl[2].zName = (char*)&pColl[3];
101351  pColl[2].enc = SQLITE_UTF16BE;
101352  memcpy(pColl[0].zName, zName, nName);
101353  pColl[0].zName[nName] = 0;
101354  pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
101355 
101356  /* If a malloc() failure occurred in sqlite3HashInsert(), it will
101357  ** return the pColl pointer to be deleted (because it wasn't added
101358  ** to the hash table).
101359  */
101360  assert( pDel==0 || pDel==pColl );
101361  if( pDel!=0 ){
101362  sqlite3OomFault(db);
101363  sqlite3DbFree(db, pDel);
101364  pColl = 0;
101365  }
101366  }
101367  }
101368  return pColl;
101369 }
101370 
101371 /*
101372 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
101373 ** Return the CollSeq* pointer for the collation sequence named zName
101374 ** for the encoding 'enc' from the database 'db'.
101375 **
101376 ** If the entry specified is not found and 'create' is true, then create a
101377 ** new entry. Otherwise return NULL.
101378 **
101379 ** A separate function sqlite3LocateCollSeq() is a wrapper around
101380 ** this routine. sqlite3LocateCollSeq() invokes the collation factory
101381 ** if necessary and generates an error message if the collating sequence
101382 ** cannot be found.
101383 **
101384 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
101385 */
101387  sqlite3 *db,
101388  u8 enc,
101389  const char *zName,
101390  int create
101391 ){
101392  CollSeq *pColl;
101393  if( zName ){
101394  pColl = findCollSeqEntry(db, zName, create);
101395  }else{
101396  pColl = db->pDfltColl;
101397  }
101398  assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
101399  assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
101400  if( pColl ) pColl += enc-1;
101401  return pColl;
101402 }
101403 
101404 /* During the search for the best function definition, this procedure
101405 ** is called to test how well the function passed as the first argument
101406 ** matches the request for a function with nArg arguments in a system
101407 ** that uses encoding enc. The value returned indicates how well the
101408 ** request is matched. A higher value indicates a better match.
101409 **
101410 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
101411 ** is also -1. In other words, we are searching for a function that
101412 ** takes a variable number of arguments.
101413 **
101414 ** If nArg is -2 that means that we are searching for any function
101415 ** regardless of the number of arguments it uses, so return a positive
101416 ** match score for any
101417 **
101418 ** The returned value is always between 0 and 6, as follows:
101419 **
101420 ** 0: Not a match.
101421 ** 1: UTF8/16 conversion required and function takes any number of arguments.
101422 ** 2: UTF16 byte order change required and function takes any number of args.
101423 ** 3: encoding matches and function takes any number of arguments
101424 ** 4: UTF8/16 conversion required - argument count matches exactly
101425 ** 5: UTF16 byte order conversion required - argument count matches exactly
101426 ** 6: Perfect match: encoding and argument count match exactly.
101427 **
101428 ** If nArg==(-2) then any function with a non-null xSFunc is
101429 ** a perfect match and any function with xSFunc NULL is
101430 ** a non-match.
101431 */
101432 #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
101433 static int matchQuality(
101434  FuncDef *p, /* The function we are evaluating for match quality */
101435  int nArg, /* Desired number of arguments. (-1)==any */
101436  u8 enc /* Desired text encoding */
101437 ){
101438  int match;
101439 
101440  /* nArg of -2 is a special case */
101441  if( nArg==(-2) ) return (p->xSFunc==0) ? 0 : FUNC_PERFECT_MATCH;
101442 
101443  /* Wrong number of arguments means "no match" */
101444  if( p->nArg!=nArg && p->nArg>=0 ) return 0;
101445 
101446  /* Give a better score to a function with a specific number of arguments
101447  ** than to function that accepts any number of arguments. */
101448  if( p->nArg==nArg ){
101449  match = 4;
101450  }else{
101451  match = 1;
101452  }
101453 
101454  /* Bonus points if the text encoding matches */
101455  if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
101456  match += 2; /* Exact encoding match */
101457  }else if( (enc & p->funcFlags & 2)!=0 ){
101458  match += 1; /* Both are UTF16, but with different byte orders */
101459  }
101460 
101461  return match;
101462 }
101463 
101464 /*
101465 ** Search a FuncDefHash for a function with the given name. Return
101466 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
101467 */
101469  int h, /* Hash of the name */
101470  const char *zFunc /* Name of function */
101471 ){
101472  FuncDef *p;
101473  for(p=sqlite3BuiltinFunctions.a[h]; p; p=p->u.pHash){
101474  if( sqlite3StrICmp(p->zName, zFunc)==0 ){
101475  return p;
101476  }
101477  }
101478  return 0;
101479 }
101480 
101481 /*
101482 ** Insert a new FuncDef into a FuncDefHash hash table.
101483 */
101485  FuncDef *aDef, /* List of global functions to be inserted */
101486  int nDef /* Length of the apDef[] list */
101487 ){
101488  int i;
101489  for(i=0; i<nDef; i++){
101490  FuncDef *pOther;
101491  const char *zName = aDef[i].zName;
101492  int nName = sqlite3Strlen30(zName);
101493  int h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
101494  pOther = functionSearch(h, zName);
101495  if( pOther ){
101496  assert( pOther!=&aDef[i] && pOther->pNext!=&aDef[i] );
101497  aDef[i].pNext = pOther->pNext;
101498  pOther->pNext = &aDef[i];
101499  }else{
101500  aDef[i].pNext = 0;
101501  aDef[i].u.pHash = sqlite3BuiltinFunctions.a[h];
101502  sqlite3BuiltinFunctions.a[h] = &aDef[i];
101503  }
101504  }
101505 }
101506 
101507 
101508 
101509 /*
101510 ** Locate a user function given a name, a number of arguments and a flag
101511 ** indicating whether the function prefers UTF-16 over UTF-8. Return a
101512 ** pointer to the FuncDef structure that defines that function, or return
101513 ** NULL if the function does not exist.
101514 **
101515 ** If the createFlag argument is true, then a new (blank) FuncDef
101516 ** structure is created and liked into the "db" structure if a
101517 ** no matching function previously existed.
101518 **
101519 ** If nArg is -2, then the first valid function found is returned. A
101520 ** function is valid if xSFunc is non-zero. The nArg==(-2)
101521 ** case is used to see if zName is a valid function name for some number
101522 ** of arguments. If nArg is -2, then createFlag must be 0.
101523 **
101524 ** If createFlag is false, then a function with the required name and
101525 ** number of arguments may be returned even if the eTextRep flag does not
101526 ** match that requested.
101527 */
101529  sqlite3 *db, /* An open database */
101530  const char *zName, /* Name of the function. zero-terminated */
101531  int nArg, /* Number of arguments. -1 means any number */
101532  u8 enc, /* Preferred text encoding */
101533  u8 createFlag /* Create new entry if true and does not otherwise exist */
101534 ){
101535  FuncDef *p; /* Iterator variable */
101536  FuncDef *pBest = 0; /* Best match found so far */
101537  int bestScore = 0; /* Score of best match */
101538  int h; /* Hash value */
101539  int nName; /* Length of the name */
101540 
101541  assert( nArg>=(-2) );
101542  assert( nArg>=(-1) || createFlag==0 );
101543  nName = sqlite3Strlen30(zName);
101544 
101545  /* First search for a match amongst the application-defined functions.
101546  */
101547  p = (FuncDef*)sqlite3HashFind(&db->aFunc, zName);
101548  while( p ){
101549  int score = matchQuality(p, nArg, enc);
101550  if( score>bestScore ){
101551  pBest = p;
101552  bestScore = score;
101553  }
101554  p = p->pNext;
101555  }
101556 
101557  /* If no match is found, search the built-in functions.
101558  **
101559  ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
101560  ** functions even if a prior app-defined function was found. And give
101561  ** priority to built-in functions.
101562  **
101563  ** Except, if createFlag is true, that means that we are trying to
101564  ** install a new function. Whatever FuncDef structure is returned it will
101565  ** have fields overwritten with new information appropriate for the
101566  ** new function. But the FuncDefs for built-in functions are read-only.
101567  ** So we must not search for built-ins when creating a new function.
101568  */
101569  if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
101570  bestScore = 0;
101571  h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % SQLITE_FUNC_HASH_SZ;
101572  p = functionSearch(h, zName);
101573  while( p ){
101574  int score = matchQuality(p, nArg, enc);
101575  if( score>bestScore ){
101576  pBest = p;
101577  bestScore = score;
101578  }
101579  p = p->pNext;
101580  }
101581  }
101582 
101583  /* If the createFlag parameter is true and the search did not reveal an
101584  ** exact match for the name, number of arguments and encoding, then add a
101585  ** new entry to the hash table and return it.
101586  */
101587  if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
101588  (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
101589  FuncDef *pOther;
101590  pBest->zName = (const char*)&pBest[1];
101591  pBest->nArg = (u16)nArg;
101592  pBest->funcFlags = enc;
101593  memcpy((char*)&pBest[1], zName, nName+1);
101594  pOther = (FuncDef*)sqlite3HashInsert(&db->aFunc, pBest->zName, pBest);
101595  if( pOther==pBest ){
101596  sqlite3DbFree(db, pBest);
101597  sqlite3OomFault(db);
101598  return 0;
101599  }else{
101600  pBest->pNext = pOther;
101601  }
101602  }
101603 
101604  if( pBest && (pBest->xSFunc || createFlag) ){
101605  return pBest;
101606  }
101607  return 0;
101608 }
101609 
101610 /*
101611 ** Free all resources held by the schema structure. The void* argument points
101612 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
101613 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
101614 ** of the schema hash tables).
101615 **
101616 ** The Schema.cache_size variable is not cleared.
101617 */
101619  Hash temp1;
101620  Hash temp2;
101621  HashElem *pElem;
101622  Schema *pSchema = (Schema *)p;
101623 
101624  temp1 = pSchema->tblHash;
101625  temp2 = pSchema->trigHash;
101626  sqlite3HashInit(&pSchema->trigHash);
101627  sqlite3HashClear(&pSchema->idxHash);
101628  for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
101630  }
101631  sqlite3HashClear(&temp2);
101632  sqlite3HashInit(&pSchema->tblHash);
101633  for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
101634  Table *pTab = sqliteHashData(pElem);
101635  sqlite3DeleteTable(0, pTab);
101636  }
101637  sqlite3HashClear(&temp1);
101638  sqlite3HashClear(&pSchema->fkeyHash);
101639  pSchema->pSeqTab = 0;
101640  if( pSchema->schemaFlags & DB_SchemaLoaded ){
101641  pSchema->iGeneration++;
101642  pSchema->schemaFlags &= ~DB_SchemaLoaded;
101643  }
101644 }
101645 
101646 /*
101647 ** Find and return the schema associated with a BTree. Create
101648 ** a new one if necessary.
101649 */
101651  Schema * p;
101652  if( pBt ){
101653  p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
101654  }else{
101655  p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
101656  }
101657  if( !p ){
101658  sqlite3OomFault(db);
101659  }else if ( 0==p->file_format ){
101660  sqlite3HashInit(&p->tblHash);
101661  sqlite3HashInit(&p->idxHash);
101662  sqlite3HashInit(&p->trigHash);
101663  sqlite3HashInit(&p->fkeyHash);
101664  p->enc = SQLITE_UTF8;
101665  }
101666  return p;
101667 }
101668 
101669 /************** End of callback.c ********************************************/
101670 /************** Begin file delete.c ******************************************/
101671 /*
101672 ** 2001 September 15
101673 **
101674 ** The author disclaims copyright to this source code. In place of
101675 ** a legal notice, here is a blessing:
101676 **
101677 ** May you do good and not evil.
101678 ** May you find forgiveness for yourself and forgive others.
101679 ** May you share freely, never taking more than you give.
101680 **
101681 *************************************************************************
101682 ** This file contains C code routines that are called by the parser
101683 ** in order to generate code for DELETE FROM statements.
101684 */
101685 /* #include "sqliteInt.h" */
101686 
101687 /*
101688 ** While a SrcList can in general represent multiple tables and subqueries
101689 ** (as in the FROM clause of a SELECT statement) in this case it contains
101690 ** the name of a single table, as one might find in an INSERT, DELETE,
101691 ** or UPDATE statement. Look up that table in the symbol table and
101692 ** return a pointer. Set an error message and return NULL if the table
101693 ** name is not found or if any other error occurs.
101694 **
101695 ** The following fields are initialized appropriate in pSrc:
101696 **
101697 ** pSrc->a[0].pTab Pointer to the Table object
101698 ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
101699 **
101700 */
101702  struct SrcList_item *pItem = pSrc->a;
101703  Table *pTab;
101704  assert( pItem && pSrc->nSrc==1 );
101705  pTab = sqlite3LocateTableItem(pParse, 0, pItem);
101706  sqlite3DeleteTable(pParse->db, pItem->pTab);
101707  pItem->pTab = pTab;
101708  if( pTab ){
101709  pTab->nRef++;
101710  }
101711  if( sqlite3IndexedByLookup(pParse, pItem) ){
101712  pTab = 0;
101713  }
101714  return pTab;
101715 }
101716 
101717 /*
101718 ** Check to make sure the given table is writable. If it is not
101719 ** writable, generate an error message and return 1. If it is
101720 ** writable return 0;
101721 */
101722 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
101723  /* A table is not writable under the following circumstances:
101724  **
101725  ** 1) It is a virtual table and no implementation of the xUpdate method
101726  ** has been provided, or
101727  ** 2) It is a system table (i.e. sqlite_master), this call is not
101728  ** part of a nested parse and writable_schema pragma has not
101729  ** been specified.
101730  **
101731  ** In either case leave an error message in pParse and return non-zero.
101732  */
101733  if( ( IsVirtual(pTab)
101734  && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
101735  || ( (pTab->tabFlags & TF_Readonly)!=0
101736  && (pParse->db->flags & SQLITE_WriteSchema)==0
101737  && pParse->nested==0 )
101738  ){
101739  sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
101740  return 1;
101741  }
101742 
101743 #ifndef SQLITE_OMIT_VIEW
101744  if( !viewOk && pTab->pSelect ){
101745  sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
101746  return 1;
101747  }
101748 #endif
101749  return 0;
101750 }
101751 
101752 
101753 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
101754 /*
101755 ** Evaluate a view and store its result in an ephemeral table. The
101756 ** pWhere argument is an optional WHERE clause that restricts the
101757 ** set of rows in the view that are to be added to the ephemeral table.
101758 */
101760  Parse *pParse, /* Parsing context */
101761  Table *pView, /* View definition */
101762  Expr *pWhere, /* Optional WHERE clause to be added */
101763  int iCur /* Cursor number for ephemeral table */
101764 ){
101765  SelectDest dest;
101766  Select *pSel;
101767  SrcList *pFrom;
101768  sqlite3 *db = pParse->db;
101769  int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
101770  pWhere = sqlite3ExprDup(db, pWhere, 0);
101771  pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
101772  if( pFrom ){
101773  assert( pFrom->nSrc==1 );
101774  pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
101775  pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
101776  assert( pFrom->a[0].pOn==0 );
101777  assert( pFrom->a[0].pUsing==0 );
101778  }
101779  pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0,
101780  SF_IncludeHidden, 0, 0);
101781  sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
101782  sqlite3Select(pParse, pSel, &dest);
101783  sqlite3SelectDelete(db, pSel);
101784 }
101785 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
101786 
101787 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
101788 /*
101789 ** Generate an expression tree to implement the WHERE, ORDER BY,
101790 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
101791 **
101792 ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
101793 ** \__________________________/
101794 ** pLimitWhere (pInClause)
101795 */
101796 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
101797  Parse *pParse, /* The parser context */
101798  SrcList *pSrc, /* the FROM clause -- which tables to scan */
101799  Expr *pWhere, /* The WHERE clause. May be null */
101800  ExprList *pOrderBy, /* The ORDER BY clause. May be null */
101801  Expr *pLimit, /* The LIMIT clause. May be null */
101802  Expr *pOffset, /* The OFFSET clause. May be null */
101803  char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
101804 ){
101805  Expr *pWhereRowid = NULL; /* WHERE rowid .. */
101806  Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
101807  Expr *pSelectRowid = NULL; /* SELECT rowid ... */
101808  ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
101809  SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
101810  Select *pSelect = NULL; /* Complete SELECT tree */
101811 
101812  /* Check that there isn't an ORDER BY without a LIMIT clause.
101813  */
101814  if( pOrderBy && (pLimit == 0) ) {
101815  sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
101816  goto limit_where_cleanup;
101817  }
101818 
101819  /* We only need to generate a select expression if there
101820  ** is a limit/offset term to enforce.
101821  */
101822  if( pLimit == 0 ) {
101823  /* if pLimit is null, pOffset will always be null as well. */
101824  assert( pOffset == 0 );
101825  return pWhere;
101826  }
101827 
101828  /* Generate a select expression tree to enforce the limit/offset
101829  ** term for the DELETE or UPDATE statement. For example:
101830  ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
101831  ** becomes:
101832  ** DELETE FROM table_a WHERE rowid IN (
101833  ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
101834  ** );
101835  */
101836 
101837  pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
101838  if( pSelectRowid == 0 ) goto limit_where_cleanup;
101839  pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
101840  if( pEList == 0 ) goto limit_where_cleanup;
101841 
101842  /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
101843  ** and the SELECT subtree. */
101844  pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
101845  if( pSelectSrc == 0 ) {
101846  sqlite3ExprListDelete(pParse->db, pEList);
101847  goto limit_where_cleanup;
101848  }
101849 
101850  /* generate the SELECT expression tree. */
101851  pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
101852  pOrderBy,0,pLimit,pOffset);
101853  if( pSelect == 0 ) return 0;
101854 
101855  /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
101856  pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
101857  pInClause = pWhereRowid ? sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0) : 0;
101858  sqlite3PExprAddSelect(pParse, pInClause, pSelect);
101859  return pInClause;
101860 
101861 limit_where_cleanup:
101862  sqlite3ExprDelete(pParse->db, pWhere);
101863  sqlite3ExprListDelete(pParse->db, pOrderBy);
101864  sqlite3ExprDelete(pParse->db, pLimit);
101865  sqlite3ExprDelete(pParse->db, pOffset);
101866  return 0;
101867 }
101868 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
101869  /* && !defined(SQLITE_OMIT_SUBQUERY) */
101870 
101871 /*
101872 ** Generate code for a DELETE FROM statement.
101873 **
101874 ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
101875 ** \________/ \________________/
101876 ** pTabList pWhere
101877 */
101879  Parse *pParse, /* The parser context */
101880  SrcList *pTabList, /* The table from which we should delete things */
101881  Expr *pWhere /* The WHERE clause. May be null */
101882 ){
101883  Vdbe *v; /* The virtual database engine */
101884  Table *pTab; /* The table from which records will be deleted */
101885  const char *zDb; /* Name of database holding pTab */
101886  int i; /* Loop counter */
101887  WhereInfo *pWInfo; /* Information about the WHERE clause */
101888  Index *pIdx; /* For looping over indices of the table */
101889  int iTabCur; /* Cursor number for the table */
101890  int iDataCur = 0; /* VDBE cursor for the canonical data source */
101891  int iIdxCur = 0; /* Cursor number of the first index */
101892  int nIdx; /* Number of indices */
101893  sqlite3 *db; /* Main database structure */
101894  AuthContext sContext; /* Authorization context */
101895  NameContext sNC; /* Name context to resolve expressions in */
101896  int iDb; /* Database number */
101897  int memCnt = -1; /* Memory cell used for change counting */
101898  int rcauth; /* Value returned by authorization callback */
101899  int eOnePass; /* ONEPASS_OFF or _SINGLE or _MULTI */
101900  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
101901  u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
101902  Index *pPk; /* The PRIMARY KEY index on the table */
101903  int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
101904  i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
101905  int iKey; /* Memory cell holding key of row to be deleted */
101906  i16 nKey; /* Number of memory cells in the row key */
101907  int iEphCur = 0; /* Ephemeral table holding all primary key values */
101908  int iRowSet = 0; /* Register for rowset of rows to delete */
101909  int addrBypass = 0; /* Address of jump over the delete logic */
101910  int addrLoop = 0; /* Top of the delete loop */
101911  int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
101912  int bComplex; /* True if there are triggers or FKs or
101913  ** subqueries in the WHERE clause */
101914 
101915 #ifndef SQLITE_OMIT_TRIGGER
101916  int isView; /* True if attempting to delete from a view */
101917  Trigger *pTrigger; /* List of table triggers, if required */
101918 #endif
101919 
101920  memset(&sContext, 0, sizeof(sContext));
101921  db = pParse->db;
101922  if( pParse->nErr || db->mallocFailed ){
101923  goto delete_from_cleanup;
101924  }
101925  assert( pTabList->nSrc==1 );
101926 
101927  /* Locate the table which we want to delete. This table has to be
101928  ** put in an SrcList structure because some of the subroutines we
101929  ** will be calling are designed to work with multiple tables and expect
101930  ** an SrcList* parameter instead of just a Table* parameter.
101931  */
101932  pTab = sqlite3SrcListLookup(pParse, pTabList);
101933  if( pTab==0 ) goto delete_from_cleanup;
101934 
101935  /* Figure out if we have any triggers and if the table being
101936  ** deleted from is a view
101937  */
101938 #ifndef SQLITE_OMIT_TRIGGER
101939  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
101940  isView = pTab->pSelect!=0;
101941  bComplex = pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0);
101942 #else
101943 # define pTrigger 0
101944 # define isView 0
101945 #endif
101946 #ifdef SQLITE_OMIT_VIEW
101947 # undef isView
101948 # define isView 0
101949 #endif
101950 
101951  /* If pTab is really a view, make sure it has been initialized.
101952  */
101953  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
101954  goto delete_from_cleanup;
101955  }
101956 
101957  if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
101958  goto delete_from_cleanup;
101959  }
101960  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
101961  assert( iDb<db->nDb );
101962  zDb = db->aDb[iDb].zName;
101963  rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
101964  assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
101965  if( rcauth==SQLITE_DENY ){
101966  goto delete_from_cleanup;
101967  }
101968  assert(!isView || pTrigger);
101969 
101970  /* Assign cursor numbers to the table and all its indices.
101971  */
101972  assert( pTabList->nSrc==1 );
101973  iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
101974  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
101975  pParse->nTab++;
101976  }
101977 
101978  /* Start the view context
101979  */
101980  if( isView ){
101981  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
101982  }
101983 
101984  /* Begin generating code.
101985  */
101986  v = sqlite3GetVdbe(pParse);
101987  if( v==0 ){
101988  goto delete_from_cleanup;
101989  }
101990  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
101991  sqlite3BeginWriteOperation(pParse, 1, iDb);
101992 
101993  /* If we are trying to delete from a view, realize that view into
101994  ** an ephemeral table.
101995  */
101996 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
101997  if( isView ){
101998  sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
101999  iDataCur = iIdxCur = iTabCur;
102000  }
102001 #endif
102002 
102003  /* Resolve the column names in the WHERE clause.
102004  */
102005  memset(&sNC, 0, sizeof(sNC));
102006  sNC.pParse = pParse;
102007  sNC.pSrcList = pTabList;
102008  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
102009  goto delete_from_cleanup;
102010  }
102011 
102012  /* Initialize the counter of the number of rows deleted, if
102013  ** we are counting rows.
102014  */
102015  if( db->flags & SQLITE_CountRows ){
102016  memCnt = ++pParse->nMem;
102017  sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
102018  }
102019 
102020 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
102021  /* Special case: A DELETE without a WHERE clause deletes everything.
102022  ** It is easier just to erase the whole table. Prior to version 3.6.5,
102023  ** this optimization caused the row change count (the value returned by
102024  ** API function sqlite3_count_changes) to be set incorrectly. */
102025  if( rcauth==SQLITE_OK
102026  && pWhere==0
102027  && !bComplex
102028  && !IsVirtual(pTab)
102029 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
102030  && db->xPreUpdateCallback==0
102031 #endif
102032  ){
102033  assert( !isView );
102034  sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
102035  if( HasRowid(pTab) ){
102036  sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
102037  pTab->zName, P4_STATIC);
102038  }
102039  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
102040  assert( pIdx->pSchema==pTab->pSchema );
102041  sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
102042  }
102043  }else
102044 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
102045  {
102047  if( sNC.ncFlags & NC_VarSelect ) bComplex = 1;
102048  wcf |= (bComplex ? 0 : WHERE_ONEPASS_MULTIROW);
102049  if( HasRowid(pTab) ){
102050  /* For a rowid table, initialize the RowSet to an empty set */
102051  pPk = 0;
102052  nPk = 1;
102053  iRowSet = ++pParse->nMem;
102054  sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
102055  }else{
102056  /* For a WITHOUT ROWID table, create an ephemeral table used to
102057  ** hold all primary keys for rows to be deleted. */
102058  pPk = sqlite3PrimaryKeyIndex(pTab);
102059  assert( pPk!=0 );
102060  nPk = pPk->nKeyCol;
102061  iPk = pParse->nMem+1;
102062  pParse->nMem += nPk;
102063  iEphCur = pParse->nTab++;
102064  addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
102065  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
102066  }
102067 
102068  /* Construct a query to find the rowid or primary key for every row
102069  ** to be deleted, based on the WHERE clause. Set variable eOnePass
102070  ** to indicate the strategy used to implement this delete:
102071  **
102072  ** ONEPASS_OFF: Two-pass approach - use a FIFO for rowids/PK values.
102073  ** ONEPASS_SINGLE: One-pass approach - at most one row deleted.
102074  ** ONEPASS_MULTI: One-pass approach - any number of rows may be deleted.
102075  */
102076  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, wcf, iTabCur+1);
102077  if( pWInfo==0 ) goto delete_from_cleanup;
102078  eOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
102079  assert( IsVirtual(pTab)==0 || eOnePass!=ONEPASS_MULTI );
102080  assert( IsVirtual(pTab) || bComplex || eOnePass!=ONEPASS_OFF );
102081 
102082  /* Keep track of the number of rows to be deleted */
102083  if( db->flags & SQLITE_CountRows ){
102084  sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
102085  }
102086 
102087  /* Extract the rowid or primary key for the current row */
102088  if( pPk ){
102089  for(i=0; i<nPk; i++){
102090  assert( pPk->aiColumn[i]>=0 );
102091  sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
102092  pPk->aiColumn[i], iPk+i);
102093  }
102094  iKey = iPk;
102095  }else{
102096  iKey = pParse->nMem + 1;
102097  iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
102098  if( iKey>pParse->nMem ) pParse->nMem = iKey;
102099  }
102100 
102101  if( eOnePass!=ONEPASS_OFF ){
102102  /* For ONEPASS, no need to store the rowid/primary-key. There is only
102103  ** one, so just keep it in its register(s) and fall through to the
102104  ** delete code. */
102105  nKey = nPk; /* OP_Found will use an unpacked key */
102106  aToOpen = sqlite3DbMallocRawNN(db, nIdx+2);
102107  if( aToOpen==0 ){
102108  sqlite3WhereEnd(pWInfo);
102109  goto delete_from_cleanup;
102110  }
102111  memset(aToOpen, 1, nIdx+1);
102112  aToOpen[nIdx+1] = 0;
102113  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
102114  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
102115  if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
102116  }else{
102117  if( pPk ){
102118  /* Add the PK key for this row to the temporary table */
102119  iKey = ++pParse->nMem;
102120  nKey = 0; /* Zero tells OP_Found to use a composite key */
102121  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
102122  sqlite3IndexAffinityStr(pParse->db, pPk), nPk);
102123  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
102124  }else{
102125  /* Add the rowid of the row to be deleted to the RowSet */
102126  nKey = 1; /* OP_Seek always uses a single rowid */
102127  sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
102128  }
102129  }
102130 
102131  /* If this DELETE cannot use the ONEPASS strategy, this is the
102132  ** end of the WHERE loop */
102133  if( eOnePass!=ONEPASS_OFF ){
102134  addrBypass = sqlite3VdbeMakeLabel(v);
102135  }else{
102136  sqlite3WhereEnd(pWInfo);
102137  }
102138 
102139  /* Unless this is a view, open cursors for the table we are
102140  ** deleting from and all its indices. If this is a view, then the
102141  ** only effect this statement has is to fire the INSTEAD OF
102142  ** triggers.
102143  */
102144  if( !isView ){
102145  int iAddrOnce = 0;
102146  if( eOnePass==ONEPASS_MULTI ){
102147  iAddrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
102148  }
102149  testcase( IsVirtual(pTab) );
102151  iTabCur, aToOpen, &iDataCur, &iIdxCur);
102152  assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
102153  assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
102154  if( eOnePass==ONEPASS_MULTI ) sqlite3VdbeJumpHere(v, iAddrOnce);
102155  }
102156 
102157  /* Set up a loop over the rowids/primary-keys that were found in the
102158  ** where-clause loop above.
102159  */
102160  if( eOnePass!=ONEPASS_OFF ){
102161  assert( nKey==nPk ); /* OP_Found will use an unpacked key */
102162  if( !IsVirtual(pTab) && aToOpen[iDataCur-iTabCur] ){
102163  assert( pPk!=0 || pTab->pSelect!=0 );
102164  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
102165  VdbeCoverage(v);
102166  }
102167  }else if( pPk ){
102168  addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
102169  sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
102170  assert( nKey==0 ); /* OP_Found will use a composite key */
102171  }else{
102172  addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
102173  VdbeCoverage(v);
102174  assert( nKey==1 );
102175  }
102176 
102177  /* Delete the row */
102178 #ifndef SQLITE_OMIT_VIRTUALTABLE
102179  if( IsVirtual(pTab) ){
102180  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
102181  sqlite3VtabMakeWritable(pParse, pTab);
102182  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
102184  assert( eOnePass==ONEPASS_OFF || eOnePass==ONEPASS_SINGLE );
102185  sqlite3MayAbort(pParse);
102186  if( eOnePass==ONEPASS_SINGLE && sqlite3IsToplevel(pParse) ){
102187  pParse->isMultiWrite = 0;
102188  }
102189  }else
102190 #endif
102191  {
102192  int count = (pParse->nested==0); /* True to count changes */
102193  int iIdxNoSeek = -1;
102194  if( bComplex==0 && aiCurOnePass[1]!=iDataCur ){
102195  iIdxNoSeek = aiCurOnePass[1];
102196  }
102197  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
102198  iKey, nKey, count, OE_Default, eOnePass, iIdxNoSeek);
102199  }
102200 
102201  /* End of the loop over all rowids/primary-keys. */
102202  if( eOnePass!=ONEPASS_OFF ){
102203  sqlite3VdbeResolveLabel(v, addrBypass);
102204  sqlite3WhereEnd(pWInfo);
102205  }else if( pPk ){
102206  sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
102207  sqlite3VdbeJumpHere(v, addrLoop);
102208  }else{
102209  sqlite3VdbeGoto(v, addrLoop);
102210  sqlite3VdbeJumpHere(v, addrLoop);
102211  }
102212 
102213  /* Close the cursors open on the table and its indexes. */
102214  if( !isView && !IsVirtual(pTab) ){
102215  if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
102216  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
102217  sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
102218  }
102219  }
102220  } /* End non-truncate path */
102221 
102222  /* Update the sqlite_sequence table by storing the content of the
102223  ** maximum rowid counter values recorded while inserting into
102224  ** autoincrement tables.
102225  */
102226  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
102227  sqlite3AutoincrementEnd(pParse);
102228  }
102229 
102230  /* Return the number of rows that were deleted. If this routine is
102231  ** generating code because of a call to sqlite3NestedParse(), do not
102232  ** invoke the callback function.
102233  */
102234  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
102235  sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
102236  sqlite3VdbeSetNumCols(v, 1);
102237  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
102238  }
102239 
102240 delete_from_cleanup:
102241  sqlite3AuthContextPop(&sContext);
102242  sqlite3SrcListDelete(db, pTabList);
102243  sqlite3ExprDelete(db, pWhere);
102244  sqlite3DbFree(db, aToOpen);
102245  return;
102246 }
102247 /* Make sure "isView" and other macros defined above are undefined. Otherwise
102248 ** they may interfere with compilation of other functions in this file
102249 ** (or in another file, if this file becomes part of the amalgamation). */
102250 #ifdef isView
102251  #undef isView
102252 #endif
102253 #ifdef pTrigger
102254  #undef pTrigger
102255 #endif
102256 
102257 /*
102258 ** This routine generates VDBE code that causes a single row of a
102259 ** single table to be deleted. Both the original table entry and
102260 ** all indices are removed.
102261 **
102262 ** Preconditions:
102263 **
102264 ** 1. iDataCur is an open cursor on the btree that is the canonical data
102265 ** store for the table. (This will be either the table itself,
102266 ** in the case of a rowid table, or the PRIMARY KEY index in the case
102267 ** of a WITHOUT ROWID table.)
102268 **
102269 ** 2. Read/write cursors for all indices of pTab must be open as
102270 ** cursor number iIdxCur+i for the i-th index.
102271 **
102272 ** 3. The primary key for the row to be deleted must be stored in a
102273 ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
102274 ** that a search record formed from OP_MakeRecord is contained in the
102275 ** single memory location iPk.
102276 **
102277 ** eMode:
102278 ** Parameter eMode may be passed either ONEPASS_OFF (0), ONEPASS_SINGLE, or
102279 ** ONEPASS_MULTI. If eMode is not ONEPASS_OFF, then the cursor
102280 ** iDataCur already points to the row to delete. If eMode is ONEPASS_OFF
102281 ** then this function must seek iDataCur to the entry identified by iPk
102282 ** and nPk before reading from it.
102283 **
102284 ** If eMode is ONEPASS_MULTI, then this call is being made as part
102285 ** of a ONEPASS delete that affects multiple rows. In this case, if
102286 ** iIdxNoSeek is a valid cursor number (>=0), then its position should
102287 ** be preserved following the delete operation. Or, if iIdxNoSeek is not
102288 ** a valid cursor number, the position of iDataCur should be preserved
102289 ** instead.
102290 **
102291 ** iIdxNoSeek:
102292 ** If iIdxNoSeek is a valid cursor number (>=0), then it identifies an
102293 ** index cursor (from within array of cursors starting at iIdxCur) that
102294 ** already points to the index entry to be deleted.
102295 */
102297  Parse *pParse, /* Parsing context */
102298  Table *pTab, /* Table containing the row to be deleted */
102299  Trigger *pTrigger, /* List of triggers to (potentially) fire */
102300  int iDataCur, /* Cursor from which column data is extracted */
102301  int iIdxCur, /* First index cursor */
102302  int iPk, /* First memory cell containing the PRIMARY KEY */
102303  i16 nPk, /* Number of PRIMARY KEY memory cells */
102304  u8 count, /* If non-zero, increment the row change counter */
102305  u8 onconf, /* Default ON CONFLICT policy for triggers */
102306  u8 eMode, /* ONEPASS_OFF, _SINGLE, or _MULTI. See above */
102307  int iIdxNoSeek /* Cursor number of cursor that does not need seeking */
102308 ){
102309  Vdbe *v = pParse->pVdbe; /* Vdbe */
102310  int iOld = 0; /* First register in OLD.* array */
102311  int iLabel; /* Label resolved to end of generated code */
102312  u8 opSeek; /* Seek opcode */
102313 
102314  /* Vdbe is guaranteed to have been allocated by this stage. */
102315  assert( v );
102316  VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
102317  iDataCur, iIdxCur, iPk, (int)nPk));
102318 
102319  /* Seek cursor iCur to the row to delete. If this row no longer exists
102320  ** (this can happen if a trigger program has already deleted it), do
102321  ** not attempt to delete it or fire any DELETE triggers. */
102322  iLabel = sqlite3VdbeMakeLabel(v);
102323  opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
102324  if( eMode==ONEPASS_OFF ){
102325  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102326  VdbeCoverageIf(v, opSeek==OP_NotExists);
102327  VdbeCoverageIf(v, opSeek==OP_NotFound);
102328  }
102329 
102330  /* If there are any triggers to fire, allocate a range of registers to
102331  ** use for the old.* references in the triggers. */
102332  if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
102333  u32 mask; /* Mask of OLD.* columns in use */
102334  int iCol; /* Iterator used while populating OLD.* */
102335  int addrStart; /* Start of BEFORE trigger programs */
102336 
102337  /* TODO: Could use temporary registers here. Also could attempt to
102338  ** avoid copying the contents of the rowid register. */
102339  mask = sqlite3TriggerColmask(
102340  pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
102341  );
102342  mask |= sqlite3FkOldmask(pParse, pTab);
102343  iOld = pParse->nMem+1;
102344  pParse->nMem += (1 + pTab->nCol);
102345 
102346  /* Populate the OLD.* pseudo-table register array. These values will be
102347  ** used by any BEFORE and AFTER triggers that exist. */
102348  sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
102349  for(iCol=0; iCol<pTab->nCol; iCol++){
102350  testcase( mask!=0xffffffff && iCol==31 );
102351  testcase( mask!=0xffffffff && iCol==32 );
102352  if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
102353  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
102354  }
102355  }
102356 
102357  /* Invoke BEFORE DELETE trigger programs. */
102358  addrStart = sqlite3VdbeCurrentAddr(v);
102359  sqlite3CodeRowTrigger(pParse, pTrigger,
102360  TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
102361  );
102362 
102363  /* If any BEFORE triggers were coded, then seek the cursor to the
102364  ** row to be deleted again. It may be that the BEFORE triggers moved
102365  ** the cursor or of already deleted the row that the cursor was
102366  ** pointing to.
102367  */
102368  if( addrStart<sqlite3VdbeCurrentAddr(v) ){
102369  sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
102370  VdbeCoverageIf(v, opSeek==OP_NotExists);
102371  VdbeCoverageIf(v, opSeek==OP_NotFound);
102372  }
102373 
102374  /* Do FK processing. This call checks that any FK constraints that
102375  ** refer to this table (i.e. constraints attached to other tables)
102376  ** are not violated by deleting this row. */
102377  sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
102378  }
102379 
102380  /* Delete the index and table entries. Skip this step if pTab is really
102381  ** a view (in which case the only effect of the DELETE statement is to
102382  ** fire the INSTEAD OF triggers).
102383  **
102384  ** If variable 'count' is non-zero, then this OP_Delete instruction should
102385  ** invoke the update-hook. The pre-update-hook, on the other hand should
102386  ** be invoked unless table pTab is a system table. The difference is that
102387  ** the update-hook is not invoked for rows removed by REPLACE, but the
102388  ** pre-update-hook is.
102389  */
102390  if( pTab->pSelect==0 ){
102391  u8 p5 = 0;
102392  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,iIdxNoSeek);
102393  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
102394  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
102395  if( eMode!=ONEPASS_OFF ){
102397  }
102398  if( iIdxNoSeek>=0 ){
102399  sqlite3VdbeAddOp1(v, OP_Delete, iIdxNoSeek);
102400  }
102401  if( eMode==ONEPASS_MULTI ) p5 |= OPFLAG_SAVEPOSITION;
102402  sqlite3VdbeChangeP5(v, p5);
102403  }
102404 
102405  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
102406  ** handle rows (possibly in other tables) that refer via a foreign key
102407  ** to the row just deleted. */
102408  sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
102409 
102410  /* Invoke AFTER DELETE trigger programs. */
102411  sqlite3CodeRowTrigger(pParse, pTrigger,
102412  TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
102413  );
102414 
102415  /* Jump here if the row had already been deleted before any BEFORE
102416  ** trigger programs were invoked. Or if a trigger program throws a
102417  ** RAISE(IGNORE) exception. */
102418  sqlite3VdbeResolveLabel(v, iLabel);
102419  VdbeModuleComment((v, "END: GenRowDel()"));
102420 }
102421 
102422 /*
102423 ** This routine generates VDBE code that causes the deletion of all
102424 ** index entries associated with a single row of a single table, pTab
102425 **
102426 ** Preconditions:
102427 **
102428 ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
102429 ** btree for the table pTab. (This will be either the table itself
102430 ** for rowid tables or to the primary key index for WITHOUT ROWID
102431 ** tables.)
102432 **
102433 ** 2. Read/write cursors for all indices of pTab must be open as
102434 ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
102435 ** index is the 0-th index.)
102436 **
102437 ** 3. The "iDataCur" cursor must be already be positioned on the row
102438 ** that is to be deleted.
102439 */
102441  Parse *pParse, /* Parsing and code generating context */
102442  Table *pTab, /* Table containing the row to be deleted */
102443  int iDataCur, /* Cursor of table holding data. */
102444  int iIdxCur, /* First index cursor */
102445  int *aRegIdx, /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
102446  int iIdxNoSeek /* Do not delete from this cursor */
102447 ){
102448  int i; /* Index loop counter */
102449  int r1 = -1; /* Register holding an index key */
102450  int iPartIdxLabel; /* Jump destination for skipping partial index entries */
102451  Index *pIdx; /* Current index */
102452  Index *pPrior = 0; /* Prior index */
102453  Vdbe *v; /* The prepared statement under construction */
102454  Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
102455 
102456  v = pParse->pVdbe;
102457  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
102458  for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
102459  assert( iIdxCur+i!=iDataCur || pPk==pIdx );
102460  if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
102461  if( pIdx==pPk ) continue;
102462  if( iIdxCur+i==iIdxNoSeek ) continue;
102463  VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
102464  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
102465  &iPartIdxLabel, pPrior, r1);
102466  sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
102467  pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
102468  sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
102469  pPrior = pIdx;
102470  }
102471 }
102472 
102473 /*
102474 ** Generate code that will assemble an index key and stores it in register
102475 ** regOut. The key with be for index pIdx which is an index on pTab.
102476 ** iCur is the index of a cursor open on the pTab table and pointing to
102477 ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
102478 ** iCur must be the cursor of the PRIMARY KEY index.
102479 **
102480 ** Return a register number which is the first in a block of
102481 ** registers that holds the elements of the index key. The
102482 ** block of registers has already been deallocated by the time
102483 ** this routine returns.
102484 **
102485 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
102486 ** to that label if pIdx is a partial index that should be skipped.
102487 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
102488 ** A partial index should be skipped if its WHERE clause evaluates
102489 ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
102490 ** will be set to zero which is an empty label that is ignored by
102491 ** sqlite3ResolvePartIdxLabel().
102492 **
102493 ** The pPrior and regPrior parameters are used to implement a cache to
102494 ** avoid unnecessary register loads. If pPrior is not NULL, then it is
102495 ** a pointer to a different index for which an index key has just been
102496 ** computed into register regPrior. If the current pIdx index is generating
102497 ** its key into the same sequence of registers and if pPrior and pIdx share
102498 ** a column in common, then the register corresponding to that column already
102499 ** holds the correct value and the loading of that register is skipped.
102500 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
102501 ** on a table with multiple indices, and especially with the ROWID or
102502 ** PRIMARY KEY columns of the index.
102503 */
102505  Parse *pParse, /* Parsing context */
102506  Index *pIdx, /* The index for which to generate a key */
102507  int iDataCur, /* Cursor number from which to take column data */
102508  int regOut, /* Put the new key into this register if not 0 */
102509  int prefixOnly, /* Compute only a unique prefix of the key */
102510  int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
102511  Index *pPrior, /* Previously generated index key */
102512  int regPrior /* Register holding previous generated key */
102513 ){
102514  Vdbe *v = pParse->pVdbe;
102515  int j;
102516  int regBase;
102517  int nCol;
102518 
102519  if( piPartIdxLabel ){
102520  if( pIdx->pPartIdxWhere ){
102521  *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
102522  pParse->iSelfTab = iDataCur;
102523  sqlite3ExprCachePush(pParse);
102524  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
102526  }else{
102527  *piPartIdxLabel = 0;
102528  }
102529  }
102530  nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
102531  regBase = sqlite3GetTempRange(pParse, nCol);
102532  if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
102533  for(j=0; j<nCol; j++){
102534  if( pPrior
102535  && pPrior->aiColumn[j]==pIdx->aiColumn[j]
102536  && pPrior->aiColumn[j]!=XN_EXPR
102537  ){
102538  /* This column was already computed by the previous index */
102539  continue;
102540  }
102541  sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iDataCur, j, regBase+j);
102542  /* If the column affinity is REAL but the number is an integer, then it
102543  ** might be stored in the table as an integer (using a compact
102544  ** representation) then converted to REAL by an OP_RealAffinity opcode.
102545  ** But we are getting ready to store this value back into an index, where
102546  ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
102547  ** opcode if it is present */
102549  }
102550  if( regOut ){
102551  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
102552  }
102553  sqlite3ReleaseTempRange(pParse, regBase, nCol);
102554  return regBase;
102555 }
102556 
102557 /*
102558 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
102559 ** because it was a partial index, then this routine should be called to
102560 ** resolve that label.
102561 */
102563  if( iLabel ){
102564  sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
102565  sqlite3ExprCachePop(pParse);
102566  }
102567 }
102568 
102569 /************** End of delete.c **********************************************/
102570 /************** Begin file func.c ********************************************/
102571 /*
102572 ** 2002 February 23
102573 **
102574 ** The author disclaims copyright to this source code. In place of
102575 ** a legal notice, here is a blessing:
102576 **
102577 ** May you do good and not evil.
102578 ** May you find forgiveness for yourself and forgive others.
102579 ** May you share freely, never taking more than you give.
102580 **
102581 *************************************************************************
102582 ** This file contains the C-language implementations for many of the SQL
102583 ** functions of SQLite. (Some function, and in particular the date and
102584 ** time functions, are implemented separately.)
102585 */
102586 /* #include "sqliteInt.h" */
102587 /* #include <stdlib.h> */
102588 /* #include <assert.h> */
102589 /* #include "vdbeInt.h" */
102590 
102591 /*
102592 ** Return the collating function associated with a function.
102593 */
102595  VdbeOp *pOp;
102596  assert( context->pVdbe!=0 );
102597  pOp = &context->pVdbe->aOp[context->iOp-1];
102598  assert( pOp->opcode==OP_CollSeq );
102599  assert( pOp->p4type==P4_COLLSEQ );
102600  return pOp->p4.pColl;
102601 }
102602 
102603 /*
102604 ** Indicate that the accumulator load should be skipped on this
102605 ** iteration of the aggregate loop.
102606 */
102608  context->skipFlag = 1;
102609 }
102610 
102611 /*
102612 ** Implementation of the non-aggregate min() and max() functions
102613 */
102614 static void minmaxFunc(
102615  sqlite3_context *context,
102616  int argc,
102617  sqlite3_value **argv
102618 ){
102619  int i;
102620  int mask; /* 0 for min() or 0xffffffff for max() */
102621  int iBest;
102622  CollSeq *pColl;
102623 
102624  assert( argc>1 );
102625  mask = sqlite3_user_data(context)==0 ? 0 : -1;
102626  pColl = sqlite3GetFuncCollSeq(context);
102627  assert( pColl );
102628  assert( mask==-1 || mask==0 );
102629  iBest = 0;
102630  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
102631  for(i=1; i<argc; i++){
102632  if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
102633  if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
102634  testcase( mask==0 );
102635  iBest = i;
102636  }
102637  }
102638  sqlite3_result_value(context, argv[iBest]);
102639 }
102640 
102641 /*
102642 ** Return the type of the argument.
102643 */
102644 static void typeofFunc(
102645  sqlite3_context *context,
102646  int NotUsed,
102647  sqlite3_value **argv
102648 ){
102649  const char *z = 0;
102650  UNUSED_PARAMETER(NotUsed);
102651  switch( sqlite3_value_type(argv[0]) ){
102652  case SQLITE_INTEGER: z = "integer"; break;
102653  case SQLITE_TEXT: z = "text"; break;
102654  case SQLITE_FLOAT: z = "real"; break;
102655  case SQLITE_BLOB: z = "blob"; break;
102656  default: z = "null"; break;
102657  }
102658  sqlite3_result_text(context, z, -1, SQLITE_STATIC);
102659 }
102660 
102661 
102662 /*
102663 ** Implementation of the length() function
102664 */
102665 static void lengthFunc(
102666  sqlite3_context *context,
102667  int argc,
102668  sqlite3_value **argv
102669 ){
102670  int len;
102671 
102672  assert( argc==1 );
102673  UNUSED_PARAMETER(argc);
102674  switch( sqlite3_value_type(argv[0]) ){
102675  case SQLITE_BLOB:
102676  case SQLITE_INTEGER:
102677  case SQLITE_FLOAT: {
102678  sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
102679  break;
102680  }
102681  case SQLITE_TEXT: {
102682  const unsigned char *z = sqlite3_value_text(argv[0]);
102683  if( z==0 ) return;
102684  len = 0;
102685  while( *z ){
102686  len++;
102687  SQLITE_SKIP_UTF8(z);
102688  }
102689  sqlite3_result_int(context, len);
102690  break;
102691  }
102692  default: {
102693  sqlite3_result_null(context);
102694  break;
102695  }
102696  }
102697 }
102698 
102699 /*
102700 ** Implementation of the abs() function.
102701 **
102702 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
102703 ** the numeric argument X.
102704 */
102705 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
102706  assert( argc==1 );
102707  UNUSED_PARAMETER(argc);
102708  switch( sqlite3_value_type(argv[0]) ){
102709  case SQLITE_INTEGER: {
102710  i64 iVal = sqlite3_value_int64(argv[0]);
102711  if( iVal<0 ){
102712  if( iVal==SMALLEST_INT64 ){
102713  /* IMP: R-31676-45509 If X is the integer -9223372036854775808
102714  ** then abs(X) throws an integer overflow error since there is no
102715  ** equivalent positive 64-bit two complement value. */
102716  sqlite3_result_error(context, "integer overflow", -1);
102717  return;
102718  }
102719  iVal = -iVal;
102720  }
102721  sqlite3_result_int64(context, iVal);
102722  break;
102723  }
102724  case SQLITE_NULL: {
102725  /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
102726  sqlite3_result_null(context);
102727  break;
102728  }
102729  default: {
102730  /* Because sqlite3_value_double() returns 0.0 if the argument is not
102731  ** something that can be converted into a number, we have:
102732  ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
102733  ** that cannot be converted to a numeric value.
102734  */
102735  double rVal = sqlite3_value_double(argv[0]);
102736  if( rVal<0 ) rVal = -rVal;
102737  sqlite3_result_double(context, rVal);
102738  break;
102739  }
102740  }
102741 }
102742 
102743 /*
102744 ** Implementation of the instr() function.
102745 **
102746 ** instr(haystack,needle) finds the first occurrence of needle
102747 ** in haystack and returns the number of previous characters plus 1,
102748 ** or 0 if needle does not occur within haystack.
102749 **
102750 ** If both haystack and needle are BLOBs, then the result is one more than
102751 ** the number of bytes in haystack prior to the first occurrence of needle,
102752 ** or 0 if needle never occurs in haystack.
102753 */
102754 static void instrFunc(
102755  sqlite3_context *context,
102756  int argc,
102757  sqlite3_value **argv
102758 ){
102759  const unsigned char *zHaystack;
102760  const unsigned char *zNeedle;
102761  int nHaystack;
102762  int nNeedle;
102763  int typeHaystack, typeNeedle;
102764  int N = 1;
102765  int isText;
102766 
102767  UNUSED_PARAMETER(argc);
102768  typeHaystack = sqlite3_value_type(argv[0]);
102769  typeNeedle = sqlite3_value_type(argv[1]);
102770  if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
102771  nHaystack = sqlite3_value_bytes(argv[0]);
102772  nNeedle = sqlite3_value_bytes(argv[1]);
102773  if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
102774  zHaystack = sqlite3_value_blob(argv[0]);
102775  zNeedle = sqlite3_value_blob(argv[1]);
102776  isText = 0;
102777  }else{
102778  zHaystack = sqlite3_value_text(argv[0]);
102779  zNeedle = sqlite3_value_text(argv[1]);
102780  isText = 1;
102781  }
102782  while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
102783  N++;
102784  do{
102785  nHaystack--;
102786  zHaystack++;
102787  }while( isText && (zHaystack[0]&0xc0)==0x80 );
102788  }
102789  if( nNeedle>nHaystack ) N = 0;
102790  sqlite3_result_int(context, N);
102791 }
102792 
102793 /*
102794 ** Implementation of the printf() function.
102795 */
102796 static void printfFunc(
102797  sqlite3_context *context,
102798  int argc,
102799  sqlite3_value **argv
102800 ){
102801  PrintfArguments x;
102802  StrAccum str;
102803  const char *zFormat;
102804  int n;
102805  sqlite3 *db = sqlite3_context_db_handle(context);
102806 
102807  if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
102808  x.nArg = argc-1;
102809  x.nUsed = 0;
102810  x.apArg = argv+1;
102811  sqlite3StrAccumInit(&str, db, 0, 0, db->aLimit[SQLITE_LIMIT_LENGTH]);
102813  sqlite3XPrintf(&str, zFormat, &x);
102814  n = str.nChar;
102815  sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
102816  SQLITE_DYNAMIC);
102817  }
102818 }
102819 
102820 /*
102821 ** Implementation of the substr() function.
102822 **
102823 ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
102824 ** p1 is 1-indexed. So substr(x,1,1) returns the first character
102825 ** of x. If x is text, then we actually count UTF-8 characters.
102826 ** If x is a blob, then we count bytes.
102827 **
102828 ** If p1 is negative, then we begin abs(p1) from the end of x[].
102829 **
102830 ** If p2 is negative, return the p2 characters preceding p1.
102831 */
102832 static void substrFunc(
102833  sqlite3_context *context,
102834  int argc,
102835  sqlite3_value **argv
102836 ){
102837  const unsigned char *z;
102838  const unsigned char *z2;
102839  int len;
102840  int p0type;
102841  i64 p1, p2;
102842  int negP2 = 0;
102843 
102844  assert( argc==3 || argc==2 );
102845  if( sqlite3_value_type(argv[1])==SQLITE_NULL
102846  || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
102847  ){
102848  return;
102849  }
102850  p0type = sqlite3_value_type(argv[0]);
102851  p1 = sqlite3_value_int(argv[1]);
102852  if( p0type==SQLITE_BLOB ){
102853  len = sqlite3_value_bytes(argv[0]);
102854  z = sqlite3_value_blob(argv[0]);
102855  if( z==0 ) return;
102856  assert( len==sqlite3_value_bytes(argv[0]) );
102857  }else{
102858  z = sqlite3_value_text(argv[0]);
102859  if( z==0 ) return;
102860  len = 0;
102861  if( p1<0 ){
102862  for(z2=z; *z2; len++){
102863  SQLITE_SKIP_UTF8(z2);
102864  }
102865  }
102866  }
102867 #ifdef SQLITE_SUBSTR_COMPATIBILITY
102868  /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
102869  ** as substr(X,1,N) - it returns the first N characters of X. This
102870  ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
102871  ** from 2009-02-02 for compatibility of applications that exploited the
102872  ** old buggy behavior. */
102873  if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
102874 #endif
102875  if( argc==3 ){
102876  p2 = sqlite3_value_int(argv[2]);
102877  if( p2<0 ){
102878  p2 = -p2;
102879  negP2 = 1;
102880  }
102881  }else{
102883  }
102884  if( p1<0 ){
102885  p1 += len;
102886  if( p1<0 ){
102887  p2 += p1;
102888  if( p2<0 ) p2 = 0;
102889  p1 = 0;
102890  }
102891  }else if( p1>0 ){
102892  p1--;
102893  }else if( p2>0 ){
102894  p2--;
102895  }
102896  if( negP2 ){
102897  p1 -= p2;
102898  if( p1<0 ){
102899  p2 += p1;
102900  p1 = 0;
102901  }
102902  }
102903  assert( p1>=0 && p2>=0 );
102904  if( p0type!=SQLITE_BLOB ){
102905  while( *z && p1 ){
102906  SQLITE_SKIP_UTF8(z);
102907  p1--;
102908  }
102909  for(z2=z; *z2 && p2; p2--){
102910  SQLITE_SKIP_UTF8(z2);
102911  }
102912  sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
102913  SQLITE_UTF8);
102914  }else{
102915  if( p1+p2>len ){
102916  p2 = len-p1;
102917  if( p2<0 ) p2 = 0;
102918  }
102919  sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
102920  }
102921 }
102922 
102923 /*
102924 ** Implementation of the round() function
102925 */
102926 #ifndef SQLITE_OMIT_FLOATING_POINT
102927 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
102928  int n = 0;
102929  double r;
102930  char *zBuf;
102931  assert( argc==1 || argc==2 );
102932  if( argc==2 ){
102933  if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
102934  n = sqlite3_value_int(argv[1]);
102935  if( n>30 ) n = 30;
102936  if( n<0 ) n = 0;
102937  }
102938  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
102939  r = sqlite3_value_double(argv[0]);
102940  /* If Y==0 and X will fit in a 64-bit int,
102941  ** handle the rounding directly,
102942  ** otherwise use printf.
102943  */
102944  if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
102945  r = (double)((sqlite_int64)(r+0.5));
102946  }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
102947  r = -(double)((sqlite_int64)((-r)+0.5));
102948  }else{
102949  zBuf = sqlite3_mprintf("%.*f",n,r);
102950  if( zBuf==0 ){
102951  sqlite3_result_error_nomem(context);
102952  return;
102953  }
102954  sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
102955  sqlite3_free(zBuf);
102956  }
102957  sqlite3_result_double(context, r);
102958 }
102959 #endif
102960 
102961 /*
102962 ** Allocate nByte bytes of space using sqlite3Malloc(). If the
102963 ** allocation fails, call sqlite3_result_error_nomem() to notify
102964 ** the database handle that malloc() has failed and return NULL.
102965 ** If nByte is larger than the maximum string or blob length, then
102966 ** raise an SQLITE_TOOBIG exception and return NULL.
102967 */
102968 static void *contextMalloc(sqlite3_context *context, i64 nByte){
102969  char *z;
102970  sqlite3 *db = sqlite3_context_db_handle(context);
102971  assert( nByte>0 );
102972  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
102973  testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
102974  if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
102975  sqlite3_result_error_toobig(context);
102976  z = 0;
102977  }else{
102978  z = sqlite3Malloc(nByte);
102979  if( !z ){
102980  sqlite3_result_error_nomem(context);
102981  }
102982  }
102983  return z;
102984 }
102985 
102986 /*
102987 ** Implementation of the upper() and lower() SQL functions.
102988 */
102989 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
102990  char *z1;
102991  const char *z2;
102992  int i, n;
102993  UNUSED_PARAMETER(argc);
102994  z2 = (char*)sqlite3_value_text(argv[0]);
102995  n = sqlite3_value_bytes(argv[0]);
102996  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
102997  assert( z2==(char*)sqlite3_value_text(argv[0]) );
102998  if( z2 ){
102999  z1 = contextMalloc(context, ((i64)n)+1);
103000  if( z1 ){
103001  for(i=0; i<n; i++){
103002  z1[i] = (char)sqlite3Toupper(z2[i]);
103003  }
103004  sqlite3_result_text(context, z1, n, sqlite3_free);
103005  }
103006  }
103007 }
103008 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103009  char *z1;
103010  const char *z2;
103011  int i, n;
103012  UNUSED_PARAMETER(argc);
103013  z2 = (char*)sqlite3_value_text(argv[0]);
103014  n = sqlite3_value_bytes(argv[0]);
103015  /* Verify that the call to _bytes() does not invalidate the _text() pointer */
103016  assert( z2==(char*)sqlite3_value_text(argv[0]) );
103017  if( z2 ){
103018  z1 = contextMalloc(context, ((i64)n)+1);
103019  if( z1 ){
103020  for(i=0; i<n; i++){
103021  z1[i] = sqlite3Tolower(z2[i]);
103022  }
103023  sqlite3_result_text(context, z1, n, sqlite3_free);
103024  }
103025  }
103026 }
103027 
103028 /*
103029 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
103030 ** as VDBE code so that unused argument values do not have to be computed.
103031 ** However, we still need some kind of function implementation for this
103032 ** routines in the function table. The noopFunc macro provides this.
103033 ** noopFunc will never be called so it doesn't matter what the implementation
103034 ** is. We might as well use the "version()" function as a substitute.
103035 */
103036 #define noopFunc versionFunc /* Substitute function - never called */
103037 
103038 /*
103039 ** Implementation of random(). Return a random integer.
103040 */
103041 static void randomFunc(
103042  sqlite3_context *context,
103043  int NotUsed,
103044  sqlite3_value **NotUsed2
103045 ){
103046  sqlite_int64 r;
103047  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103048  sqlite3_randomness(sizeof(r), &r);
103049  if( r<0 ){
103050  /* We need to prevent a random number of 0x8000000000000000
103051  ** (or -9223372036854775808) since when you do abs() of that
103052  ** number of you get the same value back again. To do this
103053  ** in a way that is testable, mask the sign bit off of negative
103054  ** values, resulting in a positive value. Then take the
103055  ** 2s complement of that positive value. The end result can
103056  ** therefore be no less than -9223372036854775807.
103057  */
103058  r = -(r & LARGEST_INT64);
103059  }
103060  sqlite3_result_int64(context, r);
103061 }
103062 
103063 /*
103064 ** Implementation of randomblob(N). Return a random blob
103065 ** that is N bytes long.
103066 */
103067 static void randomBlob(
103068  sqlite3_context *context,
103069  int argc,
103070  sqlite3_value **argv
103071 ){
103072  int n;
103073  unsigned char *p;
103074  assert( argc==1 );
103075  UNUSED_PARAMETER(argc);
103076  n = sqlite3_value_int(argv[0]);
103077  if( n<1 ){
103078  n = 1;
103079  }
103080  p = contextMalloc(context, n);
103081  if( p ){
103082  sqlite3_randomness(n, p);
103083  sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
103084  }
103085 }
103086 
103087 /*
103088 ** Implementation of the last_insert_rowid() SQL function. The return
103089 ** value is the same as the sqlite3_last_insert_rowid() API function.
103090 */
103092  sqlite3_context *context,
103093  int NotUsed,
103094  sqlite3_value **NotUsed2
103095 ){
103096  sqlite3 *db = sqlite3_context_db_handle(context);
103097  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103098  /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
103099  ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
103100  ** function. */
103102 }
103103 
103104 /*
103105 ** Implementation of the changes() SQL function.
103106 **
103107 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
103108 ** around the sqlite3_changes() C/C++ function and hence follows the same
103109 ** rules for counting changes.
103110 */
103111 static void changes(
103112  sqlite3_context *context,
103113  int NotUsed,
103114  sqlite3_value **NotUsed2
103115 ){
103116  sqlite3 *db = sqlite3_context_db_handle(context);
103117  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103118  sqlite3_result_int(context, sqlite3_changes(db));
103119 }
103120 
103121 /*
103122 ** Implementation of the total_changes() SQL function. The return value is
103123 ** the same as the sqlite3_total_changes() API function.
103124 */
103125 static void total_changes(
103126  sqlite3_context *context,
103127  int NotUsed,
103128  sqlite3_value **NotUsed2
103129 ){
103130  sqlite3 *db = sqlite3_context_db_handle(context);
103131  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103132  /* IMP: R-52756-41993 This function is a wrapper around the
103133  ** sqlite3_total_changes() C/C++ interface. */
103135 }
103136 
103137 /*
103138 ** A structure defining how to do GLOB-style comparisons.
103139 */
103141  u8 matchAll; /* "*" or "%" */
103142  u8 matchOne; /* "?" or "_" */
103143  u8 matchSet; /* "[" or 0 */
103144  u8 noCase; /* true to ignore case differences */
103145 };
103146 
103147 /*
103148 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
103149 ** character is exactly one byte in size. Also, provde the Utf8Read()
103150 ** macro for fast reading of the next character in the common case where
103151 ** the next character is ASCII.
103152 */
103153 #if defined(SQLITE_EBCDIC)
103154 # define sqlite3Utf8Read(A) (*((*A)++))
103155 # define Utf8Read(A) (*(A++))
103156 #else
103157 # define Utf8Read(A) (A[0]<0x80?*(A++):sqlite3Utf8Read(&A))
103158 #endif
103159 
103160 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
103161 /* The correct SQL-92 behavior is for the LIKE operator to ignore
103162 ** case. Thus 'a' LIKE 'A' would be true. */
103163 static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
103164 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
103165 ** is case sensitive causing 'a' LIKE 'A' to be false */
103166 static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
103167 
103168 /*
103169 ** Compare two UTF-8 strings for equality where the first string can
103170 ** potentially be a "glob" or "like" expression. Return true (1) if they
103171 ** are the same and false (0) if they are different.
103172 **
103173 ** Globbing rules:
103174 **
103175 ** '*' Matches any sequence of zero or more characters.
103176 **
103177 ** '?' Matches exactly one character.
103178 **
103179 ** [...] Matches one character from the enclosed list of
103180 ** characters.
103181 **
103182 ** [^...] Matches one character not in the enclosed list.
103183 **
103184 ** With the [...] and [^...] matching, a ']' character can be included
103185 ** in the list by making it the first character after '[' or '^'. A
103186 ** range of characters can be specified using '-'. Example:
103187 ** "[a-z]" matches any single lower-case letter. To match a '-', make
103188 ** it the last character in the list.
103189 **
103190 ** Like matching rules:
103191 **
103192 ** '%' Matches any sequence of zero or more characters
103193 **
103194 *** '_' Matches any one character
103195 **
103196 ** Ec Where E is the "esc" character and c is any other
103197 ** character, including '%', '_', and esc, match exactly c.
103198 **
103199 ** The comments within this routine usually assume glob matching.
103200 **
103201 ** This routine is usually quick, but can be N**2 in the worst case.
103202 */
103203 static int patternCompare(
103204  const u8 *zPattern, /* The glob pattern */
103205  const u8 *zString, /* The string to compare against the glob */
103206  const struct compareInfo *pInfo, /* Information about how to do the compare */
103207  u32 matchOther /* The escape char (LIKE) or '[' (GLOB) */
103208 ){
103209  u32 c, c2; /* Next pattern and input string chars */
103210  u32 matchOne = pInfo->matchOne; /* "?" or "_" */
103211  u32 matchAll = pInfo->matchAll; /* "*" or "%" */
103212  u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
103213  const u8 *zEscaped = 0; /* One past the last escaped input char */
103214 
103215  while( (c = Utf8Read(zPattern))!=0 ){
103216  if( c==matchAll ){ /* Match "*" */
103217  /* Skip over multiple "*" characters in the pattern. If there
103218  ** are also "?" characters, skip those as well, but consume a
103219  ** single character of the input string for each "?" skipped */
103220  while( (c=Utf8Read(zPattern)) == matchAll || c == matchOne ){
103221  if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
103222  return 0;
103223  }
103224  }
103225  if( c==0 ){
103226  return 1; /* "*" at the end of the pattern matches */
103227  }else if( c==matchOther ){
103228  if( pInfo->matchSet==0 ){
103229  c = sqlite3Utf8Read(&zPattern);
103230  if( c==0 ) return 0;
103231  }else{
103232  /* "[...]" immediately follows the "*". We have to do a slow
103233  ** recursive search in this case, but it is an unusual case. */
103234  assert( matchOther<0x80 ); /* '[' is a single-byte character */
103235  while( *zString
103236  && patternCompare(&zPattern[-1],zString,pInfo,matchOther)==0 ){
103237  SQLITE_SKIP_UTF8(zString);
103238  }
103239  return *zString!=0;
103240  }
103241  }
103242 
103243  /* At this point variable c contains the first character of the
103244  ** pattern string past the "*". Search in the input string for the
103245  ** first matching character and recursively contine the match from
103246  ** that point.
103247  **
103248  ** For a case-insensitive search, set variable cx to be the same as
103249  ** c but in the other case and search the input string for either
103250  ** c or cx.
103251  */
103252  if( c<=0x80 ){
103253  u32 cx;
103254  if( noCase ){
103255  cx = sqlite3Toupper(c);
103256  c = sqlite3Tolower(c);
103257  }else{
103258  cx = c;
103259  }
103260  while( (c2 = *(zString++))!=0 ){
103261  if( c2!=c && c2!=cx ) continue;
103262  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103263  }
103264  }else{
103265  while( (c2 = Utf8Read(zString))!=0 ){
103266  if( c2!=c ) continue;
103267  if( patternCompare(zPattern,zString,pInfo,matchOther) ) return 1;
103268  }
103269  }
103270  return 0;
103271  }
103272  if( c==matchOther ){
103273  if( pInfo->matchSet==0 ){
103274  c = sqlite3Utf8Read(&zPattern);
103275  if( c==0 ) return 0;
103276  zEscaped = zPattern;
103277  }else{
103278  u32 prior_c = 0;
103279  int seen = 0;
103280  int invert = 0;
103281  c = sqlite3Utf8Read(&zString);
103282  if( c==0 ) return 0;
103283  c2 = sqlite3Utf8Read(&zPattern);
103284  if( c2=='^' ){
103285  invert = 1;
103286  c2 = sqlite3Utf8Read(&zPattern);
103287  }
103288  if( c2==']' ){
103289  if( c==']' ) seen = 1;
103290  c2 = sqlite3Utf8Read(&zPattern);
103291  }
103292  while( c2 && c2!=']' ){
103293  if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
103294  c2 = sqlite3Utf8Read(&zPattern);
103295  if( c>=prior_c && c<=c2 ) seen = 1;
103296  prior_c = 0;
103297  }else{
103298  if( c==c2 ){
103299  seen = 1;
103300  }
103301  prior_c = c2;
103302  }
103303  c2 = sqlite3Utf8Read(&zPattern);
103304  }
103305  if( c2==0 || (seen ^ invert)==0 ){
103306  return 0;
103307  }
103308  continue;
103309  }
103310  }
103311  c2 = Utf8Read(zString);
103312  if( c==c2 ) continue;
103313  if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
103314  continue;
103315  }
103316  if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
103317  return 0;
103318  }
103319  return *zString==0;
103320 }
103321 
103322 /*
103323 ** The sqlite3_strglob() interface.
103324 */
103325 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
103326  return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, '[')==0;
103327 }
103328 
103329 /*
103330 ** The sqlite3_strlike() interface.
103331 */
103332 SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zPattern, const char *zStr, unsigned int esc){
103333  return patternCompare((u8*)zPattern, (u8*)zStr, &likeInfoNorm, esc)==0;
103334 }
103335 
103336 /*
103337 ** Count the number of times that the LIKE operator (or GLOB which is
103338 ** just a variation of LIKE) gets called. This is used for testing
103339 ** only.
103340 */
103341 #ifdef SQLITE_TEST
103342 SQLITE_API int sqlite3_like_count = 0;
103343 #endif
103344 
103345 
103346 /*
103347 ** Implementation of the like() SQL function. This function implements
103348 ** the build-in LIKE operator. The first argument to the function is the
103349 ** pattern and the second argument is the string. So, the SQL statements:
103350 **
103351 ** A LIKE B
103352 **
103353 ** is implemented as like(B,A).
103354 **
103355 ** This same function (with a different compareInfo structure) computes
103356 ** the GLOB operator.
103357 */
103358 static void likeFunc(
103359  sqlite3_context *context,
103360  int argc,
103361  sqlite3_value **argv
103362 ){
103363  const unsigned char *zA, *zB;
103364  u32 escape;
103365  int nPat;
103366  sqlite3 *db = sqlite3_context_db_handle(context);
103367  struct compareInfo *pInfo = sqlite3_user_data(context);
103368 
103369 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
103370  if( sqlite3_value_type(argv[0])==SQLITE_BLOB
103371  || sqlite3_value_type(argv[1])==SQLITE_BLOB
103372  ){
103373 #ifdef SQLITE_TEST
103374  sqlite3_like_count++;
103375 #endif
103376  sqlite3_result_int(context, 0);
103377  return;
103378  }
103379 #endif
103380  zB = sqlite3_value_text(argv[0]);
103381  zA = sqlite3_value_text(argv[1]);
103382 
103383  /* Limit the length of the LIKE or GLOB pattern to avoid problems
103384  ** of deep recursion and N*N behavior in patternCompare().
103385  */
103386  nPat = sqlite3_value_bytes(argv[0]);
103389  if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
103390  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
103391  return;
103392  }
103393  assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
103394 
103395  if( argc==3 ){
103396  /* The escape character string must consist of a single UTF-8 character.
103397  ** Otherwise, return an error.
103398  */
103399  const unsigned char *zEsc = sqlite3_value_text(argv[2]);
103400  if( zEsc==0 ) return;
103401  if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
103402  sqlite3_result_error(context,
103403  "ESCAPE expression must be a single character", -1);
103404  return;
103405  }
103406  escape = sqlite3Utf8Read(&zEsc);
103407  }else{
103408  escape = pInfo->matchSet;
103409  }
103410  if( zA && zB ){
103411 #ifdef SQLITE_TEST
103412  sqlite3_like_count++;
103413 #endif
103414  sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
103415  }
103416 }
103417 
103418 /*
103419 ** Implementation of the NULLIF(x,y) function. The result is the first
103420 ** argument if the arguments are different. The result is NULL if the
103421 ** arguments are equal to each other.
103422 */
103423 static void nullifFunc(
103424  sqlite3_context *context,
103425  int NotUsed,
103426  sqlite3_value **argv
103427 ){
103428  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
103429  UNUSED_PARAMETER(NotUsed);
103430  if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
103431  sqlite3_result_value(context, argv[0]);
103432  }
103433 }
103434 
103435 /*
103436 ** Implementation of the sqlite_version() function. The result is the version
103437 ** of the SQLite library that is running.
103438 */
103439 static void versionFunc(
103440  sqlite3_context *context,
103441  int NotUsed,
103442  sqlite3_value **NotUsed2
103443 ){
103444  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103445  /* IMP: R-48699-48617 This function is an SQL wrapper around the
103446  ** sqlite3_libversion() C-interface. */
103448 }
103449 
103450 /*
103451 ** Implementation of the sqlite_source_id() function. The result is a string
103452 ** that identifies the particular version of the source code used to build
103453 ** SQLite.
103454 */
103455 static void sourceidFunc(
103456  sqlite3_context *context,
103457  int NotUsed,
103458  sqlite3_value **NotUsed2
103459 ){
103460  UNUSED_PARAMETER2(NotUsed, NotUsed2);
103461  /* IMP: R-24470-31136 This function is an SQL wrapper around the
103462  ** sqlite3_sourceid() C interface. */
103464 }
103465 
103466 /*
103467 ** Implementation of the sqlite_log() function. This is a wrapper around
103468 ** sqlite3_log(). The return value is NULL. The function exists purely for
103469 ** its side-effects.
103470 */
103471 static void errlogFunc(
103472  sqlite3_context *context,
103473  int argc,
103474  sqlite3_value **argv
103475 ){
103476  UNUSED_PARAMETER(argc);
103477  UNUSED_PARAMETER(context);
103478  sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
103479 }
103480 
103481 /*
103482 ** Implementation of the sqlite_compileoption_used() function.
103483 ** The result is an integer that identifies if the compiler option
103484 ** was used to build SQLite.
103485 */
103486 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
103488  sqlite3_context *context,
103489  int argc,
103490  sqlite3_value **argv
103491 ){
103492  const char *zOptName;
103493  assert( argc==1 );
103494  UNUSED_PARAMETER(argc);
103495  /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
103496  ** function is a wrapper around the sqlite3_compileoption_used() C/C++
103497  ** function.
103498  */
103499  if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
103500  sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
103501  }
103502 }
103503 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
103504 
103505 /*
103506 ** Implementation of the sqlite_compileoption_get() function.
103507 ** The result is a string that identifies the compiler options
103508 ** used to build SQLite.
103509 */
103510 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
103512  sqlite3_context *context,
103513  int argc,
103514  sqlite3_value **argv
103515 ){
103516  int n;
103517  assert( argc==1 );
103518  UNUSED_PARAMETER(argc);
103519  /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
103520  ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
103521  */
103522  n = sqlite3_value_int(argv[0]);
103524 }
103525 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
103526 
103527 /* Array for converting from half-bytes (nybbles) into ASCII hex
103528 ** digits. */
103529 static const char hexdigits[] = {
103530  '0', '1', '2', '3', '4', '5', '6', '7',
103531  '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
103532 };
103533 
103534 /*
103535 ** Implementation of the QUOTE() function. This function takes a single
103536 ** argument. If the argument is numeric, the return value is the same as
103537 ** the argument. If the argument is NULL, the return value is the string
103538 ** "NULL". Otherwise, the argument is enclosed in single quotes with
103539 ** single-quote escapes.
103540 */
103541 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
103542  assert( argc==1 );
103543  UNUSED_PARAMETER(argc);
103544  switch( sqlite3_value_type(argv[0]) ){
103545  case SQLITE_FLOAT: {
103546  double r1, r2;
103547  char zBuf[50];
103548  r1 = sqlite3_value_double(argv[0]);
103549  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
103550  sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
103551  if( r1!=r2 ){
103552  sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
103553  }
103554  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
103555  break;
103556  }
103557  case SQLITE_INTEGER: {
103558  sqlite3_result_value(context, argv[0]);
103559  break;
103560  }
103561  case SQLITE_BLOB: {
103562  char *zText = 0;
103563  char const *zBlob = sqlite3_value_blob(argv[0]);
103564  int nBlob = sqlite3_value_bytes(argv[0]);
103565  assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
103566  zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
103567  if( zText ){
103568  int i;
103569  for(i=0; i<nBlob; i++){
103570  zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
103571  zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
103572  }
103573  zText[(nBlob*2)+2] = '\'';
103574  zText[(nBlob*2)+3] = '\0';
103575  zText[0] = 'X';
103576  zText[1] = '\'';
103577  sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
103578  sqlite3_free(zText);
103579  }
103580  break;
103581  }
103582  case SQLITE_TEXT: {
103583  int i,j;
103584  u64 n;
103585  const unsigned char *zArg = sqlite3_value_text(argv[0]);
103586  char *z;
103587 
103588  if( zArg==0 ) return;
103589  for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
103590  z = contextMalloc(context, ((i64)i)+((i64)n)+3);
103591  if( z ){
103592  z[0] = '\'';
103593  for(i=0, j=1; zArg[i]; i++){
103594  z[j++] = zArg[i];
103595  if( zArg[i]=='\'' ){
103596  z[j++] = '\'';
103597  }
103598  }
103599  z[j++] = '\'';
103600  z[j] = 0;
103601  sqlite3_result_text(context, z, j, sqlite3_free);
103602  }
103603  break;
103604  }
103605  default: {
103606  assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
103607  sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
103608  break;
103609  }
103610  }
103611 }
103612 
103613 /*
103614 ** The unicode() function. Return the integer unicode code-point value
103615 ** for the first character of the input string.
103616 */
103617 static void unicodeFunc(
103618  sqlite3_context *context,
103619  int argc,
103620  sqlite3_value **argv
103621 ){
103622  const unsigned char *z = sqlite3_value_text(argv[0]);
103623  (void)argc;
103624  if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
103625 }
103626 
103627 /*
103628 ** The char() function takes zero or more arguments, each of which is
103629 ** an integer. It constructs a string where each character of the string
103630 ** is the unicode character for the corresponding integer argument.
103631 */
103632 static void charFunc(
103633  sqlite3_context *context,
103634  int argc,
103635  sqlite3_value **argv
103636 ){
103637  unsigned char *z, *zOut;
103638  int i;
103639  zOut = z = sqlite3_malloc64( argc*4+1 );
103640  if( z==0 ){
103641  sqlite3_result_error_nomem(context);
103642  return;
103643  }
103644  for(i=0; i<argc; i++){
103645  sqlite3_int64 x;
103646  unsigned c;
103647  x = sqlite3_value_int64(argv[i]);
103648  if( x<0 || x>0x10ffff ) x = 0xfffd;
103649  c = (unsigned)(x & 0x1fffff);
103650  if( c<0x00080 ){
103651  *zOut++ = (u8)(c&0xFF);
103652  }else if( c<0x00800 ){
103653  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
103654  *zOut++ = 0x80 + (u8)(c & 0x3F);
103655  }else if( c<0x10000 ){
103656  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
103657  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
103658  *zOut++ = 0x80 + (u8)(c & 0x3F);
103659  }else{
103660  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
103661  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
103662  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
103663  *zOut++ = 0x80 + (u8)(c & 0x3F);
103664  } \
103665  }
103666  sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
103667 }
103668 
103669 /*
103670 ** The hex() function. Interpret the argument as a blob. Return
103671 ** a hexadecimal rendering as text.
103672 */
103673 static void hexFunc(
103674  sqlite3_context *context,
103675  int argc,
103676  sqlite3_value **argv
103677 ){
103678  int i, n;
103679  const unsigned char *pBlob;
103680  char *zHex, *z;
103681  assert( argc==1 );
103682  UNUSED_PARAMETER(argc);
103683  pBlob = sqlite3_value_blob(argv[0]);
103684  n = sqlite3_value_bytes(argv[0]);
103685  assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
103686  z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
103687  if( zHex ){
103688  for(i=0; i<n; i++, pBlob++){
103689  unsigned char c = *pBlob;
103690  *(z++) = hexdigits[(c>>4)&0xf];
103691  *(z++) = hexdigits[c&0xf];
103692  }
103693  *z = 0;
103694  sqlite3_result_text(context, zHex, n*2, sqlite3_free);
103695  }
103696 }
103697 
103698 /*
103699 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
103700 */
103701 static void zeroblobFunc(
103702  sqlite3_context *context,
103703  int argc,
103704  sqlite3_value **argv
103705 ){
103706  i64 n;
103707  int rc;
103708  assert( argc==1 );
103709  UNUSED_PARAMETER(argc);
103710  n = sqlite3_value_int64(argv[0]);
103711  if( n<0 ) n = 0;
103712  rc = sqlite3_result_zeroblob64(context, n); /* IMP: R-00293-64994 */
103713  if( rc ){
103714  sqlite3_result_error_code(context, rc);
103715  }
103716 }
103717 
103718 /*
103719 ** The replace() function. Three arguments are all strings: call
103720 ** them A, B, and C. The result is also a string which is derived
103721 ** from A by replacing every occurrence of B with C. The match
103722 ** must be exact. Collating sequences are not used.
103723 */
103724 static void replaceFunc(
103725  sqlite3_context *context,
103726  int argc,
103727  sqlite3_value **argv
103728 ){
103729  const unsigned char *zStr; /* The input string A */
103730  const unsigned char *zPattern; /* The pattern string B */
103731  const unsigned char *zRep; /* The replacement string C */
103732  unsigned char *zOut; /* The output */
103733  int nStr; /* Size of zStr */
103734  int nPattern; /* Size of zPattern */
103735  int nRep; /* Size of zRep */
103736  i64 nOut; /* Maximum size of zOut */
103737  int loopLimit; /* Last zStr[] that might match zPattern[] */
103738  int i, j; /* Loop counters */
103739 
103740  assert( argc==3 );
103741  UNUSED_PARAMETER(argc);
103742  zStr = sqlite3_value_text(argv[0]);
103743  if( zStr==0 ) return;
103744  nStr = sqlite3_value_bytes(argv[0]);
103745  assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
103746  zPattern = sqlite3_value_text(argv[1]);
103747  if( zPattern==0 ){
103749  || sqlite3_context_db_handle(context)->mallocFailed );
103750  return;
103751  }
103752  if( zPattern[0]==0 ){
103753  assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
103754  sqlite3_result_value(context, argv[0]);
103755  return;
103756  }
103757  nPattern = sqlite3_value_bytes(argv[1]);
103758  assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
103759  zRep = sqlite3_value_text(argv[2]);
103760  if( zRep==0 ) return;
103761  nRep = sqlite3_value_bytes(argv[2]);
103762  assert( zRep==sqlite3_value_text(argv[2]) );
103763  nOut = nStr + 1;
103764  assert( nOut<SQLITE_MAX_LENGTH );
103765  zOut = contextMalloc(context, (i64)nOut);
103766  if( zOut==0 ){
103767  return;
103768  }
103769  loopLimit = nStr - nPattern;
103770  for(i=j=0; i<=loopLimit; i++){
103771  if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
103772  zOut[j++] = zStr[i];
103773  }else{
103774  u8 *zOld;
103775  sqlite3 *db = sqlite3_context_db_handle(context);
103776  nOut += nRep - nPattern;
103777  testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
103778  testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
103779  if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
103780  sqlite3_result_error_toobig(context);
103781  sqlite3_free(zOut);
103782  return;
103783  }
103784  zOld = zOut;
103785  zOut = sqlite3_realloc64(zOut, (int)nOut);
103786  if( zOut==0 ){
103787  sqlite3_result_error_nomem(context);
103788  sqlite3_free(zOld);
103789  return;
103790  }
103791  memcpy(&zOut[j], zRep, nRep);
103792  j += nRep;
103793  i += nPattern-1;
103794  }
103795  }
103796  assert( j+nStr-i+1==nOut );
103797  memcpy(&zOut[j], &zStr[i], nStr-i);
103798  j += nStr - i;
103799  assert( j<=nOut );
103800  zOut[j] = 0;
103801  sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
103802 }
103803 
103804 /*
103805 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
103806 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
103807 */
103808 static void trimFunc(
103809  sqlite3_context *context,
103810  int argc,
103811  sqlite3_value **argv
103812 ){
103813  const unsigned char *zIn; /* Input string */
103814  const unsigned char *zCharSet; /* Set of characters to trim */
103815  int nIn; /* Number of bytes in input */
103816  int flags; /* 1: trimleft 2: trimright 3: trim */
103817  int i; /* Loop counter */
103818  unsigned char *aLen = 0; /* Length of each character in zCharSet */
103819  unsigned char **azChar = 0; /* Individual characters in zCharSet */
103820  int nChar; /* Number of characters in zCharSet */
103821 
103822  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
103823  return;
103824  }
103825  zIn = sqlite3_value_text(argv[0]);
103826  if( zIn==0 ) return;
103827  nIn = sqlite3_value_bytes(argv[0]);
103828  assert( zIn==sqlite3_value_text(argv[0]) );
103829  if( argc==1 ){
103830  static const unsigned char lenOne[] = { 1 };
103831  static unsigned char * const azOne[] = { (u8*)" " };
103832  nChar = 1;
103833  aLen = (u8*)lenOne;
103834  azChar = (unsigned char **)azOne;
103835  zCharSet = 0;
103836  }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
103837  return;
103838  }else{
103839  const unsigned char *z;
103840  for(z=zCharSet, nChar=0; *z; nChar++){
103841  SQLITE_SKIP_UTF8(z);
103842  }
103843  if( nChar>0 ){
103844  azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
103845  if( azChar==0 ){
103846  return;
103847  }
103848  aLen = (unsigned char*)&azChar[nChar];
103849  for(z=zCharSet, nChar=0; *z; nChar++){
103850  azChar[nChar] = (unsigned char *)z;
103851  SQLITE_SKIP_UTF8(z);
103852  aLen[nChar] = (u8)(z - azChar[nChar]);
103853  }
103854  }
103855  }
103856  if( nChar>0 ){
103857  flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
103858  if( flags & 1 ){
103859  while( nIn>0 ){
103860  int len = 0;
103861  for(i=0; i<nChar; i++){
103862  len = aLen[i];
103863  if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
103864  }
103865  if( i>=nChar ) break;
103866  zIn += len;
103867  nIn -= len;
103868  }
103869  }
103870  if( flags & 2 ){
103871  while( nIn>0 ){
103872  int len = 0;
103873  for(i=0; i<nChar; i++){
103874  len = aLen[i];
103875  if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
103876  }
103877  if( i>=nChar ) break;
103878  nIn -= len;
103879  }
103880  }
103881  if( zCharSet ){
103882  sqlite3_free(azChar);
103883  }
103884  }
103885  sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
103886 }
103887 
103888 
103889 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
103890 ** is only available if the SQLITE_SOUNDEX compile-time option is used
103891 ** when SQLite is built.
103892 */
103893 #ifdef SQLITE_SOUNDEX
103894 /*
103895 ** Compute the soundex encoding of a word.
103896 **
103897 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
103898 ** soundex encoding of the string X.
103899 */
103900 static void soundexFunc(
103901  sqlite3_context *context,
103902  int argc,
103903  sqlite3_value **argv
103904 ){
103905  char zResult[8];
103906  const u8 *zIn;
103907  int i, j;
103908  static const unsigned char iCode[] = {
103909  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103910  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103911  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103912  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
103913  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
103914  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
103915  0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
103916  1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
103917  };
103918  assert( argc==1 );
103919  zIn = (u8*)sqlite3_value_text(argv[0]);
103920  if( zIn==0 ) zIn = (u8*)"";
103921  for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
103922  if( zIn[i] ){
103923  u8 prevcode = iCode[zIn[i]&0x7f];
103924  zResult[0] = sqlite3Toupper(zIn[i]);
103925  for(j=1; j<4 && zIn[i]; i++){
103926  int code = iCode[zIn[i]&0x7f];
103927  if( code>0 ){
103928  if( code!=prevcode ){
103929  prevcode = code;
103930  zResult[j++] = code + '0';
103931  }
103932  }else{
103933  prevcode = 0;
103934  }
103935  }
103936  while( j<4 ){
103937  zResult[j++] = '0';
103938  }
103939  zResult[j] = 0;
103940  sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
103941  }else{
103942  /* IMP: R-64894-50321 The string "?000" is returned if the argument
103943  ** is NULL or contains no ASCII alphabetic characters. */
103944  sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
103945  }
103946 }
103947 #endif /* SQLITE_SOUNDEX */
103948 
103949 #ifndef SQLITE_OMIT_LOAD_EXTENSION
103950 /*
103951 ** A function that loads a shared-library extension then returns NULL.
103952 */
103953 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
103954  const char *zFile = (const char *)sqlite3_value_text(argv[0]);
103955  const char *zProc;
103956  sqlite3 *db = sqlite3_context_db_handle(context);
103957  char *zErrMsg = 0;
103958 
103959  /* Disallow the load_extension() SQL function unless the SQLITE_LoadExtFunc
103960  ** flag is set. See the sqlite3_enable_load_extension() API.
103961  */
103962  if( (db->flags & SQLITE_LoadExtFunc)==0 ){
103963  sqlite3_result_error(context, "not authorized", -1);
103964  return;
103965  }
103966 
103967  if( argc==2 ){
103968  zProc = (const char *)sqlite3_value_text(argv[1]);
103969  }else{
103970  zProc = 0;
103971  }
103972  if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
103973  sqlite3_result_error(context, zErrMsg, -1);
103974  sqlite3_free(zErrMsg);
103975  }
103976 }
103977 #endif
103978 
103979 
103980 /*
103981 ** An instance of the following structure holds the context of a
103982 ** sum() or avg() aggregate computation.
103983 */
103984 typedef struct SumCtx SumCtx;
103985 struct SumCtx {
103986  double rSum; /* Floating point sum */
103987  i64 iSum; /* Integer sum */
103988  i64 cnt; /* Number of elements summed */
103989  u8 overflow; /* True if integer overflow seen */
103990  u8 approx; /* True if non-integer value was input to the sum */
103991 };
103992 
103993 /*
103994 ** Routines used to compute the sum, average, and total.
103995 **
103996 ** The SUM() function follows the (broken) SQL standard which means
103997 ** that it returns NULL if it sums over no inputs. TOTAL returns
103998 ** 0.0 in that case. In addition, TOTAL always returns a float where
103999 ** SUM might return an integer if it never encounters a floating point
104000 ** value. TOTAL never fails, but SUM might through an exception if
104001 ** it overflows an integer.
104002 */
104003 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104004  SumCtx *p;
104005  int type;
104006  assert( argc==1 );
104007  UNUSED_PARAMETER(argc);
104008  p = sqlite3_aggregate_context(context, sizeof(*p));
104009  type = sqlite3_value_numeric_type(argv[0]);
104010  if( p && type!=SQLITE_NULL ){
104011  p->cnt++;
104012  if( type==SQLITE_INTEGER ){
104013  i64 v = sqlite3_value_int64(argv[0]);
104014  p->rSum += v;
104015  if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
104016  p->overflow = 1;
104017  }
104018  }else{
104019  p->rSum += sqlite3_value_double(argv[0]);
104020  p->approx = 1;
104021  }
104022  }
104023 }
104024 static void sumFinalize(sqlite3_context *context){
104025  SumCtx *p;
104026  p = sqlite3_aggregate_context(context, 0);
104027  if( p && p->cnt>0 ){
104028  if( p->overflow ){
104029  sqlite3_result_error(context,"integer overflow",-1);
104030  }else if( p->approx ){
104031  sqlite3_result_double(context, p->rSum);
104032  }else{
104033  sqlite3_result_int64(context, p->iSum);
104034  }
104035  }
104036 }
104037 static void avgFinalize(sqlite3_context *context){
104038  SumCtx *p;
104039  p = sqlite3_aggregate_context(context, 0);
104040  if( p && p->cnt>0 ){
104041  sqlite3_result_double(context, p->rSum/(double)p->cnt);
104042  }
104043 }
104044 static void totalFinalize(sqlite3_context *context){
104045  SumCtx *p;
104046  p = sqlite3_aggregate_context(context, 0);
104047  /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
104048  sqlite3_result_double(context, p ? p->rSum : (double)0);
104049 }
104050 
104051 /*
104052 ** The following structure keeps track of state information for the
104053 ** count() aggregate function.
104054 */
104055 typedef struct CountCtx CountCtx;
104056 struct CountCtx {
104057  i64 n;
104058 };
104059 
104060 /*
104061 ** Routines to implement the count() aggregate function.
104062 */
104063 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
104064  CountCtx *p;
104065  p = sqlite3_aggregate_context(context, sizeof(*p));
104066  if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
104067  p->n++;
104068  }
104069 
104070 #ifndef SQLITE_OMIT_DEPRECATED
104071  /* The sqlite3_aggregate_count() function is deprecated. But just to make
104072  ** sure it still operates correctly, verify that its count agrees with our
104073  ** internal count when using count(*) and when the total count can be
104074  ** expressed as a 32-bit integer. */
104075  assert( argc==1 || p==0 || p->n>0x7fffffff
104076  || p->n==sqlite3_aggregate_count(context) );
104077 #endif
104078 }
104079 static void countFinalize(sqlite3_context *context){
104080  CountCtx *p;
104081  p = sqlite3_aggregate_context(context, 0);
104082  sqlite3_result_int64(context, p ? p->n : 0);
104083 }
104084 
104085 /*
104086 ** Routines to implement min() and max() aggregate functions.
104087 */
104088 static void minmaxStep(
104089  sqlite3_context *context,
104090  int NotUsed,
104091  sqlite3_value **argv
104092 ){
104093  Mem *pArg = (Mem *)argv[0];
104094  Mem *pBest;
104095  UNUSED_PARAMETER(NotUsed);
104096 
104097  pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
104098  if( !pBest ) return;
104099 
104100  if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
104101  if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
104102  }else if( pBest->flags ){
104103  int max;
104104  int cmp;
104105  CollSeq *pColl = sqlite3GetFuncCollSeq(context);
104106  /* This step function is used for both the min() and max() aggregates,
104107  ** the only difference between the two being that the sense of the
104108  ** comparison is inverted. For the max() aggregate, the
104109  ** sqlite3_user_data() function returns (void *)-1. For min() it
104110  ** returns (void *)db, where db is the sqlite3* database pointer.
104111  ** Therefore the next statement sets variable 'max' to 1 for the max()
104112  ** aggregate, or 0 for min().
104113  */
104114  max = sqlite3_user_data(context)!=0;
104115  cmp = sqlite3MemCompare(pBest, pArg, pColl);
104116  if( (max && cmp<0) || (!max && cmp>0) ){
104117  sqlite3VdbeMemCopy(pBest, pArg);
104118  }else{
104119  sqlite3SkipAccumulatorLoad(context);
104120  }
104121  }else{
104122  pBest->db = sqlite3_context_db_handle(context);
104123  sqlite3VdbeMemCopy(pBest, pArg);
104124  }
104125 }
104126 static void minMaxFinalize(sqlite3_context *context){
104127  sqlite3_value *pRes;
104128  pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
104129  if( pRes ){
104130  if( pRes->flags ){
104131  sqlite3_result_value(context, pRes);
104132  }
104133  sqlite3VdbeMemRelease(pRes);
104134  }
104135 }
104136 
104137 /*
104138 ** group_concat(EXPR, ?SEPARATOR?)
104139 */
104140 static void groupConcatStep(
104141  sqlite3_context *context,
104142  int argc,
104143  sqlite3_value **argv
104144 ){
104145  const char *zVal;
104146  StrAccum *pAccum;
104147  const char *zSep;
104148  int nVal, nSep;
104149  assert( argc==1 || argc==2 );
104150  if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
104151  pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
104152 
104153  if( pAccum ){
104154  sqlite3 *db = sqlite3_context_db_handle(context);
104155  int firstTerm = pAccum->mxAlloc==0;
104156  pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
104157  if( !firstTerm ){
104158  if( argc==2 ){
104159  zSep = (char*)sqlite3_value_text(argv[1]);
104160  nSep = sqlite3_value_bytes(argv[1]);
104161  }else{
104162  zSep = ",";
104163  nSep = 1;
104164  }
104165  if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
104166  }
104167  zVal = (char*)sqlite3_value_text(argv[0]);
104168  nVal = sqlite3_value_bytes(argv[0]);
104169  if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
104170  }
104171 }
104173  StrAccum *pAccum;
104174  pAccum = sqlite3_aggregate_context(context, 0);
104175  if( pAccum ){
104176  if( pAccum->accError==STRACCUM_TOOBIG ){
104177  sqlite3_result_error_toobig(context);
104178  }else if( pAccum->accError==STRACCUM_NOMEM ){
104179  sqlite3_result_error_nomem(context);
104180  }else{
104181  sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
104182  sqlite3_free);
104183  }
104184  }
104185 }
104186 
104187 /*
104188 ** This routine does per-connection function registration. Most
104189 ** of the built-in functions above are part of the global function set.
104190 ** This routine only deals with those that are not global.
104191 */
104193  int rc = sqlite3_overload_function(db, "MATCH", 2);
104194  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
104195  if( rc==SQLITE_NOMEM ){
104196  sqlite3OomFault(db);
104197  }
104198 }
104199 
104200 /*
104201 ** Set the LIKEOPT flag on the 2-argument function with the given name.
104202 */
104203 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
104204  FuncDef *pDef;
104205  pDef = sqlite3FindFunction(db, zName, 2, SQLITE_UTF8, 0);
104206  if( ALWAYS(pDef) ){
104207  pDef->funcFlags |= flagVal;
104208  }
104209 }
104210 
104211 /*
104212 ** Register the built-in LIKE and GLOB functions. The caseSensitive
104213 ** parameter determines whether or not the LIKE operator is case
104214 ** sensitive. GLOB is always case sensitive.
104215 */
104217  struct compareInfo *pInfo;
104218  if( caseSensitive ){
104219  pInfo = (struct compareInfo*)&likeInfoAlt;
104220  }else{
104221  pInfo = (struct compareInfo*)&likeInfoNorm;
104222  }
104223  sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104224  sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
104225  sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
104226  (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
104228  setLikeOptFlag(db, "like",
104229  caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
104230 }
104231 
104232 /*
104233 ** pExpr points to an expression which implements a function. If
104234 ** it is appropriate to apply the LIKE optimization to that function
104235 ** then set aWc[0] through aWc[2] to the wildcard characters and
104236 ** return TRUE. If the function is not a LIKE-style function then
104237 ** return FALSE.
104238 **
104239 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
104240 ** the function (default for LIKE). If the function makes the distinction
104241 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
104242 ** false.
104243 */
104244 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
104245  FuncDef *pDef;
104246  if( pExpr->op!=TK_FUNCTION
104247  || !pExpr->x.pList
104248  || pExpr->x.pList->nExpr!=2
104249  ){
104250  return 0;
104251  }
104252  assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
104253  pDef = sqlite3FindFunction(db, pExpr->u.zToken, 2, SQLITE_UTF8, 0);
104254  if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
104255  return 0;
104256  }
104257 
104258  /* The memcpy() statement assumes that the wildcard characters are
104259  ** the first three statements in the compareInfo structure. The
104260  ** asserts() that follow verify that assumption
104261  */
104262  memcpy(aWc, pDef->pUserData, 3);
104263  assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
104264  assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
104265  assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
104266  *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
104267  return 1;
104268 }
104269 
104270 /*
104271 ** All of the FuncDef structures in the aBuiltinFunc[] array above
104272 ** to the global function hash table. This occurs at start-time (as
104273 ** a consequence of calling sqlite3_initialize()).
104274 **
104275 ** After this routine runs
104276 */
104278  /*
104279  ** The following array holds FuncDef structures for all of the functions
104280  ** defined in this file.
104281  **
104282  ** The array cannot be constant since changes are made to the
104283  ** FuncDef.pHash elements at start-time. The elements of this array
104284  ** are read-only after initialization is complete.
104285  **
104286  ** For peak efficiency, put the most frequently used function last.
104287  */
104288  static FuncDef aBuiltinFunc[] = {
104289 #ifdef SQLITE_SOUNDEX
104290  FUNCTION(soundex, 1, 0, 0, soundexFunc ),
104291 #endif
104292 #ifndef SQLITE_OMIT_LOAD_EXTENSION
104293  VFUNCTION(load_extension, 1, 0, 0, loadExt ),
104294  VFUNCTION(load_extension, 2, 0, 0, loadExt ),
104295 #endif
104296 #if SQLITE_USER_AUTHENTICATION
104297  FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
104298 #endif
104299 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104300  DFUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
104301  DFUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
104302 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104304  FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
104306  FUNCTION(ltrim, 1, 1, 0, trimFunc ),
104307  FUNCTION(ltrim, 2, 1, 0, trimFunc ),
104308  FUNCTION(rtrim, 1, 2, 0, trimFunc ),
104309  FUNCTION(rtrim, 2, 2, 0, trimFunc ),
104310  FUNCTION(trim, 1, 3, 0, trimFunc ),
104311  FUNCTION(trim, 2, 3, 0, trimFunc ),
104312  FUNCTION(min, -1, 0, 1, minmaxFunc ),
104313  FUNCTION(min, 0, 0, 1, 0 ),
104315  SQLITE_FUNC_MINMAX ),
104316  FUNCTION(max, -1, 1, 1, minmaxFunc ),
104317  FUNCTION(max, 0, 1, 1, 0 ),
104318  AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
104319  SQLITE_FUNC_MINMAX ),
104320  FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
104321  FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
104322  FUNCTION(instr, 2, 0, 0, instrFunc ),
104323  FUNCTION(printf, -1, 0, 0, printfFunc ),
104324  FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
104325  FUNCTION(char, -1, 0, 0, charFunc ),
104326  FUNCTION(abs, 1, 0, 0, absFunc ),
104327 #ifndef SQLITE_OMIT_FLOATING_POINT
104328  FUNCTION(round, 1, 0, 0, roundFunc ),
104329  FUNCTION(round, 2, 0, 0, roundFunc ),
104330 #endif
104331  FUNCTION(upper, 1, 0, 0, upperFunc ),
104332  FUNCTION(lower, 1, 0, 0, lowerFunc ),
104333  FUNCTION(hex, 1, 0, 0, hexFunc ),
104334  FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
104335  VFUNCTION(random, 0, 0, 0, randomFunc ),
104336  VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
104337  FUNCTION(nullif, 2, 0, 1, nullifFunc ),
104338  DFUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
104339  DFUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
104340  FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
104341  FUNCTION(quote, 1, 0, 0, quoteFunc ),
104343  VFUNCTION(changes, 0, 0, 0, changes ),
104344  VFUNCTION(total_changes, 0, 0, 0, total_changes ),
104345  FUNCTION(replace, 3, 0, 0, replaceFunc ),
104346  FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
104347  FUNCTION(substr, 2, 0, 0, substrFunc ),
104348  FUNCTION(substr, 3, 0, 0, substrFunc ),
104349  AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
104350  AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
104351  AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
104353  SQLITE_FUNC_COUNT ),
104354  AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
104355  AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
104356  AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
104357 
104359  #ifdef SQLITE_CASE_SENSITIVE_LIKE
104360  LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
104361  LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
104362  #else
104363  LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
104364  LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
104365  #endif
104366  FUNCTION(coalesce, 1, 0, 0, 0 ),
104367  FUNCTION(coalesce, 0, 0, 0, 0 ),
104368  FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
104369  };
104370 #ifndef SQLITE_OMIT_ALTERTABLE
104372 #endif
104373 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
104374  sqlite3AnalyzeFunctions();
104375 #endif
104377  sqlite3InsertBuiltinFuncs(aBuiltinFunc, ArraySize(aBuiltinFunc));
104378 
104379 #if 0 /* Enable to print out how the built-in functions are hashed */
104380  {
104381  int i;
104382  FuncDef *p;
104383  for(i=0; i<SQLITE_FUNC_HASH_SZ; i++){
104384  printf("FUNC-HASH %02d:", i);
104385  for(p=sqlite3BuiltinFunctions.a[i]; p; p=p->u.pHash){
104386  int n = sqlite3Strlen30(p->zName);
104387  int h = p->zName[0] + n;
104388  printf(" %s(%d)", p->zName, h);
104389  }
104390  printf("\n");
104391  }
104392  }
104393 #endif
104394 }
104395 
104396 /************** End of func.c ************************************************/
104397 /************** Begin file fkey.c ********************************************/
104398 /*
104399 **
104400 ** The author disclaims copyright to this source code. In place of
104401 ** a legal notice, here is a blessing:
104402 **
104403 ** May you do good and not evil.
104404 ** May you find forgiveness for yourself and forgive others.
104405 ** May you share freely, never taking more than you give.
104406 **
104407 *************************************************************************
104408 ** This file contains code used by the compiler to add foreign key
104409 ** support to compiled SQL statements.
104410 */
104411 /* #include "sqliteInt.h" */
104412 
104413 #ifndef SQLITE_OMIT_FOREIGN_KEY
104414 #ifndef SQLITE_OMIT_TRIGGER
104415 
104416 /*
104417 ** Deferred and Immediate FKs
104418 ** --------------------------
104419 **
104420 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
104421 ** If an immediate foreign key constraint is violated,
104422 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
104423 ** statement transaction rolled back. If a
104424 ** deferred foreign key constraint is violated, no action is taken
104425 ** immediately. However if the application attempts to commit the
104426 ** transaction before fixing the constraint violation, the attempt fails.
104427 **
104428 ** Deferred constraints are implemented using a simple counter associated
104429 ** with the database handle. The counter is set to zero each time a
104430 ** database transaction is opened. Each time a statement is executed
104431 ** that causes a foreign key violation, the counter is incremented. Each
104432 ** time a statement is executed that removes an existing violation from
104433 ** the database, the counter is decremented. When the transaction is
104434 ** committed, the commit fails if the current value of the counter is
104435 ** greater than zero. This scheme has two big drawbacks:
104436 **
104437 ** * When a commit fails due to a deferred foreign key constraint,
104438 ** there is no way to tell which foreign constraint is not satisfied,
104439 ** or which row it is not satisfied for.
104440 **
104441 ** * If the database contains foreign key violations when the
104442 ** transaction is opened, this may cause the mechanism to malfunction.
104443 **
104444 ** Despite these problems, this approach is adopted as it seems simpler
104445 ** than the alternatives.
104446 **
104447 ** INSERT operations:
104448 **
104449 ** I.1) For each FK for which the table is the child table, search
104450 ** the parent table for a match. If none is found increment the
104451 ** constraint counter.
104452 **
104453 ** I.2) For each FK for which the table is the parent table,
104454 ** search the child table for rows that correspond to the new
104455 ** row in the parent table. Decrement the counter for each row
104456 ** found (as the constraint is now satisfied).
104457 **
104458 ** DELETE operations:
104459 **
104460 ** D.1) For each FK for which the table is the child table,
104461 ** search the parent table for a row that corresponds to the
104462 ** deleted row in the child table. If such a row is not found,
104463 ** decrement the counter.
104464 **
104465 ** D.2) For each FK for which the table is the parent table, search
104466 ** the child table for rows that correspond to the deleted row
104467 ** in the parent table. For each found increment the counter.
104468 **
104469 ** UPDATE operations:
104470 **
104471 ** An UPDATE command requires that all 4 steps above are taken, but only
104472 ** for FK constraints for which the affected columns are actually
104473 ** modified (values must be compared at runtime).
104474 **
104475 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
104476 ** This simplifies the implementation a bit.
104477 **
104478 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
104479 ** resolution is considered to delete rows before the new row is inserted.
104480 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
104481 ** is thrown, even if the FK constraint would be satisfied after the new
104482 ** row is inserted.
104483 **
104484 ** Immediate constraints are usually handled similarly. The only difference
104485 ** is that the counter used is stored as part of each individual statement
104486 ** object (struct Vdbe). If, after the statement has run, its immediate
104487 ** constraint counter is greater than zero,
104488 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
104489 ** and the statement transaction is rolled back. An exception is an INSERT
104490 ** statement that inserts a single row only (no triggers). In this case,
104491 ** instead of using a counter, an exception is thrown immediately if the
104492 ** INSERT violates a foreign key constraint. This is necessary as such
104493 ** an INSERT does not open a statement transaction.
104494 **
104495 ** TODO: How should dropping a table be handled? How should renaming a
104496 ** table be handled?
104497 **
104498 **
104499 ** Query API Notes
104500 ** ---------------
104501 **
104502 ** Before coding an UPDATE or DELETE row operation, the code-generator
104503 ** for those two operations needs to know whether or not the operation
104504 ** requires any FK processing and, if so, which columns of the original
104505 ** row are required by the FK processing VDBE code (i.e. if FKs were
104506 ** implemented using triggers, which of the old.* columns would be
104507 ** accessed). No information is required by the code-generator before
104508 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
104509 ** generation code to query for this information are:
104510 **
104511 ** sqlite3FkRequired() - Test to see if FK processing is required.
104512 ** sqlite3FkOldmask() - Query for the set of required old.* columns.
104513 **
104514 **
104515 ** Externally accessible module functions
104516 ** --------------------------------------
104517 **
104518 ** sqlite3FkCheck() - Check for foreign key violations.
104519 ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
104520 ** sqlite3FkDelete() - Delete an FKey structure.
104521 */
104522 
104523 /*
104524 ** VDBE Calling Convention
104525 ** -----------------------
104526 **
104527 ** Example:
104528 **
104529 ** For the following INSERT statement:
104530 **
104531 ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
104532 ** INSERT INTO t1 VALUES(1, 2, 3.1);
104533 **
104534 ** Register (x): 2 (type integer)
104535 ** Register (x+1): 1 (type integer)
104536 ** Register (x+2): NULL (type NULL)
104537 ** Register (x+3): 3.1 (type real)
104538 */
104539 
104540 /*
104541 ** A foreign key constraint requires that the key columns in the parent
104542 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
104543 ** Given that pParent is the parent table for foreign key constraint pFKey,
104544 ** search the schema for a unique index on the parent key columns.
104545 **
104546 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
104547 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
104548 ** is set to point to the unique index.
104549 **
104550 ** If the parent key consists of a single column (the foreign key constraint
104551 ** is not a composite foreign key), output variable *paiCol is set to NULL.
104552 ** Otherwise, it is set to point to an allocated array of size N, where
104553 ** N is the number of columns in the parent key. The first element of the
104554 ** array is the index of the child table column that is mapped by the FK
104555 ** constraint to the parent table column stored in the left-most column
104556 ** of index *ppIdx. The second element of the array is the index of the
104557 ** child table column that corresponds to the second left-most column of
104558 ** *ppIdx, and so on.
104559 **
104560 ** If the required index cannot be found, either because:
104561 **
104562 ** 1) The named parent key columns do not exist, or
104563 **
104564 ** 2) The named parent key columns do exist, but are not subject to a
104565 ** UNIQUE or PRIMARY KEY constraint, or
104566 **
104567 ** 3) No parent key columns were provided explicitly as part of the
104568 ** foreign key definition, and the parent table does not have a
104569 ** PRIMARY KEY, or
104570 **
104571 ** 4) No parent key columns were provided explicitly as part of the
104572 ** foreign key definition, and the PRIMARY KEY of the parent table
104573 ** consists of a different number of columns to the child key in
104574 ** the child table.
104575 **
104576 ** then non-zero is returned, and a "foreign key mismatch" error loaded
104577 ** into pParse. If an OOM error occurs, non-zero is returned and the
104578 ** pParse->db->mallocFailed flag is set.
104579 */
104581  Parse *pParse, /* Parse context to store any error in */
104582  Table *pParent, /* Parent table of FK constraint pFKey */
104583  FKey *pFKey, /* Foreign key to find index for */
104584  Index **ppIdx, /* OUT: Unique index on parent table */
104585  int **paiCol /* OUT: Map of index columns in pFKey */
104586 ){
104587  Index *pIdx = 0; /* Value to return via *ppIdx */
104588  int *aiCol = 0; /* Value to return via *paiCol */
104589  int nCol = pFKey->nCol; /* Number of columns in parent key */
104590  char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
104591 
104592  /* The caller is responsible for zeroing output parameters. */
104593  assert( ppIdx && *ppIdx==0 );
104594  assert( !paiCol || *paiCol==0 );
104595  assert( pParse );
104596 
104597  /* If this is a non-composite (single column) foreign key, check if it
104598  ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
104599  ** and *paiCol set to zero and return early.
104600  **
104601  ** Otherwise, for a composite foreign key (more than one column), allocate
104602  ** space for the aiCol array (returned via output parameter *paiCol).
104603  ** Non-composite foreign keys do not require the aiCol array.
104604  */
104605  if( nCol==1 ){
104606  /* The FK maps to the IPK if any of the following are true:
104607  **
104608  ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
104609  ** mapped to the primary key of table pParent, or
104610  ** 2) The FK is explicitly mapped to a column declared as INTEGER
104611  ** PRIMARY KEY.
104612  */
104613  if( pParent->iPKey>=0 ){
104614  if( !zKey ) return 0;
104615  if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
104616  }
104617  }else if( paiCol ){
104618  assert( nCol>1 );
104619  aiCol = (int *)sqlite3DbMallocRawNN(pParse->db, nCol*sizeof(int));
104620  if( !aiCol ) return 1;
104621  *paiCol = aiCol;
104622  }
104623 
104624  for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
104625  if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
104626  /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
104627  ** of columns. If each indexed column corresponds to a foreign key
104628  ** column of pFKey, then this index is a winner. */
104629 
104630  if( zKey==0 ){
104631  /* If zKey is NULL, then this foreign key is implicitly mapped to
104632  ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
104633  ** identified by the test. */
104634  if( IsPrimaryKeyIndex(pIdx) ){
104635  if( aiCol ){
104636  int i;
104637  for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
104638  }
104639  break;
104640  }
104641  }else{
104642  /* If zKey is non-NULL, then this foreign key was declared to
104643  ** map to an explicit list of columns in table pParent. Check if this
104644  ** index matches those columns. Also, check that the index uses
104645  ** the default collation sequences for each column. */
104646  int i, j;
104647  for(i=0; i<nCol; i++){
104648  i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
104649  const char *zDfltColl; /* Def. collation for column */
104650  char *zIdxCol; /* Name of indexed column */
104651 
104652  if( iCol<0 ) break; /* No foreign keys against expression indexes */
104653 
104654  /* If the index uses a collation sequence that is different from
104655  ** the default collation sequence for the column, this index is
104656  ** unusable. Bail out early in this case. */
104657  zDfltColl = pParent->aCol[iCol].zColl;
104658  if( !zDfltColl ) zDfltColl = sqlite3StrBINARY;
104659  if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
104660 
104661  zIdxCol = pParent->aCol[iCol].zName;
104662  for(j=0; j<nCol; j++){
104663  if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
104664  if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
104665  break;
104666  }
104667  }
104668  if( j==nCol ) break;
104669  }
104670  if( i==nCol ) break; /* pIdx is usable */
104671  }
104672  }
104673  }
104674 
104675  if( !pIdx ){
104676  if( !pParse->disableTriggers ){
104677  sqlite3ErrorMsg(pParse,
104678  "foreign key mismatch - \"%w\" referencing \"%w\"",
104679  pFKey->pFrom->zName, pFKey->zTo);
104680  }
104681  sqlite3DbFree(pParse->db, aiCol);
104682  return 1;
104683  }
104684 
104685  *ppIdx = pIdx;
104686  return 0;
104687 }
104688 
104689 /*
104690 ** This function is called when a row is inserted into or deleted from the
104691 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
104692 ** on the child table of pFKey, this function is invoked twice for each row
104693 ** affected - once to "delete" the old row, and then again to "insert" the
104694 ** new row.
104695 **
104696 ** Each time it is called, this function generates VDBE code to locate the
104697 ** row in the parent table that corresponds to the row being inserted into
104698 ** or deleted from the child table. If the parent row can be found, no
104699 ** special action is taken. Otherwise, if the parent row can *not* be
104700 ** found in the parent table:
104701 **
104702 ** Operation | FK type | Action taken
104703 ** --------------------------------------------------------------------------
104704 ** INSERT immediate Increment the "immediate constraint counter".
104705 **
104706 ** DELETE immediate Decrement the "immediate constraint counter".
104707 **
104708 ** INSERT deferred Increment the "deferred constraint counter".
104709 **
104710 ** DELETE deferred Decrement the "deferred constraint counter".
104711 **
104712 ** These operations are identified in the comment at the top of this file
104713 ** (fkey.c) as "I.1" and "D.1".
104714 */
104715 static void fkLookupParent(
104716  Parse *pParse, /* Parse context */
104717  int iDb, /* Index of database housing pTab */
104718  Table *pTab, /* Parent table of FK pFKey */
104719  Index *pIdx, /* Unique index on parent key columns in pTab */
104720  FKey *pFKey, /* Foreign key constraint */
104721  int *aiCol, /* Map from parent key columns to child table columns */
104722  int regData, /* Address of array containing child table row */
104723  int nIncr, /* Increment constraint counter by this */
104724  int isIgnore /* If true, pretend pTab contains all NULL values */
104725 ){
104726  int i; /* Iterator variable */
104727  Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
104728  int iCur = pParse->nTab - 1; /* Cursor number to use */
104729  int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
104730 
104731  /* If nIncr is less than zero, then check at runtime if there are any
104732  ** outstanding constraints to resolve. If there are not, there is no need
104733  ** to check if deleting this row resolves any outstanding violations.
104734  **
104735  ** Check if any of the key columns in the child table row are NULL. If
104736  ** any are, then the constraint is considered satisfied. No need to
104737  ** search for a matching row in the parent table. */
104738  if( nIncr<0 ){
104739  sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
104740  VdbeCoverage(v);
104741  }
104742  for(i=0; i<pFKey->nCol; i++){
104743  int iReg = aiCol[i] + regData + 1;
104744  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
104745  }
104746 
104747  if( isIgnore==0 ){
104748  if( pIdx==0 ){
104749  /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
104750  ** column of the parent table (table pTab). */
104751  int iMustBeInt; /* Address of MustBeInt instruction */
104752  int regTemp = sqlite3GetTempReg(pParse);
104753 
104754  /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
104755  ** apply the affinity of the parent key). If this fails, then there
104756  ** is no matching parent key. Before using MustBeInt, make a copy of
104757  ** the value. Otherwise, the value inserted into the child key column
104758  ** will have INTEGER affinity applied to it, which may not be correct. */
104759  sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
104760  iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
104761  VdbeCoverage(v);
104762 
104763  /* If the parent table is the same as the child table, and we are about
104764  ** to increment the constraint-counter (i.e. this is an INSERT operation),
104765  ** then check if the row being inserted matches itself. If so, do not
104766  ** increment the constraint-counter. */
104767  if( pTab==pFKey->pFrom && nIncr==1 ){
104768  sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
104770  }
104771 
104772  sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
104773  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
104774  sqlite3VdbeGoto(v, iOk);
104776  sqlite3VdbeJumpHere(v, iMustBeInt);
104777  sqlite3ReleaseTempReg(pParse, regTemp);
104778  }else{
104779  int nCol = pFKey->nCol;
104780  int regTemp = sqlite3GetTempRange(pParse, nCol);
104781  int regRec = sqlite3GetTempReg(pParse);
104782 
104783  sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
104784  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
104785  for(i=0; i<nCol; i++){
104786  sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
104787  }
104788 
104789  /* If the parent table is the same as the child table, and we are about
104790  ** to increment the constraint-counter (i.e. this is an INSERT operation),
104791  ** then check if the row being inserted matches itself. If so, do not
104792  ** increment the constraint-counter.
104793  **
104794  ** If any of the parent-key values are NULL, then the row cannot match
104795  ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
104796  ** of the parent-key values are NULL (at this point it is known that
104797  ** none of the child key values are).
104798  */
104799  if( pTab==pFKey->pFrom && nIncr==1 ){
104800  int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
104801  for(i=0; i<nCol; i++){
104802  int iChild = aiCol[i]+1+regData;
104803  int iParent = pIdx->aiColumn[i]+1+regData;
104804  assert( pIdx->aiColumn[i]>=0 );
104805  assert( aiCol[i]!=pTab->iPKey );
104806  if( pIdx->aiColumn[i]==pTab->iPKey ){
104807  /* The parent key is a composite key that includes the IPK column */
104808  iParent = regData;
104809  }
104810  sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
104812  }
104813  sqlite3VdbeGoto(v, iOk);
104814  }
104815 
104816  sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
104817  sqlite3IndexAffinityStr(pParse->db,pIdx), nCol);
104818  sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
104819 
104820  sqlite3ReleaseTempReg(pParse, regRec);
104821  sqlite3ReleaseTempRange(pParse, regTemp, nCol);
104822  }
104823  }
104824 
104825  if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
104826  && !pParse->pToplevel
104827  && !pParse->isMultiWrite
104828  ){
104829  /* Special case: If this is an INSERT statement that will insert exactly
104830  ** one row into the table, raise a constraint immediately instead of
104831  ** incrementing a counter. This is necessary as the VM code is being
104832  ** generated for will not open a statement transaction. */
104833  assert( nIncr==1 );
104836  }else{
104837  if( nIncr>0 && pFKey->isDeferred==0 ){
104838  sqlite3MayAbort(pParse);
104839  }
104840  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
104841  }
104842 
104843  sqlite3VdbeResolveLabel(v, iOk);
104844  sqlite3VdbeAddOp1(v, OP_Close, iCur);
104845 }
104846 
104847 
104848 /*
104849 ** Return an Expr object that refers to a memory register corresponding
104850 ** to column iCol of table pTab.
104851 **
104852 ** regBase is the first of an array of register that contains the data
104853 ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
104854 ** column. regBase+2 holds the second column, and so forth.
104855 */
104857  Parse *pParse, /* Parsing and code generating context */
104858  Table *pTab, /* The table whose content is at r[regBase]... */
104859  int regBase, /* Contents of table pTab */
104860  i16 iCol /* Which column of pTab is desired */
104861 ){
104862  Expr *pExpr;
104863  Column *pCol;
104864  const char *zColl;
104865  sqlite3 *db = pParse->db;
104866 
104867  pExpr = sqlite3Expr(db, TK_REGISTER, 0);
104868  if( pExpr ){
104869  if( iCol>=0 && iCol!=pTab->iPKey ){
104870  pCol = &pTab->aCol[iCol];
104871  pExpr->iTable = regBase + iCol + 1;
104872  pExpr->affinity = pCol->affinity;
104873  zColl = pCol->zColl;
104874  if( zColl==0 ) zColl = db->pDfltColl->zName;
104875  pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
104876  }else{
104877  pExpr->iTable = regBase;
104878  pExpr->affinity = SQLITE_AFF_INTEGER;
104879  }
104880  }
104881  return pExpr;
104882 }
104883 
104884 /*
104885 ** Return an Expr object that refers to column iCol of table pTab which
104886 ** has cursor iCur.
104887 */
104889  sqlite3 *db, /* The database connection */
104890  Table *pTab, /* The table whose column is desired */
104891  int iCursor, /* The open cursor on the table */
104892  i16 iCol /* The column that is wanted */
104893 ){
104894  Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
104895  if( pExpr ){
104896  pExpr->pTab = pTab;
104897  pExpr->iTable = iCursor;
104898  pExpr->iColumn = iCol;
104899  }
104900  return pExpr;
104901 }
104902 
104903 /*
104904 ** This function is called to generate code executed when a row is deleted
104905 ** from the parent table of foreign key constraint pFKey and, if pFKey is
104906 ** deferred, when a row is inserted into the same table. When generating
104907 ** code for an SQL UPDATE operation, this function may be called twice -
104908 ** once to "delete" the old row and once to "insert" the new row.
104909 **
104910 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
104911 ** the number of FK violations in the db) or +1 when deleting one (as this
104912 ** may increase the number of FK constraint problems).
104913 **
104914 ** The code generated by this function scans through the rows in the child
104915 ** table that correspond to the parent table row being deleted or inserted.
104916 ** For each child row found, one of the following actions is taken:
104917 **
104918 ** Operation | FK type | Action taken
104919 ** --------------------------------------------------------------------------
104920 ** DELETE immediate Increment the "immediate constraint counter".
104921 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
104922 ** throw a "FOREIGN KEY constraint failed" exception.
104923 **
104924 ** INSERT immediate Decrement the "immediate constraint counter".
104925 **
104926 ** DELETE deferred Increment the "deferred constraint counter".
104927 ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
104928 ** throw a "FOREIGN KEY constraint failed" exception.
104929 **
104930 ** INSERT deferred Decrement the "deferred constraint counter".
104931 **
104932 ** These operations are identified in the comment at the top of this file
104933 ** (fkey.c) as "I.2" and "D.2".
104934 */
104935 static void fkScanChildren(
104936  Parse *pParse, /* Parse context */
104937  SrcList *pSrc, /* The child table to be scanned */
104938  Table *pTab, /* The parent table */
104939  Index *pIdx, /* Index on parent covering the foreign key */
104940  FKey *pFKey, /* The foreign key linking pSrc to pTab */
104941  int *aiCol, /* Map from pIdx cols to child table cols */
104942  int regData, /* Parent row data starts here */
104943  int nIncr /* Amount to increment deferred counter by */
104944 ){
104945  sqlite3 *db = pParse->db; /* Database handle */
104946  int i; /* Iterator variable */
104947  Expr *pWhere = 0; /* WHERE clause to scan with */
104948  NameContext sNameContext; /* Context used to resolve WHERE clause */
104949  WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
104950  int iFkIfZero = 0; /* Address of OP_FkIfZero */
104951  Vdbe *v = sqlite3GetVdbe(pParse);
104952 
104953  assert( pIdx==0 || pIdx->pTable==pTab );
104954  assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
104955  assert( pIdx!=0 || pFKey->nCol==1 );
104956  assert( pIdx!=0 || HasRowid(pTab) );
104957 
104958  if( nIncr<0 ){
104959  iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
104960  VdbeCoverage(v);
104961  }
104962 
104963  /* Create an Expr object representing an SQL expression like:
104964  **
104965  ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
104966  **
104967  ** The collation sequence used for the comparison should be that of
104968  ** the parent key columns. The affinity of the parent key column should
104969  ** be applied to each child key value before the comparison takes place.
104970  */
104971  for(i=0; i<pFKey->nCol; i++){
104972  Expr *pLeft; /* Value from parent table row */
104973  Expr *pRight; /* Column ref to child table */
104974  Expr *pEq; /* Expression (pLeft = pRight) */
104975  i16 iCol; /* Index of column in child table */
104976  const char *zCol; /* Name of column in child table */
104977 
104978  iCol = pIdx ? pIdx->aiColumn[i] : -1;
104979  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
104980  iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
104981  assert( iCol>=0 );
104982  zCol = pFKey->pFrom->aCol[iCol].zName;
104983  pRight = sqlite3Expr(db, TK_ID, zCol);
104984  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
104985  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
104986  }
104987 
104988  /* If the child table is the same as the parent table, then add terms
104989  ** to the WHERE clause that prevent this entry from being scanned.
104990  ** The added WHERE clause terms are like this:
104991  **
104992  ** $current_rowid!=rowid
104993  ** NOT( $current_a==a AND $current_b==b AND ... )
104994  **
104995  ** The first form is used for rowid tables. The second form is used
104996  ** for WITHOUT ROWID tables. In the second form, the primary key is
104997  ** (a,b,...)
104998  */
104999  if( pTab==pFKey->pFrom && nIncr>0 ){
105000  Expr *pNe; /* Expression (pLeft != pRight) */
105001  Expr *pLeft; /* Value from parent table row */
105002  Expr *pRight; /* Column ref to child table */
105003  if( HasRowid(pTab) ){
105004  pLeft = exprTableRegister(pParse, pTab, regData, -1);
105005  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
105006  pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
105007  }else{
105008  Expr *pEq, *pAll = 0;
105009  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
105010  assert( pIdx!=0 );
105011  for(i=0; i<pPk->nKeyCol; i++){
105012  i16 iCol = pIdx->aiColumn[i];
105013  assert( iCol>=0 );
105014  pLeft = exprTableRegister(pParse, pTab, regData, iCol);
105015  pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
105016  pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
105017  pAll = sqlite3ExprAnd(db, pAll, pEq);
105018  }
105019  pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
105020  }
105021  pWhere = sqlite3ExprAnd(db, pWhere, pNe);
105022  }
105023 
105024  /* Resolve the references in the WHERE clause. */
105025  memset(&sNameContext, 0, sizeof(NameContext));
105026  sNameContext.pSrcList = pSrc;
105027  sNameContext.pParse = pParse;
105028  sqlite3ResolveExprNames(&sNameContext, pWhere);
105029 
105030  /* Create VDBE to loop through the entries in pSrc that match the WHERE
105031  ** clause. For each row found, increment either the deferred or immediate
105032  ** foreign key constraint counter. */
105033  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
105034  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
105035  if( pWInfo ){
105036  sqlite3WhereEnd(pWInfo);
105037  }
105038 
105039  /* Clean up the WHERE clause constructed above. */
105040  sqlite3ExprDelete(db, pWhere);
105041  if( iFkIfZero ){
105042  sqlite3VdbeJumpHere(v, iFkIfZero);
105043  }
105044 }
105045 
105046 /*
105047 ** This function returns a linked list of FKey objects (connected by
105048 ** FKey.pNextTo) holding all children of table pTab. For example,
105049 ** given the following schema:
105050 **
105051 ** CREATE TABLE t1(a PRIMARY KEY);
105052 ** CREATE TABLE t2(b REFERENCES t1(a);
105053 **
105054 ** Calling this function with table "t1" as an argument returns a pointer
105055 ** to the FKey structure representing the foreign key constraint on table
105056 ** "t2". Calling this function with "t2" as the argument would return a
105057 ** NULL pointer (as there are no FK constraints for which t2 is the parent
105058 ** table).
105059 */
105061  return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
105062 }
105063 
105064 /*
105065 ** The second argument is a Trigger structure allocated by the
105066 ** fkActionTrigger() routine. This function deletes the Trigger structure
105067 ** and all of its sub-components.
105068 **
105069 ** The Trigger structure or any of its sub-components may be allocated from
105070 ** the lookaside buffer belonging to database handle dbMem.
105071 */
105072 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
105073  if( p ){
105074  TriggerStep *pStep = p->step_list;
105075  sqlite3ExprDelete(dbMem, pStep->pWhere);
105076  sqlite3ExprListDelete(dbMem, pStep->pExprList);
105077  sqlite3SelectDelete(dbMem, pStep->pSelect);
105078  sqlite3ExprDelete(dbMem, p->pWhen);
105079  sqlite3DbFree(dbMem, p);
105080  }
105081 }
105082 
105083 /*
105084 ** This function is called to generate code that runs when table pTab is
105085 ** being dropped from the database. The SrcList passed as the second argument
105086 ** to this function contains a single entry guaranteed to resolve to
105087 ** table pTab.
105088 **
105089 ** Normally, no code is required. However, if either
105090 **
105091 ** (a) The table is the parent table of a FK constraint, or
105092 ** (b) The table is the child table of a deferred FK constraint and it is
105093 ** determined at runtime that there are outstanding deferred FK
105094 ** constraint violations in the database,
105095 **
105096 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
105097 ** the table from the database. Triggers are disabled while running this
105098 ** DELETE, but foreign key actions are not.
105099 */
105101  sqlite3 *db = pParse->db;
105102  if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
105103  int iSkip = 0;
105104  Vdbe *v = sqlite3GetVdbe(pParse);
105105 
105106  assert( v ); /* VDBE has already been allocated */
105107  if( sqlite3FkReferences(pTab)==0 ){
105108  /* Search for a deferred foreign key constraint for which this table
105109  ** is the child table. If one cannot be found, return without
105110  ** generating any VDBE code. If one can be found, then jump over
105111  ** the entire DELETE if there are no outstanding deferred constraints
105112  ** when this statement is run. */
105113  FKey *p;
105114  for(p=pTab->pFKey; p; p=p->pNextFrom){
105115  if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
105116  }
105117  if( !p ) return;
105118  iSkip = sqlite3VdbeMakeLabel(v);
105119  sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
105120  }
105121 
105122  pParse->disableTriggers = 1;
105123  sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
105124  pParse->disableTriggers = 0;
105125 
105126  /* If the DELETE has generated immediate foreign key constraint
105127  ** violations, halt the VDBE and return an error at this point, before
105128  ** any modifications to the schema are made. This is because statement
105129  ** transactions are not able to rollback schema changes.
105130  **
105131  ** If the SQLITE_DeferFKs flag is set, then this is not required, as
105132  ** the statement transaction will not be rolled back even if FK
105133  ** constraints are violated.
105134  */
105135  if( (db->flags & SQLITE_DeferFKs)==0 ){
105137  VdbeCoverage(v);
105140  }
105141 
105142  if( iSkip ){
105143  sqlite3VdbeResolveLabel(v, iSkip);
105144  }
105145  }
105146 }
105147 
105148 
105149 /*
105150 ** The second argument points to an FKey object representing a foreign key
105151 ** for which pTab is the child table. An UPDATE statement against pTab
105152 ** is currently being processed. For each column of the table that is
105153 ** actually updated, the corresponding element in the aChange[] array
105154 ** is zero or greater (if a column is unmodified the corresponding element
105155 ** is set to -1). If the rowid column is modified by the UPDATE statement
105156 ** the bChngRowid argument is non-zero.
105157 **
105158 ** This function returns true if any of the columns that are part of the
105159 ** child key for FK constraint *p are modified.
105160 */
105162  Table *pTab, /* Table being updated */
105163  FKey *p, /* Foreign key for which pTab is the child */
105164  int *aChange, /* Array indicating modified columns */
105165  int bChngRowid /* True if rowid is modified by this update */
105166 ){
105167  int i;
105168  for(i=0; i<p->nCol; i++){
105169  int iChildKey = p->aCol[i].iFrom;
105170  if( aChange[iChildKey]>=0 ) return 1;
105171  if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
105172  }
105173  return 0;
105174 }
105175 
105176 /*
105177 ** The second argument points to an FKey object representing a foreign key
105178 ** for which pTab is the parent table. An UPDATE statement against pTab
105179 ** is currently being processed. For each column of the table that is
105180 ** actually updated, the corresponding element in the aChange[] array
105181 ** is zero or greater (if a column is unmodified the corresponding element
105182 ** is set to -1). If the rowid column is modified by the UPDATE statement
105183 ** the bChngRowid argument is non-zero.
105184 **
105185 ** This function returns true if any of the columns that are part of the
105186 ** parent key for FK constraint *p are modified.
105187 */
105189  Table *pTab,
105190  FKey *p,
105191  int *aChange,
105192  int bChngRowid
105193 ){
105194  int i;
105195  for(i=0; i<p->nCol; i++){
105196  char *zKey = p->aCol[i].zCol;
105197  int iKey;
105198  for(iKey=0; iKey<pTab->nCol; iKey++){
105199  if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
105200  Column *pCol = &pTab->aCol[iKey];
105201  if( zKey ){
105202  if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
105203  }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
105204  return 1;
105205  }
105206  }
105207  }
105208  }
105209  return 0;
105210 }
105211 
105212 /*
105213 ** Return true if the parser passed as the first argument is being
105214 ** used to code a trigger that is really a "SET NULL" action belonging
105215 ** to trigger pFKey.
105216 */
105217 static int isSetNullAction(Parse *pParse, FKey *pFKey){
105218  Parse *pTop = sqlite3ParseToplevel(pParse);
105219  if( pTop->pTriggerPrg ){
105220  Trigger *p = pTop->pTriggerPrg->pTrigger;
105221  if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
105222  || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
105223  ){
105224  return 1;
105225  }
105226  }
105227  return 0;
105228 }
105229 
105230 /*
105231 ** This function is called when inserting, deleting or updating a row of
105232 ** table pTab to generate VDBE code to perform foreign key constraint
105233 ** processing for the operation.
105234 **
105235 ** For a DELETE operation, parameter regOld is passed the index of the
105236 ** first register in an array of (pTab->nCol+1) registers containing the
105237 ** rowid of the row being deleted, followed by each of the column values
105238 ** of the row being deleted, from left to right. Parameter regNew is passed
105239 ** zero in this case.
105240 **
105241 ** For an INSERT operation, regOld is passed zero and regNew is passed the
105242 ** first register of an array of (pTab->nCol+1) registers containing the new
105243 ** row data.
105244 **
105245 ** For an UPDATE operation, this function is called twice. Once before
105246 ** the original record is deleted from the table using the calling convention
105247 ** described for DELETE. Then again after the original record is deleted
105248 ** but before the new record is inserted using the INSERT convention.
105249 */
105251  Parse *pParse, /* Parse context */
105252  Table *pTab, /* Row is being deleted from this table */
105253  int regOld, /* Previous row data is stored here */
105254  int regNew, /* New row data is stored here */
105255  int *aChange, /* Array indicating UPDATEd columns (or 0) */
105256  int bChngRowid /* True if rowid is UPDATEd */
105257 ){
105258  sqlite3 *db = pParse->db; /* Database handle */
105259  FKey *pFKey; /* Used to iterate through FKs */
105260  int iDb; /* Index of database containing pTab */
105261  const char *zDb; /* Name of database containing pTab */
105262  int isIgnoreErrors = pParse->disableTriggers;
105263 
105264  /* Exactly one of regOld and regNew should be non-zero. */
105265  assert( (regOld==0)!=(regNew==0) );
105266 
105267  /* If foreign-keys are disabled, this function is a no-op. */
105268  if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
105269 
105270  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
105271  zDb = db->aDb[iDb].zName;
105272 
105273  /* Loop through all the foreign key constraints for which pTab is the
105274  ** child table (the table that the foreign key definition is part of). */
105275  for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
105276  Table *pTo; /* Parent table of foreign key pFKey */
105277  Index *pIdx = 0; /* Index on key columns in pTo */
105278  int *aiFree = 0;
105279  int *aiCol;
105280  int iCol;
105281  int i;
105282  int bIgnore = 0;
105283 
105284  if( aChange
105285  && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
105286  && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
105287  ){
105288  continue;
105289  }
105290 
105291  /* Find the parent table of this foreign key. Also find a unique index
105292  ** on the parent key columns in the parent table. If either of these
105293  ** schema items cannot be located, set an error in pParse and return
105294  ** early. */
105295  if( pParse->disableTriggers ){
105296  pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
105297  }else{
105298  pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
105299  }
105300  if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
105301  assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
105302  if( !isIgnoreErrors || db->mallocFailed ) return;
105303  if( pTo==0 ){
105304  /* If isIgnoreErrors is true, then a table is being dropped. In this
105305  ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
105306  ** before actually dropping it in order to check FK constraints.
105307  ** If the parent table of an FK constraint on the current table is
105308  ** missing, behave as if it is empty. i.e. decrement the relevant
105309  ** FK counter for each row of the current table with non-NULL keys.
105310  */
105311  Vdbe *v = sqlite3GetVdbe(pParse);
105312  int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
105313  for(i=0; i<pFKey->nCol; i++){
105314  int iReg = pFKey->aCol[i].iFrom + regOld + 1;
105315  sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
105316  }
105317  sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
105318  }
105319  continue;
105320  }
105321  assert( pFKey->nCol==1 || (aiFree && pIdx) );
105322 
105323  if( aiFree ){
105324  aiCol = aiFree;
105325  }else{
105326  iCol = pFKey->aCol[0].iFrom;
105327  aiCol = &iCol;
105328  }
105329  for(i=0; i<pFKey->nCol; i++){
105330  if( aiCol[i]==pTab->iPKey ){
105331  aiCol[i] = -1;
105332  }
105333  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
105334 #ifndef SQLITE_OMIT_AUTHORIZATION
105335  /* Request permission to read the parent key columns. If the
105336  ** authorization callback returns SQLITE_IGNORE, behave as if any
105337  ** values read from the parent table are NULL. */
105338  if( db->xAuth ){
105339  int rcauth;
105340  char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
105341  rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
105342  bIgnore = (rcauth==SQLITE_IGNORE);
105343  }
105344 #endif
105345  }
105346 
105347  /* Take a shared-cache advisory read-lock on the parent table. Allocate
105348  ** a cursor to use to search the unique index on the parent key columns
105349  ** in the parent table. */
105350  sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
105351  pParse->nTab++;
105352 
105353  if( regOld!=0 ){
105354  /* A row is being removed from the child table. Search for the parent.
105355  ** If the parent does not exist, removing the child row resolves an
105356  ** outstanding foreign key constraint violation. */
105357  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
105358  }
105359  if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
105360  /* A row is being added to the child table. If a parent row cannot
105361  ** be found, adding the child row has violated the FK constraint.
105362  **
105363  ** If this operation is being performed as part of a trigger program
105364  ** that is actually a "SET NULL" action belonging to this very
105365  ** foreign key, then omit this scan altogether. As all child key
105366  ** values are guaranteed to be NULL, it is not possible for adding
105367  ** this row to cause an FK violation. */
105368  fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
105369  }
105370 
105371  sqlite3DbFree(db, aiFree);
105372  }
105373 
105374  /* Loop through all the foreign key constraints that refer to this table.
105375  ** (the "child" constraints) */
105376  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
105377  Index *pIdx = 0; /* Foreign key index for pFKey */
105378  SrcList *pSrc;
105379  int *aiCol = 0;
105380 
105381  if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
105382  continue;
105383  }
105384 
105385  if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
105386  && !pParse->pToplevel && !pParse->isMultiWrite
105387  ){
105388  assert( regOld==0 && regNew!=0 );
105389  /* Inserting a single row into a parent table cannot cause (or fix)
105390  ** an immediate foreign key violation. So do nothing in this case. */
105391  continue;
105392  }
105393 
105394  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
105395  if( !isIgnoreErrors || db->mallocFailed ) return;
105396  continue;
105397  }
105398  assert( aiCol || pFKey->nCol==1 );
105399 
105400  /* Create a SrcList structure containing the child table. We need the
105401  ** child table as a SrcList for sqlite3WhereBegin() */
105402  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
105403  if( pSrc ){
105404  struct SrcList_item *pItem = pSrc->a;
105405  pItem->pTab = pFKey->pFrom;
105406  pItem->zName = pFKey->pFrom->zName;
105407  pItem->pTab->nRef++;
105408  pItem->iCursor = pParse->nTab++;
105409 
105410  if( regNew!=0 ){
105411  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
105412  }
105413  if( regOld!=0 ){
105414  int eAction = pFKey->aAction[aChange!=0];
105415  fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
105416  /* If this is a deferred FK constraint, or a CASCADE or SET NULL
105417  ** action applies, then any foreign key violations caused by
105418  ** removing the parent key will be rectified by the action trigger.
105419  ** So do not set the "may-abort" flag in this case.
105420  **
105421  ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
105422  ** may-abort flag will eventually be set on this statement anyway
105423  ** (when this function is called as part of processing the UPDATE
105424  ** within the action trigger).
105425  **
105426  ** Note 2: At first glance it may seem like SQLite could simply omit
105427  ** all OP_FkCounter related scans when either CASCADE or SET NULL
105428  ** applies. The trouble starts if the CASCADE or SET NULL action
105429  ** trigger causes other triggers or action rules attached to the
105430  ** child table to fire. In these cases the fk constraint counters
105431  ** might be set incorrectly if any OP_FkCounter related scans are
105432  ** omitted. */
105433  if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
105434  sqlite3MayAbort(pParse);
105435  }
105436  }
105437  pItem->zName = 0;
105438  sqlite3SrcListDelete(db, pSrc);
105439  }
105440  sqlite3DbFree(db, aiCol);
105441  }
105442 }
105443 
105444 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
105445 
105446 /*
105447 ** This function is called before generating code to update or delete a
105448 ** row contained in table pTab.
105449 */
105451  Parse *pParse, /* Parse context */
105452  Table *pTab /* Table being modified */
105453 ){
105454  u32 mask = 0;
105455  if( pParse->db->flags&SQLITE_ForeignKeys ){
105456  FKey *p;
105457  int i;
105458  for(p=pTab->pFKey; p; p=p->pNextFrom){
105459  for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
105460  }
105461  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
105462  Index *pIdx = 0;
105463  sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
105464  if( pIdx ){
105465  for(i=0; i<pIdx->nKeyCol; i++){
105466  assert( pIdx->aiColumn[i]>=0 );
105467  mask |= COLUMN_MASK(pIdx->aiColumn[i]);
105468  }
105469  }
105470  }
105471  }
105472  return mask;
105473 }
105474 
105475 
105476 /*
105477 ** This function is called before generating code to update or delete a
105478 ** row contained in table pTab. If the operation is a DELETE, then
105479 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
105480 ** to an array of size N, where N is the number of columns in table pTab.
105481 ** If the i'th column is not modified by the UPDATE, then the corresponding
105482 ** entry in the aChange[] array is set to -1. If the column is modified,
105483 ** the value is 0 or greater. Parameter chngRowid is set to true if the
105484 ** UPDATE statement modifies the rowid fields of the table.
105485 **
105486 ** If any foreign key processing will be required, this function returns
105487 ** true. If there is no foreign key related processing, this function
105488 ** returns false.
105489 */
105491  Parse *pParse, /* Parse context */
105492  Table *pTab, /* Table being modified */
105493  int *aChange, /* Non-NULL for UPDATE operations */
105494  int chngRowid /* True for UPDATE that affects rowid */
105495 ){
105496  if( pParse->db->flags&SQLITE_ForeignKeys ){
105497  if( !aChange ){
105498  /* A DELETE operation. Foreign key processing is required if the
105499  ** table in question is either the child or parent table for any
105500  ** foreign key constraint. */
105501  return (sqlite3FkReferences(pTab) || pTab->pFKey);
105502  }else{
105503  /* This is an UPDATE. Foreign key processing is only required if the
105504  ** operation modifies one or more child or parent key columns. */
105505  FKey *p;
105506 
105507  /* Check if any child key columns are being modified. */
105508  for(p=pTab->pFKey; p; p=p->pNextFrom){
105509  if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
105510  }
105511 
105512  /* Check if any parent key columns are being modified. */
105513  for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
105514  if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
105515  }
105516  }
105517  }
105518  return 0;
105519 }
105520 
105521 /*
105522 ** This function is called when an UPDATE or DELETE operation is being
105523 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
105524 ** If the current operation is an UPDATE, then the pChanges parameter is
105525 ** passed a pointer to the list of columns being modified. If it is a
105526 ** DELETE, pChanges is passed a NULL pointer.
105527 **
105528 ** It returns a pointer to a Trigger structure containing a trigger
105529 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
105530 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
105531 ** returned (these actions require no special handling by the triggers
105532 ** sub-system, code for them is created by fkScanChildren()).
105533 **
105534 ** For example, if pFKey is the foreign key and pTab is table "p" in
105535 ** the following schema:
105536 **
105537 ** CREATE TABLE p(pk PRIMARY KEY);
105538 ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
105539 **
105540 ** then the returned trigger structure is equivalent to:
105541 **
105542 ** CREATE TRIGGER ... DELETE ON p BEGIN
105543 ** DELETE FROM c WHERE ck = old.pk;
105544 ** END;
105545 **
105546 ** The returned pointer is cached as part of the foreign key object. It
105547 ** is eventually freed along with the rest of the foreign key object by
105548 ** sqlite3FkDelete().
105549 */
105551  Parse *pParse, /* Parse context */
105552  Table *pTab, /* Table being updated or deleted from */
105553  FKey *pFKey, /* Foreign key to get action for */
105554  ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
105555 ){
105556  sqlite3 *db = pParse->db; /* Database handle */
105557  int action; /* One of OE_None, OE_Cascade etc. */
105558  Trigger *pTrigger; /* Trigger definition to return */
105559  int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
105560 
105561  action = pFKey->aAction[iAction];
105562  if( action==OE_Restrict && (db->flags & SQLITE_DeferFKs) ){
105563  return 0;
105564  }
105565  pTrigger = pFKey->apTrigger[iAction];
105566 
105567  if( action!=OE_None && !pTrigger ){
105568  char const *zFrom; /* Name of child table */
105569  int nFrom; /* Length in bytes of zFrom */
105570  Index *pIdx = 0; /* Parent key index for this FK */
105571  int *aiCol = 0; /* child table cols -> parent key cols */
105572  TriggerStep *pStep = 0; /* First (only) step of trigger program */
105573  Expr *pWhere = 0; /* WHERE clause of trigger step */
105574  ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
105575  Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
105576  int i; /* Iterator variable */
105577  Expr *pWhen = 0; /* WHEN clause for the trigger */
105578 
105579  if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
105580  assert( aiCol || pFKey->nCol==1 );
105581 
105582  for(i=0; i<pFKey->nCol; i++){
105583  Token tOld = { "old", 3 }; /* Literal "old" token */
105584  Token tNew = { "new", 3 }; /* Literal "new" token */
105585  Token tFromCol; /* Name of column in child table */
105586  Token tToCol; /* Name of column in parent table */
105587  int iFromCol; /* Idx of column in child table */
105588  Expr *pEq; /* tFromCol = OLD.tToCol */
105589 
105590  iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
105591  assert( iFromCol>=0 );
105592  assert( pIdx!=0 || (pTab->iPKey>=0 && pTab->iPKey<pTab->nCol) );
105593  assert( pIdx==0 || pIdx->aiColumn[i]>=0 );
105594  sqlite3TokenInit(&tToCol,
105595  pTab->aCol[pIdx ? pIdx->aiColumn[i] : pTab->iPKey].zName);
105596  sqlite3TokenInit(&tFromCol, pFKey->pFrom->aCol[iFromCol].zName);
105597 
105598  /* Create the expression "OLD.zToCol = zFromCol". It is important
105599  ** that the "OLD.zToCol" term is on the LHS of the = operator, so
105600  ** that the affinity and collation sequence associated with the
105601  ** parent table are used for the comparison. */
105602  pEq = sqlite3PExpr(pParse, TK_EQ,
105603  sqlite3PExpr(pParse, TK_DOT,
105604  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
105605  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
105606  , 0),
105607  sqlite3ExprAlloc(db, TK_ID, &tFromCol, 0)
105608  , 0);
105609  pWhere = sqlite3ExprAnd(db, pWhere, pEq);
105610 
105611  /* For ON UPDATE, construct the next term of the WHEN clause.
105612  ** The final WHEN clause will be like this:
105613  **
105614  ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
105615  */
105616  if( pChanges ){
105617  pEq = sqlite3PExpr(pParse, TK_IS,
105618  sqlite3PExpr(pParse, TK_DOT,
105619  sqlite3ExprAlloc(db, TK_ID, &tOld, 0),
105620  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
105621  0),
105622  sqlite3PExpr(pParse, TK_DOT,
105623  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
105624  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0),
105625  0),
105626  0);
105627  pWhen = sqlite3ExprAnd(db, pWhen, pEq);
105628  }
105629 
105630  if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
105631  Expr *pNew;
105632  if( action==OE_Cascade ){
105633  pNew = sqlite3PExpr(pParse, TK_DOT,
105634  sqlite3ExprAlloc(db, TK_ID, &tNew, 0),
105635  sqlite3ExprAlloc(db, TK_ID, &tToCol, 0)
105636  , 0);
105637  }else if( action==OE_SetDflt ){
105638  Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
105639  if( pDflt ){
105640  pNew = sqlite3ExprDup(db, pDflt, 0);
105641  }else{
105642  pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
105643  }
105644  }else{
105645  pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
105646  }
105647  pList = sqlite3ExprListAppend(pParse, pList, pNew);
105648  sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
105649  }
105650  }
105651  sqlite3DbFree(db, aiCol);
105652 
105653  zFrom = pFKey->pFrom->zName;
105654  nFrom = sqlite3Strlen30(zFrom);
105655 
105656  if( action==OE_Restrict ){
105657  Token tFrom;
105658  Expr *pRaise;
105659 
105660  tFrom.z = zFrom;
105661  tFrom.n = nFrom;
105662  pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
105663  if( pRaise ){
105664  pRaise->affinity = OE_Abort;
105665  }
105666  pSelect = sqlite3SelectNew(pParse,
105667  sqlite3ExprListAppend(pParse, 0, pRaise),
105668  sqlite3SrcListAppend(db, 0, &tFrom, 0),
105669  pWhere,
105670  0, 0, 0, 0, 0, 0
105671  );
105672  pWhere = 0;
105673  }
105674 
105675  /* Disable lookaside memory allocation */
105676  db->lookaside.bDisable++;
105677 
105678  pTrigger = (Trigger *)sqlite3DbMallocZero(db,
105679  sizeof(Trigger) + /* struct Trigger */
105680  sizeof(TriggerStep) + /* Single step in trigger program */
105681  nFrom + 1 /* Space for pStep->zTarget */
105682  );
105683  if( pTrigger ){
105684  pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
105685  pStep->zTarget = (char *)&pStep[1];
105686  memcpy((char *)pStep->zTarget, zFrom, nFrom);
105687 
105688  pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
105689  pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
105690  pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
105691  if( pWhen ){
105692  pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
105693  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
105694  }
105695  }
105696 
105697  /* Re-enable the lookaside buffer, if it was disabled earlier. */
105698  db->lookaside.bDisable--;
105699 
105700  sqlite3ExprDelete(db, pWhere);
105701  sqlite3ExprDelete(db, pWhen);
105702  sqlite3ExprListDelete(db, pList);
105703  sqlite3SelectDelete(db, pSelect);
105704  if( db->mallocFailed==1 ){
105705  fkTriggerDelete(db, pTrigger);
105706  return 0;
105707  }
105708  assert( pStep!=0 );
105709 
105710  switch( action ){
105711  case OE_Restrict:
105712  pStep->op = TK_SELECT;
105713  break;
105714  case OE_Cascade:
105715  if( !pChanges ){
105716  pStep->op = TK_DELETE;
105717  break;
105718  }
105719  default:
105720  pStep->op = TK_UPDATE;
105721  }
105722  pStep->pTrig = pTrigger;
105723  pTrigger->pSchema = pTab->pSchema;
105724  pTrigger->pTabSchema = pTab->pSchema;
105725  pFKey->apTrigger[iAction] = pTrigger;
105726  pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
105727  }
105728 
105729  return pTrigger;
105730 }
105731 
105732 /*
105733 ** This function is called when deleting or updating a row to implement
105734 ** any required CASCADE, SET NULL or SET DEFAULT actions.
105735 */
105737  Parse *pParse, /* Parse context */
105738  Table *pTab, /* Table being updated or deleted from */
105739  ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
105740  int regOld, /* Address of array containing old row */
105741  int *aChange, /* Array indicating UPDATEd columns (or 0) */
105742  int bChngRowid /* True if rowid is UPDATEd */
105743 ){
105744  /* If foreign-key support is enabled, iterate through all FKs that
105745  ** refer to table pTab. If there is an action associated with the FK
105746  ** for this operation (either update or delete), invoke the associated
105747  ** trigger sub-program. */
105748  if( pParse->db->flags&SQLITE_ForeignKeys ){
105749  FKey *pFKey; /* Iterator variable */
105750  for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
105751  if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
105752  Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
105753  if( pAct ){
105754  sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
105755  }
105756  }
105757  }
105758  }
105759 }
105760 
105761 #endif /* ifndef SQLITE_OMIT_TRIGGER */
105762 
105763 /*
105764 ** Free all memory associated with foreign key definitions attached to
105765 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
105766 ** hash table.
105767 */
105769  FKey *pFKey; /* Iterator variable */
105770  FKey *pNext; /* Copy of pFKey->pNextFrom */
105771 
105772  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
105773  for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
105774 
105775  /* Remove the FK from the fkeyHash hash table. */
105776  if( !db || db->pnBytesFreed==0 ){
105777  if( pFKey->pPrevTo ){
105778  pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
105779  }else{
105780  void *p = (void *)pFKey->pNextTo;
105781  const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
105782  sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
105783  }
105784  if( pFKey->pNextTo ){
105785  pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
105786  }
105787  }
105788 
105789  /* EV: R-30323-21917 Each foreign key constraint in SQLite is
105790  ** classified as either immediate or deferred.
105791  */
105792  assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
105793 
105794  /* Delete any triggers created to implement actions for this FK. */
105795 #ifndef SQLITE_OMIT_TRIGGER
105796  fkTriggerDelete(db, pFKey->apTrigger[0]);
105797  fkTriggerDelete(db, pFKey->apTrigger[1]);
105798 #endif
105799 
105800  pNext = pFKey->pNextFrom;
105801  sqlite3DbFree(db, pFKey);
105802  }
105803 }
105804 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
105805 
105806 /************** End of fkey.c ************************************************/
105807 /************** Begin file insert.c ******************************************/
105808 /*
105809 ** 2001 September 15
105810 **
105811 ** The author disclaims copyright to this source code. In place of
105812 ** a legal notice, here is a blessing:
105813 **
105814 ** May you do good and not evil.
105815 ** May you find forgiveness for yourself and forgive others.
105816 ** May you share freely, never taking more than you give.
105817 **
105818 *************************************************************************
105819 ** This file contains C code routines that are called by the parser
105820 ** to handle INSERT statements in SQLite.
105821 */
105822 /* #include "sqliteInt.h" */
105823 
105824 /*
105825 ** Generate code that will
105826 **
105827 ** (1) acquire a lock for table pTab then
105828 ** (2) open pTab as cursor iCur.
105829 **
105830 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
105831 ** for that table that is actually opened.
105832 */
105834  Parse *pParse, /* Generate code into this VDBE */
105835  int iCur, /* The cursor number of the table */
105836  int iDb, /* The database index in sqlite3.aDb[] */
105837  Table *pTab, /* The table to be opened */
105838  int opcode /* OP_OpenRead or OP_OpenWrite */
105839 ){
105840  Vdbe *v;
105841  assert( !IsVirtual(pTab) );
105842  v = sqlite3GetVdbe(pParse);
105843  assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
105844  sqlite3TableLock(pParse, iDb, pTab->tnum,
105845  (opcode==OP_OpenWrite)?1:0, pTab->zName);
105846  if( HasRowid(pTab) ){
105847  sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
105848  VdbeComment((v, "%s", pTab->zName));
105849  }else{
105850  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
105851  assert( pPk!=0 );
105852  assert( pPk->tnum==pTab->tnum );
105853  sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
105854  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
105855  VdbeComment((v, "%s", pTab->zName));
105856  }
105857 }
105858 
105859 /*
105860 ** Return a pointer to the column affinity string associated with index
105861 ** pIdx. A column affinity string has one character for each column in
105862 ** the table, according to the affinity of the column:
105863 **
105864 ** Character Column affinity
105865 ** ------------------------------
105866 ** 'A' BLOB
105867 ** 'B' TEXT
105868 ** 'C' NUMERIC
105869 ** 'D' INTEGER
105870 ** 'F' REAL
105871 **
105872 ** An extra 'D' is appended to the end of the string to cover the
105873 ** rowid that appears as the last column in every index.
105874 **
105875 ** Memory for the buffer containing the column index affinity string
105876 ** is managed along with the rest of the Index structure. It will be
105877 ** released when sqlite3DeleteIndex() is called.
105878 */
105880  if( !pIdx->zColAff ){
105881  /* The first time a column affinity string for a particular index is
105882  ** required, it is allocated and populated here. It is then stored as
105883  ** a member of the Index structure for subsequent use.
105884  **
105885  ** The column affinity string will eventually be deleted by
105886  ** sqliteDeleteIndex() when the Index structure itself is cleaned
105887  ** up.
105888  */
105889  int n;
105890  Table *pTab = pIdx->pTable;
105891  pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
105892  if( !pIdx->zColAff ){
105893  sqlite3OomFault(db);
105894  return 0;
105895  }
105896  for(n=0; n<pIdx->nColumn; n++){
105897  i16 x = pIdx->aiColumn[n];
105898  if( x>=0 ){
105899  pIdx->zColAff[n] = pTab->aCol[x].affinity;
105900  }else if( x==XN_ROWID ){
105901  pIdx->zColAff[n] = SQLITE_AFF_INTEGER;
105902  }else{
105903  char aff;
105904  assert( x==XN_EXPR );
105905  assert( pIdx->aColExpr!=0 );
105906  aff = sqlite3ExprAffinity(pIdx->aColExpr->a[n].pExpr);
105907  if( aff==0 ) aff = SQLITE_AFF_BLOB;
105908  pIdx->zColAff[n] = aff;
105909  }
105910  }
105911  pIdx->zColAff[n] = 0;
105912  }
105913 
105914  return pIdx->zColAff;
105915 }
105916 
105917 /*
105918 ** Compute the affinity string for table pTab, if it has not already been
105919 ** computed. As an optimization, omit trailing SQLITE_AFF_BLOB affinities.
105920 **
105921 ** If the affinity exists (if it is no entirely SQLITE_AFF_BLOB values) and
105922 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
105923 ** for register iReg and following. Or if affinities exists and iReg==0,
105924 ** then just set the P4 operand of the previous opcode (which should be
105925 ** an OP_MakeRecord) to the affinity string.
105926 **
105927 ** A column affinity string has one character per column:
105928 **
105929 ** Character Column affinity
105930 ** ------------------------------
105931 ** 'A' BLOB
105932 ** 'B' TEXT
105933 ** 'C' NUMERIC
105934 ** 'D' INTEGER
105935 ** 'E' REAL
105936 */
105938  int i;
105939  char *zColAff = pTab->zColAff;
105940  if( zColAff==0 ){
105941  sqlite3 *db = sqlite3VdbeDb(v);
105942  zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
105943  if( !zColAff ){
105944  sqlite3OomFault(db);
105945  return;
105946  }
105947 
105948  for(i=0; i<pTab->nCol; i++){
105949  zColAff[i] = pTab->aCol[i].affinity;
105950  }
105951  do{
105952  zColAff[i--] = 0;
105953  }while( i>=0 && zColAff[i]==SQLITE_AFF_BLOB );
105954  pTab->zColAff = zColAff;
105955  }
105956  i = sqlite3Strlen30(zColAff);
105957  if( i ){
105958  if( iReg ){
105959  sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
105960  }else{
105961  sqlite3VdbeChangeP4(v, -1, zColAff, i);
105962  }
105963  }
105964 }
105965 
105966 /*
105967 ** Return non-zero if the table pTab in database iDb or any of its indices
105968 ** have been opened at any point in the VDBE program. This is used to see if
105969 ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
105970 ** run without using a temporary table for the results of the SELECT.
105971 */
105972 static int readsTable(Parse *p, int iDb, Table *pTab){
105973  Vdbe *v = sqlite3GetVdbe(p);
105974  int i;
105975  int iEnd = sqlite3VdbeCurrentAddr(v);
105976 #ifndef SQLITE_OMIT_VIRTUALTABLE
105977  VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
105978 #endif
105979 
105980  for(i=1; i<iEnd; i++){
105981  VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
105982  assert( pOp!=0 );
105983  if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
105984  Index *pIndex;
105985  int tnum = pOp->p2;
105986  if( tnum==pTab->tnum ){
105987  return 1;
105988  }
105989  for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
105990  if( tnum==pIndex->tnum ){
105991  return 1;
105992  }
105993  }
105994  }
105995 #ifndef SQLITE_OMIT_VIRTUALTABLE
105996  if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
105997  assert( pOp->p4.pVtab!=0 );
105998  assert( pOp->p4type==P4_VTAB );
105999  return 1;
106000  }
106001 #endif
106002  }
106003  return 0;
106004 }
106005 
106006 #ifndef SQLITE_OMIT_AUTOINCREMENT
106007 /*
106008 ** Locate or create an AutoincInfo structure associated with table pTab
106009 ** which is in database iDb. Return the register number for the register
106010 ** that holds the maximum rowid.
106011 **
106012 ** There is at most one AutoincInfo structure per table even if the
106013 ** same table is autoincremented multiple times due to inserts within
106014 ** triggers. A new AutoincInfo structure is created if this is the
106015 ** first use of table pTab. On 2nd and subsequent uses, the original
106016 ** AutoincInfo structure is used.
106017 **
106018 ** Three memory locations are allocated:
106019 **
106020 ** (1) Register to hold the name of the pTab table.
106021 ** (2) Register to hold the maximum ROWID of pTab.
106022 ** (3) Register to hold the rowid in sqlite_sequence of pTab
106023 **
106024 ** The 2nd register is the one that is returned. That is all the
106025 ** insert routine needs to know about.
106026 */
106027 static int autoIncBegin(
106028  Parse *pParse, /* Parsing context */
106029  int iDb, /* Index of the database holding pTab */
106030  Table *pTab /* The table we are writing to */
106031 ){
106032  int memId = 0; /* Register holding maximum rowid */
106033  if( pTab->tabFlags & TF_Autoincrement ){
106034  Parse *pToplevel = sqlite3ParseToplevel(pParse);
106035  AutoincInfo *pInfo;
106036 
106037  pInfo = pToplevel->pAinc;
106038  while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
106039  if( pInfo==0 ){
106040  pInfo = sqlite3DbMallocRawNN(pParse->db, sizeof(*pInfo));
106041  if( pInfo==0 ) return 0;
106042  pInfo->pNext = pToplevel->pAinc;
106043  pToplevel->pAinc = pInfo;
106044  pInfo->pTab = pTab;
106045  pInfo->iDb = iDb;
106046  pToplevel->nMem++; /* Register to hold name of table */
106047  pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
106048  pToplevel->nMem++; /* Rowid in sqlite_sequence */
106049  }
106050  memId = pInfo->regCtr;
106051  }
106052  return memId;
106053 }
106054 
106055 /*
106056 ** This routine generates code that will initialize all of the
106057 ** register used by the autoincrement tracker.
106058 */
106060  AutoincInfo *p; /* Information about an AUTOINCREMENT */
106061  sqlite3 *db = pParse->db; /* The database connection */
106062  Db *pDb; /* Database only autoinc table */
106063  int memId; /* Register holding max rowid */
106064  Vdbe *v = pParse->pVdbe; /* VDBE under construction */
106065 
106066  /* This routine is never called during trigger-generation. It is
106067  ** only called from the top-level */
106068  assert( pParse->pTriggerTab==0 );
106069  assert( sqlite3IsToplevel(pParse) );
106070 
106071  assert( v ); /* We failed long ago if this is not so */
106072  for(p = pParse->pAinc; p; p = p->pNext){
106073  static const int iLn = VDBE_OFFSET_LINENO(2);
106074  static const VdbeOpList autoInc[] = {
106075  /* 0 */ {OP_Null, 0, 0, 0},
106076  /* 1 */ {OP_Rewind, 0, 9, 0},
106077  /* 2 */ {OP_Column, 0, 0, 0},
106078  /* 3 */ {OP_Ne, 0, 7, 0},
106079  /* 4 */ {OP_Rowid, 0, 0, 0},
106080  /* 5 */ {OP_Column, 0, 1, 0},
106081  /* 6 */ {OP_Goto, 0, 9, 0},
106082  /* 7 */ {OP_Next, 0, 2, 0},
106083  /* 8 */ {OP_Integer, 0, 0, 0},
106084  /* 9 */ {OP_Close, 0, 0, 0}
106085  };
106086  VdbeOp *aOp;
106087  pDb = &db->aDb[p->iDb];
106088  memId = p->regCtr;
106089  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106090  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
106091  sqlite3VdbeLoadString(v, memId-1, p->pTab->zName);
106092  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoInc), autoInc, iLn);
106093  if( aOp==0 ) break;
106094  aOp[0].p2 = memId;
106095  aOp[0].p3 = memId+1;
106096  aOp[2].p3 = memId;
106097  aOp[3].p1 = memId-1;
106098  aOp[3].p3 = memId;
106099  aOp[3].p5 = SQLITE_JUMPIFNULL;
106100  aOp[4].p2 = memId+1;
106101  aOp[5].p3 = memId;
106102  aOp[8].p2 = memId;
106103  }
106104 }
106105 
106106 /*
106107 ** Update the maximum rowid for an autoincrement calculation.
106108 **
106109 ** This routine should be called when the regRowid register holds a
106110 ** new rowid that is about to be inserted. If that new rowid is
106111 ** larger than the maximum rowid in the memId memory cell, then the
106112 ** memory cell is updated.
106113 */
106114 static void autoIncStep(Parse *pParse, int memId, int regRowid){
106115  if( memId>0 ){
106116  sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
106117  }
106118 }
106119 
106120 /*
106121 ** This routine generates the code needed to write autoincrement
106122 ** maximum rowid values back into the sqlite_sequence register.
106123 ** Every statement that might do an INSERT into an autoincrement
106124 ** table (either directly or through triggers) needs to call this
106125 ** routine just before the "exit" code.
106126 */
106128  AutoincInfo *p;
106129  Vdbe *v = pParse->pVdbe;
106130  sqlite3 *db = pParse->db;
106131 
106132  assert( v );
106133  for(p = pParse->pAinc; p; p = p->pNext){
106134  static const int iLn = VDBE_OFFSET_LINENO(2);
106135  static const VdbeOpList autoIncEnd[] = {
106136  /* 0 */ {OP_NotNull, 0, 2, 0},
106137  /* 1 */ {OP_NewRowid, 0, 0, 0},
106138  /* 2 */ {OP_MakeRecord, 0, 2, 0},
106139  /* 3 */ {OP_Insert, 0, 0, 0},
106140  /* 4 */ {OP_Close, 0, 0, 0}
106141  };
106142  VdbeOp *aOp;
106143  Db *pDb = &db->aDb[p->iDb];
106144  int iRec;
106145  int memId = p->regCtr;
106146 
106147  iRec = sqlite3GetTempReg(pParse);
106148  assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
106149  sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
106150  aOp = sqlite3VdbeAddOpList(v, ArraySize(autoIncEnd), autoIncEnd, iLn);
106151  if( aOp==0 ) break;
106152  aOp[0].p1 = memId+1;
106153  aOp[1].p2 = memId+1;
106154  aOp[2].p1 = memId-1;
106155  aOp[2].p3 = iRec;
106156  aOp[3].p2 = iRec;
106157  aOp[3].p3 = memId+1;
106158  aOp[3].p5 = OPFLAG_APPEND;
106159  sqlite3ReleaseTempReg(pParse, iRec);
106160  }
106161 }
106163  if( pParse->pAinc ) autoIncrementEnd(pParse);
106164 }
106165 #else
106166 /*
106167 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
106168 ** above are all no-ops
106169 */
106170 # define autoIncBegin(A,B,C) (0)
106171 # define autoIncStep(A,B,C)
106172 #endif /* SQLITE_OMIT_AUTOINCREMENT */
106173 
106174 
106175 /* Forward declaration */
106176 static int xferOptimization(
106177  Parse *pParse, /* Parser context */
106178  Table *pDest, /* The table we are inserting into */
106179  Select *pSelect, /* A SELECT statement to use as the data source */
106180  int onError, /* How to handle constraint errors */
106181  int iDbDest /* The database of pDest */
106182 );
106183 
106184 /*
106185 ** This routine is called to handle SQL of the following forms:
106186 **
106187 ** insert into TABLE (IDLIST) values(EXPRLIST),(EXPRLIST),...
106188 ** insert into TABLE (IDLIST) select
106189 ** insert into TABLE (IDLIST) default values
106190 **
106191 ** The IDLIST following the table name is always optional. If omitted,
106192 ** then a list of all (non-hidden) columns for the table is substituted.
106193 ** The IDLIST appears in the pColumn parameter. pColumn is NULL if IDLIST
106194 ** is omitted.
106195 **
106196 ** For the pSelect parameter holds the values to be inserted for the
106197 ** first two forms shown above. A VALUES clause is really just short-hand
106198 ** for a SELECT statement that omits the FROM clause and everything else
106199 ** that follows. If the pSelect parameter is NULL, that means that the
106200 ** DEFAULT VALUES form of the INSERT statement is intended.
106201 **
106202 ** The code generated follows one of four templates. For a simple
106203 ** insert with data coming from a single-row VALUES clause, the code executes
106204 ** once straight down through. Pseudo-code follows (we call this
106205 ** the "1st template"):
106206 **
106207 ** open write cursor to <table> and its indices
106208 ** put VALUES clause expressions into registers
106209 ** write the resulting record into <table>
106210 ** cleanup
106211 **
106212 ** The three remaining templates assume the statement is of the form
106213 **
106214 ** INSERT INTO <table> SELECT ...
106215 **
106216 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
106217 ** in other words if the SELECT pulls all columns from a single table
106218 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
106219 ** if <table2> and <table1> are distinct tables but have identical
106220 ** schemas, including all the same indices, then a special optimization
106221 ** is invoked that copies raw records from <table2> over to <table1>.
106222 ** See the xferOptimization() function for the implementation of this
106223 ** template. This is the 2nd template.
106224 **
106225 ** open a write cursor to <table>
106226 ** open read cursor on <table2>
106227 ** transfer all records in <table2> over to <table>
106228 ** close cursors
106229 ** foreach index on <table>
106230 ** open a write cursor on the <table> index
106231 ** open a read cursor on the corresponding <table2> index
106232 ** transfer all records from the read to the write cursors
106233 ** close cursors
106234 ** end foreach
106235 **
106236 ** The 3rd template is for when the second template does not apply
106237 ** and the SELECT clause does not read from <table> at any time.
106238 ** The generated code follows this template:
106239 **
106240 ** X <- A
106241 ** goto B
106242 ** A: setup for the SELECT
106243 ** loop over the rows in the SELECT
106244 ** load values into registers R..R+n
106245 ** yield X
106246 ** end loop
106247 ** cleanup after the SELECT
106248 ** end-coroutine X
106249 ** B: open write cursor to <table> and its indices
106250 ** C: yield X, at EOF goto D
106251 ** insert the select result into <table> from R..R+n
106252 ** goto C
106253 ** D: cleanup
106254 **
106255 ** The 4th template is used if the insert statement takes its
106256 ** values from a SELECT but the data is being inserted into a table
106257 ** that is also read as part of the SELECT. In the third form,
106258 ** we have to use an intermediate table to store the results of
106259 ** the select. The template is like this:
106260 **
106261 ** X <- A
106262 ** goto B
106263 ** A: setup for the SELECT
106264 ** loop over the tables in the SELECT
106265 ** load value into register R..R+n
106266 ** yield X
106267 ** end loop
106268 ** cleanup after the SELECT
106269 ** end co-routine R
106270 ** B: open temp table
106271 ** L: yield X, at EOF goto M
106272 ** insert row from R..R+n into temp table
106273 ** goto L
106274 ** M: open write cursor to <table> and its indices
106275 ** rewind temp table
106276 ** C: loop over rows of intermediate table
106277 ** transfer values form intermediate table into <table>
106278 ** end loop
106279 ** D: cleanup
106280 */
106282  Parse *pParse, /* Parser context */
106283  SrcList *pTabList, /* Name of table into which we are inserting */
106284  Select *pSelect, /* A SELECT statement to use as the data source */
106285  IdList *pColumn, /* Column names corresponding to IDLIST. */
106286  int onError /* How to handle constraint errors */
106287 ){
106288  sqlite3 *db; /* The main database structure */
106289  Table *pTab; /* The table to insert into. aka TABLE */
106290  char *zTab; /* Name of the table into which we are inserting */
106291  const char *zDb; /* Name of the database holding this table */
106292  int i, j, idx; /* Loop counters */
106293  Vdbe *v; /* Generate code into this virtual machine */
106294  Index *pIdx; /* For looping over indices of the table */
106295  int nColumn; /* Number of columns in the data */
106296  int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
106297  int iDataCur = 0; /* VDBE cursor that is the main data repository */
106298  int iIdxCur = 0; /* First index cursor */
106299  int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
106300  int endOfLoop; /* Label for the end of the insertion loop */
106301  int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
106302  int addrInsTop = 0; /* Jump to label "D" */
106303  int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
106304  SelectDest dest; /* Destination for SELECT on rhs of INSERT */
106305  int iDb; /* Index of database holding TABLE */
106306  Db *pDb; /* The database containing table being inserted into */
106307  u8 useTempTable = 0; /* Store SELECT results in intermediate table */
106308  u8 appendFlag = 0; /* True if the insert is likely to be an append */
106309  u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
106310  u8 bIdListInOrder; /* True if IDLIST is in table order */
106311  ExprList *pList = 0; /* List of VALUES() to be inserted */
106312 
106313  /* Register allocations */
106314  int regFromSelect = 0;/* Base register for data coming from SELECT */
106315  int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
106316  int regRowCount = 0; /* Memory cell used for the row counter */
106317  int regIns; /* Block of regs holding rowid+data being inserted */
106318  int regRowid; /* registers holding insert rowid */
106319  int regData; /* register holding first column to insert */
106320  int *aRegIdx = 0; /* One register allocated to each index */
106321 
106322 #ifndef SQLITE_OMIT_TRIGGER
106323  int isView; /* True if attempting to insert into a view */
106324  Trigger *pTrigger; /* List of triggers on pTab, if required */
106325  int tmask; /* Mask of trigger times */
106326 #endif
106327 
106328  db = pParse->db;
106329  memset(&dest, 0, sizeof(dest));
106330  if( pParse->nErr || db->mallocFailed ){
106331  goto insert_cleanup;
106332  }
106333 
106334  /* If the Select object is really just a simple VALUES() list with a
106335  ** single row (the common case) then keep that one row of values
106336  ** and discard the other (unused) parts of the pSelect object
106337  */
106338  if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
106339  pList = pSelect->pEList;
106340  pSelect->pEList = 0;
106341  sqlite3SelectDelete(db, pSelect);
106342  pSelect = 0;
106343  }
106344 
106345  /* Locate the table into which we will be inserting new information.
106346  */
106347  assert( pTabList->nSrc==1 );
106348  zTab = pTabList->a[0].zName;
106349  if( NEVER(zTab==0) ) goto insert_cleanup;
106350  pTab = sqlite3SrcListLookup(pParse, pTabList);
106351  if( pTab==0 ){
106352  goto insert_cleanup;
106353  }
106354  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
106355  assert( iDb<db->nDb );
106356  pDb = &db->aDb[iDb];
106357  zDb = pDb->zName;
106358  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
106359  goto insert_cleanup;
106360  }
106361  withoutRowid = !HasRowid(pTab);
106362 
106363  /* Figure out if we have any triggers and if the table being
106364  ** inserted into is a view
106365  */
106366 #ifndef SQLITE_OMIT_TRIGGER
106367  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
106368  isView = pTab->pSelect!=0;
106369 #else
106370 # define pTrigger 0
106371 # define tmask 0
106372 # define isView 0
106373 #endif
106374 #ifdef SQLITE_OMIT_VIEW
106375 # undef isView
106376 # define isView 0
106377 #endif
106378  assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
106379 
106380  /* If pTab is really a view, make sure it has been initialized.
106381  ** ViewGetColumnNames() is a no-op if pTab is not a view.
106382  */
106383  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
106384  goto insert_cleanup;
106385  }
106386 
106387  /* Cannot insert into a read-only table.
106388  */
106389  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
106390  goto insert_cleanup;
106391  }
106392 
106393  /* Allocate a VDBE
106394  */
106395  v = sqlite3GetVdbe(pParse);
106396  if( v==0 ) goto insert_cleanup;
106397  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
106398  sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
106399 
106400 #ifndef SQLITE_OMIT_XFER_OPT
106401  /* If the statement is of the form
106402  **
106403  ** INSERT INTO <table1> SELECT * FROM <table2>;
106404  **
106405  ** Then special optimizations can be applied that make the transfer
106406  ** very fast and which reduce fragmentation of indices.
106407  **
106408  ** This is the 2nd template.
106409  */
106410  if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
106411  assert( !pTrigger );
106412  assert( pList==0 );
106413  goto insert_end;
106414  }
106415 #endif /* SQLITE_OMIT_XFER_OPT */
106416 
106417  /* If this is an AUTOINCREMENT table, look up the sequence number in the
106418  ** sqlite_sequence table and store it in memory cell regAutoinc.
106419  */
106420  regAutoinc = autoIncBegin(pParse, iDb, pTab);
106421 
106422  /* Allocate registers for holding the rowid of the new row,
106423  ** the content of the new row, and the assembled row record.
106424  */
106425  regRowid = regIns = pParse->nMem+1;
106426  pParse->nMem += pTab->nCol + 1;
106427  if( IsVirtual(pTab) ){
106428  regRowid++;
106429  pParse->nMem++;
106430  }
106431  regData = regRowid+1;
106432 
106433  /* If the INSERT statement included an IDLIST term, then make sure
106434  ** all elements of the IDLIST really are columns of the table and
106435  ** remember the column indices.
106436  **
106437  ** If the table has an INTEGER PRIMARY KEY column and that column
106438  ** is named in the IDLIST, then record in the ipkColumn variable
106439  ** the index into IDLIST of the primary key column. ipkColumn is
106440  ** the index of the primary key as it appears in IDLIST, not as
106441  ** is appears in the original table. (The index of the INTEGER
106442  ** PRIMARY KEY in the original table is pTab->iPKey.)
106443  */
106444  bIdListInOrder = (pTab->tabFlags & TF_OOOHidden)==0;
106445  if( pColumn ){
106446  for(i=0; i<pColumn->nId; i++){
106447  pColumn->a[i].idx = -1;
106448  }
106449  for(i=0; i<pColumn->nId; i++){
106450  for(j=0; j<pTab->nCol; j++){
106451  if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
106452  pColumn->a[i].idx = j;
106453  if( i!=j ) bIdListInOrder = 0;
106454  if( j==pTab->iPKey ){
106455  ipkColumn = i; assert( !withoutRowid );
106456  }
106457  break;
106458  }
106459  }
106460  if( j>=pTab->nCol ){
106461  if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
106462  ipkColumn = i;
106463  bIdListInOrder = 0;
106464  }else{
106465  sqlite3ErrorMsg(pParse, "table %S has no column named %s",
106466  pTabList, 0, pColumn->a[i].zName);
106467  pParse->checkSchema = 1;
106468  goto insert_cleanup;
106469  }
106470  }
106471  }
106472  }
106473 
106474  /* Figure out how many columns of data are supplied. If the data
106475  ** is coming from a SELECT statement, then generate a co-routine that
106476  ** produces a single row of the SELECT on each invocation. The
106477  ** co-routine is the common header to the 3rd and 4th templates.
106478  */
106479  if( pSelect ){
106480  /* Data is coming from a SELECT or from a multi-row VALUES clause.
106481  ** Generate a co-routine to run the SELECT. */
106482  int regYield; /* Register holding co-routine entry-point */
106483  int addrTop; /* Top of the co-routine */
106484  int rc; /* Result code */
106485 
106486  regYield = ++pParse->nMem;
106487  addrTop = sqlite3VdbeCurrentAddr(v) + 1;
106488  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
106489  sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
106490  dest.iSdst = bIdListInOrder ? regData : 0;
106491  dest.nSdst = pTab->nCol;
106492  rc = sqlite3Select(pParse, pSelect, &dest);
106493  regFromSelect = dest.iSdst;
106494  if( rc || db->mallocFailed || pParse->nErr ) goto insert_cleanup;
106495  sqlite3VdbeEndCoroutine(v, regYield);
106496  sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
106497  assert( pSelect->pEList );
106498  nColumn = pSelect->pEList->nExpr;
106499 
106500  /* Set useTempTable to TRUE if the result of the SELECT statement
106501  ** should be written into a temporary table (template 4). Set to
106502  ** FALSE if each output row of the SELECT can be written directly into
106503  ** the destination table (template 3).
106504  **
106505  ** A temp table must be used if the table being updated is also one
106506  ** of the tables being read by the SELECT statement. Also use a
106507  ** temp table in the case of row triggers.
106508  */
106509  if( pTrigger || readsTable(pParse, iDb, pTab) ){
106510  useTempTable = 1;
106511  }
106512 
106513  if( useTempTable ){
106514  /* Invoke the coroutine to extract information from the SELECT
106515  ** and add it to a transient table srcTab. The code generated
106516  ** here is from the 4th template:
106517  **
106518  ** B: open temp table
106519  ** L: yield X, goto M at EOF
106520  ** insert row from R..R+n into temp table
106521  ** goto L
106522  ** M: ...
106523  */
106524  int regRec; /* Register to hold packed record */
106525  int regTempRowid; /* Register to hold temp table ROWID */
106526  int addrL; /* Label "L" */
106527 
106528  srcTab = pParse->nTab++;
106529  regRec = sqlite3GetTempReg(pParse);
106530  regTempRowid = sqlite3GetTempReg(pParse);
106531  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
106532  addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
106533  sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
106534  sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
106535  sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
106536  sqlite3VdbeGoto(v, addrL);
106537  sqlite3VdbeJumpHere(v, addrL);
106538  sqlite3ReleaseTempReg(pParse, regRec);
106539  sqlite3ReleaseTempReg(pParse, regTempRowid);
106540  }
106541  }else{
106542  /* This is the case if the data for the INSERT is coming from a
106543  ** single-row VALUES clause
106544  */
106545  NameContext sNC;
106546  memset(&sNC, 0, sizeof(sNC));
106547  sNC.pParse = pParse;
106548  srcTab = -1;
106549  assert( useTempTable==0 );
106550  if( pList ){
106551  nColumn = pList->nExpr;
106552  if( sqlite3ResolveExprListNames(&sNC, pList) ){
106553  goto insert_cleanup;
106554  }
106555  }else{
106556  nColumn = 0;
106557  }
106558  }
106559 
106560  /* If there is no IDLIST term but the table has an integer primary
106561  ** key, the set the ipkColumn variable to the integer primary key
106562  ** column index in the original table definition.
106563  */
106564  if( pColumn==0 && nColumn>0 ){
106565  ipkColumn = pTab->iPKey;
106566  }
106567 
106568  /* Make sure the number of columns in the source data matches the number
106569  ** of columns to be inserted into the table.
106570  */
106571  for(i=0; i<pTab->nCol; i++){
106572  nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
106573  }
106574  if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
106575  sqlite3ErrorMsg(pParse,
106576  "table %S has %d columns but %d values were supplied",
106577  pTabList, 0, pTab->nCol-nHidden, nColumn);
106578  goto insert_cleanup;
106579  }
106580  if( pColumn!=0 && nColumn!=pColumn->nId ){
106581  sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
106582  goto insert_cleanup;
106583  }
106584 
106585  /* Initialize the count of rows to be inserted
106586  */
106587  if( db->flags & SQLITE_CountRows ){
106588  regRowCount = ++pParse->nMem;
106589  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
106590  }
106591 
106592  /* If this is not a view, open the table and and all indices */
106593  if( !isView ){
106594  int nIdx;
106595  nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, -1, 0,
106596  &iDataCur, &iIdxCur);
106597  aRegIdx = sqlite3DbMallocRawNN(db, sizeof(int)*(nIdx+1));
106598  if( aRegIdx==0 ){
106599  goto insert_cleanup;
106600  }
106601  for(i=0; i<nIdx; i++){
106602  aRegIdx[i] = ++pParse->nMem;
106603  }
106604  }
106605 
106606  /* This is the top of the main insertion loop */
106607  if( useTempTable ){
106608  /* This block codes the top of loop only. The complete loop is the
106609  ** following pseudocode (template 4):
106610  **
106611  ** rewind temp table, if empty goto D
106612  ** C: loop over rows of intermediate table
106613  ** transfer values form intermediate table into <table>
106614  ** end loop
106615  ** D: ...
106616  */
106617  addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
106618  addrCont = sqlite3VdbeCurrentAddr(v);
106619  }else if( pSelect ){
106620  /* This block codes the top of loop only. The complete loop is the
106621  ** following pseudocode (template 3):
106622  **
106623  ** C: yield X, at EOF goto D
106624  ** insert the select result into <table> from R..R+n
106625  ** goto C
106626  ** D: ...
106627  */
106628  addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
106629  VdbeCoverage(v);
106630  }
106631 
106632  /* Run the BEFORE and INSTEAD OF triggers, if there are any
106633  */
106634  endOfLoop = sqlite3VdbeMakeLabel(v);
106635  if( tmask & TRIGGER_BEFORE ){
106636  int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
106637 
106638  /* build the NEW.* reference row. Note that if there is an INTEGER
106639  ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
106640  ** translated into a unique ID for the row. But on a BEFORE trigger,
106641  ** we do not know what the unique ID will be (because the insert has
106642  ** not happened yet) so we substitute a rowid of -1
106643  */
106644  if( ipkColumn<0 ){
106645  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
106646  }else{
106647  int addr1;
106648  assert( !withoutRowid );
106649  if( useTempTable ){
106650  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
106651  }else{
106652  assert( pSelect==0 ); /* Otherwise useTempTable is true */
106653  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
106654  }
106655  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
106656  sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
106657  sqlite3VdbeJumpHere(v, addr1);
106658  sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
106659  }
106660 
106661  /* Cannot have triggers on a virtual table. If it were possible,
106662  ** this block would have to account for hidden column.
106663  */
106664  assert( !IsVirtual(pTab) );
106665 
106666  /* Create the new column data
106667  */
106668  for(i=j=0; i<pTab->nCol; i++){
106669  if( pColumn ){
106670  for(j=0; j<pColumn->nId; j++){
106671  if( pColumn->a[j].idx==i ) break;
106672  }
106673  }
106674  if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId)
106675  || (pColumn==0 && IsOrdinaryHiddenColumn(&pTab->aCol[i])) ){
106676  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
106677  }else if( useTempTable ){
106678  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
106679  }else{
106680  assert( pSelect==0 ); /* Otherwise useTempTable is true */
106681  sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
106682  }
106683  if( pColumn==0 && !IsOrdinaryHiddenColumn(&pTab->aCol[i]) ) j++;
106684  }
106685 
106686  /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
106687  ** do not attempt any conversions before assembling the record.
106688  ** If this is a real table, attempt conversions as required by the
106689  ** table column affinities.
106690  */
106691  if( !isView ){
106692  sqlite3TableAffinity(v, pTab, regCols+1);
106693  }
106694 
106695  /* Fire BEFORE or INSTEAD OF triggers */
106696  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
106697  pTab, regCols-pTab->nCol-1, onError, endOfLoop);
106698 
106699  sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
106700  }
106701 
106702  /* Compute the content of the next row to insert into a range of
106703  ** registers beginning at regIns.
106704  */
106705  if( !isView ){
106706  if( IsVirtual(pTab) ){
106707  /* The row that the VUpdate opcode will delete: none */
106708  sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
106709  }
106710  if( ipkColumn>=0 ){
106711  if( useTempTable ){
106712  sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
106713  }else if( pSelect ){
106714  sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
106715  }else{
106716  VdbeOp *pOp;
106717  sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
106718  pOp = sqlite3VdbeGetOp(v, -1);
106719  if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
106720  appendFlag = 1;
106721  pOp->opcode = OP_NewRowid;
106722  pOp->p1 = iDataCur;
106723  pOp->p2 = regRowid;
106724  pOp->p3 = regAutoinc;
106725  }
106726  }
106727  /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
106728  ** to generate a unique primary key value.
106729  */
106730  if( !appendFlag ){
106731  int addr1;
106732  if( !IsVirtual(pTab) ){
106733  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
106734  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
106735  sqlite3VdbeJumpHere(v, addr1);
106736  }else{
106737  addr1 = sqlite3VdbeCurrentAddr(v);
106738  sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, addr1+2); VdbeCoverage(v);
106739  }
106740  sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
106741  }
106742  }else if( IsVirtual(pTab) || withoutRowid ){
106743  sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
106744  }else{
106745  sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
106746  appendFlag = 1;
106747  }
106748  autoIncStep(pParse, regAutoinc, regRowid);
106749 
106750  /* Compute data for all columns of the new entry, beginning
106751  ** with the first column.
106752  */
106753  nHidden = 0;
106754  for(i=0; i<pTab->nCol; i++){
106755  int iRegStore = regRowid+1+i;
106756  if( i==pTab->iPKey ){
106757  /* The value of the INTEGER PRIMARY KEY column is always a NULL.
106758  ** Whenever this column is read, the rowid will be substituted
106759  ** in its place. Hence, fill this column with a NULL to avoid
106760  ** taking up data space with information that will never be used.
106761  ** As there may be shallow copies of this value, make it a soft-NULL */
106762  sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
106763  continue;
106764  }
106765  if( pColumn==0 ){
106766  if( IsHiddenColumn(&pTab->aCol[i]) ){
106767  j = -1;
106768  nHidden++;
106769  }else{
106770  j = i - nHidden;
106771  }
106772  }else{
106773  for(j=0; j<pColumn->nId; j++){
106774  if( pColumn->a[j].idx==i ) break;
106775  }
106776  }
106777  if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
106778  sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
106779  }else if( useTempTable ){
106780  sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
106781  }else if( pSelect ){
106782  if( regFromSelect!=regData ){
106783  sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
106784  }
106785  }else{
106786  sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
106787  }
106788  }
106789 
106790  /* Generate code to check constraints and generate index keys and
106791  ** do the insertion.
106792  */
106793 #ifndef SQLITE_OMIT_VIRTUALTABLE
106794  if( IsVirtual(pTab) ){
106795  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
106796  sqlite3VtabMakeWritable(pParse, pTab);
106797  sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
106798  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
106799  sqlite3MayAbort(pParse);
106800  }else
106801 #endif
106802  {
106803  int isReplace; /* Set to true if constraints may cause a replace */
106804  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
106805  regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace, 0
106806  );
106807  sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
106808  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
106809  regIns, aRegIdx, 0, appendFlag, isReplace==0);
106810  }
106811  }
106812 
106813  /* Update the count of rows that are inserted
106814  */
106815  if( (db->flags & SQLITE_CountRows)!=0 ){
106816  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
106817  }
106818 
106819  if( pTrigger ){
106820  /* Code AFTER triggers */
106821  sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
106822  pTab, regData-2-pTab->nCol, onError, endOfLoop);
106823  }
106824 
106825  /* The bottom of the main insertion loop, if the data source
106826  ** is a SELECT statement.
106827  */
106828  sqlite3VdbeResolveLabel(v, endOfLoop);
106829  if( useTempTable ){
106830  sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
106831  sqlite3VdbeJumpHere(v, addrInsTop);
106832  sqlite3VdbeAddOp1(v, OP_Close, srcTab);
106833  }else if( pSelect ){
106834  sqlite3VdbeGoto(v, addrCont);
106835  sqlite3VdbeJumpHere(v, addrInsTop);
106836  }
106837 
106838  if( !IsVirtual(pTab) && !isView ){
106839  /* Close all tables opened */
106840  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
106841  for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
106842  sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
106843  }
106844  }
106845 
106846 insert_end:
106847  /* Update the sqlite_sequence table by storing the content of the
106848  ** maximum rowid counter values recorded while inserting into
106849  ** autoincrement tables.
106850  */
106851  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
106852  sqlite3AutoincrementEnd(pParse);
106853  }
106854 
106855  /*
106856  ** Return the number of rows inserted. If this routine is
106857  ** generating code because of a call to sqlite3NestedParse(), do not
106858  ** invoke the callback function.
106859  */
106860  if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
106861  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
106862  sqlite3VdbeSetNumCols(v, 1);
106863  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
106864  }
106865 
106866 insert_cleanup:
106867  sqlite3SrcListDelete(db, pTabList);
106868  sqlite3ExprListDelete(db, pList);
106869  sqlite3SelectDelete(db, pSelect);
106870  sqlite3IdListDelete(db, pColumn);
106871  sqlite3DbFree(db, aRegIdx);
106872 }
106873 
106874 /* Make sure "isView" and other macros defined above are undefined. Otherwise
106875 ** they may interfere with compilation of other functions in this file
106876 ** (or in another file, if this file becomes part of the amalgamation). */
106877 #ifdef isView
106878  #undef isView
106879 #endif
106880 #ifdef pTrigger
106881  #undef pTrigger
106882 #endif
106883 #ifdef tmask
106884  #undef tmask
106885 #endif
106886 
106887 /*
106888 ** Meanings of bits in of pWalker->eCode for checkConstraintUnchanged()
106889 */
106890 #define CKCNSTRNT_COLUMN 0x01 /* CHECK constraint uses a changing column */
106891 #define CKCNSTRNT_ROWID 0x02 /* CHECK constraint references the ROWID */
106892 
106893 /* This is the Walker callback from checkConstraintUnchanged(). Set
106894 ** bit 0x01 of pWalker->eCode if
106895 ** pWalker->eCode to 0 if this expression node references any of the
106896 ** columns that are being modifed by an UPDATE statement.
106897 */
106898 static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr){
106899  if( pExpr->op==TK_COLUMN ){
106900  assert( pExpr->iColumn>=0 || pExpr->iColumn==-1 );
106901  if( pExpr->iColumn>=0 ){
106902  if( pWalker->u.aiCol[pExpr->iColumn]>=0 ){
106903  pWalker->eCode |= CKCNSTRNT_COLUMN;
106904  }
106905  }else{
106906  pWalker->eCode |= CKCNSTRNT_ROWID;
106907  }
106908  }
106909  return WRC_Continue;
106910 }
106911 
106912 /*
106913 ** pExpr is a CHECK constraint on a row that is being UPDATE-ed. The
106914 ** only columns that are modified by the UPDATE are those for which
106915 ** aiChng[i]>=0, and also the ROWID is modified if chngRowid is true.
106916 **
106917 ** Return true if CHECK constraint pExpr does not use any of the
106918 ** changing columns (or the rowid if it is changing). In other words,
106919 ** return true if this CHECK constraint can be skipped when validating
106920 ** the new row in the UPDATE statement.
106921 */
106922 static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid){
106923  Walker w;
106924  memset(&w, 0, sizeof(w));
106925  w.eCode = 0;
106927  w.u.aiCol = aiChng;
106928  sqlite3WalkExpr(&w, pExpr);
106929  if( !chngRowid ){
106930  testcase( (w.eCode & CKCNSTRNT_ROWID)!=0 );
106931  w.eCode &= ~CKCNSTRNT_ROWID;
106932  }
106933  testcase( w.eCode==0 );
106937  return !w.eCode;
106938 }
106939 
106940 /*
106941 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
106942 ** on table pTab.
106943 **
106944 ** The regNewData parameter is the first register in a range that contains
106945 ** the data to be inserted or the data after the update. There will be
106946 ** pTab->nCol+1 registers in this range. The first register (the one
106947 ** that regNewData points to) will contain the new rowid, or NULL in the
106948 ** case of a WITHOUT ROWID table. The second register in the range will
106949 ** contain the content of the first table column. The third register will
106950 ** contain the content of the second table column. And so forth.
106951 **
106952 ** The regOldData parameter is similar to regNewData except that it contains
106953 ** the data prior to an UPDATE rather than afterwards. regOldData is zero
106954 ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
106955 ** checking regOldData for zero.
106956 **
106957 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
106958 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
106959 ** might be modified by the UPDATE. If pkChng is false, then the key of
106960 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
106961 **
106962 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
106963 ** was explicitly specified as part of the INSERT statement. If pkChng
106964 ** is zero, it means that the either rowid is computed automatically or
106965 ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
106966 ** pkChng will only be true if the INSERT statement provides an integer
106967 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
106968 **
106969 ** The code generated by this routine will store new index entries into
106970 ** registers identified by aRegIdx[]. No index entry is created for
106971 ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
106972 ** the same as the order of indices on the linked list of indices
106973 ** at pTab->pIndex.
106974 **
106975 ** The caller must have already opened writeable cursors on the main
106976 ** table and all applicable indices (that is to say, all indices for which
106977 ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
106978 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
106979 ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
106980 ** for the first index in the pTab->pIndex list. Cursors for other indices
106981 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
106982 **
106983 ** This routine also generates code to check constraints. NOT NULL,
106984 ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
106985 ** then the appropriate action is performed. There are five possible
106986 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
106987 **
106988 ** Constraint type Action What Happens
106989 ** --------------- ---------- ----------------------------------------
106990 ** any ROLLBACK The current transaction is rolled back and
106991 ** sqlite3_step() returns immediately with a
106992 ** return code of SQLITE_CONSTRAINT.
106993 **
106994 ** any ABORT Back out changes from the current command
106995 ** only (do not do a complete rollback) then
106996 ** cause sqlite3_step() to return immediately
106997 ** with SQLITE_CONSTRAINT.
106998 **
106999 ** any FAIL Sqlite3_step() returns immediately with a
107000 ** return code of SQLITE_CONSTRAINT. The
107001 ** transaction is not rolled back and any
107002 ** changes to prior rows are retained.
107003 **
107004 ** any IGNORE The attempt in insert or update the current
107005 ** row is skipped, without throwing an error.
107006 ** Processing continues with the next row.
107007 ** (There is an immediate jump to ignoreDest.)
107008 **
107009 ** NOT NULL REPLACE The NULL value is replace by the default
107010 ** value for that column. If the default value
107011 ** is NULL, the action is the same as ABORT.
107012 **
107013 ** UNIQUE REPLACE The other row that conflicts with the row
107014 ** being inserted is removed.
107015 **
107016 ** CHECK REPLACE Illegal. The results in an exception.
107017 **
107018 ** Which action to take is determined by the overrideError parameter.
107019 ** Or if overrideError==OE_Default, then the pParse->onError parameter
107020 ** is used. Or if pParse->onError==OE_Default then the onError value
107021 ** for the constraint is used.
107022 */
107024  Parse *pParse, /* The parser context */
107025  Table *pTab, /* The table being inserted or updated */
107026  int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
107027  int iDataCur, /* Canonical data cursor (main table or PK index) */
107028  int iIdxCur, /* First index cursor */
107029  int regNewData, /* First register in a range holding values to insert */
107030  int regOldData, /* Previous content. 0 for INSERTs */
107031  u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
107032  u8 overrideError, /* Override onError to this if not OE_Default */
107033  int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
107034  int *pbMayReplace, /* OUT: Set to true if constraint may cause a replace */
107035  int *aiChng /* column i is unchanged if aiChng[i]<0 */
107036 ){
107037  Vdbe *v; /* VDBE under constrution */
107038  Index *pIdx; /* Pointer to one of the indices */
107039  Index *pPk = 0; /* The PRIMARY KEY index */
107040  sqlite3 *db; /* Database connection */
107041  int i; /* loop counter */
107042  int ix; /* Index loop counter */
107043  int nCol; /* Number of columns */
107044  int onError; /* Conflict resolution strategy */
107045  int addr1; /* Address of jump instruction */
107046  int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
107047  int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
107048  int ipkTop = 0; /* Top of the rowid change constraint check */
107049  int ipkBottom = 0; /* Bottom of the rowid change constraint check */
107050  u8 isUpdate; /* True if this is an UPDATE operation */
107051  u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
107052  int regRowid = -1; /* Register holding ROWID value */
107053 
107054  isUpdate = regOldData!=0;
107055  db = pParse->db;
107056  v = sqlite3GetVdbe(pParse);
107057  assert( v!=0 );
107058  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
107059  nCol = pTab->nCol;
107060 
107061  /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
107062  ** normal rowid tables. nPkField is the number of key fields in the
107063  ** pPk index or 1 for a rowid table. In other words, nPkField is the
107064  ** number of fields in the true primary key of the table. */
107065  if( HasRowid(pTab) ){
107066  pPk = 0;
107067  nPkField = 1;
107068  }else{
107069  pPk = sqlite3PrimaryKeyIndex(pTab);
107070  nPkField = pPk->nKeyCol;
107071  }
107072 
107073  /* Record that this module has started */
107074  VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
107075  iDataCur, iIdxCur, regNewData, regOldData, pkChng));
107076 
107077  /* Test all NOT NULL constraints.
107078  */
107079  for(i=0; i<nCol; i++){
107080  if( i==pTab->iPKey ){
107081  continue; /* ROWID is never NULL */
107082  }
107083  if( aiChng && aiChng[i]<0 ){
107084  /* Don't bother checking for NOT NULL on columns that do not change */
107085  continue;
107086  }
107087  onError = pTab->aCol[i].notNull;
107088  if( onError==OE_None ) continue; /* This column is allowed to be NULL */
107089  if( overrideError!=OE_Default ){
107090  onError = overrideError;
107091  }else if( onError==OE_Default ){
107092  onError = OE_Abort;
107093  }
107094  if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
107095  onError = OE_Abort;
107096  }
107097  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
107098  || onError==OE_Ignore || onError==OE_Replace );
107099  switch( onError ){
107100  case OE_Abort:
107101  sqlite3MayAbort(pParse);
107102  /* Fall through */
107103  case OE_Rollback:
107104  case OE_Fail: {
107105  char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
107106  pTab->aCol[i].zName);
107108  regNewData+1+i, zMsg, P4_DYNAMIC);
107110  VdbeCoverage(v);
107111  break;
107112  }
107113  case OE_Ignore: {
107114  sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
107115  VdbeCoverage(v);
107116  break;
107117  }
107118  default: {
107119  assert( onError==OE_Replace );
107120  addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i);
107121  VdbeCoverage(v);
107122  sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
107123  sqlite3VdbeJumpHere(v, addr1);
107124  break;
107125  }
107126  }
107127  }
107128 
107129  /* Test all CHECK constraints
107130  */
107131 #ifndef SQLITE_OMIT_CHECK
107132  if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
107133  ExprList *pCheck = pTab->pCheck;
107134  pParse->ckBase = regNewData+1;
107135  onError = overrideError!=OE_Default ? overrideError : OE_Abort;
107136  for(i=0; i<pCheck->nExpr; i++){
107137  int allOk;
107138  Expr *pExpr = pCheck->a[i].pExpr;
107139  if( aiChng && checkConstraintUnchanged(pExpr, aiChng, pkChng) ) continue;
107140  allOk = sqlite3VdbeMakeLabel(v);
107141  sqlite3ExprIfTrue(pParse, pExpr, allOk, SQLITE_JUMPIFNULL);
107142  if( onError==OE_Ignore ){
107143  sqlite3VdbeGoto(v, ignoreDest);
107144  }else{
107145  char *zName = pCheck->a[i].zName;
107146  if( zName==0 ) zName = pTab->zName;
107147  if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
107149  onError, zName, P4_TRANSIENT,
107151  }
107152  sqlite3VdbeResolveLabel(v, allOk);
107153  }
107154  }
107155 #endif /* !defined(SQLITE_OMIT_CHECK) */
107156 
107157  /* If rowid is changing, make sure the new rowid does not previously
107158  ** exist in the table.
107159  */
107160  if( pkChng && pPk==0 ){
107161  int addrRowidOk = sqlite3VdbeMakeLabel(v);
107162 
107163  /* Figure out what action to take in case of a rowid collision */
107164  onError = pTab->keyConf;
107165  if( overrideError!=OE_Default ){
107166  onError = overrideError;
107167  }else if( onError==OE_Default ){
107168  onError = OE_Abort;
107169  }
107170 
107171  if( isUpdate ){
107172  /* pkChng!=0 does not mean that the rowid has change, only that
107173  ** it might have changed. Skip the conflict logic below if the rowid
107174  ** is unchanged. */
107175  sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
107177  VdbeCoverage(v);
107178  }
107179 
107180  /* If the response to a rowid conflict is REPLACE but the response
107181  ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
107182  ** to defer the running of the rowid conflict checking until after
107183  ** the UNIQUE constraints have run.
107184  */
107185  if( onError==OE_Replace && overrideError!=OE_Replace ){
107186  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
107187  if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
107188  ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
107189  break;
107190  }
107191  }
107192  }
107193 
107194  /* Check to see if the new rowid already exists in the table. Skip
107195  ** the following conflict logic if it does not. */
107196  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
107197  VdbeCoverage(v);
107198 
107199  /* Generate code that deals with a rowid collision */
107200  switch( onError ){
107201  default: {
107202  onError = OE_Abort;
107203  /* Fall thru into the next case */
107204  }
107205  case OE_Rollback:
107206  case OE_Abort:
107207  case OE_Fail: {
107208  sqlite3RowidConstraint(pParse, onError, pTab);
107209  break;
107210  }
107211  case OE_Replace: {
107212  /* If there are DELETE triggers on this table and the
107213  ** recursive-triggers flag is set, call GenerateRowDelete() to
107214  ** remove the conflicting row from the table. This will fire
107215  ** the triggers and remove both the table and index b-tree entries.
107216  **
107217  ** Otherwise, if there are no triggers or the recursive-triggers
107218  ** flag is not set, but the table has one or more indexes, call
107219  ** GenerateRowIndexDelete(). This removes the index b-tree entries
107220  ** only. The table b-tree entry will be replaced by the new entry
107221  ** when it is inserted.
107222  **
107223  ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
107224  ** also invoke MultiWrite() to indicate that this VDBE may require
107225  ** statement rollback (if the statement is aborted after the delete
107226  ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
107227  ** but being more selective here allows statements like:
107228  **
107229  ** REPLACE INTO t(rowid) VALUES($newrowid)
107230  **
107231  ** to run without a statement journal if there are no indexes on the
107232  ** table.
107233  */
107234  Trigger *pTrigger = 0;
107235  if( db->flags&SQLITE_RecTriggers ){
107236  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107237  }
107238  if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
107239  sqlite3MultiWrite(pParse);
107240  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107241  regNewData, 1, 0, OE_Replace, 1, -1);
107242  }else{
107243 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
107244  if( HasRowid(pTab) ){
107245  /* This OP_Delete opcode fires the pre-update-hook only. It does
107246  ** not modify the b-tree. It is more efficient to let the coming
107247  ** OP_Insert replace the existing entry than it is to delete the
107248  ** existing entry and then insert a new one. */
107249  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, OPFLAG_ISNOOP);
107250  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107251  }
107252 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
107253  if( pTab->pIndex ){
107254  sqlite3MultiWrite(pParse);
107255  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur,0,-1);
107256  }
107257  }
107258  seenReplace = 1;
107259  break;
107260  }
107261  case OE_Ignore: {
107262  /*assert( seenReplace==0 );*/
107263  sqlite3VdbeGoto(v, ignoreDest);
107264  break;
107265  }
107266  }
107267  sqlite3VdbeResolveLabel(v, addrRowidOk);
107268  if( ipkTop ){
107269  ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
107270  sqlite3VdbeJumpHere(v, ipkTop);
107271  }
107272  }
107273 
107274  /* Test all UNIQUE constraints by creating entries for each UNIQUE
107275  ** index and making sure that duplicate entries do not already exist.
107276  ** Compute the revised record entries for indices as we go.
107277  **
107278  ** This loop also handles the case of the PRIMARY KEY index for a
107279  ** WITHOUT ROWID table.
107280  */
107281  for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
107282  int regIdx; /* Range of registers hold conent for pIdx */
107283  int regR; /* Range of registers holding conflicting PK */
107284  int iThisCur; /* Cursor for this UNIQUE index */
107285  int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
107286 
107287  if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
107288  if( bAffinityDone==0 ){
107289  sqlite3TableAffinity(v, pTab, regNewData+1);
107290  bAffinityDone = 1;
107291  }
107292  iThisCur = iIdxCur+ix;
107293  addrUniqueOk = sqlite3VdbeMakeLabel(v);
107294 
107295  /* Skip partial indices for which the WHERE clause is not true */
107296  if( pIdx->pPartIdxWhere ){
107297  sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
107298  pParse->ckBase = regNewData+1;
107299  sqlite3ExprIfFalseDup(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
107301  pParse->ckBase = 0;
107302  }
107303 
107304  /* Create a record for this index entry as it should appear after
107305  ** the insert or update. Store that record in the aRegIdx[ix] register
107306  */
107307  regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
107308  for(i=0; i<pIdx->nColumn; i++){
107309  int iField = pIdx->aiColumn[i];
107310  int x;
107311  if( iField==XN_EXPR ){
107312  pParse->ckBase = regNewData+1;
107313  sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[i].pExpr, regIdx+i);
107314  pParse->ckBase = 0;
107315  VdbeComment((v, "%s column %d", pIdx->zName, i));
107316  }else{
107317  if( iField==XN_ROWID || iField==pTab->iPKey ){
107318  if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
107319  x = regNewData;
107320  regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
107321  }else{
107322  x = iField + regNewData + 1;
107323  }
107324  sqlite3VdbeAddOp2(v, iField<0 ? OP_IntCopy : OP_SCopy, x, regIdx+i);
107325  VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
107326  }
107327  }
107328  sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
107329  VdbeComment((v, "for %s", pIdx->zName));
107330  sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
107331 
107332  /* In an UPDATE operation, if this index is the PRIMARY KEY index
107333  ** of a WITHOUT ROWID table and there has been no change the
107334  ** primary key, then no collision is possible. The collision detection
107335  ** logic below can all be skipped. */
107336  if( isUpdate && pPk==pIdx && pkChng==0 ){
107337  sqlite3VdbeResolveLabel(v, addrUniqueOk);
107338  continue;
107339  }
107340 
107341  /* Find out what action to take in case there is a uniqueness conflict */
107342  onError = pIdx->onError;
107343  if( onError==OE_None ){
107344  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
107345  sqlite3VdbeResolveLabel(v, addrUniqueOk);
107346  continue; /* pIdx is not a UNIQUE index */
107347  }
107348  if( overrideError!=OE_Default ){
107349  onError = overrideError;
107350  }else if( onError==OE_Default ){
107351  onError = OE_Abort;
107352  }
107353 
107354  /* Check to see if the new index entry will be unique */
107355  sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
107356  regIdx, pIdx->nKeyCol); VdbeCoverage(v);
107357 
107358  /* Generate code to handle collisions */
107359  regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
107360  if( isUpdate || onError==OE_Replace ){
107361  if( HasRowid(pTab) ){
107362  sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
107363  /* Conflict only if the rowid of the existing index entry
107364  ** is different from old-rowid */
107365  if( isUpdate ){
107366  sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
107368  VdbeCoverage(v);
107369  }
107370  }else{
107371  int x;
107372  /* Extract the PRIMARY KEY from the end of the index entry and
107373  ** store it in registers regR..regR+nPk-1 */
107374  if( pIdx!=pPk ){
107375  for(i=0; i<pPk->nKeyCol; i++){
107376  assert( pPk->aiColumn[i]>=0 );
107377  x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
107378  sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
107379  VdbeComment((v, "%s.%s", pTab->zName,
107380  pTab->aCol[pPk->aiColumn[i]].zName));
107381  }
107382  }
107383  if( isUpdate ){
107384  /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
107385  ** table, only conflict if the new PRIMARY KEY values are actually
107386  ** different from the old.
107387  **
107388  ** For a UNIQUE index, only conflict if the PRIMARY KEY values
107389  ** of the matched index row are different from the original PRIMARY
107390  ** KEY values of this row before the update. */
107391  int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
107392  int op = OP_Ne;
107393  int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
107394 
107395  for(i=0; i<pPk->nKeyCol; i++){
107396  char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
107397  x = pPk->aiColumn[i];
107398  assert( x>=0 );
107399  if( i==(pPk->nKeyCol-1) ){
107400  addrJump = addrUniqueOk;
107401  op = OP_Eq;
107402  }
107403  sqlite3VdbeAddOp4(v, op,
107404  regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
107405  );
107407  VdbeCoverageIf(v, op==OP_Eq);
107408  VdbeCoverageIf(v, op==OP_Ne);
107409  }
107410  }
107411  }
107412  }
107413 
107414  /* Generate code that executes if the new index entry is not unique */
107415  assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
107416  || onError==OE_Ignore || onError==OE_Replace );
107417  switch( onError ){
107418  case OE_Rollback:
107419  case OE_Abort:
107420  case OE_Fail: {
107421  sqlite3UniqueConstraint(pParse, onError, pIdx);
107422  break;
107423  }
107424  case OE_Ignore: {
107425  sqlite3VdbeGoto(v, ignoreDest);
107426  break;
107427  }
107428  default: {
107429  Trigger *pTrigger = 0;
107430  assert( onError==OE_Replace );
107431  sqlite3MultiWrite(pParse);
107432  if( db->flags&SQLITE_RecTriggers ){
107433  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
107434  }
107435  sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
107436  regR, nPkField, 0, OE_Replace,
107437  (pIdx==pPk ? ONEPASS_SINGLE : ONEPASS_OFF), -1);
107438  seenReplace = 1;
107439  break;
107440  }
107441  }
107442  sqlite3VdbeResolveLabel(v, addrUniqueOk);
107443  sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
107444  if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
107445  }
107446  if( ipkTop ){
107447  sqlite3VdbeGoto(v, ipkTop+1);
107448  sqlite3VdbeJumpHere(v, ipkBottom);
107449  }
107450 
107451  *pbMayReplace = seenReplace;
107452  VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
107453 }
107454 
107455 /*
107456 ** This routine generates code to finish the INSERT or UPDATE operation
107457 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
107458 ** A consecutive range of registers starting at regNewData contains the
107459 ** rowid and the content to be inserted.
107460 **
107461 ** The arguments to this routine should be the same as the first six
107462 ** arguments to sqlite3GenerateConstraintChecks.
107463 */
107465  Parse *pParse, /* The parser context */
107466  Table *pTab, /* the table into which we are inserting */
107467  int iDataCur, /* Cursor of the canonical data source */
107468  int iIdxCur, /* First index cursor */
107469  int regNewData, /* Range of content */
107470  int *aRegIdx, /* Register used by each index. 0 for unused indices */
107471  int isUpdate, /* True for UPDATE, False for INSERT */
107472  int appendBias, /* True if this is likely to be an append */
107473  int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
107474 ){
107475  Vdbe *v; /* Prepared statements under construction */
107476  Index *pIdx; /* An index being inserted or updated */
107477  u8 pik_flags; /* flag values passed to the btree insert */
107478  int regData; /* Content registers (after the rowid) */
107479  int regRec; /* Register holding assembled record for the table */
107480  int i; /* Loop counter */
107481  u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
107482 
107483  v = sqlite3GetVdbe(pParse);
107484  assert( v!=0 );
107485  assert( pTab->pSelect==0 ); /* This table is not a VIEW */
107486  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
107487  if( aRegIdx[i]==0 ) continue;
107488  bAffinityDone = 1;
107489  if( pIdx->pPartIdxWhere ){
107490  sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
107491  VdbeCoverage(v);
107492  }
107493  sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
107494  pik_flags = 0;
107495  if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
107496  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
107497  assert( pParse->nested==0 );
107498  pik_flags |= OPFLAG_NCHANGE;
107499  }
107500  sqlite3VdbeChangeP5(v, pik_flags);
107501  }
107502  if( !HasRowid(pTab) ) return;
107503  regData = regNewData + 1;
107504  regRec = sqlite3GetTempReg(pParse);
107505  sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
107506  if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
107507  sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
107508  if( pParse->nested ){
107509  pik_flags = 0;
107510  }else{
107511  pik_flags = OPFLAG_NCHANGE;
107512  pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
107513  }
107514  if( appendBias ){
107515  pik_flags |= OPFLAG_APPEND;
107516  }
107517  if( useSeekResult ){
107518  pik_flags |= OPFLAG_USESEEKRESULT;
107519  }
107520  sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
107521  if( !pParse->nested ){
107522  sqlite3VdbeChangeP4(v, -1, (char *)pTab, P4_TABLE);
107523  }
107524  sqlite3VdbeChangeP5(v, pik_flags);
107525 }
107526 
107527 /*
107528 ** Allocate cursors for the pTab table and all its indices and generate
107529 ** code to open and initialized those cursors.
107530 **
107531 ** The cursor for the object that contains the complete data (normally
107532 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
107533 ** ROWID table) is returned in *piDataCur. The first index cursor is
107534 ** returned in *piIdxCur. The number of indices is returned.
107535 **
107536 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
107537 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
107538 ** If iBase is negative, then allocate the next available cursor.
107539 **
107540 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
107541 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
107542 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
107543 ** pTab->pIndex list.
107544 **
107545 ** If pTab is a virtual table, then this routine is a no-op and the
107546 ** *piDataCur and *piIdxCur values are left uninitialized.
107547 */
107549  Parse *pParse, /* Parsing context */
107550  Table *pTab, /* Table to be opened */
107551  int op, /* OP_OpenRead or OP_OpenWrite */
107552  u8 p5, /* P5 value for OP_Open* opcodes (except on WITHOUT ROWID) */
107553  int iBase, /* Use this for the table cursor, if there is one */
107554  u8 *aToOpen, /* If not NULL: boolean for each table and index */
107555  int *piDataCur, /* Write the database source cursor number here */
107556  int *piIdxCur /* Write the first index cursor number here */
107557 ){
107558  int i;
107559  int iDb;
107560  int iDataCur;
107561  Index *pIdx;
107562  Vdbe *v;
107563 
107564  assert( op==OP_OpenRead || op==OP_OpenWrite );
107565  assert( op==OP_OpenWrite || p5==0 );
107566  if( IsVirtual(pTab) ){
107567  /* This routine is a no-op for virtual tables. Leave the output
107568  ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
107569  ** can detect if they are used by mistake in the caller. */
107570  return 0;
107571  }
107572  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
107573  v = sqlite3GetVdbe(pParse);
107574  assert( v!=0 );
107575  if( iBase<0 ) iBase = pParse->nTab;
107576  iDataCur = iBase++;
107577  if( piDataCur ) *piDataCur = iDataCur;
107578  if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
107579  sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
107580  }else{
107581  sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
107582  }
107583  if( piIdxCur ) *piIdxCur = iBase;
107584  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
107585  int iIdxCur = iBase++;
107586  assert( pIdx->pSchema==pTab->pSchema );
107587  if( aToOpen==0 || aToOpen[i+1] ){
107588  sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
107589  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
107590  VdbeComment((v, "%s", pIdx->zName));
107591  }
107592  if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
107593  if( piDataCur ) *piDataCur = iIdxCur;
107594  }else{
107595  sqlite3VdbeChangeP5(v, p5);
107596  }
107597  }
107598  if( iBase>pParse->nTab ) pParse->nTab = iBase;
107599  return i;
107600 }
107601 
107602 
107603 #ifdef SQLITE_TEST
107604 /*
107605 ** The following global variable is incremented whenever the
107606 ** transfer optimization is used. This is used for testing
107607 ** purposes only - to make sure the transfer optimization really
107608 ** is happening when it is supposed to.
107609 */
107610 SQLITE_API int sqlite3_xferopt_count;
107611 #endif /* SQLITE_TEST */
107612 
107613 
107614 #ifndef SQLITE_OMIT_XFER_OPT
107615 /*
107616 ** Check to see if index pSrc is compatible as a source of data
107617 ** for index pDest in an insert transfer optimization. The rules
107618 ** for a compatible index:
107619 **
107620 ** * The index is over the same set of columns
107621 ** * The same DESC and ASC markings occurs on all columns
107622 ** * The same onError processing (OE_Abort, OE_Ignore, etc)
107623 ** * The same collating sequence on each column
107624 ** * The index has the exact same WHERE clause
107625 */
107626 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
107627  int i;
107628  assert( pDest && pSrc );
107629  assert( pDest->pTable!=pSrc->pTable );
107630  if( pDest->nKeyCol!=pSrc->nKeyCol ){
107631  return 0; /* Different number of columns */
107632  }
107633  if( pDest->onError!=pSrc->onError ){
107634  return 0; /* Different conflict resolution strategies */
107635  }
107636  for(i=0; i<pSrc->nKeyCol; i++){
107637  if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
107638  return 0; /* Different columns indexed */
107639  }
107640  if( pSrc->aiColumn[i]==XN_EXPR ){
107641  assert( pSrc->aColExpr!=0 && pDest->aColExpr!=0 );
107642  if( sqlite3ExprCompare(pSrc->aColExpr->a[i].pExpr,
107643  pDest->aColExpr->a[i].pExpr, -1)!=0 ){
107644  return 0; /* Different expressions in the index */
107645  }
107646  }
107647  if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
107648  return 0; /* Different sort orders */
107649  }
107650  if( sqlite3_stricmp(pSrc->azColl[i],pDest->azColl[i])!=0 ){
107651  return 0; /* Different collating sequences */
107652  }
107653  }
107654  if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
107655  return 0; /* Different WHERE clauses */
107656  }
107657 
107658  /* If no test above fails then the indices must be compatible */
107659  return 1;
107660 }
107661 
107662 /*
107663 ** Attempt the transfer optimization on INSERTs of the form
107664 **
107665 ** INSERT INTO tab1 SELECT * FROM tab2;
107666 **
107667 ** The xfer optimization transfers raw records from tab2 over to tab1.
107668 ** Columns are not decoded and reassembled, which greatly improves
107669 ** performance. Raw index records are transferred in the same way.
107670 **
107671 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
107672 ** There are lots of rules for determining compatibility - see comments
107673 ** embedded in the code for details.
107674 **
107675 ** This routine returns TRUE if the optimization is guaranteed to be used.
107676 ** Sometimes the xfer optimization will only work if the destination table
107677 ** is empty - a factor that can only be determined at run-time. In that
107678 ** case, this routine generates code for the xfer optimization but also
107679 ** does a test to see if the destination table is empty and jumps over the
107680 ** xfer optimization code if the test fails. In that case, this routine
107681 ** returns FALSE so that the caller will know to go ahead and generate
107682 ** an unoptimized transfer. This routine also returns FALSE if there
107683 ** is no chance that the xfer optimization can be applied.
107684 **
107685 ** This optimization is particularly useful at making VACUUM run faster.
107686 */
107688  Parse *pParse, /* Parser context */
107689  Table *pDest, /* The table we are inserting into */
107690  Select *pSelect, /* A SELECT statement to use as the data source */
107691  int onError, /* How to handle constraint errors */
107692  int iDbDest /* The database of pDest */
107693 ){
107694  sqlite3 *db = pParse->db;
107695  ExprList *pEList; /* The result set of the SELECT */
107696  Table *pSrc; /* The table in the FROM clause of SELECT */
107697  Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
107698  struct SrcList_item *pItem; /* An element of pSelect->pSrc */
107699  int i; /* Loop counter */
107700  int iDbSrc; /* The database of pSrc */
107701  int iSrc, iDest; /* Cursors from source and destination */
107702  int addr1, addr2; /* Loop addresses */
107703  int emptyDestTest = 0; /* Address of test for empty pDest */
107704  int emptySrcTest = 0; /* Address of test for empty pSrc */
107705  Vdbe *v; /* The VDBE we are building */
107706  int regAutoinc; /* Memory register used by AUTOINC */
107707  int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
107708  int regData, regRowid; /* Registers holding data and rowid */
107709 
107710  if( pSelect==0 ){
107711  return 0; /* Must be of the form INSERT INTO ... SELECT ... */
107712  }
107713  if( pParse->pWith || pSelect->pWith ){
107714  /* Do not attempt to process this query if there are an WITH clauses
107715  ** attached to it. Proceeding may generate a false "no such table: xxx"
107716  ** error if pSelect reads from a CTE named "xxx". */
107717  return 0;
107718  }
107719  if( sqlite3TriggerList(pParse, pDest) ){
107720  return 0; /* tab1 must not have triggers */
107721  }
107722 #ifndef SQLITE_OMIT_VIRTUALTABLE
107723  if( pDest->tabFlags & TF_Virtual ){
107724  return 0; /* tab1 must not be a virtual table */
107725  }
107726 #endif
107727  if( onError==OE_Default ){
107728  if( pDest->iPKey>=0 ) onError = pDest->keyConf;
107729  if( onError==OE_Default ) onError = OE_Abort;
107730  }
107731  assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
107732  if( pSelect->pSrc->nSrc!=1 ){
107733  return 0; /* FROM clause must have exactly one term */
107734  }
107735  if( pSelect->pSrc->a[0].pSelect ){
107736  return 0; /* FROM clause cannot contain a subquery */
107737  }
107738  if( pSelect->pWhere ){
107739  return 0; /* SELECT may not have a WHERE clause */
107740  }
107741  if( pSelect->pOrderBy ){
107742  return 0; /* SELECT may not have an ORDER BY clause */
107743  }
107744  /* Do not need to test for a HAVING clause. If HAVING is present but
107745  ** there is no ORDER BY, we will get an error. */
107746  if( pSelect->pGroupBy ){
107747  return 0; /* SELECT may not have a GROUP BY clause */
107748  }
107749  if( pSelect->pLimit ){
107750  return 0; /* SELECT may not have a LIMIT clause */
107751  }
107752  assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
107753  if( pSelect->pPrior ){
107754  return 0; /* SELECT may not be a compound query */
107755  }
107756  if( pSelect->selFlags & SF_Distinct ){
107757  return 0; /* SELECT may not be DISTINCT */
107758  }
107759  pEList = pSelect->pEList;
107760  assert( pEList!=0 );
107761  if( pEList->nExpr!=1 ){
107762  return 0; /* The result set must have exactly one column */
107763  }
107764  assert( pEList->a[0].pExpr );
107765  if( pEList->a[0].pExpr->op!=TK_ASTERISK ){
107766  return 0; /* The result set must be the special operator "*" */
107767  }
107768 
107769  /* At this point we have established that the statement is of the
107770  ** correct syntactic form to participate in this optimization. Now
107771  ** we have to check the semantics.
107772  */
107773  pItem = pSelect->pSrc->a;
107774  pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
107775  if( pSrc==0 ){
107776  return 0; /* FROM clause does not contain a real table */
107777  }
107778  if( pSrc==pDest ){
107779  return 0; /* tab1 and tab2 may not be the same table */
107780  }
107781  if( HasRowid(pDest)!=HasRowid(pSrc) ){
107782  return 0; /* source and destination must both be WITHOUT ROWID or not */
107783  }
107784 #ifndef SQLITE_OMIT_VIRTUALTABLE
107785  if( pSrc->tabFlags & TF_Virtual ){
107786  return 0; /* tab2 must not be a virtual table */
107787  }
107788 #endif
107789  if( pSrc->pSelect ){
107790  return 0; /* tab2 may not be a view */
107791  }
107792  if( pDest->nCol!=pSrc->nCol ){
107793  return 0; /* Number of columns must be the same in tab1 and tab2 */
107794  }
107795  if( pDest->iPKey!=pSrc->iPKey ){
107796  return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
107797  }
107798  for(i=0; i<pDest->nCol; i++){
107799  Column *pDestCol = &pDest->aCol[i];
107800  Column *pSrcCol = &pSrc->aCol[i];
107801 #ifdef SQLITE_ENABLE_HIDDEN_COLUMNS
107802  if( (db->flags & SQLITE_Vacuum)==0
107803  && (pDestCol->colFlags | pSrcCol->colFlags) & COLFLAG_HIDDEN
107804  ){
107805  return 0; /* Neither table may have __hidden__ columns */
107806  }
107807 #endif
107808  if( pDestCol->affinity!=pSrcCol->affinity ){
107809  return 0; /* Affinity must be the same on all columns */
107810  }
107811  if( sqlite3_stricmp(pDestCol->zColl, pSrcCol->zColl)!=0 ){
107812  return 0; /* Collating sequence must be the same on all columns */
107813  }
107814  if( pDestCol->notNull && !pSrcCol->notNull ){
107815  return 0; /* tab2 must be NOT NULL if tab1 is */
107816  }
107817  /* Default values for second and subsequent columns need to match. */
107818  if( i>0 ){
107819  assert( pDestCol->pDflt==0 || pDestCol->pDflt->op==TK_SPAN );
107820  assert( pSrcCol->pDflt==0 || pSrcCol->pDflt->op==TK_SPAN );
107821  if( (pDestCol->pDflt==0)!=(pSrcCol->pDflt==0)
107822  || (pDestCol->pDflt && strcmp(pDestCol->pDflt->u.zToken,
107823  pSrcCol->pDflt->u.zToken)!=0)
107824  ){
107825  return 0; /* Default values must be the same for all columns */
107826  }
107827  }
107828  }
107829  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
107830  if( IsUniqueIndex(pDestIdx) ){
107831  destHasUniqueIdx = 1;
107832  }
107833  for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
107834  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
107835  }
107836  if( pSrcIdx==0 ){
107837  return 0; /* pDestIdx has no corresponding index in pSrc */
107838  }
107839  }
107840 #ifndef SQLITE_OMIT_CHECK
107841  if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
107842  return 0; /* Tables have different CHECK constraints. Ticket #2252 */
107843  }
107844 #endif
107845 #ifndef SQLITE_OMIT_FOREIGN_KEY
107846  /* Disallow the transfer optimization if the destination table constains
107847  ** any foreign key constraints. This is more restrictive than necessary.
107848  ** But the main beneficiary of the transfer optimization is the VACUUM
107849  ** command, and the VACUUM command disables foreign key constraints. So
107850  ** the extra complication to make this rule less restrictive is probably
107851  ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
107852  */
107853  if( (db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
107854  return 0;
107855  }
107856 #endif
107857  if( (db->flags & SQLITE_CountRows)!=0 ){
107858  return 0; /* xfer opt does not play well with PRAGMA count_changes */
107859  }
107860 
107861  /* If we get this far, it means that the xfer optimization is at
107862  ** least a possibility, though it might only work if the destination
107863  ** table (tab1) is initially empty.
107864  */
107865 #ifdef SQLITE_TEST
107866  sqlite3_xferopt_count++;
107867 #endif
107868  iDbSrc = sqlite3SchemaToIndex(db, pSrc->pSchema);
107869  v = sqlite3GetVdbe(pParse);
107870  sqlite3CodeVerifySchema(pParse, iDbSrc);
107871  iSrc = pParse->nTab++;
107872  iDest = pParse->nTab++;
107873  regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
107874  regData = sqlite3GetTempReg(pParse);
107875  regRowid = sqlite3GetTempReg(pParse);
107876  sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
107877  assert( HasRowid(pDest) || destHasUniqueIdx );
107878  if( (db->flags & SQLITE_Vacuum)==0 && (
107879  (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
107880  || destHasUniqueIdx /* (2) */
107881  || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
107882  )){
107883  /* In some circumstances, we are able to run the xfer optimization
107884  ** only if the destination table is initially empty. Unless the
107885  ** SQLITE_Vacuum flag is set, this block generates code to make
107886  ** that determination. If SQLITE_Vacuum is set, then the destination
107887  ** table is always empty.
107888  **
107889  ** Conditions under which the destination must be empty:
107890  **
107891  ** (1) There is no INTEGER PRIMARY KEY but there are indices.
107892  ** (If the destination is not initially empty, the rowid fields
107893  ** of index entries might need to change.)
107894  **
107895  ** (2) The destination has a unique index. (The xfer optimization
107896  ** is unable to test uniqueness.)
107897  **
107898  ** (3) onError is something other than OE_Abort and OE_Rollback.
107899  */
107900  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
107901  emptyDestTest = sqlite3VdbeAddOp0(v, OP_Goto);
107902  sqlite3VdbeJumpHere(v, addr1);
107903  }
107904  if( HasRowid(pSrc) ){
107905  sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
107906  emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
107907  if( pDest->iPKey>=0 ){
107908  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
107909  addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
107910  VdbeCoverage(v);
107911  sqlite3RowidConstraint(pParse, onError, pDest);
107912  sqlite3VdbeJumpHere(v, addr2);
107913  autoIncStep(pParse, regAutoinc, regRowid);
107914  }else if( pDest->pIndex==0 ){
107915  addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
107916  }else{
107917  addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
107918  assert( (pDest->tabFlags & TF_Autoincrement)==0 );
107919  }
107920  sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
107921  sqlite3VdbeAddOp4(v, OP_Insert, iDest, regData, regRowid,
107922  (char*)pDest, P4_TABLE);
107924  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
107925  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
107926  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
107927  }else{
107928  sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
107929  sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
107930  }
107931  for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
107932  u8 idxInsFlags = 0;
107933  for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
107934  if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
107935  }
107936  assert( pSrcIdx );
107937  sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
107938  sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
107939  VdbeComment((v, "%s", pSrcIdx->zName));
107940  sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
107941  sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
107943  VdbeComment((v, "%s", pDestIdx->zName));
107944  addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
107945  sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
107946  if( db->flags & SQLITE_Vacuum ){
107947  /* This INSERT command is part of a VACUUM operation, which guarantees
107948  ** that the destination table is empty. If all indexed columns use
107949  ** collation sequence BINARY, then it can also be assumed that the
107950  ** index will be populated by inserting keys in strictly sorted
107951  ** order. In this case, instead of seeking within the b-tree as part
107952  ** of every OP_IdxInsert opcode, an OP_Last is added before the
107953  ** OP_IdxInsert to seek to the point within the b-tree where each key
107954  ** should be inserted. This is faster.
107955  **
107956  ** If any of the indexed columns use a collation sequence other than
107957  ** BINARY, this optimization is disabled. This is because the user
107958  ** might change the definition of a collation sequence and then run
107959  ** a VACUUM command. In that case keys may not be written in strictly
107960  ** sorted order. */
107961  for(i=0; i<pSrcIdx->nColumn; i++){
107962  const char *zColl = pSrcIdx->azColl[i];
107963  assert( sqlite3_stricmp(sqlite3StrBINARY, zColl)!=0
107964  || sqlite3StrBINARY==zColl );
107965  if( sqlite3_stricmp(sqlite3StrBINARY, zColl) ) break;
107966  }
107967  if( i==pSrcIdx->nColumn ){
107968  idxInsFlags = OPFLAG_USESEEKRESULT;
107969  sqlite3VdbeAddOp3(v, OP_Last, iDest, 0, -1);
107970  }
107971  }
107972  if( !HasRowid(pSrc) && pDestIdx->idxType==2 ){
107973  idxInsFlags |= OPFLAG_NCHANGE;
107974  }
107975  sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
107976  sqlite3VdbeChangeP5(v, idxInsFlags);
107977  sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
107978  sqlite3VdbeJumpHere(v, addr1);
107979  sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
107980  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
107981  }
107982  if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
107983  sqlite3ReleaseTempReg(pParse, regRowid);
107984  sqlite3ReleaseTempReg(pParse, regData);
107985  if( emptyDestTest ){
107987  sqlite3VdbeJumpHere(v, emptyDestTest);
107988  sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
107989  return 0;
107990  }else{
107991  return 1;
107992  }
107993 }
107994 #endif /* SQLITE_OMIT_XFER_OPT */
107995 
107996 /************** End of insert.c **********************************************/
107997 /************** Begin file legacy.c ******************************************/
107998 /*
107999 ** 2001 September 15
108000 **
108001 ** The author disclaims copyright to this source code. In place of
108002 ** a legal notice, here is a blessing:
108003 **
108004 ** May you do good and not evil.
108005 ** May you find forgiveness for yourself and forgive others.
108006 ** May you share freely, never taking more than you give.
108007 **
108008 *************************************************************************
108009 ** Main file for the SQLite library. The routines in this file
108010 ** implement the programmer interface to the library. Routines in
108011 ** other files are for internal use by SQLite and should not be
108012 ** accessed by users of the library.
108013 */
108014 
108015 /* #include "sqliteInt.h" */
108016 
108017 /*
108018 ** Execute SQL code. Return one of the SQLITE_ success/failure
108019 ** codes. Also write an error message into memory obtained from
108020 ** malloc() and make *pzErrMsg point to that message.
108021 **
108022 ** If the SQL is a query, then for each row in the query result
108023 ** the xCallback() function is called. pArg becomes the first
108024 ** argument to xCallback(). If xCallback=NULL then no callback
108025 ** is invoked, even for queries.
108026 */
108028  sqlite3 *db, /* The database on which the SQL executes */
108029  const char *zSql, /* The SQL to be executed */
108030  sqlite3_callback xCallback, /* Invoke this callback routine */
108031  void *pArg, /* First argument to xCallback() */
108032  char **pzErrMsg /* Write error messages here */
108033 ){
108034  int rc = SQLITE_OK; /* Return code */
108035  const char *zLeftover; /* Tail of unprocessed SQL */
108036  sqlite3_stmt *pStmt = 0; /* The current SQL statement */
108037  char **azCols = 0; /* Names of result columns */
108038  int callbackIsInit; /* True if callback data is initialized */
108039 
108040  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
108041  if( zSql==0 ) zSql = "";
108042 
108043  sqlite3_mutex_enter(db->mutex);
108044  sqlite3Error(db, SQLITE_OK);
108045  while( rc==SQLITE_OK && zSql[0] ){
108046  int nCol;
108047  char **azVals = 0;
108048 
108049  pStmt = 0;
108050  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
108051  assert( rc==SQLITE_OK || pStmt==0 );
108052  if( rc!=SQLITE_OK ){
108053  continue;
108054  }
108055  if( !pStmt ){
108056  /* this happens for a comment or white-space */
108057  zSql = zLeftover;
108058  continue;
108059  }
108060 
108061  callbackIsInit = 0;
108062  nCol = sqlite3_column_count(pStmt);
108063 
108064  while( 1 ){
108065  int i;
108066  rc = sqlite3_step(pStmt);
108067 
108068  /* Invoke the callback function if required */
108069  if( xCallback && (SQLITE_ROW==rc ||
108070  (SQLITE_DONE==rc && !callbackIsInit
108071  && db->flags&SQLITE_NullCallback)) ){
108072  if( !callbackIsInit ){
108073  azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
108074  if( azCols==0 ){
108075  goto exec_out;
108076  }
108077  for(i=0; i<nCol; i++){
108078  azCols[i] = (char *)sqlite3_column_name(pStmt, i);
108079  /* sqlite3VdbeSetColName() installs column names as UTF8
108080  ** strings so there is no way for sqlite3_column_name() to fail. */
108081  assert( azCols[i]!=0 );
108082  }
108083  callbackIsInit = 1;
108084  }
108085  if( rc==SQLITE_ROW ){
108086  azVals = &azCols[nCol];
108087  for(i=0; i<nCol; i++){
108088  azVals[i] = (char *)sqlite3_column_text(pStmt, i);
108089  if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
108090  sqlite3OomFault(db);
108091  goto exec_out;
108092  }
108093  }
108094  }
108095  if( xCallback(pArg, nCol, azVals, azCols) ){
108096  /* EVIDENCE-OF: R-38229-40159 If the callback function to
108097  ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
108098  ** return SQLITE_ABORT. */
108099  rc = SQLITE_ABORT;
108100  sqlite3VdbeFinalize((Vdbe *)pStmt);
108101  pStmt = 0;
108102  sqlite3Error(db, SQLITE_ABORT);
108103  goto exec_out;
108104  }
108105  }
108106 
108107  if( rc!=SQLITE_ROW ){
108108  rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
108109  pStmt = 0;
108110  zSql = zLeftover;
108111  while( sqlite3Isspace(zSql[0]) ) zSql++;
108112  break;
108113  }
108114  }
108115 
108116  sqlite3DbFree(db, azCols);
108117  azCols = 0;
108118  }
108119 
108120 exec_out:
108121  if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
108122  sqlite3DbFree(db, azCols);
108123 
108124  rc = sqlite3ApiExit(db, rc);
108125  if( rc!=SQLITE_OK && pzErrMsg ){
108126  int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
108127  *pzErrMsg = sqlite3Malloc(nErrMsg);
108128  if( *pzErrMsg ){
108129  memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
108130  }else{
108131  rc = SQLITE_NOMEM_BKPT;
108132  sqlite3Error(db, SQLITE_NOMEM);
108133  }
108134  }else if( pzErrMsg ){
108135  *pzErrMsg = 0;
108136  }
108137 
108138  assert( (rc&db->errMask)==rc );
108139  sqlite3_mutex_leave(db->mutex);
108140  return rc;
108141 }
108142 
108143 /************** End of legacy.c **********************************************/
108144 /************** Begin file loadext.c *****************************************/
108145 /*
108146 ** 2006 June 7
108147 **
108148 ** The author disclaims copyright to this source code. In place of
108149 ** a legal notice, here is a blessing:
108150 **
108151 ** May you do good and not evil.
108152 ** May you find forgiveness for yourself and forgive others.
108153 ** May you share freely, never taking more than you give.
108154 **
108155 *************************************************************************
108156 ** This file contains code used to dynamically load extensions into
108157 ** the SQLite library.
108158 */
108159 
108160 #ifndef SQLITE_CORE
108161  #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
108162 #endif
108163 /************** Include sqlite3ext.h in the middle of loadext.c **************/
108164 /************** Begin file sqlite3ext.h **************************************/
108165 /*
108166 ** 2006 June 7
108167 **
108168 ** The author disclaims copyright to this source code. In place of
108169 ** a legal notice, here is a blessing:
108170 **
108171 ** May you do good and not evil.
108172 ** May you find forgiveness for yourself and forgive others.
108173 ** May you share freely, never taking more than you give.
108174 **
108175 *************************************************************************
108176 ** This header file defines the SQLite interface for use by
108177 ** shared libraries that want to be imported as extensions into
108178 ** an SQLite instance. Shared libraries that intend to be loaded
108179 ** as extensions by SQLite should #include this file instead of
108180 ** sqlite3.h.
108181 */
108182 #ifndef _SQLITE3EXT_H_
108183 #define _SQLITE3EXT_H_
108184 /* #include "sqlite3.h" */
108185 
108187 
108188 /*
108189 ** The following structure holds pointers to all of the SQLite API
108190 ** routines.
108191 **
108192 ** WARNING: In order to maintain backwards compatibility, add new
108193 ** interfaces to the end of this structure only. If you insert new
108194 ** interfaces in the middle of this structure, then older different
108195 ** versions of SQLite will not be able to load each other's shared
108196 ** libraries!
108197 */
108199  void * (*aggregate_context)(sqlite3_context*,int nBytes);
108200  int (*aggregate_count)(sqlite3_context*);
108201  int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
108202  int (*bind_double)(sqlite3_stmt*,int,double);
108203  int (*bind_int)(sqlite3_stmt*,int,int);
108204  int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
108205  int (*bind_null)(sqlite3_stmt*,int);
108206  int (*bind_parameter_count)(sqlite3_stmt*);
108207  int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
108208  const char * (*bind_parameter_name)(sqlite3_stmt*,int);
108209  int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
108210  int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
108211  int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
108212  int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
108213  int (*busy_timeout)(sqlite3*,int ms);
108214  int (*changes)(sqlite3*);
108215  int (*close)(sqlite3*);
108216  int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
108217  int eTextRep,const char*));
108218  int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
108219  int eTextRep,const void*));
108220  const void * (*column_blob)(sqlite3_stmt*,int iCol);
108221  int (*column_bytes)(sqlite3_stmt*,int iCol);
108222  int (*column_bytes16)(sqlite3_stmt*,int iCol);
108223  int (*column_count)(sqlite3_stmt*pStmt);
108224  const char * (*column_database_name)(sqlite3_stmt*,int);
108225  const void * (*column_database_name16)(sqlite3_stmt*,int);
108226  const char * (*column_decltype)(sqlite3_stmt*,int i);
108227  const void * (*column_decltype16)(sqlite3_stmt*,int);
108228  double (*column_double)(sqlite3_stmt*,int iCol);
108229  int (*column_int)(sqlite3_stmt*,int iCol);
108230  sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
108231  const char * (*column_name)(sqlite3_stmt*,int);
108232  const void * (*column_name16)(sqlite3_stmt*,int);
108233  const char * (*column_origin_name)(sqlite3_stmt*,int);
108234  const void * (*column_origin_name16)(sqlite3_stmt*,int);
108235  const char * (*column_table_name)(sqlite3_stmt*,int);
108236  const void * (*column_table_name16)(sqlite3_stmt*,int);
108237  const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
108238  const void * (*column_text16)(sqlite3_stmt*,int iCol);
108239  int (*column_type)(sqlite3_stmt*,int iCol);
108240  sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
108241  void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
108242  int (*complete)(const char*sql);
108243  int (*complete16)(const void*sql);
108244  int (*create_collation)(sqlite3*,const char*,int,void*,
108245  int(*)(void*,int,const void*,int,const void*));
108246  int (*create_collation16)(sqlite3*,const void*,int,void*,
108247  int(*)(void*,int,const void*,int,const void*));
108248  int (*create_function)(sqlite3*,const char*,int,int,void*,
108249  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108250  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108251  void (*xFinal)(sqlite3_context*));
108252  int (*create_function16)(sqlite3*,const void*,int,int,void*,
108253  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108254  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108255  void (*xFinal)(sqlite3_context*));
108256  int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
108257  int (*data_count)(sqlite3_stmt*pStmt);
108258  sqlite3 * (*db_handle)(sqlite3_stmt*);
108259  int (*declare_vtab)(sqlite3*,const char*);
108260  int (*enable_shared_cache)(int);
108261  int (*errcode)(sqlite3*db);
108262  const char * (*errmsg)(sqlite3*);
108263  const void * (*errmsg16)(sqlite3*);
108264  int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
108265  int (*expired)(sqlite3_stmt*);
108266  int (*finalize)(sqlite3_stmt*pStmt);
108267  void (*free)(void*);
108268  void (*free_table)(char**result);
108269  int (*get_autocommit)(sqlite3*);
108270  void * (*get_auxdata)(sqlite3_context*,int);
108271  int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
108272  int (*global_recover)(void);
108273  void (*interruptx)(sqlite3*);
108275  const char * (*libversion)(void);
108276  int (*libversion_number)(void);
108277  void *(*malloc)(int);
108278  char * (*mprintf)(const char*,...);
108279  int (*open)(const char*,sqlite3**);
108280  int (*open16)(const void*,sqlite3**);
108281  int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108282  int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108283  void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
108284  void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
108285  void *(*realloc)(void*,int);
108286  int (*reset)(sqlite3_stmt*pStmt);
108287  void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
108288  void (*result_double)(sqlite3_context*,double);
108289  void (*result_error)(sqlite3_context*,const char*,int);
108290  void (*result_error16)(sqlite3_context*,const void*,int);
108291  void (*result_int)(sqlite3_context*,int);
108292  void (*result_int64)(sqlite3_context*,sqlite_int64);
108293  void (*result_null)(sqlite3_context*);
108294  void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
108295  void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
108296  void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
108297  void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
108298  void (*result_value)(sqlite3_context*,sqlite3_value*);
108299  void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
108300  int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
108301  const char*,const char*),void*);
108302  void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
108303  char * (*snprintf)(int,char*,const char*,...);
108304  int (*step)(sqlite3_stmt*);
108305  int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
108306  char const**,char const**,int*,int*,int*);
108307  void (*thread_cleanup)(void);
108309  void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
108310  int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
108311  void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
108312  sqlite_int64),void*);
108313  void * (*user_data)(sqlite3_context*);
108314  const void * (*value_blob)(sqlite3_value*);
108315  int (*value_bytes)(sqlite3_value*);
108316  int (*value_bytes16)(sqlite3_value*);
108317  double (*value_double)(sqlite3_value*);
108318  int (*value_int)(sqlite3_value*);
108319  sqlite_int64 (*value_int64)(sqlite3_value*);
108320  int (*value_numeric_type)(sqlite3_value*);
108321  const unsigned char * (*value_text)(sqlite3_value*);
108322  const void * (*value_text16)(sqlite3_value*);
108323  const void * (*value_text16be)(sqlite3_value*);
108324  const void * (*value_text16le)(sqlite3_value*);
108325  int (*value_type)(sqlite3_value*);
108326  char *(*vmprintf)(const char*,va_list);
108327  /* Added ??? */
108328  int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
108329  /* Added by 3.3.13 */
108330  int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
108331  int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
108332  int (*clear_bindings)(sqlite3_stmt*);
108333  /* Added by 3.4.1 */
108334  int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
108335  void (*xDestroy)(void *));
108336  /* Added by 3.5.0 */
108337  int (*bind_zeroblob)(sqlite3_stmt*,int,int);
108338  int (*blob_bytes)(sqlite3_blob*);
108339  int (*blob_close)(sqlite3_blob*);
108340  int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
108341  int,sqlite3_blob**);
108342  int (*blob_read)(sqlite3_blob*,void*,int,int);
108343  int (*blob_write)(sqlite3_blob*,const void*,int,int);
108344  int (*create_collation_v2)(sqlite3*,const char*,int,void*,
108345  int(*)(void*,int,const void*,int,const void*),
108346  void(*)(void*));
108347  int (*file_control)(sqlite3*,const char*,int,void*);
108348  sqlite3_int64 (*memory_highwater)(int);
108349  sqlite3_int64 (*memory_used)(void);
108350  sqlite3_mutex *(*mutex_alloc)(int);
108351  void (*mutex_enter)(sqlite3_mutex*);
108352  void (*mutex_free)(sqlite3_mutex*);
108353  void (*mutex_leave)(sqlite3_mutex*);
108354  int (*mutex_try)(sqlite3_mutex*);
108355  int (*open_v2)(const char*,sqlite3**,int,const char*);
108356  int (*release_memory)(int);
108357  void (*result_error_nomem)(sqlite3_context*);
108358  void (*result_error_toobig)(sqlite3_context*);
108359  int (*sleep)(int);
108360  void (*soft_heap_limit)(int);
108361  sqlite3_vfs *(*vfs_find)(const char*);
108362  int (*vfs_register)(sqlite3_vfs*,int);
108363  int (*vfs_unregister)(sqlite3_vfs*);
108364  int (*xthreadsafe)(void);
108365  void (*result_zeroblob)(sqlite3_context*,int);
108366  void (*result_error_code)(sqlite3_context*,int);
108367  int (*test_control)(int, ...);
108368  void (*randomness)(int,void*);
108369  sqlite3 *(*context_db_handle)(sqlite3_context*);
108370  int (*extended_result_codes)(sqlite3*,int);
108371  int (*limit)(sqlite3*,int,int);
108372  sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
108373  const char *(*sql)(sqlite3_stmt*);
108374  int (*status)(int,int*,int*,int);
108375  int (*backup_finish)(sqlite3_backup*);
108376  sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
108377  int (*backup_pagecount)(sqlite3_backup*);
108378  int (*backup_remaining)(sqlite3_backup*);
108379  int (*backup_step)(sqlite3_backup*,int);
108380  const char *(*compileoption_get)(int);
108381  int (*compileoption_used)(const char*);
108382  int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
108383  void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
108384  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
108385  void (*xFinal)(sqlite3_context*),
108386  void(*xDestroy)(void*));
108387  int (*db_config)(sqlite3*,int,...);
108388  sqlite3_mutex *(*db_mutex)(sqlite3*);
108389  int (*db_status)(sqlite3*,int,int*,int*,int);
108390  int (*extended_errcode)(sqlite3*);
108391  void (*log)(int,const char*,...);
108392  sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
108393  const char *(*sourceid)(void);
108394  int (*stmt_status)(sqlite3_stmt*,int,int);
108395  int (*strnicmp)(const char*,const char*,int);
108396  int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
108397  int (*wal_autocheckpoint)(sqlite3*,int);
108398  int (*wal_checkpoint)(sqlite3*,const char*);
108399  void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
108400  int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
108401  int (*vtab_config)(sqlite3*,int op,...);
108402  int (*vtab_on_conflict)(sqlite3*);
108403  /* Version 3.7.16 and later */
108404  int (*close_v2)(sqlite3*);
108405  const char *(*db_filename)(sqlite3*,const char*);
108406  int (*db_readonly)(sqlite3*,const char*);
108407  int (*db_release_memory)(sqlite3*);
108408  const char *(*errstr)(int);
108409  int (*stmt_busy)(sqlite3_stmt*);
108410  int (*stmt_readonly)(sqlite3_stmt*);
108411  int (*stricmp)(const char*,const char*);
108412  int (*uri_boolean)(const char*,const char*,int);
108413  sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
108414  const char *(*uri_parameter)(const char*,const char*);
108415  char *(*vsnprintf)(int,char*,const char*,va_list);
108416  int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
108417  /* Version 3.8.7 and later */
108418  int (*auto_extension)(void(*)(void));
108419  int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
108420  void(*)(void*));
108421  int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
108422  void(*)(void*),unsigned char);
108423  int (*cancel_auto_extension)(void(*)(void));
108424  int (*load_extension)(sqlite3*,const char*,const char*,char**);
108425  void *(*malloc64)(sqlite3_uint64);
108426  sqlite3_uint64 (*msize)(void*);
108427  void *(*realloc64)(void*,sqlite3_uint64);
108428  void (*reset_auto_extension)(void);
108429  void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
108430  void(*)(void*));
108431  void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
108432  void(*)(void*), unsigned char);
108433  int (*strglob)(const char*,const char*);
108434  /* Version 3.8.11 and later */
108435  sqlite3_value *(*value_dup)(const sqlite3_value*);
108436  void (*value_free)(sqlite3_value*);
108437  int (*result_zeroblob64)(sqlite3_context*,sqlite3_uint64);
108438  int (*bind_zeroblob64)(sqlite3_stmt*, int, sqlite3_uint64);
108439  /* Version 3.9.0 and later */
108440  unsigned int (*value_subtype)(sqlite3_value*);
108441  void (*result_subtype)(sqlite3_context*,unsigned int);
108442  /* Version 3.10.0 and later */
108443  int (*status64)(int,sqlite3_int64*,sqlite3_int64*,int);
108444  int (*strlike)(const char*,const char*,unsigned int);
108445  int (*db_cacheflush)(sqlite3*);
108446  /* Version 3.12.0 and later */
108447  int (*system_errno)(sqlite3*);
108448 };
108449 
108450 /*
108451 ** The following macros redefine the API routines so that they are
108452 ** redirected through the global sqlite3_api structure.
108453 **
108454 ** This header file is also used by the loadext.c source file
108455 ** (part of the main SQLite library - not an extension) so that
108456 ** it can get access to the sqlite3_api_routines structure
108457 ** definition. But the main library does not want to redefine
108458 ** the API. So the redefinition macros are only valid if the
108459 ** SQLITE_CORE macros is undefined.
108460 */
108461 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
108462 #define sqlite3_aggregate_context sqlite3_api->aggregate_context
108463 #ifndef SQLITE_OMIT_DEPRECATED
108464 #define sqlite3_aggregate_count sqlite3_api->aggregate_count
108465 #endif
108466 #define sqlite3_bind_blob sqlite3_api->bind_blob
108467 #define sqlite3_bind_double sqlite3_api->bind_double
108468 #define sqlite3_bind_int sqlite3_api->bind_int
108469 #define sqlite3_bind_int64 sqlite3_api->bind_int64
108470 #define sqlite3_bind_null sqlite3_api->bind_null
108471 #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
108472 #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
108473 #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
108474 #define sqlite3_bind_text sqlite3_api->bind_text
108475 #define sqlite3_bind_text16 sqlite3_api->bind_text16
108476 #define sqlite3_bind_value sqlite3_api->bind_value
108477 #define sqlite3_busy_handler sqlite3_api->busy_handler
108478 #define sqlite3_busy_timeout sqlite3_api->busy_timeout
108479 #define sqlite3_changes sqlite3_api->changes
108480 #define sqlite3_close sqlite3_api->close
108481 #define sqlite3_collation_needed sqlite3_api->collation_needed
108482 #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
108483 #define sqlite3_column_blob sqlite3_api->column_blob
108484 #define sqlite3_column_bytes sqlite3_api->column_bytes
108485 #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
108486 #define sqlite3_column_count sqlite3_api->column_count
108487 #define sqlite3_column_database_name sqlite3_api->column_database_name
108488 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
108489 #define sqlite3_column_decltype sqlite3_api->column_decltype
108490 #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
108491 #define sqlite3_column_double sqlite3_api->column_double
108492 #define sqlite3_column_int sqlite3_api->column_int
108493 #define sqlite3_column_int64 sqlite3_api->column_int64
108494 #define sqlite3_column_name sqlite3_api->column_name
108495 #define sqlite3_column_name16 sqlite3_api->column_name16
108496 #define sqlite3_column_origin_name sqlite3_api->column_origin_name
108497 #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
108498 #define sqlite3_column_table_name sqlite3_api->column_table_name
108499 #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
108500 #define sqlite3_column_text sqlite3_api->column_text
108501 #define sqlite3_column_text16 sqlite3_api->column_text16
108502 #define sqlite3_column_type sqlite3_api->column_type
108503 #define sqlite3_column_value sqlite3_api->column_value
108504 #define sqlite3_commit_hook sqlite3_api->commit_hook
108505 #define sqlite3_complete sqlite3_api->complete
108506 #define sqlite3_complete16 sqlite3_api->complete16
108507 #define sqlite3_create_collation sqlite3_api->create_collation
108508 #define sqlite3_create_collation16 sqlite3_api->create_collation16
108509 #define sqlite3_create_function sqlite3_api->create_function
108510 #define sqlite3_create_function16 sqlite3_api->create_function16
108511 #define sqlite3_create_module sqlite3_api->create_module
108512 #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
108513 #define sqlite3_data_count sqlite3_api->data_count
108514 #define sqlite3_db_handle sqlite3_api->db_handle
108515 #define sqlite3_declare_vtab sqlite3_api->declare_vtab
108516 #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
108517 #define sqlite3_errcode sqlite3_api->errcode
108518 #define sqlite3_errmsg sqlite3_api->errmsg
108519 #define sqlite3_errmsg16 sqlite3_api->errmsg16
108520 #define sqlite3_exec sqlite3_api->exec
108521 #ifndef SQLITE_OMIT_DEPRECATED
108522 #define sqlite3_expired sqlite3_api->expired
108523 #endif
108524 #define sqlite3_finalize sqlite3_api->finalize
108525 #define sqlite3_free sqlite3_api->free
108526 #define sqlite3_free_table sqlite3_api->free_table
108527 #define sqlite3_get_autocommit sqlite3_api->get_autocommit
108528 #define sqlite3_get_auxdata sqlite3_api->get_auxdata
108529 #define sqlite3_get_table sqlite3_api->get_table
108530 #ifndef SQLITE_OMIT_DEPRECATED
108531 #define sqlite3_global_recover sqlite3_api->global_recover
108532 #endif
108533 #define sqlite3_interrupt sqlite3_api->interruptx
108534 #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
108535 #define sqlite3_libversion sqlite3_api->libversion
108536 #define sqlite3_libversion_number sqlite3_api->libversion_number
108537 #define sqlite3_malloc sqlite3_api->malloc
108538 #define sqlite3_mprintf sqlite3_api->mprintf
108539 #define sqlite3_open sqlite3_api->open
108540 #define sqlite3_open16 sqlite3_api->open16
108541 #define sqlite3_prepare sqlite3_api->prepare
108542 #define sqlite3_prepare16 sqlite3_api->prepare16
108543 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
108544 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
108545 #define sqlite3_profile sqlite3_api->profile
108546 #define sqlite3_progress_handler sqlite3_api->progress_handler
108547 #define sqlite3_realloc sqlite3_api->realloc
108548 #define sqlite3_reset sqlite3_api->reset
108549 #define sqlite3_result_blob sqlite3_api->result_blob
108550 #define sqlite3_result_double sqlite3_api->result_double
108551 #define sqlite3_result_error sqlite3_api->result_error
108552 #define sqlite3_result_error16 sqlite3_api->result_error16
108553 #define sqlite3_result_int sqlite3_api->result_int
108554 #define sqlite3_result_int64 sqlite3_api->result_int64
108555 #define sqlite3_result_null sqlite3_api->result_null
108556 #define sqlite3_result_text sqlite3_api->result_text
108557 #define sqlite3_result_text16 sqlite3_api->result_text16
108558 #define sqlite3_result_text16be sqlite3_api->result_text16be
108559 #define sqlite3_result_text16le sqlite3_api->result_text16le
108560 #define sqlite3_result_value sqlite3_api->result_value
108561 #define sqlite3_rollback_hook sqlite3_api->rollback_hook
108562 #define sqlite3_set_authorizer sqlite3_api->set_authorizer
108563 #define sqlite3_set_auxdata sqlite3_api->set_auxdata
108564 #define sqlite3_snprintf sqlite3_api->snprintf
108565 #define sqlite3_step sqlite3_api->step
108566 #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
108567 #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
108568 #define sqlite3_total_changes sqlite3_api->total_changes
108569 #define sqlite3_trace sqlite3_api->trace
108570 #ifndef SQLITE_OMIT_DEPRECATED
108571 #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
108572 #endif
108573 #define sqlite3_update_hook sqlite3_api->update_hook
108574 #define sqlite3_user_data sqlite3_api->user_data
108575 #define sqlite3_value_blob sqlite3_api->value_blob
108576 #define sqlite3_value_bytes sqlite3_api->value_bytes
108577 #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
108578 #define sqlite3_value_double sqlite3_api->value_double
108579 #define sqlite3_value_int sqlite3_api->value_int
108580 #define sqlite3_value_int64 sqlite3_api->value_int64
108581 #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
108582 #define sqlite3_value_text sqlite3_api->value_text
108583 #define sqlite3_value_text16 sqlite3_api->value_text16
108584 #define sqlite3_value_text16be sqlite3_api->value_text16be
108585 #define sqlite3_value_text16le sqlite3_api->value_text16le
108586 #define sqlite3_value_type sqlite3_api->value_type
108587 #define sqlite3_vmprintf sqlite3_api->vmprintf
108588 #define sqlite3_vsnprintf sqlite3_api->vsnprintf
108589 #define sqlite3_overload_function sqlite3_api->overload_function
108590 #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
108591 #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
108592 #define sqlite3_clear_bindings sqlite3_api->clear_bindings
108593 #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
108594 #define sqlite3_blob_bytes sqlite3_api->blob_bytes
108595 #define sqlite3_blob_close sqlite3_api->blob_close
108596 #define sqlite3_blob_open sqlite3_api->blob_open
108597 #define sqlite3_blob_read sqlite3_api->blob_read
108598 #define sqlite3_blob_write sqlite3_api->blob_write
108599 #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
108600 #define sqlite3_file_control sqlite3_api->file_control
108601 #define sqlite3_memory_highwater sqlite3_api->memory_highwater
108602 #define sqlite3_memory_used sqlite3_api->memory_used
108603 #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
108604 #define sqlite3_mutex_enter sqlite3_api->mutex_enter
108605 #define sqlite3_mutex_free sqlite3_api->mutex_free
108606 #define sqlite3_mutex_leave sqlite3_api->mutex_leave
108607 #define sqlite3_mutex_try sqlite3_api->mutex_try
108608 #define sqlite3_open_v2 sqlite3_api->open_v2
108609 #define sqlite3_release_memory sqlite3_api->release_memory
108610 #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
108611 #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
108612 #define sqlite3_sleep sqlite3_api->sleep
108613 #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
108614 #define sqlite3_vfs_find sqlite3_api->vfs_find
108615 #define sqlite3_vfs_register sqlite3_api->vfs_register
108616 #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
108617 #define sqlite3_threadsafe sqlite3_api->xthreadsafe
108618 #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
108619 #define sqlite3_result_error_code sqlite3_api->result_error_code
108620 #define sqlite3_test_control sqlite3_api->test_control
108621 #define sqlite3_randomness sqlite3_api->randomness
108622 #define sqlite3_context_db_handle sqlite3_api->context_db_handle
108623 #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
108624 #define sqlite3_limit sqlite3_api->limit
108625 #define sqlite3_next_stmt sqlite3_api->next_stmt
108626 #define sqlite3_sql sqlite3_api->sql
108627 #define sqlite3_status sqlite3_api->status
108628 #define sqlite3_backup_finish sqlite3_api->backup_finish
108629 #define sqlite3_backup_init sqlite3_api->backup_init
108630 #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
108631 #define sqlite3_backup_remaining sqlite3_api->backup_remaining
108632 #define sqlite3_backup_step sqlite3_api->backup_step
108633 #define sqlite3_compileoption_get sqlite3_api->compileoption_get
108634 #define sqlite3_compileoption_used sqlite3_api->compileoption_used
108635 #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
108636 #define sqlite3_db_config sqlite3_api->db_config
108637 #define sqlite3_db_mutex sqlite3_api->db_mutex
108638 #define sqlite3_db_status sqlite3_api->db_status
108639 #define sqlite3_extended_errcode sqlite3_api->extended_errcode
108640 #define sqlite3_log sqlite3_api->log
108641 #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
108642 #define sqlite3_sourceid sqlite3_api->sourceid
108643 #define sqlite3_stmt_status sqlite3_api->stmt_status
108644 #define sqlite3_strnicmp sqlite3_api->strnicmp
108645 #define sqlite3_unlock_notify sqlite3_api->unlock_notify
108646 #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
108647 #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
108648 #define sqlite3_wal_hook sqlite3_api->wal_hook
108649 #define sqlite3_blob_reopen sqlite3_api->blob_reopen
108650 #define sqlite3_vtab_config sqlite3_api->vtab_config
108651 #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
108652 /* Version 3.7.16 and later */
108653 #define sqlite3_close_v2 sqlite3_api->close_v2
108654 #define sqlite3_db_filename sqlite3_api->db_filename
108655 #define sqlite3_db_readonly sqlite3_api->db_readonly
108656 #define sqlite3_db_release_memory sqlite3_api->db_release_memory
108657 #define sqlite3_errstr sqlite3_api->errstr
108658 #define sqlite3_stmt_busy sqlite3_api->stmt_busy
108659 #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
108660 #define sqlite3_stricmp sqlite3_api->stricmp
108661 #define sqlite3_uri_boolean sqlite3_api->uri_boolean
108662 #define sqlite3_uri_int64 sqlite3_api->uri_int64
108663 #define sqlite3_uri_parameter sqlite3_api->uri_parameter
108664 #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
108665 #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
108666 /* Version 3.8.7 and later */
108667 #define sqlite3_auto_extension sqlite3_api->auto_extension
108668 #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
108669 #define sqlite3_bind_text64 sqlite3_api->bind_text64
108670 #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
108671 #define sqlite3_load_extension sqlite3_api->load_extension
108672 #define sqlite3_malloc64 sqlite3_api->malloc64
108673 #define sqlite3_msize sqlite3_api->msize
108674 #define sqlite3_realloc64 sqlite3_api->realloc64
108675 #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
108676 #define sqlite3_result_blob64 sqlite3_api->result_blob64
108677 #define sqlite3_result_text64 sqlite3_api->result_text64
108678 #define sqlite3_strglob sqlite3_api->strglob
108679 /* Version 3.8.11 and later */
108680 #define sqlite3_value_dup sqlite3_api->value_dup
108681 #define sqlite3_value_free sqlite3_api->value_free
108682 #define sqlite3_result_zeroblob64 sqlite3_api->result_zeroblob64
108683 #define sqlite3_bind_zeroblob64 sqlite3_api->bind_zeroblob64
108684 /* Version 3.9.0 and later */
108685 #define sqlite3_value_subtype sqlite3_api->value_subtype
108686 #define sqlite3_result_subtype sqlite3_api->result_subtype
108687 /* Version 3.10.0 and later */
108688 #define sqlite3_status64 sqlite3_api->status64
108689 #define sqlite3_strlike sqlite3_api->strlike
108690 #define sqlite3_db_cacheflush sqlite3_api->db_cacheflush
108691 /* Version 3.12.0 and later */
108692 #define sqlite3_system_errno sqlite3_api->system_errno
108693 #endif /* !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION) */
108694 
108695 #if !defined(SQLITE_CORE) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
108696  /* This case when the file really is being compiled as a loadable
108697  ** extension */
108698 # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
108699 # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
108700 # define SQLITE_EXTENSION_INIT3 \
108701  extern const sqlite3_api_routines *sqlite3_api;
108702 #else
108703  /* This case when the file is being statically linked into the
108704  ** application */
108705 # define SQLITE_EXTENSION_INIT1 /*no-op*/
108706 # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
108707 # define SQLITE_EXTENSION_INIT3 /*no-op*/
108708 #endif
108709 
108710 #endif /* _SQLITE3EXT_H_ */
108711 
108712 /************** End of sqlite3ext.h ******************************************/
108713 /************** Continuing where we left off in loadext.c ********************/
108714 /* #include "sqliteInt.h" */
108715 /* #include <string.h> */
108716 
108717 #ifndef SQLITE_OMIT_LOAD_EXTENSION
108718 
108719 /*
108720 ** Some API routines are omitted when various features are
108721 ** excluded from a build of SQLite. Substitute a NULL pointer
108722 ** for any missing APIs.
108723 */
108724 #ifndef SQLITE_ENABLE_COLUMN_METADATA
108725 # define sqlite3_column_database_name 0
108726 # define sqlite3_column_database_name16 0
108727 # define sqlite3_column_table_name 0
108728 # define sqlite3_column_table_name16 0
108729 # define sqlite3_column_origin_name 0
108730 # define sqlite3_column_origin_name16 0
108731 #endif
108732 
108733 #ifdef SQLITE_OMIT_AUTHORIZATION
108734 # define sqlite3_set_authorizer 0
108735 #endif
108736 
108737 #ifdef SQLITE_OMIT_UTF16
108738 # define sqlite3_bind_text16 0
108739 # define sqlite3_collation_needed16 0
108740 # define sqlite3_column_decltype16 0
108741 # define sqlite3_column_name16 0
108742 # define sqlite3_column_text16 0
108743 # define sqlite3_complete16 0
108744 # define sqlite3_create_collation16 0
108745 # define sqlite3_create_function16 0
108746 # define sqlite3_errmsg16 0
108747 # define sqlite3_open16 0
108748 # define sqlite3_prepare16 0
108749 # define sqlite3_prepare16_v2 0
108750 # define sqlite3_result_error16 0
108751 # define sqlite3_result_text16 0
108752 # define sqlite3_result_text16be 0
108753 # define sqlite3_result_text16le 0
108754 # define sqlite3_value_text16 0
108755 # define sqlite3_value_text16be 0
108756 # define sqlite3_value_text16le 0
108757 # define sqlite3_column_database_name16 0
108758 # define sqlite3_column_table_name16 0
108759 # define sqlite3_column_origin_name16 0
108760 #endif
108761 
108762 #ifdef SQLITE_OMIT_COMPLETE
108763 # define sqlite3_complete 0
108764 # define sqlite3_complete16 0
108765 #endif
108766 
108767 #ifdef SQLITE_OMIT_DECLTYPE
108768 # define sqlite3_column_decltype16 0
108769 # define sqlite3_column_decltype 0
108770 #endif
108771 
108772 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
108773 # define sqlite3_progress_handler 0
108774 #endif
108775 
108776 #ifdef SQLITE_OMIT_VIRTUALTABLE
108777 # define sqlite3_create_module 0
108778 # define sqlite3_create_module_v2 0
108779 # define sqlite3_declare_vtab 0
108780 # define sqlite3_vtab_config 0
108781 # define sqlite3_vtab_on_conflict 0
108782 #endif
108783 
108784 #ifdef SQLITE_OMIT_SHARED_CACHE
108785 # define sqlite3_enable_shared_cache 0
108786 #endif
108787 
108788 #ifdef SQLITE_OMIT_TRACE
108789 # define sqlite3_profile 0
108790 # define sqlite3_trace 0
108791 #endif
108792 
108793 #ifdef SQLITE_OMIT_GET_TABLE
108794 # define sqlite3_free_table 0
108795 # define sqlite3_get_table 0
108796 #endif
108797 
108798 #ifdef SQLITE_OMIT_INCRBLOB
108799 #define sqlite3_bind_zeroblob 0
108800 #define sqlite3_blob_bytes 0
108801 #define sqlite3_blob_close 0
108802 #define sqlite3_blob_open 0
108803 #define sqlite3_blob_read 0
108804 #define sqlite3_blob_write 0
108805 #define sqlite3_blob_reopen 0
108806 #endif
108807 
108808 /*
108809 ** The following structure contains pointers to all SQLite API routines.
108810 ** A pointer to this structure is passed into extensions when they are
108811 ** loaded so that the extension can make calls back into the SQLite
108812 ** library.
108813 **
108814 ** When adding new APIs, add them to the bottom of this structure
108815 ** in order to preserve backwards compatibility.
108816 **
108817 ** Extensions that use newer APIs should first call the
108818 ** sqlite3_libversion_number() to make sure that the API they
108819 ** intend to use is supported by the library. Extensions should
108820 ** also check to make sure that the pointer to the function is
108821 ** not NULL before calling it.
108822 */
108825 #ifndef SQLITE_OMIT_DEPRECATED
108827 #else
108828  0,
108829 #endif
108843  sqlite3_changes,
108844  sqlite3_close,
108880  sqlite3_errcode,
108881  sqlite3_errmsg,
108883  sqlite3_exec,
108884 #ifndef SQLITE_OMIT_DEPRECATED
108885  sqlite3_expired,
108886 #else
108887  0,
108888 #endif
108890  sqlite3_free,
108895  0, /* Was sqlite3_global_recover(), but that function is deprecated */
108900  sqlite3_malloc,
108901  sqlite3_mprintf,
108902  sqlite3_open,
108903  sqlite3_open16,
108904  sqlite3_prepare,
108906  sqlite3_profile,
108908  sqlite3_realloc,
108909  sqlite3_reset,
108926  sqlite3_step,
108928 #ifndef SQLITE_OMIT_DEPRECATED
108930 #else
108931  0,
108932 #endif
108934  sqlite3_trace,
108935 #ifndef SQLITE_OMIT_DEPRECATED
108937 #else
108938  0,
108939 #endif
108955  /*
108956  ** The original API set ends here. All extensions can call any
108957  ** of the APIs above provided that the pointer is not NULL. But
108958  ** before calling APIs that follow, extension should check the
108959  ** sqlite3_libversion_number() to make sure they are dealing with
108960  ** a library that is new enough to support that API.
108961  *************************************************************************
108962  */
108964 
108965  /*
108966  ** Added after 3.3.13
108967  */
108971 
108972  /*
108973  ** Added for 3.4.1
108974  */
108976 
108977  /*
108978  ** Added for 3.5.0
108979  */
108990 #ifdef SQLITE_MUTEX_OMIT
108991  0,
108992  0,
108993  0,
108994  0,
108995  0,
108996 #else
109002 #endif
109003  sqlite3_open_v2,
109007  sqlite3_sleep,
109012 
109013  /*
109014  ** Added for 3.5.8
109015  */
109022 
109023  /*
109024  ** Added for 3.6.0
109025  */
109027  sqlite3_limit,
109029  sqlite3_sql,
109030  sqlite3_status,
109031 
109032  /*
109033  ** Added for 3.7.4
109034  */
109040 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
109043 #else
109044  0,
109045  0,
109046 #endif
109052  sqlite3_log,
109057 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
109059 #else
109060  0,
109061 #endif
109062 #ifndef SQLITE_OMIT_WAL
109066 #else
109067  0,
109068  0,
109069  0,
109070 #endif
109078  sqlite3_errstr,
109081  sqlite3_stricmp,
109087  /* Version 3.8.7 and later */
109094  sqlite3_msize,
109099  sqlite3_strglob,
109100  /* Version 3.8.11 and later */
109105  /* Version 3.9.0 and later */
109108  /* Version 3.10.0 and later */
109110  sqlite3_strlike,
109112  /* Version 3.12.0 and later */
109114 };
109115 
109116 /*
109117 ** Attempt to load an SQLite extension library contained in the file
109118 ** zFile. The entry point is zProc. zProc may be 0 in which case a
109119 ** default entry point name (sqlite3_extension_init) is used. Use
109120 ** of the default name is recommended.
109121 **
109122 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
109123 **
109124 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
109125 ** error message text. The calling function should free this memory
109126 ** by calling sqlite3DbFree(db, ).
109127 */
109129  sqlite3 *db, /* Load the extension into this database connection */
109130  const char *zFile, /* Name of the shared library containing extension */
109131  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
109132  char **pzErrMsg /* Put error message here if not 0 */
109133 ){
109134  sqlite3_vfs *pVfs = db->pVfs;
109135  void *handle;
109136  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
109137  char *zErrmsg = 0;
109138  const char *zEntry;
109139  char *zAltEntry = 0;
109140  void **aHandle;
109141  u64 nMsg = 300 + sqlite3Strlen30(zFile);
109142  int ii;
109143 
109144  /* Shared library endings to try if zFile cannot be loaded as written */
109145  static const char *azEndings[] = {
109146 #if SQLITE_OS_WIN
109147  "dll"
109148 #elif defined(__APPLE__)
109149  "dylib"
109150 #else
109151  "so"
109152 #endif
109153  };
109154 
109155 
109156  if( pzErrMsg ) *pzErrMsg = 0;
109157 
109158  /* Ticket #1863. To avoid a creating security problems for older
109159  ** applications that relink against newer versions of SQLite, the
109160  ** ability to run load_extension is turned off by default. One
109161  ** must call either sqlite3_enable_load_extension(db) or
109162  ** sqlite3_db_config(db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, 1, 0)
109163  ** to turn on extension loading.
109164  */
109165  if( (db->flags & SQLITE_LoadExtension)==0 ){
109166  if( pzErrMsg ){
109167  *pzErrMsg = sqlite3_mprintf("not authorized");
109168  }
109169  return SQLITE_ERROR;
109170  }
109171 
109172  zEntry = zProc ? zProc : "sqlite3_extension_init";
109173 
109174  handle = sqlite3OsDlOpen(pVfs, zFile);
109175 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
109176  for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
109177  char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
109178  if( zAltFile==0 ) return SQLITE_NOMEM_BKPT;
109179  handle = sqlite3OsDlOpen(pVfs, zAltFile);
109180  sqlite3_free(zAltFile);
109181  }
109182 #endif
109183  if( handle==0 ){
109184  if( pzErrMsg ){
109185  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109186  if( zErrmsg ){
109187  sqlite3_snprintf(nMsg, zErrmsg,
109188  "unable to open shared library [%s]", zFile);
109189  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109190  }
109191  }
109192  return SQLITE_ERROR;
109193  }
109194  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
109195  sqlite3OsDlSym(pVfs, handle, zEntry);
109196 
109197  /* If no entry point was specified and the default legacy
109198  ** entry point name "sqlite3_extension_init" was not found, then
109199  ** construct an entry point name "sqlite3_X_init" where the X is
109200  ** replaced by the lowercase value of every ASCII alphabetic
109201  ** character in the filename after the last "/" upto the first ".",
109202  ** and eliding the first three characters if they are "lib".
109203  ** Examples:
109204  **
109205  ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
109206  ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
109207  */
109208  if( xInit==0 && zProc==0 ){
109209  int iFile, iEntry, c;
109210  int ncFile = sqlite3Strlen30(zFile);
109211  zAltEntry = sqlite3_malloc64(ncFile+30);
109212  if( zAltEntry==0 ){
109213  sqlite3OsDlClose(pVfs, handle);
109214  return SQLITE_NOMEM_BKPT;
109215  }
109216  memcpy(zAltEntry, "sqlite3_", 8);
109217  for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
109218  iFile++;
109219  if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
109220  for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
109221  if( sqlite3Isalpha(c) ){
109222  zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
109223  }
109224  }
109225  memcpy(zAltEntry+iEntry, "_init", 6);
109226  zEntry = zAltEntry;
109227  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
109228  sqlite3OsDlSym(pVfs, handle, zEntry);
109229  }
109230  if( xInit==0 ){
109231  if( pzErrMsg ){
109232  nMsg += sqlite3Strlen30(zEntry);
109233  *pzErrMsg = zErrmsg = sqlite3_malloc64(nMsg);
109234  if( zErrmsg ){
109235  sqlite3_snprintf(nMsg, zErrmsg,
109236  "no entry point [%s] in shared library [%s]", zEntry, zFile);
109237  sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
109238  }
109239  }
109240  sqlite3OsDlClose(pVfs, handle);
109241  sqlite3_free(zAltEntry);
109242  return SQLITE_ERROR;
109243  }
109244  sqlite3_free(zAltEntry);
109245  if( xInit(db, &zErrmsg, &sqlite3Apis) ){
109246  if( pzErrMsg ){
109247  *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
109248  }
109249  sqlite3_free(zErrmsg);
109250  sqlite3OsDlClose(pVfs, handle);
109251  return SQLITE_ERROR;
109252  }
109253 
109254  /* Append the new shared library handle to the db->aExtension array. */
109255  aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
109256  if( aHandle==0 ){
109257  return SQLITE_NOMEM_BKPT;
109258  }
109259  if( db->nExtension>0 ){
109260  memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
109261  }
109262  sqlite3DbFree(db, db->aExtension);
109263  db->aExtension = aHandle;
109264 
109265  db->aExtension[db->nExtension++] = handle;
109266  return SQLITE_OK;
109267 }
109269  sqlite3 *db, /* Load the extension into this database connection */
109270  const char *zFile, /* Name of the shared library containing extension */
109271  const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
109272  char **pzErrMsg /* Put error message here if not 0 */
109273 ){
109274  int rc;
109275  sqlite3_mutex_enter(db->mutex);
109276  rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
109277  rc = sqlite3ApiExit(db, rc);
109278  sqlite3_mutex_leave(db->mutex);
109279  return rc;
109280 }
109281 
109282 /*
109283 ** Call this routine when the database connection is closing in order
109284 ** to clean up loaded extensions
109285 */
109287  int i;
109288  assert( sqlite3_mutex_held(db->mutex) );
109289  for(i=0; i<db->nExtension; i++){
109290  sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
109291  }
109292  sqlite3DbFree(db, db->aExtension);
109293 }
109294 
109295 /*
109296 ** Enable or disable extension loading. Extension loading is disabled by
109297 ** default so as not to open security holes in older applications.
109298 */
109300  sqlite3_mutex_enter(db->mutex);
109301  if( onoff ){
109303  }else{
109305  }
109306  sqlite3_mutex_leave(db->mutex);
109307  return SQLITE_OK;
109308 }
109309 
109310 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
109311 
109312 /*
109313 ** The auto-extension code added regardless of whether or not extension
109314 ** loading is supported. We need a dummy sqlite3Apis pointer for that
109315 ** code if regular extension loading is not available. This is that
109316 ** dummy pointer.
109317 */
109318 #ifdef SQLITE_OMIT_LOAD_EXTENSION
109319 static const sqlite3_api_routines sqlite3Apis = { 0 };
109320 #endif
109321 
109322 
109323 /*
109324 ** The following object holds the list of automatically loaded
109325 ** extensions.
109326 **
109327 ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
109328 ** mutex must be held while accessing this list.
109329 */
109332  u32 nExt; /* Number of entries in aExt[] */
109333  void (**aExt)(void); /* Pointers to the extension init functions */
109334 } sqlite3Autoext = { 0, 0 };
109335 
109336 /* The "wsdAutoext" macro will resolve to the autoextension
109337 ** state vector. If writable static data is unsupported on the target,
109338 ** we have to locate the state vector at run-time. In the more common
109339 ** case where writable static data is supported, wsdStat can refer directly
109340 ** to the "sqlite3Autoext" state vector declared above.
109341 */
109342 #ifdef SQLITE_OMIT_WSD
109343 # define wsdAutoextInit \
109344  sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
109345 # define wsdAutoext x[0]
109346 #else
109347 # define wsdAutoextInit
109348 # define wsdAutoext sqlite3Autoext
109349 #endif
109350 
109351 
109352 /*
109353 ** Register a statically linked extension that is automatically
109354 ** loaded by every new database connection.
109355 */
109357  int rc = SQLITE_OK;
109358 #ifndef SQLITE_OMIT_AUTOINIT
109359  rc = sqlite3_initialize();
109360  if( rc ){
109361  return rc;
109362  }else
109363 #endif
109364  {
109365  u32 i;
109366 #if SQLITE_THREADSAFE
109368 #endif
109369  wsdAutoextInit;
109370  sqlite3_mutex_enter(mutex);
109371  for(i=0; i<wsdAutoext.nExt; i++){
109372  if( wsdAutoext.aExt[i]==xInit ) break;
109373  }
109374  if( i==wsdAutoext.nExt ){
109375  u64 nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
109376  void (**aNew)(void);
109377  aNew = sqlite3_realloc64(wsdAutoext.aExt, nByte);
109378  if( aNew==0 ){
109379  rc = SQLITE_NOMEM_BKPT;
109380  }else{
109381  wsdAutoext.aExt = aNew;
109382  wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
109383  wsdAutoext.nExt++;
109384  }
109385  }
109386  sqlite3_mutex_leave(mutex);
109387  assert( (rc&0xff)==rc );
109388  return rc;
109389  }
109390 }
109391 
109392 /*
109393 ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
109394 ** set of routines that is invoked for each new database connection, if it
109395 ** is currently on the list. If xInit is not on the list, then this
109396 ** routine is a no-op.
109397 **
109398 ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
109399 ** was not on the list.
109400 */
109402 #if SQLITE_THREADSAFE
109404 #endif
109405  int i;
109406  int n = 0;
109407  wsdAutoextInit;
109408  sqlite3_mutex_enter(mutex);
109409  for(i=(int)wsdAutoext.nExt-1; i>=0; i--){
109410  if( wsdAutoext.aExt[i]==xInit ){
109411  wsdAutoext.nExt--;
109412  wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
109413  n++;
109414  break;
109415  }
109416  }
109417  sqlite3_mutex_leave(mutex);
109418  return n;
109419 }
109420 
109421 /*
109422 ** Reset the automatic extension loading mechanism.
109423 */
109425 #ifndef SQLITE_OMIT_AUTOINIT
109426  if( sqlite3_initialize()==SQLITE_OK )
109427 #endif
109428  {
109429 #if SQLITE_THREADSAFE
109431 #endif
109432  wsdAutoextInit;
109433  sqlite3_mutex_enter(mutex);
109434  sqlite3_free(wsdAutoext.aExt);
109435  wsdAutoext.aExt = 0;
109436  wsdAutoext.nExt = 0;
109437  sqlite3_mutex_leave(mutex);
109438  }
109439 }
109440 
109441 /*
109442 ** Load all automatic extensions.
109443 **
109444 ** If anything goes wrong, set an error in the database connection.
109445 */
109447  u32 i;
109448  int go = 1;
109449  int rc;
109450  int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
109451 
109452  wsdAutoextInit;
109453  if( wsdAutoext.nExt==0 ){
109454  /* Common case: early out without every having to acquire a mutex */
109455  return;
109456  }
109457  for(i=0; go; i++){
109458  char *zErrmsg;
109459 #if SQLITE_THREADSAFE
109461 #endif
109462  sqlite3_mutex_enter(mutex);
109463  if( i>=wsdAutoext.nExt ){
109464  xInit = 0;
109465  go = 0;
109466  }else{
109467  xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
109468  wsdAutoext.aExt[i];
109469  }
109470  sqlite3_mutex_leave(mutex);
109471  zErrmsg = 0;
109472  if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
109473  sqlite3ErrorWithMsg(db, rc,
109474  "automatic extension loading failed: %s", zErrmsg);
109475  go = 0;
109476  }
109477  sqlite3_free(zErrmsg);
109478  }
109479 }
109480 
109481 /************** End of loadext.c *********************************************/
109482 /************** Begin file pragma.c ******************************************/
109483 /*
109484 ** 2003 April 6
109485 **
109486 ** The author disclaims copyright to this source code. In place of
109487 ** a legal notice, here is a blessing:
109488 **
109489 ** May you do good and not evil.
109490 ** May you find forgiveness for yourself and forgive others.
109491 ** May you share freely, never taking more than you give.
109492 **
109493 *************************************************************************
109494 ** This file contains code used to implement the PRAGMA command.
109495 */
109496 /* #include "sqliteInt.h" */
109497 
109498 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
109499 # if defined(__APPLE__)
109500 # define SQLITE_ENABLE_LOCKING_STYLE 1
109501 # else
109502 # define SQLITE_ENABLE_LOCKING_STYLE 0
109503 # endif
109504 #endif
109505 
109506 /***************************************************************************
109507 ** The "pragma.h" include file is an automatically generated file that
109508 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
109509 ** object. This ensures that the aPragmaName[] table is arranged in
109510 ** lexicographical order to facility a binary search of the pragma name.
109511 ** Do not edit pragma.h directly. Edit and rerun the script in at
109512 ** ../tool/mkpragmatab.tcl. */
109513 /************** Include pragma.h in the middle of pragma.c *******************/
109514 /************** Begin file pragma.h ******************************************/
109515 /* DO NOT EDIT!
109516 ** This file is automatically generated by the script at
109517 ** ../tool/mkpragmatab.tcl. To update the set of pragmas, edit
109518 ** that script and rerun it.
109519 */
109520 #define PragTyp_HEADER_VALUE 0
109521 #define PragTyp_AUTO_VACUUM 1
109522 #define PragTyp_FLAG 2
109523 #define PragTyp_BUSY_TIMEOUT 3
109524 #define PragTyp_CACHE_SIZE 4
109525 #define PragTyp_CACHE_SPILL 5
109526 #define PragTyp_CASE_SENSITIVE_LIKE 6
109527 #define PragTyp_COLLATION_LIST 7
109528 #define PragTyp_COMPILE_OPTIONS 8
109529 #define PragTyp_DATA_STORE_DIRECTORY 9
109530 #define PragTyp_DATABASE_LIST 10
109531 #define PragTyp_DEFAULT_CACHE_SIZE 11
109532 #define PragTyp_ENCODING 12
109533 #define PragTyp_FOREIGN_KEY_CHECK 13
109534 #define PragTyp_FOREIGN_KEY_LIST 14
109535 #define PragTyp_INCREMENTAL_VACUUM 15
109536 #define PragTyp_INDEX_INFO 16
109537 #define PragTyp_INDEX_LIST 17
109538 #define PragTyp_INTEGRITY_CHECK 18
109539 #define PragTyp_JOURNAL_MODE 19
109540 #define PragTyp_JOURNAL_SIZE_LIMIT 20
109541 #define PragTyp_LOCK_PROXY_FILE 21
109542 #define PragTyp_LOCKING_MODE 22
109543 #define PragTyp_PAGE_COUNT 23
109544 #define PragTyp_MMAP_SIZE 24
109545 #define PragTyp_PAGE_SIZE 25
109546 #define PragTyp_SECURE_DELETE 26
109547 #define PragTyp_SHRINK_MEMORY 27
109548 #define PragTyp_SOFT_HEAP_LIMIT 28
109549 #define PragTyp_STATS 29
109550 #define PragTyp_SYNCHRONOUS 30
109551 #define PragTyp_TABLE_INFO 31
109552 #define PragTyp_TEMP_STORE 32
109553 #define PragTyp_TEMP_STORE_DIRECTORY 33
109554 #define PragTyp_THREADS 34
109555 #define PragTyp_WAL_AUTOCHECKPOINT 35
109556 #define PragTyp_WAL_CHECKPOINT 36
109557 #define PragTyp_ACTIVATE_EXTENSIONS 37
109558 #define PragTyp_HEXKEY 38
109559 #define PragTyp_KEY 39
109560 #define PragTyp_REKEY 40
109561 #define PragTyp_LOCK_STATUS 41
109562 #define PragTyp_PARSER_TRACE 42
109563 #define PragFlag_NeedSchema 0x01
109564 #define PragFlag_ReadOnly 0x02
109565 static const struct sPragmaNames {
109566  const char *const zName; /* Name of pragma */
109567  u8 ePragTyp; /* PragTyp_XXX value */
109568  u8 mPragFlag; /* Zero or more PragFlag_XXX values */
109569  u32 iArg; /* Extra argument */
109570 } aPragmaNames[] = {
109571 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
109572  { /* zName: */ "activate_extensions",
109573  /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
109574  /* ePragFlag: */ 0,
109575  /* iArg: */ 0 },
109576 #endif
109577 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
109578  { /* zName: */ "application_id",
109579  /* ePragTyp: */ PragTyp_HEADER_VALUE,
109580  /* ePragFlag: */ 0,
109581  /* iArg: */ BTREE_APPLICATION_ID },
109582 #endif
109583 #if !defined(SQLITE_OMIT_AUTOVACUUM)
109584  { /* zName: */ "auto_vacuum",
109585  /* ePragTyp: */ PragTyp_AUTO_VACUUM,
109586  /* ePragFlag: */ PragFlag_NeedSchema,
109587  /* iArg: */ 0 },
109588 #endif
109589 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109590 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
109591  { /* zName: */ "automatic_index",
109592  /* ePragTyp: */ PragTyp_FLAG,
109593  /* ePragFlag: */ 0,
109594  /* iArg: */ SQLITE_AutoIndex },
109595 #endif
109596 #endif
109597  { /* zName: */ "busy_timeout",
109598  /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
109599  /* ePragFlag: */ 0,
109600  /* iArg: */ 0 },
109601 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109602  { /* zName: */ "cache_size",
109603  /* ePragTyp: */ PragTyp_CACHE_SIZE,
109604  /* ePragFlag: */ PragFlag_NeedSchema,
109605  /* iArg: */ 0 },
109606 #endif
109607 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109608  { /* zName: */ "cache_spill",
109609  /* ePragTyp: */ PragTyp_CACHE_SPILL,
109610  /* ePragFlag: */ 0,
109611  /* iArg: */ 0 },
109612 #endif
109613  { /* zName: */ "case_sensitive_like",
109614  /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
109615  /* ePragFlag: */ 0,
109616  /* iArg: */ 0 },
109617  { /* zName: */ "cell_size_check",
109618  /* ePragTyp: */ PragTyp_FLAG,
109619  /* ePragFlag: */ 0,
109620  /* iArg: */ SQLITE_CellSizeCk },
109621 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109622  { /* zName: */ "checkpoint_fullfsync",
109623  /* ePragTyp: */ PragTyp_FLAG,
109624  /* ePragFlag: */ 0,
109625  /* iArg: */ SQLITE_CkptFullFSync },
109626 #endif
109627 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
109628  { /* zName: */ "collation_list",
109629  /* ePragTyp: */ PragTyp_COLLATION_LIST,
109630  /* ePragFlag: */ 0,
109631  /* iArg: */ 0 },
109632 #endif
109633 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
109634  { /* zName: */ "compile_options",
109635  /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
109636  /* ePragFlag: */ 0,
109637  /* iArg: */ 0 },
109638 #endif
109639 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109640  { /* zName: */ "count_changes",
109641  /* ePragTyp: */ PragTyp_FLAG,
109642  /* ePragFlag: */ 0,
109643  /* iArg: */ SQLITE_CountRows },
109644 #endif
109645 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
109646  { /* zName: */ "data_store_directory",
109647  /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
109648  /* ePragFlag: */ 0,
109649  /* iArg: */ 0 },
109650 #endif
109651 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
109652  { /* zName: */ "data_version",
109653  /* ePragTyp: */ PragTyp_HEADER_VALUE,
109654  /* ePragFlag: */ PragFlag_ReadOnly,
109655  /* iArg: */ BTREE_DATA_VERSION },
109656 #endif
109657 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
109658  { /* zName: */ "database_list",
109659  /* ePragTyp: */ PragTyp_DATABASE_LIST,
109660  /* ePragFlag: */ PragFlag_NeedSchema,
109661  /* iArg: */ 0 },
109662 #endif
109663 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
109664  { /* zName: */ "default_cache_size",
109665  /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
109666  /* ePragFlag: */ PragFlag_NeedSchema,
109667  /* iArg: */ 0 },
109668 #endif
109669 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109670 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
109671  { /* zName: */ "defer_foreign_keys",
109672  /* ePragTyp: */ PragTyp_FLAG,
109673  /* ePragFlag: */ 0,
109674  /* iArg: */ SQLITE_DeferFKs },
109675 #endif
109676 #endif
109677 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109678  { /* zName: */ "empty_result_callbacks",
109679  /* ePragTyp: */ PragTyp_FLAG,
109680  /* ePragFlag: */ 0,
109681  /* iArg: */ SQLITE_NullCallback },
109682 #endif
109683 #if !defined(SQLITE_OMIT_UTF16)
109684  { /* zName: */ "encoding",
109685  /* ePragTyp: */ PragTyp_ENCODING,
109686  /* ePragFlag: */ 0,
109687  /* iArg: */ 0 },
109688 #endif
109689 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
109690  { /* zName: */ "foreign_key_check",
109691  /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
109692  /* ePragFlag: */ PragFlag_NeedSchema,
109693  /* iArg: */ 0 },
109694 #endif
109695 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
109696  { /* zName: */ "foreign_key_list",
109697  /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
109698  /* ePragFlag: */ PragFlag_NeedSchema,
109699  /* iArg: */ 0 },
109700 #endif
109701 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109702 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
109703  { /* zName: */ "foreign_keys",
109704  /* ePragTyp: */ PragTyp_FLAG,
109705  /* ePragFlag: */ 0,
109706  /* iArg: */ SQLITE_ForeignKeys },
109707 #endif
109708 #endif
109709 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
109710  { /* zName: */ "freelist_count",
109711  /* ePragTyp: */ PragTyp_HEADER_VALUE,
109712  /* ePragFlag: */ PragFlag_ReadOnly,
109713  /* iArg: */ BTREE_FREE_PAGE_COUNT },
109714 #endif
109715 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109716  { /* zName: */ "full_column_names",
109717  /* ePragTyp: */ PragTyp_FLAG,
109718  /* ePragFlag: */ 0,
109719  /* iArg: */ SQLITE_FullColNames },
109720  { /* zName: */ "fullfsync",
109721  /* ePragTyp: */ PragTyp_FLAG,
109722  /* ePragFlag: */ 0,
109723  /* iArg: */ SQLITE_FullFSync },
109724 #endif
109725 #if defined(SQLITE_HAS_CODEC)
109726  { /* zName: */ "hexkey",
109727  /* ePragTyp: */ PragTyp_HEXKEY,
109728  /* ePragFlag: */ 0,
109729  /* iArg: */ 0 },
109730  { /* zName: */ "hexrekey",
109731  /* ePragTyp: */ PragTyp_HEXKEY,
109732  /* ePragFlag: */ 0,
109733  /* iArg: */ 0 },
109734 #endif
109735 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109736 #if !defined(SQLITE_OMIT_CHECK)
109737  { /* zName: */ "ignore_check_constraints",
109738  /* ePragTyp: */ PragTyp_FLAG,
109739  /* ePragFlag: */ 0,
109740  /* iArg: */ SQLITE_IgnoreChecks },
109741 #endif
109742 #endif
109743 #if !defined(SQLITE_OMIT_AUTOVACUUM)
109744  { /* zName: */ "incremental_vacuum",
109745  /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
109746  /* ePragFlag: */ PragFlag_NeedSchema,
109747  /* iArg: */ 0 },
109748 #endif
109749 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
109750  { /* zName: */ "index_info",
109751  /* ePragTyp: */ PragTyp_INDEX_INFO,
109752  /* ePragFlag: */ PragFlag_NeedSchema,
109753  /* iArg: */ 0 },
109754  { /* zName: */ "index_list",
109755  /* ePragTyp: */ PragTyp_INDEX_LIST,
109756  /* ePragFlag: */ PragFlag_NeedSchema,
109757  /* iArg: */ 0 },
109758  { /* zName: */ "index_xinfo",
109759  /* ePragTyp: */ PragTyp_INDEX_INFO,
109760  /* ePragFlag: */ PragFlag_NeedSchema,
109761  /* iArg: */ 1 },
109762 #endif
109763 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
109764  { /* zName: */ "integrity_check",
109765  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
109766  /* ePragFlag: */ PragFlag_NeedSchema,
109767  /* iArg: */ 0 },
109768 #endif
109769 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109770  { /* zName: */ "journal_mode",
109771  /* ePragTyp: */ PragTyp_JOURNAL_MODE,
109772  /* ePragFlag: */ PragFlag_NeedSchema,
109773  /* iArg: */ 0 },
109774  { /* zName: */ "journal_size_limit",
109775  /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
109776  /* ePragFlag: */ 0,
109777  /* iArg: */ 0 },
109778 #endif
109779 #if defined(SQLITE_HAS_CODEC)
109780  { /* zName: */ "key",
109781  /* ePragTyp: */ PragTyp_KEY,
109782  /* ePragFlag: */ 0,
109783  /* iArg: */ 0 },
109784 #endif
109785 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109786  { /* zName: */ "legacy_file_format",
109787  /* ePragTyp: */ PragTyp_FLAG,
109788  /* ePragFlag: */ 0,
109789  /* iArg: */ SQLITE_LegacyFileFmt },
109790 #endif
109791 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
109792  { /* zName: */ "lock_proxy_file",
109793  /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
109794  /* ePragFlag: */ 0,
109795  /* iArg: */ 0 },
109796 #endif
109797 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
109798  { /* zName: */ "lock_status",
109799  /* ePragTyp: */ PragTyp_LOCK_STATUS,
109800  /* ePragFlag: */ 0,
109801  /* iArg: */ 0 },
109802 #endif
109803 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109804  { /* zName: */ "locking_mode",
109805  /* ePragTyp: */ PragTyp_LOCKING_MODE,
109806  /* ePragFlag: */ 0,
109807  /* iArg: */ 0 },
109808  { /* zName: */ "max_page_count",
109809  /* ePragTyp: */ PragTyp_PAGE_COUNT,
109810  /* ePragFlag: */ PragFlag_NeedSchema,
109811  /* iArg: */ 0 },
109812  { /* zName: */ "mmap_size",
109813  /* ePragTyp: */ PragTyp_MMAP_SIZE,
109814  /* ePragFlag: */ 0,
109815  /* iArg: */ 0 },
109816  { /* zName: */ "page_count",
109817  /* ePragTyp: */ PragTyp_PAGE_COUNT,
109818  /* ePragFlag: */ PragFlag_NeedSchema,
109819  /* iArg: */ 0 },
109820  { /* zName: */ "page_size",
109821  /* ePragTyp: */ PragTyp_PAGE_SIZE,
109822  /* ePragFlag: */ 0,
109823  /* iArg: */ 0 },
109824 #endif
109825 #if defined(SQLITE_DEBUG) && !defined(SQLITE_OMIT_PARSER_TRACE)
109826  { /* zName: */ "parser_trace",
109827  /* ePragTyp: */ PragTyp_PARSER_TRACE,
109828  /* ePragFlag: */ 0,
109829  /* iArg: */ 0 },
109830 #endif
109831 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109832  { /* zName: */ "query_only",
109833  /* ePragTyp: */ PragTyp_FLAG,
109834  /* ePragFlag: */ 0,
109835  /* iArg: */ SQLITE_QueryOnly },
109836 #endif
109837 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
109838  { /* zName: */ "quick_check",
109839  /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
109840  /* ePragFlag: */ PragFlag_NeedSchema,
109841  /* iArg: */ 0 },
109842 #endif
109843 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109844  { /* zName: */ "read_uncommitted",
109845  /* ePragTyp: */ PragTyp_FLAG,
109846  /* ePragFlag: */ 0,
109847  /* iArg: */ SQLITE_ReadUncommitted },
109848  { /* zName: */ "recursive_triggers",
109849  /* ePragTyp: */ PragTyp_FLAG,
109850  /* ePragFlag: */ 0,
109851  /* iArg: */ SQLITE_RecTriggers },
109852 #endif
109853 #if defined(SQLITE_HAS_CODEC)
109854  { /* zName: */ "rekey",
109855  /* ePragTyp: */ PragTyp_REKEY,
109856  /* ePragFlag: */ 0,
109857  /* iArg: */ 0 },
109858 #endif
109859 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109860  { /* zName: */ "reverse_unordered_selects",
109861  /* ePragTyp: */ PragTyp_FLAG,
109862  /* ePragFlag: */ 0,
109863  /* iArg: */ SQLITE_ReverseOrder },
109864 #endif
109865 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
109866  { /* zName: */ "schema_version",
109867  /* ePragTyp: */ PragTyp_HEADER_VALUE,
109868  /* ePragFlag: */ 0,
109869  /* iArg: */ BTREE_SCHEMA_VERSION },
109870 #endif
109871 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109872  { /* zName: */ "secure_delete",
109873  /* ePragTyp: */ PragTyp_SECURE_DELETE,
109874  /* ePragFlag: */ 0,
109875  /* iArg: */ 0 },
109876 #endif
109877 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109878  { /* zName: */ "short_column_names",
109879  /* ePragTyp: */ PragTyp_FLAG,
109880  /* ePragFlag: */ 0,
109881  /* iArg: */ SQLITE_ShortColNames },
109882 #endif
109883  { /* zName: */ "shrink_memory",
109884  /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
109885  /* ePragFlag: */ 0,
109886  /* iArg: */ 0 },
109887  { /* zName: */ "soft_heap_limit",
109888  /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
109889  /* ePragFlag: */ 0,
109890  /* iArg: */ 0 },
109891 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109892 #if defined(SQLITE_DEBUG)
109893  { /* zName: */ "sql_trace",
109894  /* ePragTyp: */ PragTyp_FLAG,
109895  /* ePragFlag: */ 0,
109896  /* iArg: */ SQLITE_SqlTrace },
109897 #endif
109898 #endif
109899 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
109900  { /* zName: */ "stats",
109901  /* ePragTyp: */ PragTyp_STATS,
109902  /* ePragFlag: */ PragFlag_NeedSchema,
109903  /* iArg: */ 0 },
109904 #endif
109905 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109906  { /* zName: */ "synchronous",
109907  /* ePragTyp: */ PragTyp_SYNCHRONOUS,
109908  /* ePragFlag: */ PragFlag_NeedSchema,
109909  /* iArg: */ 0 },
109910 #endif
109911 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
109912  { /* zName: */ "table_info",
109913  /* ePragTyp: */ PragTyp_TABLE_INFO,
109914  /* ePragFlag: */ PragFlag_NeedSchema,
109915  /* iArg: */ 0 },
109916 #endif
109917 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
109918  { /* zName: */ "temp_store",
109919  /* ePragTyp: */ PragTyp_TEMP_STORE,
109920  /* ePragFlag: */ 0,
109921  /* iArg: */ 0 },
109922  { /* zName: */ "temp_store_directory",
109923  /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
109924  /* ePragFlag: */ 0,
109925  /* iArg: */ 0 },
109926 #endif
109927  { /* zName: */ "threads",
109928  /* ePragTyp: */ PragTyp_THREADS,
109929  /* ePragFlag: */ 0,
109930  /* iArg: */ 0 },
109931 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
109932  { /* zName: */ "user_version",
109933  /* ePragTyp: */ PragTyp_HEADER_VALUE,
109934  /* ePragFlag: */ 0,
109935  /* iArg: */ BTREE_USER_VERSION },
109936 #endif
109937 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109938 #if defined(SQLITE_DEBUG)
109939  { /* zName: */ "vdbe_addoptrace",
109940  /* ePragTyp: */ PragTyp_FLAG,
109941  /* ePragFlag: */ 0,
109942  /* iArg: */ SQLITE_VdbeAddopTrace },
109943  { /* zName: */ "vdbe_debug",
109944  /* ePragTyp: */ PragTyp_FLAG,
109945  /* ePragFlag: */ 0,
109946  /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
109947  { /* zName: */ "vdbe_eqp",
109948  /* ePragTyp: */ PragTyp_FLAG,
109949  /* ePragFlag: */ 0,
109950  /* iArg: */ SQLITE_VdbeEQP },
109951  { /* zName: */ "vdbe_listing",
109952  /* ePragTyp: */ PragTyp_FLAG,
109953  /* ePragFlag: */ 0,
109954  /* iArg: */ SQLITE_VdbeListing },
109955  { /* zName: */ "vdbe_trace",
109956  /* ePragTyp: */ PragTyp_FLAG,
109957  /* ePragFlag: */ 0,
109958  /* iArg: */ SQLITE_VdbeTrace },
109959 #endif
109960 #endif
109961 #if !defined(SQLITE_OMIT_WAL)
109962  { /* zName: */ "wal_autocheckpoint",
109963  /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
109964  /* ePragFlag: */ 0,
109965  /* iArg: */ 0 },
109966  { /* zName: */ "wal_checkpoint",
109967  /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
109968  /* ePragFlag: */ PragFlag_NeedSchema,
109969  /* iArg: */ 0 },
109970 #endif
109971 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
109972  { /* zName: */ "writable_schema",
109973  /* ePragTyp: */ PragTyp_FLAG,
109974  /* ePragFlag: */ 0,
109975  /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
109976 #endif
109977 };
109978 /* Number of pragmas: 60 on by default, 73 total. */
109979 
109980 /************** End of pragma.h **********************************************/
109981 /************** Continuing where we left off in pragma.c *********************/
109982 
109983 /*
109984 ** Interpret the given string as a safety level. Return 0 for OFF,
109985 ** 1 for ON or NORMAL, 2 for FULL, and 3 for EXTRA. Return 1 for an empty or
109986 ** unrecognized string argument. The FULL and EXTRA option is disallowed
109987 ** if the omitFull parameter it 1.
109988 **
109989 ** Note that the values returned are one less that the values that
109990 ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
109991 ** to support legacy SQL code. The safety level used to be boolean
109992 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
109993 */
109994 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
109995  /* 123456789 123456789 123 */
109996  static const char zText[] = "onoffalseyestruextrafull";
109997  static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 15, 20};
109998  static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 5, 4};
109999  static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 3, 2};
110000  /* on no off false yes true extra full */
110001  int i, n;
110002  if( sqlite3Isdigit(*z) ){
110003  return (u8)sqlite3Atoi(z);
110004  }
110005  n = sqlite3Strlen30(z);
110006  for(i=0; i<ArraySize(iLength); i++){
110007  if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0
110008  && (!omitFull || iValue[i]<=1)
110009  ){
110010  return iValue[i];
110011  }
110012  }
110013  return dflt;
110014 }
110015 
110016 /*
110017 ** Interpret the given string as a boolean value.
110018 */
110019 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
110020  return getSafetyLevel(z,1,dflt)!=0;
110021 }
110022 
110023 /* The sqlite3GetBoolean() function is used by other modules but the
110024 ** remainder of this file is specific to PRAGMA processing. So omit
110025 ** the rest of the file if PRAGMAs are omitted from the build.
110026 */
110027 #if !defined(SQLITE_OMIT_PRAGMA)
110028 
110029 /*
110030 ** Interpret the given string as a locking mode value.
110031 */
110032 static int getLockingMode(const char *z){
110033  if( z ){
110034  if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
110035  if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
110036  }
110037  return PAGER_LOCKINGMODE_QUERY;
110038 }
110039 
110040 #ifndef SQLITE_OMIT_AUTOVACUUM
110041 /*
110042 ** Interpret the given string as an auto-vacuum mode value.
110043 **
110044 ** The following strings, "none", "full" and "incremental" are
110045 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
110046 */
110047 static int getAutoVacuum(const char *z){
110048  int i;
110049  if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
110050  if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
110051  if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
110052  i = sqlite3Atoi(z);
110053  return (u8)((i>=0&&i<=2)?i:0);
110054 }
110055 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
110056 
110057 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110058 /*
110059 ** Interpret the given string as a temp db location. Return 1 for file
110060 ** backed temporary databases, 2 for the Red-Black tree in memory database
110061 ** and 0 to use the compile-time default.
110062 */
110063 static int getTempStore(const char *z){
110064  if( z[0]>='0' && z[0]<='2' ){
110065  return z[0] - '0';
110066  }else if( sqlite3StrICmp(z, "file")==0 ){
110067  return 1;
110068  }else if( sqlite3StrICmp(z, "memory")==0 ){
110069  return 2;
110070  }else{
110071  return 0;
110072  }
110073 }
110074 #endif /* SQLITE_PAGER_PRAGMAS */
110075 
110076 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110077 /*
110078 ** Invalidate temp storage, either when the temp storage is changed
110079 ** from default, or when 'file' and the temp_store_directory has changed
110080 */
110081 static int invalidateTempStorage(Parse *pParse){
110082  sqlite3 *db = pParse->db;
110083  if( db->aDb[1].pBt!=0 ){
110084  if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
110085  sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
110086  "from within a transaction");
110087  return SQLITE_ERROR;
110088  }
110089  sqlite3BtreeClose(db->aDb[1].pBt);
110090  db->aDb[1].pBt = 0;
110092  }
110093  return SQLITE_OK;
110094 }
110095 #endif /* SQLITE_PAGER_PRAGMAS */
110096 
110097 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110098 /*
110099 ** If the TEMP database is open, close it and mark the database schema
110100 ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
110101 ** or DEFAULT_TEMP_STORE pragmas.
110102 */
110103 static int changeTempStorage(Parse *pParse, const char *zStorageType){
110104  int ts = getTempStore(zStorageType);
110105  sqlite3 *db = pParse->db;
110106  if( db->temp_store==ts ) return SQLITE_OK;
110107  if( invalidateTempStorage( pParse ) != SQLITE_OK ){
110108  return SQLITE_ERROR;
110109  }
110110  db->temp_store = (u8)ts;
110111  return SQLITE_OK;
110112 }
110113 #endif /* SQLITE_PAGER_PRAGMAS */
110114 
110115 /*
110116 ** Set the names of the first N columns to the values in azCol[]
110117 */
110119  Vdbe *v, /* The query under construction */
110120  int N, /* Number of columns */
110121  const char **azCol /* Names of columns */
110122 ){
110123  int i;
110124  sqlite3VdbeSetNumCols(v, N);
110125  for(i=0; i<N; i++){
110127  }
110128 }
110129 static void setOneColumnName(Vdbe *v, const char *z){
110130  setAllColumnNames(v, 1, &z);
110131 }
110132 
110133 /*
110134 ** Generate code to return a single integer value.
110135 */
110136 static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value){
110137  sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, 1, 0, (const u8*)&value, P4_INT64);
110138  setOneColumnName(v, zLabel);
110139  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110140 }
110141 
110142 /*
110143 ** Generate code to return a single text value.
110144 */
110145 static void returnSingleText(
110146  Vdbe *v, /* Prepared statement under construction */
110147  const char *zLabel, /* Name of the result column */
110148  const char *zValue /* Value to be returned */
110149 ){
110150  if( zValue ){
110151  sqlite3VdbeLoadString(v, 1, (const char*)zValue);
110152  setOneColumnName(v, zLabel);
110153  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110154  }
110155 }
110156 
110157 
110158 /*
110159 ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
110160 ** set these values for all pagers.
110161 */
110162 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110163 static void setAllPagerFlags(sqlite3 *db){
110164  if( db->autoCommit ){
110165  Db *pDb = db->aDb;
110166  int n = db->nDb;
110171  == PAGER_FLAGS_MASK );
110173  while( (n--) > 0 ){
110174  if( pDb->pBt ){
110176  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
110177  }
110178  pDb++;
110179  }
110180  }
110181 }
110182 #else
110183 # define setAllPagerFlags(X) /* no-op */
110184 #endif
110185 
110186 
110187 /*
110188 ** Return a human-readable name for a constraint resolution action.
110189 */
110190 #ifndef SQLITE_OMIT_FOREIGN_KEY
110191 static const char *actionName(u8 action){
110192  const char *zName;
110193  switch( action ){
110194  case OE_SetNull: zName = "SET NULL"; break;
110195  case OE_SetDflt: zName = "SET DEFAULT"; break;
110196  case OE_Cascade: zName = "CASCADE"; break;
110197  case OE_Restrict: zName = "RESTRICT"; break;
110198  default: zName = "NO ACTION";
110199  assert( action==OE_None ); break;
110200  }
110201  return zName;
110202 }
110203 #endif
110204 
110205 
110206 /*
110207 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
110208 ** defined in pager.h. This function returns the associated lowercase
110209 ** journal-mode name.
110210 */
110212  static char * const azModeName[] = {
110213  "delete", "persist", "off", "truncate", "memory"
110214 #ifndef SQLITE_OMIT_WAL
110215  , "wal"
110216 #endif
110217  };
110224  assert( eMode>=0 && eMode<=ArraySize(azModeName) );
110225 
110226  if( eMode==ArraySize(azModeName) ) return 0;
110227  return azModeName[eMode];
110228 }
110229 
110230 /*
110231 ** Process a pragma statement.
110232 **
110233 ** Pragmas are of this form:
110234 **
110235 ** PRAGMA [schema.]id [= value]
110236 **
110237 ** The identifier might also be a string. The value is a string, and
110238 ** identifier, or a number. If minusFlag is true, then the value is
110239 ** a number that was preceded by a minus sign.
110240 **
110241 ** If the left side is "database.id" then pId1 is the database name
110242 ** and pId2 is the id. If the left side is just "id" then pId1 is the
110243 ** id and pId2 is any empty string.
110244 */
110246  Parse *pParse,
110247  Token *pId1, /* First part of [schema.]id field */
110248  Token *pId2, /* Second part of [schema.]id field, or NULL */
110249  Token *pValue, /* Token for <value>, or NULL */
110250  int minusFlag /* True if a '-' sign preceded <value> */
110251 ){
110252  char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
110253  char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
110254  const char *zDb = 0; /* The database name */
110255  Token *pId; /* Pointer to <id> token */
110256  char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
110257  int iDb; /* Database index for <database> */
110258  int lwr, upr, mid = 0; /* Binary search bounds */
110259  int rc; /* return value form SQLITE_FCNTL_PRAGMA */
110260  sqlite3 *db = pParse->db; /* The database connection */
110261  Db *pDb; /* The specific database being pragmaed */
110262  Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
110263  const struct sPragmaNames *pPragma;
110264 
110265  if( v==0 ) return;
110267  pParse->nMem = 2;
110268 
110269  /* Interpret the [schema.] part of the pragma statement. iDb is the
110270  ** index of the database this pragma is being applied to in db.aDb[]. */
110271  iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
110272  if( iDb<0 ) return;
110273  pDb = &db->aDb[iDb];
110274 
110275  /* If the temp database has been explicitly named as part of the
110276  ** pragma, make sure it is open.
110277  */
110278  if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
110279  return;
110280  }
110281 
110282  zLeft = sqlite3NameFromToken(db, pId);
110283  if( !zLeft ) return;
110284  if( minusFlag ){
110285  zRight = sqlite3MPrintf(db, "-%T", pValue);
110286  }else{
110287  zRight = sqlite3NameFromToken(db, pValue);
110288  }
110289 
110290  assert( pId2 );
110291  zDb = pId2->n>0 ? pDb->zName : 0;
110292  if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
110293  goto pragma_out;
110294  }
110295 
110296  /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
110297  ** connection. If it returns SQLITE_OK, then assume that the VFS
110298  ** handled the pragma and generate a no-op prepared statement.
110299  **
110300  ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
110301  ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
110302  ** object corresponding to the database file to which the pragma
110303  ** statement refers.
110304  **
110305  ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
110306  ** file control is an array of pointers to strings (char**) in which the
110307  ** second element of the array is the name of the pragma and the third
110308  ** element is the argument to the pragma or NULL if the pragma has no
110309  ** argument.
110310  */
110311  aFcntl[0] = 0;
110312  aFcntl[1] = zLeft;
110313  aFcntl[2] = zRight;
110314  aFcntl[3] = 0;
110315  db->busyHandler.nBusy = 0;
110316  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
110317  if( rc==SQLITE_OK ){
110318  returnSingleText(v, "result", aFcntl[0]);
110319  sqlite3_free(aFcntl[0]);
110320  goto pragma_out;
110321  }
110322  if( rc!=SQLITE_NOTFOUND ){
110323  if( aFcntl[0] ){
110324  sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
110325  sqlite3_free(aFcntl[0]);
110326  }
110327  pParse->nErr++;
110328  pParse->rc = rc;
110329  goto pragma_out;
110330  }
110331 
110332  /* Locate the pragma in the lookup table */
110333  lwr = 0;
110334  upr = ArraySize(aPragmaNames)-1;
110335  while( lwr<=upr ){
110336  mid = (lwr+upr)/2;
110337  rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
110338  if( rc==0 ) break;
110339  if( rc<0 ){
110340  upr = mid - 1;
110341  }else{
110342  lwr = mid + 1;
110343  }
110344  }
110345  if( lwr>upr ) goto pragma_out;
110346  pPragma = &aPragmaNames[mid];
110347 
110348  /* Make sure the database schema is loaded if the pragma requires that */
110349  if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
110350  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
110351  }
110352 
110353  /* Jump to the appropriate pragma handler */
110354  switch( pPragma->ePragTyp ){
110355 
110356 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
110357  /*
110358  ** PRAGMA [schema.]default_cache_size
110359  ** PRAGMA [schema.]default_cache_size=N
110360  **
110361  ** The first form reports the current persistent setting for the
110362  ** page cache size. The value returned is the maximum number of
110363  ** pages in the page cache. The second form sets both the current
110364  ** page cache size value and the persistent page cache size value
110365  ** stored in the database file.
110366  **
110367  ** Older versions of SQLite would set the default cache size to a
110368  ** negative number to indicate synchronous=OFF. These days, synchronous
110369  ** is always on by default regardless of the sign of the default cache
110370  ** size. But continue to take the absolute value of the default cache
110371  ** size of historical compatibility.
110372  */
110374  static const int iLn = VDBE_OFFSET_LINENO(2);
110375  static const VdbeOpList getCacheSize[] = {
110376  { OP_Transaction, 0, 0, 0}, /* 0 */
110377  { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
110378  { OP_IfPos, 1, 8, 0},
110379  { OP_Integer, 0, 2, 0},
110380  { OP_Subtract, 1, 2, 1},
110381  { OP_IfPos, 1, 8, 0},
110382  { OP_Integer, 0, 1, 0}, /* 6 */
110383  { OP_Noop, 0, 0, 0},
110384  { OP_ResultRow, 1, 1, 0},
110385  };
110386  VdbeOp *aOp;
110387  sqlite3VdbeUsesBtree(v, iDb);
110388  if( !zRight ){
110389  setOneColumnName(v, "cache_size");
110390  pParse->nMem += 2;
110391  sqlite3VdbeVerifyNoMallocRequired(v, ArraySize(getCacheSize));
110392  aOp = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize, iLn);
110393  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
110394  aOp[0].p1 = iDb;
110395  aOp[1].p1 = iDb;
110396  aOp[6].p1 = SQLITE_DEFAULT_CACHE_SIZE;
110397  }else{
110398  int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
110399  sqlite3BeginWriteOperation(pParse, 0, iDb);
110401  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110402  pDb->pSchema->cache_size = size;
110404  }
110405  break;
110406  }
110407 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
110408 
110409 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
110410  /*
110411  ** PRAGMA [schema.]page_size
110412  ** PRAGMA [schema.]page_size=N
110413  **
110414  ** The first form reports the current setting for the
110415  ** database page size in bytes. The second form sets the
110416  ** database page size value. The value can only be set if
110417  ** the database has not yet been created.
110418  */
110419  case PragTyp_PAGE_SIZE: {
110420  Btree *pBt = pDb->pBt;
110421  assert( pBt!=0 );
110422  if( !zRight ){
110423  int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
110424  returnSingleInt(v, "page_size", size);
110425  }else{
110426  /* Malloc may fail when setting the page-size, as there is an internal
110427  ** buffer that the pager module resizes using sqlite3_realloc().
110428  */
110429  db->nextPagesize = sqlite3Atoi(zRight);
110430  if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
110431  sqlite3OomFault(db);
110432  }
110433  }
110434  break;
110435  }
110436 
110437  /*
110438  ** PRAGMA [schema.]secure_delete
110439  ** PRAGMA [schema.]secure_delete=ON/OFF
110440  **
110441  ** The first form reports the current setting for the
110442  ** secure_delete flag. The second form changes the secure_delete
110443  ** flag setting and reports thenew value.
110444  */
110445  case PragTyp_SECURE_DELETE: {
110446  Btree *pBt = pDb->pBt;
110447  int b = -1;
110448  assert( pBt!=0 );
110449  if( zRight ){
110450  b = sqlite3GetBoolean(zRight, 0);
110451  }
110452  if( pId2->n==0 && b>=0 ){
110453  int ii;
110454  for(ii=0; ii<db->nDb; ii++){
110455  sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
110456  }
110457  }
110458  b = sqlite3BtreeSecureDelete(pBt, b);
110459  returnSingleInt(v, "secure_delete", b);
110460  break;
110461  }
110462 
110463  /*
110464  ** PRAGMA [schema.]max_page_count
110465  ** PRAGMA [schema.]max_page_count=N
110466  **
110467  ** The first form reports the current setting for the
110468  ** maximum number of pages in the database file. The
110469  ** second form attempts to change this setting. Both
110470  ** forms return the current setting.
110471  **
110472  ** The absolute value of N is used. This is undocumented and might
110473  ** change. The only purpose is to provide an easy way to test
110474  ** the sqlite3AbsInt32() function.
110475  **
110476  ** PRAGMA [schema.]page_count
110477  **
110478  ** Return the number of pages in the specified database.
110479  */
110480  case PragTyp_PAGE_COUNT: {
110481  int iReg;
110482  sqlite3CodeVerifySchema(pParse, iDb);
110483  iReg = ++pParse->nMem;
110484  if( sqlite3Tolower(zLeft[0])=='p' ){
110485  sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
110486  }else{
110487  sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
110488  sqlite3AbsInt32(sqlite3Atoi(zRight)));
110489  }
110490  sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
110491  sqlite3VdbeSetNumCols(v, 1);
110493  break;
110494  }
110495 
110496  /*
110497  ** PRAGMA [schema.]locking_mode
110498  ** PRAGMA [schema.]locking_mode = (normal|exclusive)
110499  */
110500  case PragTyp_LOCKING_MODE: {
110501  const char *zRet = "normal";
110502  int eMode = getLockingMode(zRight);
110503 
110504  if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
110505  /* Simple "PRAGMA locking_mode;" statement. This is a query for
110506  ** the current default locking mode (which may be different to
110507  ** the locking-mode of the main database).
110508  */
110509  eMode = db->dfltLockMode;
110510  }else{
110511  Pager *pPager;
110512  if( pId2->n==0 ){
110513  /* This indicates that no database name was specified as part
110514  ** of the PRAGMA command. In this case the locking-mode must be
110515  ** set on all attached databases, as well as the main db file.
110516  **
110517  ** Also, the sqlite3.dfltLockMode variable is set so that
110518  ** any subsequently attached databases also use the specified
110519  ** locking mode.
110520  */
110521  int ii;
110522  assert(pDb==&db->aDb[0]);
110523  for(ii=2; ii<db->nDb; ii++){
110524  pPager = sqlite3BtreePager(db->aDb[ii].pBt);
110525  sqlite3PagerLockingMode(pPager, eMode);
110526  }
110527  db->dfltLockMode = (u8)eMode;
110528  }
110529  pPager = sqlite3BtreePager(pDb->pBt);
110530  eMode = sqlite3PagerLockingMode(pPager, eMode);
110531  }
110532 
110534  || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
110535  if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
110536  zRet = "exclusive";
110537  }
110538  returnSingleText(v, "locking_mode", zRet);
110539  break;
110540  }
110541 
110542  /*
110543  ** PRAGMA [schema.]journal_mode
110544  ** PRAGMA [schema.]journal_mode =
110545  ** (delete|persist|off|truncate|memory|wal|off)
110546  */
110547  case PragTyp_JOURNAL_MODE: {
110548  int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
110549  int ii; /* Loop counter */
110550 
110551  setOneColumnName(v, "journal_mode");
110552  if( zRight==0 ){
110553  /* If there is no "=MODE" part of the pragma, do a query for the
110554  ** current mode */
110555  eMode = PAGER_JOURNALMODE_QUERY;
110556  }else{
110557  const char *zMode;
110558  int n = sqlite3Strlen30(zRight);
110559  for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
110560  if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
110561  }
110562  if( !zMode ){
110563  /* If the "=MODE" part does not match any known journal mode,
110564  ** then do a query */
110565  eMode = PAGER_JOURNALMODE_QUERY;
110566  }
110567  }
110568  if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
110569  /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
110570  iDb = 0;
110571  pId2->n = 1;
110572  }
110573  for(ii=db->nDb-1; ii>=0; ii--){
110574  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
110575  sqlite3VdbeUsesBtree(v, ii);
110576  sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
110577  }
110578  }
110579  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
110580  break;
110581  }
110582 
110583  /*
110584  ** PRAGMA [schema.]journal_size_limit
110585  ** PRAGMA [schema.]journal_size_limit=N
110586  **
110587  ** Get or set the size limit on rollback journal files.
110588  */
110590  Pager *pPager = sqlite3BtreePager(pDb->pBt);
110591  i64 iLimit = -2;
110592  if( zRight ){
110593  sqlite3DecOrHexToI64(zRight, &iLimit);
110594  if( iLimit<-1 ) iLimit = -1;
110595  }
110596  iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
110597  returnSingleInt(v, "journal_size_limit", iLimit);
110598  break;
110599  }
110600 
110601 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
110602 
110603  /*
110604  ** PRAGMA [schema.]auto_vacuum
110605  ** PRAGMA [schema.]auto_vacuum=N
110606  **
110607  ** Get or set the value of the database 'auto-vacuum' parameter.
110608  ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
110609  */
110610 #ifndef SQLITE_OMIT_AUTOVACUUM
110611  case PragTyp_AUTO_VACUUM: {
110612  Btree *pBt = pDb->pBt;
110613  assert( pBt!=0 );
110614  if( !zRight ){
110615  returnSingleInt(v, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
110616  }else{
110617  int eAuto = getAutoVacuum(zRight);
110618  assert( eAuto>=0 && eAuto<=2 );
110619  db->nextAutovac = (u8)eAuto;
110620  /* Call SetAutoVacuum() to set initialize the internal auto and
110621  ** incr-vacuum flags. This is required in case this connection
110622  ** creates the database file. It is important that it is created
110623  ** as an auto-vacuum capable db.
110624  */
110625  rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
110626  if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
110627  /* When setting the auto_vacuum mode to either "full" or
110628  ** "incremental", write the value of meta[6] in the database
110629  ** file. Before writing to meta[6], check that meta[3] indicates
110630  ** that this really is an auto-vacuum capable database.
110631  */
110632  static const int iLn = VDBE_OFFSET_LINENO(2);
110633  static const VdbeOpList setMeta6[] = {
110634  { OP_Transaction, 0, 1, 0}, /* 0 */
110636  { OP_If, 1, 0, 0}, /* 2 */
110637  { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
110638  { OP_SetCookie, 0, BTREE_INCR_VACUUM, 0}, /* 4 */
110639  };
110640  VdbeOp *aOp;
110641  int iAddr = sqlite3VdbeCurrentAddr(v);
110643  aOp = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
110644  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
110645  aOp[0].p1 = iDb;
110646  aOp[1].p1 = iDb;
110647  aOp[2].p2 = iAddr+4;
110648  aOp[4].p1 = iDb;
110649  aOp[4].p3 = eAuto - 1;
110650  sqlite3VdbeUsesBtree(v, iDb);
110651  }
110652  }
110653  break;
110654  }
110655 #endif
110656 
110657  /*
110658  ** PRAGMA [schema.]incremental_vacuum(N)
110659  **
110660  ** Do N steps of incremental vacuuming on a database.
110661  */
110662 #ifndef SQLITE_OMIT_AUTOVACUUM
110664  int iLimit, addr;
110665  if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
110666  iLimit = 0x7fffffff;
110667  }
110668  sqlite3BeginWriteOperation(pParse, 0, iDb);
110669  sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
110670  addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
110672  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
110673  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
110674  sqlite3VdbeJumpHere(v, addr);
110675  break;
110676  }
110677 #endif
110678 
110679 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
110680  /*
110681  ** PRAGMA [schema.]cache_size
110682  ** PRAGMA [schema.]cache_size=N
110683  **
110684  ** The first form reports the current local setting for the
110685  ** page cache size. The second form sets the local
110686  ** page cache size value. If N is positive then that is the
110687  ** number of pages in the cache. If N is negative, then the
110688  ** number of pages is adjusted so that the cache uses -N kibibytes
110689  ** of memory.
110690  */
110691  case PragTyp_CACHE_SIZE: {
110692  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110693  if( !zRight ){
110694  returnSingleInt(v, "cache_size", pDb->pSchema->cache_size);
110695  }else{
110696  int size = sqlite3Atoi(zRight);
110697  pDb->pSchema->cache_size = size;
110699  }
110700  break;
110701  }
110702 
110703  /*
110704  ** PRAGMA [schema.]cache_spill
110705  ** PRAGMA cache_spill=BOOLEAN
110706  ** PRAGMA [schema.]cache_spill=N
110707  **
110708  ** The first form reports the current local setting for the
110709  ** page cache spill size. The second form turns cache spill on
110710  ** or off. When turnning cache spill on, the size is set to the
110711  ** current cache_size. The third form sets a spill size that
110712  ** may be different form the cache size.
110713  ** If N is positive then that is the
110714  ** number of pages in the cache. If N is negative, then the
110715  ** number of pages is adjusted so that the cache uses -N kibibytes
110716  ** of memory.
110717  **
110718  ** If the number of cache_spill pages is less then the number of
110719  ** cache_size pages, no spilling occurs until the page count exceeds
110720  ** the number of cache_size pages.
110721  **
110722  ** The cache_spill=BOOLEAN setting applies to all attached schemas,
110723  ** not just the schema specified.
110724  */
110725  case PragTyp_CACHE_SPILL: {
110726  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110727  if( !zRight ){
110728  returnSingleInt(v, "cache_spill",
110729  (db->flags & SQLITE_CacheSpill)==0 ? 0 :
110730  sqlite3BtreeSetSpillSize(pDb->pBt,0));
110731  }else{
110732  int size = 1;
110733  if( sqlite3GetInt32(zRight, &size) ){
110734  sqlite3BtreeSetSpillSize(pDb->pBt, size);
110735  }
110736  if( sqlite3GetBoolean(zRight, size!=0) ){
110737  db->flags |= SQLITE_CacheSpill;
110738  }else{
110739  db->flags &= ~SQLITE_CacheSpill;
110740  }
110741  setAllPagerFlags(db);
110742  }
110743  break;
110744  }
110745 
110746  /*
110747  ** PRAGMA [schema.]mmap_size(N)
110748  **
110749  ** Used to set mapping size limit. The mapping size limit is
110750  ** used to limit the aggregate size of all memory mapped regions of the
110751  ** database file. If this parameter is set to zero, then memory mapping
110752  ** is not used at all. If N is negative, then the default memory map
110753  ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
110754  ** The parameter N is measured in bytes.
110755  **
110756  ** This value is advisory. The underlying VFS is free to memory map
110757  ** as little or as much as it wants. Except, if N is set to 0 then the
110758  ** upper layers will never invoke the xFetch interfaces to the VFS.
110759  */
110760  case PragTyp_MMAP_SIZE: {
110761  sqlite3_int64 sz;
110762 #if SQLITE_MAX_MMAP_SIZE>0
110763  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
110764  if( zRight ){
110765  int ii;
110766  sqlite3DecOrHexToI64(zRight, &sz);
110767  if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
110768  if( pId2->n==0 ) db->szMmap = sz;
110769  for(ii=db->nDb-1; ii>=0; ii--){
110770  if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
110771  sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
110772  }
110773  }
110774  }
110775  sz = -1;
110776  rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
110777 #else
110778  sz = 0;
110779  rc = SQLITE_OK;
110780 #endif
110781  if( rc==SQLITE_OK ){
110782  returnSingleInt(v, "mmap_size", sz);
110783  }else if( rc!=SQLITE_NOTFOUND ){
110784  pParse->nErr++;
110785  pParse->rc = rc;
110786  }
110787  break;
110788  }
110789 
110790  /*
110791  ** PRAGMA temp_store
110792  ** PRAGMA temp_store = "default"|"memory"|"file"
110793  **
110794  ** Return or set the local value of the temp_store flag. Changing
110795  ** the local value does not make changes to the disk file and the default
110796  ** value will be restored the next time the database is opened.
110797  **
110798  ** Note that it is possible for the library compile-time options to
110799  ** override this setting
110800  */
110801  case PragTyp_TEMP_STORE: {
110802  if( !zRight ){
110803  returnSingleInt(v, "temp_store", db->temp_store);
110804  }else{
110805  changeTempStorage(pParse, zRight);
110806  }
110807  break;
110808  }
110809 
110810  /*
110811  ** PRAGMA temp_store_directory
110812  ** PRAGMA temp_store_directory = ""|"directory_name"
110813  **
110814  ** Return or set the local value of the temp_store_directory flag. Changing
110815  ** the value sets a specific directory to be used for temporary files.
110816  ** Setting to a null string reverts to the default temporary directory search.
110817  ** If temporary directory is changed, then invalidateTempStorage.
110818  **
110819  */
110821  if( !zRight ){
110822  returnSingleText(v, "temp_store_directory", sqlite3_temp_directory);
110823  }else{
110824 #ifndef SQLITE_OMIT_WSD
110825  if( zRight[0] ){
110826  int res;
110827  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
110828  if( rc!=SQLITE_OK || res==0 ){
110829  sqlite3ErrorMsg(pParse, "not a writable directory");
110830  goto pragma_out;
110831  }
110832  }
110833  if( SQLITE_TEMP_STORE==0
110834  || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
110835  || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
110836  ){
110837  invalidateTempStorage(pParse);
110838  }
110839  sqlite3_free(sqlite3_temp_directory);
110840  if( zRight[0] ){
110841  sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
110842  }else{
110843  sqlite3_temp_directory = 0;
110844  }
110845 #endif /* SQLITE_OMIT_WSD */
110846  }
110847  break;
110848  }
110849 
110850 #if SQLITE_OS_WIN
110851  /*
110852  ** PRAGMA data_store_directory
110853  ** PRAGMA data_store_directory = ""|"directory_name"
110854  **
110855  ** Return or set the local value of the data_store_directory flag. Changing
110856  ** the value sets a specific directory to be used for database files that
110857  ** were specified with a relative pathname. Setting to a null string reverts
110858  ** to the default database directory, which for database files specified with
110859  ** a relative path will probably be based on the current directory for the
110860  ** process. Database file specified with an absolute path are not impacted
110861  ** by this setting, regardless of its value.
110862  **
110863  */
110865  if( !zRight ){
110866  returnSingleText(v, "data_store_directory", sqlite3_data_directory);
110867  }else{
110868 #ifndef SQLITE_OMIT_WSD
110869  if( zRight[0] ){
110870  int res;
110871  rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
110872  if( rc!=SQLITE_OK || res==0 ){
110873  sqlite3ErrorMsg(pParse, "not a writable directory");
110874  goto pragma_out;
110875  }
110876  }
110877  sqlite3_free(sqlite3_data_directory);
110878  if( zRight[0] ){
110879  sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
110880  }else{
110881  sqlite3_data_directory = 0;
110882  }
110883 #endif /* SQLITE_OMIT_WSD */
110884  }
110885  break;
110886  }
110887 #endif
110888 
110889 #if SQLITE_ENABLE_LOCKING_STYLE
110890  /*
110891  ** PRAGMA [schema.]lock_proxy_file
110892  ** PRAGMA [schema.]lock_proxy_file = ":auto:"|"lock_file_path"
110893  **
110894  ** Return or set the value of the lock_proxy_file flag. Changing
110895  ** the value sets a specific file to be used for database access locks.
110896  **
110897  */
110898  case PragTyp_LOCK_PROXY_FILE: {
110899  if( !zRight ){
110900  Pager *pPager = sqlite3BtreePager(pDb->pBt);
110901  char *proxy_file_path = NULL;
110902  sqlite3_file *pFile = sqlite3PagerFile(pPager);
110904  &proxy_file_path);
110905  returnSingleText(v, "lock_proxy_file", proxy_file_path);
110906  }else{
110907  Pager *pPager = sqlite3BtreePager(pDb->pBt);
110908  sqlite3_file *pFile = sqlite3PagerFile(pPager);
110909  int res;
110910  if( zRight[0] ){
110912  zRight);
110913  } else {
110915  NULL);
110916  }
110917  if( res!=SQLITE_OK ){
110918  sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
110919  goto pragma_out;
110920  }
110921  }
110922  break;
110923  }
110924 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
110925 
110926  /*
110927  ** PRAGMA [schema.]synchronous
110928  ** PRAGMA [schema.]synchronous=OFF|ON|NORMAL|FULL|EXTRA
110929  **
110930  ** Return or set the local value of the synchronous flag. Changing
110931  ** the local value does not make changes to the disk file and the
110932  ** default value will be restored the next time the database is
110933  ** opened.
110934  */
110935  case PragTyp_SYNCHRONOUS: {
110936  if( !zRight ){
110937  returnSingleInt(v, "synchronous", pDb->safety_level-1);
110938  }else{
110939  if( !db->autoCommit ){
110940  sqlite3ErrorMsg(pParse,
110941  "Safety level may not be changed inside a transaction");
110942  }else{
110943  int iLevel = (getSafetyLevel(zRight,0,1)+1) & PAGER_SYNCHRONOUS_MASK;
110944  if( iLevel==0 ) iLevel = 1;
110945  pDb->safety_level = iLevel;
110946  pDb->bSyncSet = 1;
110947  setAllPagerFlags(db);
110948  }
110949  }
110950  break;
110951  }
110952 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
110953 
110954 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
110955  case PragTyp_FLAG: {
110956  if( zRight==0 ){
110957  returnSingleInt(v, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
110958  }else{
110959  int mask = pPragma->iArg; /* Mask of bits to set or clear. */
110960  if( db->autoCommit==0 ){
110961  /* Foreign key support may not be enabled or disabled while not
110962  ** in auto-commit mode. */
110963  mask &= ~(SQLITE_ForeignKeys);
110964  }
110965 #if SQLITE_USER_AUTHENTICATION
110966  if( db->auth.authLevel==UAUTH_User ){
110967  /* Do not allow non-admin users to modify the schema arbitrarily */
110968  mask &= ~(SQLITE_WriteSchema);
110969  }
110970 #endif
110971 
110972  if( sqlite3GetBoolean(zRight, 0) ){
110973  db->flags |= mask;
110974  }else{
110975  db->flags &= ~mask;
110976  if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
110977  }
110978 
110979  /* Many of the flag-pragmas modify the code generated by the SQL
110980  ** compiler (eg. count_changes). So add an opcode to expire all
110981  ** compiled SQL statements after modifying a pragma value.
110982  */
110983  sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
110984  setAllPagerFlags(db);
110985  }
110986  break;
110987  }
110988 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
110989 
110990 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
110991  /*
110992  ** PRAGMA table_info(<table>)
110993  **
110994  ** Return a single row for each column of the named table. The columns of
110995  ** the returned data set are:
110996  **
110997  ** cid: Column id (numbered from left to right, starting at 0)
110998  ** name: Column name
110999  ** type: Column declaration type.
111000  ** notnull: True if 'NOT NULL' is part of column declaration
111001  ** dflt_value: The default value for the column, if any.
111002  */
111003  case PragTyp_TABLE_INFO: if( zRight ){
111004  Table *pTab;
111005  pTab = sqlite3FindTable(db, zRight, zDb);
111006  if( pTab ){
111007  static const char *azCol[] = {
111008  "cid", "name", "type", "notnull", "dflt_value", "pk"
111009  };
111010  int i, k;
111011  int nHidden = 0;
111012  Column *pCol;
111013  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
111014  pParse->nMem = 6;
111015  sqlite3CodeVerifySchema(pParse, iDb);
111016  setAllColumnNames(v, 6, azCol); assert( 6==ArraySize(azCol) );
111017  sqlite3ViewGetColumnNames(pParse, pTab);
111018  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
111019  if( IsHiddenColumn(pCol) ){
111020  nHidden++;
111021  continue;
111022  }
111023  if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
111024  k = 0;
111025  }else if( pPk==0 ){
111026  k = 1;
111027  }else{
111028  for(k=1; k<=pTab->nCol && pPk->aiColumn[k-1]!=i; k++){}
111029  }
111030  assert( pCol->pDflt==0 || pCol->pDflt->op==TK_SPAN );
111031  sqlite3VdbeMultiLoad(v, 1, "issisi",
111032  i-nHidden,
111033  pCol->zName,
111034  sqlite3ColumnType(pCol,""),
111035  pCol->notNull ? 1 : 0,
111036  pCol->pDflt ? pCol->pDflt->u.zToken : 0,
111037  k);
111038  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
111039  }
111040  }
111041  }
111042  break;
111043 
111044  case PragTyp_STATS: {
111045  static const char *azCol[] = { "table", "index", "width", "height" };
111046  Index *pIdx;
111047  HashElem *i;
111048  v = sqlite3GetVdbe(pParse);
111049  pParse->nMem = 4;
111050  sqlite3CodeVerifySchema(pParse, iDb);
111051  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
111052  for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
111053  Table *pTab = sqliteHashData(i);
111054  sqlite3VdbeMultiLoad(v, 1, "ssii",
111055  pTab->zName,
111056  0,
111057  pTab->szTabRow,
111058  pTab->nRowLogEst);
111059  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111060  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111061  sqlite3VdbeMultiLoad(v, 2, "sii",
111062  pIdx->zName,
111063  pIdx->szIdxRow,
111064  pIdx->aiRowLogEst[0]);
111065  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
111066  }
111067  }
111068  }
111069  break;
111070 
111071  case PragTyp_INDEX_INFO: if( zRight ){
111072  Index *pIdx;
111073  Table *pTab;
111074  pIdx = sqlite3FindIndex(db, zRight, zDb);
111075  if( pIdx ){
111076  static const char *azCol[] = {
111077  "seqno", "cid", "name", "desc", "coll", "key"
111078  };
111079  int i;
111080  int mx;
111081  if( pPragma->iArg ){
111082  /* PRAGMA index_xinfo (newer version with more rows and columns) */
111083  mx = pIdx->nColumn;
111084  pParse->nMem = 6;
111085  }else{
111086  /* PRAGMA index_info (legacy version) */
111087  mx = pIdx->nKeyCol;
111088  pParse->nMem = 3;
111089  }
111090  pTab = pIdx->pTable;
111091  sqlite3CodeVerifySchema(pParse, iDb);
111092  assert( pParse->nMem<=ArraySize(azCol) );
111093  setAllColumnNames(v, pParse->nMem, azCol);
111094  for(i=0; i<mx; i++){
111095  i16 cnum = pIdx->aiColumn[i];
111096  sqlite3VdbeMultiLoad(v, 1, "iis", i, cnum,
111097  cnum<0 ? 0 : pTab->aCol[cnum].zName);
111098  if( pPragma->iArg ){
111099  sqlite3VdbeMultiLoad(v, 4, "isi",
111100  pIdx->aSortOrder[i],
111101  pIdx->azColl[i],
111102  i<pIdx->nKeyCol);
111103  }
111104  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
111105  }
111106  }
111107  }
111108  break;
111109 
111110  case PragTyp_INDEX_LIST: if( zRight ){
111111  Index *pIdx;
111112  Table *pTab;
111113  int i;
111114  pTab = sqlite3FindTable(db, zRight, zDb);
111115  if( pTab ){
111116  static const char *azCol[] = {
111117  "seq", "name", "unique", "origin", "partial"
111118  };
111119  v = sqlite3GetVdbe(pParse);
111120  pParse->nMem = 5;
111121  sqlite3CodeVerifySchema(pParse, iDb);
111122  setAllColumnNames(v, 5, azCol); assert( 5==ArraySize(azCol) );
111123  for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
111124  const char *azOrigin[] = { "c", "u", "pk" };
111125  sqlite3VdbeMultiLoad(v, 1, "isisi",
111126  i,
111127  pIdx->zName,
111128  IsUniqueIndex(pIdx),
111129  azOrigin[pIdx->idxType],
111130  pIdx->pPartIdxWhere!=0);
111131  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
111132  }
111133  }
111134  }
111135  break;
111136 
111137  case PragTyp_DATABASE_LIST: {
111138  static const char *azCol[] = { "seq", "name", "file" };
111139  int i;
111140  pParse->nMem = 3;
111141  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
111142  for(i=0; i<db->nDb; i++){
111143  if( db->aDb[i].pBt==0 ) continue;
111144  assert( db->aDb[i].zName!=0 );
111145  sqlite3VdbeMultiLoad(v, 1, "iss",
111146  i,
111147  db->aDb[i].zName,
111148  sqlite3BtreeGetFilename(db->aDb[i].pBt));
111149  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
111150  }
111151  }
111152  break;
111153 
111154  case PragTyp_COLLATION_LIST: {
111155  static const char *azCol[] = { "seq", "name" };
111156  int i = 0;
111157  HashElem *p;
111158  pParse->nMem = 2;
111159  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
111160  for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
111161  CollSeq *pColl = (CollSeq *)sqliteHashData(p);
111162  sqlite3VdbeMultiLoad(v, 1, "is", i++, pColl->zName);
111163  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
111164  }
111165  }
111166  break;
111167 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
111168 
111169 #ifndef SQLITE_OMIT_FOREIGN_KEY
111170  case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
111171  FKey *pFK;
111172  Table *pTab;
111173  pTab = sqlite3FindTable(db, zRight, zDb);
111174  if( pTab ){
111175  v = sqlite3GetVdbe(pParse);
111176  pFK = pTab->pFKey;
111177  if( pFK ){
111178  static const char *azCol[] = {
111179  "id", "seq", "table", "from", "to", "on_update", "on_delete",
111180  "match"
111181  };
111182  int i = 0;
111183  pParse->nMem = 8;
111184  sqlite3CodeVerifySchema(pParse, iDb);
111185  setAllColumnNames(v, 8, azCol); assert( 8==ArraySize(azCol) );
111186  while(pFK){
111187  int j;
111188  for(j=0; j<pFK->nCol; j++){
111189  sqlite3VdbeMultiLoad(v, 1, "iissssss",
111190  i,
111191  j,
111192  pFK->zTo,
111193  pTab->aCol[pFK->aCol[j].iFrom].zName,
111194  pFK->aCol[j].zCol,
111195  actionName(pFK->aAction[1]), /* ON UPDATE */
111196  actionName(pFK->aAction[0]), /* ON DELETE */
111197  "NONE");
111198  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
111199  }
111200  ++i;
111201  pFK = pFK->pNextFrom;
111202  }
111203  }
111204  }
111205  }
111206  break;
111207 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111208 
111209 #ifndef SQLITE_OMIT_FOREIGN_KEY
111210 #ifndef SQLITE_OMIT_TRIGGER
111211  case PragTyp_FOREIGN_KEY_CHECK: {
111212  FKey *pFK; /* A foreign key constraint */
111213  Table *pTab; /* Child table contain "REFERENCES" keyword */
111214  Table *pParent; /* Parent table that child points to */
111215  Index *pIdx; /* Index in the parent table */
111216  int i; /* Loop counter: Foreign key number for pTab */
111217  int j; /* Loop counter: Field of the foreign key */
111218  HashElem *k; /* Loop counter: Next table in schema */
111219  int x; /* result variable */
111220  int regResult; /* 3 registers to hold a result row */
111221  int regKey; /* Register to hold key for checking the FK */
111222  int regRow; /* Registers to hold a row from pTab */
111223  int addrTop; /* Top of a loop checking foreign keys */
111224  int addrOk; /* Jump here if the key is OK */
111225  int *aiCols; /* child to parent column mapping */
111226  static const char *azCol[] = { "table", "rowid", "parent", "fkid" };
111227 
111228  regResult = pParse->nMem+1;
111229  pParse->nMem += 4;
111230  regKey = ++pParse->nMem;
111231  regRow = ++pParse->nMem;
111232  v = sqlite3GetVdbe(pParse);
111233  setAllColumnNames(v, 4, azCol); assert( 4==ArraySize(azCol) );
111234  sqlite3CodeVerifySchema(pParse, iDb);
111235  k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
111236  while( k ){
111237  if( zRight ){
111238  pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
111239  k = 0;
111240  }else{
111241  pTab = (Table*)sqliteHashData(k);
111242  k = sqliteHashNext(k);
111243  }
111244  if( pTab==0 || pTab->pFKey==0 ) continue;
111245  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111246  if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
111247  sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
111248  sqlite3VdbeLoadString(v, regResult, pTab->zName);
111249  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111250  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111251  if( pParent==0 ) continue;
111252  pIdx = 0;
111253  sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
111254  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
111255  if( x==0 ){
111256  if( pIdx==0 ){
111257  sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
111258  }else{
111259  sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
111260  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
111261  }
111262  }else{
111263  k = 0;
111264  break;
111265  }
111266  }
111267  assert( pParse->nErr>0 || pFK==0 );
111268  if( pFK ) break;
111269  if( pParse->nTab<i ) pParse->nTab = i;
111270  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
111271  for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
111272  pParent = sqlite3FindTable(db, pFK->zTo, zDb);
111273  pIdx = 0;
111274  aiCols = 0;
111275  if( pParent ){
111276  x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
111277  assert( x==0 );
111278  }
111279  addrOk = sqlite3VdbeMakeLabel(v);
111280  if( pParent && pIdx==0 ){
111281  int iKey = pFK->aCol[0].iFrom;
111282  assert( iKey>=0 && iKey<pTab->nCol );
111283  if( iKey!=pTab->iPKey ){
111284  sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
111285  sqlite3ColumnDefault(v, pTab, iKey, regRow);
111286  sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
111287  sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
111289  }else{
111290  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
111291  }
111292  sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
111293  sqlite3VdbeGoto(v, addrOk);
111295  }else{
111296  for(j=0; j<pFK->nCol; j++){
111297  sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
111298  aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
111299  sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
111300  }
111301  if( pParent ){
111302  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
111303  sqlite3IndexAffinityStr(db,pIdx), pFK->nCol);
111304  sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
111305  VdbeCoverage(v);
111306  }
111307  }
111308  sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
111309  sqlite3VdbeMultiLoad(v, regResult+2, "si", pFK->zTo, i-1);
111310  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
111311  sqlite3VdbeResolveLabel(v, addrOk);
111312  sqlite3DbFree(db, aiCols);
111313  }
111314  sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
111315  sqlite3VdbeJumpHere(v, addrTop);
111316  }
111317  }
111318  break;
111319 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
111320 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
111321 
111322 #ifndef NDEBUG
111323  case PragTyp_PARSER_TRACE: {
111324  if( zRight ){
111325  if( sqlite3GetBoolean(zRight, 0) ){
111326  sqlite3ParserTrace(stdout, "parser: ");
111327  }else{
111328  sqlite3ParserTrace(0, 0);
111329  }
111330  }
111331  }
111332  break;
111333 #endif
111334 
111335  /* Reinstall the LIKE and GLOB functions. The variant of LIKE
111336  ** used will be case sensitive or not depending on the RHS.
111337  */
111339  if( zRight ){
111341  }
111342  }
111343  break;
111344 
111345 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
111346 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
111347 #endif
111348 
111349 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
111350  /* Pragma "quick_check" is reduced version of
111351  ** integrity_check designed to detect most database corruption
111352  ** without most of the overhead of a full integrity-check.
111353  */
111354  case PragTyp_INTEGRITY_CHECK: {
111355  int i, j, addr, mxErr;
111356 
111357  int isQuick = (sqlite3Tolower(zLeft[0])=='q');
111358 
111359  /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
111360  ** then iDb is set to the index of the database identified by <db>.
111361  ** In this case, the integrity of database iDb only is verified by
111362  ** the VDBE created below.
111363  **
111364  ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
111365  ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
111366  ** to -1 here, to indicate that the VDBE should verify the integrity
111367  ** of all attached databases. */
111368  assert( iDb>=0 );
111369  assert( iDb==0 || pId2->z );
111370  if( pId2->z==0 ) iDb = -1;
111371 
111372  /* Initialize the VDBE program */
111373  pParse->nMem = 6;
111374  setOneColumnName(v, "integrity_check");
111375 
111376  /* Set the maximum error count */
111378  if( zRight ){
111379  sqlite3GetInt32(zRight, &mxErr);
111380  if( mxErr<=0 ){
111382  }
111383  }
111384  sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
111385 
111386  /* Do an integrity check on each database file */
111387  for(i=0; i<db->nDb; i++){
111388  HashElem *x;
111389  Hash *pTbls;
111390  int *aRoot;
111391  int cnt = 0;
111392  int mxIdx = 0;
111393  int nIdx;
111394 
111395  if( OMIT_TEMPDB && i==1 ) continue;
111396  if( iDb>=0 && i!=iDb ) continue;
111397 
111398  sqlite3CodeVerifySchema(pParse, i);
111399  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
111400  VdbeCoverage(v);
111401  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
111402  sqlite3VdbeJumpHere(v, addr);
111403 
111404  /* Do an integrity check of the B-Tree
111405  **
111406  ** Begin by finding the root pages numbers
111407  ** for all tables and indices in the database.
111408  */
111409  assert( sqlite3SchemaMutexHeld(db, i, 0) );
111410  pTbls = &db->aDb[i].pSchema->tblHash;
111411  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
111412  Table *pTab = sqliteHashData(x);
111413  Index *pIdx;
111414  if( HasRowid(pTab) ) cnt++;
111415  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){ cnt++; }
111416  if( nIdx>mxIdx ) mxIdx = nIdx;
111417  }
111418  aRoot = sqlite3DbMallocRawNN(db, sizeof(int)*(cnt+1));
111419  if( aRoot==0 ) break;
111420  for(cnt=0, x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
111421  Table *pTab = sqliteHashData(x);
111422  Index *pIdx;
111423  if( HasRowid(pTab) ) aRoot[cnt++] = pTab->tnum;
111424  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111425  aRoot[cnt++] = pIdx->tnum;
111426  }
111427  }
111428  aRoot[cnt] = 0;
111429 
111430  /* Make sure sufficient number of registers have been allocated */
111431  pParse->nMem = MAX( pParse->nMem, 8+mxIdx );
111432 
111433  /* Do the b-tree integrity checks */
111434  sqlite3VdbeAddOp4(v, OP_IntegrityCk, 2, cnt, 1, (char*)aRoot,P4_INTARRAY);
111435  sqlite3VdbeChangeP5(v, (u8)i);
111436  addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
111437  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
111438  sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
111439  P4_DYNAMIC);
111440  sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
111441  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
111442  sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
111443  sqlite3VdbeJumpHere(v, addr);
111444 
111445  /* Make sure all the indices are constructed correctly.
111446  */
111447  for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
111448  Table *pTab = sqliteHashData(x);
111449  Index *pIdx, *pPk;
111450  Index *pPrior = 0;
111451  int loopTop;
111452  int iDataCur, iIdxCur;
111453  int r1 = -1;
111454 
111455  if( pTab->pIndex==0 ) continue;
111456  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
111457  addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
111458  VdbeCoverage(v);
111459  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
111460  sqlite3VdbeJumpHere(v, addr);
111461  sqlite3ExprCacheClear(pParse);
111462  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead, 0,
111463  1, 0, &iDataCur, &iIdxCur);
111464  sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
111465  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111466  sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
111467  }
111468  assert( pParse->nMem>=8+j );
111469  assert( sqlite3NoTempsInRange(pParse,1,7+j) );
111470  sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
111471  loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
111472  /* Verify that all NOT NULL columns really are NOT NULL */
111473  for(j=0; j<pTab->nCol; j++){
111474  char *zErr;
111475  int jmp2, jmp3;
111476  if( j==pTab->iPKey ) continue;
111477  if( pTab->aCol[j].notNull==0 ) continue;
111478  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
111480  jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
111481  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
111482  zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
111483  pTab->aCol[j].zName);
111484  sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
111485  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
111486  jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
111488  sqlite3VdbeJumpHere(v, jmp2);
111489  sqlite3VdbeJumpHere(v, jmp3);
111490  }
111491  /* Validate index entries for the current row */
111492  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111493  int jmp2, jmp3, jmp4, jmp5;
111494  int ckUniq = sqlite3VdbeMakeLabel(v);
111495  if( pPk==pIdx ) continue;
111496  r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
111497  pPrior, r1);
111498  pPrior = pIdx;
111499  sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
111500  /* Verify that an index entry exists for the current table row */
111501  jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
111502  pIdx->nColumn); VdbeCoverage(v);
111503  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
111504  sqlite3VdbeLoadString(v, 3, "row ");
111505  sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
111506  sqlite3VdbeLoadString(v, 4, " missing from index ");
111507  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
111508  jmp5 = sqlite3VdbeLoadString(v, 4, pIdx->zName);
111509  sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
111510  sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
111511  jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
111513  sqlite3VdbeJumpHere(v, jmp2);
111514  /* For UNIQUE indexes, verify that only one entry exists with the
111515  ** current key. The entry is unique if (1) any column is NULL
111516  ** or (2) the next entry has a different key */
111517  if( IsUniqueIndex(pIdx) ){
111518  int uniqOk = sqlite3VdbeMakeLabel(v);
111519  int jmp6;
111520  int kk;
111521  for(kk=0; kk<pIdx->nKeyCol; kk++){
111522  int iCol = pIdx->aiColumn[kk];
111523  assert( iCol!=XN_ROWID && iCol<pTab->nCol );
111524  if( iCol>=0 && pTab->aCol[iCol].notNull ) continue;
111525  sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
111526  VdbeCoverage(v);
111527  }
111528  jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
111529  sqlite3VdbeGoto(v, uniqOk);
111530  sqlite3VdbeJumpHere(v, jmp6);
111531  sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
111532  pIdx->nKeyCol); VdbeCoverage(v);
111533  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
111534  sqlite3VdbeLoadString(v, 3, "non-unique entry in index ");
111535  sqlite3VdbeGoto(v, jmp5);
111536  sqlite3VdbeResolveLabel(v, uniqOk);
111537  }
111538  sqlite3VdbeJumpHere(v, jmp4);
111539  sqlite3ResolvePartIdxLabel(pParse, jmp3);
111540  }
111541  sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
111542  sqlite3VdbeJumpHere(v, loopTop-1);
111543 #ifndef SQLITE_OMIT_BTREECOUNT
111544  sqlite3VdbeLoadString(v, 2, "wrong # of entries in index ");
111545  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
111546  if( pPk==pIdx ) continue;
111547  addr = sqlite3VdbeCurrentAddr(v);
111548  sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
111549  sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
111550  sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
111551  sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
111553  sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
111554  sqlite3VdbeLoadString(v, 3, pIdx->zName);
111555  sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
111556  sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
111557  }
111558 #endif /* SQLITE_OMIT_BTREECOUNT */
111559  }
111560  }
111561  {
111562  static const int iLn = VDBE_OFFSET_LINENO(2);
111563  static const VdbeOpList endCode[] = {
111564  { OP_AddImm, 1, 0, 0}, /* 0 */
111565  { OP_If, 1, 4, 0}, /* 1 */
111566  { OP_String8, 0, 3, 0}, /* 2 */
111567  { OP_ResultRow, 3, 1, 0}, /* 3 */
111568  };
111569  VdbeOp *aOp;
111570 
111571  aOp = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
111572  if( aOp ){
111573  aOp[0].p2 = -mxErr;
111574  aOp[2].p4type = P4_STATIC;
111575  aOp[2].p4.z = "ok";
111576  }
111577  }
111578  }
111579  break;
111580 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
111581 
111582 #ifndef SQLITE_OMIT_UTF16
111583  /*
111584  ** PRAGMA encoding
111585  ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
111586  **
111587  ** In its first form, this pragma returns the encoding of the main
111588  ** database. If the database is not initialized, it is initialized now.
111589  **
111590  ** The second form of this pragma is a no-op if the main database file
111591  ** has not already been initialized. In this case it sets the default
111592  ** encoding that will be used for the main database file if a new file
111593  ** is created. If an existing main database file is opened, then the
111594  ** default text encoding for the existing database is used.
111595  **
111596  ** In all cases new databases created using the ATTACH command are
111597  ** created to use the same default text encoding as the main database. If
111598  ** the main database has not been initialized and/or created when ATTACH
111599  ** is executed, this is done before the ATTACH operation.
111600  **
111601  ** In the second form this pragma sets the text encoding to be used in
111602  ** new database files created using this database handle. It is only
111603  ** useful if invoked immediately after the main database i
111604  */
111605  case PragTyp_ENCODING: {
111606  static const struct EncName {
111607  char *zName;
111608  u8 enc;
111609  } encnames[] = {
111610  { "UTF8", SQLITE_UTF8 },
111611  { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
111612  { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
111613  { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
111614  { "UTF16le", SQLITE_UTF16LE },
111615  { "UTF16be", SQLITE_UTF16BE },
111616  { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
111617  { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
111618  { 0, 0 }
111619  };
111620  const struct EncName *pEnc;
111621  if( !zRight ){ /* "PRAGMA encoding" */
111622  if( sqlite3ReadSchema(pParse) ) goto pragma_out;
111623  assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
111624  assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
111625  assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
111626  returnSingleText(v, "encoding", encnames[ENC(pParse->db)].zName);
111627  }else{ /* "PRAGMA encoding = XXX" */
111628  /* Only change the value of sqlite.enc if the database handle is not
111629  ** initialized. If the main database exists, the new sqlite.enc value
111630  ** will be overwritten when the schema is next loaded. If it does not
111631  ** already exists, it will be created to use the new encoding value.
111632  */
111633  if(
111634  !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
111635  DbHasProperty(db, 0, DB_Empty)
111636  ){
111637  for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
111638  if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
111639  SCHEMA_ENC(db) = ENC(db) =
111640  pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
111641  break;
111642  }
111643  }
111644  if( !pEnc->zName ){
111645  sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
111646  }
111647  }
111648  }
111649  }
111650  break;
111651 #endif /* SQLITE_OMIT_UTF16 */
111652 
111653 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
111654  /*
111655  ** PRAGMA [schema.]schema_version
111656  ** PRAGMA [schema.]schema_version = <integer>
111657  **
111658  ** PRAGMA [schema.]user_version
111659  ** PRAGMA [schema.]user_version = <integer>
111660  **
111661  ** PRAGMA [schema.]freelist_count
111662  **
111663  ** PRAGMA [schema.]data_version
111664  **
111665  ** PRAGMA [schema.]application_id
111666  ** PRAGMA [schema.]application_id = <integer>
111667  **
111668  ** The pragma's schema_version and user_version are used to set or get
111669  ** the value of the schema-version and user-version, respectively. Both
111670  ** the schema-version and the user-version are 32-bit signed integers
111671  ** stored in the database header.
111672  **
111673  ** The schema-cookie is usually only manipulated internally by SQLite. It
111674  ** is incremented by SQLite whenever the database schema is modified (by
111675  ** creating or dropping a table or index). The schema version is used by
111676  ** SQLite each time a query is executed to ensure that the internal cache
111677  ** of the schema used when compiling the SQL query matches the schema of
111678  ** the database against which the compiled query is actually executed.
111679  ** Subverting this mechanism by using "PRAGMA schema_version" to modify
111680  ** the schema-version is potentially dangerous and may lead to program
111681  ** crashes or database corruption. Use with caution!
111682  **
111683  ** The user-version is not used internally by SQLite. It may be used by
111684  ** applications for any purpose.
111685  */
111686  case PragTyp_HEADER_VALUE: {
111687  int iCookie = pPragma->iArg; /* Which cookie to read or write */
111688  sqlite3VdbeUsesBtree(v, iDb);
111689  if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
111690  /* Write the specified cookie value */
111691  static const VdbeOpList setCookie[] = {
111692  { OP_Transaction, 0, 1, 0}, /* 0 */
111693  { OP_SetCookie, 0, 0, 0}, /* 1 */
111694  };
111695  VdbeOp *aOp;
111697  aOp = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
111698  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111699  aOp[0].p1 = iDb;
111700  aOp[1].p1 = iDb;
111701  aOp[1].p2 = iCookie;
111702  aOp[1].p3 = sqlite3Atoi(zRight);
111703  }else{
111704  /* Read the specified cookie value */
111705  static const VdbeOpList readCookie[] = {
111706  { OP_Transaction, 0, 0, 0}, /* 0 */
111707  { OP_ReadCookie, 0, 1, 0}, /* 1 */
111708  { OP_ResultRow, 1, 1, 0}
111709  };
111710  VdbeOp *aOp;
111712  aOp = sqlite3VdbeAddOpList(v, ArraySize(readCookie),readCookie,0);
111713  if( ONLY_IF_REALLOC_STRESS(aOp==0) ) break;
111714  aOp[0].p1 = iDb;
111715  aOp[1].p1 = iDb;
111716  aOp[1].p3 = iCookie;
111717  sqlite3VdbeSetNumCols(v, 1);
111719  sqlite3VdbeReusable(v);
111720  }
111721  }
111722  break;
111723 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
111724 
111725 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
111726  /*
111727  ** PRAGMA compile_options
111728  **
111729  ** Return the names of all compile-time options used in this build,
111730  ** one option per row.
111731  */
111732  case PragTyp_COMPILE_OPTIONS: {
111733  int i = 0;
111734  const char *zOpt;
111735  pParse->nMem = 1;
111736  setOneColumnName(v, "compile_option");
111737  while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
111738  sqlite3VdbeLoadString(v, 1, zOpt);
111739  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
111740  }
111741  sqlite3VdbeReusable(v);
111742  }
111743  break;
111744 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
111745 
111746 #ifndef SQLITE_OMIT_WAL
111747  /*
111748  ** PRAGMA [schema.]wal_checkpoint = passive|full|restart|truncate
111749  **
111750  ** Checkpoint the database.
111751  */
111752  case PragTyp_WAL_CHECKPOINT: {
111753  static const char *azCol[] = { "busy", "log", "checkpointed" };
111754  int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
111755  int eMode = SQLITE_CHECKPOINT_PASSIVE;
111756  if( zRight ){
111757  if( sqlite3StrICmp(zRight, "full")==0 ){
111758  eMode = SQLITE_CHECKPOINT_FULL;
111759  }else if( sqlite3StrICmp(zRight, "restart")==0 ){
111760  eMode = SQLITE_CHECKPOINT_RESTART;
111761  }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
111762  eMode = SQLITE_CHECKPOINT_TRUNCATE;
111763  }
111764  }
111765  setAllColumnNames(v, 3, azCol); assert( 3==ArraySize(azCol) );
111766  pParse->nMem = 3;
111767  sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
111768  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
111769  }
111770  break;
111771 
111772  /*
111773  ** PRAGMA wal_autocheckpoint
111774  ** PRAGMA wal_autocheckpoint = N
111775  **
111776  ** Configure a database connection to automatically checkpoint a database
111777  ** after accumulating N frames in the log. Or query for the current value
111778  ** of N.
111779  */
111781  if( zRight ){
111783  }
111784  returnSingleInt(v, "wal_autocheckpoint",
111786  SQLITE_PTR_TO_INT(db->pWalArg) : 0);
111787  }
111788  break;
111789 #endif
111790 
111791  /*
111792  ** PRAGMA shrink_memory
111793  **
111794  ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
111795  ** connection on which it is invoked to free up as much memory as it
111796  ** can, by calling sqlite3_db_release_memory().
111797  */
111798  case PragTyp_SHRINK_MEMORY: {
111800  break;
111801  }
111802 
111803  /*
111804  ** PRAGMA busy_timeout
111805  ** PRAGMA busy_timeout = N
111806  **
111807  ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
111808  ** if one is set. If no busy handler or a different busy handler is set
111809  ** then 0 is returned. Setting the busy_timeout to 0 or negative
111810  ** disables the timeout.
111811  */
111812  /*case PragTyp_BUSY_TIMEOUT*/ default: {
111813  assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
111814  if( zRight ){
111815  sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
111816  }
111817  returnSingleInt(v, "timeout", db->busyTimeout);
111818  break;
111819  }
111820 
111821  /*
111822  ** PRAGMA soft_heap_limit
111823  ** PRAGMA soft_heap_limit = N
111824  **
111825  ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
111826  ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
111827  ** specified and is a non-negative integer.
111828  ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
111829  ** returns the same integer that would be returned by the
111830  ** sqlite3_soft_heap_limit64(-1) C-language function.
111831  */
111832  case PragTyp_SOFT_HEAP_LIMIT: {
111833  sqlite3_int64 N;
111834  if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
111836  }
111837  returnSingleInt(v, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
111838  break;
111839  }
111840 
111841  /*
111842  ** PRAGMA threads
111843  ** PRAGMA threads = N
111844  **
111845  ** Configure the maximum number of worker threads. Return the new
111846  ** maximum, which might be less than requested.
111847  */
111848  case PragTyp_THREADS: {
111849  sqlite3_int64 N;
111850  if( zRight
111851  && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
111852  && N>=0
111853  ){
111854  sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
111855  }
111856  returnSingleInt(v, "threads",
111858  break;
111859  }
111860 
111861 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
111862  /*
111863  ** Report the current state of file logs for all databases
111864  */
111865  case PragTyp_LOCK_STATUS: {
111866  static const char *const azLockName[] = {
111867  "unlocked", "shared", "reserved", "pending", "exclusive"
111868  };
111869  static const char *azCol[] = { "database", "status" };
111870  int i;
111871  setAllColumnNames(v, 2, azCol); assert( 2==ArraySize(azCol) );
111872  pParse->nMem = 2;
111873  for(i=0; i<db->nDb; i++){
111874  Btree *pBt;
111875  const char *zState = "unknown";
111876  int j;
111877  if( db->aDb[i].zName==0 ) continue;
111878  pBt = db->aDb[i].pBt;
111879  if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
111880  zState = "closed";
111881  }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
111883  zState = azLockName[j];
111884  }
111885  sqlite3VdbeMultiLoad(v, 1, "ss", db->aDb[i].zName, zState);
111886  sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
111887  }
111888  break;
111889  }
111890 #endif
111891 
111892 #ifdef SQLITE_HAS_CODEC
111893  case PragTyp_KEY: {
111894  if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
111895  break;
111896  }
111897  case PragTyp_REKEY: {
111898  if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
111899  break;
111900  }
111901  case PragTyp_HEXKEY: {
111902  if( zRight ){
111903  u8 iByte;
111904  int i;
111905  char zKey[40];
111906  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
111907  iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
111908  if( (i&1)!=0 ) zKey[i/2] = iByte;
111909  }
111910  if( (zLeft[3] & 0xf)==0xb ){
111911  sqlite3_key_v2(db, zDb, zKey, i/2);
111912  }else{
111913  sqlite3_rekey_v2(db, zDb, zKey, i/2);
111914  }
111915  }
111916  break;
111917  }
111918 #endif
111919 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
111920  case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
111921 #ifdef SQLITE_HAS_CODEC
111922  if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
111923  sqlite3_activate_see(&zRight[4]);
111924  }
111925 #endif
111926 #ifdef SQLITE_ENABLE_CEROD
111927  if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
111928  sqlite3_activate_cerod(&zRight[6]);
111929  }
111930 #endif
111931  }
111932  break;
111933 #endif
111934 
111935  } /* End of the PRAGMA switch */
111936 
111937 pragma_out:
111938  sqlite3DbFree(db, zLeft);
111939  sqlite3DbFree(db, zRight);
111940 }
111941 
111942 #endif /* SQLITE_OMIT_PRAGMA */
111943 
111944 /************** End of pragma.c **********************************************/
111945 /************** Begin file prepare.c *****************************************/
111946 /*
111947 ** 2005 May 25
111948 **
111949 ** The author disclaims copyright to this source code. In place of
111950 ** a legal notice, here is a blessing:
111951 **
111952 ** May you do good and not evil.
111953 ** May you find forgiveness for yourself and forgive others.
111954 ** May you share freely, never taking more than you give.
111955 **
111956 *************************************************************************
111957 ** This file contains the implementation of the sqlite3_prepare()
111958 ** interface, and routines that contribute to loading the database schema
111959 ** from disk.
111960 */
111961 /* #include "sqliteInt.h" */
111962 
111963 /*
111964 ** Fill the InitData structure with an error message that indicates
111965 ** that the database is corrupt.
111966 */
111967 static void corruptSchema(
111968  InitData *pData, /* Initialization context */
111969  const char *zObj, /* Object being parsed at the point of error */
111970  const char *zExtra /* Error information */
111971 ){
111972  sqlite3 *db = pData->db;
111973  if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
111974  char *z;
111975  if( zObj==0 ) zObj = "?";
111976  z = sqlite3MPrintf(db, "malformed database schema (%s)", zObj);
111977  if( zExtra ) z = sqlite3MPrintf(db, "%z - %s", z, zExtra);
111978  sqlite3DbFree(db, *pData->pzErrMsg);
111979  *pData->pzErrMsg = z;
111980  }
111982 }
111983 
111984 /*
111985 ** This is the callback routine for the code that initializes the
111986 ** database. See sqlite3Init() below for additional information.
111987 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
111988 **
111989 ** Each callback contains the following information:
111990 **
111991 ** argv[0] = name of thing being created
111992 ** argv[1] = root page number for table or index. 0 for trigger or view.
111993 ** argv[2] = SQL text for the CREATE statement.
111994 **
111995 */
111996 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
111997  InitData *pData = (InitData*)pInit;
111998  sqlite3 *db = pData->db;
111999  int iDb = pData->iDb;
112000 
112001  assert( argc==3 );
112002  UNUSED_PARAMETER2(NotUsed, argc);
112003  assert( sqlite3_mutex_held(db->mutex) );
112004  DbClearProperty(db, iDb, DB_Empty);
112005  if( db->mallocFailed ){
112006  corruptSchema(pData, argv[0], 0);
112007  return 1;
112008  }
112009 
112010  assert( iDb>=0 && iDb<db->nDb );
112011  if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
112012  if( argv[1]==0 ){
112013  corruptSchema(pData, argv[0], 0);
112014  }else if( sqlite3_strnicmp(argv[2],"create ",7)==0 ){
112015  /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
112016  ** But because db->init.busy is set to 1, no VDBE code is generated
112017  ** or executed. All the parser does is build the internal data
112018  ** structures that describe the table, index, or view.
112019  */
112020  int rc;
112021  sqlite3_stmt *pStmt;
112022  TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
112023 
112024  assert( db->init.busy );
112025  db->init.iDb = iDb;
112026  db->init.newTnum = sqlite3Atoi(argv[1]);
112027  db->init.orphanTrigger = 0;
112028  TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
112029  rc = db->errCode;
112030  assert( (rc&0xFF)==(rcp&0xFF) );
112031  db->init.iDb = 0;
112032  if( SQLITE_OK!=rc ){
112033  if( db->init.orphanTrigger ){
112034  assert( iDb==1 );
112035  }else{
112036  pData->rc = rc;
112037  if( rc==SQLITE_NOMEM ){
112038  sqlite3OomFault(db);
112039  }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
112040  corruptSchema(pData, argv[0], sqlite3_errmsg(db));
112041  }
112042  }
112043  }
112044  sqlite3_finalize(pStmt);
112045  }else if( argv[0]==0 || (argv[2]!=0 && argv[2][0]!=0) ){
112046  corruptSchema(pData, argv[0], 0);
112047  }else{
112048  /* If the SQL column is blank it means this is an index that
112049  ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
112050  ** constraint for a CREATE TABLE. The index should have already
112051  ** been created when we processed the CREATE TABLE. All we have
112052  ** to do here is record the root page number for that index.
112053  */
112054  Index *pIndex;
112055  pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
112056  if( pIndex==0 ){
112057  /* This can occur if there exists an index on a TEMP table which
112058  ** has the same name as another index on a permanent index. Since
112059  ** the permanent table is hidden by the TEMP table, we can also
112060  ** safely ignore the index on the permanent table.
112061  */
112062  /* Do Nothing */;
112063  }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
112064  corruptSchema(pData, argv[0], "invalid rootpage");
112065  }
112066  }
112067  return 0;
112068 }
112069 
112070 /*
112071 ** Attempt to read the database schema and initialize internal
112072 ** data structures for a single database file. The index of the
112073 ** database file is given by iDb. iDb==0 is used for the main
112074 ** database. iDb==1 should never be used. iDb>=2 is used for
112075 ** auxiliary databases. Return one of the SQLITE_ error codes to
112076 ** indicate success or failure.
112077 */
112078 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
112079  int rc;
112080  int i;
112081 #ifndef SQLITE_OMIT_DEPRECATED
112082  int size;
112083 #endif
112084  Db *pDb;
112085  char const *azArg[4];
112086  int meta[5];
112087  InitData initData;
112088  const char *zMasterName;
112089  int openedTransaction = 0;
112090 
112091  assert( iDb>=0 && iDb<db->nDb );
112092  assert( db->aDb[iDb].pSchema );
112093  assert( sqlite3_mutex_held(db->mutex) );
112094  assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
112095 
112096  /* Construct the in-memory representation schema tables (sqlite_master or
112097  ** sqlite_temp_master) by invoking the parser directly. The appropriate
112098  ** table name will be inserted automatically by the parser so we can just
112099  ** use the abbreviation "x" here. The parser will also automatically tag
112100  ** the schema table as read-only. */
112101  azArg[0] = zMasterName = SCHEMA_TABLE(iDb);
112102  azArg[1] = "1";
112103  azArg[2] = "CREATE TABLE x(type text,name text,tbl_name text,"
112104  "rootpage integer,sql text)";
112105  azArg[3] = 0;
112106  initData.db = db;
112107  initData.iDb = iDb;
112108  initData.rc = SQLITE_OK;
112109  initData.pzErrMsg = pzErrMsg;
112110  sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
112111  if( initData.rc ){
112112  rc = initData.rc;
112113  goto error_out;
112114  }
112115 
112116  /* Create a cursor to hold the database open
112117  */
112118  pDb = &db->aDb[iDb];
112119  if( pDb->pBt==0 ){
112120  if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
112121  DbSetProperty(db, 1, DB_SchemaLoaded);
112122  }
112123  return SQLITE_OK;
112124  }
112125 
112126  /* If there is not already a read-only (or read-write) transaction opened
112127  ** on the b-tree database, open one now. If a transaction is opened, it
112128  ** will be closed before this function returns. */
112129  sqlite3BtreeEnter(pDb->pBt);
112130  if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
112131  rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
112132  if( rc!=SQLITE_OK ){
112133  sqlite3SetString(pzErrMsg, db, sqlite3ErrStr(rc));
112134  goto initone_error_out;
112135  }
112136  openedTransaction = 1;
112137  }
112138 
112139  /* Get the database meta information.
112140  **
112141  ** Meta values are as follows:
112142  ** meta[0] Schema cookie. Changes with each schema change.
112143  ** meta[1] File format of schema layer.
112144  ** meta[2] Size of the page cache.
112145  ** meta[3] Largest rootpage (auto/incr_vacuum mode)
112146  ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
112147  ** meta[5] User version
112148  ** meta[6] Incremental vacuum mode
112149  ** meta[7] unused
112150  ** meta[8] unused
112151  ** meta[9] unused
112152  **
112153  ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
112154  ** the possible values of meta[4].
112155  */
112156  for(i=0; i<ArraySize(meta); i++){
112157  sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
112158  }
112159  pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
112160 
112161  /* If opening a non-empty database, check the text encoding. For the
112162  ** main database, set sqlite3.enc to the encoding of the main database.
112163  ** For an attached db, it is an error if the encoding is not the same
112164  ** as sqlite3.enc.
112165  */
112166  if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
112167  if( iDb==0 ){
112168 #ifndef SQLITE_OMIT_UTF16
112169  u8 encoding;
112170  /* If opening the main database, set ENC(db). */
112171  encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
112172  if( encoding==0 ) encoding = SQLITE_UTF8;
112173  ENC(db) = encoding;
112174 #else
112175  ENC(db) = SQLITE_UTF8;
112176 #endif
112177  }else{
112178  /* If opening an attached database, the encoding much match ENC(db) */
112179  if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
112180  sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
112181  " text encoding as main database");
112182  rc = SQLITE_ERROR;
112183  goto initone_error_out;
112184  }
112185  }
112186  }else{
112187  DbSetProperty(db, iDb, DB_Empty);
112188  }
112189  pDb->pSchema->enc = ENC(db);
112190 
112191  if( pDb->pSchema->cache_size==0 ){
112192 #ifndef SQLITE_OMIT_DEPRECATED
112193  size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
112194  if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
112195  pDb->pSchema->cache_size = size;
112196 #else
112198 #endif
112200  }
112201 
112202  /*
112203  ** file_format==1 Version 3.0.0.
112204  ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
112205  ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
112206  ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
112207  */
112208  pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
112209  if( pDb->pSchema->file_format==0 ){
112210  pDb->pSchema->file_format = 1;
112211  }
112213  sqlite3SetString(pzErrMsg, db, "unsupported file format");
112214  rc = SQLITE_ERROR;
112215  goto initone_error_out;
112216  }
112217 
112218  /* Ticket #2804: When we open a database in the newer file format,
112219  ** clear the legacy_file_format pragma flag so that a VACUUM will
112220  ** not downgrade the database and thus invalidate any descending
112221  ** indices that the user might have created.
112222  */
112223  if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
112224  db->flags &= ~SQLITE_LegacyFileFmt;
112225  }
112226 
112227  /* Read the schema information out of the schema tables
112228  */
112229  assert( db->init.busy );
112230  {
112231  char *zSql;
112232  zSql = sqlite3MPrintf(db,
112233  "SELECT name, rootpage, sql FROM \"%w\".%s ORDER BY rowid",
112234  db->aDb[iDb].zName, zMasterName);
112235 #ifndef SQLITE_OMIT_AUTHORIZATION
112236  {
112237  sqlite3_xauth xAuth;
112238  xAuth = db->xAuth;
112239  db->xAuth = 0;
112240 #endif
112241  rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
112242 #ifndef SQLITE_OMIT_AUTHORIZATION
112243  db->xAuth = xAuth;
112244  }
112245 #endif
112246  if( rc==SQLITE_OK ) rc = initData.rc;
112247  sqlite3DbFree(db, zSql);
112248 #ifndef SQLITE_OMIT_ANALYZE
112249  if( rc==SQLITE_OK ){
112250  sqlite3AnalysisLoad(db, iDb);
112251  }
112252 #endif
112253  }
112254  if( db->mallocFailed ){
112255  rc = SQLITE_NOMEM_BKPT;
112257  }
112258  if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
112259  /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
112260  ** the schema loaded, even if errors occurred. In this situation the
112261  ** current sqlite3_prepare() operation will fail, but the following one
112262  ** will attempt to compile the supplied statement against whatever subset
112263  ** of the schema was loaded before the error occurred. The primary
112264  ** purpose of this is to allow access to the sqlite_master table
112265  ** even when its contents have been corrupted.
112266  */
112267  DbSetProperty(db, iDb, DB_SchemaLoaded);
112268  rc = SQLITE_OK;
112269  }
112270 
112271  /* Jump here for an error that occurs after successfully allocating
112272  ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
112273  ** before that point, jump to error_out.
112274  */
112275 initone_error_out:
112276  if( openedTransaction ){
112277  sqlite3BtreeCommit(pDb->pBt);
112278  }
112279  sqlite3BtreeLeave(pDb->pBt);
112280 
112281 error_out:
112282  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
112283  sqlite3OomFault(db);
112284  }
112285  return rc;
112286 }
112287 
112288 /*
112289 ** Initialize all database files - the main database file, the file
112290 ** used to store temporary tables, and any additional database files
112291 ** created using ATTACH statements. Return a success code. If an
112292 ** error occurs, write an error message into *pzErrMsg.
112293 **
112294 ** After a database is initialized, the DB_SchemaLoaded bit is set
112295 ** bit is set in the flags field of the Db structure. If the database
112296 ** file was of zero-length, then the DB_Empty flag is also set.
112297 */
112298 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
112299  int i, rc;
112300  int commit_internal = !(db->flags&SQLITE_InternChanges);
112301 
112302  assert( sqlite3_mutex_held(db->mutex) );
112303  assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
112304  assert( db->init.busy==0 );
112305  rc = SQLITE_OK;
112306  db->init.busy = 1;
112307  ENC(db) = SCHEMA_ENC(db);
112308  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
112309  if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
112310  rc = sqlite3InitOne(db, i, pzErrMsg);
112311  if( rc ){
112312  sqlite3ResetOneSchema(db, i);
112313  }
112314  }
112315 
112316  /* Once all the other databases have been initialized, load the schema
112317  ** for the TEMP database. This is loaded last, as the TEMP database
112318  ** schema may contain references to objects in other databases.
112319  */
112320 #ifndef SQLITE_OMIT_TEMPDB
112321  assert( db->nDb>1 );
112322  if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
112323  rc = sqlite3InitOne(db, 1, pzErrMsg);
112324  if( rc ){
112325  sqlite3ResetOneSchema(db, 1);
112326  }
112327  }
112328 #endif
112329 
112330  db->init.busy = 0;
112331  if( rc==SQLITE_OK && commit_internal ){
112333  }
112334 
112335  return rc;
112336 }
112337 
112338 /*
112339 ** This routine is a no-op if the database schema is already initialized.
112340 ** Otherwise, the schema is loaded. An error code is returned.
112341 */
112343  int rc = SQLITE_OK;
112344  sqlite3 *db = pParse->db;
112345  assert( sqlite3_mutex_held(db->mutex) );
112346  if( !db->init.busy ){
112347  rc = sqlite3Init(db, &pParse->zErrMsg);
112348  }
112349  if( rc!=SQLITE_OK ){
112350  pParse->rc = rc;
112351  pParse->nErr++;
112352  }
112353  return rc;
112354 }
112355 
112356 
112357 /*
112358 ** Check schema cookies in all databases. If any cookie is out
112359 ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
112360 ** make no changes to pParse->rc.
112361 */
112362 static void schemaIsValid(Parse *pParse){
112363  sqlite3 *db = pParse->db;
112364  int iDb;
112365  int rc;
112366  int cookie;
112367 
112368  assert( pParse->checkSchema );
112369  assert( sqlite3_mutex_held(db->mutex) );
112370  for(iDb=0; iDb<db->nDb; iDb++){
112371  int openedTransaction = 0; /* True if a transaction is opened */
112372  Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
112373  if( pBt==0 ) continue;
112374 
112375  /* If there is not already a read-only (or read-write) transaction opened
112376  ** on the b-tree database, open one now. If a transaction is opened, it
112377  ** will be closed immediately after reading the meta-value. */
112378  if( !sqlite3BtreeIsInReadTrans(pBt) ){
112379  rc = sqlite3BtreeBeginTrans(pBt, 0);
112380  if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
112381  sqlite3OomFault(db);
112382  }
112383  if( rc!=SQLITE_OK ) return;
112384  openedTransaction = 1;
112385  }
112386 
112387  /* Read the schema cookie from the database. If it does not match the
112388  ** value stored as part of the in-memory schema representation,
112389  ** set Parse.rc to SQLITE_SCHEMA. */
112390  sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
112391  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112392  if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
112393  sqlite3ResetOneSchema(db, iDb);
112394  pParse->rc = SQLITE_SCHEMA;
112395  }
112396 
112397  /* Close the transaction, if one was opened. */
112398  if( openedTransaction ){
112399  sqlite3BtreeCommit(pBt);
112400  }
112401  }
112402 }
112403 
112404 /*
112405 ** Convert a schema pointer into the iDb index that indicates
112406 ** which database file in db->aDb[] the schema refers to.
112407 **
112408 ** If the same database is attached more than once, the first
112409 ** attached database is returned.
112410 */
112411 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
112412  int i = -1000000;
112413 
112414  /* If pSchema is NULL, then return -1000000. This happens when code in
112415  ** expr.c is trying to resolve a reference to a transient table (i.e. one
112416  ** created by a sub-select). In this case the return value of this
112417  ** function should never be used.
112418  **
112419  ** We return -1000000 instead of the more usual -1 simply because using
112420  ** -1000000 as the incorrect index into db->aDb[] is much
112421  ** more likely to cause a segfault than -1 (of course there are assert()
112422  ** statements too, but it never hurts to play the odds).
112423  */
112424  assert( sqlite3_mutex_held(db->mutex) );
112425  if( pSchema ){
112426  for(i=0; ALWAYS(i<db->nDb); i++){
112427  if( db->aDb[i].pSchema==pSchema ){
112428  break;
112429  }
112430  }
112431  assert( i>=0 && i<db->nDb );
112432  }
112433  return i;
112434 }
112435 
112436 /*
112437 ** Free all memory allocations in the pParse object
112438 */
112440  if( pParse ){
112441  sqlite3 *db = pParse->db;
112442  sqlite3DbFree(db, pParse->aLabel);
112443  sqlite3ExprListDelete(db, pParse->pConstExpr);
112444  if( db ){
112445  assert( db->lookaside.bDisable >= pParse->disableLookaside );
112446  db->lookaside.bDisable -= pParse->disableLookaside;
112447  }
112448  pParse->disableLookaside = 0;
112449  }
112450 }
112451 
112452 /*
112453 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
112454 */
112455 static int sqlite3Prepare(
112456  sqlite3 *db, /* Database handle. */
112457  const char *zSql, /* UTF-8 encoded SQL statement. */
112458  int nBytes, /* Length of zSql in bytes. */
112459  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
112460  Vdbe *pReprepare, /* VM being reprepared */
112461  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112462  const char **pzTail /* OUT: End of parsed string */
112463 ){
112464  Parse *pParse; /* Parsing context */
112465  char *zErrMsg = 0; /* Error message */
112466  int rc = SQLITE_OK; /* Result code */
112467  int i; /* Loop counter */
112468 
112469  /* Allocate the parsing context */
112470  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
112471  if( pParse==0 ){
112472  rc = SQLITE_NOMEM_BKPT;
112473  goto end_prepare;
112474  }
112475  pParse->pReprepare = pReprepare;
112476  assert( ppStmt && *ppStmt==0 );
112477  /* assert( !db->mallocFailed ); // not true with SQLITE_USE_ALLOCA */
112478  assert( sqlite3_mutex_held(db->mutex) );
112479 
112480  /* Check to verify that it is possible to get a read lock on all
112481  ** database schemas. The inability to get a read lock indicates that
112482  ** some other database connection is holding a write-lock, which in
112483  ** turn means that the other connection has made uncommitted changes
112484  ** to the schema.
112485  **
112486  ** Were we to proceed and prepare the statement against the uncommitted
112487  ** schema changes and if those schema changes are subsequently rolled
112488  ** back and different changes are made in their place, then when this
112489  ** prepared statement goes to run the schema cookie would fail to detect
112490  ** the schema change. Disaster would follow.
112491  **
112492  ** This thread is currently holding mutexes on all Btrees (because
112493  ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
112494  ** is not possible for another thread to start a new schema change
112495  ** while this routine is running. Hence, we do not need to hold
112496  ** locks on the schema, we just need to make sure nobody else is
112497  ** holding them.
112498  **
112499  ** Note that setting READ_UNCOMMITTED overrides most lock detection,
112500  ** but it does *not* override schema lock detection, so this all still
112501  ** works even if READ_UNCOMMITTED is set.
112502  */
112503  for(i=0; i<db->nDb; i++) {
112504  Btree *pBt = db->aDb[i].pBt;
112505  if( pBt ){
112506  assert( sqlite3BtreeHoldsMutex(pBt) );
112507  rc = sqlite3BtreeSchemaLocked(pBt);
112508  if( rc ){
112509  const char *zDb = db->aDb[i].zName;
112510  sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
112512  goto end_prepare;
112513  }
112514  }
112515  }
112516 
112517  sqlite3VtabUnlockList(db);
112518 
112519  pParse->db = db;
112520  pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
112521  if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
112522  char *zSqlCopy;
112523  int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
112524  testcase( nBytes==mxLen );
112525  testcase( nBytes==mxLen+1 );
112526  if( nBytes>mxLen ){
112527  sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
112528  rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
112529  goto end_prepare;
112530  }
112531  zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
112532  if( zSqlCopy ){
112533  sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
112534  pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
112535  sqlite3DbFree(db, zSqlCopy);
112536  }else{
112537  pParse->zTail = &zSql[nBytes];
112538  }
112539  }else{
112540  sqlite3RunParser(pParse, zSql, &zErrMsg);
112541  }
112542  assert( 0==pParse->nQueryLoop );
112543 
112544  if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
112545  if( pParse->checkSchema ){
112546  schemaIsValid(pParse);
112547  }
112548  if( db->mallocFailed ){
112549  pParse->rc = SQLITE_NOMEM_BKPT;
112550  }
112551  if( pzTail ){
112552  *pzTail = pParse->zTail;
112553  }
112554  rc = pParse->rc;
112555 
112556 #ifndef SQLITE_OMIT_EXPLAIN
112557  if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
112558  static const char * const azColName[] = {
112559  "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
112560  "selectid", "order", "from", "detail"
112561  };
112562  int iFirst, mx;
112563  if( pParse->explain==2 ){
112564  sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
112565  iFirst = 8;
112566  mx = 12;
112567  }else{
112568  sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
112569  iFirst = 0;
112570  mx = 8;
112571  }
112572  for(i=iFirst; i<mx; i++){
112573  sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
112574  azColName[i], SQLITE_STATIC);
112575  }
112576  }
112577 #endif
112578 
112579  if( db->init.busy==0 ){
112580  Vdbe *pVdbe = pParse->pVdbe;
112581  sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
112582  }
112583  if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
112584  sqlite3VdbeFinalize(pParse->pVdbe);
112585  assert(!(*ppStmt));
112586  }else{
112587  *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
112588  }
112589 
112590  if( zErrMsg ){
112591  sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
112592  sqlite3DbFree(db, zErrMsg);
112593  }else{
112594  sqlite3Error(db, rc);
112595  }
112596 
112597  /* Delete any TriggerPrg structures allocated while parsing this statement. */
112598  while( pParse->pTriggerPrg ){
112599  TriggerPrg *pT = pParse->pTriggerPrg;
112600  pParse->pTriggerPrg = pT->pNext;
112601  sqlite3DbFree(db, pT);
112602  }
112603 
112604 end_prepare:
112605 
112606  sqlite3ParserReset(pParse);
112607  sqlite3StackFree(db, pParse);
112608  rc = sqlite3ApiExit(db, rc);
112609  assert( (rc&db->errMask)==rc );
112610  return rc;
112611 }
112613  sqlite3 *db, /* Database handle. */
112614  const char *zSql, /* UTF-8 encoded SQL statement. */
112615  int nBytes, /* Length of zSql in bytes. */
112616  int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
112617  Vdbe *pOld, /* VM being reprepared */
112618  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112619  const char **pzTail /* OUT: End of parsed string */
112620 ){
112621  int rc;
112622 
112623 #ifdef SQLITE_ENABLE_API_ARMOR
112624  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
112625 #endif
112626  *ppStmt = 0;
112627  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
112628  return SQLITE_MISUSE_BKPT;
112629  }
112630  sqlite3_mutex_enter(db->mutex);
112631  sqlite3BtreeEnterAll(db);
112632  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
112633  if( rc==SQLITE_SCHEMA ){
112634  sqlite3_finalize(*ppStmt);
112635  rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
112636  }
112637  sqlite3BtreeLeaveAll(db);
112638  sqlite3_mutex_leave(db->mutex);
112639  assert( rc==SQLITE_OK || *ppStmt==0 );
112640  return rc;
112641 }
112642 
112643 /*
112644 ** Rerun the compilation of a statement after a schema change.
112645 **
112646 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
112647 ** if the statement cannot be recompiled because another connection has
112648 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
112649 ** occurs, return SQLITE_SCHEMA.
112650 */
112652  int rc;
112653  sqlite3_stmt *pNew;
112654  const char *zSql;
112655  sqlite3 *db;
112656 
112657  assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
112658  zSql = sqlite3_sql((sqlite3_stmt *)p);
112659  assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
112660  db = sqlite3VdbeDb(p);
112661  assert( sqlite3_mutex_held(db->mutex) );
112662  rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
112663  if( rc ){
112664  if( rc==SQLITE_NOMEM ){
112665  sqlite3OomFault(db);
112666  }
112667  assert( pNew==0 );
112668  return rc;
112669  }else{
112670  assert( pNew!=0 );
112671  }
112672  sqlite3VdbeSwap((Vdbe*)pNew, p);
112673  sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
112675  sqlite3VdbeFinalize((Vdbe*)pNew);
112676  return SQLITE_OK;
112677 }
112678 
112679 
112680 /*
112681 ** Two versions of the official API. Legacy and new use. In the legacy
112682 ** version, the original SQL text is not saved in the prepared statement
112683 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
112684 ** sqlite3_step(). In the new version, the original SQL text is retained
112685 ** and the statement is automatically recompiled if an schema change
112686 ** occurs.
112687 */
112689  sqlite3 *db, /* Database handle. */
112690  const char *zSql, /* UTF-8 encoded SQL statement. */
112691  int nBytes, /* Length of zSql in bytes. */
112692  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112693  const char **pzTail /* OUT: End of parsed string */
112694 ){
112695  int rc;
112696  rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
112697  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
112698  return rc;
112699 }
112701  sqlite3 *db, /* Database handle. */
112702  const char *zSql, /* UTF-8 encoded SQL statement. */
112703  int nBytes, /* Length of zSql in bytes. */
112704  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112705  const char **pzTail /* OUT: End of parsed string */
112706 ){
112707  int rc;
112708  rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
112709  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
112710  return rc;
112711 }
112712 
112713 
112714 #ifndef SQLITE_OMIT_UTF16
112715 /*
112716 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
112717 */
112719  sqlite3 *db, /* Database handle. */
112720  const void *zSql, /* UTF-16 encoded SQL statement. */
112721  int nBytes, /* Length of zSql in bytes. */
112722  int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
112723  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112724  const void **pzTail /* OUT: End of parsed string */
112725 ){
112726  /* This function currently works by first transforming the UTF-16
112727  ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
112728  ** tricky bit is figuring out the pointer to return in *pzTail.
112729  */
112730  char *zSql8;
112731  const char *zTail8 = 0;
112732  int rc = SQLITE_OK;
112733 
112734 #ifdef SQLITE_ENABLE_API_ARMOR
112735  if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
112736 #endif
112737  *ppStmt = 0;
112738  if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
112739  return SQLITE_MISUSE_BKPT;
112740  }
112741  if( nBytes>=0 ){
112742  int sz;
112743  const char *z = (const char*)zSql;
112744  for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
112745  nBytes = sz;
112746  }
112747  sqlite3_mutex_enter(db->mutex);
112748  zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
112749  if( zSql8 ){
112750  rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
112751  }
112752 
112753  if( zTail8 && pzTail ){
112754  /* If sqlite3_prepare returns a tail pointer, we calculate the
112755  ** equivalent pointer into the UTF-16 string by counting the unicode
112756  ** characters between zSql8 and zTail8, and then returning a pointer
112757  ** the same number of characters into the UTF-16 string.
112758  */
112759  int chars2_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
112760  *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars2_parsed);
112761  }
112762  sqlite3DbFree(db, zSql8);
112763  rc = sqlite3ApiExit(db, rc);
112764  sqlite3_mutex_leave(db->mutex);
112765  return rc;
112766 }
112767 
112768 /*
112769 ** Two versions of the official API. Legacy and new use. In the legacy
112770 ** version, the original SQL text is not saved in the prepared statement
112771 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
112772 ** sqlite3_step(). In the new version, the original SQL text is retained
112773 ** and the statement is automatically recompiled if an schema change
112774 ** occurs.
112775 */
112777  sqlite3 *db, /* Database handle. */
112778  const void *zSql, /* UTF-16 encoded SQL statement. */
112779  int nBytes, /* Length of zSql in bytes. */
112780  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112781  const void **pzTail /* OUT: End of parsed string */
112782 ){
112783  int rc;
112784  rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
112785  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
112786  return rc;
112787 }
112789  sqlite3 *db, /* Database handle. */
112790  const void *zSql, /* UTF-16 encoded SQL statement. */
112791  int nBytes, /* Length of zSql in bytes. */
112792  sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
112793  const void **pzTail /* OUT: End of parsed string */
112794 ){
112795  int rc;
112796  rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
112797  assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
112798  return rc;
112799 }
112800 
112801 #endif /* SQLITE_OMIT_UTF16 */
112802 
112803 /************** End of prepare.c *********************************************/
112804 /************** Begin file select.c ******************************************/
112805 /*
112806 ** 2001 September 15
112807 **
112808 ** The author disclaims copyright to this source code. In place of
112809 ** a legal notice, here is a blessing:
112810 **
112811 ** May you do good and not evil.
112812 ** May you find forgiveness for yourself and forgive others.
112813 ** May you share freely, never taking more than you give.
112814 **
112815 *************************************************************************
112816 ** This file contains C code routines that are called by the parser
112817 ** to handle SELECT statements in SQLite.
112818 */
112819 /* #include "sqliteInt.h" */
112820 
112821 /*
112822 ** Trace output macros
112823 */
112824 #if SELECTTRACE_ENABLED
112825 /***/ int sqlite3SelectTrace = 0;
112826 # define SELECTTRACE(K,P,S,X) \
112827  if(sqlite3SelectTrace&(K)) \
112828  sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",\
112829  (S)->zSelName,(S)),\
112830  sqlite3DebugPrintf X
112831 #else
112832 # define SELECTTRACE(K,P,S,X)
112833 #endif
112834 
112835 
112836 /*
112837 ** An instance of the following object is used to record information about
112838 ** how to process the DISTINCT keyword, to simplify passing that information
112839 ** into the selectInnerLoop() routine.
112840 */
112841 typedef struct DistinctCtx DistinctCtx;
112843  u8 isTnct; /* True if the DISTINCT keyword is present */
112844  u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
112845  int tabTnct; /* Ephemeral table used for DISTINCT processing */
112846  int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
112847 };
112848 
112849 /*
112850 ** An instance of the following object is used to record information about
112851 ** the ORDER BY (or GROUP BY) clause of query is being coded.
112852 */
112853 typedef struct SortCtx SortCtx;
112854 struct SortCtx {
112855  ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
112856  int nOBSat; /* Number of ORDER BY terms satisfied by indices */
112857  int iECursor; /* Cursor number for the sorter */
112858  int regReturn; /* Register holding block-output return address */
112859  int labelBkOut; /* Start label for the block-output subroutine */
112860  int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
112861  int labelDone; /* Jump here when done, ex: LIMIT reached */
112862  u8 sortFlags; /* Zero or more SORTFLAG_* bits */
112863 };
112864 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
112865 
112866 /*
112867 ** Delete all the content of a Select structure. Deallocate the structure
112868 ** itself only if bFree is true.
112869 */
112870 static void clearSelect(sqlite3 *db, Select *p, int bFree){
112871  while( p ){
112872  Select *pPrior = p->pPrior;
112873  sqlite3ExprListDelete(db, p->pEList);
112874  sqlite3SrcListDelete(db, p->pSrc);
112875  sqlite3ExprDelete(db, p->pWhere);
112877  sqlite3ExprDelete(db, p->pHaving);
112879  sqlite3ExprDelete(db, p->pLimit);
112880  sqlite3ExprDelete(db, p->pOffset);
112881  if( p->pWith ) sqlite3WithDelete(db, p->pWith);
112882  if( bFree ) sqlite3DbFree(db, p);
112883  p = pPrior;
112884  bFree = 1;
112885  }
112886 }
112887 
112888 /*
112889 ** Initialize a SelectDest structure.
112890 */
112891 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
112892  pDest->eDest = (u8)eDest;
112893  pDest->iSDParm = iParm;
112894  pDest->affSdst = 0;
112895  pDest->iSdst = 0;
112896  pDest->nSdst = 0;
112897 }
112898 
112899 
112900 /*
112901 ** Allocate a new Select structure and return a pointer to that
112902 ** structure.
112903 */
112905  Parse *pParse, /* Parsing context */
112906  ExprList *pEList, /* which columns to include in the result */
112907  SrcList *pSrc, /* the FROM clause -- which tables to scan */
112908  Expr *pWhere, /* the WHERE clause */
112909  ExprList *pGroupBy, /* the GROUP BY clause */
112910  Expr *pHaving, /* the HAVING clause */
112911  ExprList *pOrderBy, /* the ORDER BY clause */
112912  u32 selFlags, /* Flag parameters, such as SF_Distinct */
112913  Expr *pLimit, /* LIMIT value. NULL means not used */
112914  Expr *pOffset /* OFFSET value. NULL means no offset */
112915 ){
112916  Select *pNew;
112917  Select standin;
112918  sqlite3 *db = pParse->db;
112919  pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
112920  if( pNew==0 ){
112921  assert( db->mallocFailed );
112922  pNew = &standin;
112923  }
112924  if( pEList==0 ){
112925  pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ASTERISK,0));
112926  }
112927  pNew->pEList = pEList;
112928  pNew->op = TK_SELECT;
112929  pNew->selFlags = selFlags;
112930  pNew->iLimit = 0;
112931  pNew->iOffset = 0;
112932 #if SELECTTRACE_ENABLED
112933  pNew->zSelName[0] = 0;
112934 #endif
112935  pNew->addrOpenEphm[0] = -1;
112936  pNew->addrOpenEphm[1] = -1;
112937  pNew->nSelectRow = 0;
112938  if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
112939  pNew->pSrc = pSrc;
112940  pNew->pWhere = pWhere;
112941  pNew->pGroupBy = pGroupBy;
112942  pNew->pHaving = pHaving;
112943  pNew->pOrderBy = pOrderBy;
112944  pNew->pPrior = 0;
112945  pNew->pNext = 0;
112946  pNew->pLimit = pLimit;
112947  pNew->pOffset = pOffset;
112948  pNew->pWith = 0;
112949  assert( pOffset==0 || pLimit!=0 || pParse->nErr>0 || db->mallocFailed!=0 );
112950  if( db->mallocFailed ) {
112951  clearSelect(db, pNew, pNew!=&standin);
112952  pNew = 0;
112953  }else{
112954  assert( pNew->pSrc!=0 || pParse->nErr>0 );
112955  }
112956  assert( pNew!=&standin );
112957  return pNew;
112958 }
112959 
112960 #if SELECTTRACE_ENABLED
112961 /*
112962 ** Set the name of a Select object
112963 */
112964 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
112965  if( p && zName ){
112966  sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
112967  }
112968 }
112969 #endif
112970 
112971 
112972 /*
112973 ** Delete the given Select structure and all of its substructures.
112974 */
112976  if( p ) clearSelect(db, p, 1);
112977 }
112978 
112979 /*
112980 ** Return a pointer to the right-most SELECT statement in a compound.
112981 */
112983  while( p->pNext ) p = p->pNext;
112984  return p;
112985 }
112986 
112987 /*
112988 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
112989 ** type of join. Return an integer constant that expresses that type
112990 ** in terms of the following bit values:
112991 **
112992 ** JT_INNER
112993 ** JT_CROSS
112994 ** JT_OUTER
112995 ** JT_NATURAL
112996 ** JT_LEFT
112997 ** JT_RIGHT
112998 **
112999 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
113000 **
113001 ** If an illegal or unsupported join type is seen, then still return
113002 ** a join type, but put an error in the pParse structure.
113003 */
113005  int jointype = 0;
113006  Token *apAll[3];
113007  Token *p;
113008  /* 0123456789 123456789 123456789 123 */
113009  static const char zKeyText[] = "naturaleftouterightfullinnercross";
113010  static const struct {
113011  u8 i; /* Beginning of keyword text in zKeyText[] */
113012  u8 nChar; /* Length of the keyword in characters */
113013  u8 code; /* Join type mask */
113014  } aKeyword[] = {
113015  /* natural */ { 0, 7, JT_NATURAL },
113016  /* left */ { 6, 4, JT_LEFT|JT_OUTER },
113017  /* outer */ { 10, 5, JT_OUTER },
113018  /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
113019  /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
113020  /* inner */ { 23, 5, JT_INNER },
113021  /* cross */ { 28, 5, JT_INNER|JT_CROSS },
113022  };
113023  int i, j;
113024  apAll[0] = pA;
113025  apAll[1] = pB;
113026  apAll[2] = pC;
113027  for(i=0; i<3 && apAll[i]; i++){
113028  p = apAll[i];
113029  for(j=0; j<ArraySize(aKeyword); j++){
113030  if( p->n==aKeyword[j].nChar
113031  && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
113032  jointype |= aKeyword[j].code;
113033  break;
113034  }
113035  }
113036  testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
113037  if( j>=ArraySize(aKeyword) ){
113038  jointype |= JT_ERROR;
113039  break;
113040  }
113041  }
113042  if(
113043  (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
113044  (jointype & JT_ERROR)!=0
113045  ){
113046  const char *zSp = " ";
113047  assert( pB!=0 );
113048  if( pC==0 ){ zSp++; }
113049  sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
113050  "%T %T%s%T", pA, pB, zSp, pC);
113051  jointype = JT_INNER;
113052  }else if( (jointype & JT_OUTER)!=0
113053  && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
113054  sqlite3ErrorMsg(pParse,
113055  "RIGHT and FULL OUTER JOINs are not currently supported");
113056  jointype = JT_INNER;
113057  }
113058  return jointype;
113059 }
113060 
113061 /*
113062 ** Return the index of a column in a table. Return -1 if the column
113063 ** is not contained in the table.
113064 */
113065 static int columnIndex(Table *pTab, const char *zCol){
113066  int i;
113067  for(i=0; i<pTab->nCol; i++){
113068  if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
113069  }
113070  return -1;
113071 }
113072 
113073 /*
113074 ** Search the first N tables in pSrc, from left to right, looking for a
113075 ** table that has a column named zCol.
113076 **
113077 ** When found, set *piTab and *piCol to the table index and column index
113078 ** of the matching column and return TRUE.
113079 **
113080 ** If not found, return FALSE.
113081 */
113083  SrcList *pSrc, /* Array of tables to search */
113084  int N, /* Number of tables in pSrc->a[] to search */
113085  const char *zCol, /* Name of the column we are looking for */
113086  int *piTab, /* Write index of pSrc->a[] here */
113087  int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
113088 ){
113089  int i; /* For looping over tables in pSrc */
113090  int iCol; /* Index of column matching zCol */
113091 
113092  assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
113093  for(i=0; i<N; i++){
113094  iCol = columnIndex(pSrc->a[i].pTab, zCol);
113095  if( iCol>=0 ){
113096  if( piTab ){
113097  *piTab = i;
113098  *piCol = iCol;
113099  }
113100  return 1;
113101  }
113102  }
113103  return 0;
113104 }
113105 
113106 /*
113107 ** This function is used to add terms implied by JOIN syntax to the
113108 ** WHERE clause expression of a SELECT statement. The new term, which
113109 ** is ANDed with the existing WHERE clause, is of the form:
113110 **
113111 ** (tab1.col1 = tab2.col2)
113112 **
113113 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
113114 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
113115 ** column iColRight of tab2.
113116 */
113117 static void addWhereTerm(
113118  Parse *pParse, /* Parsing context */
113119  SrcList *pSrc, /* List of tables in FROM clause */
113120  int iLeft, /* Index of first table to join in pSrc */
113121  int iColLeft, /* Index of column in first table */
113122  int iRight, /* Index of second table in pSrc */
113123  int iColRight, /* Index of column in second table */
113124  int isOuterJoin, /* True if this is an OUTER join */
113125  Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
113126 ){
113127  sqlite3 *db = pParse->db;
113128  Expr *pE1;
113129  Expr *pE2;
113130  Expr *pEq;
113131 
113132  assert( iLeft<iRight );
113133  assert( pSrc->nSrc>iRight );
113134  assert( pSrc->a[iLeft].pTab );
113135  assert( pSrc->a[iRight].pTab );
113136 
113137  pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
113138  pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
113139 
113140  pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
113141  if( pEq && isOuterJoin ){
113145  pEq->iRightJoinTable = (i16)pE2->iTable;
113146  }
113147  *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
113148 }
113149 
113150 /*
113151 ** Set the EP_FromJoin property on all terms of the given expression.
113152 ** And set the Expr.iRightJoinTable to iTable for every term in the
113153 ** expression.
113154 **
113155 ** The EP_FromJoin property is used on terms of an expression to tell
113156 ** the LEFT OUTER JOIN processing logic that this term is part of the
113157 ** join restriction specified in the ON or USING clause and not a part
113158 ** of the more general WHERE clause. These terms are moved over to the
113159 ** WHERE clause during join processing but we need to remember that they
113160 ** originated in the ON or USING clause.
113161 **
113162 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
113163 ** expression depends on table iRightJoinTable even if that table is not
113164 ** explicitly mentioned in the expression. That information is needed
113165 ** for cases like this:
113166 **
113167 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
113168 **
113169 ** The where clause needs to defer the handling of the t1.x=5
113170 ** term until after the t2 loop of the join. In that way, a
113171 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
113172 ** defer the handling of t1.x=5, it will be processed immediately
113173 ** after the t1 loop and rows with t1.x!=5 will never appear in
113174 ** the output, which is incorrect.
113175 */
113176 static void setJoinExpr(Expr *p, int iTable){
113177  while( p ){
113181  p->iRightJoinTable = (i16)iTable;
113182  if( p->op==TK_FUNCTION && p->x.pList ){
113183  int i;
113184  for(i=0; i<p->x.pList->nExpr; i++){
113185  setJoinExpr(p->x.pList->a[i].pExpr, iTable);
113186  }
113187  }
113188  setJoinExpr(p->pLeft, iTable);
113189  p = p->pRight;
113190  }
113191 }
113192 
113193 /*
113194 ** This routine processes the join information for a SELECT statement.
113195 ** ON and USING clauses are converted into extra terms of the WHERE clause.
113196 ** NATURAL joins also create extra WHERE clause terms.
113197 **
113198 ** The terms of a FROM clause are contained in the Select.pSrc structure.
113199 ** The left most table is the first entry in Select.pSrc. The right-most
113200 ** table is the last entry. The join operator is held in the entry to
113201 ** the left. Thus entry 0 contains the join operator for the join between
113202 ** entries 0 and 1. Any ON or USING clauses associated with the join are
113203 ** also attached to the left entry.
113204 **
113205 ** This routine returns the number of errors encountered.
113206 */
113207 static int sqliteProcessJoin(Parse *pParse, Select *p){
113208  SrcList *pSrc; /* All tables in the FROM clause */
113209  int i, j; /* Loop counters */
113210  struct SrcList_item *pLeft; /* Left table being joined */
113211  struct SrcList_item *pRight; /* Right table being joined */
113212 
113213  pSrc = p->pSrc;
113214  pLeft = &pSrc->a[0];
113215  pRight = &pLeft[1];
113216  for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
113217  Table *pLeftTab = pLeft->pTab;
113218  Table *pRightTab = pRight->pTab;
113219  int isOuter;
113220 
113221  if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
113222  isOuter = (pRight->fg.jointype & JT_OUTER)!=0;
113223 
113224  /* When the NATURAL keyword is present, add WHERE clause terms for
113225  ** every column that the two tables have in common.
113226  */
113227  if( pRight->fg.jointype & JT_NATURAL ){
113228  if( pRight->pOn || pRight->pUsing ){
113229  sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
113230  "an ON or USING clause", 0);
113231  return 1;
113232  }
113233  for(j=0; j<pRightTab->nCol; j++){
113234  char *zName; /* Name of column in the right table */
113235  int iLeft; /* Matching left table */
113236  int iLeftCol; /* Matching column in the left table */
113237 
113238  zName = pRightTab->aCol[j].zName;
113239  if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
113240  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
113241  isOuter, &p->pWhere);
113242  }
113243  }
113244  }
113245 
113246  /* Disallow both ON and USING clauses in the same join
113247  */
113248  if( pRight->pOn && pRight->pUsing ){
113249  sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
113250  "clauses in the same join");
113251  return 1;
113252  }
113253 
113254  /* Add the ON clause to the end of the WHERE clause, connected by
113255  ** an AND operator.
113256  */
113257  if( pRight->pOn ){
113258  if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
113259  p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
113260  pRight->pOn = 0;
113261  }
113262 
113263  /* Create extra terms on the WHERE clause for each column named
113264  ** in the USING clause. Example: If the two tables to be joined are
113265  ** A and B and the USING clause names X, Y, and Z, then add this
113266  ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
113267  ** Report an error if any column mentioned in the USING clause is
113268  ** not contained in both tables to be joined.
113269  */
113270  if( pRight->pUsing ){
113271  IdList *pList = pRight->pUsing;
113272  for(j=0; j<pList->nId; j++){
113273  char *zName; /* Name of the term in the USING clause */
113274  int iLeft; /* Table on the left with matching column name */
113275  int iLeftCol; /* Column number of matching column on the left */
113276  int iRightCol; /* Column number of matching column on the right */
113277 
113278  zName = pList->a[j].zName;
113279  iRightCol = columnIndex(pRightTab, zName);
113280  if( iRightCol<0
113281  || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
113282  ){
113283  sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
113284  "not present in both tables", zName);
113285  return 1;
113286  }
113287  addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
113288  isOuter, &p->pWhere);
113289  }
113290  }
113291  }
113292  return 0;
113293 }
113294 
113295 /* Forward reference */
113296 static KeyInfo *keyInfoFromExprList(
113297  Parse *pParse, /* Parsing context */
113298  ExprList *pList, /* Form the KeyInfo object from this ExprList */
113299  int iStart, /* Begin with this column of pList */
113300  int nExtra /* Add this many extra columns to the end */
113301 );
113302 
113303 /*
113304 ** Generate code that will push the record in registers regData
113305 ** through regData+nData-1 onto the sorter.
113306 */
113307 static void pushOntoSorter(
113308  Parse *pParse, /* Parser context */
113309  SortCtx *pSort, /* Information about the ORDER BY clause */
113310  Select *pSelect, /* The whole SELECT statement */
113311  int regData, /* First register holding data to be sorted */
113312  int regOrigData, /* First register holding data before packing */
113313  int nData, /* Number of elements in the data array */
113314  int nPrefixReg /* No. of reg prior to regData available for use */
113315 ){
113316  Vdbe *v = pParse->pVdbe; /* Stmt under construction */
113317  int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
113318  int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
113319  int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
113320  int regBase; /* Regs for sorter record */
113321  int regRecord = ++pParse->nMem; /* Assembled sorter record */
113322  int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
113323  int op; /* Opcode to add sorter record to sorter */
113324  int iLimit; /* LIMIT counter */
113325 
113326  assert( bSeq==0 || bSeq==1 );
113327  assert( nData==1 || regData==regOrigData );
113328  if( nPrefixReg ){
113329  assert( nPrefixReg==nExpr+bSeq );
113330  regBase = regData - nExpr - bSeq;
113331  }else{
113332  regBase = pParse->nMem + 1;
113333  pParse->nMem += nBase;
113334  }
113335  assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
113336  iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
113337  pSort->labelDone = sqlite3VdbeMakeLabel(v);
113338  sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
113340  if( bSeq ){
113341  sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
113342  }
113343  if( nPrefixReg==0 ){
113344  sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
113345  }
113346  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
113347  if( nOBSat>0 ){
113348  int regPrevKey; /* The first nOBSat columns of the previous row */
113349  int addrFirst; /* Address of the OP_IfNot opcode */
113350  int addrJmp; /* Address of the OP_Jump opcode */
113351  VdbeOp *pOp; /* Opcode that opens the sorter */
113352  int nKey; /* Number of sorting key columns, including OP_Sequence */
113353  KeyInfo *pKI; /* Original KeyInfo on the sorter table */
113354 
113355  regPrevKey = pParse->nMem+1;
113356  pParse->nMem += pSort->nOBSat;
113357  nKey = nExpr - pSort->nOBSat + bSeq;
113358  if( bSeq ){
113359  addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
113360  }else{
113361  addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
113362  }
113363  VdbeCoverage(v);
113364  sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
113365  pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
113366  if( pParse->db->mallocFailed ) return;
113367  pOp->p2 = nKey + nData;
113368  pKI = pOp->p4.pKeyInfo;
113369  memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
113370  sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
113371  testcase( pKI->nXField>2 );
113372  pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
113373  pKI->nXField-1);
113374  addrJmp = sqlite3VdbeCurrentAddr(v);
113375  sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
113376  pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
113377  pSort->regReturn = ++pParse->nMem;
113378  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
113380  if( iLimit ){
113381  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
113382  VdbeCoverage(v);
113383  }
113384  sqlite3VdbeJumpHere(v, addrFirst);
113385  sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
113386  sqlite3VdbeJumpHere(v, addrJmp);
113387  }
113388  if( pSort->sortFlags & SORTFLAG_UseSorter ){
113389  op = OP_SorterInsert;
113390  }else{
113391  op = OP_IdxInsert;
113392  }
113393  sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
113394  if( iLimit ){
113395  int addr;
113396  addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, 1); VdbeCoverage(v);
113397  sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
113398  sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
113399  sqlite3VdbeJumpHere(v, addr);
113400  }
113401 }
113402 
113403 /*
113404 ** Add code to implement the OFFSET
113405 */
113406 static void codeOffset(
113407  Vdbe *v, /* Generate code into this VM */
113408  int iOffset, /* Register holding the offset counter */
113409  int iContinue /* Jump here to skip the current record */
113410 ){
113411  if( iOffset>0 ){
113412  sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
113413  VdbeComment((v, "OFFSET"));
113414  }
113415 }
113416 
113417 /*
113418 ** Add code that will check to make sure the N registers starting at iMem
113419 ** form a distinct entry. iTab is a sorting index that holds previously
113420 ** seen combinations of the N values. A new entry is made in iTab
113421 ** if the current N values are new.
113422 **
113423 ** A jump to addrRepeat is made and the N+1 values are popped from the
113424 ** stack if the top N elements are not distinct.
113425 */
113426 static void codeDistinct(
113427  Parse *pParse, /* Parsing and code generating context */
113428  int iTab, /* A sorting index used to test for distinctness */
113429  int addrRepeat, /* Jump to here if not distinct */
113430  int N, /* Number of elements */
113431  int iMem /* First element */
113432 ){
113433  Vdbe *v;
113434  int r1;
113435 
113436  v = pParse->pVdbe;
113437  r1 = sqlite3GetTempReg(pParse);
113438  sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
113439  sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
113440  sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
113441  sqlite3ReleaseTempReg(pParse, r1);
113442 }
113443 
113444 #ifndef SQLITE_OMIT_SUBQUERY
113445 /*
113446 ** Generate an error message when a SELECT is used within a subexpression
113447 ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
113448 ** column. We do this in a subroutine because the error used to occur
113449 ** in multiple places. (The error only occurs in one place now, but we
113450 ** retain the subroutine to minimize code disruption.)
113451 */
113453  Parse *pParse, /* Parse context. */
113454  SelectDest *pDest, /* Destination of SELECT results */
113455  int nExpr /* Number of result columns returned by SELECT */
113456 ){
113457  int eDest = pDest->eDest;
113458  if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
113459  sqlite3ErrorMsg(pParse, "only a single result allowed for "
113460  "a SELECT that is part of an expression");
113461  return 1;
113462  }else{
113463  return 0;
113464  }
113465 }
113466 #endif
113467 
113468 /*
113469 ** This routine generates the code for the inside of the inner loop
113470 ** of a SELECT.
113471 **
113472 ** If srcTab is negative, then the pEList expressions
113473 ** are evaluated in order to get the data for this row. If srcTab is
113474 ** zero or more, then data is pulled from srcTab and pEList is used only
113475 ** to get number columns and the datatype for each column.
113476 */
113477 static void selectInnerLoop(
113478  Parse *pParse, /* The parser context */
113479  Select *p, /* The complete select statement being coded */
113480  ExprList *pEList, /* List of values being extracted */
113481  int srcTab, /* Pull data from this table */
113482  SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
113483  DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
113484  SelectDest *pDest, /* How to dispose of the results */
113485  int iContinue, /* Jump here to continue with next row */
113486  int iBreak /* Jump here to break out of the inner loop */
113487 ){
113488  Vdbe *v = pParse->pVdbe;
113489  int i;
113490  int hasDistinct; /* True if the DISTINCT keyword is present */
113491  int regResult; /* Start of memory holding result set */
113492  int eDest = pDest->eDest; /* How to dispose of results */
113493  int iParm = pDest->iSDParm; /* First argument to disposal method */
113494  int nResultCol; /* Number of result columns */
113495  int nPrefixReg = 0; /* Number of extra registers before regResult */
113496 
113497  assert( v );
113498  assert( pEList!=0 );
113499  hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
113500  if( pSort && pSort->pOrderBy==0 ) pSort = 0;
113501  if( pSort==0 && !hasDistinct ){
113502  assert( iContinue!=0 );
113503  codeOffset(v, p->iOffset, iContinue);
113504  }
113505 
113506  /* Pull the requested columns.
113507  */
113508  nResultCol = pEList->nExpr;
113509 
113510  if( pDest->iSdst==0 ){
113511  if( pSort ){
113512  nPrefixReg = pSort->pOrderBy->nExpr;
113513  if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
113514  pParse->nMem += nPrefixReg;
113515  }
113516  pDest->iSdst = pParse->nMem+1;
113517  pParse->nMem += nResultCol;
113518  }else if( pDest->iSdst+nResultCol > pParse->nMem ){
113519  /* This is an error condition that can result, for example, when a SELECT
113520  ** on the right-hand side of an INSERT contains more result columns than
113521  ** there are columns in the table on the left. The error will be caught
113522  ** and reported later. But we need to make sure enough memory is allocated
113523  ** to avoid other spurious errors in the meantime. */
113524  pParse->nMem += nResultCol;
113525  }
113526  pDest->nSdst = nResultCol;
113527  regResult = pDest->iSdst;
113528  if( srcTab>=0 ){
113529  for(i=0; i<nResultCol; i++){
113530  sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
113531  VdbeComment((v, "%s", pEList->a[i].zName));
113532  }
113533  }else if( eDest!=SRT_Exists ){
113534  /* If the destination is an EXISTS(...) expression, the actual
113535  ** values returned by the SELECT are not required.
113536  */
113537  u8 ecelFlags;
113538  if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
113539  ecelFlags = SQLITE_ECEL_DUP;
113540  }else{
113541  ecelFlags = 0;
113542  }
113543  sqlite3ExprCodeExprList(pParse, pEList, regResult, 0, ecelFlags);
113544  }
113545 
113546  /* If the DISTINCT keyword was present on the SELECT statement
113547  ** and this row has been seen before, then do not make this row
113548  ** part of the result.
113549  */
113550  if( hasDistinct ){
113551  switch( pDistinct->eTnctType ){
113552  case WHERE_DISTINCT_ORDERED: {
113553  VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
113554  int iJump; /* Jump destination */
113555  int regPrev; /* Previous row content */
113556 
113557  /* Allocate space for the previous row */
113558  regPrev = pParse->nMem+1;
113559  pParse->nMem += nResultCol;
113560 
113561  /* Change the OP_OpenEphemeral coded earlier to an OP_Null
113562  ** sets the MEM_Cleared bit on the first register of the
113563  ** previous value. This will cause the OP_Ne below to always
113564  ** fail on the first iteration of the loop even if the first
113565  ** row is all NULLs.
113566  */
113567  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
113568  pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
113569  pOp->opcode = OP_Null;
113570  pOp->p1 = 1;
113571  pOp->p2 = regPrev;
113572 
113573  iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
113574  for(i=0; i<nResultCol; i++){
113575  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
113576  if( i<nResultCol-1 ){
113577  sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
113578  VdbeCoverage(v);
113579  }else{
113580  sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
113581  VdbeCoverage(v);
113582  }
113583  sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
113585  }
113586  assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
113587  sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
113588  break;
113589  }
113590 
113591  case WHERE_DISTINCT_UNIQUE: {
113592  sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
113593  break;
113594  }
113595 
113596  default: {
113597  assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
113598  codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol,
113599  regResult);
113600  break;
113601  }
113602  }
113603  if( pSort==0 ){
113604  codeOffset(v, p->iOffset, iContinue);
113605  }
113606  }
113607 
113608  switch( eDest ){
113609  /* In this mode, write each query result to the key of the temporary
113610  ** table iParm.
113611  */
113612 #ifndef SQLITE_OMIT_COMPOUND_SELECT
113613  case SRT_Union: {
113614  int r1;
113615  r1 = sqlite3GetTempReg(pParse);
113616  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
113617  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
113618  sqlite3ReleaseTempReg(pParse, r1);
113619  break;
113620  }
113621 
113622  /* Construct a record from the query result, but instead of
113623  ** saving that record, use it as a key to delete elements from
113624  ** the temporary table iParm.
113625  */
113626  case SRT_Except: {
113627  sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
113628  break;
113629  }
113630 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
113631 
113632  /* Store the result as data using a unique key.
113633  */
113634  case SRT_Fifo:
113635  case SRT_DistFifo:
113636  case SRT_Table:
113637  case SRT_EphemTab: {
113638  int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
113639  testcase( eDest==SRT_Table );
113640  testcase( eDest==SRT_EphemTab );
113641  testcase( eDest==SRT_Fifo );
113642  testcase( eDest==SRT_DistFifo );
113643  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
113644 #ifndef SQLITE_OMIT_CTE
113645  if( eDest==SRT_DistFifo ){
113646  /* If the destination is DistFifo, then cursor (iParm+1) is open
113647  ** on an ephemeral index. If the current row is already present
113648  ** in the index, do not write it to the output. If not, add the
113649  ** current row to the index and proceed with writing it to the
113650  ** output table as well. */
113651  int addr = sqlite3VdbeCurrentAddr(v) + 4;
113652  sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
113653  VdbeCoverage(v);
113654  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
113655  assert( pSort==0 );
113656  }
113657 #endif
113658  if( pSort ){
113659  pushOntoSorter(pParse, pSort, p, r1+nPrefixReg,regResult,1,nPrefixReg);
113660  }else{
113661  int r2 = sqlite3GetTempReg(pParse);
113662  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
113663  sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
113665  sqlite3ReleaseTempReg(pParse, r2);
113666  }
113667  sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
113668  break;
113669  }
113670 
113671 #ifndef SQLITE_OMIT_SUBQUERY
113672  /* If we are creating a set for an "expr IN (SELECT ...)" construct,
113673  ** then there should be a single item on the stack. Write this
113674  ** item into the set table with bogus data.
113675  */
113676  case SRT_Set: {
113677  assert( nResultCol==1 );
113678  pDest->affSdst =
113679  sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
113680  if( pSort ){
113681  /* At first glance you would think we could optimize out the
113682  ** ORDER BY in this case since the order of entries in the set
113683  ** does not matter. But there might be a LIMIT clause, in which
113684  ** case the order does matter */
113685  pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
113686  }else{
113687  int r1 = sqlite3GetTempReg(pParse);
113688  sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
113689  sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
113690  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
113691  sqlite3ReleaseTempReg(pParse, r1);
113692  }
113693  break;
113694  }
113695 
113696  /* If any row exist in the result set, record that fact and abort.
113697  */
113698  case SRT_Exists: {
113699  sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
113700  /* The LIMIT clause will terminate the loop for us */
113701  break;
113702  }
113703 
113704  /* If this is a scalar select that is part of an expression, then
113705  ** store the results in the appropriate memory cell and break out
113706  ** of the scan loop.
113707  */
113708  case SRT_Mem: {
113709  assert( nResultCol==1 );
113710  if( pSort ){
113711  pushOntoSorter(pParse, pSort, p, regResult, regResult, 1, nPrefixReg);
113712  }else{
113713  assert( regResult==iParm );
113714  /* The LIMIT clause will jump out of the loop for us */
113715  }
113716  break;
113717  }
113718 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
113719 
113720  case SRT_Coroutine: /* Send data to a co-routine */
113721  case SRT_Output: { /* Return the results */
113722  testcase( eDest==SRT_Coroutine );
113723  testcase( eDest==SRT_Output );
113724  if( pSort ){
113725  pushOntoSorter(pParse, pSort, p, regResult, regResult, nResultCol,
113726  nPrefixReg);
113727  }else if( eDest==SRT_Coroutine ){
113728  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
113729  }else{
113730  sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
113731  sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
113732  }
113733  break;
113734  }
113735 
113736 #ifndef SQLITE_OMIT_CTE
113737  /* Write the results into a priority queue that is order according to
113738  ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
113739  ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
113740  ** pSO->nExpr columns, then make sure all keys are unique by adding a
113741  ** final OP_Sequence column. The last column is the record as a blob.
113742  */
113743  case SRT_DistQueue:
113744  case SRT_Queue: {
113745  int nKey;
113746  int r1, r2, r3;
113747  int addrTest = 0;
113748  ExprList *pSO;
113749  pSO = pDest->pOrderBy;
113750  assert( pSO );
113751  nKey = pSO->nExpr;
113752  r1 = sqlite3GetTempReg(pParse);
113753  r2 = sqlite3GetTempRange(pParse, nKey+2);
113754  r3 = r2+nKey+1;
113755  if( eDest==SRT_DistQueue ){
113756  /* If the destination is DistQueue, then cursor (iParm+1) is open
113757  ** on a second ephemeral index that holds all values every previously
113758  ** added to the queue. */
113759  addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
113760  regResult, nResultCol);
113761  VdbeCoverage(v);
113762  }
113763  sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
113764  if( eDest==SRT_DistQueue ){
113765  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
113767  }
113768  for(i=0; i<nKey; i++){
113770  regResult + pSO->a[i].u.x.iOrderByCol - 1,
113771  r2+i);
113772  }
113773  sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
113774  sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
113775  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
113776  if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
113777  sqlite3ReleaseTempReg(pParse, r1);
113778  sqlite3ReleaseTempRange(pParse, r2, nKey+2);
113779  break;
113780  }
113781 #endif /* SQLITE_OMIT_CTE */
113782 
113783 
113784 
113785 #if !defined(SQLITE_OMIT_TRIGGER)
113786  /* Discard the results. This is used for SELECT statements inside
113787  ** the body of a TRIGGER. The purpose of such selects is to call
113788  ** user-defined functions that have side effects. We do not care
113789  ** about the actual results of the select.
113790  */
113791  default: {
113792  assert( eDest==SRT_Discard );
113793  break;
113794  }
113795 #endif
113796  }
113797 
113798  /* Jump to the end of the loop if the LIMIT is reached. Except, if
113799  ** there is a sorter, in which case the sorter has already limited
113800  ** the output for us.
113801  */
113802  if( pSort==0 && p->iLimit ){
113804  }
113805 }
113806 
113807 /*
113808 ** Allocate a KeyInfo object sufficient for an index of N key columns and
113809 ** X extra columns.
113810 */
113811 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
113812  int nExtra = (N+X)*(sizeof(CollSeq*)+1);
113813  KeyInfo *p = sqlite3Malloc(sizeof(KeyInfo) + nExtra);
113814  if( p ){
113815  p->aSortOrder = (u8*)&p->aColl[N+X];
113816  p->nField = (u16)N;
113817  p->nXField = (u16)X;
113818  p->enc = ENC(db);
113819  p->db = db;
113820  p->nRef = 1;
113821  memset(&p[1], 0, nExtra);
113822  }else{
113823  sqlite3OomFault(db);
113824  }
113825  return p;
113826 }
113827 
113828 /*
113829 ** Deallocate a KeyInfo object
113830 */
113832  if( p ){
113833  assert( p->nRef>0 );
113834  p->nRef--;
113835  if( p->nRef==0 ) sqlite3DbFree(0, p);
113836  }
113837 }
113838 
113839 /*
113840 ** Make a new pointer to a KeyInfo object
113841 */
113843  if( p ){
113844  assert( p->nRef>0 );
113845  p->nRef++;
113846  }
113847  return p;
113848 }
113849 
113850 #ifdef SQLITE_DEBUG
113851 /*
113852 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
113853 ** can only be changed if this is just a single reference to the object.
113854 **
113855 ** This routine is used only inside of assert() statements.
113856 */
113857 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
113858 #endif /* SQLITE_DEBUG */
113859 
113860 /*
113861 ** Given an expression list, generate a KeyInfo structure that records
113862 ** the collating sequence for each expression in that expression list.
113863 **
113864 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
113865 ** KeyInfo structure is appropriate for initializing a virtual index to
113866 ** implement that clause. If the ExprList is the result set of a SELECT
113867 ** then the KeyInfo structure is appropriate for initializing a virtual
113868 ** index to implement a DISTINCT test.
113869 **
113870 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
113871 ** function is responsible for seeing that this structure is eventually
113872 ** freed.
113873 */
113875  Parse *pParse, /* Parsing context */
113876  ExprList *pList, /* Form the KeyInfo object from this ExprList */
113877  int iStart, /* Begin with this column of pList */
113878  int nExtra /* Add this many extra columns to the end */
113879 ){
113880  int nExpr;
113881  KeyInfo *pInfo;
113882  struct ExprList_item *pItem;
113883  sqlite3 *db = pParse->db;
113884  int i;
113885 
113886  nExpr = pList->nExpr;
113887  pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
113888  if( pInfo ){
113889  assert( sqlite3KeyInfoIsWriteable(pInfo) );
113890  for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
113891  CollSeq *pColl;
113892  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
113893  if( !pColl ) pColl = db->pDfltColl;
113894  pInfo->aColl[i-iStart] = pColl;
113895  pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
113896  }
113897  }
113898  return pInfo;
113899 }
113900 
113901 /*
113902 ** Name of the connection operator, used for error messages.
113903 */
113904 static const char *selectOpName(int id){
113905  char *z;
113906  switch( id ){
113907  case TK_ALL: z = "UNION ALL"; break;
113908  case TK_INTERSECT: z = "INTERSECT"; break;
113909  case TK_EXCEPT: z = "EXCEPT"; break;
113910  default: z = "UNION"; break;
113911  }
113912  return z;
113913 }
113914 
113915 #ifndef SQLITE_OMIT_EXPLAIN
113916 /*
113917 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
113918 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
113919 ** where the caption is of the form:
113920 **
113921 ** "USE TEMP B-TREE FOR xxx"
113922 **
113923 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
113924 ** is determined by the zUsage argument.
113925 */
113926 static void explainTempTable(Parse *pParse, const char *zUsage){
113927  if( pParse->explain==2 ){
113928  Vdbe *v = pParse->pVdbe;
113929  char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
113930  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
113931  }
113932 }
113933 
113934 /*
113935 ** Assign expression b to lvalue a. A second, no-op, version of this macro
113936 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
113937 ** in sqlite3Select() to assign values to structure member variables that
113938 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
113939 ** code with #ifndef directives.
113940 */
113941 # define explainSetInteger(a, b) a = b
113942 
113943 #else
113944 /* No-op versions of the explainXXX() functions and macros. */
113945 # define explainTempTable(y,z)
113946 # define explainSetInteger(y,z)
113947 #endif
113948 
113949 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
113950 /*
113951 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
113952 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
113953 ** where the caption is of one of the two forms:
113954 **
113955 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
113956 ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
113957 **
113958 ** where iSub1 and iSub2 are the integers passed as the corresponding
113959 ** function parameters, and op is the text representation of the parameter
113960 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
113961 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
113962 ** false, or the second form if it is true.
113963 */
113964 static void explainComposite(
113965  Parse *pParse, /* Parse context */
113966  int op, /* One of TK_UNION, TK_EXCEPT etc. */
113967  int iSub1, /* Subquery id 1 */
113968  int iSub2, /* Subquery id 2 */
113969  int bUseTmp /* True if a temp table was used */
113970 ){
113971  assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
113972  if( pParse->explain==2 ){
113973  Vdbe *v = pParse->pVdbe;
113974  char *zMsg = sqlite3MPrintf(
113975  pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
113976  bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
113977  );
113978  sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
113979  }
113980 }
113981 #else
113982 /* No-op versions of the explainXXX() functions and macros. */
113983 # define explainComposite(v,w,x,y,z)
113984 #endif
113985 
113986 /*
113987 ** If the inner loop was generated using a non-null pOrderBy argument,
113988 ** then the results were placed in a sorter. After the loop is terminated
113989 ** we need to run the sorter and output the results. The following
113990 ** routine generates the code needed to do that.
113991 */
113992 static void generateSortTail(
113993  Parse *pParse, /* Parsing context */
113994  Select *p, /* The SELECT statement */
113995  SortCtx *pSort, /* Information on the ORDER BY clause */
113996  int nColumn, /* Number of columns of data */
113997  SelectDest *pDest /* Write the sorted results here */
113998 ){
113999  Vdbe *v = pParse->pVdbe; /* The prepared statement */
114000  int addrBreak = pSort->labelDone; /* Jump here to exit loop */
114001  int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
114002  int addr;
114003  int addrOnce = 0;
114004  int iTab;
114005  ExprList *pOrderBy = pSort->pOrderBy;
114006  int eDest = pDest->eDest;
114007  int iParm = pDest->iSDParm;
114008  int regRow;
114009  int regRowid;
114010  int nKey;
114011  int iSortTab; /* Sorter cursor to read from */
114012  int nSortData; /* Trailing values to read from sorter */
114013  int i;
114014  int bSeq; /* True if sorter record includes seq. no. */
114015 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
114016  struct ExprList_item *aOutEx = p->pEList->a;
114017 #endif
114018 
114019  assert( addrBreak<0 );
114020  if( pSort->labelBkOut ){
114021  sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
114022  sqlite3VdbeGoto(v, addrBreak);
114023  sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
114024  }
114025  iTab = pSort->iECursor;
114026  if( eDest==SRT_Output || eDest==SRT_Coroutine ){
114027  regRowid = 0;
114028  regRow = pDest->iSdst;
114029  nSortData = nColumn;
114030  }else{
114031  regRowid = sqlite3GetTempReg(pParse);
114032  regRow = sqlite3GetTempReg(pParse);
114033  nSortData = 1;
114034  }
114035  nKey = pOrderBy->nExpr - pSort->nOBSat;
114036  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114037  int regSortOut = ++pParse->nMem;
114038  iSortTab = pParse->nTab++;
114039  if( pSort->labelBkOut ){
114040  addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
114041  }
114042  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
114043  if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
114044  addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
114045  VdbeCoverage(v);
114046  codeOffset(v, p->iOffset, addrContinue);
114047  sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
114048  bSeq = 0;
114049  }else{
114050  addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
114051  codeOffset(v, p->iOffset, addrContinue);
114052  iSortTab = iTab;
114053  bSeq = 1;
114054  }
114055  for(i=0; i<nSortData; i++){
114056  sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
114057  VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
114058  }
114059  switch( eDest ){
114060  case SRT_EphemTab: {
114061  sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
114062  sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
114064  break;
114065  }
114066 #ifndef SQLITE_OMIT_SUBQUERY
114067  case SRT_Set: {
114068  assert( nColumn==1 );
114069  sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
114070  &pDest->affSdst, 1);
114071  sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
114072  sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
114073  break;
114074  }
114075  case SRT_Mem: {
114076  assert( nColumn==1 );
114077  sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
114078  /* The LIMIT clause will terminate the loop for us */
114079  break;
114080  }
114081 #endif
114082  default: {
114083  assert( eDest==SRT_Output || eDest==SRT_Coroutine );
114084  testcase( eDest==SRT_Output );
114085  testcase( eDest==SRT_Coroutine );
114086  if( eDest==SRT_Output ){
114087  sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
114088  sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
114089  }else{
114090  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
114091  }
114092  break;
114093  }
114094  }
114095  if( regRowid ){
114096  sqlite3ReleaseTempReg(pParse, regRow);
114097  sqlite3ReleaseTempReg(pParse, regRowid);
114098  }
114099  /* The bottom of the loop
114100  */
114101  sqlite3VdbeResolveLabel(v, addrContinue);
114102  if( pSort->sortFlags & SORTFLAG_UseSorter ){
114103  sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
114104  }else{
114105  sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
114106  }
114107  if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
114108  sqlite3VdbeResolveLabel(v, addrBreak);
114109 }
114110 
114111 /*
114112 ** Return a pointer to a string containing the 'declaration type' of the
114113 ** expression pExpr. The string may be treated as static by the caller.
114114 **
114115 ** Also try to estimate the size of the returned value and return that
114116 ** result in *pEstWidth.
114117 **
114118 ** The declaration type is the exact datatype definition extracted from the
114119 ** original CREATE TABLE statement if the expression is a column. The
114120 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
114121 ** is considered a column can be complex in the presence of subqueries. The
114122 ** result-set expression in all of the following SELECT statements is
114123 ** considered a column by this function.
114124 **
114125 ** SELECT col FROM tbl;
114126 ** SELECT (SELECT col FROM tbl;
114127 ** SELECT (SELECT col FROM tbl);
114128 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
114129 **
114130 ** The declaration type for any expression other than a column is NULL.
114131 **
114132 ** This routine has either 3 or 6 parameters depending on whether or not
114133 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
114134 */
114135 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114136 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
114137 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
114138 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
114139 #endif
114140 static const char *columnTypeImpl(
114141  NameContext *pNC,
114142  Expr *pExpr,
114143 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114144  const char **pzOrigDb,
114145  const char **pzOrigTab,
114146  const char **pzOrigCol,
114147 #endif
114148  u8 *pEstWidth
114149 ){
114150  char const *zType = 0;
114151  int j;
114152  u8 estWidth = 1;
114153 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114154  char const *zOrigDb = 0;
114155  char const *zOrigTab = 0;
114156  char const *zOrigCol = 0;
114157 #endif
114158 
114159  assert( pExpr!=0 );
114160  assert( pNC->pSrcList!=0 );
114161  switch( pExpr->op ){
114162  case TK_AGG_COLUMN:
114163  case TK_COLUMN: {
114164  /* The expression is a column. Locate the table the column is being
114165  ** extracted from in NameContext.pSrcList. This table may be real
114166  ** database table or a subquery.
114167  */
114168  Table *pTab = 0; /* Table structure column is extracted from */
114169  Select *pS = 0; /* Select the column is extracted from */
114170  int iCol = pExpr->iColumn; /* Index of column in pTab */
114171  testcase( pExpr->op==TK_AGG_COLUMN );
114172  testcase( pExpr->op==TK_COLUMN );
114173  while( pNC && !pTab ){
114174  SrcList *pTabList = pNC->pSrcList;
114175  for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
114176  if( j<pTabList->nSrc ){
114177  pTab = pTabList->a[j].pTab;
114178  pS = pTabList->a[j].pSelect;
114179  }else{
114180  pNC = pNC->pNext;
114181  }
114182  }
114183 
114184  if( pTab==0 ){
114185  /* At one time, code such as "SELECT new.x" within a trigger would
114186  ** cause this condition to run. Since then, we have restructured how
114187  ** trigger code is generated and so this condition is no longer
114188  ** possible. However, it can still be true for statements like
114189  ** the following:
114190  **
114191  ** CREATE TABLE t1(col INTEGER);
114192  ** SELECT (SELECT t1.col) FROM FROM t1;
114193  **
114194  ** when columnType() is called on the expression "t1.col" in the
114195  ** sub-select. In this case, set the column type to NULL, even
114196  ** though it should really be "INTEGER".
114197  **
114198  ** This is not a problem, as the column type of "t1.col" is never
114199  ** used. When columnType() is called on the expression
114200  ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
114201  ** branch below. */
114202  break;
114203  }
114204 
114205  assert( pTab && pExpr->pTab==pTab );
114206  if( pS ){
114207  /* The "table" is actually a sub-select or a view in the FROM clause
114208  ** of the SELECT statement. Return the declaration type and origin
114209  ** data for the result-set column of the sub-select.
114210  */
114211  if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
114212  /* If iCol is less than zero, then the expression requests the
114213  ** rowid of the sub-select or view. This expression is legal (see
114214  ** test case misc2.2.2) - it always evaluates to NULL.
114215  **
114216  ** The ALWAYS() is because iCol>=pS->pEList->nExpr will have been
114217  ** caught already by name resolution.
114218  */
114219  NameContext sNC;
114220  Expr *p = pS->pEList->a[iCol].pExpr;
114221  sNC.pSrcList = pS->pSrc;
114222  sNC.pNext = pNC;
114223  sNC.pParse = pNC->pParse;
114224  zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
114225  }
114226  }else if( pTab->pSchema ){
114227  /* A real table */
114228  assert( !pS );
114229  if( iCol<0 ) iCol = pTab->iPKey;
114230  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
114231 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114232  if( iCol<0 ){
114233  zType = "INTEGER";
114234  zOrigCol = "rowid";
114235  }else{
114236  zOrigCol = pTab->aCol[iCol].zName;
114237  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114238  estWidth = pTab->aCol[iCol].szEst;
114239  }
114240  zOrigTab = pTab->zName;
114241  if( pNC->pParse ){
114242  int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
114243  zOrigDb = pNC->pParse->db->aDb[iDb].zName;
114244  }
114245 #else
114246  if( iCol<0 ){
114247  zType = "INTEGER";
114248  }else{
114249  zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
114250  estWidth = pTab->aCol[iCol].szEst;
114251  }
114252 #endif
114253  }
114254  break;
114255  }
114256 #ifndef SQLITE_OMIT_SUBQUERY
114257  case TK_SELECT: {
114258  /* The expression is a sub-select. Return the declaration type and
114259  ** origin info for the single column in the result set of the SELECT
114260  ** statement.
114261  */
114262  NameContext sNC;
114263  Select *pS = pExpr->x.pSelect;
114264  Expr *p = pS->pEList->a[0].pExpr;
114265  assert( ExprHasProperty(pExpr, EP_xIsSelect) );
114266  sNC.pSrcList = pS->pSrc;
114267  sNC.pNext = pNC;
114268  sNC.pParse = pNC->pParse;
114269  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
114270  break;
114271  }
114272 #endif
114273  }
114274 
114275 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114276  if( pzOrigDb ){
114277  assert( pzOrigTab && pzOrigCol );
114278  *pzOrigDb = zOrigDb;
114279  *pzOrigTab = zOrigTab;
114280  *pzOrigCol = zOrigCol;
114281  }
114282 #endif
114283  if( pEstWidth ) *pEstWidth = estWidth;
114284  return zType;
114285 }
114286 
114287 /*
114288 ** Generate code that will tell the VDBE the declaration types of columns
114289 ** in the result set.
114290 */
114292  Parse *pParse, /* Parser context */
114293  SrcList *pTabList, /* List of tables */
114294  ExprList *pEList /* Expressions defining the result set */
114295 ){
114296 #ifndef SQLITE_OMIT_DECLTYPE
114297  Vdbe *v = pParse->pVdbe;
114298  int i;
114299  NameContext sNC;
114300  sNC.pSrcList = pTabList;
114301  sNC.pParse = pParse;
114302  for(i=0; i<pEList->nExpr; i++){
114303  Expr *p = pEList->a[i].pExpr;
114304  const char *zType;
114305 #ifdef SQLITE_ENABLE_COLUMN_METADATA
114306  const char *zOrigDb = 0;
114307  const char *zOrigTab = 0;
114308  const char *zOrigCol = 0;
114309  zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
114310 
114311  /* The vdbe must make its own copy of the column-type and other
114312  ** column specific strings, in case the schema is reset before this
114313  ** virtual machine is deleted.
114314  */
114318 #else
114319  zType = columnType(&sNC, p, 0, 0, 0, 0);
114320 #endif
114322  }
114323 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
114324 }
114325 
114326 /*
114327 ** Generate code that will tell the VDBE the names of columns
114328 ** in the result set. This information is used to provide the
114329 ** azCol[] values in the callback.
114330 */
114332  Parse *pParse, /* Parser context */
114333  SrcList *pTabList, /* List of tables */
114334  ExprList *pEList /* Expressions defining the result set */
114335 ){
114336  Vdbe *v = pParse->pVdbe;
114337  int i, j;
114338  sqlite3 *db = pParse->db;
114339  int fullNames, shortNames;
114340 
114341 #ifndef SQLITE_OMIT_EXPLAIN
114342  /* If this is an EXPLAIN, skip this step */
114343  if( pParse->explain ){
114344  return;
114345  }
114346 #endif
114347 
114348  if( pParse->colNamesSet || db->mallocFailed ) return;
114349  assert( v!=0 );
114350  assert( pTabList!=0 );
114351  pParse->colNamesSet = 1;
114352  fullNames = (db->flags & SQLITE_FullColNames)!=0;
114353  shortNames = (db->flags & SQLITE_ShortColNames)!=0;
114354  sqlite3VdbeSetNumCols(v, pEList->nExpr);
114355  for(i=0; i<pEList->nExpr; i++){
114356  Expr *p;
114357  p = pEList->a[i].pExpr;
114358  if( NEVER(p==0) ) continue;
114359  if( pEList->a[i].zName ){
114360  char *zName = pEList->a[i].zName;
114362  }else if( p->op==TK_COLUMN || p->op==TK_AGG_COLUMN ){
114363  Table *pTab;
114364  char *zCol;
114365  int iCol = p->iColumn;
114366  for(j=0; ALWAYS(j<pTabList->nSrc); j++){
114367  if( pTabList->a[j].iCursor==p->iTable ) break;
114368  }
114369  assert( j<pTabList->nSrc );
114370  pTab = pTabList->a[j].pTab;
114371  if( iCol<0 ) iCol = pTab->iPKey;
114372  assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
114373  if( iCol<0 ){
114374  zCol = "rowid";
114375  }else{
114376  zCol = pTab->aCol[iCol].zName;
114377  }
114378  if( !shortNames && !fullNames ){
114380  sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
114381  }else if( fullNames ){
114382  char *zName = 0;
114383  zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
114385  }else{
114387  }
114388  }else{
114389  const char *z = pEList->a[i].zSpan;
114390  z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
114392  }
114393  }
114394  generateColumnTypes(pParse, pTabList, pEList);
114395 }
114396 
114397 /*
114398 ** Given an expression list (which is really the list of expressions
114399 ** that form the result set of a SELECT statement) compute appropriate
114400 ** column names for a table that would hold the expression list.
114401 **
114402 ** All column names will be unique.
114403 **
114404 ** Only the column names are computed. Column.zType, Column.zColl,
114405 ** and other fields of Column are zeroed.
114406 **
114407 ** Return SQLITE_OK on success. If a memory allocation error occurs,
114408 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
114409 */
114411  Parse *pParse, /* Parsing context */
114412  ExprList *pEList, /* Expr list from which to derive column names */
114413  i16 *pnCol, /* Write the number of columns here */
114414  Column **paCol /* Write the new column list here */
114415 ){
114416  sqlite3 *db = pParse->db; /* Database connection */
114417  int i, j; /* Loop counters */
114418  u32 cnt; /* Index added to make the name unique */
114419  Column *aCol, *pCol; /* For looping over result columns */
114420  int nCol; /* Number of columns in the result set */
114421  Expr *p; /* Expression for a single result column */
114422  char *zName; /* Column name */
114423  int nName; /* Size of name in zName[] */
114424  Hash ht; /* Hash table of column names */
114425 
114426  sqlite3HashInit(&ht);
114427  if( pEList ){
114428  nCol = pEList->nExpr;
114429  aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
114430  testcase( aCol==0 );
114431  }else{
114432  nCol = 0;
114433  aCol = 0;
114434  }
114435  assert( nCol==(i16)nCol );
114436  *pnCol = nCol;
114437  *paCol = aCol;
114438 
114439  for(i=0, pCol=aCol; i<nCol && !db->mallocFailed; i++, pCol++){
114440  /* Get an appropriate name for the column
114441  */
114442  p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
114443  if( (zName = pEList->a[i].zName)!=0 ){
114444  /* If the column contains an "AS <name>" phrase, use <name> as the name */
114445  }else{
114446  Expr *pColExpr = p; /* The expression that is the result column name */
114447  Table *pTab; /* Table associated with this expression */
114448  while( pColExpr->op==TK_DOT ){
114449  pColExpr = pColExpr->pRight;
114450  assert( pColExpr!=0 );
114451  }
114452  if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
114453  /* For columns use the column name name */
114454  int iCol = pColExpr->iColumn;
114455  pTab = pColExpr->pTab;
114456  if( iCol<0 ) iCol = pTab->iPKey;
114457  zName = iCol>=0 ? pTab->aCol[iCol].zName : "rowid";
114458  }else if( pColExpr->op==TK_ID ){
114459  assert( !ExprHasProperty(pColExpr, EP_IntValue) );
114460  zName = pColExpr->u.zToken;
114461  }else{
114462  /* Use the original text of the column expression as its name */
114463  zName = pEList->a[i].zSpan;
114464  }
114465  }
114466  zName = sqlite3MPrintf(db, "%s", zName);
114467 
114468  /* Make sure the column name is unique. If the name is not unique,
114469  ** append an integer to the name so that it becomes unique.
114470  */
114471  cnt = 0;
114472  while( zName && sqlite3HashFind(&ht, zName)!=0 ){
114473  nName = sqlite3Strlen30(zName);
114474  if( nName>0 ){
114475  for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
114476  if( zName[j]==':' ) nName = j;
114477  }
114478  zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
114479  if( cnt>3 ) sqlite3_randomness(sizeof(cnt), &cnt);
114480  }
114481  pCol->zName = zName;
114483  if( zName && sqlite3HashInsert(&ht, zName, pCol)==pCol ){
114484  sqlite3OomFault(db);
114485  }
114486  }
114487  sqlite3HashClear(&ht);
114488  if( db->mallocFailed ){
114489  for(j=0; j<i; j++){
114490  sqlite3DbFree(db, aCol[j].zName);
114491  }
114492  sqlite3DbFree(db, aCol);
114493  *paCol = 0;
114494  *pnCol = 0;
114495  return SQLITE_NOMEM_BKPT;
114496  }
114497  return SQLITE_OK;
114498 }
114499 
114500 /*
114501 ** Add type and collation information to a column list based on
114502 ** a SELECT statement.
114503 **
114504 ** The column list presumably came from selectColumnNamesFromExprList().
114505 ** The column list has only names, not types or collations. This
114506 ** routine goes through and adds the types and collations.
114507 **
114508 ** This routine requires that all identifiers in the SELECT
114509 ** statement be resolved.
114510 */
114512  Parse *pParse, /* Parsing contexts */
114513  Table *pTab, /* Add column type information to this table */
114514  Select *pSelect /* SELECT used to determine types and collations */
114515 ){
114516  sqlite3 *db = pParse->db;
114517  NameContext sNC;
114518  Column *pCol;
114519  CollSeq *pColl;
114520  int i;
114521  Expr *p;
114522  struct ExprList_item *a;
114523  u64 szAll = 0;
114524 
114525  assert( pSelect!=0 );
114526  assert( (pSelect->selFlags & SF_Resolved)!=0 );
114527  assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
114528  if( db->mallocFailed ) return;
114529  memset(&sNC, 0, sizeof(sNC));
114530  sNC.pSrcList = pSelect->pSrc;
114531  a = pSelect->pEList->a;
114532  for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
114533  const char *zType;
114534  int n, m;
114535  p = a[i].pExpr;
114536  zType = columnType(&sNC, p, 0, 0, 0, &pCol->szEst);
114537  szAll += pCol->szEst;
114538  pCol->affinity = sqlite3ExprAffinity(p);
114539  if( zType && (m = sqlite3Strlen30(zType))>0 ){
114540  n = sqlite3Strlen30(pCol->zName);
114541  pCol->zName = sqlite3DbReallocOrFree(db, pCol->zName, n+m+2);
114542  if( pCol->zName ){
114543  memcpy(&pCol->zName[n+1], zType, m+1);
114544  pCol->colFlags |= COLFLAG_HASTYPE;
114545  }
114546  }
114547  if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_BLOB;
114548  pColl = sqlite3ExprCollSeq(pParse, p);
114549  if( pColl && pCol->zColl==0 ){
114550  pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
114551  }
114552  }
114553  pTab->szTabRow = sqlite3LogEst(szAll*4);
114554 }
114555 
114556 /*
114557 ** Given a SELECT statement, generate a Table structure that describes
114558 ** the result set of that SELECT.
114559 */
114561  Table *pTab;
114562  sqlite3 *db = pParse->db;
114563  int savedFlags;
114564 
114565  savedFlags = db->flags;
114566  db->flags &= ~SQLITE_FullColNames;
114567  db->flags |= SQLITE_ShortColNames;
114568  sqlite3SelectPrep(pParse, pSelect, 0);
114569  if( pParse->nErr ) return 0;
114570  while( pSelect->pPrior ) pSelect = pSelect->pPrior;
114571  db->flags = savedFlags;
114572  pTab = sqlite3DbMallocZero(db, sizeof(Table) );
114573  if( pTab==0 ){
114574  return 0;
114575  }
114576  /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
114577  ** is disabled */
114578  assert( db->lookaside.bDisable );
114579  pTab->nRef = 1;
114580  pTab->zName = 0;
114581  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
114582  sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
114583  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSelect);
114584  pTab->iPKey = -1;
114585  if( db->mallocFailed ){
114586  sqlite3DeleteTable(db, pTab);
114587  return 0;
114588  }
114589  return pTab;
114590 }
114591 
114592 /*
114593 ** Get a VDBE for the given parser context. Create a new one if necessary.
114594 ** If an error occurs, return NULL and leave a message in pParse.
114595 */
114597  Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
114598  if( v ) sqlite3VdbeAddOp0(v, OP_Init);
114599  if( pParse->pToplevel==0
114601  ){
114602  pParse->okConstFactor = 1;
114603  }
114604  return v;
114605 }
114607  Vdbe *v = pParse->pVdbe;
114608  return v ? v : allocVdbe(pParse);
114609 }
114610 
114611 
114612 /*
114613 ** Compute the iLimit and iOffset fields of the SELECT based on the
114614 ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
114615 ** that appear in the original SQL statement after the LIMIT and OFFSET
114616 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
114617 ** are the integer memory register numbers for counters used to compute
114618 ** the limit and offset. If there is no limit and/or offset, then
114619 ** iLimit and iOffset are negative.
114620 **
114621 ** This routine changes the values of iLimit and iOffset only if
114622 ** a limit or offset is defined by pLimit and pOffset. iLimit and
114623 ** iOffset should have been preset to appropriate default values (zero)
114624 ** prior to calling this routine.
114625 **
114626 ** The iOffset register (if it exists) is initialized to the value
114627 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
114628 ** iOffset+1 is initialized to LIMIT+OFFSET.
114629 **
114630 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
114631 ** redefined. The UNION ALL operator uses this property to force
114632 ** the reuse of the same limit and offset registers across multiple
114633 ** SELECT statements.
114634 */
114635 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
114636  Vdbe *v = 0;
114637  int iLimit = 0;
114638  int iOffset;
114639  int n;
114640  if( p->iLimit ) return;
114641 
114642  /*
114643  ** "LIMIT -1" always shows all rows. There is some
114644  ** controversy about what the correct behavior should be.
114645  ** The current implementation interprets "LIMIT 0" to mean
114646  ** no rows.
114647  */
114648  sqlite3ExprCacheClear(pParse);
114649  assert( p->pOffset==0 || p->pLimit!=0 );
114650  if( p->pLimit ){
114651  p->iLimit = iLimit = ++pParse->nMem;
114652  v = sqlite3GetVdbe(pParse);
114653  assert( v!=0 );
114654  if( sqlite3ExprIsInteger(p->pLimit, &n) ){
114655  sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
114656  VdbeComment((v, "LIMIT counter"));
114657  if( n==0 ){
114658  sqlite3VdbeGoto(v, iBreak);
114659  }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
114660  p->nSelectRow = sqlite3LogEst((u64)n);
114661  p->selFlags |= SF_FixedLimit;
114662  }
114663  }else{
114664  sqlite3ExprCode(pParse, p->pLimit, iLimit);
114665  sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
114666  VdbeComment((v, "LIMIT counter"));
114667  sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
114668  }
114669  if( p->pOffset ){
114670  p->iOffset = iOffset = ++pParse->nMem;
114671  pParse->nMem++; /* Allocate an extra register for limit+offset */
114672  sqlite3ExprCode(pParse, p->pOffset, iOffset);
114673  sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
114674  VdbeComment((v, "OFFSET counter"));
114675  sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
114676  VdbeComment((v, "LIMIT+OFFSET"));
114677  }
114678  }
114679 }
114680 
114681 #ifndef SQLITE_OMIT_COMPOUND_SELECT
114682 /*
114683 ** Return the appropriate collating sequence for the iCol-th column of
114684 ** the result set for the compound-select statement "p". Return NULL if
114685 ** the column has no default collating sequence.
114686 **
114687 ** The collating sequence for the compound select is taken from the
114688 ** left-most term of the select that has a collating sequence.
114689 */
114690 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
114691  CollSeq *pRet;
114692  if( p->pPrior ){
114693  pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
114694  }else{
114695  pRet = 0;
114696  }
114697  assert( iCol>=0 );
114698  /* iCol must be less than p->pEList->nExpr. Otherwise an error would
114699  ** have been thrown during name resolution and we would not have gotten
114700  ** this far */
114701  if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
114702  pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
114703  }
114704  return pRet;
114705 }
114706 
114707 /*
114708 ** The select statement passed as the second parameter is a compound SELECT
114709 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
114710 ** structure suitable for implementing the ORDER BY.
114711 **
114712 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
114713 ** function is responsible for ensuring that this structure is eventually
114714 ** freed.
114715 */
114716 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
114717  ExprList *pOrderBy = p->pOrderBy;
114718  int nOrderBy = p->pOrderBy->nExpr;
114719  sqlite3 *db = pParse->db;
114720  KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
114721  if( pRet ){
114722  int i;
114723  for(i=0; i<nOrderBy; i++){
114724  struct ExprList_item *pItem = &pOrderBy->a[i];
114725  Expr *pTerm = pItem->pExpr;
114726  CollSeq *pColl;
114727 
114728  if( pTerm->flags & EP_Collate ){
114729  pColl = sqlite3ExprCollSeq(pParse, pTerm);
114730  }else{
114731  pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
114732  if( pColl==0 ) pColl = db->pDfltColl;
114733  pOrderBy->a[i].pExpr =
114734  sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
114735  }
114736  assert( sqlite3KeyInfoIsWriteable(pRet) );
114737  pRet->aColl[i] = pColl;
114738  pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
114739  }
114740  }
114741 
114742  return pRet;
114743 }
114744 
114745 #ifndef SQLITE_OMIT_CTE
114746 /*
114747 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
114748 ** query of the form:
114749 **
114750 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
114751 ** \___________/ \_______________/
114752 ** p->pPrior p
114753 **
114754 **
114755 ** There is exactly one reference to the recursive-table in the FROM clause
114756 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
114757 **
114758 ** The setup-query runs once to generate an initial set of rows that go
114759 ** into a Queue table. Rows are extracted from the Queue table one by
114760 ** one. Each row extracted from Queue is output to pDest. Then the single
114761 ** extracted row (now in the iCurrent table) becomes the content of the
114762 ** recursive-table for a recursive-query run. The output of the recursive-query
114763 ** is added back into the Queue table. Then another row is extracted from Queue
114764 ** and the iteration continues until the Queue table is empty.
114765 **
114766 ** If the compound query operator is UNION then no duplicate rows are ever
114767 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
114768 ** that have ever been inserted into Queue and causes duplicates to be
114769 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
114770 **
114771 ** If the query has an ORDER BY, then entries in the Queue table are kept in
114772 ** ORDER BY order and the first entry is extracted for each cycle. Without
114773 ** an ORDER BY, the Queue table is just a FIFO.
114774 **
114775 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
114776 ** have been output to pDest. A LIMIT of zero means to output no rows and a
114777 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
114778 ** with a positive value, then the first OFFSET outputs are discarded rather
114779 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
114780 ** rows have been skipped.
114781 */
114783  Parse *pParse, /* Parsing context */
114784  Select *p, /* The recursive SELECT to be coded */
114785  SelectDest *pDest /* What to do with query results */
114786 ){
114787  SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
114788  int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
114789  Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
114790  Select *pSetup = p->pPrior; /* The setup query */
114791  int addrTop; /* Top of the loop */
114792  int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
114793  int iCurrent = 0; /* The Current table */
114794  int regCurrent; /* Register holding Current table */
114795  int iQueue; /* The Queue table */
114796  int iDistinct = 0; /* To ensure unique results if UNION */
114797  int eDest = SRT_Fifo; /* How to write to Queue */
114798  SelectDest destQueue; /* SelectDest targetting the Queue table */
114799  int i; /* Loop counter */
114800  int rc; /* Result code */
114801  ExprList *pOrderBy; /* The ORDER BY clause */
114802  Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
114803  int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
114804 
114805  /* Obtain authorization to do a recursive query */
114806  if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
114807 
114808  /* Process the LIMIT and OFFSET clauses, if they exist */
114809  addrBreak = sqlite3VdbeMakeLabel(v);
114810  computeLimitRegisters(pParse, p, addrBreak);
114811  pLimit = p->pLimit;
114812  pOffset = p->pOffset;
114813  regLimit = p->iLimit;
114814  regOffset = p->iOffset;
114815  p->pLimit = p->pOffset = 0;
114816  p->iLimit = p->iOffset = 0;
114817  pOrderBy = p->pOrderBy;
114818 
114819  /* Locate the cursor number of the Current table */
114820  for(i=0; ALWAYS(i<pSrc->nSrc); i++){
114821  if( pSrc->a[i].fg.isRecursive ){
114822  iCurrent = pSrc->a[i].iCursor;
114823  break;
114824  }
114825  }
114826 
114827  /* Allocate cursors numbers for Queue and Distinct. The cursor number for
114828  ** the Distinct table must be exactly one greater than Queue in order
114829  ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
114830  iQueue = pParse->nTab++;
114831  if( p->op==TK_UNION ){
114832  eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
114833  iDistinct = pParse->nTab++;
114834  }else{
114835  eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
114836  }
114837  sqlite3SelectDestInit(&destQueue, eDest, iQueue);
114838 
114839  /* Allocate cursors for Current, Queue, and Distinct. */
114840  regCurrent = ++pParse->nMem;
114841  sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
114842  if( pOrderBy ){
114843  KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
114844  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
114845  (char*)pKeyInfo, P4_KEYINFO);
114846  destQueue.pOrderBy = pOrderBy;
114847  }else{
114848  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
114849  }
114850  VdbeComment((v, "Queue table"));
114851  if( iDistinct ){
114852  p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
114853  p->selFlags |= SF_UsesEphemeral;
114854  }
114855 
114856  /* Detach the ORDER BY clause from the compound SELECT */
114857  p->pOrderBy = 0;
114858 
114859  /* Store the results of the setup-query in Queue. */
114860  pSetup->pNext = 0;
114861  rc = sqlite3Select(pParse, pSetup, &destQueue);
114862  pSetup->pNext = p;
114863  if( rc ) goto end_of_recursive_query;
114864 
114865  /* Find the next row in the Queue and output that row */
114866  addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
114867 
114868  /* Transfer the next row in Queue over to Current */
114869  sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
114870  if( pOrderBy ){
114871  sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
114872  }else{
114873  sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
114874  }
114875  sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
114876 
114877  /* Output the single row in Current */
114878  addrCont = sqlite3VdbeMakeLabel(v);
114879  codeOffset(v, regOffset, addrCont);
114880  selectInnerLoop(pParse, p, p->pEList, iCurrent,
114881  0, 0, pDest, addrCont, addrBreak);
114882  if( regLimit ){
114883  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
114884  VdbeCoverage(v);
114885  }
114886  sqlite3VdbeResolveLabel(v, addrCont);
114887 
114888  /* Execute the recursive SELECT taking the single row in Current as
114889  ** the value for the recursive-table. Store the results in the Queue.
114890  */
114891  if( p->selFlags & SF_Aggregate ){
114892  sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
114893  }else{
114894  p->pPrior = 0;
114895  sqlite3Select(pParse, p, &destQueue);
114896  assert( p->pPrior==0 );
114897  p->pPrior = pSetup;
114898  }
114899 
114900  /* Keep running the loop until the Queue is empty */
114901  sqlite3VdbeGoto(v, addrTop);
114902  sqlite3VdbeResolveLabel(v, addrBreak);
114903 
114904 end_of_recursive_query:
114905  sqlite3ExprListDelete(pParse->db, p->pOrderBy);
114906  p->pOrderBy = pOrderBy;
114907  p->pLimit = pLimit;
114908  p->pOffset = pOffset;
114909  return;
114910 }
114911 #endif /* SQLITE_OMIT_CTE */
114912 
114913 /* Forward references */
114914 static int multiSelectOrderBy(
114915  Parse *pParse, /* Parsing context */
114916  Select *p, /* The right-most of SELECTs to be coded */
114917  SelectDest *pDest /* What to do with query results */
114918 );
114919 
114920 /*
114921 ** Handle the special case of a compound-select that originates from a
114922 ** VALUES clause. By handling this as a special case, we avoid deep
114923 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
114924 ** on a VALUES clause.
114925 **
114926 ** Because the Select object originates from a VALUES clause:
114927 ** (1) It has no LIMIT or OFFSET
114928 ** (2) All terms are UNION ALL
114929 ** (3) There is no ORDER BY clause
114930 */
114932  Parse *pParse, /* Parsing context */
114933  Select *p, /* The right-most of SELECTs to be coded */
114934  SelectDest *pDest /* What to do with query results */
114935 ){
114936  Select *pPrior;
114937  int nRow = 1;
114938  int rc = 0;
114939  assert( p->selFlags & SF_MultiValue );
114940  do{
114941  assert( p->selFlags & SF_Values );
114942  assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
114943  assert( p->pLimit==0 );
114944  assert( p->pOffset==0 );
114945  assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
114946  if( p->pPrior==0 ) break;
114947  assert( p->pPrior->pNext==p );
114948  p = p->pPrior;
114949  nRow++;
114950  }while(1);
114951  while( p ){
114952  pPrior = p->pPrior;
114953  p->pPrior = 0;
114954  rc = sqlite3Select(pParse, p, pDest);
114955  p->pPrior = pPrior;
114956  if( rc ) break;
114957  p->nSelectRow = nRow;
114958  p = p->pNext;
114959  }
114960  return rc;
114961 }
114962 
114963 /*
114964 ** This routine is called to process a compound query form from
114965 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
114966 ** INTERSECT
114967 **
114968 ** "p" points to the right-most of the two queries. the query on the
114969 ** left is p->pPrior. The left query could also be a compound query
114970 ** in which case this routine will be called recursively.
114971 **
114972 ** The results of the total query are to be written into a destination
114973 ** of type eDest with parameter iParm.
114974 **
114975 ** Example 1: Consider a three-way compound SQL statement.
114976 **
114977 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
114978 **
114979 ** This statement is parsed up as follows:
114980 **
114981 ** SELECT c FROM t3
114982 ** |
114983 ** `-----> SELECT b FROM t2
114984 ** |
114985 ** `------> SELECT a FROM t1
114986 **
114987 ** The arrows in the diagram above represent the Select.pPrior pointer.
114988 ** So if this routine is called with p equal to the t3 query, then
114989 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
114990 **
114991 ** Notice that because of the way SQLite parses compound SELECTs, the
114992 ** individual selects always group from left to right.
114993 */
114994 static int multiSelect(
114995  Parse *pParse, /* Parsing context */
114996  Select *p, /* The right-most of SELECTs to be coded */
114997  SelectDest *pDest /* What to do with query results */
114998 ){
114999  int rc = SQLITE_OK; /* Success code from a subroutine */
115000  Select *pPrior; /* Another SELECT immediately to our left */
115001  Vdbe *v; /* Generate code to this VDBE */
115002  SelectDest dest; /* Alternative data destination */
115003  Select *pDelete = 0; /* Chain of simple selects to delete */
115004  sqlite3 *db; /* Database connection */
115005 #ifndef SQLITE_OMIT_EXPLAIN
115006  int iSub1 = 0; /* EQP id of left-hand query */
115007  int iSub2 = 0; /* EQP id of right-hand query */
115008 #endif
115009 
115010  /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
115011  ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
115012  */
115013  assert( p && p->pPrior ); /* Calling function guarantees this much */
115014  assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
115015  db = pParse->db;
115016  pPrior = p->pPrior;
115017  dest = *pDest;
115018  if( pPrior->pOrderBy ){
115019  sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
115020  selectOpName(p->op));
115021  rc = 1;
115022  goto multi_select_end;
115023  }
115024  if( pPrior->pLimit ){
115025  sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
115026  selectOpName(p->op));
115027  rc = 1;
115028  goto multi_select_end;
115029  }
115030 
115031  v = sqlite3GetVdbe(pParse);
115032  assert( v!=0 ); /* The VDBE already created by calling function */
115033 
115034  /* Create the destination temporary table if necessary
115035  */
115036  if( dest.eDest==SRT_EphemTab ){
115037  assert( p->pEList );
115039  dest.eDest = SRT_Table;
115040  }
115041 
115042  /* Special handling for a compound-select that originates as a VALUES clause.
115043  */
115044  if( p->selFlags & SF_MultiValue ){
115045  rc = multiSelectValues(pParse, p, &dest);
115046  goto multi_select_end;
115047  }
115048 
115049  /* Make sure all SELECTs in the statement have the same number of elements
115050  ** in their result sets.
115051  */
115052  assert( p->pEList && pPrior->pEList );
115053  assert( p->pEList->nExpr==pPrior->pEList->nExpr );
115054 
115055 #ifndef SQLITE_OMIT_CTE
115056  if( p->selFlags & SF_Recursive ){
115057  generateWithRecursiveQuery(pParse, p, &dest);
115058  }else
115059 #endif
115060 
115061  /* Compound SELECTs that have an ORDER BY clause are handled separately.
115062  */
115063  if( p->pOrderBy ){
115064  return multiSelectOrderBy(pParse, p, pDest);
115065  }else
115066 
115067  /* Generate code for the left and right SELECT statements.
115068  */
115069  switch( p->op ){
115070  case TK_ALL: {
115071  int addr = 0;
115072  int nLimit;
115073  assert( !pPrior->pLimit );
115074  pPrior->iLimit = p->iLimit;
115075  pPrior->iOffset = p->iOffset;
115076  pPrior->pLimit = p->pLimit;
115077  pPrior->pOffset = p->pOffset;
115078  explainSetInteger(iSub1, pParse->iNextSelectId);
115079  rc = sqlite3Select(pParse, pPrior, &dest);
115080  p->pLimit = 0;
115081  p->pOffset = 0;
115082  if( rc ){
115083  goto multi_select_end;
115084  }
115085  p->pPrior = 0;
115086  p->iLimit = pPrior->iLimit;
115087  p->iOffset = pPrior->iOffset;
115088  if( p->iLimit ){
115089  addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
115090  VdbeComment((v, "Jump ahead if LIMIT reached"));
115091  if( p->iOffset ){
115093  p->iLimit, p->iOffset+1, p->iOffset);
115094  }
115095  }
115096  explainSetInteger(iSub2, pParse->iNextSelectId);
115097  rc = sqlite3Select(pParse, p, &dest);
115098  testcase( rc!=SQLITE_OK );
115099  pDelete = p->pPrior;
115100  p->pPrior = pPrior;
115101  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115102  if( pPrior->pLimit
115103  && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
115104  && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
115105  ){
115106  p->nSelectRow = sqlite3LogEst((u64)nLimit);
115107  }
115108  if( addr ){
115109  sqlite3VdbeJumpHere(v, addr);
115110  }
115111  break;
115112  }
115113  case TK_EXCEPT:
115114  case TK_UNION: {
115115  int unionTab; /* Cursor number of the temporary table holding result */
115116  u8 op = 0; /* One of the SRT_ operations to apply to self */
115117  int priorOp; /* The SRT_ operation to apply to prior selects */
115118  Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
115119  int addr;
115120  SelectDest uniondest;
115121 
115122  testcase( p->op==TK_EXCEPT );
115123  testcase( p->op==TK_UNION );
115124  priorOp = SRT_Union;
115125  if( dest.eDest==priorOp ){
115126  /* We can reuse a temporary table generated by a SELECT to our
115127  ** right.
115128  */
115129  assert( p->pLimit==0 ); /* Not allowed on leftward elements */
115130  assert( p->pOffset==0 ); /* Not allowed on leftward elements */
115131  unionTab = dest.iSDParm;
115132  }else{
115133  /* We will need to create our own temporary table to hold the
115134  ** intermediate results.
115135  */
115136  unionTab = pParse->nTab++;
115137  assert( p->pOrderBy==0 );
115138  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
115139  assert( p->addrOpenEphm[0] == -1 );
115140  p->addrOpenEphm[0] = addr;
115142  assert( p->pEList );
115143  }
115144 
115145  /* Code the SELECT statements to our left
115146  */
115147  assert( !pPrior->pOrderBy );
115148  sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
115149  explainSetInteger(iSub1, pParse->iNextSelectId);
115150  rc = sqlite3Select(pParse, pPrior, &uniondest);
115151  if( rc ){
115152  goto multi_select_end;
115153  }
115154 
115155  /* Code the current SELECT statement
115156  */
115157  if( p->op==TK_EXCEPT ){
115158  op = SRT_Except;
115159  }else{
115160  assert( p->op==TK_UNION );
115161  op = SRT_Union;
115162  }
115163  p->pPrior = 0;
115164  pLimit = p->pLimit;
115165  p->pLimit = 0;
115166  pOffset = p->pOffset;
115167  p->pOffset = 0;
115168  uniondest.eDest = op;
115169  explainSetInteger(iSub2, pParse->iNextSelectId);
115170  rc = sqlite3Select(pParse, p, &uniondest);
115171  testcase( rc!=SQLITE_OK );
115172  /* Query flattening in sqlite3Select() might refill p->pOrderBy.
115173  ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
115175  pDelete = p->pPrior;
115176  p->pPrior = pPrior;
115177  p->pOrderBy = 0;
115178  if( p->op==TK_UNION ){
115179  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115180  }
115181  sqlite3ExprDelete(db, p->pLimit);
115182  p->pLimit = pLimit;
115183  p->pOffset = pOffset;
115184  p->iLimit = 0;
115185  p->iOffset = 0;
115186 
115187  /* Convert the data in the temporary table into whatever form
115188  ** it is that we currently need.
115189  */
115190  assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
115191  if( dest.eDest!=priorOp ){
115192  int iCont, iBreak, iStart;
115193  assert( p->pEList );
115194  if( dest.eDest==SRT_Output ){
115195  Select *pFirst = p;
115196  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115197  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115198  }
115199  iBreak = sqlite3VdbeMakeLabel(v);
115200  iCont = sqlite3VdbeMakeLabel(v);
115201  computeLimitRegisters(pParse, p, iBreak);
115202  sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
115203  iStart = sqlite3VdbeCurrentAddr(v);
115204  selectInnerLoop(pParse, p, p->pEList, unionTab,
115205  0, 0, &dest, iCont, iBreak);
115206  sqlite3VdbeResolveLabel(v, iCont);
115207  sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
115208  sqlite3VdbeResolveLabel(v, iBreak);
115209  sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
115210  }
115211  break;
115212  }
115213  default: assert( p->op==TK_INTERSECT ); {
115214  int tab1, tab2;
115215  int iCont, iBreak, iStart;
115216  Expr *pLimit, *pOffset;
115217  int addr;
115218  SelectDest intersectdest;
115219  int r1;
115220 
115221  /* INTERSECT is different from the others since it requires
115222  ** two temporary tables. Hence it has its own case. Begin
115223  ** by allocating the tables we will need.
115224  */
115225  tab1 = pParse->nTab++;
115226  tab2 = pParse->nTab++;
115227  assert( p->pOrderBy==0 );
115228 
115229  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
115230  assert( p->addrOpenEphm[0] == -1 );
115231  p->addrOpenEphm[0] = addr;
115233  assert( p->pEList );
115234 
115235  /* Code the SELECTs to our left into temporary table "tab1".
115236  */
115237  sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
115238  explainSetInteger(iSub1, pParse->iNextSelectId);
115239  rc = sqlite3Select(pParse, pPrior, &intersectdest);
115240  if( rc ){
115241  goto multi_select_end;
115242  }
115243 
115244  /* Code the current SELECT into temporary table "tab2"
115245  */
115246  addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
115247  assert( p->addrOpenEphm[1] == -1 );
115248  p->addrOpenEphm[1] = addr;
115249  p->pPrior = 0;
115250  pLimit = p->pLimit;
115251  p->pLimit = 0;
115252  pOffset = p->pOffset;
115253  p->pOffset = 0;
115254  intersectdest.iSDParm = tab2;
115255  explainSetInteger(iSub2, pParse->iNextSelectId);
115256  rc = sqlite3Select(pParse, p, &intersectdest);
115257  testcase( rc!=SQLITE_OK );
115258  pDelete = p->pPrior;
115259  p->pPrior = pPrior;
115260  if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
115261  sqlite3ExprDelete(db, p->pLimit);
115262  p->pLimit = pLimit;
115263  p->pOffset = pOffset;
115264 
115265  /* Generate code to take the intersection of the two temporary
115266  ** tables.
115267  */
115268  assert( p->pEList );
115269  if( dest.eDest==SRT_Output ){
115270  Select *pFirst = p;
115271  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115272  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115273  }
115274  iBreak = sqlite3VdbeMakeLabel(v);
115275  iCont = sqlite3VdbeMakeLabel(v);
115276  computeLimitRegisters(pParse, p, iBreak);
115277  sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
115278  r1 = sqlite3GetTempReg(pParse);
115279  iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
115280  sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
115281  sqlite3ReleaseTempReg(pParse, r1);
115282  selectInnerLoop(pParse, p, p->pEList, tab1,
115283  0, 0, &dest, iCont, iBreak);
115284  sqlite3VdbeResolveLabel(v, iCont);
115285  sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
115286  sqlite3VdbeResolveLabel(v, iBreak);
115287  sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
115288  sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
115289  break;
115290  }
115291  }
115292 
115293  explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
115294 
115295  /* Compute collating sequences used by
115296  ** temporary tables needed to implement the compound select.
115297  ** Attach the KeyInfo structure to all temporary tables.
115298  **
115299  ** This section is run by the right-most SELECT statement only.
115300  ** SELECT statements to the left always skip this part. The right-most
115301  ** SELECT might also skip this part if it has no ORDER BY clause and
115302  ** no temp tables are required.
115303  */
115304  if( p->selFlags & SF_UsesEphemeral ){
115305  int i; /* Loop counter */
115306  KeyInfo *pKeyInfo; /* Collating sequence for the result set */
115307  Select *pLoop; /* For looping through SELECT statements */
115308  CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
115309  int nCol; /* Number of columns in result set */
115310 
115311  assert( p->pNext==0 );
115312  nCol = p->pEList->nExpr;
115313  pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
115314  if( !pKeyInfo ){
115315  rc = SQLITE_NOMEM_BKPT;
115316  goto multi_select_end;
115317  }
115318  for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
115319  *apColl = multiSelectCollSeq(pParse, p, i);
115320  if( 0==*apColl ){
115321  *apColl = db->pDfltColl;
115322  }
115323  }
115324 
115325  for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
115326  for(i=0; i<2; i++){
115327  int addr = pLoop->addrOpenEphm[i];
115328  if( addr<0 ){
115329  /* If [0] is unused then [1] is also unused. So we can
115330  ** always safely abort as soon as the first unused slot is found */
115331  assert( pLoop->addrOpenEphm[1]<0 );
115332  break;
115333  }
115334  sqlite3VdbeChangeP2(v, addr, nCol);
115335  sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
115336  P4_KEYINFO);
115337  pLoop->addrOpenEphm[i] = -1;
115338  }
115339  }
115340  sqlite3KeyInfoUnref(pKeyInfo);
115341  }
115342 
115343 multi_select_end:
115344  pDest->iSdst = dest.iSdst;
115345  pDest->nSdst = dest.nSdst;
115346  sqlite3SelectDelete(db, pDelete);
115347  return rc;
115348 }
115349 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
115350 
115351 /*
115352 ** Error message for when two or more terms of a compound select have different
115353 ** size result sets.
115354 */
115356  if( p->selFlags & SF_Values ){
115357  sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
115358  }else{
115359  sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
115360  " do not have the same number of result columns", selectOpName(p->op));
115361  }
115362 }
115363 
115364 /*
115365 ** Code an output subroutine for a coroutine implementation of a
115366 ** SELECT statment.
115367 **
115368 ** The data to be output is contained in pIn->iSdst. There are
115369 ** pIn->nSdst columns to be output. pDest is where the output should
115370 ** be sent.
115371 **
115372 ** regReturn is the number of the register holding the subroutine
115373 ** return address.
115374 **
115375 ** If regPrev>0 then it is the first register in a vector that
115376 ** records the previous output. mem[regPrev] is a flag that is false
115377 ** if there has been no previous output. If regPrev>0 then code is
115378 ** generated to suppress duplicates. pKeyInfo is used for comparing
115379 ** keys.
115380 **
115381 ** If the LIMIT found in p->iLimit is reached, jump immediately to
115382 ** iBreak.
115383 */
115385  Parse *pParse, /* Parsing context */
115386  Select *p, /* The SELECT statement */
115387  SelectDest *pIn, /* Coroutine supplying data */
115388  SelectDest *pDest, /* Where to send the data */
115389  int regReturn, /* The return address register */
115390  int regPrev, /* Previous result register. No uniqueness if 0 */
115391  KeyInfo *pKeyInfo, /* For comparing with previous entry */
115392  int iBreak /* Jump here if we hit the LIMIT */
115393 ){
115394  Vdbe *v = pParse->pVdbe;
115395  int iContinue;
115396  int addr;
115397 
115398  addr = sqlite3VdbeCurrentAddr(v);
115399  iContinue = sqlite3VdbeMakeLabel(v);
115400 
115401  /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
115402  */
115403  if( regPrev ){
115404  int addr1, addr2;
115405  addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
115406  addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
115407  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
115408  sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
115409  sqlite3VdbeJumpHere(v, addr1);
115410  sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
115411  sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
115412  }
115413  if( pParse->db->mallocFailed ) return 0;
115414 
115415  /* Suppress the first OFFSET entries if there is an OFFSET clause
115416  */
115417  codeOffset(v, p->iOffset, iContinue);
115418 
115419  assert( pDest->eDest!=SRT_Exists );
115420  assert( pDest->eDest!=SRT_Table );
115421  switch( pDest->eDest ){
115422  /* Store the result as data using a unique key.
115423  */
115424  case SRT_EphemTab: {
115425  int r1 = sqlite3GetTempReg(pParse);
115426  int r2 = sqlite3GetTempReg(pParse);
115427  sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
115428  sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
115429  sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
115431  sqlite3ReleaseTempReg(pParse, r2);
115432  sqlite3ReleaseTempReg(pParse, r1);
115433  break;
115434  }
115435 
115436 #ifndef SQLITE_OMIT_SUBQUERY
115437  /* If we are creating a set for an "expr IN (SELECT ...)" construct,
115438  ** then there should be a single item on the stack. Write this
115439  ** item into the set table with bogus data.
115440  */
115441  case SRT_Set: {
115442  int r1;
115443  assert( pIn->nSdst==1 || pParse->nErr>0 );
115444  pDest->affSdst =
115445  sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
115446  r1 = sqlite3GetTempReg(pParse);
115447  sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
115448  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
115449  sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
115450  sqlite3ReleaseTempReg(pParse, r1);
115451  break;
115452  }
115453 
115454  /* If this is a scalar select that is part of an expression, then
115455  ** store the results in the appropriate memory cell and break out
115456  ** of the scan loop.
115457  */
115458  case SRT_Mem: {
115459  assert( pIn->nSdst==1 || pParse->nErr>0 ); testcase( pIn->nSdst!=1 );
115460  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
115461  /* The LIMIT clause will jump out of the loop for us */
115462  break;
115463  }
115464 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
115465 
115466  /* The results are stored in a sequence of registers
115467  ** starting at pDest->iSdst. Then the co-routine yields.
115468  */
115469  case SRT_Coroutine: {
115470  if( pDest->iSdst==0 ){
115471  pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
115472  pDest->nSdst = pIn->nSdst;
115473  }
115474  sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
115475  sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
115476  break;
115477  }
115478 
115479  /* If none of the above, then the result destination must be
115480  ** SRT_Output. This routine is never called with any other
115481  ** destination other than the ones handled above or SRT_Output.
115482  **
115483  ** For SRT_Output, results are stored in a sequence of registers.
115484  ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
115485  ** return the next row of result.
115486  */
115487  default: {
115488  assert( pDest->eDest==SRT_Output );
115489  sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
115490  sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
115491  break;
115492  }
115493  }
115494 
115495  /* Jump to the end of the loop if the LIMIT is reached.
115496  */
115497  if( p->iLimit ){
115499  }
115500 
115501  /* Generate the subroutine return
115502  */
115503  sqlite3VdbeResolveLabel(v, iContinue);
115504  sqlite3VdbeAddOp1(v, OP_Return, regReturn);
115505 
115506  return addr;
115507 }
115508 
115509 /*
115510 ** Alternative compound select code generator for cases when there
115511 ** is an ORDER BY clause.
115512 **
115513 ** We assume a query of the following form:
115514 **
115515 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
115516 **
115517 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
115518 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
115519 ** co-routines. Then run the co-routines in parallel and merge the results
115520 ** into the output. In addition to the two coroutines (called selectA and
115521 ** selectB) there are 7 subroutines:
115522 **
115523 ** outA: Move the output of the selectA coroutine into the output
115524 ** of the compound query.
115525 **
115526 ** outB: Move the output of the selectB coroutine into the output
115527 ** of the compound query. (Only generated for UNION and
115528 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
115529 ** appears only in B.)
115530 **
115531 ** AltB: Called when there is data from both coroutines and A<B.
115532 **
115533 ** AeqB: Called when there is data from both coroutines and A==B.
115534 **
115535 ** AgtB: Called when there is data from both coroutines and A>B.
115536 **
115537 ** EofA: Called when data is exhausted from selectA.
115538 **
115539 ** EofB: Called when data is exhausted from selectB.
115540 **
115541 ** The implementation of the latter five subroutines depend on which
115542 ** <operator> is used:
115543 **
115544 **
115545 ** UNION ALL UNION EXCEPT INTERSECT
115546 ** ------------- ----------------- -------------- -----------------
115547 ** AltB: outA, nextA outA, nextA outA, nextA nextA
115548 **
115549 ** AeqB: outA, nextA nextA nextA outA, nextA
115550 **
115551 ** AgtB: outB, nextB outB, nextB nextB nextB
115552 **
115553 ** EofA: outB, nextB outB, nextB halt halt
115554 **
115555 ** EofB: outA, nextA outA, nextA outA, nextA halt
115556 **
115557 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
115558 ** causes an immediate jump to EofA and an EOF on B following nextB causes
115559 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
115560 ** following nextX causes a jump to the end of the select processing.
115561 **
115562 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
115563 ** within the output subroutine. The regPrev register set holds the previously
115564 ** output value. A comparison is made against this value and the output
115565 ** is skipped if the next results would be the same as the previous.
115566 **
115567 ** The implementation plan is to implement the two coroutines and seven
115568 ** subroutines first, then put the control logic at the bottom. Like this:
115569 **
115570 ** goto Init
115571 ** coA: coroutine for left query (A)
115572 ** coB: coroutine for right query (B)
115573 ** outA: output one row of A
115574 ** outB: output one row of B (UNION and UNION ALL only)
115575 ** EofA: ...
115576 ** EofB: ...
115577 ** AltB: ...
115578 ** AeqB: ...
115579 ** AgtB: ...
115580 ** Init: initialize coroutine registers
115581 ** yield coA
115582 ** if eof(A) goto EofA
115583 ** yield coB
115584 ** if eof(B) goto EofB
115585 ** Cmpr: Compare A, B
115586 ** Jump AltB, AeqB, AgtB
115587 ** End: ...
115588 **
115589 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
115590 ** actually called using Gosub and they do not Return. EofA and EofB loop
115591 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
115592 ** and AgtB jump to either L2 or to one of EofA or EofB.
115593 */
115594 #ifndef SQLITE_OMIT_COMPOUND_SELECT
115596  Parse *pParse, /* Parsing context */
115597  Select *p, /* The right-most of SELECTs to be coded */
115598  SelectDest *pDest /* What to do with query results */
115599 ){
115600  int i, j; /* Loop counters */
115601  Select *pPrior; /* Another SELECT immediately to our left */
115602  Vdbe *v; /* Generate code to this VDBE */
115603  SelectDest destA; /* Destination for coroutine A */
115604  SelectDest destB; /* Destination for coroutine B */
115605  int regAddrA; /* Address register for select-A coroutine */
115606  int regAddrB; /* Address register for select-B coroutine */
115607  int addrSelectA; /* Address of the select-A coroutine */
115608  int addrSelectB; /* Address of the select-B coroutine */
115609  int regOutA; /* Address register for the output-A subroutine */
115610  int regOutB; /* Address register for the output-B subroutine */
115611  int addrOutA; /* Address of the output-A subroutine */
115612  int addrOutB = 0; /* Address of the output-B subroutine */
115613  int addrEofA; /* Address of the select-A-exhausted subroutine */
115614  int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
115615  int addrEofB; /* Address of the select-B-exhausted subroutine */
115616  int addrAltB; /* Address of the A<B subroutine */
115617  int addrAeqB; /* Address of the A==B subroutine */
115618  int addrAgtB; /* Address of the A>B subroutine */
115619  int regLimitA; /* Limit register for select-A */
115620  int regLimitB; /* Limit register for select-A */
115621  int regPrev; /* A range of registers to hold previous output */
115622  int savedLimit; /* Saved value of p->iLimit */
115623  int savedOffset; /* Saved value of p->iOffset */
115624  int labelCmpr; /* Label for the start of the merge algorithm */
115625  int labelEnd; /* Label for the end of the overall SELECT stmt */
115626  int addr1; /* Jump instructions that get retargetted */
115627  int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
115628  KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
115629  KeyInfo *pKeyMerge; /* Comparison information for merging rows */
115630  sqlite3 *db; /* Database connection */
115631  ExprList *pOrderBy; /* The ORDER BY clause */
115632  int nOrderBy; /* Number of terms in the ORDER BY clause */
115633  int *aPermute; /* Mapping from ORDER BY terms to result set columns */
115634 #ifndef SQLITE_OMIT_EXPLAIN
115635  int iSub1; /* EQP id of left-hand query */
115636  int iSub2; /* EQP id of right-hand query */
115637 #endif
115638 
115639  assert( p->pOrderBy!=0 );
115640  assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
115641  db = pParse->db;
115642  v = pParse->pVdbe;
115643  assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
115644  labelEnd = sqlite3VdbeMakeLabel(v);
115645  labelCmpr = sqlite3VdbeMakeLabel(v);
115646 
115647 
115648  /* Patch up the ORDER BY clause
115649  */
115650  op = p->op;
115651  pPrior = p->pPrior;
115652  assert( pPrior->pOrderBy==0 );
115653  pOrderBy = p->pOrderBy;
115654  assert( pOrderBy );
115655  nOrderBy = pOrderBy->nExpr;
115656 
115657  /* For operators other than UNION ALL we have to make sure that
115658  ** the ORDER BY clause covers every term of the result set. Add
115659  ** terms to the ORDER BY clause as necessary.
115660  */
115661  if( op!=TK_ALL ){
115662  for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
115663  struct ExprList_item *pItem;
115664  for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
115665  assert( pItem->u.x.iOrderByCol>0 );
115666  if( pItem->u.x.iOrderByCol==i ) break;
115667  }
115668  if( j==nOrderBy ){
115669  Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
115670  if( pNew==0 ) return SQLITE_NOMEM_BKPT;
115671  pNew->flags |= EP_IntValue;
115672  pNew->u.iValue = i;
115673  pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
115674  if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
115675  }
115676  }
115677  }
115678 
115679  /* Compute the comparison permutation and keyinfo that is used with
115680  ** the permutation used to determine if the next
115681  ** row of results comes from selectA or selectB. Also add explicit
115682  ** collations to the ORDER BY clause terms so that when the subqueries
115683  ** to the right and the left are evaluated, they use the correct
115684  ** collation.
115685  */
115686  aPermute = sqlite3DbMallocRawNN(db, sizeof(int)*(nOrderBy + 1));
115687  if( aPermute ){
115688  struct ExprList_item *pItem;
115689  aPermute[0] = nOrderBy;
115690  for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
115691  assert( pItem->u.x.iOrderByCol>0 );
115692  assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
115693  aPermute[i] = pItem->u.x.iOrderByCol - 1;
115694  }
115695  pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
115696  }else{
115697  pKeyMerge = 0;
115698  }
115699 
115700  /* Reattach the ORDER BY clause to the query.
115701  */
115702  p->pOrderBy = pOrderBy;
115703  pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
115704 
115705  /* Allocate a range of temporary registers and the KeyInfo needed
115706  ** for the logic that removes duplicate result rows when the
115707  ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
115708  */
115709  if( op==TK_ALL ){
115710  regPrev = 0;
115711  }else{
115712  int nExpr = p->pEList->nExpr;
115713  assert( nOrderBy>=nExpr || db->mallocFailed );
115714  regPrev = pParse->nMem+1;
115715  pParse->nMem += nExpr+1;
115716  sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
115717  pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
115718  if( pKeyDup ){
115719  assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
115720  for(i=0; i<nExpr; i++){
115721  pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
115722  pKeyDup->aSortOrder[i] = 0;
115723  }
115724  }
115725  }
115726 
115727  /* Separate the left and the right query from one another
115728  */
115729  p->pPrior = 0;
115730  pPrior->pNext = 0;
115731  sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
115732  if( pPrior->pPrior==0 ){
115733  sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
115734  }
115735 
115736  /* Compute the limit registers */
115737  computeLimitRegisters(pParse, p, labelEnd);
115738  if( p->iLimit && op==TK_ALL ){
115739  regLimitA = ++pParse->nMem;
115740  regLimitB = ++pParse->nMem;
115741  sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
115742  regLimitA);
115743  sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
115744  }else{
115745  regLimitA = regLimitB = 0;
115746  }
115747  sqlite3ExprDelete(db, p->pLimit);
115748  p->pLimit = 0;
115749  sqlite3ExprDelete(db, p->pOffset);
115750  p->pOffset = 0;
115751 
115752  regAddrA = ++pParse->nMem;
115753  regAddrB = ++pParse->nMem;
115754  regOutA = ++pParse->nMem;
115755  regOutB = ++pParse->nMem;
115756  sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
115757  sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
115758 
115759  /* Generate a coroutine to evaluate the SELECT statement to the
115760  ** left of the compound operator - the "A" select.
115761  */
115762  addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
115763  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
115764  VdbeComment((v, "left SELECT"));
115765  pPrior->iLimit = regLimitA;
115766  explainSetInteger(iSub1, pParse->iNextSelectId);
115767  sqlite3Select(pParse, pPrior, &destA);
115768  sqlite3VdbeEndCoroutine(v, regAddrA);
115769  sqlite3VdbeJumpHere(v, addr1);
115770 
115771  /* Generate a coroutine to evaluate the SELECT statement on
115772  ** the right - the "B" select
115773  */
115774  addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
115775  addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
115776  VdbeComment((v, "right SELECT"));
115777  savedLimit = p->iLimit;
115778  savedOffset = p->iOffset;
115779  p->iLimit = regLimitB;
115780  p->iOffset = 0;
115781  explainSetInteger(iSub2, pParse->iNextSelectId);
115782  sqlite3Select(pParse, p, &destB);
115783  p->iLimit = savedLimit;
115784  p->iOffset = savedOffset;
115785  sqlite3VdbeEndCoroutine(v, regAddrB);
115786 
115787  /* Generate a subroutine that outputs the current row of the A
115788  ** select as the next output row of the compound select.
115789  */
115790  VdbeNoopComment((v, "Output routine for A"));
115791  addrOutA = generateOutputSubroutine(pParse,
115792  p, &destA, pDest, regOutA,
115793  regPrev, pKeyDup, labelEnd);
115794 
115795  /* Generate a subroutine that outputs the current row of the B
115796  ** select as the next output row of the compound select.
115797  */
115798  if( op==TK_ALL || op==TK_UNION ){
115799  VdbeNoopComment((v, "Output routine for B"));
115800  addrOutB = generateOutputSubroutine(pParse,
115801  p, &destB, pDest, regOutB,
115802  regPrev, pKeyDup, labelEnd);
115803  }
115804  sqlite3KeyInfoUnref(pKeyDup);
115805 
115806  /* Generate a subroutine to run when the results from select A
115807  ** are exhausted and only data in select B remains.
115808  */
115809  if( op==TK_EXCEPT || op==TK_INTERSECT ){
115810  addrEofA_noB = addrEofA = labelEnd;
115811  }else{
115812  VdbeNoopComment((v, "eof-A subroutine"));
115813  addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
115814  addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
115815  VdbeCoverage(v);
115816  sqlite3VdbeGoto(v, addrEofA);
115817  p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
115818  }
115819 
115820  /* Generate a subroutine to run when the results from select B
115821  ** are exhausted and only data in select A remains.
115822  */
115823  if( op==TK_INTERSECT ){
115824  addrEofB = addrEofA;
115825  if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
115826  }else{
115827  VdbeNoopComment((v, "eof-B subroutine"));
115828  addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
115829  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
115830  sqlite3VdbeGoto(v, addrEofB);
115831  }
115832 
115833  /* Generate code to handle the case of A<B
115834  */
115835  VdbeNoopComment((v, "A-lt-B subroutine"));
115836  addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
115837  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
115838  sqlite3VdbeGoto(v, labelCmpr);
115839 
115840  /* Generate code to handle the case of A==B
115841  */
115842  if( op==TK_ALL ){
115843  addrAeqB = addrAltB;
115844  }else if( op==TK_INTERSECT ){
115845  addrAeqB = addrAltB;
115846  addrAltB++;
115847  }else{
115848  VdbeNoopComment((v, "A-eq-B subroutine"));
115849  addrAeqB =
115850  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
115851  sqlite3VdbeGoto(v, labelCmpr);
115852  }
115853 
115854  /* Generate code to handle the case of A>B
115855  */
115856  VdbeNoopComment((v, "A-gt-B subroutine"));
115857  addrAgtB = sqlite3VdbeCurrentAddr(v);
115858  if( op==TK_ALL || op==TK_UNION ){
115859  sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
115860  }
115861  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
115862  sqlite3VdbeGoto(v, labelCmpr);
115863 
115864  /* This code runs once to initialize everything.
115865  */
115866  sqlite3VdbeJumpHere(v, addr1);
115867  sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
115868  sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
115869 
115870  /* Implement the main merge loop
115871  */
115872  sqlite3VdbeResolveLabel(v, labelCmpr);
115873  sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
115874  sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
115875  (char*)pKeyMerge, P4_KEYINFO);
115877  sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
115878 
115879  /* Jump to the this point in order to terminate the query.
115880  */
115881  sqlite3VdbeResolveLabel(v, labelEnd);
115882 
115883  /* Set the number of output columns
115884  */
115885  if( pDest->eDest==SRT_Output ){
115886  Select *pFirst = pPrior;
115887  while( pFirst->pPrior ) pFirst = pFirst->pPrior;
115888  generateColumnNames(pParse, pFirst->pSrc, pFirst->pEList);
115889  }
115890 
115891  /* Reassembly the compound query so that it will be freed correctly
115892  ** by the calling function */
115893  if( p->pPrior ){
115894  sqlite3SelectDelete(db, p->pPrior);
115895  }
115896  p->pPrior = pPrior;
115897  pPrior->pNext = p;
115898 
115899  /*** TBD: Insert subroutine calls to close cursors on incomplete
115900  **** subqueries ****/
115901  explainComposite(pParse, p->op, iSub1, iSub2, 0);
115902  return pParse->nErr!=0;
115903 }
115904 #endif
115905 
115906 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
115907 /* Forward Declarations */
115908 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
115909 static void substSelect(sqlite3*, Select *, int, ExprList*, int);
115910 
115911 /*
115912 ** Scan through the expression pExpr. Replace every reference to
115913 ** a column in table number iTable with a copy of the iColumn-th
115914 ** entry in pEList. (But leave references to the ROWID column
115915 ** unchanged.)
115916 **
115917 ** This routine is part of the flattening procedure. A subquery
115918 ** whose result set is defined by pEList appears as entry in the
115919 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
115920 ** FORM clause entry is iTable. This routine make the necessary
115921 ** changes to pExpr so that it refers directly to the source table
115922 ** of the subquery rather the result set of the subquery.
115923 */
115925  sqlite3 *db, /* Report malloc errors to this connection */
115926  Expr *pExpr, /* Expr in which substitution occurs */
115927  int iTable, /* Table to be substituted */
115928  ExprList *pEList /* Substitute expressions */
115929 ){
115930  if( pExpr==0 ) return 0;
115931  if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
115932  if( pExpr->iColumn<0 ){
115933  pExpr->op = TK_NULL;
115934  }else{
115935  Expr *pNew;
115936  assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
115937  assert( pExpr->pLeft==0 && pExpr->pRight==0 );
115938  pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
115939  sqlite3ExprDelete(db, pExpr);
115940  pExpr = pNew;
115941  }
115942  }else{
115943  pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
115944  pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
115945  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
115946  substSelect(db, pExpr->x.pSelect, iTable, pEList, 1);
115947  }else{
115948  substExprList(db, pExpr->x.pList, iTable, pEList);
115949  }
115950  }
115951  return pExpr;
115952 }
115953 static void substExprList(
115954  sqlite3 *db, /* Report malloc errors here */
115955  ExprList *pList, /* List to scan and in which to make substitutes */
115956  int iTable, /* Table to be substituted */
115957  ExprList *pEList /* Substitute values */
115958 ){
115959  int i;
115960  if( pList==0 ) return;
115961  for(i=0; i<pList->nExpr; i++){
115962  pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
115963  }
115964 }
115965 static void substSelect(
115966  sqlite3 *db, /* Report malloc errors here */
115967  Select *p, /* SELECT statement in which to make substitutions */
115968  int iTable, /* Table to be replaced */
115969  ExprList *pEList, /* Substitute values */
115970  int doPrior /* Do substitutes on p->pPrior too */
115971 ){
115972  SrcList *pSrc;
115973  struct SrcList_item *pItem;
115974  int i;
115975  if( !p ) return;
115976  do{
115977  substExprList(db, p->pEList, iTable, pEList);
115978  substExprList(db, p->pGroupBy, iTable, pEList);
115979  substExprList(db, p->pOrderBy, iTable, pEList);
115980  p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
115981  p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
115982  pSrc = p->pSrc;
115983  assert( pSrc!=0 );
115984  for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
115985  substSelect(db, pItem->pSelect, iTable, pEList, 1);
115986  if( pItem->fg.isTabFunc ){
115987  substExprList(db, pItem->u1.pFuncArg, iTable, pEList);
115988  }
115989  }
115990  }while( doPrior && (p = p->pPrior)!=0 );
115991 }
115992 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
115993 
115994 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
115995 /*
115996 ** This routine attempts to flatten subqueries as a performance optimization.
115997 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
115998 **
115999 ** To understand the concept of flattening, consider the following
116000 ** query:
116001 **
116002 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
116003 **
116004 ** The default way of implementing this query is to execute the
116005 ** subquery first and store the results in a temporary table, then
116006 ** run the outer query on that temporary table. This requires two
116007 ** passes over the data. Furthermore, because the temporary table
116008 ** has no indices, the WHERE clause on the outer query cannot be
116009 ** optimized.
116010 **
116011 ** This routine attempts to rewrite queries such as the above into
116012 ** a single flat select, like this:
116013 **
116014 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
116015 **
116016 ** The code generated for this simplification gives the same result
116017 ** but only has to scan the data once. And because indices might
116018 ** exist on the table t1, a complete scan of the data might be
116019 ** avoided.
116020 **
116021 ** Flattening is only attempted if all of the following are true:
116022 **
116023 ** (1) The subquery and the outer query do not both use aggregates.
116024 **
116025 ** (2) The subquery is not an aggregate or (2a) the outer query is not a join
116026 ** and (2b) the outer query does not use subqueries other than the one
116027 ** FROM-clause subquery that is a candidate for flattening. (2b is
116028 ** due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
116029 **
116030 ** (3) The subquery is not the right operand of a left outer join
116031 ** (Originally ticket #306. Strengthened by ticket #3300)
116032 **
116033 ** (4) The subquery is not DISTINCT.
116034 **
116035 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
116036 ** sub-queries that were excluded from this optimization. Restriction
116037 ** (4) has since been expanded to exclude all DISTINCT subqueries.
116038 **
116039 ** (6) The subquery does not use aggregates or the outer query is not
116040 ** DISTINCT.
116041 **
116042 ** (7) The subquery has a FROM clause. TODO: For subqueries without
116043 ** A FROM clause, consider adding a FROM close with the special
116044 ** table sqlite_once that consists of a single row containing a
116045 ** single NULL.
116046 **
116047 ** (8) The subquery does not use LIMIT or the outer query is not a join.
116048 **
116049 ** (9) The subquery does not use LIMIT or the outer query does not use
116050 ** aggregates.
116051 **
116052 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
116053 ** accidently carried the comment forward until 2014-09-15. Original
116054 ** text: "The subquery does not use aggregates or the outer query
116055 ** does not use LIMIT."
116056 **
116057 ** (11) The subquery and the outer query do not both have ORDER BY clauses.
116058 **
116059 ** (**) Not implemented. Subsumed into restriction (3). Was previously
116060 ** a separate restriction deriving from ticket #350.
116061 **
116062 ** (13) The subquery and outer query do not both use LIMIT.
116063 **
116064 ** (14) The subquery does not use OFFSET.
116065 **
116066 ** (15) The outer query is not part of a compound select or the
116067 ** subquery does not have a LIMIT clause.
116068 ** (See ticket #2339 and ticket [02a8e81d44]).
116069 **
116070 ** (16) The outer query is not an aggregate or the subquery does
116071 ** not contain ORDER BY. (Ticket #2942) This used to not matter
116072 ** until we introduced the group_concat() function.
116073 **
116074 ** (17) The sub-query is not a compound select, or it is a UNION ALL
116075 ** compound clause made up entirely of non-aggregate queries, and
116076 ** the parent query:
116077 **
116078 ** * is not itself part of a compound select,
116079 ** * is not an aggregate or DISTINCT query, and
116080 ** * is not a join
116081 **
116082 ** The parent and sub-query may contain WHERE clauses. Subject to
116083 ** rules (11), (13) and (14), they may also contain ORDER BY,
116084 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
116085 ** operator other than UNION ALL because all the other compound
116086 ** operators have an implied DISTINCT which is disallowed by
116087 ** restriction (4).
116088 **
116089 ** Also, each component of the sub-query must return the same number
116090 ** of result columns. This is actually a requirement for any compound
116091 ** SELECT statement, but all the code here does is make sure that no
116092 ** such (illegal) sub-query is flattened. The caller will detect the
116093 ** syntax error and return a detailed message.
116094 **
116095 ** (18) If the sub-query is a compound select, then all terms of the
116096 ** ORDER by clause of the parent must be simple references to
116097 ** columns of the sub-query.
116098 **
116099 ** (19) The subquery does not use LIMIT or the outer query does not
116100 ** have a WHERE clause.
116101 **
116102 ** (20) If the sub-query is a compound select, then it must not use
116103 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
116104 ** somewhat by saying that the terms of the ORDER BY clause must
116105 ** appear as unmodified result columns in the outer query. But we
116106 ** have other optimizations in mind to deal with that case.
116107 **
116108 ** (21) The subquery does not use LIMIT or the outer query is not
116109 ** DISTINCT. (See ticket [752e1646fc]).
116110 **
116111 ** (22) The subquery is not a recursive CTE.
116112 **
116113 ** (23) The parent is not a recursive CTE, or the sub-query is not a
116114 ** compound query. This restriction is because transforming the
116115 ** parent to a compound query confuses the code that handles
116116 ** recursive queries in multiSelect().
116117 **
116118 ** (24) The subquery is not an aggregate that uses the built-in min() or
116119 ** or max() functions. (Without this restriction, a query like:
116120 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
116121 ** return the value X for which Y was maximal.)
116122 **
116123 **
116124 ** In this routine, the "p" parameter is a pointer to the outer query.
116125 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
116126 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
116127 **
116128 ** If flattening is not attempted, this routine is a no-op and returns 0.
116129 ** If flattening is attempted this routine returns 1.
116130 **
116131 ** All of the expression analysis must occur on both the outer query and
116132 ** the subquery before this routine runs.
116133 */
116134 static int flattenSubquery(
116135  Parse *pParse, /* Parsing context */
116136  Select *p, /* The parent or outer SELECT statement */
116137  int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
116138  int isAgg, /* True if outer SELECT uses aggregate functions */
116139  int subqueryIsAgg /* True if the subquery uses aggregate functions */
116140 ){
116141  const char *zSavedAuthContext = pParse->zAuthContext;
116142  Select *pParent; /* Current UNION ALL term of the other query */
116143  Select *pSub; /* The inner query or "subquery" */
116144  Select *pSub1; /* Pointer to the rightmost select in sub-query */
116145  SrcList *pSrc; /* The FROM clause of the outer query */
116146  SrcList *pSubSrc; /* The FROM clause of the subquery */
116147  ExprList *pList; /* The result set of the outer query */
116148  int iParent; /* VDBE cursor number of the pSub result set temp table */
116149  int i; /* Loop counter */
116150  Expr *pWhere; /* The WHERE clause */
116151  struct SrcList_item *pSubitem; /* The subquery */
116152  sqlite3 *db = pParse->db;
116153 
116154  /* Check to see if flattening is permitted. Return 0 if not.
116155  */
116156  assert( p!=0 );
116157  assert( p->pPrior==0 ); /* Unable to flatten compound queries */
116158  if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
116159  pSrc = p->pSrc;
116160  assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
116161  pSubitem = &pSrc->a[iFrom];
116162  iParent = pSubitem->iCursor;
116163  pSub = pSubitem->pSelect;
116164  assert( pSub!=0 );
116165  if( subqueryIsAgg ){
116166  if( isAgg ) return 0; /* Restriction (1) */
116167  if( pSrc->nSrc>1 ) return 0; /* Restriction (2a) */
116168  if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
116169  || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
116171  ){
116172  return 0; /* Restriction (2b) */
116173  }
116174  }
116175 
116176  pSubSrc = pSub->pSrc;
116177  assert( pSubSrc );
116178  /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
116179  ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
116180  ** because they could be computed at compile-time. But when LIMIT and OFFSET
116181  ** became arbitrary expressions, we were forced to add restrictions (13)
116182  ** and (14). */
116183  if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
116184  if( pSub->pOffset ) return 0; /* Restriction (14) */
116185  if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
116186  return 0; /* Restriction (15) */
116187  }
116188  if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
116189  if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
116190  if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
116191  return 0; /* Restrictions (8)(9) */
116192  }
116193  if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
116194  return 0; /* Restriction (6) */
116195  }
116196  if( p->pOrderBy && pSub->pOrderBy ){
116197  return 0; /* Restriction (11) */
116198  }
116199  if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
116200  if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
116201  if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
116202  return 0; /* Restriction (21) */
116203  }
116204  testcase( pSub->selFlags & SF_Recursive );
116205  testcase( pSub->selFlags & SF_MinMaxAgg );
116206  if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
116207  return 0; /* Restrictions (22) and (24) */
116208  }
116209  if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
116210  return 0; /* Restriction (23) */
116211  }
116212 
116213  /* OBSOLETE COMMENT 1:
116214  ** Restriction 3: If the subquery is a join, make sure the subquery is
116215  ** not used as the right operand of an outer join. Examples of why this
116216  ** is not allowed:
116217  **
116218  ** t1 LEFT OUTER JOIN (t2 JOIN t3)
116219  **
116220  ** If we flatten the above, we would get
116221  **
116222  ** (t1 LEFT OUTER JOIN t2) JOIN t3
116223  **
116224  ** which is not at all the same thing.
116225  **
116226  ** OBSOLETE COMMENT 2:
116227  ** Restriction 12: If the subquery is the right operand of a left outer
116228  ** join, make sure the subquery has no WHERE clause.
116229  ** An examples of why this is not allowed:
116230  **
116231  ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
116232  **
116233  ** If we flatten the above, we would get
116234  **
116235  ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
116236  **
116237  ** But the t2.x>0 test will always fail on a NULL row of t2, which
116238  ** effectively converts the OUTER JOIN into an INNER JOIN.
116239  **
116240  ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
116241  ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
116242  ** is fraught with danger. Best to avoid the whole thing. If the
116243  ** subquery is the right term of a LEFT JOIN, then do not flatten.
116244  */
116245  if( (pSubitem->fg.jointype & JT_OUTER)!=0 ){
116246  return 0;
116247  }
116248 
116249  /* Restriction 17: If the sub-query is a compound SELECT, then it must
116250  ** use only the UNION ALL operator. And none of the simple select queries
116251  ** that make up the compound SELECT are allowed to be aggregate or distinct
116252  ** queries.
116253  */
116254  if( pSub->pPrior ){
116255  if( pSub->pOrderBy ){
116256  return 0; /* Restriction 20 */
116257  }
116258  if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
116259  return 0;
116260  }
116261  for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
116264  assert( pSub->pSrc!=0 );
116265  assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
116266  if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
116267  || (pSub1->pPrior && pSub1->op!=TK_ALL)
116268  || pSub1->pSrc->nSrc<1
116269  ){
116270  return 0;
116271  }
116272  testcase( pSub1->pSrc->nSrc>1 );
116273  }
116274 
116275  /* Restriction 18. */
116276  if( p->pOrderBy ){
116277  int ii;
116278  for(ii=0; ii<p->pOrderBy->nExpr; ii++){
116279  if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
116280  }
116281  }
116282  }
116283 
116284  /***** If we reach this point, flattening is permitted. *****/
116285  SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
116286  pSub->zSelName, pSub, iFrom));
116287 
116288  /* Authorize the subquery */
116289  pParse->zAuthContext = pSubitem->zName;
116290  TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
116291  testcase( i==SQLITE_DENY );
116292  pParse->zAuthContext = zSavedAuthContext;
116293 
116294  /* If the sub-query is a compound SELECT statement, then (by restrictions
116295  ** 17 and 18 above) it must be a UNION ALL and the parent query must
116296  ** be of the form:
116297  **
116298  ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
116299  **
116300  ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
116301  ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
116302  ** OFFSET clauses and joins them to the left-hand-side of the original
116303  ** using UNION ALL operators. In this case N is the number of simple
116304  ** select statements in the compound sub-query.
116305  **
116306  ** Example:
116307  **
116308  ** SELECT a+1 FROM (
116309  ** SELECT x FROM tab
116310  ** UNION ALL
116311  ** SELECT y FROM tab
116312  ** UNION ALL
116313  ** SELECT abs(z*2) FROM tab2
116314  ** ) WHERE a!=5 ORDER BY 1
116315  **
116316  ** Transformed into:
116317  **
116318  ** SELECT x+1 FROM tab WHERE x+1!=5
116319  ** UNION ALL
116320  ** SELECT y+1 FROM tab WHERE y+1!=5
116321  ** UNION ALL
116322  ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
116323  ** ORDER BY 1
116324  **
116325  ** We call this the "compound-subquery flattening".
116326  */
116327  for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
116328  Select *pNew;
116329  ExprList *pOrderBy = p->pOrderBy;
116330  Expr *pLimit = p->pLimit;
116331  Expr *pOffset = p->pOffset;
116332  Select *pPrior = p->pPrior;
116333  p->pOrderBy = 0;
116334  p->pSrc = 0;
116335  p->pPrior = 0;
116336  p->pLimit = 0;
116337  p->pOffset = 0;
116338  pNew = sqlite3SelectDup(db, p, 0);
116339  sqlite3SelectSetName(pNew, pSub->zSelName);
116340  p->pOffset = pOffset;
116341  p->pLimit = pLimit;
116342  p->pOrderBy = pOrderBy;
116343  p->pSrc = pSrc;
116344  p->op = TK_ALL;
116345  if( pNew==0 ){
116346  p->pPrior = pPrior;
116347  }else{
116348  pNew->pPrior = pPrior;
116349  if( pPrior ) pPrior->pNext = pNew;
116350  pNew->pNext = p;
116351  p->pPrior = pNew;
116352  SELECTTRACE(2,pParse,p,
116353  ("compound-subquery flattener creates %s.%p as peer\n",
116354  pNew->zSelName, pNew));
116355  }
116356  if( db->mallocFailed ) return 1;
116357  }
116358 
116359  /* Begin flattening the iFrom-th entry of the FROM clause
116360  ** in the outer query.
116361  */
116362  pSub = pSub1 = pSubitem->pSelect;
116363 
116364  /* Delete the transient table structure associated with the
116365  ** subquery
116366  */
116367  sqlite3DbFree(db, pSubitem->zDatabase);
116368  sqlite3DbFree(db, pSubitem->zName);
116369  sqlite3DbFree(db, pSubitem->zAlias);
116370  pSubitem->zDatabase = 0;
116371  pSubitem->zName = 0;
116372  pSubitem->zAlias = 0;
116373  pSubitem->pSelect = 0;
116374 
116375  /* Defer deleting the Table object associated with the
116376  ** subquery until code generation is
116377  ** complete, since there may still exist Expr.pTab entries that
116378  ** refer to the subquery even after flattening. Ticket #3346.
116379  **
116380  ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
116381  */
116382  if( ALWAYS(pSubitem->pTab!=0) ){
116383  Table *pTabToDel = pSubitem->pTab;
116384  if( pTabToDel->nRef==1 ){
116385  Parse *pToplevel = sqlite3ParseToplevel(pParse);
116386  pTabToDel->pNextZombie = pToplevel->pZombieTab;
116387  pToplevel->pZombieTab = pTabToDel;
116388  }else{
116389  pTabToDel->nRef--;
116390  }
116391  pSubitem->pTab = 0;
116392  }
116393 
116394  /* The following loop runs once for each term in a compound-subquery
116395  ** flattening (as described above). If we are doing a different kind
116396  ** of flattening - a flattening other than a compound-subquery flattening -
116397  ** then this loop only runs once.
116398  **
116399  ** This loop moves all of the FROM elements of the subquery into the
116400  ** the FROM clause of the outer query. Before doing this, remember
116401  ** the cursor number for the original outer query FROM element in
116402  ** iParent. The iParent cursor will never be used. Subsequent code
116403  ** will scan expressions looking for iParent references and replace
116404  ** those references with expressions that resolve to the subquery FROM
116405  ** elements we are now copying in.
116406  */
116407  for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
116408  int nSubSrc;
116409  u8 jointype = 0;
116410  pSubSrc = pSub->pSrc; /* FROM clause of subquery */
116411  nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
116412  pSrc = pParent->pSrc; /* FROM clause of the outer query */
116413 
116414  if( pSrc ){
116415  assert( pParent==p ); /* First time through the loop */
116416  jointype = pSubitem->fg.jointype;
116417  }else{
116418  assert( pParent!=p ); /* 2nd and subsequent times through the loop */
116419  pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
116420  if( pSrc==0 ){
116421  assert( db->mallocFailed );
116422  break;
116423  }
116424  }
116425 
116426  /* The subquery uses a single slot of the FROM clause of the outer
116427  ** query. If the subquery has more than one element in its FROM clause,
116428  ** then expand the outer query to make space for it to hold all elements
116429  ** of the subquery.
116430  **
116431  ** Example:
116432  **
116433  ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
116434  **
116435  ** The outer query has 3 slots in its FROM clause. One slot of the
116436  ** outer query (the middle slot) is used by the subquery. The next
116437  ** block of code will expand the outer query FROM clause to 4 slots.
116438  ** The middle slot is expanded to two slots in order to make space
116439  ** for the two elements in the FROM clause of the subquery.
116440  */
116441  if( nSubSrc>1 ){
116442  pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
116443  if( db->mallocFailed ){
116444  break;
116445  }
116446  }
116447 
116448  /* Transfer the FROM clause terms from the subquery into the
116449  ** outer query.
116450  */
116451  for(i=0; i<nSubSrc; i++){
116452  sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
116453  assert( pSrc->a[i+iFrom].fg.isTabFunc==0 );
116454  pSrc->a[i+iFrom] = pSubSrc->a[i];
116455  memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
116456  }
116457  pSrc->a[iFrom].fg.jointype = jointype;
116458 
116459  /* Now begin substituting subquery result set expressions for
116460  ** references to the iParent in the outer query.
116461  **
116462  ** Example:
116463  **
116464  ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
116465  ** \ \_____________ subquery __________/ /
116466  ** \_____________________ outer query ______________________________/
116467  **
116468  ** We look at every expression in the outer query and every place we see
116469  ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
116470  */
116471  pList = pParent->pEList;
116472  for(i=0; i<pList->nExpr; i++){
116473  if( pList->a[i].zName==0 ){
116474  char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
116475  sqlite3Dequote(zName);
116476  pList->a[i].zName = zName;
116477  }
116478  }
116479  if( pSub->pOrderBy ){
116480  /* At this point, any non-zero iOrderByCol values indicate that the
116481  ** ORDER BY column expression is identical to the iOrderByCol'th
116482  ** expression returned by SELECT statement pSub. Since these values
116483  ** do not necessarily correspond to columns in SELECT statement pParent,
116484  ** zero them before transfering the ORDER BY clause.
116485  **
116486  ** Not doing this may cause an error if a subsequent call to this
116487  ** function attempts to flatten a compound sub-query into pParent
116488  ** (the only way this can happen is if the compound sub-query is
116489  ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
116490  ExprList *pOrderBy = pSub->pOrderBy;
116491  for(i=0; i<pOrderBy->nExpr; i++){
116492  pOrderBy->a[i].u.x.iOrderByCol = 0;
116493  }
116494  assert( pParent->pOrderBy==0 );
116495  assert( pSub->pPrior==0 );
116496  pParent->pOrderBy = pOrderBy;
116497  pSub->pOrderBy = 0;
116498  }
116499  pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
116500  if( subqueryIsAgg ){
116501  assert( pParent->pHaving==0 );
116502  pParent->pHaving = pParent->pWhere;
116503  pParent->pWhere = pWhere;
116504  pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
116505  sqlite3ExprDup(db, pSub->pHaving, 0));
116506  assert( pParent->pGroupBy==0 );
116507  pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
116508  }else{
116509  pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
116510  }
116511  substSelect(db, pParent, iParent, pSub->pEList, 0);
116512 
116513  /* The flattened query is distinct if either the inner or the
116514  ** outer query is distinct.
116515  */
116516  pParent->selFlags |= pSub->selFlags & SF_Distinct;
116517 
116518  /*
116519  ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
116520  **
116521  ** One is tempted to try to add a and b to combine the limits. But this
116522  ** does not work if either limit is negative.
116523  */
116524  if( pSub->pLimit ){
116525  pParent->pLimit = pSub->pLimit;
116526  pSub->pLimit = 0;
116527  }
116528  }
116529 
116530  /* Finially, delete what is left of the subquery and return
116531  ** success.
116532  */
116533  sqlite3SelectDelete(db, pSub1);
116534 
116535 #if SELECTTRACE_ENABLED
116536  if( sqlite3SelectTrace & 0x100 ){
116537  SELECTTRACE(0x100,pParse,p,("After flattening:\n"));
116538  sqlite3TreeViewSelect(0, p, 0);
116539  }
116540 #endif
116541 
116542  return 1;
116543 }
116544 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
116545 
116546 
116547 
116548 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
116549 /*
116550 ** Make copies of relevant WHERE clause terms of the outer query into
116551 ** the WHERE clause of subquery. Example:
116552 **
116553 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
116554 **
116555 ** Transformed into:
116556 **
116557 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
116558 ** WHERE x=5 AND y=10;
116559 **
116560 ** The hope is that the terms added to the inner query will make it more
116561 ** efficient.
116562 **
116563 ** Do not attempt this optimization if:
116564 **
116565 ** (1) The inner query is an aggregate. (In that case, we'd really want
116566 ** to copy the outer WHERE-clause terms onto the HAVING clause of the
116567 ** inner query. But they probably won't help there so do not bother.)
116568 **
116569 ** (2) The inner query is the recursive part of a common table expression.
116570 **
116571 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
116572 ** close would change the meaning of the LIMIT).
116573 **
116574 ** (4) The inner query is the right operand of a LEFT JOIN. (The caller
116575 ** enforces this restriction since this routine does not have enough
116576 ** information to know.)
116577 **
116578 ** (5) The WHERE clause expression originates in the ON or USING clause
116579 ** of a LEFT JOIN.
116580 **
116581 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
116582 ** terms are duplicated into the subquery.
116583 */
116585  sqlite3 *db, /* The database connection (for malloc()) */
116586  Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
116587  Expr *pWhere, /* The WHERE clause of the outer query */
116588  int iCursor /* Cursor number of the subquery */
116589 ){
116590  Expr *pNew;
116591  int nChng = 0;
116592  Select *pX; /* For looping over compound SELECTs in pSubq */
116593  if( pWhere==0 ) return 0;
116594  for(pX=pSubq; pX; pX=pX->pPrior){
116595  if( (pX->selFlags & (SF_Aggregate|SF_Recursive))!=0 ){
116596  testcase( pX->selFlags & SF_Aggregate );
116597  testcase( pX->selFlags & SF_Recursive );
116598  testcase( pX!=pSubq );
116599  return 0; /* restrictions (1) and (2) */
116600  }
116601  }
116602  if( pSubq->pLimit!=0 ){
116603  return 0; /* restriction (3) */
116604  }
116605  while( pWhere->op==TK_AND ){
116606  nChng += pushDownWhereTerms(db, pSubq, pWhere->pRight, iCursor);
116607  pWhere = pWhere->pLeft;
116608  }
116609  if( ExprHasProperty(pWhere,EP_FromJoin) ) return 0; /* restriction 5 */
116610  if( sqlite3ExprIsTableConstant(pWhere, iCursor) ){
116611  nChng++;
116612  while( pSubq ){
116613  pNew = sqlite3ExprDup(db, pWhere, 0);
116614  pNew = substExpr(db, pNew, iCursor, pSubq->pEList);
116615  pSubq->pWhere = sqlite3ExprAnd(db, pSubq->pWhere, pNew);
116616  pSubq = pSubq->pPrior;
116617  }
116618  }
116619  return nChng;
116620 }
116621 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
116622 
116623 /*
116624 ** Based on the contents of the AggInfo structure indicated by the first
116625 ** argument, this function checks if the following are true:
116626 **
116627 ** * the query contains just a single aggregate function,
116628 ** * the aggregate function is either min() or max(), and
116629 ** * the argument to the aggregate function is a column value.
116630 **
116631 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
116632 ** is returned as appropriate. Also, *ppMinMax is set to point to the
116633 ** list of arguments passed to the aggregate before returning.
116634 **
116635 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
116636 ** WHERE_ORDERBY_NORMAL is returned.
116637 */
116638 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
116639  int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
116640 
116641  *ppMinMax = 0;
116642  if( pAggInfo->nFunc==1 ){
116643  Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
116644  ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
116645 
116646  assert( pExpr->op==TK_AGG_FUNCTION );
116647  if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
116648  const char *zFunc = pExpr->u.zToken;
116649  if( sqlite3StrICmp(zFunc, "min")==0 ){
116650  eRet = WHERE_ORDERBY_MIN;
116651  *ppMinMax = pEList;
116652  }else if( sqlite3StrICmp(zFunc, "max")==0 ){
116653  eRet = WHERE_ORDERBY_MAX;
116654  *ppMinMax = pEList;
116655  }
116656  }
116657  }
116658 
116659  assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
116660  return eRet;
116661 }
116662 
116663 /*
116664 ** The select statement passed as the first argument is an aggregate query.
116665 ** The second argument is the associated aggregate-info object. This
116666 ** function tests if the SELECT is of the form:
116667 **
116668 ** SELECT count(*) FROM <tbl>
116669 **
116670 ** where table is a database table, not a sub-select or view. If the query
116671 ** does match this pattern, then a pointer to the Table object representing
116672 ** <tbl> is returned. Otherwise, 0 is returned.
116673 */
116674 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
116675  Table *pTab;
116676  Expr *pExpr;
116677 
116678  assert( !p->pGroupBy );
116679 
116680  if( p->pWhere || p->pEList->nExpr!=1
116681  || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
116682  ){
116683  return 0;
116684  }
116685  pTab = p->pSrc->a[0].pTab;
116686  pExpr = p->pEList->a[0].pExpr;
116687  assert( pTab && !pTab->pSelect && pExpr );
116688 
116689  if( IsVirtual(pTab) ) return 0;
116690  if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
116691  if( NEVER(pAggInfo->nFunc==0) ) return 0;
116692  if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
116693  if( pExpr->flags&EP_Distinct ) return 0;
116694 
116695  return pTab;
116696 }
116697 
116698 /*
116699 ** If the source-list item passed as an argument was augmented with an
116700 ** INDEXED BY clause, then try to locate the specified index. If there
116701 ** was such a clause and the named index cannot be found, return
116702 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
116703 ** pFrom->pIndex and return SQLITE_OK.
116704 */
116705 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
116706  if( pFrom->pTab && pFrom->fg.isIndexedBy ){
116707  Table *pTab = pFrom->pTab;
116708  char *zIndexedBy = pFrom->u1.zIndexedBy;
116709  Index *pIdx;
116710  for(pIdx=pTab->pIndex;
116711  pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
116712  pIdx=pIdx->pNext
116713  );
116714  if( !pIdx ){
116715  sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
116716  pParse->checkSchema = 1;
116717  return SQLITE_ERROR;
116718  }
116719  pFrom->pIBIndex = pIdx;
116720  }
116721  return SQLITE_OK;
116722 }
116723 /*
116724 ** Detect compound SELECT statements that use an ORDER BY clause with
116725 ** an alternative collating sequence.
116726 **
116727 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
116728 **
116729 ** These are rewritten as a subquery:
116730 **
116731 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
116732 ** ORDER BY ... COLLATE ...
116733 **
116734 ** This transformation is necessary because the multiSelectOrderBy() routine
116735 ** above that generates the code for a compound SELECT with an ORDER BY clause
116736 ** uses a merge algorithm that requires the same collating sequence on the
116737 ** result columns as on the ORDER BY clause. See ticket
116738 ** http://www.sqlite.org/src/info/6709574d2a
116739 **
116740 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
116741 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
116742 ** there are COLLATE terms in the ORDER BY.
116743 */
116745  int i;
116746  Select *pNew;
116747  Select *pX;
116748  sqlite3 *db;
116749  struct ExprList_item *a;
116750  SrcList *pNewSrc;
116751  Parse *pParse;
116752  Token dummy;
116753 
116754  if( p->pPrior==0 ) return WRC_Continue;
116755  if( p->pOrderBy==0 ) return WRC_Continue;
116756  for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
116757  if( pX==0 ) return WRC_Continue;
116758  a = p->pOrderBy->a;
116759  for(i=p->pOrderBy->nExpr-1; i>=0; i--){
116760  if( a[i].pExpr->flags & EP_Collate ) break;
116761  }
116762  if( i<0 ) return WRC_Continue;
116763 
116764  /* If we reach this point, that means the transformation is required. */
116765 
116766  pParse = pWalker->pParse;
116767  db = pParse->db;
116768  pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
116769  if( pNew==0 ) return WRC_Abort;
116770  memset(&dummy, 0, sizeof(dummy));
116771  pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
116772  if( pNewSrc==0 ) return WRC_Abort;
116773  *pNew = *p;
116774  p->pSrc = pNewSrc;
116775  p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
116776  p->op = TK_SELECT;
116777  p->pWhere = 0;
116778  pNew->pGroupBy = 0;
116779  pNew->pHaving = 0;
116780  pNew->pOrderBy = 0;
116781  p->pPrior = 0;
116782  p->pNext = 0;
116783  p->pWith = 0;
116784  p->selFlags &= ~SF_Compound;
116785  assert( (p->selFlags & SF_Converted)==0 );
116786  p->selFlags |= SF_Converted;
116787  assert( pNew->pPrior!=0 );
116788  pNew->pPrior->pNext = pNew;
116789  pNew->pLimit = 0;
116790  pNew->pOffset = 0;
116791  return WRC_Continue;
116792 }
116793 
116794 /*
116795 ** Check to see if the FROM clause term pFrom has table-valued function
116796 ** arguments. If it does, leave an error message in pParse and return
116797 ** non-zero, since pFrom is not allowed to be a table-valued function.
116798 */
116799 static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom){
116800  if( pFrom->fg.isTabFunc ){
116801  sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
116802  return 1;
116803  }
116804  return 0;
116805 }
116806 
116807 #ifndef SQLITE_OMIT_CTE
116808 /*
116809 ** Argument pWith (which may be NULL) points to a linked list of nested
116810 ** WITH contexts, from inner to outermost. If the table identified by
116811 ** FROM clause element pItem is really a common-table-expression (CTE)
116812 ** then return a pointer to the CTE definition for that table. Otherwise
116813 ** return NULL.
116814 **
116815 ** If a non-NULL value is returned, set *ppContext to point to the With
116816 ** object that the returned CTE belongs to.
116817 */
116818 static struct Cte *searchWith(
116819  With *pWith, /* Current innermost WITH clause */
116820  struct SrcList_item *pItem, /* FROM clause element to resolve */
116821  With **ppContext /* OUT: WITH clause return value belongs to */
116822 ){
116823  const char *zName;
116824  if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
116825  With *p;
116826  for(p=pWith; p; p=p->pOuter){
116827  int i;
116828  for(i=0; i<p->nCte; i++){
116829  if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
116830  *ppContext = p;
116831  return &p->a[i];
116832  }
116833  }
116834  }
116835  }
116836  return 0;
116837 }
116838 
116839 /* The code generator maintains a stack of active WITH clauses
116840 ** with the inner-most WITH clause being at the top of the stack.
116841 **
116842 ** This routine pushes the WITH clause passed as the second argument
116843 ** onto the top of the stack. If argument bFree is true, then this
116844 ** WITH clause will never be popped from the stack. In this case it
116845 ** should be freed along with the Parse object. In other cases, when
116846 ** bFree==0, the With object will be freed along with the SELECT
116847 ** statement with which it is associated.
116848 */
116849 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
116850  assert( bFree==0 || (pParse->pWith==0 && pParse->pWithToFree==0) );
116851  if( pWith ){
116852  assert( pParse->pWith!=pWith );
116853  pWith->pOuter = pParse->pWith;
116854  pParse->pWith = pWith;
116855  if( bFree ) pParse->pWithToFree = pWith;
116856  }
116857 }
116858 
116859 /*
116860 ** This function checks if argument pFrom refers to a CTE declared by
116861 ** a WITH clause on the stack currently maintained by the parser. And,
116862 ** if currently processing a CTE expression, if it is a recursive
116863 ** reference to the current CTE.
116864 **
116865 ** If pFrom falls into either of the two categories above, pFrom->pTab
116866 ** and other fields are populated accordingly. The caller should check
116867 ** (pFrom->pTab!=0) to determine whether or not a successful match
116868 ** was found.
116869 **
116870 ** Whether or not a match is found, SQLITE_OK is returned if no error
116871 ** occurs. If an error does occur, an error message is stored in the
116872 ** parser and some error code other than SQLITE_OK returned.
116873 */
116874 static int withExpand(
116875  Walker *pWalker,
116876  struct SrcList_item *pFrom
116877 ){
116878  Parse *pParse = pWalker->pParse;
116879  sqlite3 *db = pParse->db;
116880  struct Cte *pCte; /* Matched CTE (or NULL if no match) */
116881  With *pWith; /* WITH clause that pCte belongs to */
116882 
116883  assert( pFrom->pTab==0 );
116884 
116885  pCte = searchWith(pParse->pWith, pFrom, &pWith);
116886  if( pCte ){
116887  Table *pTab;
116888  ExprList *pEList;
116889  Select *pSel;
116890  Select *pLeft; /* Left-most SELECT statement */
116891  int bMayRecursive; /* True if compound joined by UNION [ALL] */
116892  With *pSavedWith; /* Initial value of pParse->pWith */
116893 
116894  /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
116895  ** recursive reference to CTE pCte. Leave an error in pParse and return
116896  ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
116897  ** In this case, proceed. */
116898  if( pCte->zCteErr ){
116899  sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
116900  return SQLITE_ERROR;
116901  }
116902  if( cannotBeFunction(pParse, pFrom) ) return SQLITE_ERROR;
116903 
116904  assert( pFrom->pTab==0 );
116905  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
116906  if( pTab==0 ) return WRC_Abort;
116907  pTab->nRef = 1;
116908  pTab->zName = sqlite3DbStrDup(db, pCte->zName);
116909  pTab->iPKey = -1;
116910  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
116912  pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
116913  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
116914  assert( pFrom->pSelect );
116915 
116916  /* Check if this is a recursive CTE. */
116917  pSel = pFrom->pSelect;
116918  bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
116919  if( bMayRecursive ){
116920  int i;
116921  SrcList *pSrc = pFrom->pSelect->pSrc;
116922  for(i=0; i<pSrc->nSrc; i++){
116923  struct SrcList_item *pItem = &pSrc->a[i];
116924  if( pItem->zDatabase==0
116925  && pItem->zName!=0
116926  && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
116927  ){
116928  pItem->pTab = pTab;
116929  pItem->fg.isRecursive = 1;
116930  pTab->nRef++;
116931  pSel->selFlags |= SF_Recursive;
116932  }
116933  }
116934  }
116935 
116936  /* Only one recursive reference is permitted. */
116937  if( pTab->nRef>2 ){
116938  sqlite3ErrorMsg(
116939  pParse, "multiple references to recursive table: %s", pCte->zName
116940  );
116941  return SQLITE_ERROR;
116942  }
116943  assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
116944 
116945  pCte->zCteErr = "circular reference: %s";
116946  pSavedWith = pParse->pWith;
116947  pParse->pWith = pWith;
116948  sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
116949  pParse->pWith = pWith;
116950 
116951  for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
116952  pEList = pLeft->pEList;
116953  if( pCte->pCols ){
116954  if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
116955  sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
116956  pCte->zName, pEList->nExpr, pCte->pCols->nExpr
116957  );
116958  pParse->pWith = pSavedWith;
116959  return SQLITE_ERROR;
116960  }
116961  pEList = pCte->pCols;
116962  }
116963 
116964  sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
116965  if( bMayRecursive ){
116966  if( pSel->selFlags & SF_Recursive ){
116967  pCte->zCteErr = "multiple recursive references: %s";
116968  }else{
116969  pCte->zCteErr = "recursive reference in a subquery: %s";
116970  }
116971  sqlite3WalkSelect(pWalker, pSel);
116972  }
116973  pCte->zCteErr = 0;
116974  pParse->pWith = pSavedWith;
116975  }
116976 
116977  return SQLITE_OK;
116978 }
116979 #endif
116980 
116981 #ifndef SQLITE_OMIT_CTE
116982 /*
116983 ** If the SELECT passed as the second argument has an associated WITH
116984 ** clause, pop it from the stack stored as part of the Parse object.
116985 **
116986 ** This function is used as the xSelectCallback2() callback by
116987 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
116988 ** names and other FROM clause elements.
116989 */
116990 static void selectPopWith(Walker *pWalker, Select *p){
116991  Parse *pParse = pWalker->pParse;
116992  With *pWith = findRightmost(p)->pWith;
116993  if( pWith!=0 ){
116994  assert( pParse->pWith==pWith );
116995  pParse->pWith = pWith->pOuter;
116996  }
116997 }
116998 #else
116999 #define selectPopWith 0
117000 #endif
117001 
117002 /*
117003 ** This routine is a Walker callback for "expanding" a SELECT statement.
117004 ** "Expanding" means to do the following:
117005 **
117006 ** (1) Make sure VDBE cursor numbers have been assigned to every
117007 ** element of the FROM clause.
117008 **
117009 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
117010 ** defines FROM clause. When views appear in the FROM clause,
117011 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
117012 ** that implements the view. A copy is made of the view's SELECT
117013 ** statement so that we can freely modify or delete that statement
117014 ** without worrying about messing up the persistent representation
117015 ** of the view.
117016 **
117017 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
117018 ** on joins and the ON and USING clause of joins.
117019 **
117020 ** (4) Scan the list of columns in the result set (pEList) looking
117021 ** for instances of the "*" operator or the TABLE.* operator.
117022 ** If found, expand each "*" to be every column in every table
117023 ** and TABLE.* to be every column in TABLE.
117024 **
117025 */
117026 static int selectExpander(Walker *pWalker, Select *p){
117027  Parse *pParse = pWalker->pParse;
117028  int i, j, k;
117029  SrcList *pTabList;
117030  ExprList *pEList;
117031  struct SrcList_item *pFrom;
117032  sqlite3 *db = pParse->db;
117033  Expr *pE, *pRight, *pExpr;
117034  u16 selFlags = p->selFlags;
117035 
117036  p->selFlags |= SF_Expanded;
117037  if( db->mallocFailed ){
117038  return WRC_Abort;
117039  }
117040  if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
117041  return WRC_Prune;
117042  }
117043  pTabList = p->pSrc;
117044  pEList = p->pEList;
117045  if( pWalker->xSelectCallback2==selectPopWith ){
117046  sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
117047  }
117048 
117049  /* Make sure cursor numbers have been assigned to all entries in
117050  ** the FROM clause of the SELECT statement.
117051  */
117052  sqlite3SrcListAssignCursors(pParse, pTabList);
117053 
117054  /* Look up every table named in the FROM clause of the select. If
117055  ** an entry of the FROM clause is a subquery instead of a table or view,
117056  ** then create a transient table structure to describe the subquery.
117057  */
117058  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117059  Table *pTab;
117060  assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
117061  if( pFrom->fg.isRecursive ) continue;
117062  assert( pFrom->pTab==0 );
117063 #ifndef SQLITE_OMIT_CTE
117064  if( withExpand(pWalker, pFrom) ) return WRC_Abort;
117065  if( pFrom->pTab ) {} else
117066 #endif
117067  if( pFrom->zName==0 ){
117068 #ifndef SQLITE_OMIT_SUBQUERY
117069  Select *pSel = pFrom->pSelect;
117070  /* A sub-query in the FROM clause of a SELECT */
117071  assert( pSel!=0 );
117072  assert( pFrom->pTab==0 );
117073  if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
117074  pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
117075  if( pTab==0 ) return WRC_Abort;
117076  pTab->nRef = 1;
117077  pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
117078  while( pSel->pPrior ){ pSel = pSel->pPrior; }
117079  sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
117080  pTab->iPKey = -1;
117081  pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
117082  pTab->tabFlags |= TF_Ephemeral;
117083 #endif
117084  }else{
117085  /* An ordinary table or view name in the FROM clause */
117086  assert( pFrom->pTab==0 );
117087  pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
117088  if( pTab==0 ) return WRC_Abort;
117089  if( pTab->nRef==0xffff ){
117090  sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
117091  pTab->zName);
117092  pFrom->pTab = 0;
117093  return WRC_Abort;
117094  }
117095  pTab->nRef++;
117096  if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
117097  return WRC_Abort;
117098  }
117099 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
117100  if( IsVirtual(pTab) || pTab->pSelect ){
117101  i16 nCol;
117102  if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
117103  assert( pFrom->pSelect==0 );
117104  pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
117105  sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
117106  nCol = pTab->nCol;
117107  pTab->nCol = -1;
117108  sqlite3WalkSelect(pWalker, pFrom->pSelect);
117109  pTab->nCol = nCol;
117110  }
117111 #endif
117112  }
117113 
117114  /* Locate the index named by the INDEXED BY clause, if any. */
117115  if( sqlite3IndexedByLookup(pParse, pFrom) ){
117116  return WRC_Abort;
117117  }
117118  }
117119 
117120  /* Process NATURAL keywords, and ON and USING clauses of joins.
117121  */
117122  if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
117123  return WRC_Abort;
117124  }
117125 
117126  /* For every "*" that occurs in the column list, insert the names of
117127  ** all columns in all tables. And for every TABLE.* insert the names
117128  ** of all columns in TABLE. The parser inserted a special expression
117129  ** with the TK_ASTERISK operator for each "*" that it found in the column
117130  ** list. The following code just has to locate the TK_ASTERISK
117131  ** expressions and expand each one to the list of all columns in
117132  ** all tables.
117133  **
117134  ** The first loop just checks to see if there are any "*" operators
117135  ** that need expanding.
117136  */
117137  for(k=0; k<pEList->nExpr; k++){
117138  pE = pEList->a[k].pExpr;
117139  if( pE->op==TK_ASTERISK ) break;
117140  assert( pE->op!=TK_DOT || pE->pRight!=0 );
117141  assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
117142  if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
117143  }
117144  if( k<pEList->nExpr ){
117145  /*
117146  ** If we get here it means the result set contains one or more "*"
117147  ** operators that need to be expanded. Loop through each expression
117148  ** in the result set and expand them one by one.
117149  */
117150  struct ExprList_item *a = pEList->a;
117151  ExprList *pNew = 0;
117152  int flags = pParse->db->flags;
117153  int longNames = (flags & SQLITE_FullColNames)!=0
117154  && (flags & SQLITE_ShortColNames)==0;
117155 
117156  for(k=0; k<pEList->nExpr; k++){
117157  pE = a[k].pExpr;
117158  pRight = pE->pRight;
117159  assert( pE->op!=TK_DOT || pRight!=0 );
117160  if( pE->op!=TK_ASTERISK
117161  && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
117162  ){
117163  /* This particular expression does not need to be expanded.
117164  */
117165  pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
117166  if( pNew ){
117167  pNew->a[pNew->nExpr-1].zName = a[k].zName;
117168  pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
117169  a[k].zName = 0;
117170  a[k].zSpan = 0;
117171  }
117172  a[k].pExpr = 0;
117173  }else{
117174  /* This expression is a "*" or a "TABLE.*" and needs to be
117175  ** expanded. */
117176  int tableSeen = 0; /* Set to 1 when TABLE matches */
117177  char *zTName = 0; /* text of name of TABLE */
117178  if( pE->op==TK_DOT ){
117179  assert( pE->pLeft!=0 );
117181  zTName = pE->pLeft->u.zToken;
117182  }
117183  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117184  Table *pTab = pFrom->pTab;
117185  Select *pSub = pFrom->pSelect;
117186  char *zTabName = pFrom->zAlias;
117187  const char *zSchemaName = 0;
117188  int iDb;
117189  if( zTabName==0 ){
117190  zTabName = pTab->zName;
117191  }
117192  if( db->mallocFailed ) break;
117193  if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
117194  pSub = 0;
117195  if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
117196  continue;
117197  }
117198  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
117199  zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
117200  }
117201  for(j=0; j<pTab->nCol; j++){
117202  char *zName = pTab->aCol[j].zName;
117203  char *zColname; /* The computed column name */
117204  char *zToFree; /* Malloced string that needs to be freed */
117205  Token sColname; /* Computed column name as a token */
117206 
117207  assert( zName );
117208  if( zTName && pSub
117209  && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
117210  ){
117211  continue;
117212  }
117213 
117214  /* If a column is marked as 'hidden', omit it from the expanded
117215  ** result-set list unless the SELECT has the SF_IncludeHidden
117216  ** bit set.
117217  */
117218  if( (p->selFlags & SF_IncludeHidden)==0
117219  && IsHiddenColumn(&pTab->aCol[j])
117220  ){
117221  continue;
117222  }
117223  tableSeen = 1;
117224 
117225  if( i>0 && zTName==0 ){
117226  if( (pFrom->fg.jointype & JT_NATURAL)!=0
117227  && tableAndColumnIndex(pTabList, i, zName, 0, 0)
117228  ){
117229  /* In a NATURAL join, omit the join columns from the
117230  ** table to the right of the join */
117231  continue;
117232  }
117233  if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
117234  /* In a join with a USING clause, omit columns in the
117235  ** using clause from the table on the right. */
117236  continue;
117237  }
117238  }
117239  pRight = sqlite3Expr(db, TK_ID, zName);
117240  zColname = zName;
117241  zToFree = 0;
117242  if( longNames || pTabList->nSrc>1 ){
117243  Expr *pLeft;
117244  pLeft = sqlite3Expr(db, TK_ID, zTabName);
117245  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
117246  if( zSchemaName ){
117247  pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
117248  pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
117249  }
117250  if( longNames ){
117251  zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
117252  zToFree = zColname;
117253  }
117254  }else{
117255  pExpr = pRight;
117256  }
117257  pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
117258  sqlite3TokenInit(&sColname, zColname);
117259  sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
117260  if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
117261  struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
117262  if( pSub ){
117263  pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
117264  testcase( pX->zSpan==0 );
117265  }else{
117266  pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
117267  zSchemaName, zTabName, zColname);
117268  testcase( pX->zSpan==0 );
117269  }
117270  pX->bSpanIsTab = 1;
117271  }
117272  sqlite3DbFree(db, zToFree);
117273  }
117274  }
117275  if( !tableSeen ){
117276  if( zTName ){
117277  sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
117278  }else{
117279  sqlite3ErrorMsg(pParse, "no tables specified");
117280  }
117281  }
117282  }
117283  }
117284  sqlite3ExprListDelete(db, pEList);
117285  p->pEList = pNew;
117286  }
117287 #if SQLITE_MAX_COLUMN
117288  if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
117289  sqlite3ErrorMsg(pParse, "too many columns in result set");
117290  return WRC_Abort;
117291  }
117292 #endif
117293  return WRC_Continue;
117294 }
117295 
117296 /*
117297 ** No-op routine for the parse-tree walker.
117298 **
117299 ** When this routine is the Walker.xExprCallback then expression trees
117300 ** are walked without any actions being taken at each node. Presumably,
117301 ** when this routine is used for Walker.xExprCallback then
117302 ** Walker.xSelectCallback is set to do something useful for every
117303 ** subquery in the parser tree.
117304 */
117306  UNUSED_PARAMETER2(NotUsed, NotUsed2);
117307  return WRC_Continue;
117308 }
117309 
117310 /*
117311 ** This routine "expands" a SELECT statement and all of its subqueries.
117312 ** For additional information on what it means to "expand" a SELECT
117313 ** statement, see the comment on the selectExpand worker callback above.
117314 **
117315 ** Expanding a SELECT statement is the first step in processing a
117316 ** SELECT statement. The SELECT statement must be expanded before
117317 ** name resolution is performed.
117318 **
117319 ** If anything goes wrong, an error message is written into pParse.
117320 ** The calling function can detect the problem by looking at pParse->nErr
117321 ** and/or pParse->db->mallocFailed.
117322 */
117323 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
117324  Walker w;
117325  memset(&w, 0, sizeof(w));
117327  w.pParse = pParse;
117328  if( pParse->hasCompound ){
117330  sqlite3WalkSelect(&w, pSelect);
117331  }
117333  if( (pSelect->selFlags & SF_MultiValue)==0 ){
117335  }
117336  sqlite3WalkSelect(&w, pSelect);
117337 }
117338 
117339 
117340 #ifndef SQLITE_OMIT_SUBQUERY
117341 /*
117342 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
117343 ** interface.
117344 **
117345 ** For each FROM-clause subquery, add Column.zType and Column.zColl
117346 ** information to the Table structure that represents the result set
117347 ** of that subquery.
117348 **
117349 ** The Table structure that represents the result set was constructed
117350 ** by selectExpander() but the type and collation information was omitted
117351 ** at that point because identifiers had not yet been resolved. This
117352 ** routine is called after identifier resolution.
117353 */
117354 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
117355  Parse *pParse;
117356  int i;
117357  SrcList *pTabList;
117358  struct SrcList_item *pFrom;
117359 
117360  assert( p->selFlags & SF_Resolved );
117361  assert( (p->selFlags & SF_HasTypeInfo)==0 );
117362  p->selFlags |= SF_HasTypeInfo;
117363  pParse = pWalker->pParse;
117364  pTabList = p->pSrc;
117365  for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
117366  Table *pTab = pFrom->pTab;
117367  assert( pTab!=0 );
117368  if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
117369  /* A sub-query in the FROM clause of a SELECT */
117370  Select *pSel = pFrom->pSelect;
117371  if( pSel ){
117372  while( pSel->pPrior ) pSel = pSel->pPrior;
117373  sqlite3SelectAddColumnTypeAndCollation(pParse, pTab, pSel);
117374  }
117375  }
117376  }
117377 }
117378 #endif
117379 
117380 
117381 /*
117382 ** This routine adds datatype and collating sequence information to
117383 ** the Table structures of all FROM-clause subqueries in a
117384 ** SELECT statement.
117385 **
117386 ** Use this routine after name resolution.
117387 */
117388 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
117389 #ifndef SQLITE_OMIT_SUBQUERY
117390  Walker w;
117391  memset(&w, 0, sizeof(w));
117394  w.pParse = pParse;
117395  sqlite3WalkSelect(&w, pSelect);
117396 #endif
117397 }
117398 
117399 
117400 /*
117401 ** This routine sets up a SELECT statement for processing. The
117402 ** following is accomplished:
117403 **
117404 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
117405 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
117406 ** * ON and USING clauses are shifted into WHERE statements
117407 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
117408 ** * Identifiers in expression are matched to tables.
117409 **
117410 ** This routine acts recursively on all subqueries within the SELECT.
117411 */
117413  Parse *pParse, /* The parser context */
117414  Select *p, /* The SELECT statement being coded. */
117415  NameContext *pOuterNC /* Name context for container */
117416 ){
117417  sqlite3 *db;
117418  if( NEVER(p==0) ) return;
117419  db = pParse->db;
117420  if( db->mallocFailed ) return;
117421  if( p->selFlags & SF_HasTypeInfo ) return;
117422  sqlite3SelectExpand(pParse, p);
117423  if( pParse->nErr || db->mallocFailed ) return;
117424  sqlite3ResolveSelectNames(pParse, p, pOuterNC);
117425  if( pParse->nErr || db->mallocFailed ) return;
117426  sqlite3SelectAddTypeInfo(pParse, p);
117427 }
117428 
117429 /*
117430 ** Reset the aggregate accumulator.
117431 **
117432 ** The aggregate accumulator is a set of memory cells that hold
117433 ** intermediate results while calculating an aggregate. This
117434 ** routine generates code that stores NULLs in all of those memory
117435 ** cells.
117436 */
117437 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
117438  Vdbe *v = pParse->pVdbe;
117439  int i;
117440  struct AggInfo_func *pFunc;
117441  int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
117442  if( nReg==0 ) return;
117443 #ifdef SQLITE_DEBUG
117444  /* Verify that all AggInfo registers are within the range specified by
117445  ** AggInfo.mnReg..AggInfo.mxReg */
117446  assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
117447  for(i=0; i<pAggInfo->nColumn; i++){
117448  assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
117449  && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
117450  }
117451  for(i=0; i<pAggInfo->nFunc; i++){
117452  assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
117453  && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
117454  }
117455 #endif
117456  sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
117457  for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
117458  if( pFunc->iDistinct>=0 ){
117459  Expr *pE = pFunc->pExpr;
117461  if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
117462  sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
117463  "argument");
117464  pFunc->iDistinct = -1;
117465  }else{
117466  KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
117467  sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
117468  (char*)pKeyInfo, P4_KEYINFO);
117469  }
117470  }
117471  }
117472 }
117473 
117474 /*
117475 ** Invoke the OP_AggFinalize opcode for every aggregate function
117476 ** in the AggInfo structure.
117477 */
117478 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
117479  Vdbe *v = pParse->pVdbe;
117480  int i;
117481  struct AggInfo_func *pF;
117482  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
117483  ExprList *pList = pF->pExpr->x.pList;
117484  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
117485  sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
117486  (void*)pF->pFunc, P4_FUNCDEF);
117487  }
117488 }
117489 
117490 /*
117491 ** Update the accumulator memory cells for an aggregate based on
117492 ** the current cursor position.
117493 */
117494 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
117495  Vdbe *v = pParse->pVdbe;
117496  int i;
117497  int regHit = 0;
117498  int addrHitTest = 0;
117499  struct AggInfo_func *pF;
117500  struct AggInfo_col *pC;
117501 
117502  pAggInfo->directMode = 1;
117503  for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
117504  int nArg;
117505  int addrNext = 0;
117506  int regAgg;
117507  ExprList *pList = pF->pExpr->x.pList;
117508  assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
117509  if( pList ){
117510  nArg = pList->nExpr;
117511  regAgg = sqlite3GetTempRange(pParse, nArg);
117512  sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
117513  }else{
117514  nArg = 0;
117515  regAgg = 0;
117516  }
117517  if( pF->iDistinct>=0 ){
117518  addrNext = sqlite3VdbeMakeLabel(v);
117519  testcase( nArg==0 ); /* Error condition */
117520  testcase( nArg>1 ); /* Also an error */
117521  codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
117522  }
117523  if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
117524  CollSeq *pColl = 0;
117525  struct ExprList_item *pItem;
117526  int j;
117527  assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
117528  for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
117529  pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
117530  }
117531  if( !pColl ){
117532  pColl = pParse->db->pDfltColl;
117533  }
117534  if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
117535  sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
117536  }
117537  sqlite3VdbeAddOp4(v, OP_AggStep0, 0, regAgg, pF->iMem,
117538  (void*)pF->pFunc, P4_FUNCDEF);
117539  sqlite3VdbeChangeP5(v, (u8)nArg);
117540  sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
117541  sqlite3ReleaseTempRange(pParse, regAgg, nArg);
117542  if( addrNext ){
117543  sqlite3VdbeResolveLabel(v, addrNext);
117544  sqlite3ExprCacheClear(pParse);
117545  }
117546  }
117547 
117548  /* Before populating the accumulator registers, clear the column cache.
117549  ** Otherwise, if any of the required column values are already present
117550  ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
117551  ** to pC->iMem. But by the time the value is used, the original register
117552  ** may have been used, invalidating the underlying buffer holding the
117553  ** text or blob value. See ticket [883034dcb5].
117554  **
117555  ** Another solution would be to change the OP_SCopy used to copy cached
117556  ** values to an OP_Copy.
117557  */
117558  if( regHit ){
117559  addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
117560  }
117561  sqlite3ExprCacheClear(pParse);
117562  for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
117563  sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
117564  }
117565  pAggInfo->directMode = 0;
117566  sqlite3ExprCacheClear(pParse);
117567  if( addrHitTest ){
117568  sqlite3VdbeJumpHere(v, addrHitTest);
117569  }
117570 }
117571 
117572 /*
117573 ** Add a single OP_Explain instruction to the VDBE to explain a simple
117574 ** count(*) query ("SELECT count(*) FROM pTab").
117575 */
117576 #ifndef SQLITE_OMIT_EXPLAIN
117578  Parse *pParse, /* Parse context */
117579  Table *pTab, /* Table being queried */
117580  Index *pIdx /* Index used to optimize scan, or NULL */
117581 ){
117582  if( pParse->explain==2 ){
117583  int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
117584  char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
117585  pTab->zName,
117586  bCover ? " USING COVERING INDEX " : "",
117587  bCover ? pIdx->zName : ""
117588  );
117590  pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
117591  );
117592  }
117593 }
117594 #else
117595 # define explainSimpleCount(a,b,c)
117596 #endif
117597 
117598 /*
117599 ** Generate code for the SELECT statement given in the p argument.
117600 **
117601 ** The results are returned according to the SelectDest structure.
117602 ** See comments in sqliteInt.h for further information.
117603 **
117604 ** This routine returns the number of errors. If any errors are
117605 ** encountered, then an appropriate error message is left in
117606 ** pParse->zErrMsg.
117607 **
117608 ** This routine does NOT free the Select structure passed in. The
117609 ** calling function needs to do that.
117610 */
117612  Parse *pParse, /* The parser context */
117613  Select *p, /* The SELECT statement being coded. */
117614  SelectDest *pDest /* What to do with the query results */
117615 ){
117616  int i, j; /* Loop counters */
117617  WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
117618  Vdbe *v; /* The virtual machine under construction */
117619  int isAgg; /* True for select lists like "count(*)" */
117620  ExprList *pEList = 0; /* List of columns to extract. */
117621  SrcList *pTabList; /* List of tables to select from */
117622  Expr *pWhere; /* The WHERE clause. May be NULL */
117623  ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
117624  Expr *pHaving; /* The HAVING clause. May be NULL */
117625  int rc = 1; /* Value to return from this function */
117626  DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
117627  SortCtx sSort; /* Info on how to code the ORDER BY clause */
117628  AggInfo sAggInfo; /* Information used by aggregate queries */
117629  int iEnd; /* Address of the end of the query */
117630  sqlite3 *db; /* The database connection */
117631 
117632 #ifndef SQLITE_OMIT_EXPLAIN
117633  int iRestoreSelectId = pParse->iSelectId;
117634  pParse->iSelectId = pParse->iNextSelectId++;
117635 #endif
117636 
117637  db = pParse->db;
117638  if( p==0 || db->mallocFailed || pParse->nErr ){
117639  return 1;
117640  }
117641  if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
117642  memset(&sAggInfo, 0, sizeof(sAggInfo));
117643 #if SELECTTRACE_ENABLED
117644  pParse->nSelectIndent++;
117645  SELECTTRACE(1,pParse,p, ("begin processing:\n"));
117646  if( sqlite3SelectTrace & 0x100 ){
117647  sqlite3TreeViewSelect(0, p, 0);
117648  }
117649 #endif
117650 
117651  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
117652  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
117653  assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
117654  assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
117655  if( IgnorableOrderby(pDest) ){
117656  assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
117657  pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
117658  pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
117659  pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
117660  /* If ORDER BY makes no difference in the output then neither does
117661  ** DISTINCT so it can be removed too. */
117663  p->pOrderBy = 0;
117664  p->selFlags &= ~SF_Distinct;
117665  }
117666  sqlite3SelectPrep(pParse, p, 0);
117667  memset(&sSort, 0, sizeof(sSort));
117668  sSort.pOrderBy = p->pOrderBy;
117669  pTabList = p->pSrc;
117670  if( pParse->nErr || db->mallocFailed ){
117671  goto select_end;
117672  }
117673  assert( p->pEList!=0 );
117674  isAgg = (p->selFlags & SF_Aggregate)!=0;
117675 #if SELECTTRACE_ENABLED
117676  if( sqlite3SelectTrace & 0x100 ){
117677  SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
117678  sqlite3TreeViewSelect(0, p, 0);
117679  }
117680 #endif
117681 
117682 
117683  /* If writing to memory or generating a set
117684  ** only a single column may be output.
117685  */
117686 #ifndef SQLITE_OMIT_SUBQUERY
117687  if( checkForMultiColumnSelectError(pParse, pDest, p->pEList->nExpr) ){
117688  goto select_end;
117689  }
117690 #endif
117691 
117692  /* Try to flatten subqueries in the FROM clause up into the main query
117693  */
117694 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117695  for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
117696  struct SrcList_item *pItem = &pTabList->a[i];
117697  Select *pSub = pItem->pSelect;
117698  int isAggSub;
117699  Table *pTab = pItem->pTab;
117700  if( pSub==0 ) continue;
117701 
117702  /* Catch mismatch in the declared columns of a view and the number of
117703  ** columns in the SELECT on the RHS */
117704  if( pTab->nCol!=pSub->pEList->nExpr ){
117705  sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
117706  pTab->nCol, pTab->zName, pSub->pEList->nExpr);
117707  goto select_end;
117708  }
117709 
117710  isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
117711  if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
117712  /* This subquery can be absorbed into its parent. */
117713  if( isAggSub ){
117714  isAgg = 1;
117715  p->selFlags |= SF_Aggregate;
117716  }
117717  i = -1;
117718  }
117719  pTabList = p->pSrc;
117720  if( db->mallocFailed ) goto select_end;
117721  if( !IgnorableOrderby(pDest) ){
117722  sSort.pOrderBy = p->pOrderBy;
117723  }
117724  }
117725 #endif
117726 
117727  /* Get a pointer the VDBE under construction, allocating a new VDBE if one
117728  ** does not already exist */
117729  v = sqlite3GetVdbe(pParse);
117730  if( v==0 ) goto select_end;
117731 
117732 #ifndef SQLITE_OMIT_COMPOUND_SELECT
117733  /* Handle compound SELECT statements using the separate multiSelect()
117734  ** procedure.
117735  */
117736  if( p->pPrior ){
117737  rc = multiSelect(pParse, p, pDest);
117738  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
117739 #if SELECTTRACE_ENABLED
117740  SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
117741  pParse->nSelectIndent--;
117742 #endif
117743  return rc;
117744  }
117745 #endif
117746 
117747  /* Generate code for all sub-queries in the FROM clause
117748  */
117749 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
117750  for(i=0; i<pTabList->nSrc; i++){
117751  struct SrcList_item *pItem = &pTabList->a[i];
117752  SelectDest dest;
117753  Select *pSub = pItem->pSelect;
117754  if( pSub==0 ) continue;
117755 
117756  /* Sometimes the code for a subquery will be generated more than
117757  ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
117758  ** for example. In that case, do not regenerate the code to manifest
117759  ** a view or the co-routine to implement a view. The first instance
117760  ** is sufficient, though the subroutine to manifest the view does need
117761  ** to be invoked again. */
117762  if( pItem->addrFillSub ){
117763  if( pItem->fg.viaCoroutine==0 ){
117764  sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
117765  }
117766  continue;
117767  }
117768 
117769  /* Increment Parse.nHeight by the height of the largest expression
117770  ** tree referred to by this, the parent select. The child select
117771  ** may contain expression trees of at most
117772  ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
117773  ** more conservative than necessary, but much easier than enforcing
117774  ** an exact limit.
117775  */
117776  pParse->nHeight += sqlite3SelectExprHeight(p);
117777 
117778  /* Make copies of constant WHERE-clause terms in the outer query down
117779  ** inside the subquery. This can help the subquery to run more efficiently.
117780  */
117781  if( (pItem->fg.jointype & JT_OUTER)==0
117782  && pushDownWhereTerms(db, pSub, p->pWhere, pItem->iCursor)
117783  ){
117784 #if SELECTTRACE_ENABLED
117785  if( sqlite3SelectTrace & 0x100 ){
117786  SELECTTRACE(0x100,pParse,p,("After WHERE-clause push-down:\n"));
117787  sqlite3TreeViewSelect(0, p, 0);
117788  }
117789 #endif
117790  }
117791 
117792  /* Generate code to implement the subquery
117793  **
117794  ** The subquery is implemented as a co-routine if all of these are true:
117795  ** (1) The subquery is guaranteed to be the outer loop (so that it
117796  ** does not need to be computed more than once)
117797  ** (2) The ALL keyword after SELECT is omitted. (Applications are
117798  ** allowed to say "SELECT ALL" instead of just "SELECT" to disable
117799  ** the use of co-routines.)
117800  ** (3) Co-routines are not disabled using sqlite3_test_control()
117801  ** with SQLITE_TESTCTRL_OPTIMIZATIONS.
117802  **
117803  ** TODO: Are there other reasons beside (1) to use a co-routine
117804  ** implementation?
117805  */
117806  if( i==0
117807  && (pTabList->nSrc==1
117808  || (pTabList->a[1].fg.jointype&(JT_LEFT|JT_CROSS))!=0) /* (1) */
117809  && (p->selFlags & SF_All)==0 /* (2) */
117810  && OptimizationEnabled(db, SQLITE_SubqCoroutine) /* (3) */
117811  ){
117812  /* Implement a co-routine that will return a single row of the result
117813  ** set on each invocation.
117814  */
117815  int addrTop = sqlite3VdbeCurrentAddr(v)+1;
117816  pItem->regReturn = ++pParse->nMem;
117817  sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
117818  VdbeComment((v, "%s", pItem->pTab->zName));
117819  pItem->addrFillSub = addrTop;
117820  sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
117821  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
117822  sqlite3Select(pParse, pSub, &dest);
117823  pItem->pTab->nRowLogEst = pSub->nSelectRow;
117824  pItem->fg.viaCoroutine = 1;
117825  pItem->regResult = dest.iSdst;
117826  sqlite3VdbeEndCoroutine(v, pItem->regReturn);
117827  sqlite3VdbeJumpHere(v, addrTop-1);
117828  sqlite3ClearTempRegCache(pParse);
117829  }else{
117830  /* Generate a subroutine that will fill an ephemeral table with
117831  ** the content of this subquery. pItem->addrFillSub will point
117832  ** to the address of the generated subroutine. pItem->regReturn
117833  ** is a register allocated to hold the subroutine return address
117834  */
117835  int topAddr;
117836  int onceAddr = 0;
117837  int retAddr;
117838  assert( pItem->addrFillSub==0 );
117839  pItem->regReturn = ++pParse->nMem;
117840  topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
117841  pItem->addrFillSub = topAddr+1;
117842  if( pItem->fg.isCorrelated==0 ){
117843  /* If the subquery is not correlated and if we are not inside of
117844  ** a trigger, then we only need to compute the value of the subquery
117845  ** once. */
117846  onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
117847  VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
117848  }else{
117849  VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
117850  }
117851  sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
117852  explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
117853  sqlite3Select(pParse, pSub, &dest);
117854  pItem->pTab->nRowLogEst = pSub->nSelectRow;
117855  if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
117856  retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
117857  VdbeComment((v, "end %s", pItem->pTab->zName));
117858  sqlite3VdbeChangeP1(v, topAddr, retAddr);
117859  sqlite3ClearTempRegCache(pParse);
117860  }
117861  if( db->mallocFailed ) goto select_end;
117862  pParse->nHeight -= sqlite3SelectExprHeight(p);
117863  }
117864 #endif
117865 
117866  /* Various elements of the SELECT copied into local variables for
117867  ** convenience */
117868  pEList = p->pEList;
117869  pWhere = p->pWhere;
117870  pGroupBy = p->pGroupBy;
117871  pHaving = p->pHaving;
117872  sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
117873 
117874 #if SELECTTRACE_ENABLED
117875  if( sqlite3SelectTrace & 0x400 ){
117876  SELECTTRACE(0x400,pParse,p,("After all FROM-clause analysis:\n"));
117877  sqlite3TreeViewSelect(0, p, 0);
117878  }
117879 #endif
117880 
117881  /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
117882  ** if the select-list is the same as the ORDER BY list, then this query
117883  ** can be rewritten as a GROUP BY. In other words, this:
117884  **
117885  ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
117886  **
117887  ** is transformed to:
117888  **
117889  ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
117890  **
117891  ** The second form is preferred as a single index (or temp-table) may be
117892  ** used for both the ORDER BY and DISTINCT processing. As originally
117893  ** written the query must use a temp-table for at least one of the ORDER
117894  ** BY and DISTINCT, and an index or separate temp-table for the other.
117895  */
117897  && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
117898  ){
117899  p->selFlags &= ~SF_Distinct;
117900  pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
117901  /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
117902  ** the sDistinct.isTnct is still set. Hence, isTnct represents the
117903  ** original setting of the SF_Distinct flag, not the current setting */
117904  assert( sDistinct.isTnct );
117905 
117906 #if SELECTTRACE_ENABLED
117907  if( sqlite3SelectTrace & 0x400 ){
117908  SELECTTRACE(0x400,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
117909  sqlite3TreeViewSelect(0, p, 0);
117910  }
117911 #endif
117912  }
117913 
117914  /* If there is an ORDER BY clause, then create an ephemeral index to
117915  ** do the sorting. But this sorting ephemeral index might end up
117916  ** being unused if the data can be extracted in pre-sorted order.
117917  ** If that is the case, then the OP_OpenEphemeral instruction will be
117918  ** changed to an OP_Noop once we figure out that the sorting index is
117919  ** not needed. The sSort.addrSortIndex variable is used to facilitate
117920  ** that change.
117921  */
117922  if( sSort.pOrderBy ){
117923  KeyInfo *pKeyInfo;
117924  pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
117925  sSort.iECursor = pParse->nTab++;
117926  sSort.addrSortIndex =
117928  sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
117929  (char*)pKeyInfo, P4_KEYINFO
117930  );
117931  }else{
117932  sSort.addrSortIndex = -1;
117933  }
117934 
117935  /* If the output is destined for a temporary table, open that table.
117936  */
117937  if( pDest->eDest==SRT_EphemTab ){
117938  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
117939  }
117940 
117941  /* Set the limiter.
117942  */
117943  iEnd = sqlite3VdbeMakeLabel(v);
117944  p->nSelectRow = 320; /* 4 billion rows */
117945  computeLimitRegisters(pParse, p, iEnd);
117946  if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
117948  sSort.sortFlags |= SORTFLAG_UseSorter;
117949  }
117950 
117951  /* Open an ephemeral index to use for the distinct set.
117952  */
117953  if( p->selFlags & SF_Distinct ){
117954  sDistinct.tabTnct = pParse->nTab++;
117956  sDistinct.tabTnct, 0, 0,
117957  (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
117958  P4_KEYINFO);
117960  sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
117961  }else{
117962  sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
117963  }
117964 
117965  if( !isAgg && pGroupBy==0 ){
117966  /* No aggregate functions and no GROUP BY clause */
117967  u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
117969  wctrlFlags |= p->selFlags & SF_FixedLimit;
117970 
117971  /* Begin the database scan. */
117972  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
117973  p->pEList, wctrlFlags, p->nSelectRow);
117974  if( pWInfo==0 ) goto select_end;
117975  if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
117976  p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
117977  }
117978  if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
117979  sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
117980  }
117981  if( sSort.pOrderBy ){
117982  sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
117983  if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
117984  sSort.pOrderBy = 0;
117985  }
117986  }
117987 
117988  /* If sorting index that was created by a prior OP_OpenEphemeral
117989  ** instruction ended up not being needed, then change the OP_OpenEphemeral
117990  ** into an OP_Noop.
117991  */
117992  if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
117994  }
117995 
117996  /* Use the standard inner loop. */
117997  selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
117998  sqlite3WhereContinueLabel(pWInfo),
117999  sqlite3WhereBreakLabel(pWInfo));
118000 
118001  /* End the database scan loop.
118002  */
118003  sqlite3WhereEnd(pWInfo);
118004  }else{
118005  /* This case when there exist aggregate functions or a GROUP BY clause
118006  ** or both */
118007  NameContext sNC; /* Name context for processing aggregate information */
118008  int iAMem; /* First Mem address for storing current GROUP BY */
118009  int iBMem; /* First Mem address for previous GROUP BY */
118010  int iUseFlag; /* Mem address holding flag indicating that at least
118011  ** one row of the input to the aggregator has been
118012  ** processed */
118013  int iAbortFlag; /* Mem address which causes query abort if positive */
118014  int groupBySort; /* Rows come from source in GROUP BY order */
118015  int addrEnd; /* End of processing for this SELECT */
118016  int sortPTab = 0; /* Pseudotable used to decode sorting results */
118017  int sortOut = 0; /* Output register from the sorter */
118018  int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
118019 
118020  /* Remove any and all aliases between the result set and the
118021  ** GROUP BY clause.
118022  */
118023  if( pGroupBy ){
118024  int k; /* Loop counter */
118025  struct ExprList_item *pItem; /* For looping over expression in a list */
118026 
118027  for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
118028  pItem->u.x.iAlias = 0;
118029  }
118030  for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
118031  pItem->u.x.iAlias = 0;
118032  }
118033  assert( 66==sqlite3LogEst(100) );
118034  if( p->nSelectRow>66 ) p->nSelectRow = 66;
118035  }else{
118036  assert( 0==sqlite3LogEst(1) );
118037  p->nSelectRow = 0;
118038  }
118039 
118040  /* If there is both a GROUP BY and an ORDER BY clause and they are
118041  ** identical, then it may be possible to disable the ORDER BY clause
118042  ** on the grounds that the GROUP BY will cause elements to come out
118043  ** in the correct order. It also may not - the GROUP BY might use a
118044  ** database index that causes rows to be grouped together as required
118045  ** but not actually sorted. Either way, record the fact that the
118046  ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
118047  ** variable. */
118048  if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
118049  orderByGrp = 1;
118050  }
118051 
118052  /* Create a label to jump to when we want to abort the query */
118053  addrEnd = sqlite3VdbeMakeLabel(v);
118054 
118055  /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
118056  ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
118057  ** SELECT statement.
118058  */
118059  memset(&sNC, 0, sizeof(sNC));
118060  sNC.pParse = pParse;
118061  sNC.pSrcList = pTabList;
118062  sNC.pAggInfo = &sAggInfo;
118063  sAggInfo.mnReg = pParse->nMem+1;
118064  sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
118065  sAggInfo.pGroupBy = pGroupBy;
118066  sqlite3ExprAnalyzeAggList(&sNC, pEList);
118067  sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
118068  if( pHaving ){
118069  sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
118070  }
118071  sAggInfo.nAccumulator = sAggInfo.nColumn;
118072  for(i=0; i<sAggInfo.nFunc; i++){
118073  assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
118074  sNC.ncFlags |= NC_InAggFunc;
118075  sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
118076  sNC.ncFlags &= ~NC_InAggFunc;
118077  }
118078  sAggInfo.mxReg = pParse->nMem;
118079  if( db->mallocFailed ) goto select_end;
118080 
118081  /* Processing for aggregates with GROUP BY is very different and
118082  ** much more complex than aggregates without a GROUP BY.
118083  */
118084  if( pGroupBy ){
118085  KeyInfo *pKeyInfo; /* Keying information for the group by clause */
118086  int addr1; /* A-vs-B comparision jump */
118087  int addrOutputRow; /* Start of subroutine that outputs a result row */
118088  int regOutputRow; /* Return address register for output subroutine */
118089  int addrSetAbort; /* Set the abort flag and return */
118090  int addrTopOfLoop; /* Top of the input loop */
118091  int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
118092  int addrReset; /* Subroutine for resetting the accumulator */
118093  int regReset; /* Return address register for reset subroutine */
118094 
118095  /* If there is a GROUP BY clause we might need a sorting index to
118096  ** implement it. Allocate that sorting index now. If it turns out
118097  ** that we do not need it after all, the OP_SorterOpen instruction
118098  ** will be converted into a Noop.
118099  */
118100  sAggInfo.sortingIdx = pParse->nTab++;
118101  pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
118102  addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
118103  sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
118104  0, (char*)pKeyInfo, P4_KEYINFO);
118105 
118106  /* Initialize memory locations used by GROUP BY aggregate processing
118107  */
118108  iUseFlag = ++pParse->nMem;
118109  iAbortFlag = ++pParse->nMem;
118110  regOutputRow = ++pParse->nMem;
118111  addrOutputRow = sqlite3VdbeMakeLabel(v);
118112  regReset = ++pParse->nMem;
118113  addrReset = sqlite3VdbeMakeLabel(v);
118114  iAMem = pParse->nMem + 1;
118115  pParse->nMem += pGroupBy->nExpr;
118116  iBMem = pParse->nMem + 1;
118117  pParse->nMem += pGroupBy->nExpr;
118118  sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
118119  VdbeComment((v, "clear abort flag"));
118120  sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
118121  VdbeComment((v, "indicate accumulator empty"));
118122  sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
118123 
118124  /* Begin a loop that will extract all source rows in GROUP BY order.
118125  ** This might involve two separate loops with an OP_Sort in between, or
118126  ** it might be a single loop that uses an index to extract information
118127  ** in the right order to begin with.
118128  */
118129  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118130  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
118131  WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
118132  );
118133  if( pWInfo==0 ) goto select_end;
118134  if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
118135  /* The optimizer is able to deliver rows in group by order so
118136  ** we do not have to sort. The OP_OpenEphemeral table will be
118137  ** cancelled later because we still need to use the pKeyInfo
118138  */
118139  groupBySort = 0;
118140  }else{
118141  /* Rows are coming out in undetermined order. We have to push
118142  ** each row into a sorting index, terminate the first loop,
118143  ** then loop over the sorting index in order to get the output
118144  ** in sorted order
118145  */
118146  int regBase;
118147  int regRecord;
118148  int nCol;
118149  int nGroupBy;
118150 
118151  explainTempTable(pParse,
118152  (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
118153  "DISTINCT" : "GROUP BY");
118154 
118155  groupBySort = 1;
118156  nGroupBy = pGroupBy->nExpr;
118157  nCol = nGroupBy;
118158  j = nGroupBy;
118159  for(i=0; i<sAggInfo.nColumn; i++){
118160  if( sAggInfo.aCol[i].iSorterColumn>=j ){
118161  nCol++;
118162  j++;
118163  }
118164  }
118165  regBase = sqlite3GetTempRange(pParse, nCol);
118166  sqlite3ExprCacheClear(pParse);
118167  sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
118168  j = nGroupBy;
118169  for(i=0; i<sAggInfo.nColumn; i++){
118170  struct AggInfo_col *pCol = &sAggInfo.aCol[i];
118171  if( pCol->iSorterColumn>=j ){
118172  int r1 = j + regBase;
118174  pCol->pTab, pCol->iColumn, pCol->iTable, r1);
118175  j++;
118176  }
118177  }
118178  regRecord = sqlite3GetTempReg(pParse);
118179  sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
118180  sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
118181  sqlite3ReleaseTempReg(pParse, regRecord);
118182  sqlite3ReleaseTempRange(pParse, regBase, nCol);
118183  sqlite3WhereEnd(pWInfo);
118184  sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
118185  sortOut = sqlite3GetTempReg(pParse);
118186  sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
118187  sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
118188  VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
118189  sAggInfo.useSortingIdx = 1;
118190  sqlite3ExprCacheClear(pParse);
118191 
118192  }
118193 
118194  /* If the index or temporary table used by the GROUP BY sort
118195  ** will naturally deliver rows in the order required by the ORDER BY
118196  ** clause, cancel the ephemeral table open coded earlier.
118197  **
118198  ** This is an optimization - the correct answer should result regardless.
118199  ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
118200  ** disable this optimization for testing purposes. */
118201  if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
118202  && (groupBySort || sqlite3WhereIsSorted(pWInfo))
118203  ){
118204  sSort.pOrderBy = 0;
118206  }
118207 
118208  /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
118209  ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
118210  ** Then compare the current GROUP BY terms against the GROUP BY terms
118211  ** from the previous row currently stored in a0, a1, a2...
118212  */
118213  addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
118214  sqlite3ExprCacheClear(pParse);
118215  if( groupBySort ){
118217  sortOut, sortPTab);
118218  }
118219  for(j=0; j<pGroupBy->nExpr; j++){
118220  if( groupBySort ){
118221  sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
118222  }else{
118223  sAggInfo.directMode = 1;
118224  sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
118225  }
118226  }
118227  sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
118228  (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
118229  addr1 = sqlite3VdbeCurrentAddr(v);
118230  sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
118231 
118232  /* Generate code that runs whenever the GROUP BY changes.
118233  ** Changes in the GROUP BY are detected by the previous code
118234  ** block. If there were no changes, this block is skipped.
118235  **
118236  ** This code copies current group by terms in b0,b1,b2,...
118237  ** over to a0,a1,a2. It then calls the output subroutine
118238  ** and resets the aggregate accumulator registers in preparation
118239  ** for the next GROUP BY batch.
118240  */
118241  sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
118242  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118243  VdbeComment((v, "output one row"));
118244  sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
118245  VdbeComment((v, "check abort flag"));
118246  sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
118247  VdbeComment((v, "reset accumulator"));
118248 
118249  /* Update the aggregate accumulators based on the content of
118250  ** the current row
118251  */
118252  sqlite3VdbeJumpHere(v, addr1);
118253  updateAccumulator(pParse, &sAggInfo);
118254  sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
118255  VdbeComment((v, "indicate data in accumulator"));
118256 
118257  /* End of the loop
118258  */
118259  if( groupBySort ){
118260  sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
118261  VdbeCoverage(v);
118262  }else{
118263  sqlite3WhereEnd(pWInfo);
118264  sqlite3VdbeChangeToNoop(v, addrSortingIdx);
118265  }
118266 
118267  /* Output the final row of result
118268  */
118269  sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
118270  VdbeComment((v, "output final row"));
118271 
118272  /* Jump over the subroutines
118273  */
118274  sqlite3VdbeGoto(v, addrEnd);
118275 
118276  /* Generate a subroutine that outputs a single row of the result
118277  ** set. This subroutine first looks at the iUseFlag. If iUseFlag
118278  ** is less than or equal to zero, the subroutine is a no-op. If
118279  ** the processing calls for the query to abort, this subroutine
118280  ** increments the iAbortFlag memory location before returning in
118281  ** order to signal the caller to abort.
118282  */
118283  addrSetAbort = sqlite3VdbeCurrentAddr(v);
118284  sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
118285  VdbeComment((v, "set abort flag"));
118286  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118287  sqlite3VdbeResolveLabel(v, addrOutputRow);
118288  addrOutputRow = sqlite3VdbeCurrentAddr(v);
118289  sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
118290  VdbeCoverage(v);
118291  VdbeComment((v, "Groupby result generator entry point"));
118292  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118293  finalizeAggFunctions(pParse, &sAggInfo);
118294  sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
118295  selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
118296  &sDistinct, pDest,
118297  addrOutputRow+1, addrSetAbort);
118298  sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
118299  VdbeComment((v, "end groupby result generator"));
118300 
118301  /* Generate a subroutine that will reset the group-by accumulator
118302  */
118303  sqlite3VdbeResolveLabel(v, addrReset);
118304  resetAccumulator(pParse, &sAggInfo);
118305  sqlite3VdbeAddOp1(v, OP_Return, regReset);
118306 
118307  } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
118308  else {
118309  ExprList *pDel = 0;
118310 #ifndef SQLITE_OMIT_BTREECOUNT
118311  Table *pTab;
118312  if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
118313  /* If isSimpleCount() returns a pointer to a Table structure, then
118314  ** the SQL statement is of the form:
118315  **
118316  ** SELECT count(*) FROM <tbl>
118317  **
118318  ** where the Table structure returned represents table <tbl>.
118319  **
118320  ** This statement is so common that it is optimized specially. The
118321  ** OP_Count instruction is executed either on the intkey table that
118322  ** contains the data for table <tbl> or on one of its indexes. It
118323  ** is better to execute the op on an index, as indexes are almost
118324  ** always spread across less pages than their corresponding tables.
118325  */
118326  const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
118327  const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
118328  Index *pIdx; /* Iterator variable */
118329  KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
118330  Index *pBest = 0; /* Best index found so far */
118331  int iRoot = pTab->tnum; /* Root page of scanned b-tree */
118332 
118333  sqlite3CodeVerifySchema(pParse, iDb);
118334  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
118335 
118336  /* Search for the index that has the lowest scan cost.
118337  **
118338  ** (2011-04-15) Do not do a full scan of an unordered index.
118339  **
118340  ** (2013-10-03) Do not count the entries in a partial index.
118341  **
118342  ** In practice the KeyInfo structure will not be used. It is only
118343  ** passed to keep OP_OpenRead happy.
118344  */
118345  if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
118346  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
118347  if( pIdx->bUnordered==0
118348  && pIdx->szIdxRow<pTab->szTabRow
118349  && pIdx->pPartIdxWhere==0
118350  && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
118351  ){
118352  pBest = pIdx;
118353  }
118354  }
118355  if( pBest ){
118356  iRoot = pBest->tnum;
118357  pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
118358  }
118359 
118360  /* Open a read-only cursor, execute the OP_Count, close the cursor. */
118361  sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
118362  if( pKeyInfo ){
118363  sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
118364  }
118365  sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
118366  sqlite3VdbeAddOp1(v, OP_Close, iCsr);
118367  explainSimpleCount(pParse, pTab, pBest);
118368  }else
118369 #endif /* SQLITE_OMIT_BTREECOUNT */
118370  {
118371  /* Check if the query is of one of the following forms:
118372  **
118373  ** SELECT min(x) FROM ...
118374  ** SELECT max(x) FROM ...
118375  **
118376  ** If it is, then ask the code in where.c to attempt to sort results
118377  ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
118378  ** If where.c is able to produce results sorted in this order, then
118379  ** add vdbe code to break out of the processing loop after the
118380  ** first iteration (since the first iteration of the loop is
118381  ** guaranteed to operate on the row with the minimum or maximum
118382  ** value of x, the only row required).
118383  **
118384  ** A special flag must be passed to sqlite3WhereBegin() to slightly
118385  ** modify behavior as follows:
118386  **
118387  ** + If the query is a "SELECT min(x)", then the loop coded by
118388  ** where.c should not iterate over any values with a NULL value
118389  ** for x.
118390  **
118391  ** + The optimizer code in where.c (the thing that decides which
118392  ** index or indices to use) should place a different priority on
118393  ** satisfying the 'ORDER BY' clause than it does in other cases.
118394  ** Refer to code and comments in where.c for details.
118395  */
118396  ExprList *pMinMax = 0;
118397  u8 flag = WHERE_ORDERBY_NORMAL;
118398 
118399  assert( p->pGroupBy==0 );
118400  assert( flag==0 );
118401  if( p->pHaving==0 ){
118402  flag = minMaxQuery(&sAggInfo, &pMinMax);
118403  }
118404  assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
118405 
118406  if( flag ){
118407  pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
118408  pDel = pMinMax;
118409  assert( db->mallocFailed || pMinMax!=0 );
118410  if( !db->mallocFailed ){
118411  pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
118412  pMinMax->a[0].pExpr->op = TK_COLUMN;
118413  }
118414  }
118415 
118416  /* This case runs if the aggregate has no GROUP BY clause. The
118417  ** processing is much simpler since there is only a single row
118418  ** of output.
118419  */
118420  resetAccumulator(pParse, &sAggInfo);
118421  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
118422  if( pWInfo==0 ){
118423  sqlite3ExprListDelete(db, pDel);
118424  goto select_end;
118425  }
118426  updateAccumulator(pParse, &sAggInfo);
118427  assert( pMinMax==0 || pMinMax->nExpr==1 );
118428  if( sqlite3WhereIsOrdered(pWInfo)>0 ){
118430  VdbeComment((v, "%s() by index",
118431  (flag==WHERE_ORDERBY_MIN?"min":"max")));
118432  }
118433  sqlite3WhereEnd(pWInfo);
118434  finalizeAggFunctions(pParse, &sAggInfo);
118435  }
118436 
118437  sSort.pOrderBy = 0;
118438  sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
118439  selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
118440  pDest, addrEnd, addrEnd);
118441  sqlite3ExprListDelete(db, pDel);
118442  }
118443  sqlite3VdbeResolveLabel(v, addrEnd);
118444 
118445  } /* endif aggregate query */
118446 
118447  if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
118448  explainTempTable(pParse, "DISTINCT");
118449  }
118450 
118451  /* If there is an ORDER BY clause, then we need to sort the results
118452  ** and send them to the callback one by one.
118453  */
118454  if( sSort.pOrderBy ){
118455  explainTempTable(pParse,
118456  sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
118457  generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
118458  }
118459 
118460  /* Jump here to skip this query
118461  */
118462  sqlite3VdbeResolveLabel(v, iEnd);
118463 
118464  /* The SELECT has been coded. If there is an error in the Parse structure,
118465  ** set the return code to 1. Otherwise 0. */
118466  rc = (pParse->nErr>0);
118467 
118468  /* Control jumps to here if an error is encountered above, or upon
118469  ** successful coding of the SELECT.
118470  */
118471 select_end:
118472  explainSetInteger(pParse->iSelectId, iRestoreSelectId);
118473 
118474  /* Identify column names if results of the SELECT are to be output.
118475  */
118476  if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
118477  generateColumnNames(pParse, pTabList, pEList);
118478  }
118479 
118480  sqlite3DbFree(db, sAggInfo.aCol);
118481  sqlite3DbFree(db, sAggInfo.aFunc);
118482 #if SELECTTRACE_ENABLED
118483  SELECTTRACE(1,pParse,p,("end processing\n"));
118484  pParse->nSelectIndent--;
118485 #endif
118486  return rc;
118487 }
118488 
118489 /************** End of select.c **********************************************/
118490 /************** Begin file table.c *******************************************/
118491 /*
118492 ** 2001 September 15
118493 **
118494 ** The author disclaims copyright to this source code. In place of
118495 ** a legal notice, here is a blessing:
118496 **
118497 ** May you do good and not evil.
118498 ** May you find forgiveness for yourself and forgive others.
118499 ** May you share freely, never taking more than you give.
118500 **
118501 *************************************************************************
118502 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
118503 ** interface routines. These are just wrappers around the main
118504 ** interface routine of sqlite3_exec().
118505 **
118506 ** These routines are in a separate files so that they will not be linked
118507 ** if they are not used.
118508 */
118509 /* #include "sqliteInt.h" */
118510 /* #include <stdlib.h> */
118511 /* #include <string.h> */
118512 
118513 #ifndef SQLITE_OMIT_GET_TABLE
118514 
118515 /*
118516 ** This structure is used to pass data from sqlite3_get_table() through
118517 ** to the callback function is uses to build the result.
118518 */
118519 typedef struct TabResult {
118520  char **azResult; /* Accumulated output */
118521  char *zErrMsg; /* Error message text, if an error occurs */
118522  u32 nAlloc; /* Slots allocated for azResult[] */
118523  u32 nRow; /* Number of rows in the result */
118524  u32 nColumn; /* Number of columns in the result */
118525  u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
118526  int rc; /* Return code from sqlite3_exec() */
118527 } TabResult;
118528 
118529 /*
118530 ** This routine is called once for each row in the result table. Its job
118531 ** is to fill in the TabResult structure appropriately, allocating new
118532 ** memory as necessary.
118533 */
118534 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
118535  TabResult *p = (TabResult*)pArg; /* Result accumulator */
118536  int need; /* Slots needed in p->azResult[] */
118537  int i; /* Loop counter */
118538  char *z; /* A single column of result */
118539 
118540  /* Make sure there is enough space in p->azResult to hold everything
118541  ** we need to remember from this invocation of the callback.
118542  */
118543  if( p->nRow==0 && argv!=0 ){
118544  need = nCol*2;
118545  }else{
118546  need = nCol;
118547  }
118548  if( p->nData + need > p->nAlloc ){
118549  char **azNew;
118550  p->nAlloc = p->nAlloc*2 + need;
118551  azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
118552  if( azNew==0 ) goto malloc_failed;
118553  p->azResult = azNew;
118554  }
118555 
118556  /* If this is the first row, then generate an extra row containing
118557  ** the names of all columns.
118558  */
118559  if( p->nRow==0 ){
118560  p->nColumn = nCol;
118561  for(i=0; i<nCol; i++){
118562  z = sqlite3_mprintf("%s", colv[i]);
118563  if( z==0 ) goto malloc_failed;
118564  p->azResult[p->nData++] = z;
118565  }
118566  }else if( (int)p->nColumn!=nCol ){
118567  sqlite3_free(p->zErrMsg);
118568  p->zErrMsg = sqlite3_mprintf(
118569  "sqlite3_get_table() called with two or more incompatible queries"
118570  );
118571  p->rc = SQLITE_ERROR;
118572  return 1;
118573  }
118574 
118575  /* Copy over the row data
118576  */
118577  if( argv!=0 ){
118578  for(i=0; i<nCol; i++){
118579  if( argv[i]==0 ){
118580  z = 0;
118581  }else{
118582  int n = sqlite3Strlen30(argv[i])+1;
118583  z = sqlite3_malloc64( n );
118584  if( z==0 ) goto malloc_failed;
118585  memcpy(z, argv[i], n);
118586  }
118587  p->azResult[p->nData++] = z;
118588  }
118589  p->nRow++;
118590  }
118591  return 0;
118592 
118593 malloc_failed:
118594  p->rc = SQLITE_NOMEM_BKPT;
118595  return 1;
118596 }
118597 
118598 /*
118599 ** Query the database. But instead of invoking a callback for each row,
118600 ** malloc() for space to hold the result and return the entire results
118601 ** at the conclusion of the call.
118602 **
118603 ** The result that is written to ***pazResult is held in memory obtained
118604 ** from malloc(). But the caller cannot free this memory directly.
118605 ** Instead, the entire table should be passed to sqlite3_free_table() when
118606 ** the calling procedure is finished using it.
118607 */
118609  sqlite3 *db, /* The database on which the SQL executes */
118610  const char *zSql, /* The SQL to be executed */
118611  char ***pazResult, /* Write the result table here */
118612  int *pnRow, /* Write the number of rows in the result here */
118613  int *pnColumn, /* Write the number of columns of result here */
118614  char **pzErrMsg /* Write error messages here */
118615 ){
118616  int rc;
118617  TabResult res;
118618 
118619 #ifdef SQLITE_ENABLE_API_ARMOR
118620  if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
118621 #endif
118622  *pazResult = 0;
118623  if( pnColumn ) *pnColumn = 0;
118624  if( pnRow ) *pnRow = 0;
118625  if( pzErrMsg ) *pzErrMsg = 0;
118626  res.zErrMsg = 0;
118627  res.nRow = 0;
118628  res.nColumn = 0;
118629  res.nData = 1;
118630  res.nAlloc = 20;
118631  res.rc = SQLITE_OK;
118632  res.azResult = sqlite3_malloc64(sizeof(char*)*res.nAlloc );
118633  if( res.azResult==0 ){
118634  db->errCode = SQLITE_NOMEM;
118635  return SQLITE_NOMEM_BKPT;
118636  }
118637  res.azResult[0] = 0;
118638  rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
118639  assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
118640  res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
118641  if( (rc&0xff)==SQLITE_ABORT ){
118642  sqlite3_free_table(&res.azResult[1]);
118643  if( res.zErrMsg ){
118644  if( pzErrMsg ){
118645  sqlite3_free(*pzErrMsg);
118646  *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
118647  }
118648  sqlite3_free(res.zErrMsg);
118649  }
118650  db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
118651  return res.rc;
118652  }
118653  sqlite3_free(res.zErrMsg);
118654  if( rc!=SQLITE_OK ){
118655  sqlite3_free_table(&res.azResult[1]);
118656  return rc;
118657  }
118658  if( res.nAlloc>res.nData ){
118659  char **azNew;
118660  azNew = sqlite3_realloc64( res.azResult, sizeof(char*)*res.nData );
118661  if( azNew==0 ){
118662  sqlite3_free_table(&res.azResult[1]);
118663  db->errCode = SQLITE_NOMEM;
118664  return SQLITE_NOMEM_BKPT;
118665  }
118666  res.azResult = azNew;
118667  }
118668  *pazResult = &res.azResult[1];
118669  if( pnColumn ) *pnColumn = res.nColumn;
118670  if( pnRow ) *pnRow = res.nRow;
118671  return rc;
118672 }
118673 
118674 /*
118675 ** This routine frees the space the sqlite3_get_table() malloced.
118676 */
118678  char **azResult /* Result returned from sqlite3_get_table() */
118679 ){
118680  if( azResult ){
118681  int i, n;
118682  azResult--;
118683  assert( azResult!=0 );
118684  n = SQLITE_PTR_TO_INT(azResult[0]);
118685  for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
118686  sqlite3_free(azResult);
118687  }
118688 }
118689 
118690 #endif /* SQLITE_OMIT_GET_TABLE */
118691 
118692 /************** End of table.c ***********************************************/
118693 /************** Begin file trigger.c *****************************************/
118694 /*
118695 **
118696 ** The author disclaims copyright to this source code. In place of
118697 ** a legal notice, here is a blessing:
118698 **
118699 ** May you do good and not evil.
118700 ** May you find forgiveness for yourself and forgive others.
118701 ** May you share freely, never taking more than you give.
118702 **
118703 *************************************************************************
118704 ** This file contains the implementation for TRIGGERs
118705 */
118706 /* #include "sqliteInt.h" */
118707 
118708 #ifndef SQLITE_OMIT_TRIGGER
118709 /*
118710 ** Delete a linked list of TriggerStep structures.
118711 */
118712 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
118713  while( pTriggerStep ){
118714  TriggerStep * pTmp = pTriggerStep;
118715  pTriggerStep = pTriggerStep->pNext;
118716 
118717  sqlite3ExprDelete(db, pTmp->pWhere);
118718  sqlite3ExprListDelete(db, pTmp->pExprList);
118719  sqlite3SelectDelete(db, pTmp->pSelect);
118720  sqlite3IdListDelete(db, pTmp->pIdList);
118721 
118722  sqlite3DbFree(db, pTmp);
118723  }
118724 }
118725 
118726 /*
118727 ** Given table pTab, return a list of all the triggers attached to
118728 ** the table. The list is connected by Trigger.pNext pointers.
118729 **
118730 ** All of the triggers on pTab that are in the same database as pTab
118731 ** are already attached to pTab->pTrigger. But there might be additional
118732 ** triggers on pTab in the TEMP schema. This routine prepends all
118733 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
118734 ** and returns the combined list.
118735 **
118736 ** To state it another way: This routine returns a list of all triggers
118737 ** that fire off of pTab. The list will include any TEMP triggers on
118738 ** pTab as well as the triggers lised in pTab->pTrigger.
118739 */
118741  Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
118742  Trigger *pList = 0; /* List of triggers to return */
118743 
118744  if( pParse->disableTriggers ){
118745  return 0;
118746  }
118747 
118748  if( pTmpSchema!=pTab->pSchema ){
118749  HashElem *p;
118750  assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
118751  for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
118752  Trigger *pTrig = (Trigger *)sqliteHashData(p);
118753  if( pTrig->pTabSchema==pTab->pSchema
118754  && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
118755  ){
118756  pTrig->pNext = (pList ? pList : pTab->pTrigger);
118757  pList = pTrig;
118758  }
118759  }
118760  }
118761 
118762  return (pList ? pList : pTab->pTrigger);
118763 }
118764 
118765 /*
118766 ** This is called by the parser when it sees a CREATE TRIGGER statement
118767 ** up to the point of the BEGIN before the trigger actions. A Trigger
118768 ** structure is generated based on the information available and stored
118769 ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
118770 ** sqlite3FinishTrigger() function is called to complete the trigger
118771 ** construction process.
118772 */
118774  Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
118775  Token *pName1, /* The name of the trigger */
118776  Token *pName2, /* The name of the trigger */
118777  int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
118778  int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
118779  IdList *pColumns, /* column list if this is an UPDATE OF trigger */
118780  SrcList *pTableName,/* The name of the table/view the trigger applies to */
118781  Expr *pWhen, /* WHEN clause */
118782  int isTemp, /* True if the TEMPORARY keyword is present */
118783  int noErr /* Suppress errors if the trigger already exists */
118784 ){
118785  Trigger *pTrigger = 0; /* The new trigger */
118786  Table *pTab; /* Table that the trigger fires off of */
118787  char *zName = 0; /* Name of the trigger */
118788  sqlite3 *db = pParse->db; /* The database connection */
118789  int iDb; /* The database to store the trigger in */
118790  Token *pName; /* The unqualified db name */
118791  DbFixer sFix; /* State vector for the DB fixer */
118792  int iTabDb; /* Index of the database holding pTab */
118793 
118794  assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
118795  assert( pName2!=0 );
118796  assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
118797  assert( op>0 && op<0xff );
118798  if( isTemp ){
118799  /* If TEMP was specified, then the trigger name may not be qualified. */
118800  if( pName2->n>0 ){
118801  sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
118802  goto trigger_cleanup;
118803  }
118804  iDb = 1;
118805  pName = pName1;
118806  }else{
118807  /* Figure out the db that the trigger will be created in */
118808  iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
118809  if( iDb<0 ){
118810  goto trigger_cleanup;
118811  }
118812  }
118813  if( !pTableName || db->mallocFailed ){
118814  goto trigger_cleanup;
118815  }
118816 
118817  /* A long-standing parser bug is that this syntax was allowed:
118818  **
118819  ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
118820  ** ^^^^^^^^
118821  **
118822  ** To maintain backwards compatibility, ignore the database
118823  ** name on pTableName if we are reparsing out of SQLITE_MASTER.
118824  */
118825  if( db->init.busy && iDb!=1 ){
118826  sqlite3DbFree(db, pTableName->a[0].zDatabase);
118827  pTableName->a[0].zDatabase = 0;
118828  }
118829 
118830  /* If the trigger name was unqualified, and the table is a temp table,
118831  ** then set iDb to 1 to create the trigger in the temporary database.
118832  ** If sqlite3SrcListLookup() returns 0, indicating the table does not
118833  ** exist, the error is caught by the block below.
118834  */
118835  pTab = sqlite3SrcListLookup(pParse, pTableName);
118836  if( db->init.busy==0 && pName2->n==0 && pTab
118837  && pTab->pSchema==db->aDb[1].pSchema ){
118838  iDb = 1;
118839  }
118840 
118841  /* Ensure the table name matches database name and that the table exists */
118842  if( db->mallocFailed ) goto trigger_cleanup;
118843  assert( pTableName->nSrc==1 );
118844  sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
118845  if( sqlite3FixSrcList(&sFix, pTableName) ){
118846  goto trigger_cleanup;
118847  }
118848  pTab = sqlite3SrcListLookup(pParse, pTableName);
118849  if( !pTab ){
118850  /* The table does not exist. */
118851  if( db->init.iDb==1 ){
118852  /* Ticket #3810.
118853  ** Normally, whenever a table is dropped, all associated triggers are
118854  ** dropped too. But if a TEMP trigger is created on a non-TEMP table
118855  ** and the table is dropped by a different database connection, the
118856  ** trigger is not visible to the database connection that does the
118857  ** drop so the trigger cannot be dropped. This results in an
118858  ** "orphaned trigger" - a trigger whose associated table is missing.
118859  */
118860  db->init.orphanTrigger = 1;
118861  }
118862  goto trigger_cleanup;
118863  }
118864  if( IsVirtual(pTab) ){
118865  sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
118866  goto trigger_cleanup;
118867  }
118868 
118869  /* Check that the trigger name is not reserved and that no trigger of the
118870  ** specified name exists */
118871  zName = sqlite3NameFromToken(db, pName);
118872  if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
118873  goto trigger_cleanup;
118874  }
118875  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
118876  if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
118877  if( !noErr ){
118878  sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
118879  }else{
118880  assert( !db->init.busy );
118881  sqlite3CodeVerifySchema(pParse, iDb);
118882  }
118883  goto trigger_cleanup;
118884  }
118885 
118886  /* Do not create a trigger on a system table */
118887  if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
118888  sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
118889  goto trigger_cleanup;
118890  }
118891 
118892  /* INSTEAD of triggers are only for views and views only support INSTEAD
118893  ** of triggers.
118894  */
118895  if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
118896  sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
118897  (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
118898  goto trigger_cleanup;
118899  }
118900  if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
118901  sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
118902  " trigger on table: %S", pTableName, 0);
118903  goto trigger_cleanup;
118904  }
118905  iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
118906 
118907 #ifndef SQLITE_OMIT_AUTHORIZATION
118908  {
118909  int code = SQLITE_CREATE_TRIGGER;
118910  const char *zDb = db->aDb[iTabDb].zName;
118911  const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
118912  if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
118913  if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
118914  goto trigger_cleanup;
118915  }
118916  if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
118917  goto trigger_cleanup;
118918  }
118919  }
118920 #endif
118921 
118922  /* INSTEAD OF triggers can only appear on views and BEFORE triggers
118923  ** cannot appear on views. So we might as well translate every
118924  ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
118925  ** elsewhere.
118926  */
118927  if (tr_tm == TK_INSTEAD){
118928  tr_tm = TK_BEFORE;
118929  }
118930 
118931  /* Build the Trigger object */
118932  pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
118933  if( pTrigger==0 ) goto trigger_cleanup;
118934  pTrigger->zName = zName;
118935  zName = 0;
118936  pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
118937  pTrigger->pSchema = db->aDb[iDb].pSchema;
118938  pTrigger->pTabSchema = pTab->pSchema;
118939  pTrigger->op = (u8)op;
118940  pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
118941  pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
118942  pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
118943  assert( pParse->pNewTrigger==0 );
118944  pParse->pNewTrigger = pTrigger;
118945 
118946 trigger_cleanup:
118947  sqlite3DbFree(db, zName);
118948  sqlite3SrcListDelete(db, pTableName);
118949  sqlite3IdListDelete(db, pColumns);
118950  sqlite3ExprDelete(db, pWhen);
118951  if( !pParse->pNewTrigger ){
118952  sqlite3DeleteTrigger(db, pTrigger);
118953  }else{
118954  assert( pParse->pNewTrigger==pTrigger );
118955  }
118956 }
118957 
118958 /*
118959 ** This routine is called after all of the trigger actions have been parsed
118960 ** in order to complete the process of building the trigger.
118961 */
118963  Parse *pParse, /* Parser context */
118964  TriggerStep *pStepList, /* The triggered program */
118965  Token *pAll /* Token that describes the complete CREATE TRIGGER */
118966 ){
118967  Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
118968  char *zName; /* Name of trigger */
118969  sqlite3 *db = pParse->db; /* The database */
118970  DbFixer sFix; /* Fixer object */
118971  int iDb; /* Database containing the trigger */
118972  Token nameToken; /* Trigger name for error reporting */
118973 
118974  pParse->pNewTrigger = 0;
118975  if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
118976  zName = pTrig->zName;
118977  iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
118978  pTrig->step_list = pStepList;
118979  while( pStepList ){
118980  pStepList->pTrig = pTrig;
118981  pStepList = pStepList->pNext;
118982  }
118983  sqlite3TokenInit(&nameToken, pTrig->zName);
118984  sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
118985  if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
118986  || sqlite3FixExpr(&sFix, pTrig->pWhen)
118987  ){
118988  goto triggerfinish_cleanup;
118989  }
118990 
118991  /* if we are not initializing,
118992  ** build the sqlite_master entry
118993  */
118994  if( !db->init.busy ){
118995  Vdbe *v;
118996  char *z;
118997 
118998  /* Make an entry in the sqlite_master table */
118999  v = sqlite3GetVdbe(pParse);
119000  if( v==0 ) goto triggerfinish_cleanup;
119001  sqlite3BeginWriteOperation(pParse, 0, iDb);
119002  z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
119003  sqlite3NestedParse(pParse,
119004  "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
119005  db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
119006  pTrig->table, z);
119007  sqlite3DbFree(db, z);
119008  sqlite3ChangeCookie(pParse, iDb);
119010  sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
119011  }
119012 
119013  if( db->init.busy ){
119014  Trigger *pLink = pTrig;
119015  Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
119016  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119017  pTrig = sqlite3HashInsert(pHash, zName, pTrig);
119018  if( pTrig ){
119019  sqlite3OomFault(db);
119020  }else if( pLink->pSchema==pLink->pTabSchema ){
119021  Table *pTab;
119022  pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
119023  assert( pTab!=0 );
119024  pLink->pNext = pTab->pTrigger;
119025  pTab->pTrigger = pLink;
119026  }
119027  }
119028 
119029 triggerfinish_cleanup:
119030  sqlite3DeleteTrigger(db, pTrig);
119031  assert( !pParse->pNewTrigger );
119032  sqlite3DeleteTriggerStep(db, pStepList);
119033 }
119034 
119035 /*
119036 ** Turn a SELECT statement (that the pSelect parameter points to) into
119037 ** a trigger step. Return a pointer to a TriggerStep structure.
119038 **
119039 ** The parser calls this routine when it finds a SELECT statement in
119040 ** body of a TRIGGER.
119041 */
119043  TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
119044  if( pTriggerStep==0 ) {
119045  sqlite3SelectDelete(db, pSelect);
119046  return 0;
119047  }
119048  pTriggerStep->op = TK_SELECT;
119049  pTriggerStep->pSelect = pSelect;
119050  pTriggerStep->orconf = OE_Default;
119051  return pTriggerStep;
119052 }
119053 
119054 /*
119055 ** Allocate space to hold a new trigger step. The allocated space
119056 ** holds both the TriggerStep object and the TriggerStep.target.z string.
119057 **
119058 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
119059 */
119061  sqlite3 *db, /* Database connection */
119062  u8 op, /* Trigger opcode */
119063  Token *pName /* The target name */
119064 ){
119065  TriggerStep *pTriggerStep;
119066 
119067  pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n + 1);
119068  if( pTriggerStep ){
119069  char *z = (char*)&pTriggerStep[1];
119070  memcpy(z, pName->z, pName->n);
119071  sqlite3Dequote(z);
119072  pTriggerStep->zTarget = z;
119073  pTriggerStep->op = op;
119074  }
119075  return pTriggerStep;
119076 }
119077 
119078 /*
119079 ** Build a trigger step out of an INSERT statement. Return a pointer
119080 ** to the new trigger step.
119081 **
119082 ** The parser calls this routine when it sees an INSERT inside the
119083 ** body of a trigger.
119084 */
119086  sqlite3 *db, /* The database connection */
119087  Token *pTableName, /* Name of the table into which we insert */
119088  IdList *pColumn, /* List of columns in pTableName to insert into */
119089  Select *pSelect, /* A SELECT statement that supplies values */
119090  u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
119091 ){
119092  TriggerStep *pTriggerStep;
119093 
119094  assert(pSelect != 0 || db->mallocFailed);
119095 
119096  pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
119097  if( pTriggerStep ){
119098  pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
119099  pTriggerStep->pIdList = pColumn;
119100  pTriggerStep->orconf = orconf;
119101  }else{
119102  sqlite3IdListDelete(db, pColumn);
119103  }
119104  sqlite3SelectDelete(db, pSelect);
119105 
119106  return pTriggerStep;
119107 }
119108 
119109 /*
119110 ** Construct a trigger step that implements an UPDATE statement and return
119111 ** a pointer to that trigger step. The parser calls this routine when it
119112 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
119113 */
119115  sqlite3 *db, /* The database connection */
119116  Token *pTableName, /* Name of the table to be updated */
119117  ExprList *pEList, /* The SET clause: list of column and new values */
119118  Expr *pWhere, /* The WHERE clause */
119119  u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
119120 ){
119121  TriggerStep *pTriggerStep;
119122 
119123  pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
119124  if( pTriggerStep ){
119125  pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
119126  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119127  pTriggerStep->orconf = orconf;
119128  }
119129  sqlite3ExprListDelete(db, pEList);
119130  sqlite3ExprDelete(db, pWhere);
119131  return pTriggerStep;
119132 }
119133 
119134 /*
119135 ** Construct a trigger step that implements a DELETE statement and return
119136 ** a pointer to that trigger step. The parser calls this routine when it
119137 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
119138 */
119140  sqlite3 *db, /* Database connection */
119141  Token *pTableName, /* The table from which rows are deleted */
119142  Expr *pWhere /* The WHERE clause */
119143 ){
119144  TriggerStep *pTriggerStep;
119145 
119146  pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
119147  if( pTriggerStep ){
119148  pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
119149  pTriggerStep->orconf = OE_Default;
119150  }
119151  sqlite3ExprDelete(db, pWhere);
119152  return pTriggerStep;
119153 }
119154 
119155 /*
119156 ** Recursively delete a Trigger structure
119157 */
119158 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
119159  if( pTrigger==0 ) return;
119160  sqlite3DeleteTriggerStep(db, pTrigger->step_list);
119161  sqlite3DbFree(db, pTrigger->zName);
119162  sqlite3DbFree(db, pTrigger->table);
119163  sqlite3ExprDelete(db, pTrigger->pWhen);
119164  sqlite3IdListDelete(db, pTrigger->pColumns);
119165  sqlite3DbFree(db, pTrigger);
119166 }
119167 
119168 /*
119169 ** This function is called to drop a trigger from the database schema.
119170 **
119171 ** This may be called directly from the parser and therefore identifies
119172 ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
119173 ** same job as this routine except it takes a pointer to the trigger
119174 ** instead of the trigger name.
119175 **/
119176 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
119177  Trigger *pTrigger = 0;
119178  int i;
119179  const char *zDb;
119180  const char *zName;
119181  sqlite3 *db = pParse->db;
119182 
119183  if( db->mallocFailed ) goto drop_trigger_cleanup;
119184  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
119185  goto drop_trigger_cleanup;
119186  }
119187 
119188  assert( pName->nSrc==1 );
119189  zDb = pName->a[0].zDatabase;
119190  zName = pName->a[0].zName;
119191  assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
119192  for(i=OMIT_TEMPDB; i<db->nDb; i++){
119193  int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
119194  if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
119195  assert( sqlite3SchemaMutexHeld(db, j, 0) );
119196  pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
119197  if( pTrigger ) break;
119198  }
119199  if( !pTrigger ){
119200  if( !noErr ){
119201  sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
119202  }else{
119203  sqlite3CodeVerifyNamedSchema(pParse, zDb);
119204  }
119205  pParse->checkSchema = 1;
119206  goto drop_trigger_cleanup;
119207  }
119208  sqlite3DropTriggerPtr(pParse, pTrigger);
119209 
119210 drop_trigger_cleanup:
119211  sqlite3SrcListDelete(db, pName);
119212 }
119213 
119214 /*
119215 ** Return a pointer to the Table structure for the table that a trigger
119216 ** is set on.
119217 */
119218 static Table *tableOfTrigger(Trigger *pTrigger){
119219  return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
119220 }
119221 
119222 
119223 /*
119224 ** Drop a trigger given a pointer to that trigger.
119225 */
119227  Table *pTable;
119228  Vdbe *v;
119229  sqlite3 *db = pParse->db;
119230  int iDb;
119231 
119232  iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
119233  assert( iDb>=0 && iDb<db->nDb );
119234  pTable = tableOfTrigger(pTrigger);
119235  assert( pTable );
119236  assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
119237 #ifndef SQLITE_OMIT_AUTHORIZATION
119238  {
119239  int code = SQLITE_DROP_TRIGGER;
119240  const char *zDb = db->aDb[iDb].zName;
119241  const char *zTab = SCHEMA_TABLE(iDb);
119242  if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
119243  if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
119244  sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
119245  return;
119246  }
119247  }
119248 #endif
119249 
119250  /* Generate code to destroy the database record of the trigger.
119251  */
119252  assert( pTable!=0 );
119253  if( (v = sqlite3GetVdbe(pParse))!=0 ){
119254  sqlite3NestedParse(pParse,
119255  "DELETE FROM %Q.%s WHERE name=%Q AND type='trigger'",
119256  db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrigger->zName
119257  );
119258  sqlite3ChangeCookie(pParse, iDb);
119259  sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
119260  }
119261 }
119262 
119263 /*
119264 ** Remove a trigger from the hash tables of the sqlite* pointer.
119265 */
119266 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
119267  Trigger *pTrigger;
119268  Hash *pHash;
119269 
119270  assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
119271  pHash = &(db->aDb[iDb].pSchema->trigHash);
119272  pTrigger = sqlite3HashInsert(pHash, zName, 0);
119273  if( ALWAYS(pTrigger) ){
119274  if( pTrigger->pSchema==pTrigger->pTabSchema ){
119275  Table *pTab = tableOfTrigger(pTrigger);
119276  Trigger **pp;
119277  for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
119278  *pp = (*pp)->pNext;
119279  }
119280  sqlite3DeleteTrigger(db, pTrigger);
119281  db->flags |= SQLITE_InternChanges;
119282  }
119283 }
119284 
119285 /*
119286 ** pEList is the SET clause of an UPDATE statement. Each entry
119287 ** in pEList is of the format <id>=<expr>. If any of the entries
119288 ** in pEList have an <id> which matches an identifier in pIdList,
119289 ** then return TRUE. If pIdList==NULL, then it is considered a
119290 ** wildcard that matches anything. Likewise if pEList==NULL then
119291 ** it matches anything so always return true. Return false only
119292 ** if there is no match.
119293 */
119294 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
119295  int e;
119296  if( pIdList==0 || NEVER(pEList==0) ) return 1;
119297  for(e=0; e<pEList->nExpr; e++){
119298  if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
119299  }
119300  return 0;
119301 }
119302 
119303 /*
119304 ** Return a list of all triggers on table pTab if there exists at least
119305 ** one trigger that must be fired when an operation of type 'op' is
119306 ** performed on the table, and, if that operation is an UPDATE, if at
119307 ** least one of the columns in pChanges is being modified.
119308 */
119310  Parse *pParse, /* Parse context */
119311  Table *pTab, /* The table the contains the triggers */
119312  int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
119313  ExprList *pChanges, /* Columns that change in an UPDATE statement */
119314  int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
119315 ){
119316  int mask = 0;
119317  Trigger *pList = 0;
119318  Trigger *p;
119319 
119320  if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
119321  pList = sqlite3TriggerList(pParse, pTab);
119322  }
119323  assert( pList==0 || IsVirtual(pTab)==0 );
119324  for(p=pList; p; p=p->pNext){
119325  if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
119326  mask |= p->tr_tm;
119327  }
119328  }
119329  if( pMask ){
119330  *pMask = mask;
119331  }
119332  return (mask ? pList : 0);
119333 }
119334 
119335 /*
119336 ** Convert the pStep->zTarget string into a SrcList and return a pointer
119337 ** to that SrcList.
119338 **
119339 ** This routine adds a specific database name, if needed, to the target when
119340 ** forming the SrcList. This prevents a trigger in one database from
119341 ** referring to a target in another database. An exception is when the
119342 ** trigger is in TEMP in which case it can refer to any other database it
119343 ** wants.
119344 */
119346  Parse *pParse, /* The parsing context */
119347  TriggerStep *pStep /* The trigger containing the target token */
119348 ){
119349  sqlite3 *db = pParse->db;
119350  int iDb; /* Index of the database to use */
119351  SrcList *pSrc; /* SrcList to be returned */
119352 
119353  pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
119354  if( pSrc ){
119355  assert( pSrc->nSrc>0 );
119356  pSrc->a[pSrc->nSrc-1].zName = sqlite3DbStrDup(db, pStep->zTarget);
119357  iDb = sqlite3SchemaToIndex(db, pStep->pTrig->pSchema);
119358  if( iDb==0 || iDb>=2 ){
119359  assert( iDb<db->nDb );
119360  pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
119361  }
119362  }
119363  return pSrc;
119364 }
119365 
119366 /*
119367 ** Generate VDBE code for the statements inside the body of a single
119368 ** trigger.
119369 */
119371  Parse *pParse, /* The parser context */
119372  TriggerStep *pStepList, /* List of statements inside the trigger body */
119373  int orconf /* Conflict algorithm. (OE_Abort, etc) */
119374 ){
119375  TriggerStep *pStep;
119376  Vdbe *v = pParse->pVdbe;
119377  sqlite3 *db = pParse->db;
119378 
119379  assert( pParse->pTriggerTab && pParse->pToplevel );
119380  assert( pStepList );
119381  assert( v!=0 );
119382  for(pStep=pStepList; pStep; pStep=pStep->pNext){
119383  /* Figure out the ON CONFLICT policy that will be used for this step
119384  ** of the trigger program. If the statement that caused this trigger
119385  ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
119386  ** the ON CONFLICT policy that was specified as part of the trigger
119387  ** step statement. Example:
119388  **
119389  ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
119390  ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
119391  ** END;
119392  **
119393  ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
119394  ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
119395  */
119396  pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
119397  assert( pParse->okConstFactor==0 );
119398 
119399  switch( pStep->op ){
119400  case TK_UPDATE: {
119401  sqlite3Update(pParse,
119402  targetSrcList(pParse, pStep),
119403  sqlite3ExprListDup(db, pStep->pExprList, 0),
119404  sqlite3ExprDup(db, pStep->pWhere, 0),
119405  pParse->eOrconf
119406  );
119407  break;
119408  }
119409  case TK_INSERT: {
119410  sqlite3Insert(pParse,
119411  targetSrcList(pParse, pStep),
119412  sqlite3SelectDup(db, pStep->pSelect, 0),
119413  sqlite3IdListDup(db, pStep->pIdList),
119414  pParse->eOrconf
119415  );
119416  break;
119417  }
119418  case TK_DELETE: {
119419  sqlite3DeleteFrom(pParse,
119420  targetSrcList(pParse, pStep),
119421  sqlite3ExprDup(db, pStep->pWhere, 0)
119422  );
119423  break;
119424  }
119425  default: assert( pStep->op==TK_SELECT ); {
119426  SelectDest sDest;
119427  Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
119428  sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
119429  sqlite3Select(pParse, pSelect, &sDest);
119430  sqlite3SelectDelete(db, pSelect);
119431  break;
119432  }
119433  }
119434  if( pStep->op!=TK_SELECT ){
119436  }
119437  }
119438 
119439  return 0;
119440 }
119441 
119442 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
119443 /*
119444 ** This function is used to add VdbeComment() annotations to a VDBE
119445 ** program. It is not used in production code, only for debugging.
119446 */
119447 static const char *onErrorText(int onError){
119448  switch( onError ){
119449  case OE_Abort: return "abort";
119450  case OE_Rollback: return "rollback";
119451  case OE_Fail: return "fail";
119452  case OE_Replace: return "replace";
119453  case OE_Ignore: return "ignore";
119454  case OE_Default: return "default";
119455  }
119456  return "n/a";
119457 }
119458 #endif
119459 
119460 /*
119461 ** Parse context structure pFrom has just been used to create a sub-vdbe
119462 ** (trigger program). If an error has occurred, transfer error information
119463 ** from pFrom to pTo.
119464 */
119465 static void transferParseError(Parse *pTo, Parse *pFrom){
119466  assert( pFrom->zErrMsg==0 || pFrom->nErr );
119467  assert( pTo->zErrMsg==0 || pTo->nErr );
119468  if( pTo->nErr==0 ){
119469  pTo->zErrMsg = pFrom->zErrMsg;
119470  pTo->nErr = pFrom->nErr;
119471  pTo->rc = pFrom->rc;
119472  }else{
119473  sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
119474  }
119475 }
119476 
119477 /*
119478 ** Create and populate a new TriggerPrg object with a sub-program
119479 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
119480 */
119482  Parse *pParse, /* Current parse context */
119483  Trigger *pTrigger, /* Trigger to code */
119484  Table *pTab, /* The table pTrigger is attached to */
119485  int orconf /* ON CONFLICT policy to code trigger program with */
119486 ){
119487  Parse *pTop = sqlite3ParseToplevel(pParse);
119488  sqlite3 *db = pParse->db; /* Database handle */
119489  TriggerPrg *pPrg; /* Value to return */
119490  Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
119491  Vdbe *v; /* Temporary VM */
119492  NameContext sNC; /* Name context for sub-vdbe */
119493  SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
119494  Parse *pSubParse; /* Parse context for sub-vdbe */
119495  int iEndTrigger = 0; /* Label to jump to if WHEN is false */
119496 
119497  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
119498  assert( pTop->pVdbe );
119499 
119500  /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
119501  ** are freed if an error occurs, link them into the Parse.pTriggerPrg
119502  ** list of the top-level Parse object sooner rather than later. */
119503  pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
119504  if( !pPrg ) return 0;
119505  pPrg->pNext = pTop->pTriggerPrg;
119506  pTop->pTriggerPrg = pPrg;
119507  pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
119508  if( !pProgram ) return 0;
119509  sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
119510  pPrg->pTrigger = pTrigger;
119511  pPrg->orconf = orconf;
119512  pPrg->aColmask[0] = 0xffffffff;
119513  pPrg->aColmask[1] = 0xffffffff;
119514 
119515  /* Allocate and populate a new Parse context to use for coding the
119516  ** trigger sub-program. */
119517  pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
119518  if( !pSubParse ) return 0;
119519  memset(&sNC, 0, sizeof(sNC));
119520  sNC.pParse = pSubParse;
119521  pSubParse->db = db;
119522  pSubParse->pTriggerTab = pTab;
119523  pSubParse->pToplevel = pTop;
119524  pSubParse->zAuthContext = pTrigger->zName;
119525  pSubParse->eTriggerOp = pTrigger->op;
119526  pSubParse->nQueryLoop = pParse->nQueryLoop;
119527 
119528  v = sqlite3GetVdbe(pSubParse);
119529  if( v ){
119530  VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
119531  pTrigger->zName, onErrorText(orconf),
119532  (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
119533  (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
119534  (pTrigger->op==TK_INSERT ? "INSERT" : ""),
119535  (pTrigger->op==TK_DELETE ? "DELETE" : ""),
119536  pTab->zName
119537  ));
119538 #ifndef SQLITE_OMIT_TRACE
119539  sqlite3VdbeChangeP4(v, -1,
119540  sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
119541  );
119542 #endif
119543 
119544  /* If one was specified, code the WHEN clause. If it evaluates to false
119545  ** (or NULL) the sub-vdbe is immediately halted by jumping to the
119546  ** OP_Halt inserted at the end of the program. */
119547  if( pTrigger->pWhen ){
119548  pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
119549  if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
119550  && db->mallocFailed==0
119551  ){
119552  iEndTrigger = sqlite3VdbeMakeLabel(v);
119553  sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
119554  }
119555  sqlite3ExprDelete(db, pWhen);
119556  }
119557 
119558  /* Code the trigger program into the sub-vdbe. */
119559  codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
119560 
119561  /* Insert an OP_Halt at the end of the sub-program. */
119562  if( iEndTrigger ){
119563  sqlite3VdbeResolveLabel(v, iEndTrigger);
119564  }
119566  VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
119567 
119568  transferParseError(pParse, pSubParse);
119569  if( db->mallocFailed==0 ){
119570  pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
119571  }
119572  pProgram->nMem = pSubParse->nMem;
119573  pProgram->nCsr = pSubParse->nTab;
119574  pProgram->nOnce = pSubParse->nOnce;
119575  pProgram->token = (void *)pTrigger;
119576  pPrg->aColmask[0] = pSubParse->oldmask;
119577  pPrg->aColmask[1] = pSubParse->newmask;
119578  sqlite3VdbeDelete(v);
119579  }
119580 
119581  assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
119582  assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
119583  sqlite3ParserReset(pSubParse);
119584  sqlite3StackFree(db, pSubParse);
119585 
119586  return pPrg;
119587 }
119588 
119589 /*
119590 ** Return a pointer to a TriggerPrg object containing the sub-program for
119591 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
119592 ** TriggerPrg object exists, a new object is allocated and populated before
119593 ** being returned.
119594 */
119596  Parse *pParse, /* Current parse context */
119597  Trigger *pTrigger, /* Trigger to code */
119598  Table *pTab, /* The table trigger pTrigger is attached to */
119599  int orconf /* ON CONFLICT algorithm. */
119600 ){
119601  Parse *pRoot = sqlite3ParseToplevel(pParse);
119602  TriggerPrg *pPrg;
119603 
119604  assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
119605 
119606  /* It may be that this trigger has already been coded (or is in the
119607  ** process of being coded). If this is the case, then an entry with
119608  ** a matching TriggerPrg.pTrigger field will be present somewhere
119609  ** in the Parse.pTriggerPrg list. Search for such an entry. */
119610  for(pPrg=pRoot->pTriggerPrg;
119611  pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
119612  pPrg=pPrg->pNext
119613  );
119614 
119615  /* If an existing TriggerPrg could not be located, create a new one. */
119616  if( !pPrg ){
119617  pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
119618  }
119619 
119620  return pPrg;
119621 }
119622 
119623 /*
119624 ** Generate code for the trigger program associated with trigger p on
119625 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
119626 ** function are the same as those described in the header function for
119627 ** sqlite3CodeRowTrigger()
119628 */
119630  Parse *pParse, /* Parse context */
119631  Trigger *p, /* Trigger to code */
119632  Table *pTab, /* The table to code triggers from */
119633  int reg, /* Reg array containing OLD.* and NEW.* values */
119634  int orconf, /* ON CONFLICT policy */
119635  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
119636 ){
119637  Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
119638  TriggerPrg *pPrg;
119639  pPrg = getRowTrigger(pParse, p, pTab, orconf);
119640  assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
119641 
119642  /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
119643  ** is a pointer to the sub-vdbe containing the trigger program. */
119644  if( pPrg ){
119645  int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
119646 
119647  sqlite3VdbeAddOp4(v, OP_Program, reg, ignoreJump, ++pParse->nMem,
119648  (const char *)pPrg->pProgram, P4_SUBPROGRAM);
119649  VdbeComment(
119650  (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
119651 
119652  /* Set the P5 operand of the OP_Program instruction to non-zero if
119653  ** recursive invocation of this trigger program is disallowed. Recursive
119654  ** invocation is disallowed if (a) the sub-program is really a trigger,
119655  ** not a foreign key action, and (b) the flag to enable recursive triggers
119656  ** is clear. */
119657  sqlite3VdbeChangeP5(v, (u8)bRecursive);
119658  }
119659 }
119660 
119661 /*
119662 ** This is called to code the required FOR EACH ROW triggers for an operation
119663 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
119664 ** is given by the op parameter. The tr_tm parameter determines whether the
119665 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
119666 ** parameter pChanges is passed the list of columns being modified.
119667 **
119668 ** If there are no triggers that fire at the specified time for the specified
119669 ** operation on pTab, this function is a no-op.
119670 **
119671 ** The reg argument is the address of the first in an array of registers
119672 ** that contain the values substituted for the new.* and old.* references
119673 ** in the trigger program. If N is the number of columns in table pTab
119674 ** (a copy of pTab->nCol), then registers are populated as follows:
119675 **
119676 ** Register Contains
119677 ** ------------------------------------------------------
119678 ** reg+0 OLD.rowid
119679 ** reg+1 OLD.* value of left-most column of pTab
119680 ** ... ...
119681 ** reg+N OLD.* value of right-most column of pTab
119682 ** reg+N+1 NEW.rowid
119683 ** reg+N+2 OLD.* value of left-most column of pTab
119684 ** ... ...
119685 ** reg+N+N+1 NEW.* value of right-most column of pTab
119686 **
119687 ** For ON DELETE triggers, the registers containing the NEW.* values will
119688 ** never be accessed by the trigger program, so they are not allocated or
119689 ** populated by the caller (there is no data to populate them with anyway).
119690 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
119691 ** are never accessed, and so are not allocated by the caller. So, for an
119692 ** ON INSERT trigger, the value passed to this function as parameter reg
119693 ** is not a readable register, although registers (reg+N) through
119694 ** (reg+N+N+1) are.
119695 **
119696 ** Parameter orconf is the default conflict resolution algorithm for the
119697 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
119698 ** is the instruction that control should jump to if a trigger program
119699 ** raises an IGNORE exception.
119700 */
119702  Parse *pParse, /* Parse context */
119703  Trigger *pTrigger, /* List of triggers on table pTab */
119704  int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
119705  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
119706  int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
119707  Table *pTab, /* The table to code triggers from */
119708  int reg, /* The first in an array of registers (see above) */
119709  int orconf, /* ON CONFLICT policy */
119710  int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
119711 ){
119712  Trigger *p; /* Used to iterate through pTrigger list */
119713 
119714  assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
119715  assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
119716  assert( (op==TK_UPDATE)==(pChanges!=0) );
119717 
119718  for(p=pTrigger; p; p=p->pNext){
119719 
119720  /* Sanity checking: The schema for the trigger and for the table are
119721  ** always defined. The trigger must be in the same schema as the table
119722  ** or else it must be a TEMP trigger. */
119723  assert( p->pSchema!=0 );
119724  assert( p->pTabSchema!=0 );
119725  assert( p->pSchema==p->pTabSchema
119726  || p->pSchema==pParse->db->aDb[1].pSchema );
119727 
119728  /* Determine whether we should code this trigger */
119729  if( p->op==op
119730  && p->tr_tm==tr_tm
119731  && checkColumnOverlap(p->pColumns, pChanges)
119732  ){
119733  sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
119734  }
119735  }
119736 }
119737 
119738 /*
119739 ** Triggers may access values stored in the old.* or new.* pseudo-table.
119740 ** This function returns a 32-bit bitmask indicating which columns of the
119741 ** old.* or new.* tables actually are used by triggers. This information
119742 ** may be used by the caller, for example, to avoid having to load the entire
119743 ** old.* record into memory when executing an UPDATE or DELETE command.
119744 **
119745 ** Bit 0 of the returned mask is set if the left-most column of the
119746 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
119747 ** the second leftmost column value is required, and so on. If there
119748 ** are more than 32 columns in the table, and at least one of the columns
119749 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
119750 **
119751 ** It is not possible to determine if the old.rowid or new.rowid column is
119752 ** accessed by triggers. The caller must always assume that it is.
119753 **
119754 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
119755 ** applies to the old.* table. If 1, the new.* table.
119756 **
119757 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
119758 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
119759 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
119760 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
119761 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
119762 */
119764  Parse *pParse, /* Parse context */
119765  Trigger *pTrigger, /* List of triggers on table pTab */
119766  ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
119767  int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
119768  int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
119769  Table *pTab, /* The table to code triggers from */
119770  int orconf /* Default ON CONFLICT policy for trigger steps */
119771 ){
119772  const int op = pChanges ? TK_UPDATE : TK_DELETE;
119773  u32 mask = 0;
119774  Trigger *p;
119775 
119776  assert( isNew==1 || isNew==0 );
119777  for(p=pTrigger; p; p=p->pNext){
119778  if( p->op==op && (tr_tm&p->tr_tm)
119779  && checkColumnOverlap(p->pColumns,pChanges)
119780  ){
119781  TriggerPrg *pPrg;
119782  pPrg = getRowTrigger(pParse, p, pTab, orconf);
119783  if( pPrg ){
119784  mask |= pPrg->aColmask[isNew];
119785  }
119786  }
119787  }
119788 
119789  return mask;
119790 }
119791 
119792 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
119793 
119794 /************** End of trigger.c *********************************************/
119795 /************** Begin file update.c ******************************************/
119796 /*
119797 ** 2001 September 15
119798 **
119799 ** The author disclaims copyright to this source code. In place of
119800 ** a legal notice, here is a blessing:
119801 **
119802 ** May you do good and not evil.
119803 ** May you find forgiveness for yourself and forgive others.
119804 ** May you share freely, never taking more than you give.
119805 **
119806 *************************************************************************
119807 ** This file contains C code routines that are called by the parser
119808 ** to handle UPDATE statements.
119809 */
119810 /* #include "sqliteInt.h" */
119811 
119812 #ifndef SQLITE_OMIT_VIRTUALTABLE
119813 /* Forward declaration */
119814 static void updateVirtualTable(
119815  Parse *pParse, /* The parsing context */
119816  SrcList *pSrc, /* The virtual table to be modified */
119817  Table *pTab, /* The virtual table */
119818  ExprList *pChanges, /* The columns to change in the UPDATE statement */
119819  Expr *pRowidExpr, /* Expression used to recompute the rowid */
119820  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
119821  Expr *pWhere, /* WHERE clause of the UPDATE statement */
119822  int onError /* ON CONFLICT strategy */
119823 );
119824 #endif /* SQLITE_OMIT_VIRTUALTABLE */
119825 
119826 /*
119827 ** The most recently coded instruction was an OP_Column to retrieve the
119828 ** i-th column of table pTab. This routine sets the P4 parameter of the
119829 ** OP_Column to the default value, if any.
119830 **
119831 ** The default value of a column is specified by a DEFAULT clause in the
119832 ** column definition. This was either supplied by the user when the table
119833 ** was created, or added later to the table definition by an ALTER TABLE
119834 ** command. If the latter, then the row-records in the table btree on disk
119835 ** may not contain a value for the column and the default value, taken
119836 ** from the P4 parameter of the OP_Column instruction, is returned instead.
119837 ** If the former, then all row-records are guaranteed to include a value
119838 ** for the column and the P4 value is not required.
119839 **
119840 ** Column definitions created by an ALTER TABLE command may only have
119841 ** literal default values specified: a number, null or a string. (If a more
119842 ** complicated default expression value was provided, it is evaluated
119843 ** when the ALTER TABLE is executed and one of the literal values written
119844 ** into the sqlite_master table.)
119845 **
119846 ** Therefore, the P4 parameter is only required if the default value for
119847 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
119848 ** function is capable of transforming these types of expressions into
119849 ** sqlite3_value objects.
119850 **
119851 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
119852 ** on register iReg. This is used when an equivalent integer value is
119853 ** stored in place of an 8-byte floating point value in order to save
119854 ** space.
119855 */
119856 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
119857  assert( pTab!=0 );
119858  if( !pTab->pSelect ){
119859  sqlite3_value *pValue = 0;
119860  u8 enc = ENC(sqlite3VdbeDb(v));
119861  Column *pCol = &pTab->aCol[i];
119862  VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
119863  assert( i<pTab->nCol );
119864  sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
119865  pCol->affinity, &pValue);
119866  if( pValue ){
119867  sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
119868  }
119869 #ifndef SQLITE_OMIT_FLOATING_POINT
119870  if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
119872  }
119873 #endif
119874  }
119875 }
119876 
119877 /*
119878 ** Process an UPDATE statement.
119879 **
119880 ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
119881 ** \_______/ \________/ \______/ \________________/
119882 * onError pTabList pChanges pWhere
119883 */
119885  Parse *pParse, /* The parser context */
119886  SrcList *pTabList, /* The table in which we should change things */
119887  ExprList *pChanges, /* Things to be changed */
119888  Expr *pWhere, /* The WHERE clause. May be null */
119889  int onError /* How to handle constraint errors */
119890 ){
119891  int i, j; /* Loop counters */
119892  Table *pTab; /* The table to be updated */
119893  int addrTop = 0; /* VDBE instruction address of the start of the loop */
119894  WhereInfo *pWInfo; /* Information about the WHERE clause */
119895  Vdbe *v; /* The virtual database engine */
119896  Index *pIdx; /* For looping over indices */
119897  Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
119898  int nIdx; /* Number of indices that need updating */
119899  int iBaseCur; /* Base cursor number */
119900  int iDataCur; /* Cursor for the canonical data btree */
119901  int iIdxCur; /* Cursor for the first index */
119902  sqlite3 *db; /* The database structure */
119903  int *aRegIdx = 0; /* One register assigned to each index to be updated */
119904  int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
119905  ** an expression for the i-th column of the table.
119906  ** aXRef[i]==-1 if the i-th column is not changed. */
119907  u8 *aToOpen; /* 1 for tables and indices to be opened */
119908  u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
119909  u8 chngRowid; /* Rowid changed in a normal table */
119910  u8 chngKey; /* Either chngPk or chngRowid */
119911  Expr *pRowidExpr = 0; /* Expression defining the new record number */
119912  AuthContext sContext; /* The authorization context */
119913  NameContext sNC; /* The name-context to resolve expressions in */
119914  int iDb; /* Database containing the table being updated */
119915  int okOnePass; /* True for one-pass algorithm without the FIFO */
119916  int hasFK; /* True if foreign key processing is required */
119917  int labelBreak; /* Jump here to break out of UPDATE loop */
119918  int labelContinue; /* Jump here to continue next step of UPDATE loop */
119919 
119920 #ifndef SQLITE_OMIT_TRIGGER
119921  int isView; /* True when updating a view (INSTEAD OF trigger) */
119922  Trigger *pTrigger; /* List of triggers on pTab, if required */
119923  int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
119924 #endif
119925  int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
119926  int iEph = 0; /* Ephemeral table holding all primary key values */
119927  int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
119928  int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
119929 
119930  /* Register Allocations */
119931  int regRowCount = 0; /* A count of rows changed */
119932  int regOldRowid = 0; /* The old rowid */
119933  int regNewRowid = 0; /* The new rowid */
119934  int regNew = 0; /* Content of the NEW.* table in triggers */
119935  int regOld = 0; /* Content of OLD.* table in triggers */
119936  int regRowSet = 0; /* Rowset of rows to be updated */
119937  int regKey = 0; /* composite PRIMARY KEY value */
119938 
119939  memset(&sContext, 0, sizeof(sContext));
119940  db = pParse->db;
119941  if( pParse->nErr || db->mallocFailed ){
119942  goto update_cleanup;
119943  }
119944  assert( pTabList->nSrc==1 );
119945 
119946  /* Locate the table which we want to update.
119947  */
119948  pTab = sqlite3SrcListLookup(pParse, pTabList);
119949  if( pTab==0 ) goto update_cleanup;
119950  iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
119951 
119952  /* Figure out if we have any triggers and if the table being
119953  ** updated is a view.
119954  */
119955 #ifndef SQLITE_OMIT_TRIGGER
119956  pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
119957  isView = pTab->pSelect!=0;
119958  assert( pTrigger || tmask==0 );
119959 #else
119960 # define pTrigger 0
119961 # define isView 0
119962 # define tmask 0
119963 #endif
119964 #ifdef SQLITE_OMIT_VIEW
119965 # undef isView
119966 # define isView 0
119967 #endif
119968 
119969  if( sqlite3ViewGetColumnNames(pParse, pTab) ){
119970  goto update_cleanup;
119971  }
119972  if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
119973  goto update_cleanup;
119974  }
119975 
119976  /* Allocate a cursors for the main database table and for all indices.
119977  ** The index cursors might not be used, but if they are used they
119978  ** need to occur right after the database cursor. So go ahead and
119979  ** allocate enough space, just in case.
119980  */
119981  pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
119982  iIdxCur = iDataCur+1;
119983  pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
119984  for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
119985  if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
119986  iDataCur = pParse->nTab;
119987  pTabList->a[0].iCursor = iDataCur;
119988  }
119989  pParse->nTab++;
119990  }
119991 
119992  /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
119993  ** Initialize aXRef[] and aToOpen[] to their default values.
119994  */
119995  aXRef = sqlite3DbMallocRawNN(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
119996  if( aXRef==0 ) goto update_cleanup;
119997  aRegIdx = aXRef+pTab->nCol;
119998  aToOpen = (u8*)(aRegIdx+nIdx);
119999  memset(aToOpen, 1, nIdx+1);
120000  aToOpen[nIdx+1] = 0;
120001  for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
120002 
120003  /* Initialize the name-context */
120004  memset(&sNC, 0, sizeof(sNC));
120005  sNC.pParse = pParse;
120006  sNC.pSrcList = pTabList;
120007 
120008  /* Resolve the column names in all the expressions of the
120009  ** of the UPDATE statement. Also find the column index
120010  ** for each column to be updated in the pChanges array. For each
120011  ** column to be updated, make sure we have authorization to change
120012  ** that column.
120013  */
120014  chngRowid = chngPk = 0;
120015  for(i=0; i<pChanges->nExpr; i++){
120016  if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
120017  goto update_cleanup;
120018  }
120019  for(j=0; j<pTab->nCol; j++){
120020  if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
120021  if( j==pTab->iPKey ){
120022  chngRowid = 1;
120023  pRowidExpr = pChanges->a[i].pExpr;
120024  }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
120025  chngPk = 1;
120026  }
120027  aXRef[j] = i;
120028  break;
120029  }
120030  }
120031  if( j>=pTab->nCol ){
120032  if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
120033  j = -1;
120034  chngRowid = 1;
120035  pRowidExpr = pChanges->a[i].pExpr;
120036  }else{
120037  sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
120038  pParse->checkSchema = 1;
120039  goto update_cleanup;
120040  }
120041  }
120042 #ifndef SQLITE_OMIT_AUTHORIZATION
120043  {
120044  int rc;
120045  rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
120046  j<0 ? "ROWID" : pTab->aCol[j].zName,
120047  db->aDb[iDb].zName);
120048  if( rc==SQLITE_DENY ){
120049  goto update_cleanup;
120050  }else if( rc==SQLITE_IGNORE ){
120051  aXRef[j] = -1;
120052  }
120053  }
120054 #endif
120055  }
120056  assert( (chngRowid & chngPk)==0 );
120057  assert( chngRowid==0 || chngRowid==1 );
120058  assert( chngPk==0 || chngPk==1 );
120059  chngKey = chngRowid + chngPk;
120060 
120061  /* The SET expressions are not actually used inside the WHERE loop.
120062  ** So reset the colUsed mask. Unless this is a virtual table. In that
120063  ** case, set all bits of the colUsed mask (to ensure that the virtual
120064  ** table implementation makes all columns available).
120065  */
120066  pTabList->a[0].colUsed = IsVirtual(pTab) ? ALLBITS : 0;
120067 
120068  hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
120069 
120070  /* There is one entry in the aRegIdx[] array for each index on the table
120071  ** being updated. Fill in aRegIdx[] with a register number that will hold
120072  ** the key for accessing each index.
120073  **
120074  ** FIXME: Be smarter about omitting indexes that use expressions.
120075  */
120076  for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
120077  int reg;
120078  if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
120079  reg = ++pParse->nMem;
120080  }else{
120081  reg = 0;
120082  for(i=0; i<pIdx->nKeyCol; i++){
120083  i16 iIdxCol = pIdx->aiColumn[i];
120084  if( iIdxCol<0 || aXRef[iIdxCol]>=0 ){
120085  reg = ++pParse->nMem;
120086  break;
120087  }
120088  }
120089  }
120090  if( reg==0 ) aToOpen[j+1] = 0;
120091  aRegIdx[j] = reg;
120092  }
120093 
120094  /* Begin generating code. */
120095  v = sqlite3GetVdbe(pParse);
120096  if( v==0 ) goto update_cleanup;
120097  if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
120098  sqlite3BeginWriteOperation(pParse, 1, iDb);
120099 
120100  /* Allocate required registers. */
120101  if( !IsVirtual(pTab) ){
120102  regRowSet = ++pParse->nMem;
120103  regOldRowid = regNewRowid = ++pParse->nMem;
120104  if( chngPk || pTrigger || hasFK ){
120105  regOld = pParse->nMem + 1;
120106  pParse->nMem += pTab->nCol;
120107  }
120108  if( chngKey || pTrigger || hasFK ){
120109  regNewRowid = ++pParse->nMem;
120110  }
120111  regNew = pParse->nMem + 1;
120112  pParse->nMem += pTab->nCol;
120113  }
120114 
120115  /* Start the view context. */
120116  if( isView ){
120117  sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
120118  }
120119 
120120  /* If we are trying to update a view, realize that view into
120121  ** an ephemeral table.
120122  */
120123 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
120124  if( isView ){
120125  sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
120126  }
120127 #endif
120128 
120129  /* Resolve the column names in all the expressions in the
120130  ** WHERE clause.
120131  */
120132  if( sqlite3ResolveExprNames(&sNC, pWhere) ){
120133  goto update_cleanup;
120134  }
120135 
120136 #ifndef SQLITE_OMIT_VIRTUALTABLE
120137  /* Virtual tables must be handled separately */
120138  if( IsVirtual(pTab) ){
120139  updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
120140  pWhere, onError);
120141  goto update_cleanup;
120142  }
120143 #endif
120144 
120145  /* Begin the database scan
120146  */
120147  if( HasRowid(pTab) ){
120148  sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
120149  pWInfo = sqlite3WhereBegin(
120150  pParse, pTabList, pWhere, 0, 0,
120152  );
120153  if( pWInfo==0 ) goto update_cleanup;
120154  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120155 
120156  /* Remember the rowid of every item to be updated.
120157  */
120158  sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
120159  if( !okOnePass ){
120160  sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
120161  }
120162 
120163  /* End the database scan loop.
120164  */
120165  sqlite3WhereEnd(pWInfo);
120166  }else{
120167  int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
120168  i16 nPk; /* Number of components of the PRIMARY KEY */
120169  int addrOpen; /* Address of the OpenEphemeral instruction */
120170 
120171  assert( pPk!=0 );
120172  nPk = pPk->nKeyCol;
120173  iPk = pParse->nMem+1;
120174  pParse->nMem += nPk;
120175  regKey = ++pParse->nMem;
120176  iEph = pParse->nTab++;
120177  sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
120178  addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
120179  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
120180  pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
120181  WHERE_ONEPASS_DESIRED, iIdxCur);
120182  if( pWInfo==0 ) goto update_cleanup;
120183  okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
120184  for(i=0; i<nPk; i++){
120185  assert( pPk->aiColumn[i]>=0 );
120186  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
120187  iPk+i);
120188  }
120189  if( okOnePass ){
120190  sqlite3VdbeChangeToNoop(v, addrOpen);
120191  nKey = nPk;
120192  regKey = iPk;
120193  }else{
120194  sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
120195  sqlite3IndexAffinityStr(db, pPk), nPk);
120196  sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
120197  }
120198  sqlite3WhereEnd(pWInfo);
120199  }
120200 
120201  /* Initialize the count of updated rows
120202  */
120203  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
120204  regRowCount = ++pParse->nMem;
120205  sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
120206  }
120207 
120208  labelBreak = sqlite3VdbeMakeLabel(v);
120209  if( !isView ){
120210  /*
120211  ** Open every index that needs updating. Note that if any
120212  ** index could potentially invoke a REPLACE conflict resolution
120213  ** action, then we need to open all indices because we might need
120214  ** to be deleting some records.
120215  */
120216  if( onError==OE_Replace ){
120217  memset(aToOpen, 1, nIdx+1);
120218  }else{
120219  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120220  if( pIdx->onError==OE_Replace ){
120221  memset(aToOpen, 1, nIdx+1);
120222  break;
120223  }
120224  }
120225  }
120226  if( okOnePass ){
120227  if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
120228  if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
120229  }
120230  sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, 0, iBaseCur, aToOpen,
120231  0, 0);
120232  }
120233 
120234  /* Top of the update loop */
120235  if( okOnePass ){
120236  if( aToOpen[iDataCur-iBaseCur] && !isView ){
120237  assert( pPk );
120238  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
120240  }
120241  labelContinue = labelBreak;
120242  sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
120243  VdbeCoverageIf(v, pPk==0);
120244  VdbeCoverageIf(v, pPk!=0);
120245  }else if( pPk ){
120246  labelContinue = sqlite3VdbeMakeLabel(v);
120247  sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
120248  addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
120249  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
120250  VdbeCoverage(v);
120251  }else{
120252  labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
120253  regOldRowid);
120254  VdbeCoverage(v);
120255  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
120256  VdbeCoverage(v);
120257  }
120258 
120259  /* If the record number will change, set register regNewRowid to
120260  ** contain the new value. If the record number is not being modified,
120261  ** then regNewRowid is the same register as regOldRowid, which is
120262  ** already populated. */
120263  assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
120264  if( chngRowid ){
120265  sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
120266  sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
120267  }
120268 
120269  /* Compute the old pre-UPDATE content of the row being changed, if that
120270  ** information is needed */
120271  if( chngPk || hasFK || pTrigger ){
120272  u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
120273  oldmask |= sqlite3TriggerColmask(pParse,
120274  pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
120275  );
120276  for(i=0; i<pTab->nCol; i++){
120277  if( oldmask==0xffffffff
120278  || (i<32 && (oldmask & MASKBIT32(i))!=0)
120279  || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
120280  ){
120281  testcase( oldmask!=0xffffffff && i==31 );
120282  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
120283  }else{
120284  sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
120285  }
120286  }
120287  if( chngRowid==0 && pPk==0 ){
120288  sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
120289  }
120290  }
120291 
120292  /* Populate the array of registers beginning at regNew with the new
120293  ** row data. This array is used to check constants, create the new
120294  ** table and index records, and as the values for any new.* references
120295  ** made by triggers.
120296  **
120297  ** If there are one or more BEFORE triggers, then do not populate the
120298  ** registers associated with columns that are (a) not modified by
120299  ** this UPDATE statement and (b) not accessed by new.* references. The
120300  ** values for registers not modified by the UPDATE must be reloaded from
120301  ** the database after the BEFORE triggers are fired anyway (as the trigger
120302  ** may have modified them). So not loading those that are not going to
120303  ** be used eliminates some redundant opcodes.
120304  */
120305  newmask = sqlite3TriggerColmask(
120306  pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
120307  );
120308  for(i=0; i<pTab->nCol; i++){
120309  if( i==pTab->iPKey ){
120310  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
120311  }else{
120312  j = aXRef[i];
120313  if( j>=0 ){
120314  sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
120315  }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
120316  /* This branch loads the value of a column that will not be changed
120317  ** into a register. This is done if there are no BEFORE triggers, or
120318  ** if there are one or more BEFORE triggers that use this value via
120319  ** a new.* reference in a trigger program.
120320  */
120321  testcase( i==31 );
120322  testcase( i==32 );
120323  sqlite3ExprCodeGetColumnToReg(pParse, pTab, i, iDataCur, regNew+i);
120324  }else{
120325  sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
120326  }
120327  }
120328  }
120329 
120330  /* Fire any BEFORE UPDATE triggers. This happens before constraints are
120331  ** verified. One could argue that this is wrong.
120332  */
120333  if( tmask&TRIGGER_BEFORE ){
120334  sqlite3TableAffinity(v, pTab, regNew);
120335  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
120336  TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
120337 
120338  /* The row-trigger may have deleted the row being updated. In this
120339  ** case, jump to the next row. No updates or AFTER triggers are
120340  ** required. This behavior - what happens when the row being updated
120341  ** is deleted or renamed by a BEFORE trigger - is left undefined in the
120342  ** documentation.
120343  */
120344  if( pPk ){
120345  sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
120346  VdbeCoverage(v);
120347  }else{
120348  sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
120349  VdbeCoverage(v);
120350  }
120351 
120352  /* If it did not delete it, the row-trigger may still have modified
120353  ** some of the columns of the row being updated. Load the values for
120354  ** all columns not modified by the update statement into their
120355  ** registers in case this has happened.
120356  */
120357  for(i=0; i<pTab->nCol; i++){
120358  if( aXRef[i]<0 && i!=pTab->iPKey ){
120359  sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
120360  }
120361  }
120362  }
120363 
120364  if( !isView ){
120365  int addr1 = 0; /* Address of jump instruction */
120366  int bReplace = 0; /* True if REPLACE conflict resolution might happen */
120367 
120368  /* Do constraint checks. */
120369  assert( regOldRowid>0 );
120370  sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
120371  regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace,
120372  aXRef);
120373 
120374  /* Do FK constraint checks. */
120375  if( hasFK ){
120376  sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
120377  }
120378 
120379  /* Delete the index entries associated with the current record. */
120380  if( bReplace || chngKey ){
120381  if( pPk ){
120382  addr1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
120383  }else{
120384  addr1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
120385  }
120387  }
120388  sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx, -1);
120389 
120390  /* If changing the rowid value, or if there are foreign key constraints
120391  ** to process, delete the old record. Otherwise, add a noop OP_Delete
120392  ** to invoke the pre-update hook.
120393  **
120394  ** That (regNew==regnewRowid+1) is true is also important for the
120395  ** pre-update hook. If the caller invokes preupdate_new(), the returned
120396  ** value is copied from memory cell (regNewRowid+1+iCol), where iCol
120397  ** is the column index supplied by the user.
120398  */
120399  assert( regNew==regNewRowid+1 );
120400 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
120401  sqlite3VdbeAddOp3(v, OP_Delete, iDataCur,
120402  OPFLAG_ISUPDATE | ((hasFK || chngKey || pPk!=0) ? 0 : OPFLAG_ISNOOP),
120403  regNewRowid
120404  );
120405  if( !pParse->nested ){
120406  sqlite3VdbeChangeP4(v, -1, (char*)pTab, P4_TABLE);
120407  }
120408 #else
120409  if( hasFK || chngKey || pPk!=0 ){
120410  sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
120411  }
120412 #endif
120413  if( bReplace || chngKey ){
120414  sqlite3VdbeJumpHere(v, addr1);
120415  }
120416 
120417  if( hasFK ){
120418  sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
120419  }
120420 
120421  /* Insert the new index entries and the new record. */
120422  sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
120423  regNewRowid, aRegIdx, 1, 0, 0);
120424 
120425  /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
120426  ** handle rows (possibly in other tables) that refer via a foreign key
120427  ** to the row just updated. */
120428  if( hasFK ){
120429  sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
120430  }
120431  }
120432 
120433  /* Increment the row counter
120434  */
120435  if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
120436  sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
120437  }
120438 
120439  sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
120440  TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
120441 
120442  /* Repeat the above with the next record to be updated, until
120443  ** all record selected by the WHERE clause have been updated.
120444  */
120445  if( okOnePass ){
120446  /* Nothing to do at end-of-loop for a single-pass */
120447  }else if( pPk ){
120448  sqlite3VdbeResolveLabel(v, labelContinue);
120449  sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
120450  }else{
120451  sqlite3VdbeGoto(v, labelContinue);
120452  }
120453  sqlite3VdbeResolveLabel(v, labelBreak);
120454 
120455  /* Close all tables */
120456  for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
120457  assert( aRegIdx );
120458  if( aToOpen[i+1] ){
120459  sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
120460  }
120461  }
120462  if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
120463 
120464  /* Update the sqlite_sequence table by storing the content of the
120465  ** maximum rowid counter values recorded while inserting into
120466  ** autoincrement tables.
120467  */
120468  if( pParse->nested==0 && pParse->pTriggerTab==0 ){
120469  sqlite3AutoincrementEnd(pParse);
120470  }
120471 
120472  /*
120473  ** Return the number of rows that were changed. If this routine is
120474  ** generating code because of a call to sqlite3NestedParse(), do not
120475  ** invoke the callback function.
120476  */
120477  if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
120478  sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
120479  sqlite3VdbeSetNumCols(v, 1);
120480  sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
120481  }
120482 
120483 update_cleanup:
120484  sqlite3AuthContextPop(&sContext);
120485  sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
120486  sqlite3SrcListDelete(db, pTabList);
120487  sqlite3ExprListDelete(db, pChanges);
120488  sqlite3ExprDelete(db, pWhere);
120489  return;
120490 }
120491 /* Make sure "isView" and other macros defined above are undefined. Otherwise
120492 ** they may interfere with compilation of other functions in this file
120493 ** (or in another file, if this file becomes part of the amalgamation). */
120494 #ifdef isView
120495  #undef isView
120496 #endif
120497 #ifdef pTrigger
120498  #undef pTrigger
120499 #endif
120500 
120501 #ifndef SQLITE_OMIT_VIRTUALTABLE
120502 /*
120503 ** Generate code for an UPDATE of a virtual table.
120504 **
120505 ** There are two possible strategies - the default and the special
120506 ** "onepass" strategy. Onepass is only used if the virtual table
120507 ** implementation indicates that pWhere may match at most one row.
120508 **
120509 ** The default strategy is to create an ephemeral table that contains
120510 ** for each row to be changed:
120511 **
120512 ** (A) The original rowid of that row.
120513 ** (B) The revised rowid for the row.
120514 ** (C) The content of every column in the row.
120515 **
120516 ** Then loop through the contents of this ephemeral table executing a
120517 ** VUpdate for each row. When finished, drop the ephemeral table.
120518 **
120519 ** The "onepass" strategy does not use an ephemeral table. Instead, it
120520 ** stores the same values (A, B and C above) in a register array and
120521 ** makes a single invocation of VUpdate.
120522 */
120524  Parse *pParse, /* The parsing context */
120525  SrcList *pSrc, /* The virtual table to be modified */
120526  Table *pTab, /* The virtual table */
120527  ExprList *pChanges, /* The columns to change in the UPDATE statement */
120528  Expr *pRowid, /* Expression used to recompute the rowid */
120529  int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
120530  Expr *pWhere, /* WHERE clause of the UPDATE statement */
120531  int onError /* ON CONFLICT strategy */
120532 ){
120533  Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
120534  int ephemTab; /* Table holding the result of the SELECT */
120535  int i; /* Loop counter */
120536  sqlite3 *db = pParse->db; /* Database connection */
120537  const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
120538  WhereInfo *pWInfo;
120539  int nArg = 2 + pTab->nCol; /* Number of arguments to VUpdate */
120540  int regArg; /* First register in VUpdate arg array */
120541  int regRec; /* Register in which to assemble record */
120542  int regRowid; /* Register for ephem table rowid */
120543  int iCsr = pSrc->a[0].iCursor; /* Cursor used for virtual table scan */
120544  int aDummy[2]; /* Unused arg for sqlite3WhereOkOnePass() */
120545  int bOnePass; /* True to use onepass strategy */
120546  int addr; /* Address of OP_OpenEphemeral */
120547 
120548  /* Allocate nArg registers to martial the arguments to VUpdate. Then
120549  ** create and open the ephemeral table in which the records created from
120550  ** these arguments will be temporarily stored. */
120551  assert( v );
120552  ephemTab = pParse->nTab++;
120553  addr= sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, nArg);
120554  regArg = pParse->nMem + 1;
120555  pParse->nMem += nArg;
120556  regRec = ++pParse->nMem;
120557  regRowid = ++pParse->nMem;
120558 
120559  /* Start scanning the virtual table */
120560  pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0,0,WHERE_ONEPASS_DESIRED,0);
120561  if( pWInfo==0 ) return;
120562 
120563  /* Populate the argument registers. */
120564  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg);
120565  if( pRowid ){
120566  sqlite3ExprCode(pParse, pRowid, regArg+1);
120567  }else{
120568  sqlite3VdbeAddOp2(v, OP_Rowid, iCsr, regArg+1);
120569  }
120570  for(i=0; i<pTab->nCol; i++){
120571  if( aXRef[i]>=0 ){
120572  sqlite3ExprCode(pParse, pChanges->a[aXRef[i]].pExpr, regArg+2+i);
120573  }else{
120574  sqlite3VdbeAddOp3(v, OP_VColumn, iCsr, i, regArg+2+i);
120575  }
120576  }
120577 
120578  bOnePass = sqlite3WhereOkOnePass(pWInfo, aDummy);
120579 
120580  if( bOnePass ){
120581  /* If using the onepass strategy, no-op out the OP_OpenEphemeral coded
120582  ** above. Also, if this is a top-level parse (not a trigger), clear the
120583  ** multi-write flag so that the VM does not open a statement journal */
120584  sqlite3VdbeChangeToNoop(v, addr);
120585  if( sqlite3IsToplevel(pParse) ){
120586  pParse->isMultiWrite = 0;
120587  }
120588  }else{
120589  /* Create a record from the argument register contents and insert it into
120590  ** the ephemeral table. */
120591  sqlite3VdbeAddOp3(v, OP_MakeRecord, regArg, nArg, regRec);
120592  sqlite3VdbeAddOp2(v, OP_NewRowid, ephemTab, regRowid);
120593  sqlite3VdbeAddOp3(v, OP_Insert, ephemTab, regRec, regRowid);
120594  }
120595 
120596 
120597  if( bOnePass==0 ){
120598  /* End the virtual table scan */
120599  sqlite3WhereEnd(pWInfo);
120600 
120601  /* Begin scannning through the ephemeral table. */
120602  addr = sqlite3VdbeAddOp1(v, OP_Rewind, ephemTab); VdbeCoverage(v);
120603 
120604  /* Extract arguments from the current row of the ephemeral table and
120605  ** invoke the VUpdate method. */
120606  for(i=0; i<nArg; i++){
120607  sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i, regArg+i);
120608  }
120609  }
120610  sqlite3VtabMakeWritable(pParse, pTab);
120611  sqlite3VdbeAddOp4(v, OP_VUpdate, 0, nArg, regArg, pVTab, P4_VTAB);
120612  sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
120613  sqlite3MayAbort(pParse);
120614 
120615  /* End of the ephemeral table scan. Or, if using the onepass strategy,
120616  ** jump to here if the scan visited zero rows. */
120617  if( bOnePass==0 ){
120618  sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
120619  sqlite3VdbeJumpHere(v, addr);
120620  sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
120621  }else{
120622  sqlite3WhereEnd(pWInfo);
120623  }
120624 }
120625 #endif /* SQLITE_OMIT_VIRTUALTABLE */
120626 
120627 /************** End of update.c **********************************************/
120628 /************** Begin file vacuum.c ******************************************/
120629 /*
120630 ** 2003 April 6
120631 **
120632 ** The author disclaims copyright to this source code. In place of
120633 ** a legal notice, here is a blessing:
120634 **
120635 ** May you do good and not evil.
120636 ** May you find forgiveness for yourself and forgive others.
120637 ** May you share freely, never taking more than you give.
120638 **
120639 *************************************************************************
120640 ** This file contains code used to implement the VACUUM command.
120641 **
120642 ** Most of the code in this file may be omitted by defining the
120643 ** SQLITE_OMIT_VACUUM macro.
120644 */
120645 /* #include "sqliteInt.h" */
120646 /* #include "vdbeInt.h" */
120647 
120648 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
120649 /*
120650 ** Finalize a prepared statement. If there was an error, store the
120651 ** text of the error message in *pzErrMsg. Return the result code.
120652 */
120653 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
120654  int rc;
120655  rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
120656  if( rc ){
120657  sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
120658  }
120659  return rc;
120660 }
120661 
120662 /*
120663 ** Execute zSql on database db. Return an error code.
120664 */
120665 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
120666  sqlite3_stmt *pStmt;
120667  VVA_ONLY( int rc; )
120668  if( !zSql ){
120669  return SQLITE_NOMEM_BKPT;
120670  }
120671  if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
120672  sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
120673  return sqlite3_errcode(db);
120674  }
120675  VVA_ONLY( rc = ) sqlite3_step(pStmt);
120676  assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
120677  return vacuumFinalize(db, pStmt, pzErrMsg);
120678 }
120679 
120680 /*
120681 ** Execute zSql on database db. The statement returns exactly
120682 ** one column. Execute this as SQL on the same database.
120683 */
120684 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
120685  sqlite3_stmt *pStmt;
120686  int rc;
120687 
120688  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
120689  if( rc!=SQLITE_OK ) return rc;
120690 
120691  while( SQLITE_ROW==sqlite3_step(pStmt) ){
120692  rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
120693  if( rc!=SQLITE_OK ){
120694  vacuumFinalize(db, pStmt, pzErrMsg);
120695  return rc;
120696  }
120697  }
120698 
120699  return vacuumFinalize(db, pStmt, pzErrMsg);
120700 }
120701 
120702 /*
120703 ** The VACUUM command is used to clean up the database,
120704 ** collapse free space, etc. It is modelled after the VACUUM command
120705 ** in PostgreSQL. The VACUUM command works as follows:
120706 **
120707 ** (1) Create a new transient database file
120708 ** (2) Copy all content from the database being vacuumed into
120709 ** the new transient database file
120710 ** (3) Copy content from the transient database back into the
120711 ** original database.
120712 **
120713 ** The transient database requires temporary disk space approximately
120714 ** equal to the size of the original database. The copy operation of
120715 ** step (3) requires additional temporary disk space approximately equal
120716 ** to the size of the original database for the rollback journal.
120717 ** Hence, temporary disk space that is approximately 2x the size of the
120718 ** original database is required. Every page of the database is written
120719 ** approximately 3 times: Once for step (2) and twice for step (3).
120720 ** Two writes per page are required in step (3) because the original
120721 ** database content must be written into the rollback journal prior to
120722 ** overwriting the database with the vacuumed content.
120723 **
120724 ** Only 1x temporary space and only 1x writes would be required if
120725 ** the copy of step (3) were replaced by deleting the original database
120726 ** and renaming the transient database as the original. But that will
120727 ** not work if other processes are attached to the original database.
120728 ** And a power loss in between deleting the original and renaming the
120729 ** transient would cause the database file to appear to be deleted
120730 ** following reboot.
120731 */
120733  Vdbe *v = sqlite3GetVdbe(pParse);
120734  if( v ){
120735  sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
120736  sqlite3VdbeUsesBtree(v, 0);
120737  }
120738  return;
120739 }
120740 
120741 /*
120742 ** This routine implements the OP_Vacuum opcode of the VDBE.
120743 */
120744 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
120745  int rc = SQLITE_OK; /* Return code from service routines */
120746  Btree *pMain; /* The database being vacuumed */
120747  Btree *pTemp; /* The temporary database we vacuum into */
120748  char *zSql = 0; /* SQL statements */
120749  int saved_flags; /* Saved value of the db->flags */
120750  int saved_nChange; /* Saved value of db->nChange */
120751  int saved_nTotalChange; /* Saved value of db->nTotalChange */
120752  void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
120753  Db *pDb = 0; /* Database to detach at end of vacuum */
120754  int isMemDb; /* True if vacuuming a :memory: database */
120755  int nRes; /* Bytes of reserved space at the end of each page */
120756  int nDb; /* Number of attached databases */
120757 
120758  if( !db->autoCommit ){
120759  sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
120760  return SQLITE_ERROR;
120761  }
120762  if( db->nVdbeActive>1 ){
120763  sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
120764  return SQLITE_ERROR;
120765  }
120766 
120767  /* Save the current value of the database flags so that it can be
120768  ** restored before returning. Then set the writable-schema flag, and
120769  ** disable CHECK and foreign key constraints. */
120770  saved_flags = db->flags;
120771  saved_nChange = db->nChange;
120772  saved_nTotalChange = db->nTotalChange;
120773  saved_xTrace = db->xTrace;
120776  db->xTrace = 0;
120777 
120778  pMain = db->aDb[0].pBt;
120779  isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
120780 
120781  /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
120782  ** can be set to 'off' for this file, as it is not recovered if a crash
120783  ** occurs anyway. The integrity of the database is maintained by a
120784  ** (possibly synchronous) transaction opened on the main database before
120785  ** sqlite3BtreeCopyFile() is called.
120786  **
120787  ** An optimisation would be to use a non-journaled pager.
120788  ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
120789  ** that actually made the VACUUM run slower. Very little journalling
120790  ** actually occurs when doing a vacuum since the vacuum_db is initially
120791  ** empty. Only the journal header is written. Apparently it takes more
120792  ** time to parse and run the PRAGMA to turn journalling off than it does
120793  ** to write the journal header file.
120794  */
120795  nDb = db->nDb;
120796  if( sqlite3TempInMemory(db) ){
120797  zSql = "ATTACH ':memory:' AS vacuum_db;";
120798  }else{
120799  zSql = "ATTACH '' AS vacuum_db;";
120800  }
120801  rc = execSql(db, pzErrMsg, zSql);
120802  if( db->nDb>nDb ){
120803  pDb = &db->aDb[db->nDb-1];
120804  assert( strcmp(pDb->zName,"vacuum_db")==0 );
120805  }
120806  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120807  pTemp = db->aDb[db->nDb-1].pBt;
120808 
120809  /* The call to execSql() to attach the temp database has left the file
120810  ** locked (as there was more than one active statement when the transaction
120811  ** to read the schema was concluded. Unlock it here so that this doesn't
120812  ** cause problems for the call to BtreeSetPageSize() below. */
120813  sqlite3BtreeCommit(pTemp);
120814 
120815  nRes = sqlite3BtreeGetOptimalReserve(pMain);
120816 
120817  /* A VACUUM cannot change the pagesize of an encrypted database. */
120818 #ifdef SQLITE_HAS_CODEC
120819  if( db->nextPagesize ){
120820  extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
120821  int nKey;
120822  char *zKey;
120823  sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
120824  if( nKey ) db->nextPagesize = 0;
120825  }
120826 #endif
120827 
120828  rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
120829  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120830 
120831  /* Begin a transaction and take an exclusive lock on the main database
120832  ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
120833  ** to ensure that we do not try to change the page-size on a WAL database.
120834  */
120835  rc = execSql(db, pzErrMsg, "BEGIN;");
120836  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120837  rc = sqlite3BtreeBeginTrans(pMain, 2);
120838  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120839 
120840  /* Do not attempt to change the page size for a WAL database */
120842  ==PAGER_JOURNALMODE_WAL ){
120843  db->nextPagesize = 0;
120844  }
120845 
120846  if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
120847  || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
120848  || NEVER(db->mallocFailed)
120849  ){
120850  rc = SQLITE_NOMEM_BKPT;
120851  goto end_of_vacuum;
120852  }
120853 
120854 #ifndef SQLITE_OMIT_AUTOVACUUM
120855  sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
120856  sqlite3BtreeGetAutoVacuum(pMain));
120857 #endif
120858 
120859  /* Query the schema of the main database. Create a mirror schema
120860  ** in the temporary database.
120861  */
120862  rc = execExecSql(db, pzErrMsg,
120863  "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
120864  " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
120865  " AND coalesce(rootpage,1)>0"
120866  );
120867  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120868  rc = execExecSql(db, pzErrMsg,
120869  "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
120870  " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
120871  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120872  rc = execExecSql(db, pzErrMsg,
120873  "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
120874  " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
120875  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120876 
120877  /* Loop through the tables in the main database. For each, do
120878  ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
120879  ** the contents to the temporary database.
120880  */
120881  assert( (db->flags & SQLITE_Vacuum)==0 );
120882  db->flags |= SQLITE_Vacuum;
120883  rc = execExecSql(db, pzErrMsg,
120884  "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
120885  "|| ' SELECT * FROM main.' || quote(name) || ';'"
120886  "FROM main.sqlite_master "
120887  "WHERE type = 'table' AND name!='sqlite_sequence' "
120888  " AND coalesce(rootpage,1)>0"
120889  );
120890  assert( (db->flags & SQLITE_Vacuum)!=0 );
120891  db->flags &= ~SQLITE_Vacuum;
120892  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120893 
120894  /* Copy over the sequence table
120895  */
120896  rc = execExecSql(db, pzErrMsg,
120897  "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
120898  "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
120899  );
120900  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120901  rc = execExecSql(db, pzErrMsg,
120902  "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
120903  "|| ' SELECT * FROM main.' || quote(name) || ';' "
120904  "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
120905  );
120906  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120907 
120908 
120909  /* Copy the triggers, views, and virtual tables from the main database
120910  ** over to the temporary database. None of these objects has any
120911  ** associated storage, so all we have to do is copy their entries
120912  ** from the SQLITE_MASTER table.
120913  */
120914  rc = execSql(db, pzErrMsg,
120915  "INSERT INTO vacuum_db.sqlite_master "
120916  " SELECT type, name, tbl_name, rootpage, sql"
120917  " FROM main.sqlite_master"
120918  " WHERE type='view' OR type='trigger'"
120919  " OR (type='table' AND rootpage=0)"
120920  );
120921  if( rc ) goto end_of_vacuum;
120922 
120923  /* At this point, there is a write transaction open on both the
120924  ** vacuum database and the main database. Assuming no error occurs,
120925  ** both transactions are closed by this block - the main database
120926  ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
120927  ** call to sqlite3BtreeCommit().
120928  */
120929  {
120930  u32 meta;
120931  int i;
120932 
120933  /* This array determines which meta meta values are preserved in the
120934  ** vacuum. Even entries are the meta value number and odd entries
120935  ** are an increment to apply to the meta value after the vacuum.
120936  ** The increment is used to increase the schema cookie so that other
120937  ** connections to the same database will know to reread the schema.
120938  */
120939  static const unsigned char aCopy[] = {
120940  BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
120941  BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
120942  BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
120943  BTREE_USER_VERSION, 0, /* Preserve the user version */
120944  BTREE_APPLICATION_ID, 0, /* Preserve the application id */
120945  };
120946 
120947  assert( 1==sqlite3BtreeIsInTrans(pTemp) );
120948  assert( 1==sqlite3BtreeIsInTrans(pMain) );
120949 
120950  /* Copy Btree meta values */
120951  for(i=0; i<ArraySize(aCopy); i+=2){
120952  /* GetMeta() and UpdateMeta() cannot fail in this context because
120953  ** we already have page 1 loaded into cache and marked dirty. */
120954  sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
120955  rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
120956  if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
120957  }
120958 
120959  rc = sqlite3BtreeCopyFile(pMain, pTemp);
120960  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120961  rc = sqlite3BtreeCommit(pTemp);
120962  if( rc!=SQLITE_OK ) goto end_of_vacuum;
120963 #ifndef SQLITE_OMIT_AUTOVACUUM
120965 #endif
120966  }
120967 
120968  assert( rc==SQLITE_OK );
120969  rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
120970 
120971 end_of_vacuum:
120972  /* Restore the original value of db->flags */
120973  db->flags = saved_flags;
120974  db->nChange = saved_nChange;
120975  db->nTotalChange = saved_nTotalChange;
120976  db->xTrace = saved_xTrace;
120977  sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
120978 
120979  /* Currently there is an SQL level transaction open on the vacuum
120980  ** database. No locks are held on any other files (since the main file
120981  ** was committed at the btree level). So it safe to end the transaction
120982  ** by manually setting the autoCommit flag to true and detaching the
120983  ** vacuum database. The vacuum_db journal file is deleted when the pager
120984  ** is closed by the DETACH.
120985  */
120986  db->autoCommit = 1;
120987 
120988  if( pDb ){
120989  sqlite3BtreeClose(pDb->pBt);
120990  pDb->pBt = 0;
120991  pDb->pSchema = 0;
120992  }
120993 
120994  /* This both clears the schemas and reduces the size of the db->aDb[]
120995  ** array. */
120997 
120998  return rc;
120999 }
121000 
121001 #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
121002 
121003 /************** End of vacuum.c **********************************************/
121004 /************** Begin file vtab.c ********************************************/
121005 /*
121006 ** 2006 June 10
121007 **
121008 ** The author disclaims copyright to this source code. In place of
121009 ** a legal notice, here is a blessing:
121010 **
121011 ** May you do good and not evil.
121012 ** May you find forgiveness for yourself and forgive others.
121013 ** May you share freely, never taking more than you give.
121014 **
121015 *************************************************************************
121016 ** This file contains code used to help implement virtual tables.
121017 */
121018 #ifndef SQLITE_OMIT_VIRTUALTABLE
121019 /* #include "sqliteInt.h" */
121020 
121021 /*
121022 ** Before a virtual table xCreate() or xConnect() method is invoked, the
121023 ** sqlite3.pVtabCtx member variable is set to point to an instance of
121024 ** this struct allocated on the stack. It is used by the implementation of
121025 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
121026 ** are invoked only from within xCreate and xConnect methods.
121027 */
121028 struct VtabCtx {
121029  VTable *pVTable; /* The virtual table being constructed */
121030  Table *pTab; /* The Table object to which the virtual table belongs */
121031  VtabCtx *pPrior; /* Parent context (if any) */
121032  int bDeclared; /* True after sqlite3_declare_vtab() is called */
121033 };
121034 
121035 /*
121036 ** The actual function that does the work of creating a new module.
121037 ** This function implements the sqlite3_create_module() and
121038 ** sqlite3_create_module_v2() interfaces.
121039 */
121040 static int createModule(
121041  sqlite3 *db, /* Database in which module is registered */
121042  const char *zName, /* Name assigned to this module */
121043  const sqlite3_module *pModule, /* The definition of the module */
121044  void *pAux, /* Context pointer for xCreate/xConnect */
121045  void (*xDestroy)(void *) /* Module destructor function */
121046 ){
121047  int rc = SQLITE_OK;
121048  int nName;
121049 
121050  sqlite3_mutex_enter(db->mutex);
121051  nName = sqlite3Strlen30(zName);
121052  if( sqlite3HashFind(&db->aModule, zName) ){
121053  rc = SQLITE_MISUSE_BKPT;
121054  }else{
121055  Module *pMod;
121056  pMod = (Module *)sqlite3DbMallocRawNN(db, sizeof(Module) + nName + 1);
121057  if( pMod ){
121058  Module *pDel;
121059  char *zCopy = (char *)(&pMod[1]);
121060  memcpy(zCopy, zName, nName+1);
121061  pMod->zName = zCopy;
121062  pMod->pModule = pModule;
121063  pMod->pAux = pAux;
121064  pMod->xDestroy = xDestroy;
121065  pMod->pEpoTab = 0;
121066  pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
121067  assert( pDel==0 || pDel==pMod );
121068  if( pDel ){
121069  sqlite3OomFault(db);
121070  sqlite3DbFree(db, pDel);
121071  }
121072  }
121073  }
121074  rc = sqlite3ApiExit(db, rc);
121075  if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
121076 
121077  sqlite3_mutex_leave(db->mutex);
121078  return rc;
121079 }
121080 
121081 
121082 /*
121083 ** External API function used to create a new virtual-table module.
121084 */
121086  sqlite3 *db, /* Database in which module is registered */
121087  const char *zName, /* Name assigned to this module */
121088  const sqlite3_module *pModule, /* The definition of the module */
121089  void *pAux /* Context pointer for xCreate/xConnect */
121090 ){
121091 #ifdef SQLITE_ENABLE_API_ARMOR
121092  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121093 #endif
121094  return createModule(db, zName, pModule, pAux, 0);
121095 }
121096 
121097 /*
121098 ** External API function used to create a new virtual-table module.
121099 */
121101  sqlite3 *db, /* Database in which module is registered */
121102  const char *zName, /* Name assigned to this module */
121103  const sqlite3_module *pModule, /* The definition of the module */
121104  void *pAux, /* Context pointer for xCreate/xConnect */
121105  void (*xDestroy)(void *) /* Module destructor function */
121106 ){
121107 #ifdef SQLITE_ENABLE_API_ARMOR
121108  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
121109 #endif
121110  return createModule(db, zName, pModule, pAux, xDestroy);
121111 }
121112 
121113 /*
121114 ** Lock the virtual table so that it cannot be disconnected.
121115 ** Locks nest. Every lock should have a corresponding unlock.
121116 ** If an unlock is omitted, resources leaks will occur.
121117 **
121118 ** If a disconnect is attempted while a virtual table is locked,
121119 ** the disconnect is deferred until all locks have been removed.
121120 */
121122  pVTab->nRef++;
121123 }
121124 
121125 
121126 /*
121127 ** pTab is a pointer to a Table structure representing a virtual-table.
121128 ** Return a pointer to the VTable object used by connection db to access
121129 ** this virtual-table, if one has been created, or NULL otherwise.
121130 */
121132  VTable *pVtab;
121133  assert( IsVirtual(pTab) );
121134  for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
121135  return pVtab;
121136 }
121137 
121138 /*
121139 ** Decrement the ref-count on a virtual table object. When the ref-count
121140 ** reaches zero, call the xDisconnect() method to delete the object.
121141 */
121143  sqlite3 *db = pVTab->db;
121144 
121145  assert( db );
121146  assert( pVTab->nRef>0 );
121148 
121149  pVTab->nRef--;
121150  if( pVTab->nRef==0 ){
121151  sqlite3_vtab *p = pVTab->pVtab;
121152  if( p ){
121153  p->pModule->xDisconnect(p);
121154  }
121155  sqlite3DbFree(db, pVTab);
121156  }
121157 }
121158 
121159 /*
121160 ** Table p is a virtual table. This function moves all elements in the
121161 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
121162 ** database connections to be disconnected at the next opportunity.
121163 ** Except, if argument db is not NULL, then the entry associated with
121164 ** connection db is left in the p->pVTable list.
121165 */
121166 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
121167  VTable *pRet = 0;
121168  VTable *pVTable = p->pVTable;
121169  p->pVTable = 0;
121170 
121171  /* Assert that the mutex (if any) associated with the BtShared database
121172  ** that contains table p is held by the caller. See header comments
121173  ** above function sqlite3VtabUnlockList() for an explanation of why
121174  ** this makes it safe to access the sqlite3.pDisconnect list of any
121175  ** database connection that may have an entry in the p->pVTable list.
121176  */
121177  assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
121178 
121179  while( pVTable ){
121180  sqlite3 *db2 = pVTable->db;
121181  VTable *pNext = pVTable->pNext;
121182  assert( db2 );
121183  if( db2==db ){
121184  pRet = pVTable;
121185  p->pVTable = pRet;
121186  pRet->pNext = 0;
121187  }else{
121188  pVTable->pNext = db2->pDisconnect;
121189  db2->pDisconnect = pVTable;
121190  }
121191  pVTable = pNext;
121192  }
121193 
121194  assert( !db || pRet );
121195  return pRet;
121196 }
121197 
121198 /*
121199 ** Table *p is a virtual table. This function removes the VTable object
121200 ** for table *p associated with database connection db from the linked
121201 ** list in p->pVTab. It also decrements the VTable ref count. This is
121202 ** used when closing database connection db to free all of its VTable
121203 ** objects without disturbing the rest of the Schema object (which may
121204 ** be being used by other shared-cache connections).
121205 */
121207  VTable **ppVTab;
121208 
121209  assert( IsVirtual(p) );
121210  assert( sqlite3BtreeHoldsAllMutexes(db) );
121211  assert( sqlite3_mutex_held(db->mutex) );
121212 
121213  for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
121214  if( (*ppVTab)->db==db ){
121215  VTable *pVTab = *ppVTab;
121216  *ppVTab = pVTab->pNext;
121217  sqlite3VtabUnlock(pVTab);
121218  break;
121219  }
121220  }
121221 }
121222 
121223 
121224 /*
121225 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
121226 **
121227 ** This function may only be called when the mutexes associated with all
121228 ** shared b-tree databases opened using connection db are held by the
121229 ** caller. This is done to protect the sqlite3.pDisconnect list. The
121230 ** sqlite3.pDisconnect list is accessed only as follows:
121231 **
121232 ** 1) By this function. In this case, all BtShared mutexes and the mutex
121233 ** associated with the database handle itself must be held.
121234 **
121235 ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
121236 ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
121237 ** associated with the database the virtual table is stored in is held
121238 ** or, if the virtual table is stored in a non-sharable database, then
121239 ** the database handle mutex is held.
121240 **
121241 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
121242 ** by multiple threads. It is thread-safe.
121243 */
121245  VTable *p = db->pDisconnect;
121246  db->pDisconnect = 0;
121247 
121248  assert( sqlite3BtreeHoldsAllMutexes(db) );
121249  assert( sqlite3_mutex_held(db->mutex) );
121250 
121251  if( p ){
121253  do {
121254  VTable *pNext = p->pNext;
121255  sqlite3VtabUnlock(p);
121256  p = pNext;
121257  }while( p );
121258  }
121259 }
121260 
121261 /*
121262 ** Clear any and all virtual-table information from the Table record.
121263 ** This routine is called, for example, just before deleting the Table
121264 ** record.
121265 **
121266 ** Since it is a virtual-table, the Table structure contains a pointer
121267 ** to the head of a linked list of VTable structures. Each VTable
121268 ** structure is associated with a single sqlite3* user of the schema.
121269 ** The reference count of the VTable structure associated with database
121270 ** connection db is decremented immediately (which may lead to the
121271 ** structure being xDisconnected and free). Any other VTable structures
121272 ** in the list are moved to the sqlite3.pDisconnect list of the associated
121273 ** database connection.
121274 */
121276  if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
121277  if( p->azModuleArg ){
121278  int i;
121279  for(i=0; i<p->nModuleArg; i++){
121280  if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
121281  }
121282  sqlite3DbFree(db, p->azModuleArg);
121283  }
121284 }
121285 
121286 /*
121287 ** Add a new module argument to pTable->azModuleArg[].
121288 ** The string is not copied - the pointer is stored. The
121289 ** string will be freed automatically when the table is
121290 ** deleted.
121291 */
121292 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
121293  int nBytes = sizeof(char *)*(2+pTable->nModuleArg);
121294  char **azModuleArg;
121295  azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
121296  if( azModuleArg==0 ){
121297  sqlite3DbFree(db, zArg);
121298  }else{
121299  int i = pTable->nModuleArg++;
121300  azModuleArg[i] = zArg;
121301  azModuleArg[i+1] = 0;
121302  pTable->azModuleArg = azModuleArg;
121303  }
121304 }
121305 
121306 /*
121307 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
121308 ** statement. The module name has been parsed, but the optional list
121309 ** of parameters that follow the module name are still pending.
121310 */
121312  Parse *pParse, /* Parsing context */
121313  Token *pName1, /* Name of new table, or database name */
121314  Token *pName2, /* Name of new table or NULL */
121315  Token *pModuleName, /* Name of the module for the virtual table */
121316  int ifNotExists /* No error if the table already exists */
121317 ){
121318  int iDb; /* The database the table is being created in */
121319  Table *pTable; /* The new virtual table */
121320  sqlite3 *db; /* Database connection */
121321 
121322  sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
121323  pTable = pParse->pNewTable;
121324  if( pTable==0 ) return;
121325  assert( 0==pTable->pIndex );
121326 
121327  db = pParse->db;
121328  iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
121329  assert( iDb>=0 );
121330 
121331  pTable->tabFlags |= TF_Virtual;
121332  pTable->nModuleArg = 0;
121333  addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
121334  addModuleArgument(db, pTable, 0);
121335  addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
121336  assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
121337  || (pParse->sNameToken.z==pName1->z && pName2->z==0)
121338  );
121339  pParse->sNameToken.n = (int)(
121340  &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
121341  );
121342 
121343 #ifndef SQLITE_OMIT_AUTHORIZATION
121344  /* Creating a virtual table invokes the authorization callback twice.
121345  ** The first invocation, to obtain permission to INSERT a row into the
121346  ** sqlite_master table, has already been made by sqlite3StartTable().
121347  ** The second call, to obtain permission to create the table, is made now.
121348  */
121349  if( pTable->azModuleArg ){
121350  sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
121351  pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
121352  }
121353 #endif
121354 }
121355 
121356 /*
121357 ** This routine takes the module argument that has been accumulating
121358 ** in pParse->zArg[] and appends it to the list of arguments on the
121359 ** virtual table currently under construction in pParse->pTable.
121360 */
121361 static void addArgumentToVtab(Parse *pParse){
121362  if( pParse->sArg.z && pParse->pNewTable ){
121363  const char *z = (const char*)pParse->sArg.z;
121364  int n = pParse->sArg.n;
121365  sqlite3 *db = pParse->db;
121366  addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
121367  }
121368 }
121369 
121370 /*
121371 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
121372 ** has been completely parsed.
121373 */
121375  Table *pTab = pParse->pNewTable; /* The table being constructed */
121376  sqlite3 *db = pParse->db; /* The database connection */
121377 
121378  if( pTab==0 ) return;
121379  addArgumentToVtab(pParse);
121380  pParse->sArg.z = 0;
121381  if( pTab->nModuleArg<1 ) return;
121382 
121383  /* If the CREATE VIRTUAL TABLE statement is being entered for the
121384  ** first time (in other words if the virtual table is actually being
121385  ** created now instead of just being read out of sqlite_master) then
121386  ** do additional initialization work and store the statement text
121387  ** in the sqlite_master table.
121388  */
121389  if( !db->init.busy ){
121390  char *zStmt;
121391  char *zWhere;
121392  int iDb;
121393  int iReg;
121394  Vdbe *v;
121395 
121396  /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
121397  if( pEnd ){
121398  pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
121399  }
121400  zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
121401 
121402  /* A slot for the record has already been allocated in the
121403  ** SQLITE_MASTER table. We just need to update that slot with all
121404  ** the information we've collected.
121405  **
121406  ** The VM register number pParse->regRowid holds the rowid of an
121407  ** entry in the sqlite_master table tht was created for this vtab
121408  ** by sqlite3StartTable().
121409  */
121410  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121411  sqlite3NestedParse(pParse,
121412  "UPDATE %Q.%s "
121413  "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
121414  "WHERE rowid=#%d",
121415  db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
121416  pTab->zName,
121417  pTab->zName,
121418  zStmt,
121419  pParse->regRowid
121420  );
121421  sqlite3DbFree(db, zStmt);
121422  v = sqlite3GetVdbe(pParse);
121423  sqlite3ChangeCookie(pParse, iDb);
121424 
121425  sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
121426  zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
121427  sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
121428 
121429  iReg = ++pParse->nMem;
121430  sqlite3VdbeLoadString(v, iReg, pTab->zName);
121431  sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
121432  }
121433 
121434  /* If we are rereading the sqlite_master table create the in-memory
121435  ** record of the table. The xConnect() method is not called until
121436  ** the first time the virtual table is used in an SQL statement. This
121437  ** allows a schema that contains virtual tables to be loaded before
121438  ** the required virtual table implementations are registered. */
121439  else {
121440  Table *pOld;
121441  Schema *pSchema = pTab->pSchema;
121442  const char *zName = pTab->zName;
121443  assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
121444  pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
121445  if( pOld ){
121446  sqlite3OomFault(db);
121447  assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
121448  return;
121449  }
121450  pParse->pNewTable = 0;
121451  }
121452 }
121453 
121454 /*
121455 ** The parser calls this routine when it sees the first token
121456 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
121457 */
121459  addArgumentToVtab(pParse);
121460  pParse->sArg.z = 0;
121461  pParse->sArg.n = 0;
121462 }
121463 
121464 /*
121465 ** The parser calls this routine for each token after the first token
121466 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
121467 */
121469  Token *pArg = &pParse->sArg;
121470  if( pArg->z==0 ){
121471  pArg->z = p->z;
121472  pArg->n = p->n;
121473  }else{
121474  assert(pArg->z <= p->z);
121475  pArg->n = (int)(&p->z[p->n] - pArg->z);
121476  }
121477 }
121478 
121479 /*
121480 ** Invoke a virtual table constructor (either xCreate or xConnect). The
121481 ** pointer to the function to invoke is passed as the fourth parameter
121482 ** to this procedure.
121483 */
121485  sqlite3 *db,
121486  Table *pTab,
121487  Module *pMod,
121488  int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
121489  char **pzErr
121490 ){
121491  VtabCtx sCtx;
121492  VTable *pVTable;
121493  int rc;
121494  const char *const*azArg = (const char *const*)pTab->azModuleArg;
121495  int nArg = pTab->nModuleArg;
121496  char *zErr = 0;
121497  char *zModuleName;
121498  int iDb;
121499  VtabCtx *pCtx;
121500 
121501  /* Check that the virtual-table is not already being initialized */
121502  for(pCtx=db->pVtabCtx; pCtx; pCtx=pCtx->pPrior){
121503  if( pCtx->pTab==pTab ){
121504  *pzErr = sqlite3MPrintf(db,
121505  "vtable constructor called recursively: %s", pTab->zName
121506  );
121507  return SQLITE_LOCKED;
121508  }
121509  }
121510 
121511  zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
121512  if( !zModuleName ){
121513  return SQLITE_NOMEM_BKPT;
121514  }
121515 
121516  pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
121517  if( !pVTable ){
121518  sqlite3DbFree(db, zModuleName);
121519  return SQLITE_NOMEM_BKPT;
121520  }
121521  pVTable->db = db;
121522  pVTable->pMod = pMod;
121523 
121524  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
121525  pTab->azModuleArg[1] = db->aDb[iDb].zName;
121526 
121527  /* Invoke the virtual table constructor */
121528  assert( &db->pVtabCtx );
121529  assert( xConstruct );
121530  sCtx.pTab = pTab;
121531  sCtx.pVTable = pVTable;
121532  sCtx.pPrior = db->pVtabCtx;
121533  sCtx.bDeclared = 0;
121534  db->pVtabCtx = &sCtx;
121535  rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
121536  db->pVtabCtx = sCtx.pPrior;
121537  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
121538  assert( sCtx.pTab==pTab );
121539 
121540  if( SQLITE_OK!=rc ){
121541  if( zErr==0 ){
121542  *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
121543  }else {
121544  *pzErr = sqlite3MPrintf(db, "%s", zErr);
121545  sqlite3_free(zErr);
121546  }
121547  sqlite3DbFree(db, pVTable);
121548  }else if( ALWAYS(pVTable->pVtab) ){
121549  /* Justification of ALWAYS(): A correct vtab constructor must allocate
121550  ** the sqlite3_vtab object if successful. */
121551  memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
121552  pVTable->pVtab->pModule = pMod->pModule;
121553  pVTable->nRef = 1;
121554  if( sCtx.bDeclared==0 ){
121555  const char *zFormat = "vtable constructor did not declare schema: %s";
121556  *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
121557  sqlite3VtabUnlock(pVTable);
121558  rc = SQLITE_ERROR;
121559  }else{
121560  int iCol;
121561  u8 oooHidden = 0;
121562  /* If everything went according to plan, link the new VTable structure
121563  ** into the linked list headed by pTab->pVTable. Then loop through the
121564  ** columns of the table to see if any of them contain the token "hidden".
121565  ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
121566  ** the type string. */
121567  pVTable->pNext = pTab->pVTable;
121568  pTab->pVTable = pVTable;
121569 
121570  for(iCol=0; iCol<pTab->nCol; iCol++){
121571  char *zType = sqlite3ColumnType(&pTab->aCol[iCol], "");
121572  int nType;
121573  int i = 0;
121574  nType = sqlite3Strlen30(zType);
121575  for(i=0; i<nType; i++){
121576  if( 0==sqlite3StrNICmp("hidden", &zType[i], 6)
121577  && (i==0 || zType[i-1]==' ')
121578  && (zType[i+6]=='\0' || zType[i+6]==' ')
121579  ){
121580  break;
121581  }
121582  }
121583  if( i<nType ){
121584  int j;
121585  int nDel = 6 + (zType[i+6] ? 1 : 0);
121586  for(j=i; (j+nDel)<=nType; j++){
121587  zType[j] = zType[j+nDel];
121588  }
121589  if( zType[i]=='\0' && i>0 ){
121590  assert(zType[i-1]==' ');
121591  zType[i-1] = '\0';
121592  }
121593  pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
121594  oooHidden = TF_OOOHidden;
121595  }else{
121596  pTab->tabFlags |= oooHidden;
121597  }
121598  }
121599  }
121600  }
121601 
121602  sqlite3DbFree(db, zModuleName);
121603  return rc;
121604 }
121605 
121606 /*
121607 ** This function is invoked by the parser to call the xConnect() method
121608 ** of the virtual table pTab. If an error occurs, an error code is returned
121609 ** and an error left in pParse.
121610 **
121611 ** This call is a no-op if table pTab is not a virtual table.
121612 */
121614  sqlite3 *db = pParse->db;
121615  const char *zMod;
121616  Module *pMod;
121617  int rc;
121618 
121619  assert( pTab );
121620  if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
121621  return SQLITE_OK;
121622  }
121623 
121624  /* Locate the required virtual table module */
121625  zMod = pTab->azModuleArg[0];
121626  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
121627 
121628  if( !pMod ){
121629  const char *zModule = pTab->azModuleArg[0];
121630  sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
121631  rc = SQLITE_ERROR;
121632  }else{
121633  char *zErr = 0;
121634  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
121635  if( rc!=SQLITE_OK ){
121636  sqlite3ErrorMsg(pParse, "%s", zErr);
121637  }
121638  sqlite3DbFree(db, zErr);
121639  }
121640 
121641  return rc;
121642 }
121643 /*
121644 ** Grow the db->aVTrans[] array so that there is room for at least one
121645 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
121646 */
121647 static int growVTrans(sqlite3 *db){
121648  const int ARRAY_INCR = 5;
121649 
121650  /* Grow the sqlite3.aVTrans array if required */
121651  if( (db->nVTrans%ARRAY_INCR)==0 ){
121652  VTable **aVTrans;
121653  int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
121654  aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
121655  if( !aVTrans ){
121656  return SQLITE_NOMEM_BKPT;
121657  }
121658  memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
121659  db->aVTrans = aVTrans;
121660  }
121661 
121662  return SQLITE_OK;
121663 }
121664 
121665 /*
121666 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
121667 ** have already been reserved using growVTrans().
121668 */
121669 static void addToVTrans(sqlite3 *db, VTable *pVTab){
121670  /* Add pVtab to the end of sqlite3.aVTrans */
121671  db->aVTrans[db->nVTrans++] = pVTab;
121672  sqlite3VtabLock(pVTab);
121673 }
121674 
121675 /*
121676 ** This function is invoked by the vdbe to call the xCreate method
121677 ** of the virtual table named zTab in database iDb.
121678 **
121679 ** If an error occurs, *pzErr is set to point an an English language
121680 ** description of the error and an SQLITE_XXX error code is returned.
121681 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
121682 */
121683 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
121684  int rc = SQLITE_OK;
121685  Table *pTab;
121686  Module *pMod;
121687  const char *zMod;
121688 
121689  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
121690  assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
121691 
121692  /* Locate the required virtual table module */
121693  zMod = pTab->azModuleArg[0];
121694  pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
121695 
121696  /* If the module has been registered and includes a Create method,
121697  ** invoke it now. If the module has not been registered, return an
121698  ** error. Otherwise, do nothing.
121699  */
121700  if( pMod==0 || pMod->pModule->xCreate==0 || pMod->pModule->xDestroy==0 ){
121701  *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
121702  rc = SQLITE_ERROR;
121703  }else{
121704  rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
121705  }
121706 
121707  /* Justification of ALWAYS(): The xConstructor method is required to
121708  ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
121709  if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
121710  rc = growVTrans(db);
121711  if( rc==SQLITE_OK ){
121712  addToVTrans(db, sqlite3GetVTable(db, pTab));
121713  }
121714  }
121715 
121716  return rc;
121717 }
121718 
121719 /*
121720 ** This function is used to set the schema of a virtual table. It is only
121721 ** valid to call this function from within the xCreate() or xConnect() of a
121722 ** virtual table module.
121723 */
121724 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
121725  VtabCtx *pCtx;
121726  Parse *pParse;
121727  int rc = SQLITE_OK;
121728  Table *pTab;
121729  char *zErr = 0;
121730 
121731 #ifdef SQLITE_ENABLE_API_ARMOR
121732  if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
121733  return SQLITE_MISUSE_BKPT;
121734  }
121735 #endif
121736  sqlite3_mutex_enter(db->mutex);
121737  pCtx = db->pVtabCtx;
121738  if( !pCtx || pCtx->bDeclared ){
121740  sqlite3_mutex_leave(db->mutex);
121741  return SQLITE_MISUSE_BKPT;
121742  }
121743  pTab = pCtx->pTab;
121744  assert( (pTab->tabFlags & TF_Virtual)!=0 );
121745 
121746  pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
121747  if( pParse==0 ){
121748  rc = SQLITE_NOMEM_BKPT;
121749  }else{
121750  pParse->declareVtab = 1;
121751  pParse->db = db;
121752  pParse->nQueryLoop = 1;
121753 
121754  if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
121755  && pParse->pNewTable
121756  && !db->mallocFailed
121757  && !pParse->pNewTable->pSelect
121758  && (pParse->pNewTable->tabFlags & TF_Virtual)==0
121759  ){
121760  if( !pTab->aCol ){
121761  pTab->aCol = pParse->pNewTable->aCol;
121762  pTab->nCol = pParse->pNewTable->nCol;
121763  pParse->pNewTable->nCol = 0;
121764  pParse->pNewTable->aCol = 0;
121765  }
121766  pCtx->bDeclared = 1;
121767  }else{
121768  sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
121769  sqlite3DbFree(db, zErr);
121770  rc = SQLITE_ERROR;
121771  }
121772  pParse->declareVtab = 0;
121773 
121774  if( pParse->pVdbe ){
121775  sqlite3VdbeFinalize(pParse->pVdbe);
121776  }
121777  sqlite3DeleteTable(db, pParse->pNewTable);
121778  sqlite3ParserReset(pParse);
121779  sqlite3StackFree(db, pParse);
121780  }
121781 
121782  assert( (rc&0xff)==rc );
121783  rc = sqlite3ApiExit(db, rc);
121784  sqlite3_mutex_leave(db->mutex);
121785  return rc;
121786 }
121787 
121788 /*
121789 ** This function is invoked by the vdbe to call the xDestroy method
121790 ** of the virtual table named zTab in database iDb. This occurs
121791 ** when a DROP TABLE is mentioned.
121792 **
121793 ** This call is a no-op if zTab is not a virtual table.
121794 */
121795 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
121796  int rc = SQLITE_OK;
121797  Table *pTab;
121798 
121799  pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
121800  if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
121801  VTable *p;
121802  int (*xDestroy)(sqlite3_vtab *);
121803  for(p=pTab->pVTable; p; p=p->pNext){
121804  assert( p->pVtab );
121805  if( p->pVtab->nRef>0 ){
121806  return SQLITE_LOCKED;
121807  }
121808  }
121809  p = vtabDisconnectAll(db, pTab);
121810  xDestroy = p->pMod->pModule->xDestroy;
121811  assert( xDestroy!=0 ); /* Checked before the virtual table is created */
121812  rc = xDestroy(p->pVtab);
121813  /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
121814  if( rc==SQLITE_OK ){
121815  assert( pTab->pVTable==p && p->pNext==0 );
121816  p->pVtab = 0;
121817  pTab->pVTable = 0;
121818  sqlite3VtabUnlock(p);
121819  }
121820  }
121821 
121822  return rc;
121823 }
121824 
121825 /*
121826 ** This function invokes either the xRollback or xCommit method
121827 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
121828 ** called is identified by the second argument, "offset", which is
121829 ** the offset of the method to call in the sqlite3_module structure.
121830 **
121831 ** The array is cleared after invoking the callbacks.
121832 */
121833 static void callFinaliser(sqlite3 *db, int offset){
121834  int i;
121835  if( db->aVTrans ){
121836  VTable **aVTrans = db->aVTrans;
121837  db->aVTrans = 0;
121838  for(i=0; i<db->nVTrans; i++){
121839  VTable *pVTab = aVTrans[i];
121840  sqlite3_vtab *p = pVTab->pVtab;
121841  if( p ){
121842  int (*x)(sqlite3_vtab *);
121843  x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
121844  if( x ) x(p);
121845  }
121846  pVTab->iSavepoint = 0;
121847  sqlite3VtabUnlock(pVTab);
121848  }
121849  sqlite3DbFree(db, aVTrans);
121850  db->nVTrans = 0;
121851  }
121852 }
121853 
121854 /*
121855 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
121856 ** array. Return the error code for the first error that occurs, or
121857 ** SQLITE_OK if all xSync operations are successful.
121858 **
121859 ** If an error message is available, leave it in p->zErrMsg.
121860 */
121861 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
121862  int i;
121863  int rc = SQLITE_OK;
121864  VTable **aVTrans = db->aVTrans;
121865 
121866  db->aVTrans = 0;
121867  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
121868  int (*x)(sqlite3_vtab *);
121869  sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
121870  if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
121871  rc = x(pVtab);
121872  sqlite3VtabImportErrmsg(p, pVtab);
121873  }
121874  }
121875  db->aVTrans = aVTrans;
121876  return rc;
121877 }
121878 
121879 /*
121880 ** Invoke the xRollback method of all virtual tables in the
121881 ** sqlite3.aVTrans array. Then clear the array itself.
121882 */
121884  callFinaliser(db, offsetof(sqlite3_module,xRollback));
121885  return SQLITE_OK;
121886 }
121887 
121888 /*
121889 ** Invoke the xCommit method of all virtual tables in the
121890 ** sqlite3.aVTrans array. Then clear the array itself.
121891 */
121893  callFinaliser(db, offsetof(sqlite3_module,xCommit));
121894  return SQLITE_OK;
121895 }
121896 
121897 /*
121898 ** If the virtual table pVtab supports the transaction interface
121899 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
121900 ** not currently open, invoke the xBegin method now.
121901 **
121902 ** If the xBegin call is successful, place the sqlite3_vtab pointer
121903 ** in the sqlite3.aVTrans array.
121904 */
121905 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
121906  int rc = SQLITE_OK;
121907  const sqlite3_module *pModule;
121908 
121909  /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
121910  ** than zero, then this function is being called from within a
121911  ** virtual module xSync() callback. It is illegal to write to
121912  ** virtual module tables in this case, so return SQLITE_LOCKED.
121913  */
121914  if( sqlite3VtabInSync(db) ){
121915  return SQLITE_LOCKED;
121916  }
121917  if( !pVTab ){
121918  return SQLITE_OK;
121919  }
121920  pModule = pVTab->pVtab->pModule;
121921 
121922  if( pModule->xBegin ){
121923  int i;
121924 
121925  /* If pVtab is already in the aVTrans array, return early */
121926  for(i=0; i<db->nVTrans; i++){
121927  if( db->aVTrans[i]==pVTab ){
121928  return SQLITE_OK;
121929  }
121930  }
121931 
121932  /* Invoke the xBegin method. If successful, add the vtab to the
121933  ** sqlite3.aVTrans[] array. */
121934  rc = growVTrans(db);
121935  if( rc==SQLITE_OK ){
121936  rc = pModule->xBegin(pVTab->pVtab);
121937  if( rc==SQLITE_OK ){
121938  int iSvpt = db->nStatement + db->nSavepoint;
121939  addToVTrans(db, pVTab);
121940  if( iSvpt ) rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, iSvpt-1);
121941  }
121942  }
121943  }
121944  return rc;
121945 }
121946 
121947 /*
121948 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
121949 ** virtual tables that currently have an open transaction. Pass iSavepoint
121950 ** as the second argument to the virtual table method invoked.
121951 **
121952 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
121953 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
121954 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
121955 ** an open transaction is invoked.
121956 **
121957 ** If any virtual table method returns an error code other than SQLITE_OK,
121958 ** processing is abandoned and the error returned to the caller of this
121959 ** function immediately. If all calls to virtual table methods are successful,
121960 ** SQLITE_OK is returned.
121961 */
121962 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
121963  int rc = SQLITE_OK;
121964 
121966  assert( iSavepoint>=-1 );
121967  if( db->aVTrans ){
121968  int i;
121969  for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
121970  VTable *pVTab = db->aVTrans[i];
121971  const sqlite3_module *pMod = pVTab->pMod->pModule;
121972  if( pVTab->pVtab && pMod->iVersion>=2 ){
121973  int (*xMethod)(sqlite3_vtab *, int);
121974  switch( op ){
121975  case SAVEPOINT_BEGIN:
121976  xMethod = pMod->xSavepoint;
121977  pVTab->iSavepoint = iSavepoint+1;
121978  break;
121979  case SAVEPOINT_ROLLBACK:
121980  xMethod = pMod->xRollbackTo;
121981  break;
121982  default:
121983  xMethod = pMod->xRelease;
121984  break;
121985  }
121986  if( xMethod && pVTab->iSavepoint>iSavepoint ){
121987  rc = xMethod(pVTab->pVtab, iSavepoint);
121988  }
121989  }
121990  }
121991  }
121992  return rc;
121993 }
121994 
121995 /*
121996 ** The first parameter (pDef) is a function implementation. The
121997 ** second parameter (pExpr) is the first argument to this function.
121998 ** If pExpr is a column in a virtual table, then let the virtual
121999 ** table implementation have an opportunity to overload the function.
122000 **
122001 ** This routine is used to allow virtual table implementations to
122002 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
122003 **
122004 ** Return either the pDef argument (indicating no change) or a
122005 ** new FuncDef structure that is marked as ephemeral using the
122006 ** SQLITE_FUNC_EPHEM flag.
122007 */
122009  sqlite3 *db, /* Database connection for reporting malloc problems */
122010  FuncDef *pDef, /* Function to possibly overload */
122011  int nArg, /* Number of arguments to the function */
122012  Expr *pExpr /* First argument to the function */
122013 ){
122014  Table *pTab;
122015  sqlite3_vtab *pVtab;
122016  sqlite3_module *pMod;
122017  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
122018  void *pArg = 0;
122019  FuncDef *pNew;
122020  int rc = 0;
122021  char *zLowerName;
122022  unsigned char *z;
122023 
122024 
122025  /* Check to see the left operand is a column in a virtual table */
122026  if( NEVER(pExpr==0) ) return pDef;
122027  if( pExpr->op!=TK_COLUMN ) return pDef;
122028  pTab = pExpr->pTab;
122029  if( NEVER(pTab==0) ) return pDef;
122030  if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
122031  pVtab = sqlite3GetVTable(db, pTab)->pVtab;
122032  assert( pVtab!=0 );
122033  assert( pVtab->pModule!=0 );
122034  pMod = (sqlite3_module *)pVtab->pModule;
122035  if( pMod->xFindFunction==0 ) return pDef;
122036 
122037  /* Call the xFindFunction method on the virtual table implementation
122038  ** to see if the implementation wants to overload this function
122039  */
122040  zLowerName = sqlite3DbStrDup(db, pDef->zName);
122041  if( zLowerName ){
122042  for(z=(unsigned char*)zLowerName; *z; z++){
122043  *z = sqlite3UpperToLower[*z];
122044  }
122045  rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xSFunc, &pArg);
122046  sqlite3DbFree(db, zLowerName);
122047  }
122048  if( rc==0 ){
122049  return pDef;
122050  }
122051 
122052  /* Create a new ephemeral function definition for the overloaded
122053  ** function */
122054  pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
122055  + sqlite3Strlen30(pDef->zName) + 1);
122056  if( pNew==0 ){
122057  return pDef;
122058  }
122059  *pNew = *pDef;
122060  pNew->zName = (const char*)&pNew[1];
122061  memcpy((char*)&pNew[1], pDef->zName, sqlite3Strlen30(pDef->zName)+1);
122062  pNew->xSFunc = xSFunc;
122063  pNew->pUserData = pArg;
122064  pNew->funcFlags |= SQLITE_FUNC_EPHEM;
122065  return pNew;
122066 }
122067 
122068 /*
122069 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
122070 ** array so that an OP_VBegin will get generated for it. Add pTab to the
122071 ** array if it is missing. If pTab is already in the array, this routine
122072 ** is a no-op.
122073 */
122075  Parse *pToplevel = sqlite3ParseToplevel(pParse);
122076  int i, n;
122077  Table **apVtabLock;
122078 
122079  assert( IsVirtual(pTab) );
122080  for(i=0; i<pToplevel->nVtabLock; i++){
122081  if( pTab==pToplevel->apVtabLock[i] ) return;
122082  }
122083  n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
122084  apVtabLock = sqlite3_realloc64(pToplevel->apVtabLock, n);
122085  if( apVtabLock ){
122086  pToplevel->apVtabLock = apVtabLock;
122087  pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
122088  }else{
122089  sqlite3OomFault(pToplevel->db);
122090  }
122091 }
122092 
122093 /*
122094 ** Check to see if virtual tale module pMod can be have an eponymous
122095 ** virtual table instance. If it can, create one if one does not already
122096 ** exist. Return non-zero if the eponymous virtual table instance exists
122097 ** when this routine returns, and return zero if it does not exist.
122098 **
122099 ** An eponymous virtual table instance is one that is named after its
122100 ** module, and more importantly, does not require a CREATE VIRTUAL TABLE
122101 ** statement in order to come into existance. Eponymous virtual table
122102 ** instances always exist. They cannot be DROP-ed.
122103 **
122104 ** Any virtual table module for which xConnect and xCreate are the same
122105 ** method can have an eponymous virtual table instance.
122106 */
122108  const sqlite3_module *pModule = pMod->pModule;
122109  Table *pTab;
122110  char *zErr = 0;
122111  int nName;
122112  int rc;
122113  sqlite3 *db = pParse->db;
122114  if( pMod->pEpoTab ) return 1;
122115  if( pModule->xCreate!=0 && pModule->xCreate!=pModule->xConnect ) return 0;
122116  nName = sqlite3Strlen30(pMod->zName) + 1;
122117  pTab = sqlite3DbMallocZero(db, sizeof(Table) + nName);
122118  if( pTab==0 ) return 0;
122119  pMod->pEpoTab = pTab;
122120  pTab->zName = (char*)&pTab[1];
122121  memcpy(pTab->zName, pMod->zName, nName);
122122  pTab->nRef = 1;
122123  pTab->pSchema = db->aDb[0].pSchema;
122124  pTab->tabFlags |= TF_Virtual;
122125  pTab->nModuleArg = 0;
122126  pTab->iPKey = -1;
122127  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122128  addModuleArgument(db, pTab, 0);
122129  addModuleArgument(db, pTab, sqlite3DbStrDup(db, pTab->zName));
122130  rc = vtabCallConstructor(db, pTab, pMod, pModule->xConnect, &zErr);
122131  if( rc ){
122132  sqlite3ErrorMsg(pParse, "%s", zErr);
122133  sqlite3DbFree(db, zErr);
122134  sqlite3VtabEponymousTableClear(db, pMod);
122135  return 0;
122136  }
122137  return 1;
122138 }
122139 
122140 /*
122141 ** Erase the eponymous virtual table instance associated with
122142 ** virtual table module pMod, if it exists.
122143 */
122145  Table *pTab = pMod->pEpoTab;
122146  if( pTab!=0 ){
122147  sqlite3DeleteColumnNames(db, pTab);
122148  sqlite3VtabClear(db, pTab);
122149  sqlite3DbFree(db, pTab);
122150  pMod->pEpoTab = 0;
122151  }
122152 }
122153 
122154 /*
122155 ** Return the ON CONFLICT resolution mode in effect for the virtual
122156 ** table update operation currently in progress.
122157 **
122158 ** The results of this routine are undefined unless it is called from
122159 ** within an xUpdate method.
122160 */
122162  static const unsigned char aMap[] = {
122164  };
122165 #ifdef SQLITE_ENABLE_API_ARMOR
122166  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122167 #endif
122168  assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
122169  assert( OE_Ignore==4 && OE_Replace==5 );
122170  assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
122171  return (int)aMap[db->vtabOnConflict-1];
122172 }
122173 
122174 /*
122175 ** Call from within the xCreate() or xConnect() methods to provide
122176 ** the SQLite core with additional information about the behavior
122177 ** of the virtual table being implemented.
122178 */
122179 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
122180  va_list ap;
122181  int rc = SQLITE_OK;
122182 
122183 #ifdef SQLITE_ENABLE_API_ARMOR
122184  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
122185 #endif
122186  sqlite3_mutex_enter(db->mutex);
122187  va_start(ap, op);
122188  switch( op ){
122190  VtabCtx *p = db->pVtabCtx;
122191  if( !p ){
122192  rc = SQLITE_MISUSE_BKPT;
122193  }else{
122194  assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
122195  p->pVTable->bConstraint = (u8)va_arg(ap, int);
122196  }
122197  break;
122198  }
122199  default:
122200  rc = SQLITE_MISUSE_BKPT;
122201  break;
122202  }
122203  va_end(ap);
122204 
122205  if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
122206  sqlite3_mutex_leave(db->mutex);
122207  return rc;
122208 }
122209 
122210 #endif /* SQLITE_OMIT_VIRTUALTABLE */
122211 
122212 /************** End of vtab.c ************************************************/
122213 /************** Begin file wherecode.c ***************************************/
122214 /*
122215 ** 2015-06-06
122216 **
122217 ** The author disclaims copyright to this source code. In place of
122218 ** a legal notice, here is a blessing:
122219 **
122220 ** May you do good and not evil.
122221 ** May you find forgiveness for yourself and forgive others.
122222 ** May you share freely, never taking more than you give.
122223 **
122224 *************************************************************************
122225 ** This module contains C code that generates VDBE code used to process
122226 ** the WHERE clause of SQL statements.
122227 **
122228 ** This file was split off from where.c on 2015-06-06 in order to reduce the
122229 ** size of where.c and make it easier to edit. This file contains the routines
122230 ** that actually generate the bulk of the WHERE loop code. The original where.c
122231 ** file retains the code that does query planning and analysis.
122232 */
122233 /* #include "sqliteInt.h" */
122234 /************** Include whereInt.h in the middle of wherecode.c **************/
122235 /************** Begin file whereInt.h ****************************************/
122236 /*
122237 ** 2013-11-12
122238 **
122239 ** The author disclaims copyright to this source code. In place of
122240 ** a legal notice, here is a blessing:
122241 **
122242 ** May you do good and not evil.
122243 ** May you find forgiveness for yourself and forgive others.
122244 ** May you share freely, never taking more than you give.
122245 **
122246 *************************************************************************
122247 **
122248 ** This file contains structure and macro definitions for the query
122249 ** planner logic in "where.c". These definitions are broken out into
122250 ** a separate source file for easier editing.
122251 */
122252 
122253 /*
122254 ** Trace output macros
122255 */
122256 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
122257 /***/ int sqlite3WhereTrace;
122258 #endif
122259 #if defined(SQLITE_DEBUG) \
122260  && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
122261 # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
122262 # define WHERETRACE_ENABLED 1
122263 #else
122264 # define WHERETRACE(K,X)
122265 #endif
122266 
122267 /* Forward references
122268 */
122269 typedef struct WhereClause WhereClause;
122271 typedef struct WhereOrInfo WhereOrInfo;
122273 typedef struct WhereLevel WhereLevel;
122274 typedef struct WhereLoop WhereLoop;
122275 typedef struct WherePath WherePath;
122276 typedef struct WhereTerm WhereTerm;
122278 typedef struct WhereScan WhereScan;
122279 typedef struct WhereOrCost WhereOrCost;
122280 typedef struct WhereOrSet WhereOrSet;
122281 
122282 /*
122283 ** This object contains information needed to implement a single nested
122284 ** loop in WHERE clause.
122285 **
122286 ** Contrast this object with WhereLoop. This object describes the
122287 ** implementation of the loop. WhereLoop describes the algorithm.
122288 ** This object contains a pointer to the WhereLoop algorithm as one of
122289 ** its elements.
122290 **
122291 ** The WhereInfo object contains a single instance of this object for
122292 ** each term in the FROM clause (which is to say, for each of the
122293 ** nested loops as implemented). The order of WhereLevel objects determines
122294 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
122295 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
122296 */
122297 struct WhereLevel {
122298  int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
122299  int iTabCur; /* The VDBE cursor used to access the table */
122300  int iIdxCur; /* The VDBE cursor used to access pIdx */
122301  int addrBrk; /* Jump here to break out of the loop */
122302  int addrNxt; /* Jump here to start the next IN combination */
122303  int addrSkip; /* Jump here for next iteration of skip-scan */
122304  int addrCont; /* Jump here to continue with the next loop cycle */
122305  int addrFirst; /* First instruction of interior of the loop */
122306  int addrBody; /* Beginning of the body of this loop */
122307 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
122308  u32 iLikeRepCntr; /* LIKE range processing counter register (times 2) */
122309  int addrLikeRep; /* LIKE range processing address */
122310 #endif
122311  u8 iFrom; /* Which entry in the FROM clause */
122312  u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
122313  int p1, p2; /* Operands of the opcode used to ends the loop */
122314  union { /* Information that depends on pWLoop->wsFlags */
122315  struct {
122316  int nIn; /* Number of entries in aInLoop[] */
122317  struct InLoop {
122318  int iCur; /* The VDBE cursor used by this IN operator */
122319  int addrInTop; /* Top of the IN loop */
122320  u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
122321  } *aInLoop; /* Information about each nested IN operator */
122322  } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
122323  Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
122324  } u;
122325  struct WhereLoop *pWLoop; /* The selected WhereLoop object */
122326  Bitmask notReady; /* FROM entries not usable at this level */
122327 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
122328  int addrVisit; /* Address at which row is visited */
122329 #endif
122330 };
122331 
122332 /*
122333 ** Each instance of this object represents an algorithm for evaluating one
122334 ** term of a join. Every term of the FROM clause will have at least
122335 ** one corresponding WhereLoop object (unless INDEXED BY constraints
122336 ** prevent a query solution - which is an error) and many terms of the
122337 ** FROM clause will have multiple WhereLoop objects, each describing a
122338 ** potential way of implementing that FROM-clause term, together with
122339 ** dependencies and cost estimates for using the chosen algorithm.
122340 **
122341 ** Query planning consists of building up a collection of these WhereLoop
122342 ** objects, then computing a particular sequence of WhereLoop objects, with
122343 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
122344 ** and that minimize the overall cost.
122345 */
122346 struct WhereLoop {
122347  Bitmask prereq; /* Bitmask of other loops that must run first */
122348  Bitmask maskSelf; /* Bitmask identifying table iTab */
122349 #ifdef SQLITE_DEBUG
122350  char cId; /* Symbolic ID of this loop for debugging use */
122351 #endif
122352  u8 iTab; /* Position in FROM clause of table for this loop */
122353  u8 iSortIdx; /* Sorting index number. 0==None */
122354  LogEst rSetup; /* One-time setup cost (ex: create transient index) */
122355  LogEst rRun; /* Cost of running each loop */
122356  LogEst nOut; /* Estimated number of output rows */
122357  union {
122358  struct { /* Information for internal btree tables */
122359  u16 nEq; /* Number of equality constraints */
122360  Index *pIndex; /* Index used, or NULL */
122361  } btree;
122362  struct { /* Information for virtual tables */
122363  int idxNum; /* Index number */
122364  u8 needFree; /* True if sqlite3_free(idxStr) is needed */
122365  i8 isOrdered; /* True if satisfies ORDER BY */
122366  u16 omitMask; /* Terms that may be omitted */
122367  char *idxStr; /* Index identifier string */
122368  } vtab;
122369  } u;
122370  u32 wsFlags; /* WHERE_* flags describing the plan */
122371  u16 nLTerm; /* Number of entries in aLTerm[] */
122372  u16 nSkip; /* Number of NULL aLTerm[] entries */
122373  /**** whereLoopXfer() copies fields above ***********************/
122374 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
122375  u16 nLSlot; /* Number of slots allocated for aLTerm[] */
122376  WhereTerm **aLTerm; /* WhereTerms used */
122377  WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
122378  WhereTerm *aLTermSpace[3]; /* Initial aLTerm[] space */
122379 };
122380 
122381 /* This object holds the prerequisites and the cost of running a
122382 ** subquery on one operand of an OR operator in the WHERE clause.
122383 ** See WhereOrSet for additional information
122384 */
122386  Bitmask prereq; /* Prerequisites */
122387  LogEst rRun; /* Cost of running this subquery */
122388  LogEst nOut; /* Number of outputs for this subquery */
122389 };
122390 
122391 /* The WhereOrSet object holds a set of possible WhereOrCosts that
122392 ** correspond to the subquery(s) of OR-clause processing. Only the
122393 ** best N_OR_COST elements are retained.
122394 */
122395 #define N_OR_COST 3
122396 struct WhereOrSet {
122397  u16 n; /* Number of valid a[] entries */
122398  WhereOrCost a[N_OR_COST]; /* Set of best costs */
122399 };
122400 
122401 /*
122402 ** Each instance of this object holds a sequence of WhereLoop objects
122403 ** that implement some or all of a query plan.
122404 **
122405 ** Think of each WhereLoop object as a node in a graph with arcs
122406 ** showing dependencies and costs for travelling between nodes. (That is
122407 ** not a completely accurate description because WhereLoop costs are a
122408 ** vector, not a scalar, and because dependencies are many-to-one, not
122409 ** one-to-one as are graph nodes. But it is a useful visualization aid.)
122410 ** Then a WherePath object is a path through the graph that visits some
122411 ** or all of the WhereLoop objects once.
122412 **
122413 ** The "solver" works by creating the N best WherePath objects of length
122414 ** 1. Then using those as a basis to compute the N best WherePath objects
122415 ** of length 2. And so forth until the length of WherePaths equals the
122416 ** number of nodes in the FROM clause. The best (lowest cost) WherePath
122417 ** at the end is the chosen query plan.
122418 */
122419 struct WherePath {
122420  Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
122421  Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
122422  LogEst nRow; /* Estimated number of rows generated by this path */
122423  LogEst rCost; /* Total cost of this path */
122424  LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
122425  i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
122426  WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
122427 };
122428 
122429 /*
122430 ** The query generator uses an array of instances of this structure to
122431 ** help it analyze the subexpressions of the WHERE clause. Each WHERE
122432 ** clause subexpression is separated from the others by AND operators,
122433 ** usually, or sometimes subexpressions separated by OR.
122434 **
122435 ** All WhereTerms are collected into a single WhereClause structure.
122436 ** The following identity holds:
122437 **
122438 ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
122439 **
122440 ** When a term is of the form:
122441 **
122442 ** X <op> <expr>
122443 **
122444 ** where X is a column name and <op> is one of certain operators,
122445 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
122446 ** cursor number and column number for X. WhereTerm.eOperator records
122447 ** the <op> using a bitmask encoding defined by WO_xxx below. The
122448 ** use of a bitmask encoding for the operator allows us to search
122449 ** quickly for terms that match any of several different operators.
122450 **
122451 ** A WhereTerm might also be two or more subterms connected by OR:
122452 **
122453 ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
122454 **
122455 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
122456 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
122457 ** is collected about the OR clause.
122458 **
122459 ** If a term in the WHERE clause does not match either of the two previous
122460 ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
122461 ** to the original subexpression content and wtFlags is set up appropriately
122462 ** but no other fields in the WhereTerm object are meaningful.
122463 **
122464 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
122465 ** but they do so indirectly. A single WhereMaskSet structure translates
122466 ** cursor number into bits and the translated bit is stored in the prereq
122467 ** fields. The translation is used in order to maximize the number of
122468 ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
122469 ** spread out over the non-negative integers. For example, the cursor
122470 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
122471 ** translates these sparse cursor numbers into consecutive integers
122472 ** beginning with 0 in order to make the best possible use of the available
122473 ** bits in the Bitmask. So, in the example above, the cursor numbers
122474 ** would be mapped into integers 0 through 7.
122475 **
122476 ** The number of terms in a join is limited by the number of bits
122477 ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
122478 ** is only able to process joins with 64 or fewer tables.
122479 */
122480 struct WhereTerm {
122481  Expr *pExpr; /* Pointer to the subexpression that is this term */
122482  int iParent; /* Disable pWC->a[iParent] when this term disabled */
122483  int leftCursor; /* Cursor number of X in "X <op> <expr>" */
122484  union {
122485  int leftColumn; /* Column number of X in "X <op> <expr>" */
122486  WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
122487  WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
122488  } u;
122489  LogEst truthProb; /* Probability of truth for this expression */
122490  u16 eOperator; /* A WO_xx value describing <op> */
122491  u16 wtFlags; /* TERM_xxx bit flags. See below */
122492  u8 nChild; /* Number of children that must disable us */
122493  u8 eMatchOp; /* Op for vtab MATCH/LIKE/GLOB/REGEXP terms */
122494  WhereClause *pWC; /* The clause this term is part of */
122495  Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
122496  Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
122497 };
122498 
122499 /*
122500 ** Allowed values of WhereTerm.wtFlags
122501 */
122502 #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
122503 #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
122504 #define TERM_CODED 0x04 /* This term is already coded */
122505 #define TERM_COPIED 0x08 /* Has a child */
122506 #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
122507 #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
122508 #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
122509 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122510 # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
122511 #else
122512 # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
122513 #endif
122514 #define TERM_LIKEOPT 0x100 /* Virtual terms from the LIKE optimization */
122515 #define TERM_LIKECOND 0x200 /* Conditionally this LIKE operator term */
122516 #define TERM_LIKE 0x400 /* The original LIKE operator */
122517 #define TERM_IS 0x800 /* Term.pExpr is an IS operator */
122518 
122519 /*
122520 ** An instance of the WhereScan object is used as an iterator for locating
122521 ** terms in the WHERE clause that are useful to the query planner.
122522 */
122523 struct WhereScan {
122524  WhereClause *pOrigWC; /* Original, innermost WhereClause */
122525  WhereClause *pWC; /* WhereClause currently being scanned */
122526  const char *zCollName; /* Required collating sequence, if not NULL */
122527  Expr *pIdxExpr; /* Search for this index expression */
122528  char idxaff; /* Must match this affinity, if zCollName!=NULL */
122529  unsigned char nEquiv; /* Number of entries in aEquiv[] */
122530  unsigned char iEquiv; /* Next unused slot in aEquiv[] */
122531  u32 opMask; /* Acceptable operators */
122532  int k; /* Resume scanning at this->pWC->a[this->k] */
122533  int aiCur[11]; /* Cursors in the equivalence class */
122534  i16 aiColumn[11]; /* Corresponding column number in the eq-class */
122535 };
122536 
122537 /*
122538 ** An instance of the following structure holds all information about a
122539 ** WHERE clause. Mostly this is a container for one or more WhereTerms.
122540 **
122541 ** Explanation of pOuter: For a WHERE clause of the form
122542 **
122543 ** a AND ((b AND c) OR (d AND e)) AND f
122544 **
122545 ** There are separate WhereClause objects for the whole clause and for
122546 ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
122547 ** subclauses points to the WhereClause object for the whole clause.
122548 */
122550  WhereInfo *pWInfo; /* WHERE clause processing context */
122551  WhereClause *pOuter; /* Outer conjunction */
122552  u8 op; /* Split operator. TK_AND or TK_OR */
122553  int nTerm; /* Number of terms */
122554  int nSlot; /* Number of entries in a[] */
122555  WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
122556 #if defined(SQLITE_SMALL_STACK)
122557  WhereTerm aStatic[1]; /* Initial static space for a[] */
122558 #else
122559  WhereTerm aStatic[8]; /* Initial static space for a[] */
122560 #endif
122561 };
122562 
122563 /*
122564 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
122565 ** a dynamically allocated instance of the following structure.
122566 */
122568  WhereClause wc; /* Decomposition into subterms */
122569  Bitmask indexable; /* Bitmask of all indexable tables in the clause */
122570 };
122571 
122572 /*
122573 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
122574 ** a dynamically allocated instance of the following structure.
122575 */
122577  WhereClause wc; /* The subexpression broken out */
122578 };
122579 
122580 /*
122581 ** An instance of the following structure keeps track of a mapping
122582 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
122583 **
122584 ** The VDBE cursor numbers are small integers contained in
122585 ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
122586 ** clause, the cursor numbers might not begin with 0 and they might
122587 ** contain gaps in the numbering sequence. But we want to make maximum
122588 ** use of the bits in our bitmasks. This structure provides a mapping
122589 ** from the sparse cursor numbers into consecutive integers beginning
122590 ** with 0.
122591 **
122592 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
122593 ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
122594 **
122595 ** For example, if the WHERE clause expression used these VDBE
122596 ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
122597 ** would map those cursor numbers into bits 0 through 5.
122598 **
122599 ** Note that the mapping is not necessarily ordered. In the example
122600 ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
122601 ** 57->5, 73->4. Or one of 719 other combinations might be used. It
122602 ** does not really matter. What is important is that sparse cursor
122603 ** numbers all get mapped into bit numbers that begin with 0 and contain
122604 ** no gaps.
122605 */
122607  int n; /* Number of assigned cursor values */
122608  int ix[BMS]; /* Cursor assigned to each bit */
122609 };
122610 
122611 /*
122612 ** Initialize a WhereMaskSet object
122613 */
122614 #define initMaskSet(P) (P)->n=0
122615 
122616 /*
122617 ** This object is a convenience wrapper holding all information needed
122618 ** to construct WhereLoop objects for a particular query.
122619 */
122621  WhereInfo *pWInfo; /* Information about this WHERE */
122622  WhereClause *pWC; /* WHERE clause terms */
122623  ExprList *pOrderBy; /* ORDER BY clause */
122624  WhereLoop *pNew; /* Template WhereLoop */
122625  WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
122626 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
122627  UnpackedRecord *pRec; /* Probe for stat4 (if required) */
122628  int nRecValid; /* Number of valid fields currently in pRec */
122629 #endif
122630 };
122631 
122632 /*
122633 ** The WHERE clause processing routine has two halves. The
122634 ** first part does the start of the WHERE loop and the second
122635 ** half does the tail of the WHERE loop. An instance of
122636 ** this structure is returned by the first half and passed
122637 ** into the second half to give some continuity.
122638 **
122639 ** An instance of this object holds the complete state of the query
122640 ** planner.
122641 */
122642 struct WhereInfo {
122643  Parse *pParse; /* Parsing and code generating context */
122644  SrcList *pTabList; /* List of tables in the join */
122645  ExprList *pOrderBy; /* The ORDER BY clause or NULL */
122646  ExprList *pDistinctSet; /* DISTINCT over all these values */
122647  WhereLoop *pLoops; /* List of all WhereLoop objects */
122648  Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
122649  LogEst nRowOut; /* Estimated number of output rows */
122650  LogEst iLimit; /* LIMIT if wctrlFlags has WHERE_USE_LIMIT */
122651  u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
122652  i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
122653  u8 sorted; /* True if really sorted (not just grouped) */
122654  u8 eOnePass; /* ONEPASS_OFF, or _SINGLE, or _MULTI */
122655  u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
122656  u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
122657  u8 nLevel; /* Number of nested loop */
122658  int iTop; /* The very beginning of the WHERE loop */
122659  int iContinue; /* Jump here to continue with next record */
122660  int iBreak; /* Jump here to break out of the loop */
122661  int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
122662  int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
122663  WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
122664  WhereClause sWC; /* Decomposition of the WHERE clause */
122665  WhereLevel a[1]; /* Information about each nest loop in WHERE */
122666 };
122667 
122668 /*
122669 ** Private interfaces - callable only by other where.c routines.
122670 **
122671 ** where.c:
122672 */
122675  WhereClause *pWC, /* The WHERE clause to be searched */
122676  int iCur, /* Cursor number of LHS */
122677  int iColumn, /* Column number of LHS */
122678  Bitmask notReady, /* RHS must not overlap with this mask */
122679  u32 op, /* Mask of WO_xx values describing operator */
122680  Index *pIdx /* Must be compatible with this index, if not NULL */
122681 );
122682 
122683 /* wherecode.c: */
122684 #ifndef SQLITE_OMIT_EXPLAIN
122686  Parse *pParse, /* Parse context */
122687  SrcList *pTabList, /* Table list this loop refers to */
122688  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
122689  int iLevel, /* Value for "level" column of output */
122690  int iFrom, /* Value for "from" column of output */
122691  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
122692 );
122693 #else
122694 # define sqlite3WhereExplainOneScan(u,v,w,x,y,z) 0
122695 #endif /* SQLITE_OMIT_EXPLAIN */
122696 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
122698  Vdbe *v, /* Vdbe to add scanstatus entry to */
122699  SrcList *pSrclist, /* FROM clause pLvl reads data from */
122700  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
122701  int addrExplain /* Address of OP_Explain (or 0) */
122702 );
122703 #else
122704 # define sqlite3WhereAddScanStatus(a, b, c, d) ((void)d)
122705 #endif
122707  WhereInfo *pWInfo, /* Complete information about the WHERE clause */
122708  int iLevel, /* Which level of pWInfo->a[] should be coded */
122709  Bitmask notReady /* Which tables are currently available */
122710 );
122711 
122712 /* whereexpr.c: */
122719 SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse*, struct SrcList_item*, WhereClause*);
122720 
122721 
122722 
122723 
122724 
122725 /*
122726 ** Bitmasks for the operators on WhereTerm objects. These are all
122727 ** operators that are of interest to the query planner. An
122728 ** OR-ed combination of these values can be used when searching for
122729 ** particular WhereTerms within a WhereClause.
122730 **
122731 ** Value constraints:
122732 ** WO_EQ == SQLITE_INDEX_CONSTRAINT_EQ
122733 ** WO_LT == SQLITE_INDEX_CONSTRAINT_LT
122734 ** WO_LE == SQLITE_INDEX_CONSTRAINT_LE
122735 ** WO_GT == SQLITE_INDEX_CONSTRAINT_GT
122736 ** WO_GE == SQLITE_INDEX_CONSTRAINT_GE
122737 ** WO_MATCH == SQLITE_INDEX_CONSTRAINT_MATCH
122738 */
122739 #define WO_IN 0x0001
122740 #define WO_EQ 0x0002
122741 #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
122742 #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
122743 #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
122744 #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
122745 #define WO_MATCH 0x0040
122746 #define WO_IS 0x0080
122747 #define WO_ISNULL 0x0100
122748 #define WO_OR 0x0200 /* Two or more OR-connected terms */
122749 #define WO_AND 0x0400 /* Two or more AND-connected terms */
122750 #define WO_EQUIV 0x0800 /* Of the form A==B, both columns */
122751 #define WO_NOOP 0x1000 /* This term does not restrict search space */
122752 
122753 #define WO_ALL 0x1fff /* Mask of all possible WO_* values */
122754 #define WO_SINGLE 0x01ff /* Mask of all non-compound WO_* values */
122755 
122756 /*
122757 ** These are definitions of bits in the WhereLoop.wsFlags field.
122758 ** The particular combination of bits in each WhereLoop help to
122759 ** determine the algorithm that WhereLoop represents.
122760 */
122761 #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
122762 #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
122763 #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
122764 #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
122765 #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
122766 #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
122767 #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
122768 #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
122769 #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
122770 #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
122771 #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
122772 #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
122773 #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
122774 #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
122775 #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
122776 #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
122777 #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
122778 #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
122779 #define WHERE_PARTIALIDX 0x00020000 /* The automatic index is partial */
122780 
122781 /************** End of whereInt.h ********************************************/
122782 /************** Continuing where we left off in wherecode.c ******************/
122783 
122784 #ifndef SQLITE_OMIT_EXPLAIN
122785 /*
122786 ** This routine is a helper for explainIndexRange() below
122787 **
122788 ** pStr holds the text of an expression that we are building up one term
122789 ** at a time. This routine adds a new term to the end of the expression.
122790 ** Terms are separated by AND so add the "AND" text for second and subsequent
122791 ** terms only.
122792 */
122794  StrAccum *pStr, /* The text expression being built */
122795  int iTerm, /* Index of this term. First is zero */
122796  const char *zColumn, /* Name of the column */
122797  const char *zOp /* Name of the operator */
122798 ){
122799  if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
122800  sqlite3StrAccumAppendAll(pStr, zColumn);
122801  sqlite3StrAccumAppend(pStr, zOp, 1);
122802  sqlite3StrAccumAppend(pStr, "?", 1);
122803 }
122804 
122805 /*
122806 ** Return the name of the i-th column of the pIdx index.
122807 */
122808 static const char *explainIndexColumnName(Index *pIdx, int i){
122809  i = pIdx->aiColumn[i];
122810  if( i==XN_EXPR ) return "<expr>";
122811  if( i==XN_ROWID ) return "rowid";
122812  return pIdx->pTable->aCol[i].zName;
122813 }
122814 
122815 /*
122816 ** Argument pLevel describes a strategy for scanning table pTab. This
122817 ** function appends text to pStr that describes the subset of table
122818 ** rows scanned by the strategy in the form of an SQL expression.
122819 **
122820 ** For example, if the query:
122821 **
122822 ** SELECT * FROM t1 WHERE a=1 AND b>2;
122823 **
122824 ** is run and there is an index on (a, b), then this function returns a
122825 ** string similar to:
122826 **
122827 ** "a=? AND b>?"
122828 */
122829 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop){
122830  Index *pIndex = pLoop->u.btree.pIndex;
122831  u16 nEq = pLoop->u.btree.nEq;
122832  u16 nSkip = pLoop->nSkip;
122833  int i, j;
122834 
122835  if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
122836  sqlite3StrAccumAppend(pStr, " (", 2);
122837  for(i=0; i<nEq; i++){
122838  const char *z = explainIndexColumnName(pIndex, i);
122839  if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
122840  sqlite3XPrintf(pStr, i>=nSkip ? "%s=?" : "ANY(%s)", z);
122841  }
122842 
122843  j = i;
122844  if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
122845  const char *z = explainIndexColumnName(pIndex, i);
122846  explainAppendTerm(pStr, i++, z, ">");
122847  }
122848  if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
122849  const char *z = explainIndexColumnName(pIndex, j);
122850  explainAppendTerm(pStr, i, z, "<");
122851  }
122852  sqlite3StrAccumAppend(pStr, ")", 1);
122853 }
122854 
122855 /*
122856 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
122857 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
122858 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode
122859 ** is added to the output to describe the table scan strategy in pLevel.
122860 **
122861 ** If an OP_Explain opcode is added to the VM, its address is returned.
122862 ** Otherwise, if no OP_Explain is coded, zero is returned.
122863 */
122865  Parse *pParse, /* Parse context */
122866  SrcList *pTabList, /* Table list this loop refers to */
122867  WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
122868  int iLevel, /* Value for "level" column of output */
122869  int iFrom, /* Value for "from" column of output */
122870  u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
122871 ){
122872  int ret = 0;
122873 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
122874  if( pParse->explain==2 )
122875 #endif
122876  {
122877  struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
122878  Vdbe *v = pParse->pVdbe; /* VM being constructed */
122879  sqlite3 *db = pParse->db; /* Database handle */
122880  int iId = pParse->iSelectId; /* Select id (left-most output column) */
122881  int isSearch; /* True for a SEARCH. False for SCAN. */
122882  WhereLoop *pLoop; /* The controlling WhereLoop object */
122883  u32 flags; /* Flags that describe this loop */
122884  char *zMsg; /* Text to add to EQP output */
122885  StrAccum str; /* EQP output string */
122886  char zBuf[100]; /* Initial space for EQP output string */
122887 
122888  pLoop = pLevel->pWLoop;
122889  flags = pLoop->wsFlags;
122890  if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
122891 
122892  isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
122893  || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
122894  || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
122895 
122896  sqlite3StrAccumInit(&str, db, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
122897  sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
122898  if( pItem->pSelect ){
122899  sqlite3XPrintf(&str, " SUBQUERY %d", pItem->iSelectId);
122900  }else{
122901  sqlite3XPrintf(&str, " TABLE %s", pItem->zName);
122902  }
122903 
122904  if( pItem->zAlias ){
122905  sqlite3XPrintf(&str, " AS %s", pItem->zAlias);
122906  }
122907  if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
122908  const char *zFmt = 0;
122909  Index *pIdx;
122910 
122911  assert( pLoop->u.btree.pIndex!=0 );
122912  pIdx = pLoop->u.btree.pIndex;
122913  assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
122914  if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
122915  if( isSearch ){
122916  zFmt = "PRIMARY KEY";
122917  }
122918  }else if( flags & WHERE_PARTIALIDX ){
122919  zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
122920  }else if( flags & WHERE_AUTO_INDEX ){
122921  zFmt = "AUTOMATIC COVERING INDEX";
122922  }else if( flags & WHERE_IDX_ONLY ){
122923  zFmt = "COVERING INDEX %s";
122924  }else{
122925  zFmt = "INDEX %s";
122926  }
122927  if( zFmt ){
122928  sqlite3StrAccumAppend(&str, " USING ", 7);
122929  sqlite3XPrintf(&str, zFmt, pIdx->zName);
122930  explainIndexRange(&str, pLoop);
122931  }
122932  }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
122933  const char *zRangeOp;
122934  if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
122935  zRangeOp = "=";
122936  }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
122937  zRangeOp = ">? AND rowid<";
122938  }else if( flags&WHERE_BTM_LIMIT ){
122939  zRangeOp = ">";
122940  }else{
122941  assert( flags&WHERE_TOP_LIMIT);
122942  zRangeOp = "<";
122943  }
122944  sqlite3XPrintf(&str, " USING INTEGER PRIMARY KEY (rowid%s?)",zRangeOp);
122945  }
122946 #ifndef SQLITE_OMIT_VIRTUALTABLE
122947  else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
122948  sqlite3XPrintf(&str, " VIRTUAL TABLE INDEX %d:%s",
122949  pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
122950  }
122951 #endif
122952 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
122953  if( pLoop->nOut>=10 ){
122954  sqlite3XPrintf(&str, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
122955  }else{
122956  sqlite3StrAccumAppend(&str, " (~1 row)", 9);
122957  }
122958 #endif
122959  zMsg = sqlite3StrAccumFinish(&str);
122960  ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
122961  }
122962  return ret;
122963 }
122964 #endif /* SQLITE_OMIT_EXPLAIN */
122965 
122966 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
122967 /*
122968 ** Configure the VM passed as the first argument with an
122969 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to
122970 ** implement level pLvl. Argument pSrclist is a pointer to the FROM
122971 ** clause that the scan reads data from.
122972 **
122973 ** If argument addrExplain is not 0, it must be the address of an
122974 ** OP_Explain instruction that describes the same loop.
122975 */
122977  Vdbe *v, /* Vdbe to add scanstatus entry to */
122978  SrcList *pSrclist, /* FROM clause pLvl reads data from */
122979  WhereLevel *pLvl, /* Level to add scanstatus() entry for */
122980  int addrExplain /* Address of OP_Explain (or 0) */
122981 ){
122982  const char *zObj = 0;
122983  WhereLoop *pLoop = pLvl->pWLoop;
122984  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 && pLoop->u.btree.pIndex!=0 ){
122985  zObj = pLoop->u.btree.pIndex->zName;
122986  }else{
122987  zObj = pSrclist->a[pLvl->iFrom].zName;
122988  }
122990  v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
122991  );
122992 }
122993 #endif
122994 
122995 
122996 /*
122997 ** Disable a term in the WHERE clause. Except, do not disable the term
122998 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
122999 ** or USING clause of that join.
123000 **
123001 ** Consider the term t2.z='ok' in the following queries:
123002 **
123003 ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
123004 ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
123005 ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
123006 **
123007 ** The t2.z='ok' is disabled in the in (2) because it originates
123008 ** in the ON clause. The term is disabled in (3) because it is not part
123009 ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
123010 **
123011 ** Disabling a term causes that term to not be tested in the inner loop
123012 ** of the join. Disabling is an optimization. When terms are satisfied
123013 ** by indices, we disable them to prevent redundant tests in the inner
123014 ** loop. We would get the correct results if nothing were ever disabled,
123015 ** but joins might run a little slower. The trick is to disable as much
123016 ** as we can without disabling too much. If we disabled in (1), we'd get
123017 ** the wrong answer. See ticket #813.
123018 **
123019 ** If all the children of a term are disabled, then that term is also
123020 ** automatically disabled. In this way, terms get disabled if derived
123021 ** virtual terms are tested first. For example:
123022 **
123023 ** x GLOB 'abc*' AND x>='abc' AND x<'acd'
123024 ** \___________/ \______/ \_____/
123025 ** parent child1 child2
123026 **
123027 ** Only the parent term was in the original WHERE clause. The child1
123028 ** and child2 terms were added by the LIKE optimization. If both of
123029 ** the virtual child terms are valid, then testing of the parent can be
123030 ** skipped.
123031 **
123032 ** Usually the parent term is marked as TERM_CODED. But if the parent
123033 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
123034 ** The TERM_LIKECOND marking indicates that the term should be coded inside
123035 ** a conditional such that is only evaluated on the second pass of a
123036 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
123037 */
123038 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
123039  int nLoop = 0;
123040  while( pTerm
123041  && (pTerm->wtFlags & TERM_CODED)==0
123042  && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
123043  && (pLevel->notReady & pTerm->prereqAll)==0
123044  ){
123045  if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
123046  pTerm->wtFlags |= TERM_LIKECOND;
123047  }else{
123048  pTerm->wtFlags |= TERM_CODED;
123049  }
123050  if( pTerm->iParent<0 ) break;
123051  pTerm = &pTerm->pWC->a[pTerm->iParent];
123052  pTerm->nChild--;
123053  if( pTerm->nChild!=0 ) break;
123054  nLoop++;
123055  }
123056 }
123057 
123058 /*
123059 ** Code an OP_Affinity opcode to apply the column affinity string zAff
123060 ** to the n registers starting at base.
123061 **
123062 ** As an optimization, SQLITE_AFF_BLOB entries (which are no-ops) at the
123063 ** beginning and end of zAff are ignored. If all entries in zAff are
123064 ** SQLITE_AFF_BLOB, then no code gets generated.
123065 **
123066 ** This routine makes its own copy of zAff so that the caller is free
123067 ** to modify zAff after this routine returns.
123068 */
123069 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
123070  Vdbe *v = pParse->pVdbe;
123071  if( zAff==0 ){
123072  assert( pParse->db->mallocFailed );
123073  return;
123074  }
123075  assert( v!=0 );
123076 
123077  /* Adjust base and n to skip over SQLITE_AFF_BLOB entries at the beginning
123078  ** and end of the affinity string.
123079  */
123080  while( n>0 && zAff[0]==SQLITE_AFF_BLOB ){
123081  n--;
123082  base++;
123083  zAff++;
123084  }
123085  while( n>1 && zAff[n-1]==SQLITE_AFF_BLOB ){
123086  n--;
123087  }
123088 
123089  /* Code the OP_Affinity opcode if there is anything left to do. */
123090  if( n>0 ){
123091  sqlite3VdbeAddOp4(v, OP_Affinity, base, n, 0, zAff, n);
123092  sqlite3ExprCacheAffinityChange(pParse, base, n);
123093  }
123094 }
123095 
123096 
123097 /*
123098 ** Generate code for a single equality term of the WHERE clause. An equality
123099 ** term can be either X=expr or X IN (...). pTerm is the term to be
123100 ** coded.
123101 **
123102 ** The current value for the constraint is left in register iReg.
123103 **
123104 ** For a constraint of the form X=expr, the expression is evaluated and its
123105 ** result is left on the stack. For constraints of the form X IN (...)
123106 ** this routine sets up a loop that will iterate over all values of X.
123107 */
123109  Parse *pParse, /* The parsing context */
123110  WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
123111  WhereLevel *pLevel, /* The level of the FROM clause we are working on */
123112  int iEq, /* Index of the equality term within this level */
123113  int bRev, /* True for reverse-order IN operations */
123114  int iTarget /* Attempt to leave results in this register */
123115 ){
123116  Expr *pX = pTerm->pExpr;
123117  Vdbe *v = pParse->pVdbe;
123118  int iReg; /* Register holding results */
123119 
123120  assert( iTarget>0 );
123121  if( pX->op==TK_EQ || pX->op==TK_IS ){
123122  iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
123123  }else if( pX->op==TK_ISNULL ){
123124  iReg = iTarget;
123125  sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
123126 #ifndef SQLITE_OMIT_SUBQUERY
123127  }else{
123128  int eType;
123129  int iTab;
123130  struct InLoop *pIn;
123131  WhereLoop *pLoop = pLevel->pWLoop;
123132 
123133  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
123134  && pLoop->u.btree.pIndex!=0
123135  && pLoop->u.btree.pIndex->aSortOrder[iEq]
123136  ){
123137  testcase( iEq==0 );
123138  testcase( bRev );
123139  bRev = !bRev;
123140  }
123141  assert( pX->op==TK_IN );
123142  iReg = iTarget;
123143  eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
123144  if( eType==IN_INDEX_INDEX_DESC ){
123145  testcase( bRev );
123146  bRev = !bRev;
123147  }
123148  iTab = pX->iTable;
123149  sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
123150  VdbeCoverageIf(v, bRev);
123151  VdbeCoverageIf(v, !bRev);
123152  assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
123153  pLoop->wsFlags |= WHERE_IN_ABLE;
123154  if( pLevel->u.in.nIn==0 ){
123155  pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
123156  }
123157  pLevel->u.in.nIn++;
123158  pLevel->u.in.aInLoop =
123159  sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
123160  sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
123161  pIn = pLevel->u.in.aInLoop;
123162  if( pIn ){
123163  pIn += pLevel->u.in.nIn - 1;
123164  pIn->iCur = iTab;
123165  if( eType==IN_INDEX_ROWID ){
123166  pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
123167  }else{
123168  pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
123169  }
123170  pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
123171  sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
123172  }else{
123173  pLevel->u.in.nIn = 0;
123174  }
123175 #endif
123176  }
123177  disableTerm(pLevel, pTerm);
123178  return iReg;
123179 }
123180 
123181 /*
123182 ** Generate code that will evaluate all == and IN constraints for an
123183 ** index scan.
123184 **
123185 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
123186 ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
123187 ** The index has as many as three equality constraints, but in this
123188 ** example, the third "c" value is an inequality. So only two
123189 ** constraints are coded. This routine will generate code to evaluate
123190 ** a==5 and b IN (1,2,3). The current values for a and b will be stored
123191 ** in consecutive registers and the index of the first register is returned.
123192 **
123193 ** In the example above nEq==2. But this subroutine works for any value
123194 ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
123195 ** The only thing it does is allocate the pLevel->iMem memory cell and
123196 ** compute the affinity string.
123197 **
123198 ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
123199 ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
123200 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
123201 ** occurs after the nEq quality constraints.
123202 **
123203 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
123204 ** the index of the first memory cell in that range. The code that
123205 ** calls this routine will use that memory range to store keys for
123206 ** start and termination conditions of the loop.
123207 ** key value of the loop. If one or more IN operators appear, then
123208 ** this routine allocates an additional nEq memory cells for internal
123209 ** use.
123210 **
123211 ** Before returning, *pzAff is set to point to a buffer containing a
123212 ** copy of the column affinity string of the index allocated using
123213 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
123214 ** with equality constraints that use BLOB or NONE affinity are set to
123215 ** SQLITE_AFF_BLOB. This is to deal with SQL such as the following:
123216 **
123217 ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
123218 ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
123219 **
123220 ** In the example above, the index on t1(a) has TEXT affinity. But since
123221 ** the right hand side of the equality constraint (t2.b) has BLOB/NONE affinity,
123222 ** no conversion should be attempted before using a t2.b value as part of
123223 ** a key to search the index. Hence the first byte in the returned affinity
123224 ** string in this example would be set to SQLITE_AFF_BLOB.
123225 */
123227  Parse *pParse, /* Parsing context */
123228  WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
123229  int bRev, /* Reverse the order of IN operators */
123230  int nExtraReg, /* Number of extra registers to allocate */
123231  char **pzAff /* OUT: Set to point to affinity string */
123232 ){
123233  u16 nEq; /* The number of == or IN constraints to code */
123234  u16 nSkip; /* Number of left-most columns to skip */
123235  Vdbe *v = pParse->pVdbe; /* The vm under construction */
123236  Index *pIdx; /* The index being used for this loop */
123237  WhereTerm *pTerm; /* A single constraint term */
123238  WhereLoop *pLoop; /* The WhereLoop object */
123239  int j; /* Loop counter */
123240  int regBase; /* Base register */
123241  int nReg; /* Number of registers to allocate */
123242  char *zAff; /* Affinity string to return */
123243 
123244  /* This module is only called on query plans that use an index. */
123245  pLoop = pLevel->pWLoop;
123246  assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
123247  nEq = pLoop->u.btree.nEq;
123248  nSkip = pLoop->nSkip;
123249  pIdx = pLoop->u.btree.pIndex;
123250  assert( pIdx!=0 );
123251 
123252  /* Figure out how many memory cells we will need then allocate them.
123253  */
123254  regBase = pParse->nMem + 1;
123255  nReg = pLoop->u.btree.nEq + nExtraReg;
123256  pParse->nMem += nReg;
123257 
123258  zAff = sqlite3DbStrDup(pParse->db,sqlite3IndexAffinityStr(pParse->db,pIdx));
123259  assert( zAff!=0 || pParse->db->mallocFailed );
123260 
123261  if( nSkip ){
123262  int iIdxCur = pLevel->iIdxCur;
123263  sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
123264  VdbeCoverageIf(v, bRev==0);
123265  VdbeCoverageIf(v, bRev!=0);
123266  VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
123267  j = sqlite3VdbeAddOp0(v, OP_Goto);
123268  pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
123269  iIdxCur, 0, regBase, nSkip);
123270  VdbeCoverageIf(v, bRev==0);
123271  VdbeCoverageIf(v, bRev!=0);
123272  sqlite3VdbeJumpHere(v, j);
123273  for(j=0; j<nSkip; j++){
123274  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
123275  testcase( pIdx->aiColumn[j]==XN_EXPR );
123276  VdbeComment((v, "%s", explainIndexColumnName(pIdx, j)));
123277  }
123278  }
123279 
123280  /* Evaluate the equality constraints
123281  */
123282  assert( zAff==0 || (int)strlen(zAff)>=nEq );
123283  for(j=nSkip; j<nEq; j++){
123284  int r1;
123285  pTerm = pLoop->aLTerm[j];
123286  assert( pTerm!=0 );
123287  /* The following testcase is true for indices with redundant columns.
123288  ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
123289  testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
123290  testcase( pTerm->wtFlags & TERM_VIRTUAL );
123291  r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
123292  if( r1!=regBase+j ){
123293  if( nReg==1 ){
123294  sqlite3ReleaseTempReg(pParse, regBase);
123295  regBase = r1;
123296  }else{
123297  sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
123298  }
123299  }
123300  testcase( pTerm->eOperator & WO_ISNULL );
123301  testcase( pTerm->eOperator & WO_IN );
123302  if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
123303  Expr *pRight = pTerm->pExpr->pRight;
123304  if( (pTerm->wtFlags & TERM_IS)==0 && sqlite3ExprCanBeNull(pRight) ){
123305  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
123306  VdbeCoverage(v);
123307  }
123308  if( zAff ){
123309  if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_BLOB ){
123310  zAff[j] = SQLITE_AFF_BLOB;
123311  }
123312  if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
123313  zAff[j] = SQLITE_AFF_BLOB;
123314  }
123315  }
123316  }
123317  }
123318  *pzAff = zAff;
123319  return regBase;
123320 }
123321 
123322 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123323 /*
123324 ** If the most recently coded instruction is a constant range constraint
123325 ** (a string literal) that originated from the LIKE optimization, then
123326 ** set P3 and P5 on the OP_String opcode so that the string will be cast
123327 ** to a BLOB at appropriate times.
123328 **
123329 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
123330 ** expression: "x>='ABC' AND x<'abd'". But this requires that the range
123331 ** scan loop run twice, once for strings and a second time for BLOBs.
123332 ** The OP_String opcodes on the second pass convert the upper and lower
123333 ** bound string contants to blobs. This routine makes the necessary changes
123334 ** to the OP_String opcodes for that to happen.
123335 **
123336 ** Except, of course, if SQLITE_LIKE_DOESNT_MATCH_BLOBS is defined, then
123337 ** only the one pass through the string space is required, so this routine
123338 ** becomes a no-op.
123339 */
123341  Vdbe *v, /* prepared statement under construction */
123342  WhereLevel *pLevel, /* The loop that contains the LIKE operator */
123343  WhereTerm *pTerm /* The upper or lower bound just coded */
123344 ){
123345  if( pTerm->wtFlags & TERM_LIKEOPT ){
123346  VdbeOp *pOp;
123347  assert( pLevel->iLikeRepCntr>0 );
123348  pOp = sqlite3VdbeGetOp(v, -1);
123349  assert( pOp!=0 );
123350  assert( pOp->opcode==OP_String8
123351  || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
123352  pOp->p3 = (int)(pLevel->iLikeRepCntr>>1); /* Register holding counter */
123353  pOp->p5 = (u8)(pLevel->iLikeRepCntr&1); /* ASC or DESC */
123354  }
123355 }
123356 #else
123357 # define whereLikeOptimizationStringFixup(A,B,C)
123358 #endif
123359 
123360 #ifdef SQLITE_ENABLE_CURSOR_HINTS
123361 /*
123362 ** Information is passed from codeCursorHint() down to individual nodes of
123363 ** the expression tree (by sqlite3WalkExpr()) using an instance of this
123364 ** structure.
123365 */
123366 struct CCurHint {
123367  int iTabCur; /* Cursor for the main table */
123368  int iIdxCur; /* Cursor for the index, if pIdx!=0. Unused otherwise */
123369  Index *pIdx; /* The index used to access the table */
123370 };
123371 
123372 /*
123373 ** This function is called for every node of an expression that is a candidate
123374 ** for a cursor hint on an index cursor. For TK_COLUMN nodes that reference
123375 ** the table CCurHint.iTabCur, verify that the same column can be
123376 ** accessed through the index. If it cannot, then set pWalker->eCode to 1.
123377 */
123378 static int codeCursorHintCheckExpr(Walker *pWalker, Expr *pExpr){
123379  struct CCurHint *pHint = pWalker->u.pCCurHint;
123380  assert( pHint->pIdx!=0 );
123381  if( pExpr->op==TK_COLUMN
123382  && pExpr->iTable==pHint->iTabCur
123383  && sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn)<0
123384  ){
123385  pWalker->eCode = 1;
123386  }
123387  return WRC_Continue;
123388 }
123389 
123390 
123391 /*
123392 ** This function is called on every node of an expression tree used as an
123393 ** argument to the OP_CursorHint instruction. If the node is a TK_COLUMN
123394 ** that accesses any table other than the one identified by
123395 ** CCurHint.iTabCur, then do the following:
123396 **
123397 ** 1) allocate a register and code an OP_Column instruction to read
123398 ** the specified column into the new register, and
123399 **
123400 ** 2) transform the expression node to a TK_REGISTER node that reads
123401 ** from the newly populated register.
123402 **
123403 ** Also, if the node is a TK_COLUMN that does access the table idenified
123404 ** by pCCurHint.iTabCur, and an index is being used (which we will
123405 ** know because CCurHint.pIdx!=0) then transform the TK_COLUMN into
123406 ** an access of the index rather than the original table.
123407 */
123408 static int codeCursorHintFixExpr(Walker *pWalker, Expr *pExpr){
123409  int rc = WRC_Continue;
123410  struct CCurHint *pHint = pWalker->u.pCCurHint;
123411  if( pExpr->op==TK_COLUMN ){
123412  if( pExpr->iTable!=pHint->iTabCur ){
123413  Vdbe *v = pWalker->pParse->pVdbe;
123414  int reg = ++pWalker->pParse->nMem; /* Register for column value */
123416  v, pExpr->pTab, pExpr->iTable, pExpr->iColumn, reg
123417  );
123418  pExpr->op = TK_REGISTER;
123419  pExpr->iTable = reg;
123420  }else if( pHint->pIdx!=0 ){
123421  pExpr->iTable = pHint->iIdxCur;
123422  pExpr->iColumn = sqlite3ColumnOfIndex(pHint->pIdx, pExpr->iColumn);
123423  assert( pExpr->iColumn>=0 );
123424  }
123425  }else if( pExpr->op==TK_AGG_FUNCTION ){
123426  /* An aggregate function in the WHERE clause of a query means this must
123427  ** be a correlated sub-query, and expression pExpr is an aggregate from
123428  ** the parent context. Do not walk the function arguments in this case.
123429  **
123430  ** todo: It should be possible to replace this node with a TK_REGISTER
123431  ** expression, as the result of the expression must be stored in a
123432  ** register at this point. The same holds for TK_AGG_COLUMN nodes. */
123433  rc = WRC_Prune;
123434  }
123435  return rc;
123436 }
123437 
123438 /*
123439 ** Insert an OP_CursorHint instruction if it is appropriate to do so.
123440 */
123441 static void codeCursorHint(
123442  WhereInfo *pWInfo, /* The where clause */
123443  WhereLevel *pLevel, /* Which loop to provide hints for */
123444  WhereTerm *pEndRange /* Hint this end-of-scan boundary term if not NULL */
123445 ){
123446  Parse *pParse = pWInfo->pParse;
123447  sqlite3 *db = pParse->db;
123448  Vdbe *v = pParse->pVdbe;
123449  Expr *pExpr = 0;
123450  WhereLoop *pLoop = pLevel->pWLoop;
123451  int iCur;
123452  WhereClause *pWC;
123453  WhereTerm *pTerm;
123454  int i, j;
123455  struct CCurHint sHint;
123456  Walker sWalker;
123457 
123458  if( OptimizationDisabled(db, SQLITE_CursorHints) ) return;
123459  iCur = pLevel->iTabCur;
123460  assert( iCur==pWInfo->pTabList->a[pLevel->iFrom].iCursor );
123461  sHint.iTabCur = iCur;
123462  sHint.iIdxCur = pLevel->iIdxCur;
123463  sHint.pIdx = pLoop->u.btree.pIndex;
123464  memset(&sWalker, 0, sizeof(sWalker));
123465  sWalker.pParse = pParse;
123466  sWalker.u.pCCurHint = &sHint;
123467  pWC = &pWInfo->sWC;
123468  for(i=0; i<pWC->nTerm; i++){
123469  pTerm = &pWC->a[i];
123470  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
123471  if( pTerm->prereqAll & pLevel->notReady ) continue;
123472  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) continue;
123473 
123474  /* All terms in pWLoop->aLTerm[] except pEndRange are used to initialize
123475  ** the cursor. These terms are not needed as hints for a pure range
123476  ** scan (that has no == terms) so omit them. */
123477  if( pLoop->u.btree.nEq==0 && pTerm!=pEndRange ){
123478  for(j=0; j<pLoop->nLTerm && pLoop->aLTerm[j]!=pTerm; j++){}
123479  if( j<pLoop->nLTerm ) continue;
123480  }
123481 
123482  /* No subqueries or non-deterministic functions allowed */
123483  if( sqlite3ExprContainsSubquery(pTerm->pExpr) ) continue;
123484 
123485  /* For an index scan, make sure referenced columns are actually in
123486  ** the index. */
123487  if( sHint.pIdx!=0 ){
123488  sWalker.eCode = 0;
123489  sWalker.xExprCallback = codeCursorHintCheckExpr;
123490  sqlite3WalkExpr(&sWalker, pTerm->pExpr);
123491  if( sWalker.eCode ) continue;
123492  }
123493 
123494  /* If we survive all prior tests, that means this term is worth hinting */
123495  pExpr = sqlite3ExprAnd(db, pExpr, sqlite3ExprDup(db, pTerm->pExpr, 0));
123496  }
123497  if( pExpr!=0 ){
123498  sWalker.xExprCallback = codeCursorHintFixExpr;
123499  sqlite3WalkExpr(&sWalker, pExpr);
123501  (sHint.pIdx ? sHint.iIdxCur : sHint.iTabCur), 0, 0,
123502  (const char*)pExpr, P4_EXPR);
123503  }
123504 }
123505 #else
123506 # define codeCursorHint(A,B,C) /* No-op */
123507 #endif /* SQLITE_ENABLE_CURSOR_HINTS */
123508 
123509 /*
123510 ** Cursor iCur is open on an intkey b-tree (a table). Register iRowid contains
123511 ** a rowid value just read from cursor iIdxCur, open on index pIdx. This
123512 ** function generates code to do a deferred seek of cursor iCur to the
123513 ** rowid stored in register iRowid.
123514 **
123515 ** Normally, this is just:
123516 **
123517 ** OP_Seek $iCur $iRowid
123518 **
123519 ** However, if the scan currently being coded is a branch of an OR-loop and
123520 ** the statement currently being coded is a SELECT, then P3 of the OP_Seek
123521 ** is set to iIdxCur and P4 is set to point to an array of integers
123522 ** containing one entry for each column of the table cursor iCur is open
123523 ** on. For each table column, if the column is the i'th column of the
123524 ** index, then the corresponding array entry is set to (i+1). If the column
123525 ** does not appear in the index at all, the array entry is set to 0.
123526 */
123527 static void codeDeferredSeek(
123528  WhereInfo *pWInfo, /* Where clause context */
123529  Index *pIdx, /* Index scan is using */
123530  int iCur, /* Cursor for IPK b-tree */
123531  int iIdxCur /* Index cursor */
123532 ){
123533  Parse *pParse = pWInfo->pParse; /* Parse context */
123534  Vdbe *v = pParse->pVdbe; /* Vdbe to generate code within */
123535 
123536  assert( iIdxCur>0 );
123537  assert( pIdx->aiColumn[pIdx->nColumn-1]==-1 );
123538 
123539  sqlite3VdbeAddOp3(v, OP_Seek, iIdxCur, 0, iCur);
123540  if( (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)
123541  && DbMaskAllZero(sqlite3ParseToplevel(pParse)->writeMask)
123542  ){
123543  int i;
123544  Table *pTab = pIdx->pTable;
123545  int *ai = (int*)sqlite3DbMallocZero(pParse->db, sizeof(int)*(pTab->nCol+1));
123546  if( ai ){
123547  ai[0] = pTab->nCol;
123548  for(i=0; i<pIdx->nColumn-1; i++){
123549  assert( pIdx->aiColumn[i]<pTab->nCol );
123550  if( pIdx->aiColumn[i]>=0 ) ai[pIdx->aiColumn[i]+1] = i+1;
123551  }
123552  sqlite3VdbeChangeP4(v, -1, (char*)ai, P4_INTARRAY);
123553  }
123554  }
123555 }
123556 
123557 /*
123558 ** Generate code for the start of the iLevel-th loop in the WHERE clause
123559 ** implementation described by pWInfo.
123560 */
123562  WhereInfo *pWInfo, /* Complete information about the WHERE clause */
123563  int iLevel, /* Which level of pWInfo->a[] should be coded */
123564  Bitmask notReady /* Which tables are currently available */
123565 ){
123566  int j, k; /* Loop counters */
123567  int iCur; /* The VDBE cursor for the table */
123568  int addrNxt; /* Where to jump to continue with the next IN case */
123569  int omitTable; /* True if we use the index only */
123570  int bRev; /* True if we need to scan in reverse order */
123571  WhereLevel *pLevel; /* The where level to be coded */
123572  WhereLoop *pLoop; /* The WhereLoop object being coded */
123573  WhereClause *pWC; /* Decomposition of the entire WHERE clause */
123574  WhereTerm *pTerm; /* A WHERE clause term */
123575  Parse *pParse; /* Parsing context */
123576  sqlite3 *db; /* Database connection */
123577  Vdbe *v; /* The prepared stmt under constructions */
123578  struct SrcList_item *pTabItem; /* FROM clause term being coded */
123579  int addrBrk; /* Jump here to break out of the loop */
123580  int addrCont; /* Jump here to continue with next cycle */
123581  int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
123582  int iReleaseReg = 0; /* Temp register to free before returning */
123583 
123584  pParse = pWInfo->pParse;
123585  v = pParse->pVdbe;
123586  pWC = &pWInfo->sWC;
123587  db = pParse->db;
123588  pLevel = &pWInfo->a[iLevel];
123589  pLoop = pLevel->pWLoop;
123590  pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
123591  iCur = pTabItem->iCursor;
123592  pLevel->notReady = notReady & ~sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
123593  bRev = (pWInfo->revMask>>iLevel)&1;
123594  omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
123595  && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
123596  VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
123597 
123598  /* Create labels for the "break" and "continue" instructions
123599  ** for the current loop. Jump to addrBrk to break out of a loop.
123600  ** Jump to cont to go immediately to the next iteration of the
123601  ** loop.
123602  **
123603  ** When there is an IN operator, we also have a "addrNxt" label that
123604  ** means to continue with the next IN value combination. When
123605  ** there are no IN operators in the constraints, the "addrNxt" label
123606  ** is the same as "addrBrk".
123607  */
123608  addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
123609  addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
123610 
123611  /* If this is the right table of a LEFT OUTER JOIN, allocate and
123612  ** initialize a memory cell that records if this table matches any
123613  ** row of the left table of the join.
123614  */
123615  if( pLevel->iFrom>0 && (pTabItem[0].fg.jointype & JT_LEFT)!=0 ){
123616  pLevel->iLeftJoin = ++pParse->nMem;
123617  sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
123618  VdbeComment((v, "init LEFT JOIN no-match flag"));
123619  }
123620 
123621  /* Special case of a FROM clause subquery implemented as a co-routine */
123622  if( pTabItem->fg.viaCoroutine ){
123623  int regYield = pTabItem->regReturn;
123624  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
123625  pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
123626  VdbeCoverage(v);
123627  VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
123628  pLevel->op = OP_Goto;
123629  }else
123630 
123631 #ifndef SQLITE_OMIT_VIRTUALTABLE
123632  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
123633  /* Case 1: The table is a virtual-table. Use the VFilter and VNext
123634  ** to access the data.
123635  */
123636  int iReg; /* P3 Value for OP_VFilter */
123637  int addrNotFound;
123638  int nConstraint = pLoop->nLTerm;
123639  int iIn; /* Counter for IN constraints */
123640 
123641  sqlite3ExprCachePush(pParse);
123642  iReg = sqlite3GetTempRange(pParse, nConstraint+2);
123643  addrNotFound = pLevel->addrBrk;
123644  for(j=0; j<nConstraint; j++){
123645  int iTarget = iReg+j+2;
123646  pTerm = pLoop->aLTerm[j];
123647  if( NEVER(pTerm==0) ) continue;
123648  if( pTerm->eOperator & WO_IN ){
123649  codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
123650  addrNotFound = pLevel->addrNxt;
123651  }else{
123652  sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
123653  }
123654  }
123655  sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
123656  sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
123657  sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
123658  pLoop->u.vtab.idxStr,
123659  pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
123660  VdbeCoverage(v);
123661  pLoop->u.vtab.needFree = 0;
123662  pLevel->p1 = iCur;
123663  pLevel->op = pWInfo->eOnePass ? OP_Noop : OP_VNext;
123664  pLevel->p2 = sqlite3VdbeCurrentAddr(v);
123665  iIn = pLevel->u.in.nIn;
123666  for(j=nConstraint-1; j>=0; j--){
123667  pTerm = pLoop->aLTerm[j];
123668  if( j<16 && (pLoop->u.vtab.omitMask>>j)&1 ){
123669  disableTerm(pLevel, pTerm);
123670  }else if( (pTerm->eOperator & WO_IN)!=0 ){
123671  Expr *pCompare; /* The comparison operator */
123672  Expr *pRight; /* RHS of the comparison */
123673  VdbeOp *pOp; /* Opcode to access the value of the IN constraint */
123674 
123675  /* Reload the constraint value into reg[iReg+j+2]. The same value
123676  ** was loaded into the same register prior to the OP_VFilter, but
123677  ** the xFilter implementation might have changed the datatype or
123678  ** encoding of the value in the register, so it *must* be reloaded. */
123679  assert( pLevel->u.in.aInLoop!=0 || db->mallocFailed );
123680  if( !db->mallocFailed ){
123681  assert( iIn>0 );
123682  pOp = sqlite3VdbeGetOp(v, pLevel->u.in.aInLoop[--iIn].addrInTop);
123683  assert( pOp->opcode==OP_Column || pOp->opcode==OP_Rowid );
123684  assert( pOp->opcode!=OP_Column || pOp->p3==iReg+j+2 );
123685  assert( pOp->opcode!=OP_Rowid || pOp->p2==iReg+j+2 );
123686  testcase( pOp->opcode==OP_Rowid );
123687  sqlite3VdbeAddOp3(v, pOp->opcode, pOp->p1, pOp->p2, pOp->p3);
123688  }
123689 
123690  /* Generate code that will continue to the next row if
123691  ** the IN constraint is not satisfied */
123692  pCompare = sqlite3PExpr(pParse, TK_EQ, 0, 0, 0);
123693  assert( pCompare!=0 || db->mallocFailed );
123694  if( pCompare ){
123695  pCompare->pLeft = pTerm->pExpr->pLeft;
123696  pCompare->pRight = pRight = sqlite3Expr(db, TK_REGISTER, 0);
123697  if( pRight ){
123698  pRight->iTable = iReg+j+2;
123699  sqlite3ExprIfFalse(pParse, pCompare, pLevel->addrCont, 0);
123700  }
123701  pCompare->pLeft = 0;
123702  sqlite3ExprDelete(db, pCompare);
123703  }
123704  }
123705  }
123706  /* These registers need to be preserved in case there is an IN operator
123707  ** loop. So we could deallocate the registers here (and potentially
123708  ** reuse them later) if (pLoop->wsFlags & WHERE_IN_ABLE)==0. But it seems
123709  ** simpler and safer to simply not reuse the registers.
123710  **
123711  ** sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
123712  */
123713  sqlite3ExprCachePop(pParse);
123714  }else
123715 #endif /* SQLITE_OMIT_VIRTUALTABLE */
123716 
123717  if( (pLoop->wsFlags & WHERE_IPK)!=0
123718  && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
123719  ){
123720  /* Case 2: We can directly reference a single row using an
123721  ** equality comparison against the ROWID field. Or
123722  ** we reference multiple rows using a "rowid IN (...)"
123723  ** construct.
123724  */
123725  assert( pLoop->u.btree.nEq==1 );
123726  pTerm = pLoop->aLTerm[0];
123727  assert( pTerm!=0 );
123728  assert( pTerm->pExpr!=0 );
123729  assert( omitTable==0 );
123730  testcase( pTerm->wtFlags & TERM_VIRTUAL );
123731  iReleaseReg = ++pParse->nMem;
123732  iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
123733  if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
123734  addrNxt = pLevel->addrNxt;
123735  sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
123736  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
123737  VdbeCoverage(v);
123738  sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
123739  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
123740  VdbeComment((v, "pk"));
123741  pLevel->op = OP_Noop;
123742  }else if( (pLoop->wsFlags & WHERE_IPK)!=0
123743  && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
123744  ){
123745  /* Case 3: We have an inequality comparison against the ROWID field.
123746  */
123747  int testOp = OP_Noop;
123748  int start;
123749  int memEndValue = 0;
123750  WhereTerm *pStart, *pEnd;
123751 
123752  assert( omitTable==0 );
123753  j = 0;
123754  pStart = pEnd = 0;
123755  if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
123756  if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
123757  assert( pStart!=0 || pEnd!=0 );
123758  if( bRev ){
123759  pTerm = pStart;
123760  pStart = pEnd;
123761  pEnd = pTerm;
123762  }
123763  codeCursorHint(pWInfo, pLevel, pEnd);
123764  if( pStart ){
123765  Expr *pX; /* The expression that defines the start bound */
123766  int r1, rTemp; /* Registers for holding the start boundary */
123767 
123768  /* The following constant maps TK_xx codes into corresponding
123769  ** seek opcodes. It depends on a particular ordering of TK_xx
123770  */
123771  const u8 aMoveOp[] = {
123772  /* TK_GT */ OP_SeekGT,
123773  /* TK_LE */ OP_SeekLE,
123774  /* TK_LT */ OP_SeekLT,
123775  /* TK_GE */ OP_SeekGE
123776  };
123777  assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
123778  assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
123779  assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
123780 
123781  assert( (pStart->wtFlags & TERM_VNULL)==0 );
123782  testcase( pStart->wtFlags & TERM_VIRTUAL );
123783  pX = pStart->pExpr;
123784  assert( pX!=0 );
123785  testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
123786  r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
123787  sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
123788  VdbeComment((v, "pk"));
123789  VdbeCoverageIf(v, pX->op==TK_GT);
123790  VdbeCoverageIf(v, pX->op==TK_LE);
123791  VdbeCoverageIf(v, pX->op==TK_LT);
123792  VdbeCoverageIf(v, pX->op==TK_GE);
123793  sqlite3ExprCacheAffinityChange(pParse, r1, 1);
123794  sqlite3ReleaseTempReg(pParse, rTemp);
123795  disableTerm(pLevel, pStart);
123796  }else{
123797  sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
123798  VdbeCoverageIf(v, bRev==0);
123799  VdbeCoverageIf(v, bRev!=0);
123800  }
123801  if( pEnd ){
123802  Expr *pX;
123803  pX = pEnd->pExpr;
123804  assert( pX!=0 );
123805  assert( (pEnd->wtFlags & TERM_VNULL)==0 );
123806  testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
123807  testcase( pEnd->wtFlags & TERM_VIRTUAL );
123808  memEndValue = ++pParse->nMem;
123809  sqlite3ExprCode(pParse, pX->pRight, memEndValue);
123810  if( pX->op==TK_LT || pX->op==TK_GT ){
123811  testOp = bRev ? OP_Le : OP_Ge;
123812  }else{
123813  testOp = bRev ? OP_Lt : OP_Gt;
123814  }
123815  disableTerm(pLevel, pEnd);
123816  }
123817  start = sqlite3VdbeCurrentAddr(v);
123818  pLevel->op = bRev ? OP_Prev : OP_Next;
123819  pLevel->p1 = iCur;
123820  pLevel->p2 = start;
123821  assert( pLevel->p5==0 );
123822  if( testOp!=OP_Noop ){
123823  iRowidReg = ++pParse->nMem;
123824  sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
123825  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
123826  sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
123827  VdbeCoverageIf(v, testOp==OP_Le);
123828  VdbeCoverageIf(v, testOp==OP_Lt);
123829  VdbeCoverageIf(v, testOp==OP_Ge);
123830  VdbeCoverageIf(v, testOp==OP_Gt);
123832  }
123833  }else if( pLoop->wsFlags & WHERE_INDEXED ){
123834  /* Case 4: A scan using an index.
123835  **
123836  ** The WHERE clause may contain zero or more equality
123837  ** terms ("==" or "IN" operators) that refer to the N
123838  ** left-most columns of the index. It may also contain
123839  ** inequality constraints (>, <, >= or <=) on the indexed
123840  ** column that immediately follows the N equalities. Only
123841  ** the right-most column can be an inequality - the rest must
123842  ** use the "==" and "IN" operators. For example, if the
123843  ** index is on (x,y,z), then the following clauses are all
123844  ** optimized:
123845  **
123846  ** x=5
123847  ** x=5 AND y=10
123848  ** x=5 AND y<10
123849  ** x=5 AND y>5 AND y<10
123850  ** x=5 AND y=5 AND z<=10
123851  **
123852  ** The z<10 term of the following cannot be used, only
123853  ** the x=5 term:
123854  **
123855  ** x=5 AND z<10
123856  **
123857  ** N may be zero if there are inequality constraints.
123858  ** If there are no inequality constraints, then N is at
123859  ** least one.
123860  **
123861  ** This case is also used when there are no WHERE clause
123862  ** constraints but an index is selected anyway, in order
123863  ** to force the output order to conform to an ORDER BY.
123864  */
123865  static const u8 aStartOp[] = {
123866  0,
123867  0,
123868  OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
123869  OP_Last, /* 3: (!start_constraints && startEq && bRev) */
123870  OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
123871  OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
123872  OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
123873  OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
123874  };
123875  static const u8 aEndOp[] = {
123876  OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
123877  OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
123878  OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
123879  OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
123880  };
123881  u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
123882  int regBase; /* Base register holding constraint values */
123883  WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
123884  WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
123885  int startEq; /* True if range start uses ==, >= or <= */
123886  int endEq; /* True if range end uses ==, >= or <= */
123887  int start_constraints; /* Start of range is constrained */
123888  int nConstraint; /* Number of constraint terms */
123889  Index *pIdx; /* The index we will be using */
123890  int iIdxCur; /* The VDBE cursor for the index */
123891  int nExtraReg = 0; /* Number of extra registers needed */
123892  int op; /* Instruction opcode */
123893  char *zStartAff; /* Affinity for start of range constraint */
123894  char cEndAff = 0; /* Affinity for end of range constraint */
123895  u8 bSeekPastNull = 0; /* True to seek past initial nulls */
123896  u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
123897 
123898  pIdx = pLoop->u.btree.pIndex;
123899  iIdxCur = pLevel->iIdxCur;
123900  assert( nEq>=pLoop->nSkip );
123901 
123902  /* If this loop satisfies a sort order (pOrderBy) request that
123903  ** was passed to this function to implement a "SELECT min(x) ..."
123904  ** query, then the caller will only allow the loop to run for
123905  ** a single iteration. This means that the first row returned
123906  ** should not have a NULL value stored in 'x'. If column 'x' is
123907  ** the first one after the nEq equality constraints in the index,
123908  ** this requires some special handling.
123909  */
123910  assert( pWInfo->pOrderBy==0
123911  || pWInfo->pOrderBy->nExpr==1
123912  || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
123913  if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
123914  && pWInfo->nOBSat>0
123915  && (pIdx->nKeyCol>nEq)
123916  ){
123917  assert( pLoop->nSkip==0 );
123918  bSeekPastNull = 1;
123919  nExtraReg = 1;
123920  }
123921 
123922  /* Find any inequality constraint terms for the start and end
123923  ** of the range.
123924  */
123925  j = nEq;
123926  if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
123927  pRangeStart = pLoop->aLTerm[j++];
123928  nExtraReg = 1;
123929  /* Like optimization range constraints always occur in pairs */
123930  assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 ||
123931  (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
123932  }
123933  if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
123934  pRangeEnd = pLoop->aLTerm[j++];
123935  nExtraReg = 1;
123936 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
123937  if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
123938  assert( pRangeStart!=0 ); /* LIKE opt constraints */
123939  assert( pRangeStart->wtFlags & TERM_LIKEOPT ); /* occur in pairs */
123940  pLevel->iLikeRepCntr = (u32)++pParse->nMem;
123941  sqlite3VdbeAddOp2(v, OP_Integer, 1, (int)pLevel->iLikeRepCntr);
123942  VdbeComment((v, "LIKE loop counter"));
123943  pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
123944  /* iLikeRepCntr actually stores 2x the counter register number. The
123945  ** bottom bit indicates whether the search order is ASC or DESC. */
123946  testcase( bRev );
123947  testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
123948  assert( (bRev & ~1)==0 );
123949  pLevel->iLikeRepCntr <<=1;
123950  pLevel->iLikeRepCntr |= bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC);
123951  }
123952 #endif
123953  if( pRangeStart==0
123954  && (j = pIdx->aiColumn[nEq])>=0
123955  && pIdx->pTable->aCol[j].notNull==0
123956  ){
123957  bSeekPastNull = 1;
123958  }
123959  }
123960  assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
123961 
123962  /* If we are doing a reverse order scan on an ascending index, or
123963  ** a forward order scan on a descending index, interchange the
123964  ** start and end terms (pRangeStart and pRangeEnd).
123965  */
123966  if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
123967  || (bRev && pIdx->nKeyCol==nEq)
123968  ){
123969  SWAP(WhereTerm *, pRangeEnd, pRangeStart);
123970  SWAP(u8, bSeekPastNull, bStopAtNull);
123971  }
123972 
123973  /* Generate code to evaluate all constraint terms using == or IN
123974  ** and store the values of those terms in an array of registers
123975  ** starting at regBase.
123976  */
123977  codeCursorHint(pWInfo, pLevel, pRangeEnd);
123978  regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
123979  assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
123980  if( zStartAff ) cEndAff = zStartAff[nEq];
123981  addrNxt = pLevel->addrNxt;
123982 
123983  testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
123984  testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
123985  testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
123986  testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
123987  startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
123988  endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
123989  start_constraints = pRangeStart || nEq>0;
123990 
123991  /* Seek the index cursor to the start of the range. */
123992  nConstraint = nEq;
123993  if( pRangeStart ){
123994  Expr *pRight = pRangeStart->pExpr->pRight;
123995  sqlite3ExprCode(pParse, pRight, regBase+nEq);
123996  whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
123997  if( (pRangeStart->wtFlags & TERM_VNULL)==0
123998  && sqlite3ExprCanBeNull(pRight)
123999  ){
124000  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124001  VdbeCoverage(v);
124002  }
124003  if( zStartAff ){
124004  if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_BLOB){
124005  /* Since the comparison is to be performed with no conversions
124006  ** applied to the operands, set the affinity to apply to pRight to
124007  ** SQLITE_AFF_BLOB. */
124008  zStartAff[nEq] = SQLITE_AFF_BLOB;
124009  }
124010  if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
124011  zStartAff[nEq] = SQLITE_AFF_BLOB;
124012  }
124013  }
124014  nConstraint++;
124015  testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
124016  }else if( bSeekPastNull ){
124017  sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124018  nConstraint++;
124019  startEq = 0;
124020  start_constraints = 1;
124021  }
124022  codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
124023  if( pLoop->nSkip>0 && nConstraint==pLoop->nSkip ){
124024  /* The skip-scan logic inside the call to codeAllEqualityConstraints()
124025  ** above has already left the cursor sitting on the correct row,
124026  ** so no further seeking is needed */
124027  }else{
124028  op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
124029  assert( op!=0 );
124030  sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124031  VdbeCoverage(v);
124032  VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
124033  VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
124034  VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
124035  VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
124036  VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
124037  VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
124038  }
124039 
124040  /* Load the value for the inequality constraint at the end of the
124041  ** range (if any).
124042  */
124043  nConstraint = nEq;
124044  if( pRangeEnd ){
124045  Expr *pRight = pRangeEnd->pExpr->pRight;
124046  sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
124047  sqlite3ExprCode(pParse, pRight, regBase+nEq);
124048  whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
124049  if( (pRangeEnd->wtFlags & TERM_VNULL)==0
124050  && sqlite3ExprCanBeNull(pRight)
124051  ){
124052  sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
124053  VdbeCoverage(v);
124054  }
124055  if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_BLOB
124056  && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
124057  ){
124058  codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
124059  }
124060  nConstraint++;
124061  testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
124062  }else if( bStopAtNull ){
124063  sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
124064  endEq = 0;
124065  nConstraint++;
124066  }
124067  sqlite3DbFree(db, zStartAff);
124068 
124069  /* Top of the loop body */
124070  pLevel->p2 = sqlite3VdbeCurrentAddr(v);
124071 
124072  /* Check if the index cursor is past the end of the range. */
124073  if( nConstraint ){
124074  op = aEndOp[bRev*2 + endEq];
124075  sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
124076  testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
124077  testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
124078  testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
124079  testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
124080  }
124081 
124082  /* Seek the table cursor, if required */
124083  disableTerm(pLevel, pRangeStart);
124084  disableTerm(pLevel, pRangeEnd);
124085  if( omitTable ){
124086  /* pIdx is a covering index. No need to access the main table. */
124087  }else if( HasRowid(pIdx->pTable) ){
124088  if( (pWInfo->wctrlFlags & WHERE_SEEK_TABLE)!=0 ){
124089  iRowidReg = ++pParse->nMem;
124090  sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
124091  sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
124092  sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, iRowidReg);
124093  VdbeCoverage(v);
124094  }else{
124095  codeDeferredSeek(pWInfo, pIdx, iCur, iIdxCur);
124096  }
124097  }else if( iCur!=iIdxCur ){
124098  Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
124099  iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
124100  for(j=0; j<pPk->nKeyCol; j++){
124101  k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
124102  sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
124103  }
124104  sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
124105  iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
124106  }
124107 
124108  /* Record the instruction used to terminate the loop. Disable
124109  ** WHERE clause terms made redundant by the index range scan.
124110  */
124111  if( pLoop->wsFlags & WHERE_ONEROW ){
124112  pLevel->op = OP_Noop;
124113  }else if( bRev ){
124114  pLevel->op = OP_Prev;
124115  }else{
124116  pLevel->op = OP_Next;
124117  }
124118  pLevel->p1 = iIdxCur;
124119  pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
124120  if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
124122  }else{
124123  assert( pLevel->p5==0 );
124124  }
124125  }else
124126 
124127 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
124128  if( pLoop->wsFlags & WHERE_MULTI_OR ){
124129  /* Case 5: Two or more separately indexed terms connected by OR
124130  **
124131  ** Example:
124132  **
124133  ** CREATE TABLE t1(a,b,c,d);
124134  ** CREATE INDEX i1 ON t1(a);
124135  ** CREATE INDEX i2 ON t1(b);
124136  ** CREATE INDEX i3 ON t1(c);
124137  **
124138  ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
124139  **
124140  ** In the example, there are three indexed terms connected by OR.
124141  ** The top of the loop looks like this:
124142  **
124143  ** Null 1 # Zero the rowset in reg 1
124144  **
124145  ** Then, for each indexed term, the following. The arguments to
124146  ** RowSetTest are such that the rowid of the current row is inserted
124147  ** into the RowSet. If it is already present, control skips the
124148  ** Gosub opcode and jumps straight to the code generated by WhereEnd().
124149  **
124150  ** sqlite3WhereBegin(<term>)
124151  ** RowSetTest # Insert rowid into rowset
124152  ** Gosub 2 A
124153  ** sqlite3WhereEnd()
124154  **
124155  ** Following the above, code to terminate the loop. Label A, the target
124156  ** of the Gosub above, jumps to the instruction right after the Goto.
124157  **
124158  ** Null 1 # Zero the rowset in reg 1
124159  ** Goto B # The loop is finished.
124160  **
124161  ** A: <loop body> # Return data, whatever.
124162  **
124163  ** Return 2 # Jump back to the Gosub
124164  **
124165  ** B: <after the loop>
124166  **
124167  ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
124168  ** use an ephemeral index instead of a RowSet to record the primary
124169  ** keys of the rows we have already seen.
124170  **
124171  */
124172  WhereClause *pOrWc; /* The OR-clause broken out into subterms */
124173  SrcList *pOrTab; /* Shortened table list or OR-clause generation */
124174  Index *pCov = 0; /* Potential covering index (or NULL) */
124175  int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
124176 
124177  int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
124178  int regRowset = 0; /* Register for RowSet object */
124179  int regRowid = 0; /* Register holding rowid */
124180  int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
124181  int iRetInit; /* Address of regReturn init */
124182  int untestedTerms = 0; /* Some terms not completely tested */
124183  int ii; /* Loop counter */
124184  u16 wctrlFlags; /* Flags for sub-WHERE clause */
124185  Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
124186  Table *pTab = pTabItem->pTab;
124187 
124188  pTerm = pLoop->aLTerm[0];
124189  assert( pTerm!=0 );
124190  assert( pTerm->eOperator & WO_OR );
124191  assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
124192  pOrWc = &pTerm->u.pOrInfo->wc;
124193  pLevel->op = OP_Return;
124194  pLevel->p1 = regReturn;
124195 
124196  /* Set up a new SrcList in pOrTab containing the table being scanned
124197  ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
124198  ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
124199  */
124200  if( pWInfo->nLevel>1 ){
124201  int nNotReady; /* The number of notReady tables */
124202  struct SrcList_item *origSrc; /* Original list of tables */
124203  nNotReady = pWInfo->nLevel - iLevel - 1;
124204  pOrTab = sqlite3StackAllocRaw(db,
124205  sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
124206  if( pOrTab==0 ) return notReady;
124207  pOrTab->nAlloc = (u8)(nNotReady + 1);
124208  pOrTab->nSrc = pOrTab->nAlloc;
124209  memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
124210  origSrc = pWInfo->pTabList->a;
124211  for(k=1; k<=nNotReady; k++){
124212  memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
124213  }
124214  }else{
124215  pOrTab = pWInfo->pTabList;
124216  }
124217 
124218  /* Initialize the rowset register to contain NULL. An SQL NULL is
124219  ** equivalent to an empty rowset. Or, create an ephemeral index
124220  ** capable of holding primary keys in the case of a WITHOUT ROWID.
124221  **
124222  ** Also initialize regReturn to contain the address of the instruction
124223  ** immediately following the OP_Return at the bottom of the loop. This
124224  ** is required in a few obscure LEFT JOIN cases where control jumps
124225  ** over the top of the loop into the body of it. In this case the
124226  ** correct response for the end-of-loop code (the OP_Return) is to
124227  ** fall through to the next instruction, just as an OP_Next does if
124228  ** called on an uninitialized cursor.
124229  */
124230  if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
124231  if( HasRowid(pTab) ){
124232  regRowset = ++pParse->nMem;
124233  sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
124234  }else{
124235  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
124236  regRowset = pParse->nTab++;
124237  sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
124238  sqlite3VdbeSetP4KeyInfo(pParse, pPk);
124239  }
124240  regRowid = ++pParse->nMem;
124241  }
124242  iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
124243 
124244  /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
124245  ** Then for every term xN, evaluate as the subexpression: xN AND z
124246  ** That way, terms in y that are factored into the disjunction will
124247  ** be picked up by the recursive calls to sqlite3WhereBegin() below.
124248  **
124249  ** Actually, each subexpression is converted to "xN AND w" where w is
124250  ** the "interesting" terms of z - terms that did not originate in the
124251  ** ON or USING clause of a LEFT JOIN, and terms that are usable as
124252  ** indices.
124253  **
124254  ** This optimization also only applies if the (x1 OR x2 OR ...) term
124255  ** is not contained in the ON clause of a LEFT JOIN.
124256  ** See ticket http://www.sqlite.org/src/info/f2369304e4
124257  */
124258  if( pWC->nTerm>1 ){
124259  int iTerm;
124260  for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
124261  Expr *pExpr = pWC->a[iTerm].pExpr;
124262  if( &pWC->a[iTerm] == pTerm ) continue;
124263  if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
124264  testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
124265  testcase( pWC->a[iTerm].wtFlags & TERM_CODED );
124266  if( (pWC->a[iTerm].wtFlags & (TERM_VIRTUAL|TERM_CODED))!=0 ) continue;
124267  if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
124268  testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
124269  pExpr = sqlite3ExprDup(db, pExpr, 0);
124270  pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
124271  }
124272  if( pAndExpr ){
124273  pAndExpr = sqlite3PExpr(pParse, TK_AND|TKFLG_DONTFOLD, 0, pAndExpr, 0);
124274  }
124275  }
124276 
124277  /* Run a separate WHERE clause for each term of the OR clause. After
124278  ** eliminating duplicates from other WHERE clauses, the action for each
124279  ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
124280  */
124281  wctrlFlags = WHERE_OMIT_OPEN_CLOSE
124285  | (pWInfo->wctrlFlags & WHERE_SEEK_TABLE);
124286  for(ii=0; ii<pOrWc->nTerm; ii++){
124287  WhereTerm *pOrTerm = &pOrWc->a[ii];
124288  if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
124289  WhereInfo *pSubWInfo; /* Info for single OR-term scan */
124290  Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
124291  int jmp1 = 0; /* Address of jump operation */
124292  if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
124293  pAndExpr->pLeft = pOrExpr;
124294  pOrExpr = pAndExpr;
124295  }
124296  /* Loop through table entries that match term pOrTerm. */
124297  WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
124298  pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
124299  wctrlFlags, iCovCur);
124300  assert( pSubWInfo || pParse->nErr || db->mallocFailed );
124301  if( pSubWInfo ){
124302  WhereLoop *pSubLoop;
124303  int addrExplain = sqlite3WhereExplainOneScan(
124304  pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
124305  );
124306  sqlite3WhereAddScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
124307 
124308  /* This is the sub-WHERE clause body. First skip over
124309  ** duplicate rows from prior sub-WHERE clauses, and record the
124310  ** rowid (or PRIMARY KEY) for the current row so that the same
124311  ** row will be skipped in subsequent sub-WHERE clauses.
124312  */
124313  if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
124314  int r;
124315  int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
124316  if( HasRowid(pTab) ){
124317  r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
124318  jmp1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0,
124319  r,iSet);
124320  VdbeCoverage(v);
124321  }else{
124322  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
124323  int nPk = pPk->nKeyCol;
124324  int iPk;
124325 
124326  /* Read the PK into an array of temp registers. */
124327  r = sqlite3GetTempRange(pParse, nPk);
124328  for(iPk=0; iPk<nPk; iPk++){
124329  int iCol = pPk->aiColumn[iPk];
124330  sqlite3ExprCodeGetColumnToReg(pParse, pTab, iCol, iCur, r+iPk);
124331  }
124332 
124333  /* Check if the temp table already contains this key. If so,
124334  ** the row has already been included in the result set and
124335  ** can be ignored (by jumping past the Gosub below). Otherwise,
124336  ** insert the key into the temp table and proceed with processing
124337  ** the row.
124338  **
124339  ** Use some of the same optimizations as OP_RowSetTest: If iSet
124340  ** is zero, assume that the key cannot already be present in
124341  ** the temp table. And if iSet is -1, assume that there is no
124342  ** need to insert the key into the temp table, as it will never
124343  ** be tested for. */
124344  if( iSet ){
124345  jmp1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
124346  VdbeCoverage(v);
124347  }
124348  if( iSet>=0 ){
124349  sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
124350  sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
124351  if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
124352  }
124353 
124354  /* Release the array of temp registers */
124355  sqlite3ReleaseTempRange(pParse, r, nPk);
124356  }
124357  }
124358 
124359  /* Invoke the main loop body as a subroutine */
124360  sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
124361 
124362  /* Jump here (skipping the main loop body subroutine) if the
124363  ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
124364  if( jmp1 ) sqlite3VdbeJumpHere(v, jmp1);
124365 
124366  /* The pSubWInfo->untestedTerms flag means that this OR term
124367  ** contained one or more AND term from a notReady table. The
124368  ** terms from the notReady table could not be tested and will
124369  ** need to be tested later.
124370  */
124371  if( pSubWInfo->untestedTerms ) untestedTerms = 1;
124372 
124373  /* If all of the OR-connected terms are optimized using the same
124374  ** index, and the index is opened using the same cursor number
124375  ** by each call to sqlite3WhereBegin() made by this loop, it may
124376  ** be possible to use that index as a covering index.
124377  **
124378  ** If the call to sqlite3WhereBegin() above resulted in a scan that
124379  ** uses an index, and this is either the first OR-connected term
124380  ** processed or the index is the same as that used by all previous
124381  ** terms, set pCov to the candidate covering index. Otherwise, set
124382  ** pCov to NULL to indicate that no candidate covering index will
124383  ** be available.
124384  */
124385  pSubLoop = pSubWInfo->a[0].pWLoop;
124386  assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
124387  if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
124388  && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
124389  && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
124390  ){
124391  assert( pSubWInfo->a[0].iIdxCur==iCovCur );
124392  pCov = pSubLoop->u.btree.pIndex;
124393  wctrlFlags |= WHERE_REOPEN_IDX;
124394  }else{
124395  pCov = 0;
124396  }
124397 
124398  /* Finish the loop through table entries that match term pOrTerm. */
124399  sqlite3WhereEnd(pSubWInfo);
124400  }
124401  }
124402  }
124403  pLevel->u.pCovidx = pCov;
124404  if( pCov ) pLevel->iIdxCur = iCovCur;
124405  if( pAndExpr ){
124406  pAndExpr->pLeft = 0;
124407  sqlite3ExprDelete(db, pAndExpr);
124408  }
124409  sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
124410  sqlite3VdbeGoto(v, pLevel->addrBrk);
124411  sqlite3VdbeResolveLabel(v, iLoopBody);
124412 
124413  if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
124414  if( !untestedTerms ) disableTerm(pLevel, pTerm);
124415  }else
124416 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
124417 
124418  {
124419  /* Case 6: There is no usable index. We must do a complete
124420  ** scan of the entire table.
124421  */
124422  static const u8 aStep[] = { OP_Next, OP_Prev };
124423  static const u8 aStart[] = { OP_Rewind, OP_Last };
124424  assert( bRev==0 || bRev==1 );
124425  if( pTabItem->fg.isRecursive ){
124426  /* Tables marked isRecursive have only a single row that is stored in
124427  ** a pseudo-cursor. No need to Rewind or Next such cursors. */
124428  pLevel->op = OP_Noop;
124429  }else{
124430  codeCursorHint(pWInfo, pLevel, 0);
124431  pLevel->op = aStep[bRev];
124432  pLevel->p1 = iCur;
124433  pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
124434  VdbeCoverageIf(v, bRev==0);
124435  VdbeCoverageIf(v, bRev!=0);
124437  }
124438  }
124439 
124440 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
124441  pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
124442 #endif
124443 
124444  /* Insert code to test every subexpression that can be completely
124445  ** computed using the current set of tables.
124446  */
124447  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
124448  Expr *pE;
124449  int skipLikeAddr = 0;
124450  testcase( pTerm->wtFlags & TERM_VIRTUAL );
124451  testcase( pTerm->wtFlags & TERM_CODED );
124452  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124453  if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
124454  testcase( pWInfo->untestedTerms==0
124455  && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
124456  pWInfo->untestedTerms = 1;
124457  continue;
124458  }
124459  pE = pTerm->pExpr;
124460  assert( pE!=0 );
124461  if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
124462  continue;
124463  }
124464  if( pTerm->wtFlags & TERM_LIKECOND ){
124465  /* If the TERM_LIKECOND flag is set, that means that the range search
124466  ** is sufficient to guarantee that the LIKE operator is true, so we
124467  ** can skip the call to the like(A,B) function. But this only works
124468  ** for strings. So do not skip the call to the function on the pass
124469  ** that compares BLOBs. */
124470 #ifdef SQLITE_LIKE_DOESNT_MATCH_BLOBS
124471  continue;
124472 #else
124473  u32 x = pLevel->iLikeRepCntr;
124474  assert( x>0 );
124475  skipLikeAddr = sqlite3VdbeAddOp1(v, (x&1)? OP_IfNot : OP_If, (int)(x>>1));
124476  VdbeCoverage(v);
124477 #endif
124478  }
124479  sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
124480  if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
124481  pTerm->wtFlags |= TERM_CODED;
124482  }
124483 
124484  /* Insert code to test for implied constraints based on transitivity
124485  ** of the "==" operator.
124486  **
124487  ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
124488  ** and we are coding the t1 loop and the t2 loop has not yet coded,
124489  ** then we cannot use the "t1.a=t2.b" constraint, but we can code
124490  ** the implied "t1.a=123" constraint.
124491  */
124492  for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
124493  Expr *pE, *pEAlt;
124494  WhereTerm *pAlt;
124495  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124496  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) continue;
124497  if( (pTerm->eOperator & WO_EQUIV)==0 ) continue;
124498  if( pTerm->leftCursor!=iCur ) continue;
124499  if( pLevel->iLeftJoin ) continue;
124500  pE = pTerm->pExpr;
124502  assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
124503  pAlt = sqlite3WhereFindTerm(pWC, iCur, pTerm->u.leftColumn, notReady,
124504  WO_EQ|WO_IN|WO_IS, 0);
124505  if( pAlt==0 ) continue;
124506  if( pAlt->wtFlags & (TERM_CODED) ) continue;
124507  testcase( pAlt->eOperator & WO_EQ );
124508  testcase( pAlt->eOperator & WO_IS );
124509  testcase( pAlt->eOperator & WO_IN );
124510  VdbeModuleComment((v, "begin transitive constraint"));
124511  pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
124512  if( pEAlt ){
124513  *pEAlt = *pAlt->pExpr;
124514  pEAlt->pLeft = pE->pLeft;
124515  sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
124516  sqlite3StackFree(db, pEAlt);
124517  }
124518  }
124519 
124520  /* For a LEFT OUTER JOIN, generate code that will record the fact that
124521  ** at least one row of the right table has matched the left table.
124522  */
124523  if( pLevel->iLeftJoin ){
124524  pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
124525  sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
124526  VdbeComment((v, "record LEFT JOIN hit"));
124527  sqlite3ExprCacheClear(pParse);
124528  for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
124529  testcase( pTerm->wtFlags & TERM_VIRTUAL );
124530  testcase( pTerm->wtFlags & TERM_CODED );
124531  if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
124532  if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
124533  assert( pWInfo->untestedTerms );
124534  continue;
124535  }
124536  assert( pTerm->pExpr );
124537  sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
124538  pTerm->wtFlags |= TERM_CODED;
124539  }
124540  }
124541 
124542  return pLevel->notReady;
124543 }
124544 
124545 /************** End of wherecode.c *******************************************/
124546 /************** Begin file whereexpr.c ***************************************/
124547 /*
124548 ** 2015-06-08
124549 **
124550 ** The author disclaims copyright to this source code. In place of
124551 ** a legal notice, here is a blessing:
124552 **
124553 ** May you do good and not evil.
124554 ** May you find forgiveness for yourself and forgive others.
124555 ** May you share freely, never taking more than you give.
124556 **
124557 *************************************************************************
124558 ** This module contains C code that generates VDBE code used to process
124559 ** the WHERE clause of SQL statements.
124560 **
124561 ** This file was originally part of where.c but was split out to improve
124562 ** readability and editabiliity. This file contains utility routines for
124563 ** analyzing Expr objects in the WHERE clause.
124564 */
124565 /* #include "sqliteInt.h" */
124566 /* #include "whereInt.h" */
124567 
124568 /* Forward declarations */
124569 static void exprAnalyze(SrcList*, WhereClause*, int);
124570 
124571 /*
124572 ** Deallocate all memory associated with a WhereOrInfo object.
124573 */
124574 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
124576  sqlite3DbFree(db, p);
124577 }
124578 
124579 /*
124580 ** Deallocate all memory associated with a WhereAndInfo object.
124581 */
124582 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
124584  sqlite3DbFree(db, p);
124585 }
124586 
124587 /*
124588 ** Add a single new WhereTerm entry to the WhereClause object pWC.
124589 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
124590 ** The index in pWC->a[] of the new WhereTerm is returned on success.
124591 ** 0 is returned if the new WhereTerm could not be added due to a memory
124592 ** allocation error. The memory allocation failure will be recorded in
124593 ** the db->mallocFailed flag so that higher-level functions can detect it.
124594 **
124595 ** This routine will increase the size of the pWC->a[] array as necessary.
124596 **
124597 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
124598 ** for freeing the expression p is assumed by the WhereClause object pWC.
124599 ** This is true even if this routine fails to allocate a new WhereTerm.
124600 **
124601 ** WARNING: This routine might reallocate the space used to store
124602 ** WhereTerms. All pointers to WhereTerms should be invalidated after
124603 ** calling this routine. Such pointers may be reinitialized by referencing
124604 ** the pWC->a[] array.
124605 */
124606 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
124607  WhereTerm *pTerm;
124608  int idx;
124609  testcase( wtFlags & TERM_VIRTUAL );
124610  if( pWC->nTerm>=pWC->nSlot ){
124611  WhereTerm *pOld = pWC->a;
124612  sqlite3 *db = pWC->pWInfo->pParse->db;
124613  pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
124614  if( pWC->a==0 ){
124615  if( wtFlags & TERM_DYNAMIC ){
124616  sqlite3ExprDelete(db, p);
124617  }
124618  pWC->a = pOld;
124619  return 0;
124620  }
124621  memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
124622  if( pOld!=pWC->aStatic ){
124623  sqlite3DbFree(db, pOld);
124624  }
124625  pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
124626  memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
124627  }
124628  pTerm = &pWC->a[idx = pWC->nTerm++];
124629  if( p && ExprHasProperty(p, EP_Unlikely) ){
124630  pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
124631  }else{
124632  pTerm->truthProb = 1;
124633  }
124634  pTerm->pExpr = sqlite3ExprSkipCollate(p);
124635  pTerm->wtFlags = wtFlags;
124636  pTerm->pWC = pWC;
124637  pTerm->iParent = -1;
124638  return idx;
124639 }
124640 
124641 /*
124642 ** Return TRUE if the given operator is one of the operators that is
124643 ** allowed for an indexable WHERE clause term. The allowed operators are
124644 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
124645 */
124646 static int allowedOp(int op){
124647  assert( TK_GT>TK_EQ && TK_GT<TK_GE );
124648  assert( TK_LT>TK_EQ && TK_LT<TK_GE );
124649  assert( TK_LE>TK_EQ && TK_LE<TK_GE );
124650  assert( TK_GE==TK_EQ+4 );
124651  return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
124652 }
124653 
124654 /*
124655 ** Commute a comparison operator. Expressions of the form "X op Y"
124656 ** are converted into "Y op X".
124657 **
124658 ** If left/right precedence rules come into play when determining the
124659 ** collating sequence, then COLLATE operators are adjusted to ensure
124660 ** that the collating sequence does not change. For example:
124661 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
124662 ** the left hand side of a comparison overrides any collation sequence
124663 ** attached to the right. For the same reason the EP_Collate flag
124664 ** is not commuted.
124665 */
124666 static void exprCommute(Parse *pParse, Expr *pExpr){
124667  u16 expRight = (pExpr->pRight->flags & EP_Collate);
124668  u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
124669  assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
124670  if( expRight==expLeft ){
124671  /* Either X and Y both have COLLATE operator or neither do */
124672  if( expRight ){
124673  /* Both X and Y have COLLATE operators. Make sure X is always
124674  ** used by clearing the EP_Collate flag from Y. */
124675  pExpr->pRight->flags &= ~EP_Collate;
124676  }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
124677  /* Neither X nor Y have COLLATE operators, but X has a non-default
124678  ** collating sequence. So add the EP_Collate marker on X to cause
124679  ** it to be searched first. */
124680  pExpr->pLeft->flags |= EP_Collate;
124681  }
124682  }
124683  SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
124684  if( pExpr->op>=TK_GT ){
124685  assert( TK_LT==TK_GT+2 );
124686  assert( TK_GE==TK_LE+2 );
124687  assert( TK_GT>TK_EQ );
124688  assert( TK_GT<TK_LE );
124689  assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
124690  pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
124691  }
124692 }
124693 
124694 /*
124695 ** Translate from TK_xx operator to WO_xx bitmask.
124696 */
124697 static u16 operatorMask(int op){
124698  u16 c;
124699  assert( allowedOp(op) );
124700  if( op==TK_IN ){
124701  c = WO_IN;
124702  }else if( op==TK_ISNULL ){
124703  c = WO_ISNULL;
124704  }else if( op==TK_IS ){
124705  c = WO_IS;
124706  }else{
124707  assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
124708  c = (u16)(WO_EQ<<(op-TK_EQ));
124709  }
124710  assert( op!=TK_ISNULL || c==WO_ISNULL );
124711  assert( op!=TK_IN || c==WO_IN );
124712  assert( op!=TK_EQ || c==WO_EQ );
124713  assert( op!=TK_LT || c==WO_LT );
124714  assert( op!=TK_LE || c==WO_LE );
124715  assert( op!=TK_GT || c==WO_GT );
124716  assert( op!=TK_GE || c==WO_GE );
124717  assert( op!=TK_IS || c==WO_IS );
124718  return c;
124719 }
124720 
124721 
124722 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
124723 /*
124724 ** Check to see if the given expression is a LIKE or GLOB operator that
124725 ** can be optimized using inequality constraints. Return TRUE if it is
124726 ** so and false if not.
124727 **
124728 ** In order for the operator to be optimizible, the RHS must be a string
124729 ** literal that does not begin with a wildcard. The LHS must be a column
124730 ** that may only be NULL, a string, or a BLOB, never a number. (This means
124731 ** that virtual tables cannot participate in the LIKE optimization.) The
124732 ** collating sequence for the column on the LHS must be appropriate for
124733 ** the operator.
124734 */
124735 static int isLikeOrGlob(
124736  Parse *pParse, /* Parsing and code generating context */
124737  Expr *pExpr, /* Test this expression */
124738  Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
124739  int *pisComplete, /* True if the only wildcard is % in the last character */
124740  int *pnoCase /* True if uppercase is equivalent to lowercase */
124741 ){
124742  const char *z = 0; /* String on RHS of LIKE operator */
124743  Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
124744  ExprList *pList; /* List of operands to the LIKE operator */
124745  int c; /* One character in z[] */
124746  int cnt; /* Number of non-wildcard prefix characters */
124747  char wc[3]; /* Wildcard characters */
124748  sqlite3 *db = pParse->db; /* Database connection */
124749  sqlite3_value *pVal = 0;
124750  int op; /* Opcode of pRight */
124751  int rc; /* Result code to return */
124752 
124753  if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
124754  return 0;
124755  }
124756 #ifdef SQLITE_EBCDIC
124757  if( *pnoCase ) return 0;
124758 #endif
124759  pList = pExpr->x.pList;
124760  pLeft = pList->a[1].pExpr;
124761  if( pLeft->op!=TK_COLUMN
124763  || IsVirtual(pLeft->pTab) /* Value might be numeric */
124764  ){
124765  /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
124766  ** be the name of an indexed column with TEXT affinity. */
124767  return 0;
124768  }
124769  assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
124770 
124771  pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
124772  op = pRight->op;
124773  if( op==TK_VARIABLE ){
124774  Vdbe *pReprepare = pParse->pReprepare;
124775  int iCol = pRight->iColumn;
124776  pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
124777  if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
124778  z = (char *)sqlite3_value_text(pVal);
124779  }
124780  sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
124781  assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
124782  }else if( op==TK_STRING ){
124783  z = pRight->u.zToken;
124784  }
124785  if( z ){
124786  cnt = 0;
124787  while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
124788  cnt++;
124789  }
124790  if( cnt!=0 && 255!=(u8)z[cnt-1] ){
124791  Expr *pPrefix;
124792  *pisComplete = c==wc[0] && z[cnt+1]==0;
124793  pPrefix = sqlite3Expr(db, TK_STRING, z);
124794  if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
124795  *ppPrefix = pPrefix;
124796  if( op==TK_VARIABLE ){
124797  Vdbe *v = pParse->pVdbe;
124798  sqlite3VdbeSetVarmask(v, pRight->iColumn);
124799  if( *pisComplete && pRight->u.zToken[1] ){
124800  /* If the rhs of the LIKE expression is a variable, and the current
124801  ** value of the variable means there is no need to invoke the LIKE
124802  ** function, then no OP_Variable will be added to the program.
124803  ** This causes problems for the sqlite3_bind_parameter_name()
124804  ** API. To work around them, add a dummy OP_Variable here.
124805  */
124806  int r1 = sqlite3GetTempReg(pParse);
124807  sqlite3ExprCodeTarget(pParse, pRight, r1);
124809  sqlite3ReleaseTempReg(pParse, r1);
124810  }
124811  }
124812  }else{
124813  z = 0;
124814  }
124815  }
124816 
124817  rc = (z!=0);
124818  sqlite3ValueFree(pVal);
124819  return rc;
124820 }
124821 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
124822 
124823 
124824 #ifndef SQLITE_OMIT_VIRTUALTABLE
124825 /*
124826 ** Check to see if the given expression is of the form
124827 **
124828 ** column OP expr
124829 **
124830 ** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
124831 ** column of a virtual table.
124832 **
124833 ** If it is then return TRUE. If not, return FALSE.
124834 */
124835 static int isMatchOfColumn(
124836  Expr *pExpr, /* Test this expression */
124837  unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
124838 ){
124839  struct Op2 {
124840  const char *zOp;
124841  unsigned char eOp2;
124842  } aOp[] = {
124843  { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
124844  { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
124845  { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
124846  { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
124847  };
124848  ExprList *pList;
124849  Expr *pCol; /* Column reference */
124850  int i;
124851 
124852  if( pExpr->op!=TK_FUNCTION ){
124853  return 0;
124854  }
124855  pList = pExpr->x.pList;
124856  if( pList==0 || pList->nExpr!=2 ){
124857  return 0;
124858  }
124859  pCol = pList->a[1].pExpr;
124860  if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
124861  return 0;
124862  }
124863  for(i=0; i<ArraySize(aOp); i++){
124864  if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
124865  *peOp2 = aOp[i].eOp2;
124866  return 1;
124867  }
124868  }
124869  return 0;
124870 }
124871 #endif /* SQLITE_OMIT_VIRTUALTABLE */
124872 
124873 /*
124874 ** If the pBase expression originated in the ON or USING clause of
124875 ** a join, then transfer the appropriate markings over to derived.
124876 */
124877 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
124878  if( pDerived ){
124879  pDerived->flags |= pBase->flags & EP_FromJoin;
124880  pDerived->iRightJoinTable = pBase->iRightJoinTable;
124881  }
124882 }
124883 
124884 /*
124885 ** Mark term iChild as being a child of term iParent
124886 */
124887 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
124888  pWC->a[iChild].iParent = iParent;
124889  pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
124890  pWC->a[iParent].nChild++;
124891 }
124892 
124893 /*
124894 ** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
124895 ** a conjunction, then return just pTerm when N==0. If N is exceeds
124896 ** the number of available subterms, return NULL.
124897 */
124898 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
124899  if( pTerm->eOperator!=WO_AND ){
124900  return N==0 ? pTerm : 0;
124901  }
124902  if( N<pTerm->u.pAndInfo->wc.nTerm ){
124903  return &pTerm->u.pAndInfo->wc.a[N];
124904  }
124905  return 0;
124906 }
124907 
124908 /*
124909 ** Subterms pOne and pTwo are contained within WHERE clause pWC. The
124910 ** two subterms are in disjunction - they are OR-ed together.
124911 **
124912 ** If these two terms are both of the form: "A op B" with the same
124913 ** A and B values but different operators and if the operators are
124914 ** compatible (if one is = and the other is <, for example) then
124915 ** add a new virtual AND term to pWC that is the combination of the
124916 ** two.
124917 **
124918 ** Some examples:
124919 **
124920 ** x<y OR x=y --> x<=y
124921 ** x=y OR x=y --> x=y
124922 ** x<=y OR x<y --> x<=y
124923 **
124924 ** The following is NOT generated:
124925 **
124926 ** x<y OR x>y --> x!=y
124927 */
124929  SrcList *pSrc, /* the FROM clause */
124930  WhereClause *pWC, /* The complete WHERE clause */
124931  WhereTerm *pOne, /* First disjunct */
124932  WhereTerm *pTwo /* Second disjunct */
124933 ){
124934  u16 eOp = pOne->eOperator | pTwo->eOperator;
124935  sqlite3 *db; /* Database connection (for malloc) */
124936  Expr *pNew; /* New virtual expression */
124937  int op; /* Operator for the combined expression */
124938  int idxNew; /* Index in pWC of the next virtual term */
124939 
124940  if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
124941  if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
124942  if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
124943  && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
124944  assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
124945  assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
124946  if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
124947  if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
124948  /* If we reach this point, it means the two subterms can be combined */
124949  if( (eOp & (eOp-1))!=0 ){
124950  if( eOp & (WO_LT|WO_LE) ){
124951  eOp = WO_LE;
124952  }else{
124953  assert( eOp & (WO_GT|WO_GE) );
124954  eOp = WO_GE;
124955  }
124956  }
124957  db = pWC->pWInfo->pParse->db;
124958  pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
124959  if( pNew==0 ) return;
124960  for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
124961  pNew->op = op;
124962  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
124963  exprAnalyze(pSrc, pWC, idxNew);
124964 }
124965 
124966 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
124967 /*
124968 ** Analyze a term that consists of two or more OR-connected
124969 ** subterms. So in:
124970 **
124971 ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
124972 ** ^^^^^^^^^^^^^^^^^^^^
124973 **
124974 ** This routine analyzes terms such as the middle term in the above example.
124975 ** A WhereOrTerm object is computed and attached to the term under
124976 ** analysis, regardless of the outcome of the analysis. Hence:
124977 **
124978 ** WhereTerm.wtFlags |= TERM_ORINFO
124979 ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
124980 **
124981 ** The term being analyzed must have two or more of OR-connected subterms.
124982 ** A single subterm might be a set of AND-connected sub-subterms.
124983 ** Examples of terms under analysis:
124984 **
124985 ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
124986 ** (B) x=expr1 OR expr2=x OR x=expr3
124987 ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
124988 ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
124989 ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
124990 ** (F) x>A OR (x=A AND y>=B)
124991 **
124992 ** CASE 1:
124993 **
124994 ** If all subterms are of the form T.C=expr for some single column of C and
124995 ** a single table T (as shown in example B above) then create a new virtual
124996 ** term that is an equivalent IN expression. In other words, if the term
124997 ** being analyzed is:
124998 **
124999 ** x = expr1 OR expr2 = x OR x = expr3
125000 **
125001 ** then create a new virtual term like this:
125002 **
125003 ** x IN (expr1,expr2,expr3)
125004 **
125005 ** CASE 2:
125006 **
125007 ** If there are exactly two disjuncts and one side has x>A and the other side
125008 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
125009 ** WHERE clause of the form "x>=A". Example:
125010 **
125011 ** x>A OR (x=A AND y>B) adds: x>=A
125012 **
125013 ** The added conjunct can sometimes be helpful in query planning.
125014 **
125015 ** CASE 3:
125016 **
125017 ** If all subterms are indexable by a single table T, then set
125018 **
125019 ** WhereTerm.eOperator = WO_OR
125020 ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
125021 **
125022 ** A subterm is "indexable" if it is of the form
125023 ** "T.C <op> <expr>" where C is any column of table T and
125024 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
125025 ** A subterm is also indexable if it is an AND of two or more
125026 ** subsubterms at least one of which is indexable. Indexable AND
125027 ** subterms have their eOperator set to WO_AND and they have
125028 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
125029 **
125030 ** From another point of view, "indexable" means that the subterm could
125031 ** potentially be used with an index if an appropriate index exists.
125032 ** This analysis does not consider whether or not the index exists; that
125033 ** is decided elsewhere. This analysis only looks at whether subterms
125034 ** appropriate for indexing exist.
125035 **
125036 ** All examples A through E above satisfy case 3. But if a term
125037 ** also satisfies case 1 (such as B) we know that the optimizer will
125038 ** always prefer case 1, so in that case we pretend that case 3 is not
125039 ** satisfied.
125040 **
125041 ** It might be the case that multiple tables are indexable. For example,
125042 ** (E) above is indexable on tables P, Q, and R.
125043 **
125044 ** Terms that satisfy case 3 are candidates for lookup by using
125045 ** separate indices to find rowids for each subterm and composing
125046 ** the union of all rowids using a RowSet object. This is similar
125047 ** to "bitmap indices" in other database engines.
125048 **
125049 ** OTHERWISE:
125050 **
125051 ** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
125052 ** zero. This term is not useful for search.
125053 */
125055  SrcList *pSrc, /* the FROM clause */
125056  WhereClause *pWC, /* the complete WHERE clause */
125057  int idxTerm /* Index of the OR-term to be analyzed */
125058 ){
125059  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
125060  Parse *pParse = pWInfo->pParse; /* Parser context */
125061  sqlite3 *db = pParse->db; /* Database connection */
125062  WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
125063  Expr *pExpr = pTerm->pExpr; /* The expression of the term */
125064  int i; /* Loop counters */
125065  WhereClause *pOrWc; /* Breakup of pTerm into subterms */
125066  WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
125067  WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
125068  Bitmask chngToIN; /* Tables that might satisfy case 1 */
125069  Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
125070 
125071  /*
125072  ** Break the OR clause into its separate subterms. The subterms are
125073  ** stored in a WhereClause structure containing within the WhereOrInfo
125074  ** object that is attached to the original OR clause term.
125075  */
125076  assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
125077  assert( pExpr->op==TK_OR );
125078  pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
125079  if( pOrInfo==0 ) return;
125080  pTerm->wtFlags |= TERM_ORINFO;
125081  pOrWc = &pOrInfo->wc;
125082  memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
125083  sqlite3WhereClauseInit(pOrWc, pWInfo);
125084  sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
125085  sqlite3WhereExprAnalyze(pSrc, pOrWc);
125086  if( db->mallocFailed ) return;
125087  assert( pOrWc->nTerm>=2 );
125088 
125089  /*
125090  ** Compute the set of tables that might satisfy cases 1 or 3.
125091  */
125092  indexable = ~(Bitmask)0;
125093  chngToIN = ~(Bitmask)0;
125094  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
125095  if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
125096  WhereAndInfo *pAndInfo;
125097  assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
125098  chngToIN = 0;
125099  pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
125100  if( pAndInfo ){
125101  WhereClause *pAndWC;
125102  WhereTerm *pAndTerm;
125103  int j;
125104  Bitmask b = 0;
125105  pOrTerm->u.pAndInfo = pAndInfo;
125106  pOrTerm->wtFlags |= TERM_ANDINFO;
125107  pOrTerm->eOperator = WO_AND;
125108  pAndWC = &pAndInfo->wc;
125109  memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
125110  sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
125111  sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
125112  sqlite3WhereExprAnalyze(pSrc, pAndWC);
125113  pAndWC->pOuter = pWC;
125114  if( !db->mallocFailed ){
125115  for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
125116  assert( pAndTerm->pExpr );
125117  if( allowedOp(pAndTerm->pExpr->op) ){
125118  b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
125119  }
125120  }
125121  }
125122  indexable &= b;
125123  }
125124  }else if( pOrTerm->wtFlags & TERM_COPIED ){
125125  /* Skip this term for now. We revisit it when we process the
125126  ** corresponding TERM_VIRTUAL term */
125127  }else{
125128  Bitmask b;
125129  b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
125130  if( pOrTerm->wtFlags & TERM_VIRTUAL ){
125131  WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
125132  b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
125133  }
125134  indexable &= b;
125135  if( (pOrTerm->eOperator & WO_EQ)==0 ){
125136  chngToIN = 0;
125137  }else{
125138  chngToIN &= b;
125139  }
125140  }
125141  }
125142 
125143  /*
125144  ** Record the set of tables that satisfy case 3. The set might be
125145  ** empty.
125146  */
125147  pOrInfo->indexable = indexable;
125148  pTerm->eOperator = indexable==0 ? 0 : WO_OR;
125149 
125150  /* For a two-way OR, attempt to implementation case 2.
125151  */
125152  if( indexable && pOrWc->nTerm==2 ){
125153  int iOne = 0;
125154  WhereTerm *pOne;
125155  while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
125156  int iTwo = 0;
125157  WhereTerm *pTwo;
125158  while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
125159  whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
125160  }
125161  }
125162  }
125163 
125164  /*
125165  ** chngToIN holds a set of tables that *might* satisfy case 1. But
125166  ** we have to do some additional checking to see if case 1 really
125167  ** is satisfied.
125168  **
125169  ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
125170  ** that there is no possibility of transforming the OR clause into an
125171  ** IN operator because one or more terms in the OR clause contain
125172  ** something other than == on a column in the single table. The 1-bit
125173  ** case means that every term of the OR clause is of the form
125174  ** "table.column=expr" for some single table. The one bit that is set
125175  ** will correspond to the common table. We still need to check to make
125176  ** sure the same column is used on all terms. The 2-bit case is when
125177  ** the all terms are of the form "table1.column=table2.column". It
125178  ** might be possible to form an IN operator with either table1.column
125179  ** or table2.column as the LHS if either is common to every term of
125180  ** the OR clause.
125181  **
125182  ** Note that terms of the form "table.column1=table.column2" (the
125183  ** same table on both sizes of the ==) cannot be optimized.
125184  */
125185  if( chngToIN ){
125186  int okToChngToIN = 0; /* True if the conversion to IN is valid */
125187  int iColumn = -1; /* Column index on lhs of IN operator */
125188  int iCursor = -1; /* Table cursor common to all terms */
125189  int j = 0; /* Loop counter */
125190 
125191  /* Search for a table and column that appears on one side or the
125192  ** other of the == operator in every subterm. That table and column
125193  ** will be recorded in iCursor and iColumn. There might not be any
125194  ** such table and column. Set okToChngToIN if an appropriate table
125195  ** and column is found but leave okToChngToIN false if not found.
125196  */
125197  for(j=0; j<2 && !okToChngToIN; j++){
125198  pOrTerm = pOrWc->a;
125199  for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
125200  assert( pOrTerm->eOperator & WO_EQ );
125201  pOrTerm->wtFlags &= ~TERM_OR_OK;
125202  if( pOrTerm->leftCursor==iCursor ){
125203  /* This is the 2-bit case and we are on the second iteration and
125204  ** current term is from the first iteration. So skip this term. */
125205  assert( j==1 );
125206  continue;
125207  }
125208  if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
125209  pOrTerm->leftCursor))==0 ){
125210  /* This term must be of the form t1.a==t2.b where t2 is in the
125211  ** chngToIN set but t1 is not. This term will be either preceded
125212  ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
125213  ** and use its inversion. */
125214  testcase( pOrTerm->wtFlags & TERM_COPIED );
125215  testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
125216  assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
125217  continue;
125218  }
125219  iColumn = pOrTerm->u.leftColumn;
125220  iCursor = pOrTerm->leftCursor;
125221  break;
125222  }
125223  if( i<0 ){
125224  /* No candidate table+column was found. This can only occur
125225  ** on the second iteration */
125226  assert( j==1 );
125227  assert( IsPowerOfTwo(chngToIN) );
125228  assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
125229  break;
125230  }
125231  testcase( j==1 );
125232 
125233  /* We have found a candidate table and column. Check to see if that
125234  ** table and column is common to every term in the OR clause */
125235  okToChngToIN = 1;
125236  for(; i>=0 && okToChngToIN; i--, pOrTerm++){
125237  assert( pOrTerm->eOperator & WO_EQ );
125238  if( pOrTerm->leftCursor!=iCursor ){
125239  pOrTerm->wtFlags &= ~TERM_OR_OK;
125240  }else if( pOrTerm->u.leftColumn!=iColumn ){
125241  okToChngToIN = 0;
125242  }else{
125243  int affLeft, affRight;
125244  /* If the right-hand side is also a column, then the affinities
125245  ** of both right and left sides must be such that no type
125246  ** conversions are required on the right. (Ticket #2249)
125247  */
125248  affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
125249  affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
125250  if( affRight!=0 && affRight!=affLeft ){
125251  okToChngToIN = 0;
125252  }else{
125253  pOrTerm->wtFlags |= TERM_OR_OK;
125254  }
125255  }
125256  }
125257  }
125258 
125259  /* At this point, okToChngToIN is true if original pTerm satisfies
125260  ** case 1. In that case, construct a new virtual term that is
125261  ** pTerm converted into an IN operator.
125262  */
125263  if( okToChngToIN ){
125264  Expr *pDup; /* A transient duplicate expression */
125265  ExprList *pList = 0; /* The RHS of the IN operator */
125266  Expr *pLeft = 0; /* The LHS of the IN operator */
125267  Expr *pNew; /* The complete IN operator */
125268 
125269  for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
125270  if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
125271  assert( pOrTerm->eOperator & WO_EQ );
125272  assert( pOrTerm->leftCursor==iCursor );
125273  assert( pOrTerm->u.leftColumn==iColumn );
125274  pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
125275  pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
125276  pLeft = pOrTerm->pExpr->pLeft;
125277  }
125278  assert( pLeft!=0 );
125279  pDup = sqlite3ExprDup(db, pLeft, 0);
125280  pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
125281  if( pNew ){
125282  int idxNew;
125283  transferJoinMarkings(pNew, pExpr);
125284  assert( !ExprHasProperty(pNew, EP_xIsSelect) );
125285  pNew->x.pList = pList;
125286  idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
125287  testcase( idxNew==0 );
125288  exprAnalyze(pSrc, pWC, idxNew);
125289  pTerm = &pWC->a[idxTerm];
125290  markTermAsChild(pWC, idxNew, idxTerm);
125291  }else{
125292  sqlite3ExprListDelete(db, pList);
125293  }
125294  pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
125295  }
125296  }
125297 }
125298 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
125299 
125300 /*
125301 ** We already know that pExpr is a binary operator where both operands are
125302 ** column references. This routine checks to see if pExpr is an equivalence
125303 ** relation:
125304 ** 1. The SQLITE_Transitive optimization must be enabled
125305 ** 2. Must be either an == or an IS operator
125306 ** 3. Not originating in the ON clause of an OUTER JOIN
125307 ** 4. The affinities of A and B must be compatible
125308 ** 5a. Both operands use the same collating sequence OR
125309 ** 5b. The overall collating sequence is BINARY
125310 ** If this routine returns TRUE, that means that the RHS can be substituted
125311 ** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
125312 ** This is an optimization. No harm comes from returning 0. But if 1 is
125313 ** returned when it should not be, then incorrect answers might result.
125314 */
125315 static int termIsEquivalence(Parse *pParse, Expr *pExpr){
125316  char aff1, aff2;
125317  CollSeq *pColl;
125318  const char *zColl1, *zColl2;
125319  if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
125320  if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
125321  if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
125322  aff1 = sqlite3ExprAffinity(pExpr->pLeft);
125323  aff2 = sqlite3ExprAffinity(pExpr->pRight);
125324  if( aff1!=aff2
125325  && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
125326  ){
125327  return 0;
125328  }
125329  pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
125330  if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
125331  pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
125332  /* Since pLeft and pRight are both a column references, their collating
125333  ** sequence should always be defined. */
125334  zColl1 = ALWAYS(pColl) ? pColl->zName : 0;
125335  pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
125336  zColl2 = ALWAYS(pColl) ? pColl->zName : 0;
125337  return sqlite3StrICmp(zColl1, zColl2)==0;
125338 }
125339 
125340 /*
125341 ** Recursively walk the expressions of a SELECT statement and generate
125342 ** a bitmask indicating which tables are used in that expression
125343 ** tree.
125344 */
125345 static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
125346  Bitmask mask = 0;
125347  while( pS ){
125348  SrcList *pSrc = pS->pSrc;
125349  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
125350  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
125351  mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
125352  mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
125353  mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
125354  if( ALWAYS(pSrc!=0) ){
125355  int i;
125356  for(i=0; i<pSrc->nSrc; i++){
125357  mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
125358  mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
125359  }
125360  }
125361  pS = pS->pPrior;
125362  }
125363  return mask;
125364 }
125365 
125366 /*
125367 ** Expression pExpr is one operand of a comparison operator that might
125368 ** be useful for indexing. This routine checks to see if pExpr appears
125369 ** in any index. Return TRUE (1) if pExpr is an indexed term and return
125370 ** FALSE (0) if not. If TRUE is returned, also set *piCur to the cursor
125371 ** number of the table that is indexed and *piColumn to the column number
125372 ** of the column that is indexed, or -2 if an expression is being indexed.
125373 **
125374 ** If pExpr is a TK_COLUMN column reference, then this routine always returns
125375 ** true even if that particular column is not indexed, because the column
125376 ** might be added to an automatic index later.
125377 */
125379  SrcList *pFrom, /* The FROM clause */
125380  Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
125381  Expr *pExpr, /* An operand of a comparison operator */
125382  int *piCur, /* Write the referenced table cursor number here */
125383  int *piColumn /* Write the referenced table column number here */
125384 ){
125385  Index *pIdx;
125386  int i;
125387  int iCur;
125388  if( pExpr->op==TK_COLUMN ){
125389  *piCur = pExpr->iTable;
125390  *piColumn = pExpr->iColumn;
125391  return 1;
125392  }
125393  if( mPrereq==0 ) return 0; /* No table references */
125394  if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
125395  for(i=0; mPrereq>1; i++, mPrereq>>=1){}
125396  iCur = pFrom->a[i].iCursor;
125397  for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
125398  if( pIdx->aColExpr==0 ) continue;
125399  for(i=0; i<pIdx->nKeyCol; i++){
125400  if( pIdx->aiColumn[i]!=(-2) ) continue;
125401  if( sqlite3ExprCompare(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
125402  *piCur = iCur;
125403  *piColumn = -2;
125404  return 1;
125405  }
125406  }
125407  }
125408  return 0;
125409 }
125410 
125411 /*
125412 ** The input to this routine is an WhereTerm structure with only the
125413 ** "pExpr" field filled in. The job of this routine is to analyze the
125414 ** subexpression and populate all the other fields of the WhereTerm
125415 ** structure.
125416 **
125417 ** If the expression is of the form "<expr> <op> X" it gets commuted
125418 ** to the standard form of "X <op> <expr>".
125419 **
125420 ** If the expression is of the form "X <op> Y" where both X and Y are
125421 ** columns, then the original expression is unchanged and a new virtual
125422 ** term of the form "Y <op> X" is added to the WHERE clause and
125423 ** analyzed separately. The original term is marked with TERM_COPIED
125424 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
125425 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
125426 ** is a commuted copy of a prior term.) The original term has nChild=1
125427 ** and the copy has idxParent set to the index of the original term.
125428 */
125429 static void exprAnalyze(
125430  SrcList *pSrc, /* the FROM clause */
125431  WhereClause *pWC, /* the WHERE clause */
125432  int idxTerm /* Index of the term to be analyzed */
125433 ){
125434  WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
125435  WhereTerm *pTerm; /* The term to be analyzed */
125436  WhereMaskSet *pMaskSet; /* Set of table index masks */
125437  Expr *pExpr; /* The expression to be analyzed */
125438  Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
125439  Bitmask prereqAll; /* Prerequesites of pExpr */
125440  Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
125441  Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
125442  int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
125443  int noCase = 0; /* uppercase equivalent to lowercase */
125444  int op; /* Top-level operator. pExpr->op */
125445  Parse *pParse = pWInfo->pParse; /* Parsing context */
125446  sqlite3 *db = pParse->db; /* Database connection */
125447  unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
125448 
125449  if( db->mallocFailed ){
125450  return;
125451  }
125452  pTerm = &pWC->a[idxTerm];
125453  pMaskSet = &pWInfo->sMaskSet;
125454  pExpr = pTerm->pExpr;
125455  assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
125456  prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
125457  op = pExpr->op;
125458  if( op==TK_IN ){
125459  assert( pExpr->pRight==0 );
125460  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
125461  pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
125462  }else{
125463  pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
125464  }
125465  }else if( op==TK_ISNULL ){
125466  pTerm->prereqRight = 0;
125467  }else{
125468  pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
125469  }
125470  prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
125471  if( ExprHasProperty(pExpr, EP_FromJoin) ){
125472  Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
125473  prereqAll |= x;
125474  extraRight = x-1; /* ON clause terms may not be used with an index
125475  ** on left table of a LEFT JOIN. Ticket #3015 */
125476  }
125477  pTerm->prereqAll = prereqAll;
125478  pTerm->leftCursor = -1;
125479  pTerm->iParent = -1;
125480  pTerm->eOperator = 0;
125481  if( allowedOp(op) ){
125482  int iCur, iColumn;
125483  Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
125484  Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
125485  u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
125486  if( exprMightBeIndexed(pSrc, prereqLeft, pLeft, &iCur, &iColumn) ){
125487  pTerm->leftCursor = iCur;
125488  pTerm->u.leftColumn = iColumn;
125489  pTerm->eOperator = operatorMask(op) & opMask;
125490  }
125491  if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
125492  if( pRight
125493  && exprMightBeIndexed(pSrc, pTerm->prereqRight, pRight, &iCur, &iColumn)
125494  ){
125495  WhereTerm *pNew;
125496  Expr *pDup;
125497  u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
125498  if( pTerm->leftCursor>=0 ){
125499  int idxNew;
125500  pDup = sqlite3ExprDup(db, pExpr, 0);
125501  if( db->mallocFailed ){
125502  sqlite3ExprDelete(db, pDup);
125503  return;
125504  }
125505  idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
125506  if( idxNew==0 ) return;
125507  pNew = &pWC->a[idxNew];
125508  markTermAsChild(pWC, idxNew, idxTerm);
125509  if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
125510  pTerm = &pWC->a[idxTerm];
125511  pTerm->wtFlags |= TERM_COPIED;
125512 
125513  if( termIsEquivalence(pParse, pDup) ){
125514  pTerm->eOperator |= WO_EQUIV;
125515  eExtraOp = WO_EQUIV;
125516  }
125517  }else{
125518  pDup = pExpr;
125519  pNew = pTerm;
125520  }
125521  exprCommute(pParse, pDup);
125522  pNew->leftCursor = iCur;
125523  pNew->u.leftColumn = iColumn;
125524  testcase( (prereqLeft | extraRight) != prereqLeft );
125525  pNew->prereqRight = prereqLeft | extraRight;
125526  pNew->prereqAll = prereqAll;
125527  pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
125528  }
125529  }
125530 
125531 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
125532  /* If a term is the BETWEEN operator, create two new virtual terms
125533  ** that define the range that the BETWEEN implements. For example:
125534  **
125535  ** a BETWEEN b AND c
125536  **
125537  ** is converted into:
125538  **
125539  ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
125540  **
125541  ** The two new terms are added onto the end of the WhereClause object.
125542  ** The new terms are "dynamic" and are children of the original BETWEEN
125543  ** term. That means that if the BETWEEN term is coded, the children are
125544  ** skipped. Or, if the children are satisfied by an index, the original
125545  ** BETWEEN term is skipped.
125546  */
125547  else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
125548  ExprList *pList = pExpr->x.pList;
125549  int i;
125550  static const u8 ops[] = {TK_GE, TK_LE};
125551  assert( pList!=0 );
125552  assert( pList->nExpr==2 );
125553  for(i=0; i<2; i++){
125554  Expr *pNewExpr;
125555  int idxNew;
125556  pNewExpr = sqlite3PExpr(pParse, ops[i],
125557  sqlite3ExprDup(db, pExpr->pLeft, 0),
125558  sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
125559  transferJoinMarkings(pNewExpr, pExpr);
125560  idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
125561  testcase( idxNew==0 );
125562  exprAnalyze(pSrc, pWC, idxNew);
125563  pTerm = &pWC->a[idxTerm];
125564  markTermAsChild(pWC, idxNew, idxTerm);
125565  }
125566  }
125567 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
125568 
125569 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
125570  /* Analyze a term that is composed of two or more subterms connected by
125571  ** an OR operator.
125572  */
125573  else if( pExpr->op==TK_OR ){
125574  assert( pWC->op==TK_AND );
125575  exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
125576  pTerm = &pWC->a[idxTerm];
125577  }
125578 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
125579 
125580 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
125581  /* Add constraints to reduce the search space on a LIKE or GLOB
125582  ** operator.
125583  **
125584  ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
125585  **
125586  ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
125587  **
125588  ** The last character of the prefix "abc" is incremented to form the
125589  ** termination condition "abd". If case is not significant (the default
125590  ** for LIKE) then the lower-bound is made all uppercase and the upper-
125591  ** bound is made all lowercase so that the bounds also work when comparing
125592  ** BLOBs.
125593  */
125594  if( pWC->op==TK_AND
125595  && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
125596  ){
125597  Expr *pLeft; /* LHS of LIKE/GLOB operator */
125598  Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
125599  Expr *pNewExpr1;
125600  Expr *pNewExpr2;
125601  int idxNew1;
125602  int idxNew2;
125603  const char *zCollSeqName; /* Name of collating sequence */
125604  const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
125605 
125606  pLeft = pExpr->x.pList->a[1].pExpr;
125607  pStr2 = sqlite3ExprDup(db, pStr1, 0);
125608 
125609  /* Convert the lower bound to upper-case and the upper bound to
125610  ** lower-case (upper-case is less than lower-case in ASCII) so that
125611  ** the range constraints also work for BLOBs
125612  */
125613  if( noCase && !pParse->db->mallocFailed ){
125614  int i;
125615  char c;
125616  pTerm->wtFlags |= TERM_LIKE;
125617  for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
125618  pStr1->u.zToken[i] = sqlite3Toupper(c);
125619  pStr2->u.zToken[i] = sqlite3Tolower(c);
125620  }
125621  }
125622 
125623  if( !db->mallocFailed ){
125624  u8 c, *pC; /* Last character before the first wildcard */
125625  pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
125626  c = *pC;
125627  if( noCase ){
125628  /* The point is to increment the last character before the first
125629  ** wildcard. But if we increment '@', that will push it into the
125630  ** alphabetic range where case conversions will mess up the
125631  ** inequality. To avoid this, make sure to also run the full
125632  ** LIKE on all candidate expressions by clearing the isComplete flag
125633  */
125634  if( c=='A'-1 ) isComplete = 0;
125635  c = sqlite3UpperToLower[c];
125636  }
125637  *pC = c + 1;
125638  }
125639  zCollSeqName = noCase ? "NOCASE" : "BINARY";
125640  pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
125641  pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
125642  sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
125643  pStr1, 0);
125644  transferJoinMarkings(pNewExpr1, pExpr);
125645  idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
125646  testcase( idxNew1==0 );
125647  exprAnalyze(pSrc, pWC, idxNew1);
125648  pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
125649  pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
125650  sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
125651  pStr2, 0);
125652  transferJoinMarkings(pNewExpr2, pExpr);
125653  idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
125654  testcase( idxNew2==0 );
125655  exprAnalyze(pSrc, pWC, idxNew2);
125656  pTerm = &pWC->a[idxTerm];
125657  if( isComplete ){
125658  markTermAsChild(pWC, idxNew1, idxTerm);
125659  markTermAsChild(pWC, idxNew2, idxTerm);
125660  }
125661  }
125662 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
125663 
125664 #ifndef SQLITE_OMIT_VIRTUALTABLE
125665  /* Add a WO_MATCH auxiliary term to the constraint set if the
125666  ** current expression is of the form: column MATCH expr.
125667  ** This information is used by the xBestIndex methods of
125668  ** virtual tables. The native query optimizer does not attempt
125669  ** to do anything with MATCH functions.
125670  */
125671  if( isMatchOfColumn(pExpr, &eOp2) ){
125672  int idxNew;
125673  Expr *pRight, *pLeft;
125674  WhereTerm *pNewTerm;
125675  Bitmask prereqColumn, prereqExpr;
125676 
125677  pRight = pExpr->x.pList->a[0].pExpr;
125678  pLeft = pExpr->x.pList->a[1].pExpr;
125679  prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
125680  prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
125681  if( (prereqExpr & prereqColumn)==0 ){
125682  Expr *pNewExpr;
125683  pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
125684  0, sqlite3ExprDup(db, pRight, 0), 0);
125685  idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
125686  testcase( idxNew==0 );
125687  pNewTerm = &pWC->a[idxNew];
125688  pNewTerm->prereqRight = prereqExpr;
125689  pNewTerm->leftCursor = pLeft->iTable;
125690  pNewTerm->u.leftColumn = pLeft->iColumn;
125691  pNewTerm->eOperator = WO_MATCH;
125692  pNewTerm->eMatchOp = eOp2;
125693  markTermAsChild(pWC, idxNew, idxTerm);
125694  pTerm = &pWC->a[idxTerm];
125695  pTerm->wtFlags |= TERM_COPIED;
125696  pNewTerm->prereqAll = pTerm->prereqAll;
125697  }
125698  }
125699 #endif /* SQLITE_OMIT_VIRTUALTABLE */
125700 
125701 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
125702  /* When sqlite_stat3 histogram data is available an operator of the
125703  ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
125704  ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
125705  ** virtual term of that form.
125706  **
125707  ** Note that the virtual term must be tagged with TERM_VNULL.
125708  */
125709  if( pExpr->op==TK_NOTNULL
125710  && pExpr->pLeft->op==TK_COLUMN
125711  && pExpr->pLeft->iColumn>=0
125713  ){
125714  Expr *pNewExpr;
125715  Expr *pLeft = pExpr->pLeft;
125716  int idxNew;
125717  WhereTerm *pNewTerm;
125718 
125719  pNewExpr = sqlite3PExpr(pParse, TK_GT,
125720  sqlite3ExprDup(db, pLeft, 0),
125721  sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
125722 
125723  idxNew = whereClauseInsert(pWC, pNewExpr,
125725  if( idxNew ){
125726  pNewTerm = &pWC->a[idxNew];
125727  pNewTerm->prereqRight = 0;
125728  pNewTerm->leftCursor = pLeft->iTable;
125729  pNewTerm->u.leftColumn = pLeft->iColumn;
125730  pNewTerm->eOperator = WO_GT;
125731  markTermAsChild(pWC, idxNew, idxTerm);
125732  pTerm = &pWC->a[idxTerm];
125733  pTerm->wtFlags |= TERM_COPIED;
125734  pNewTerm->prereqAll = pTerm->prereqAll;
125735  }
125736  }
125737 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
125738 
125739  /* Prevent ON clause terms of a LEFT JOIN from being used to drive
125740  ** an index for tables to the left of the join.
125741  */
125742  pTerm->prereqRight |= extraRight;
125743 }
125744 
125745 /***************************************************************************
125746 ** Routines with file scope above. Interface to the rest of the where.c
125747 ** subsystem follows.
125748 ***************************************************************************/
125749 
125750 /*
125751 ** This routine identifies subexpressions in the WHERE clause where
125752 ** each subexpression is separated by the AND operator or some other
125753 ** operator specified in the op parameter. The WhereClause structure
125754 ** is filled with pointers to subexpressions. For example:
125755 **
125756 ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
125757 ** \________/ \_______________/ \________________/
125758 ** slot[0] slot[1] slot[2]
125759 **
125760 ** The original WHERE clause in pExpr is unaltered. All this routine
125761 ** does is make slot[] entries point to substructure within pExpr.
125762 **
125763 ** In the previous sentence and in the diagram, "slot[]" refers to
125764 ** the WhereClause.a[] array. The slot[] array grows as needed to contain
125765 ** all terms of the WHERE clause.
125766 */
125768  Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
125769  pWC->op = op;
125770  if( pE2==0 ) return;
125771  if( pE2->op!=op ){
125772  whereClauseInsert(pWC, pExpr, 0);
125773  }else{
125774  sqlite3WhereSplit(pWC, pE2->pLeft, op);
125775  sqlite3WhereSplit(pWC, pE2->pRight, op);
125776  }
125777 }
125778 
125779 /*
125780 ** Initialize a preallocated WhereClause structure.
125781 */
125783  WhereClause *pWC, /* The WhereClause to be initialized */
125784  WhereInfo *pWInfo /* The WHERE processing context */
125785 ){
125786  pWC->pWInfo = pWInfo;
125787  pWC->pOuter = 0;
125788  pWC->nTerm = 0;
125789  pWC->nSlot = ArraySize(pWC->aStatic);
125790  pWC->a = pWC->aStatic;
125791 }
125792 
125793 /*
125794 ** Deallocate a WhereClause structure. The WhereClause structure
125795 ** itself is not freed. This routine is the inverse of
125796 ** sqlite3WhereClauseInit().
125797 */
125799  int i;
125800  WhereTerm *a;
125801  sqlite3 *db = pWC->pWInfo->pParse->db;
125802  for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
125803  if( a->wtFlags & TERM_DYNAMIC ){
125804  sqlite3ExprDelete(db, a->pExpr);
125805  }
125806  if( a->wtFlags & TERM_ORINFO ){
125807  whereOrInfoDelete(db, a->u.pOrInfo);
125808  }else if( a->wtFlags & TERM_ANDINFO ){
125809  whereAndInfoDelete(db, a->u.pAndInfo);
125810  }
125811  }
125812  if( pWC->a!=pWC->aStatic ){
125813  sqlite3DbFree(db, pWC->a);
125814  }
125815 }
125816 
125817 
125818 /*
125819 ** These routines walk (recursively) an expression tree and generate
125820 ** a bitmask indicating which tables are used in that expression
125821 ** tree.
125822 */
125824  Bitmask mask = 0;
125825  if( p==0 ) return 0;
125826  if( p->op==TK_COLUMN ){
125827  mask = sqlite3WhereGetMask(pMaskSet, p->iTable);
125828  return mask;
125829  }
125830  mask = sqlite3WhereExprUsage(pMaskSet, p->pRight);
125831  if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
125832  if( ExprHasProperty(p, EP_xIsSelect) ){
125833  mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
125834  }else if( p->x.pList ){
125835  mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
125836  }
125837  return mask;
125838 }
125840  int i;
125841  Bitmask mask = 0;
125842  if( pList ){
125843  for(i=0; i<pList->nExpr; i++){
125844  mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
125845  }
125846  }
125847  return mask;
125848 }
125849 
125850 
125851 /*
125852 ** Call exprAnalyze on all terms in a WHERE clause.
125853 **
125854 ** Note that exprAnalyze() might add new virtual terms onto the
125855 ** end of the WHERE clause. We do not want to analyze these new
125856 ** virtual terms, so start analyzing at the end and work forward
125857 ** so that the added virtual terms are never processed.
125858 */
125860  SrcList *pTabList, /* the FROM clause */
125861  WhereClause *pWC /* the WHERE clause to be analyzed */
125862 ){
125863  int i;
125864  for(i=pWC->nTerm-1; i>=0; i--){
125865  exprAnalyze(pTabList, pWC, i);
125866  }
125867 }
125868 
125869 /*
125870 ** For table-valued-functions, transform the function arguments into
125871 ** new WHERE clause terms.
125872 **
125873 ** Each function argument translates into an equality constraint against
125874 ** a HIDDEN column in the table.
125875 */
125877  Parse *pParse, /* Parsing context */
125878  struct SrcList_item *pItem, /* The FROM clause term to process */
125879  WhereClause *pWC /* Xfer function arguments to here */
125880 ){
125881  Table *pTab;
125882  int j, k;
125883  ExprList *pArgs;
125884  Expr *pColRef;
125885  Expr *pTerm;
125886  if( pItem->fg.isTabFunc==0 ) return;
125887  pTab = pItem->pTab;
125888  assert( pTab!=0 );
125889  pArgs = pItem->u1.pFuncArg;
125890  if( pArgs==0 ) return;
125891  for(j=k=0; j<pArgs->nExpr; j++){
125892  while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
125893  if( k>=pTab->nCol ){
125894  sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
125895  pTab->zName, j);
125896  return;
125897  }
125898  pColRef = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
125899  if( pColRef==0 ) return;
125900  pColRef->iTable = pItem->iCursor;
125901  pColRef->iColumn = k++;
125902  pColRef->pTab = pTab;
125903  pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
125904  sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0), 0);
125905  whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
125906  }
125907 }
125908 
125909 /************** End of whereexpr.c *******************************************/
125910 /************** Begin file where.c *******************************************/
125911 /*
125912 ** 2001 September 15
125913 **
125914 ** The author disclaims copyright to this source code. In place of
125915 ** a legal notice, here is a blessing:
125916 **
125917 ** May you do good and not evil.
125918 ** May you find forgiveness for yourself and forgive others.
125919 ** May you share freely, never taking more than you give.
125920 **
125921 *************************************************************************
125922 ** This module contains C code that generates VDBE code used to process
125923 ** the WHERE clause of SQL statements. This module is responsible for
125924 ** generating the code that loops through a table looking for applicable
125925 ** rows. Indices are selected and used to speed the search when doing
125926 ** so is applicable. Because this module is responsible for selecting
125927 ** indices, you might also think of this module as the "query optimizer".
125928 */
125929 /* #include "sqliteInt.h" */
125930 /* #include "whereInt.h" */
125931 
125932 /* Forward declaration of methods */
125933 static int whereLoopResize(sqlite3*, WhereLoop*, int);
125934 
125935 /* Test variable that can be set to enable WHERE tracing */
125936 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
125937 /***/ int sqlite3WhereTrace = 0;
125938 #endif
125939 
125940 
125941 /*
125942 ** Return the estimated number of output rows from a WHERE clause
125943 */
125945  return pWInfo->nRowOut;
125946 }
125947 
125948 /*
125949 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
125950 ** WHERE clause returns outputs for DISTINCT processing.
125951 */
125953  return pWInfo->eDistinct;
125954 }
125955 
125956 /*
125957 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
125958 ** Return FALSE if the output needs to be sorted.
125959 */
125961  return pWInfo->nOBSat;
125962 }
125963 
125964 /*
125965 ** Return the VDBE address or label to jump to in order to continue
125966 ** immediately with the next row of a WHERE clause.
125967 */
125969  assert( pWInfo->iContinue!=0 );
125970  return pWInfo->iContinue;
125971 }
125972 
125973 /*
125974 ** Return the VDBE address or label to jump to in order to break
125975 ** out of a WHERE loop.
125976 */
125978  return pWInfo->iBreak;
125979 }
125980 
125981 /*
125982 ** Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
125983 ** operate directly on the rowis returned by a WHERE clause. Return
125984 ** ONEPASS_SINGLE (1) if the statement can operation directly because only
125985 ** a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
125986 ** optimization can be used on multiple
125987 **
125988 ** If the ONEPASS optimization is used (if this routine returns true)
125989 ** then also write the indices of open cursors used by ONEPASS
125990 ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
125991 ** table and iaCur[1] gets the cursor used by an auxiliary index.
125992 ** Either value may be -1, indicating that cursor is not used.
125993 ** Any cursors returned will have been opened for writing.
125994 **
125995 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
125996 ** unable to use the ONEPASS optimization.
125997 */
125999  memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
126000 #ifdef WHERETRACE_ENABLED
126001  if( sqlite3WhereTrace && pWInfo->eOnePass!=ONEPASS_OFF ){
126002  sqlite3DebugPrintf("%s cursors: %d %d\n",
126003  pWInfo->eOnePass==ONEPASS_SINGLE ? "ONEPASS_SINGLE" : "ONEPASS_MULTI",
126004  aiCur[0], aiCur[1]);
126005  }
126006 #endif
126007  return pWInfo->eOnePass;
126008 }
126009 
126010 /*
126011 ** Move the content of pSrc into pDest
126012 */
126013 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
126014  pDest->n = pSrc->n;
126015  memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
126016 }
126017 
126018 /*
126019 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
126020 **
126021 ** The new entry might overwrite an existing entry, or it might be
126022 ** appended, or it might be discarded. Do whatever is the right thing
126023 ** so that pSet keeps the N_OR_COST best entries seen so far.
126024 */
126025 static int whereOrInsert(
126026  WhereOrSet *pSet, /* The WhereOrSet to be updated */
126027  Bitmask prereq, /* Prerequisites of the new entry */
126028  LogEst rRun, /* Run-cost of the new entry */
126029  LogEst nOut /* Number of outputs for the new entry */
126030 ){
126031  u16 i;
126032  WhereOrCost *p;
126033  for(i=pSet->n, p=pSet->a; i>0; i--, p++){
126034  if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
126035  goto whereOrInsert_done;
126036  }
126037  if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
126038  return 0;
126039  }
126040  }
126041  if( pSet->n<N_OR_COST ){
126042  p = &pSet->a[pSet->n++];
126043  p->nOut = nOut;
126044  }else{
126045  p = pSet->a;
126046  for(i=1; i<pSet->n; i++){
126047  if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
126048  }
126049  if( p->rRun<=rRun ) return 0;
126050  }
126051 whereOrInsert_done:
126052  p->prereq = prereq;
126053  p->rRun = rRun;
126054  if( p->nOut>nOut ) p->nOut = nOut;
126055  return 1;
126056 }
126057 
126058 /*
126059 ** Return the bitmask for the given cursor number. Return 0 if
126060 ** iCursor is not in the set.
126061 */
126062 SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *pMaskSet, int iCursor){
126063  int i;
126064  assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
126065  for(i=0; i<pMaskSet->n; i++){
126066  if( pMaskSet->ix[i]==iCursor ){
126067  return MASKBIT(i);
126068  }
126069  }
126070  return 0;
126071 }
126072 
126073 /*
126074 ** Create a new mask for cursor iCursor.
126075 **
126076 ** There is one cursor per table in the FROM clause. The number of
126077 ** tables in the FROM clause is limited by a test early in the
126078 ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
126079 ** array will never overflow.
126080 */
126081 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
126082  assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
126083  pMaskSet->ix[pMaskSet->n++] = iCursor;
126084 }
126085 
126086 /*
126087 ** Advance to the next WhereTerm that matches according to the criteria
126088 ** established when the pScan object was initialized by whereScanInit().
126089 ** Return NULL if there are no more matching WhereTerms.
126090 */
126092  int iCur; /* The cursor on the LHS of the term */
126093  i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
126094  Expr *pX; /* An expression being tested */
126095  WhereClause *pWC; /* Shorthand for pScan->pWC */
126096  WhereTerm *pTerm; /* The term being tested */
126097  int k = pScan->k; /* Where to start scanning */
126098 
126099  while( pScan->iEquiv<=pScan->nEquiv ){
126100  iCur = pScan->aiCur[pScan->iEquiv-1];
126101  iColumn = pScan->aiColumn[pScan->iEquiv-1];
126102  if( iColumn==XN_EXPR && pScan->pIdxExpr==0 ) return 0;
126103  while( (pWC = pScan->pWC)!=0 ){
126104  for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
126105  if( pTerm->leftCursor==iCur
126106  && pTerm->u.leftColumn==iColumn
126107  && (iColumn!=XN_EXPR
126108  || sqlite3ExprCompare(pTerm->pExpr->pLeft,pScan->pIdxExpr,iCur)==0)
126109  && (pScan->iEquiv<=1 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
126110  ){
126111  if( (pTerm->eOperator & WO_EQUIV)!=0
126112  && pScan->nEquiv<ArraySize(pScan->aiCur)
126113  && (pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight))->op==TK_COLUMN
126114  ){
126115  int j;
126116  for(j=0; j<pScan->nEquiv; j++){
126117  if( pScan->aiCur[j]==pX->iTable
126118  && pScan->aiColumn[j]==pX->iColumn ){
126119  break;
126120  }
126121  }
126122  if( j==pScan->nEquiv ){
126123  pScan->aiCur[j] = pX->iTable;
126124  pScan->aiColumn[j] = pX->iColumn;
126125  pScan->nEquiv++;
126126  }
126127  }
126128  if( (pTerm->eOperator & pScan->opMask)!=0 ){
126129  /* Verify the affinity and collating sequence match */
126130  if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
126131  CollSeq *pColl;
126132  Parse *pParse = pWC->pWInfo->pParse;
126133  pX = pTerm->pExpr;
126134  if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
126135  continue;
126136  }
126137  assert(pX->pLeft);
126138  pColl = sqlite3BinaryCompareCollSeq(pParse,
126139  pX->pLeft, pX->pRight);
126140  if( pColl==0 ) pColl = pParse->db->pDfltColl;
126141  if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
126142  continue;
126143  }
126144  }
126145  if( (pTerm->eOperator & (WO_EQ|WO_IS))!=0
126146  && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
126147  && pX->iTable==pScan->aiCur[0]
126148  && pX->iColumn==pScan->aiColumn[0]
126149  ){
126150  testcase( pTerm->eOperator & WO_IS );
126151  continue;
126152  }
126153  pScan->k = k+1;
126154  return pTerm;
126155  }
126156  }
126157  }
126158  pScan->pWC = pScan->pWC->pOuter;
126159  k = 0;
126160  }
126161  pScan->pWC = pScan->pOrigWC;
126162  k = 0;
126163  pScan->iEquiv++;
126164  }
126165  return 0;
126166 }
126167 
126168 /*
126169 ** Initialize a WHERE clause scanner object. Return a pointer to the
126170 ** first match. Return NULL if there are no matches.
126171 **
126172 ** The scanner will be searching the WHERE clause pWC. It will look
126173 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
126174 ** iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
126175 ** must be one of the indexes of table iCur.
126176 **
126177 ** The <op> must be one of the operators described by opMask.
126178 **
126179 ** If the search is for X and the WHERE clause contains terms of the
126180 ** form X=Y then this routine might also return terms of the form
126181 ** "Y <op> <expr>". The number of levels of transitivity is limited,
126182 ** but is enough to handle most commonly occurring SQL statements.
126183 **
126184 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
126185 ** index pIdx.
126186 */
126188  WhereScan *pScan, /* The WhereScan object being initialized */
126189  WhereClause *pWC, /* The WHERE clause to be scanned */
126190  int iCur, /* Cursor to scan for */
126191  int iColumn, /* Column to scan for */
126192  u32 opMask, /* Operator(s) to scan for */
126193  Index *pIdx /* Must be compatible with this index */
126194 ){
126195  int j = 0;
126196 
126197  /* memset(pScan, 0, sizeof(*pScan)); */
126198  pScan->pOrigWC = pWC;
126199  pScan->pWC = pWC;
126200  pScan->pIdxExpr = 0;
126201  if( pIdx ){
126202  j = iColumn;
126203  iColumn = pIdx->aiColumn[j];
126204  if( iColumn==XN_EXPR ) pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
126205  if( iColumn==pIdx->pTable->iPKey ) iColumn = XN_ROWID;
126206  }
126207  if( pIdx && iColumn>=0 ){
126208  pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
126209  pScan->zCollName = pIdx->azColl[j];
126210  }else{
126211  pScan->idxaff = 0;
126212  pScan->zCollName = 0;
126213  }
126214  pScan->opMask = opMask;
126215  pScan->k = 0;
126216  pScan->aiCur[0] = iCur;
126217  pScan->aiColumn[0] = iColumn;
126218  pScan->nEquiv = 1;
126219  pScan->iEquiv = 1;
126220  return whereScanNext(pScan);
126221 }
126222 
126223 /*
126224 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
126225 ** where X is a reference to the iColumn of table iCur or of index pIdx
126226 ** if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
126227 ** the op parameter. Return a pointer to the term. Return 0 if not found.
126228 **
126229 ** If pIdx!=0 then it must be one of the indexes of table iCur.
126230 ** Search for terms matching the iColumn-th column of pIdx
126231 ** rather than the iColumn-th column of table iCur.
126232 **
126233 ** The term returned might by Y=<expr> if there is another constraint in
126234 ** the WHERE clause that specifies that X=Y. Any such constraints will be
126235 ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
126236 ** aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
126237 ** slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
126238 ** other equivalent values. Hence a search for X will return <expr> if X=A1
126239 ** and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
126240 **
126241 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
126242 ** then try for the one with no dependencies on <expr> - in other words where
126243 ** <expr> is a constant expression of some kind. Only return entries of
126244 ** the form "X <op> Y" where Y is a column in another table if no terms of
126245 ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
126246 ** exist, try to return a term that does not use WO_EQUIV.
126247 */
126249  WhereClause *pWC, /* The WHERE clause to be searched */
126250  int iCur, /* Cursor number of LHS */
126251  int iColumn, /* Column number of LHS */
126252  Bitmask notReady, /* RHS must not overlap with this mask */
126253  u32 op, /* Mask of WO_xx values describing operator */
126254  Index *pIdx /* Must be compatible with this index, if not NULL */
126255 ){
126256  WhereTerm *pResult = 0;
126257  WhereTerm *p;
126258  WhereScan scan;
126259 
126260  p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
126261  op &= WO_EQ|WO_IS;
126262  while( p ){
126263  if( (p->prereqRight & notReady)==0 ){
126264  if( p->prereqRight==0 && (p->eOperator&op)!=0 ){
126265  testcase( p->eOperator & WO_IS );
126266  return p;
126267  }
126268  if( pResult==0 ) pResult = p;
126269  }
126270  p = whereScanNext(&scan);
126271  }
126272  return pResult;
126273 }
126274 
126275 /*
126276 ** This function searches pList for an entry that matches the iCol-th column
126277 ** of index pIdx.
126278 **
126279 ** If such an expression is found, its index in pList->a[] is returned. If
126280 ** no expression is found, -1 is returned.
126281 */
126282 static int findIndexCol(
126283  Parse *pParse, /* Parse context */
126284  ExprList *pList, /* Expression list to search */
126285  int iBase, /* Cursor for table associated with pIdx */
126286  Index *pIdx, /* Index to match column of */
126287  int iCol /* Column of index to match */
126288 ){
126289  int i;
126290  const char *zColl = pIdx->azColl[iCol];
126291 
126292  for(i=0; i<pList->nExpr; i++){
126293  Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
126294  if( p->op==TK_COLUMN
126295  && p->iColumn==pIdx->aiColumn[iCol]
126296  && p->iTable==iBase
126297  ){
126298  CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
126299  if( pColl && 0==sqlite3StrICmp(pColl->zName, zColl) ){
126300  return i;
126301  }
126302  }
126303  }
126304 
126305  return -1;
126306 }
126307 
126308 /*
126309 ** Return TRUE if the iCol-th column of index pIdx is NOT NULL
126310 */
126311 static int indexColumnNotNull(Index *pIdx, int iCol){
126312  int j;
126313  assert( pIdx!=0 );
126314  assert( iCol>=0 && iCol<pIdx->nColumn );
126315  j = pIdx->aiColumn[iCol];
126316  if( j>=0 ){
126317  return pIdx->pTable->aCol[j].notNull;
126318  }else if( j==(-1) ){
126319  return 1;
126320  }else{
126321  assert( j==(-2) );
126322  return 0; /* Assume an indexed expression can always yield a NULL */
126323 
126324  }
126325 }
126326 
126327 /*
126328 ** Return true if the DISTINCT expression-list passed as the third argument
126329 ** is redundant.
126330 **
126331 ** A DISTINCT list is redundant if any subset of the columns in the
126332 ** DISTINCT list are collectively unique and individually non-null.
126333 */
126335  Parse *pParse, /* Parsing context */
126336  SrcList *pTabList, /* The FROM clause */
126337  WhereClause *pWC, /* The WHERE clause */
126338  ExprList *pDistinct /* The result set that needs to be DISTINCT */
126339 ){
126340  Table *pTab;
126341  Index *pIdx;
126342  int i;
126343  int iBase;
126344 
126345  /* If there is more than one table or sub-select in the FROM clause of
126346  ** this query, then it will not be possible to show that the DISTINCT
126347  ** clause is redundant. */
126348  if( pTabList->nSrc!=1 ) return 0;
126349  iBase = pTabList->a[0].iCursor;
126350  pTab = pTabList->a[0].pTab;
126351 
126352  /* If any of the expressions is an IPK column on table iBase, then return
126353  ** true. Note: The (p->iTable==iBase) part of this test may be false if the
126354  ** current SELECT is a correlated sub-query.
126355  */
126356  for(i=0; i<pDistinct->nExpr; i++){
126357  Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
126358  if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
126359  }
126360 
126361  /* Loop through all indices on the table, checking each to see if it makes
126362  ** the DISTINCT qualifier redundant. It does so if:
126363  **
126364  ** 1. The index is itself UNIQUE, and
126365  **
126366  ** 2. All of the columns in the index are either part of the pDistinct
126367  ** list, or else the WHERE clause contains a term of the form "col=X",
126368  ** where X is a constant value. The collation sequences of the
126369  ** comparison and select-list expressions must match those of the index.
126370  **
126371  ** 3. All of those index columns for which the WHERE clause does not
126372  ** contain a "col=X" term are subject to a NOT NULL constraint.
126373  */
126374  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
126375  if( !IsUniqueIndex(pIdx) ) continue;
126376  for(i=0; i<pIdx->nKeyCol; i++){
126377  if( 0==sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask)0, WO_EQ, pIdx) ){
126378  if( findIndexCol(pParse, pDistinct, iBase, pIdx, i)<0 ) break;
126379  if( indexColumnNotNull(pIdx, i)==0 ) break;
126380  }
126381  }
126382  if( i==pIdx->nKeyCol ){
126383  /* This index implies that the DISTINCT qualifier is redundant. */
126384  return 1;
126385  }
126386  }
126387 
126388  return 0;
126389 }
126390 
126391 
126392 /*
126393 ** Estimate the logarithm of the input value to base 2.
126394 */
126395 static LogEst estLog(LogEst N){
126396  return N<=10 ? 0 : sqlite3LogEst(N) - 33;
126397 }
126398 
126399 /*
126400 ** Convert OP_Column opcodes to OP_Copy in previously generated code.
126401 **
126402 ** This routine runs over generated VDBE code and translates OP_Column
126403 ** opcodes into OP_Copy when the table is being accessed via co-routine
126404 ** instead of via table lookup.
126405 **
126406 ** If the bIncrRowid parameter is 0, then any OP_Rowid instructions on
126407 ** cursor iTabCur are transformed into OP_Null. Or, if bIncrRowid is non-zero,
126408 ** then each OP_Rowid is transformed into an instruction to increment the
126409 ** value stored in its output register.
126410 */
126412  Vdbe *v, /* The VDBE containing code to translate */
126413  int iStart, /* Translate from this opcode to the end */
126414  int iTabCur, /* OP_Column/OP_Rowid references to this table */
126415  int iRegister, /* The first column is in this register */
126416  int bIncrRowid /* If non-zero, transform OP_rowid to OP_AddImm(1) */
126417 ){
126418  VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
126419  int iEnd = sqlite3VdbeCurrentAddr(v);
126420  for(; iStart<iEnd; iStart++, pOp++){
126421  if( pOp->p1!=iTabCur ) continue;
126422  if( pOp->opcode==OP_Column ){
126423  pOp->opcode = OP_Copy;
126424  pOp->p1 = pOp->p2 + iRegister;
126425  pOp->p2 = pOp->p3;
126426  pOp->p3 = 0;
126427  }else if( pOp->opcode==OP_Rowid ){
126428  if( bIncrRowid ){
126429  /* Increment the value stored in the P2 operand of the OP_Rowid. */
126430  pOp->opcode = OP_AddImm;
126431  pOp->p1 = pOp->p2;
126432  pOp->p2 = 1;
126433  }else{
126434  pOp->opcode = OP_Null;
126435  pOp->p1 = 0;
126436  pOp->p3 = 0;
126437  }
126438  }
126439  }
126440 }
126441 
126442 /*
126443 ** Two routines for printing the content of an sqlite3_index_info
126444 ** structure. Used for testing and debugging only. If neither
126445 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
126446 ** are no-ops.
126447 */
126448 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
126449 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
126450  int i;
126451  if( !sqlite3WhereTrace ) return;
126452  for(i=0; i<p->nConstraint; i++){
126453  sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
126454  i,
126455  p->aConstraint[i].iColumn,
126456  p->aConstraint[i].iTermOffset,
126457  p->aConstraint[i].op,
126458  p->aConstraint[i].usable);
126459  }
126460  for(i=0; i<p->nOrderBy; i++){
126461  sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
126462  i,
126463  p->aOrderBy[i].iColumn,
126464  p->aOrderBy[i].desc);
126465  }
126466 }
126467 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
126468  int i;
126469  if( !sqlite3WhereTrace ) return;
126470  for(i=0; i<p->nConstraint; i++){
126471  sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
126472  i,
126473  p->aConstraintUsage[i].argvIndex,
126474  p->aConstraintUsage[i].omit);
126475  }
126476  sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
126477  sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
126478  sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
126479  sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
126480  sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
126481 }
126482 #else
126483 #define TRACE_IDX_INPUTS(A)
126484 #define TRACE_IDX_OUTPUTS(A)
126485 #endif
126486 
126487 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
126488 /*
126489 ** Return TRUE if the WHERE clause term pTerm is of a form where it
126490 ** could be used with an index to access pSrc, assuming an appropriate
126491 ** index existed.
126492 */
126494  WhereTerm *pTerm, /* WHERE clause term to check */
126495  struct SrcList_item *pSrc, /* Table we are trying to access */
126496  Bitmask notReady /* Tables in outer loops of the join */
126497 ){
126498  char aff;
126499  if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
126500  if( (pTerm->eOperator & (WO_EQ|WO_IS))==0 ) return 0;
126501  if( (pTerm->prereqRight & notReady)!=0 ) return 0;
126502  if( pTerm->u.leftColumn<0 ) return 0;
126503  aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
126504  if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
126505  testcase( pTerm->pExpr->op==TK_IS );
126506  return 1;
126507 }
126508 #endif
126509 
126510 
126511 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
126512 /*
126513 ** Generate code to construct the Index object for an automatic index
126514 ** and to set up the WhereLevel object pLevel so that the code generator
126515 ** makes use of the automatic index.
126516 */
126518  Parse *pParse, /* The parsing context */
126519  WhereClause *pWC, /* The WHERE clause */
126520  struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
126521  Bitmask notReady, /* Mask of cursors that are not available */
126522  WhereLevel *pLevel /* Write new index here */
126523 ){
126524  int nKeyCol; /* Number of columns in the constructed index */
126525  WhereTerm *pTerm; /* A single term of the WHERE clause */
126526  WhereTerm *pWCEnd; /* End of pWC->a[] */
126527  Index *pIdx; /* Object describing the transient index */
126528  Vdbe *v; /* Prepared statement under construction */
126529  int addrInit; /* Address of the initialization bypass jump */
126530  Table *pTable; /* The table being indexed */
126531  int addrTop; /* Top of the index fill loop */
126532  int regRecord; /* Register holding an index record */
126533  int n; /* Column counter */
126534  int i; /* Loop counter */
126535  int mxBitCol; /* Maximum column in pSrc->colUsed */
126536  CollSeq *pColl; /* Collating sequence to on a column */
126537  WhereLoop *pLoop; /* The Loop object */
126538  char *zNotUsed; /* Extra space on the end of pIdx */
126539  Bitmask idxCols; /* Bitmap of columns used for indexing */
126540  Bitmask extraCols; /* Bitmap of additional columns */
126541  u8 sentWarning = 0; /* True if a warnning has been issued */
126542  Expr *pPartial = 0; /* Partial Index Expression */
126543  int iContinue = 0; /* Jump here to skip excluded rows */
126544  struct SrcList_item *pTabItem; /* FROM clause term being indexed */
126545  int addrCounter = 0; /* Address where integer counter is initialized */
126546  int regBase; /* Array of registers where record is assembled */
126547 
126548  /* Generate code to skip over the creation and initialization of the
126549  ** transient index on 2nd and subsequent iterations of the loop. */
126550  v = pParse->pVdbe;
126551  assert( v!=0 );
126552  addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
126553 
126554  /* Count the number of columns that will be added to the index
126555  ** and used to match WHERE clause constraints */
126556  nKeyCol = 0;
126557  pTable = pSrc->pTab;
126558  pWCEnd = &pWC->a[pWC->nTerm];
126559  pLoop = pLevel->pWLoop;
126560  idxCols = 0;
126561  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
126562  Expr *pExpr = pTerm->pExpr;
126563  assert( !ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
126564  || pExpr->iRightJoinTable!=pSrc->iCursor /* for the right-hand */
126565  || pLoop->prereq!=0 ); /* table of a LEFT JOIN */
126566  if( pLoop->prereq==0
126567  && (pTerm->wtFlags & TERM_VIRTUAL)==0
126568  && !ExprHasProperty(pExpr, EP_FromJoin)
126569  && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
126570  pPartial = sqlite3ExprAnd(pParse->db, pPartial,
126571  sqlite3ExprDup(pParse->db, pExpr, 0));
126572  }
126573  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
126574  int iCol = pTerm->u.leftColumn;
126575  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
126576  testcase( iCol==BMS );
126577  testcase( iCol==BMS-1 );
126578  if( !sentWarning ){
126580  "automatic index on %s(%s)", pTable->zName,
126581  pTable->aCol[iCol].zName);
126582  sentWarning = 1;
126583  }
126584  if( (idxCols & cMask)==0 ){
126585  if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
126586  goto end_auto_index_create;
126587  }
126588  pLoop->aLTerm[nKeyCol++] = pTerm;
126589  idxCols |= cMask;
126590  }
126591  }
126592  }
126593  assert( nKeyCol>0 );
126594  pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
126596  | WHERE_AUTO_INDEX;
126597 
126598  /* Count the number of additional columns needed to create a
126599  ** covering index. A "covering index" is an index that contains all
126600  ** columns that are needed by the query. With a covering index, the
126601  ** original table never needs to be accessed. Automatic indices must
126602  ** be a covering index because the index will not be updated if the
126603  ** original table changes and the index and table cannot both be used
126604  ** if they go out of sync.
126605  */
126606  extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
126607  mxBitCol = MIN(BMS-1,pTable->nCol);
126608  testcase( pTable->nCol==BMS-1 );
126609  testcase( pTable->nCol==BMS-2 );
126610  for(i=0; i<mxBitCol; i++){
126611  if( extraCols & MASKBIT(i) ) nKeyCol++;
126612  }
126613  if( pSrc->colUsed & MASKBIT(BMS-1) ){
126614  nKeyCol += pTable->nCol - BMS + 1;
126615  }
126616 
126617  /* Construct the Index object to describe this index */
126618  pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
126619  if( pIdx==0 ) goto end_auto_index_create;
126620  pLoop->u.btree.pIndex = pIdx;
126621  pIdx->zName = "auto-index";
126622  pIdx->pTable = pTable;
126623  n = 0;
126624  idxCols = 0;
126625  for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
126626  if( termCanDriveIndex(pTerm, pSrc, notReady) ){
126627  int iCol = pTerm->u.leftColumn;
126628  Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
126629  testcase( iCol==BMS-1 );
126630  testcase( iCol==BMS );
126631  if( (idxCols & cMask)==0 ){
126632  Expr *pX = pTerm->pExpr;
126633  idxCols |= cMask;
126634  pIdx->aiColumn[n] = pTerm->u.leftColumn;
126635  pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
126636  pIdx->azColl[n] = pColl ? pColl->zName : sqlite3StrBINARY;
126637  n++;
126638  }
126639  }
126640  }
126641  assert( (u32)n==pLoop->u.btree.nEq );
126642 
126643  /* Add additional columns needed to make the automatic index into
126644  ** a covering index */
126645  for(i=0; i<mxBitCol; i++){
126646  if( extraCols & MASKBIT(i) ){
126647  pIdx->aiColumn[n] = i;
126648  pIdx->azColl[n] = sqlite3StrBINARY;
126649  n++;
126650  }
126651  }
126652  if( pSrc->colUsed & MASKBIT(BMS-1) ){
126653  for(i=BMS-1; i<pTable->nCol; i++){
126654  pIdx->aiColumn[n] = i;
126655  pIdx->azColl[n] = sqlite3StrBINARY;
126656  n++;
126657  }
126658  }
126659  assert( n==nKeyCol );
126660  pIdx->aiColumn[n] = XN_ROWID;
126661  pIdx->azColl[n] = sqlite3StrBINARY;
126662 
126663  /* Create the automatic index */
126664  assert( pLevel->iIdxCur>=0 );
126665  pLevel->iIdxCur = pParse->nTab++;
126666  sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
126667  sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
126668  VdbeComment((v, "for %s", pTable->zName));
126669 
126670  /* Fill the automatic index with content */
126671  sqlite3ExprCachePush(pParse);
126672  pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
126673  if( pTabItem->fg.viaCoroutine ){
126674  int regYield = pTabItem->regReturn;
126675  addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
126676  sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
126677  addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
126678  VdbeCoverage(v);
126679  VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
126680  }else{
126681  addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
126682  }
126683  if( pPartial ){
126684  iContinue = sqlite3VdbeMakeLabel(v);
126685  sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
126686  pLoop->wsFlags |= WHERE_PARTIALIDX;
126687  }
126688  regRecord = sqlite3GetTempReg(pParse);
126689  regBase = sqlite3GenerateIndexKey(
126690  pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0
126691  );
126692  sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
126694  if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
126695  if( pTabItem->fg.viaCoroutine ){
126696  sqlite3VdbeChangeP2(v, addrCounter, regBase+n);
126697  translateColumnToCopy(v, addrTop, pLevel->iTabCur, pTabItem->regResult, 1);
126698  sqlite3VdbeGoto(v, addrTop);
126699  pTabItem->fg.viaCoroutine = 0;
126700  }else{
126701  sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
126702  }
126704  sqlite3VdbeJumpHere(v, addrTop);
126705  sqlite3ReleaseTempReg(pParse, regRecord);
126706  sqlite3ExprCachePop(pParse);
126707 
126708  /* Jump here when skipping the initialization */
126709  sqlite3VdbeJumpHere(v, addrInit);
126710 
126711 end_auto_index_create:
126712  sqlite3ExprDelete(pParse->db, pPartial);
126713 }
126714 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
126715 
126716 #ifndef SQLITE_OMIT_VIRTUALTABLE
126717 /*
126718 ** Allocate and populate an sqlite3_index_info structure. It is the
126719 ** responsibility of the caller to eventually release the structure
126720 ** by passing the pointer returned by this function to sqlite3_free().
126721 */
126723  Parse *pParse,
126724  WhereClause *pWC,
126725  Bitmask mUnusable, /* Ignore terms with these prereqs */
126726  struct SrcList_item *pSrc,
126727  ExprList *pOrderBy
126728 ){
126729  int i, j;
126730  int nTerm;
126731  struct sqlite3_index_constraint *pIdxCons;
126732  struct sqlite3_index_orderby *pIdxOrderBy;
126733  struct sqlite3_index_constraint_usage *pUsage;
126734  WhereTerm *pTerm;
126735  int nOrderBy;
126736  sqlite3_index_info *pIdxInfo;
126737 
126738  /* Count the number of possible WHERE clause constraints referring
126739  ** to this virtual table */
126740  for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
126741  if( pTerm->leftCursor != pSrc->iCursor ) continue;
126742  if( pTerm->prereqRight & mUnusable ) continue;
126743  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
126744  testcase( pTerm->eOperator & WO_IN );
126745  testcase( pTerm->eOperator & WO_ISNULL );
126746  testcase( pTerm->eOperator & WO_IS );
126747  testcase( pTerm->eOperator & WO_ALL );
126748  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
126749  if( pTerm->wtFlags & TERM_VNULL ) continue;
126750  assert( pTerm->u.leftColumn>=(-1) );
126751  nTerm++;
126752  }
126753 
126754  /* If the ORDER BY clause contains only columns in the current
126755  ** virtual table then allocate space for the aOrderBy part of
126756  ** the sqlite3_index_info structure.
126757  */
126758  nOrderBy = 0;
126759  if( pOrderBy ){
126760  int n = pOrderBy->nExpr;
126761  for(i=0; i<n; i++){
126762  Expr *pExpr = pOrderBy->a[i].pExpr;
126763  if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
126764  }
126765  if( i==n){
126766  nOrderBy = n;
126767  }
126768  }
126769 
126770  /* Allocate the sqlite3_index_info structure
126771  */
126772  pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
126773  + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
126774  + sizeof(*pIdxOrderBy)*nOrderBy );
126775  if( pIdxInfo==0 ){
126776  sqlite3ErrorMsg(pParse, "out of memory");
126777  return 0;
126778  }
126779 
126780  /* Initialize the structure. The sqlite3_index_info structure contains
126781  ** many fields that are declared "const" to prevent xBestIndex from
126782  ** changing them. We have to do some funky casting in order to
126783  ** initialize those fields.
126784  */
126785  pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
126786  pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
126787  pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
126788  *(int*)&pIdxInfo->nConstraint = nTerm;
126789  *(int*)&pIdxInfo->nOrderBy = nOrderBy;
126790  *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
126791  *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
126792  *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
126793  pUsage;
126794 
126795  for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
126796  u8 op;
126797  if( pTerm->leftCursor != pSrc->iCursor ) continue;
126798  if( pTerm->prereqRight & mUnusable ) continue;
126799  assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
126800  testcase( pTerm->eOperator & WO_IN );
126801  testcase( pTerm->eOperator & WO_IS );
126802  testcase( pTerm->eOperator & WO_ISNULL );
126803  testcase( pTerm->eOperator & WO_ALL );
126804  if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV|WO_IS))==0 ) continue;
126805  if( pTerm->wtFlags & TERM_VNULL ) continue;
126806  assert( pTerm->u.leftColumn>=(-1) );
126807  pIdxCons[j].iColumn = pTerm->u.leftColumn;
126808  pIdxCons[j].iTermOffset = i;
126809  op = (u8)pTerm->eOperator & WO_ALL;
126810  if( op==WO_IN ) op = WO_EQ;
126811  if( op==WO_MATCH ){
126812  op = pTerm->eMatchOp;
126813  }
126814  pIdxCons[j].op = op;
126815  /* The direct assignment in the previous line is possible only because
126816  ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
126817  ** following asserts verify this fact. */
126825  j++;
126826  }
126827  for(i=0; i<nOrderBy; i++){
126828  Expr *pExpr = pOrderBy->a[i].pExpr;
126829  pIdxOrderBy[i].iColumn = pExpr->iColumn;
126830  pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
126831  }
126832 
126833  return pIdxInfo;
126834 }
126835 
126836 /*
126837 ** The table object reference passed as the second argument to this function
126838 ** must represent a virtual table. This function invokes the xBestIndex()
126839 ** method of the virtual table with the sqlite3_index_info object that
126840 ** comes in as the 3rd argument to this function.
126841 **
126842 ** If an error occurs, pParse is populated with an error message and a
126843 ** non-zero value is returned. Otherwise, 0 is returned and the output
126844 ** part of the sqlite3_index_info structure is left populated.
126845 **
126846 ** Whether or not an error is returned, it is the responsibility of the
126847 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
126848 ** that this is required.
126849 */
126850 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
126851  sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
126852  int rc;
126853 
126854  TRACE_IDX_INPUTS(p);
126855  rc = pVtab->pModule->xBestIndex(pVtab, p);
126856  TRACE_IDX_OUTPUTS(p);
126857 
126858  if( rc!=SQLITE_OK ){
126859  if( rc==SQLITE_NOMEM ){
126860  sqlite3OomFault(pParse->db);
126861  }else if( !pVtab->zErrMsg ){
126862  sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
126863  }else{
126864  sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
126865  }
126866  }
126867  sqlite3_free(pVtab->zErrMsg);
126868  pVtab->zErrMsg = 0;
126869 
126870 #if 0
126871  /* This error is now caught by the caller.
126872  ** Search for "xBestIndex malfunction" below */
126873  for(i=0; i<p->nConstraint; i++){
126874  if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
126875  sqlite3ErrorMsg(pParse,
126876  "table %s: xBestIndex returned an invalid plan", pTab->zName);
126877  }
126878  }
126879 #endif
126880 
126881  return pParse->nErr;
126882 }
126883 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
126884 
126885 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
126886 /*
126887 ** Estimate the location of a particular key among all keys in an
126888 ** index. Store the results in aStat as follows:
126889 **
126890 ** aStat[0] Est. number of rows less than pRec
126891 ** aStat[1] Est. number of rows equal to pRec
126892 **
126893 ** Return the index of the sample that is the smallest sample that
126894 ** is greater than or equal to pRec. Note that this index is not an index
126895 ** into the aSample[] array - it is an index into a virtual set of samples
126896 ** based on the contents of aSample[] and the number of fields in record
126897 ** pRec.
126898 */
126899 static int whereKeyStats(
126900  Parse *pParse, /* Database connection */
126901  Index *pIdx, /* Index to consider domain of */
126902  UnpackedRecord *pRec, /* Vector of values to consider */
126903  int roundUp, /* Round up if true. Round down if false */
126904  tRowcnt *aStat /* OUT: stats written here */
126905 ){
126906  IndexSample *aSample = pIdx->aSample;
126907  int iCol; /* Index of required stats in anEq[] etc. */
126908  int i; /* Index of first sample >= pRec */
126909  int iSample; /* Smallest sample larger than or equal to pRec */
126910  int iMin = 0; /* Smallest sample not yet tested */
126911  int iTest; /* Next sample to test */
126912  int res; /* Result of comparison operation */
126913  int nField; /* Number of fields in pRec */
126914  tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
126915 
126916 #ifndef SQLITE_DEBUG
126917  UNUSED_PARAMETER( pParse );
126918 #endif
126919  assert( pRec!=0 );
126920  assert( pIdx->nSample>0 );
126921  assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
126922 
126923  /* Do a binary search to find the first sample greater than or equal
126924  ** to pRec. If pRec contains a single field, the set of samples to search
126925  ** is simply the aSample[] array. If the samples in aSample[] contain more
126926  ** than one fields, all fields following the first are ignored.
126927  **
126928  ** If pRec contains N fields, where N is more than one, then as well as the
126929  ** samples in aSample[] (truncated to N fields), the search also has to
126930  ** consider prefixes of those samples. For example, if the set of samples
126931  ** in aSample is:
126932  **
126933  ** aSample[0] = (a, 5)
126934  ** aSample[1] = (a, 10)
126935  ** aSample[2] = (b, 5)
126936  ** aSample[3] = (c, 100)
126937  ** aSample[4] = (c, 105)
126938  **
126939  ** Then the search space should ideally be the samples above and the
126940  ** unique prefixes [a], [b] and [c]. But since that is hard to organize,
126941  ** the code actually searches this set:
126942  **
126943  ** 0: (a)
126944  ** 1: (a, 5)
126945  ** 2: (a, 10)
126946  ** 3: (a, 10)
126947  ** 4: (b)
126948  ** 5: (b, 5)
126949  ** 6: (c)
126950  ** 7: (c, 100)
126951  ** 8: (c, 105)
126952  ** 9: (c, 105)
126953  **
126954  ** For each sample in the aSample[] array, N samples are present in the
126955  ** effective sample array. In the above, samples 0 and 1 are based on
126956  ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
126957  **
126958  ** Often, sample i of each block of N effective samples has (i+1) fields.
126959  ** Except, each sample may be extended to ensure that it is greater than or
126960  ** equal to the previous sample in the array. For example, in the above,
126961  ** sample 2 is the first sample of a block of N samples, so at first it
126962  ** appears that it should be 1 field in size. However, that would make it
126963  ** smaller than sample 1, so the binary search would not work. As a result,
126964  ** it is extended to two fields. The duplicates that this creates do not
126965  ** cause any problems.
126966  */
126967  nField = pRec->nField;
126968  iCol = 0;
126969  iSample = pIdx->nSample * nField;
126970  do{
126971  int iSamp; /* Index in aSample[] of test sample */
126972  int n; /* Number of fields in test sample */
126973 
126974  iTest = (iMin+iSample)/2;
126975  iSamp = iTest / nField;
126976  if( iSamp>0 ){
126977  /* The proposed effective sample is a prefix of sample aSample[iSamp].
126978  ** Specifically, the shortest prefix of at least (1 + iTest%nField)
126979  ** fields that is greater than the previous effective sample. */
126980  for(n=(iTest % nField) + 1; n<nField; n++){
126981  if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
126982  }
126983  }else{
126984  n = iTest + 1;
126985  }
126986 
126987  pRec->nField = n;
126988  res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
126989  if( res<0 ){
126990  iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
126991  iMin = iTest+1;
126992  }else if( res==0 && n<nField ){
126993  iLower = aSample[iSamp].anLt[n-1];
126994  iMin = iTest+1;
126995  res = -1;
126996  }else{
126997  iSample = iTest;
126998  iCol = n-1;
126999  }
127000  }while( res && iMin<iSample );
127001  i = iSample / nField;
127002 
127003 #ifdef SQLITE_DEBUG
127004  /* The following assert statements check that the binary search code
127005  ** above found the right answer. This block serves no purpose other
127006  ** than to invoke the asserts. */
127007  if( pParse->db->mallocFailed==0 ){
127008  if( res==0 ){
127009  /* If (res==0) is true, then pRec must be equal to sample i. */
127010  assert( i<pIdx->nSample );
127011  assert( iCol==nField-1 );
127012  pRec->nField = nField;
127013  assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
127014  || pParse->db->mallocFailed
127015  );
127016  }else{
127017  /* Unless i==pIdx->nSample, indicating that pRec is larger than
127018  ** all samples in the aSample[] array, pRec must be smaller than the
127019  ** (iCol+1) field prefix of sample i. */
127020  assert( i<=pIdx->nSample && i>=0 );
127021  pRec->nField = iCol+1;
127022  assert( i==pIdx->nSample
127023  || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
127024  || pParse->db->mallocFailed );
127025 
127026  /* if i==0 and iCol==0, then record pRec is smaller than all samples
127027  ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
127028  ** be greater than or equal to the (iCol) field prefix of sample i.
127029  ** If (i>0), then pRec must also be greater than sample (i-1). */
127030  if( iCol>0 ){
127031  pRec->nField = iCol;
127032  assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
127033  || pParse->db->mallocFailed );
127034  }
127035  if( i>0 ){
127036  pRec->nField = nField;
127037  assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
127038  || pParse->db->mallocFailed );
127039  }
127040  }
127041  }
127042 #endif /* ifdef SQLITE_DEBUG */
127043 
127044  if( res==0 ){
127045  /* Record pRec is equal to sample i */
127046  assert( iCol==nField-1 );
127047  aStat[0] = aSample[i].anLt[iCol];
127048  aStat[1] = aSample[i].anEq[iCol];
127049  }else{
127050  /* At this point, the (iCol+1) field prefix of aSample[i] is the first
127051  ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
127052  ** is larger than all samples in the array. */
127053  tRowcnt iUpper, iGap;
127054  if( i>=pIdx->nSample ){
127055  iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
127056  }else{
127057  iUpper = aSample[i].anLt[iCol];
127058  }
127059 
127060  if( iLower>=iUpper ){
127061  iGap = 0;
127062  }else{
127063  iGap = iUpper - iLower;
127064  }
127065  if( roundUp ){
127066  iGap = (iGap*2)/3;
127067  }else{
127068  iGap = iGap/3;
127069  }
127070  aStat[0] = iLower + iGap;
127071  aStat[1] = pIdx->aAvgEq[iCol];
127072  }
127073 
127074  /* Restore the pRec->nField value before returning. */
127075  pRec->nField = nField;
127076  return i;
127077 }
127078 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127079 
127080 /*
127081 ** If it is not NULL, pTerm is a term that provides an upper or lower
127082 ** bound on a range scan. Without considering pTerm, it is estimated
127083 ** that the scan will visit nNew rows. This function returns the number
127084 ** estimated to be visited after taking pTerm into account.
127085 **
127086 ** If the user explicitly specified a likelihood() value for this term,
127087 ** then the return value is the likelihood multiplied by the number of
127088 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
127089 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
127090 */
127091 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
127092  LogEst nRet = nNew;
127093  if( pTerm ){
127094  if( pTerm->truthProb<=0 ){
127095  nRet += pTerm->truthProb;
127096  }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
127097  nRet -= 20; assert( 20==sqlite3LogEst(4) );
127098  }
127099  }
127100  return nRet;
127101 }
127102 
127103 
127104 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127105 /*
127106 ** Return the affinity for a single column of an index.
127107 */
127108 static char sqlite3IndexColumnAffinity(sqlite3 *db, Index *pIdx, int iCol){
127109  assert( iCol>=0 && iCol<pIdx->nColumn );
127110  if( !pIdx->zColAff ){
127111  if( sqlite3IndexAffinityStr(db, pIdx)==0 ) return SQLITE_AFF_BLOB;
127112  }
127113  return pIdx->zColAff[iCol];
127114 }
127115 #endif
127116 
127117 
127118 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127119 /*
127120 ** This function is called to estimate the number of rows visited by a
127121 ** range-scan on a skip-scan index. For example:
127122 **
127123 ** CREATE INDEX i1 ON t1(a, b, c);
127124 ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
127125 **
127126 ** Value pLoop->nOut is currently set to the estimated number of rows
127127 ** visited for scanning (a=? AND b=?). This function reduces that estimate
127128 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
127129 ** on the stat4 data for the index. this scan will be peformed multiple
127130 ** times (once for each (a,b) combination that matches a=?) is dealt with
127131 ** by the caller.
127132 **
127133 ** It does this by scanning through all stat4 samples, comparing values
127134 ** extracted from pLower and pUpper with the corresponding column in each
127135 ** sample. If L and U are the number of samples found to be less than or
127136 ** equal to the values extracted from pLower and pUpper respectively, and
127137 ** N is the total number of samples, the pLoop->nOut value is adjusted
127138 ** as follows:
127139 **
127140 ** nOut = nOut * ( min(U - L, 1) / N )
127141 **
127142 ** If pLower is NULL, or a value cannot be extracted from the term, L is
127143 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
127144 ** U is set to N.
127145 **
127146 ** Normally, this function sets *pbDone to 1 before returning. However,
127147 ** if no value can be extracted from either pLower or pUpper (and so the
127148 ** estimate of the number of rows delivered remains unchanged), *pbDone
127149 ** is left as is.
127150 **
127151 ** If an error occurs, an SQLite error code is returned. Otherwise,
127152 ** SQLITE_OK.
127153 */
127154 static int whereRangeSkipScanEst(
127155  Parse *pParse, /* Parsing & code generating context */
127156  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
127157  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
127158  WhereLoop *pLoop, /* Update the .nOut value of this loop */
127159  int *pbDone /* Set to true if at least one expr. value extracted */
127160 ){
127161  Index *p = pLoop->u.btree.pIndex;
127162  int nEq = pLoop->u.btree.nEq;
127163  sqlite3 *db = pParse->db;
127164  int nLower = -1;
127165  int nUpper = p->nSample+1;
127166  int rc = SQLITE_OK;
127167  u8 aff = sqlite3IndexColumnAffinity(db, p, nEq);
127168  CollSeq *pColl;
127169 
127170  sqlite3_value *p1 = 0; /* Value extracted from pLower */
127171  sqlite3_value *p2 = 0; /* Value extracted from pUpper */
127172  sqlite3_value *pVal = 0; /* Value extracted from record */
127173 
127174  pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
127175  if( pLower ){
127176  rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
127177  nLower = 0;
127178  }
127179  if( pUpper && rc==SQLITE_OK ){
127180  rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
127181  nUpper = p2 ? 0 : p->nSample;
127182  }
127183 
127184  if( p1 || p2 ){
127185  int i;
127186  int nDiff;
127187  for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
127188  rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
127189  if( rc==SQLITE_OK && p1 ){
127190  int res = sqlite3MemCompare(p1, pVal, pColl);
127191  if( res>=0 ) nLower++;
127192  }
127193  if( rc==SQLITE_OK && p2 ){
127194  int res = sqlite3MemCompare(p2, pVal, pColl);
127195  if( res>=0 ) nUpper++;
127196  }
127197  }
127198  nDiff = (nUpper - nLower);
127199  if( nDiff<=0 ) nDiff = 1;
127200 
127201  /* If there is both an upper and lower bound specified, and the
127202  ** comparisons indicate that they are close together, use the fallback
127203  ** method (assume that the scan visits 1/64 of the rows) for estimating
127204  ** the number of rows visited. Otherwise, estimate the number of rows
127205  ** using the method described in the header comment for this function. */
127206  if( nDiff!=1 || pUpper==0 || pLower==0 ){
127207  int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
127208  pLoop->nOut -= nAdjust;
127209  *pbDone = 1;
127210  WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
127211  nLower, nUpper, nAdjust*-1, pLoop->nOut));
127212  }
127213 
127214  }else{
127215  assert( *pbDone==0 );
127216  }
127217 
127218  sqlite3ValueFree(p1);
127219  sqlite3ValueFree(p2);
127220  sqlite3ValueFree(pVal);
127221 
127222  return rc;
127223 }
127224 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127225 
127226 /*
127227 ** This function is used to estimate the number of rows that will be visited
127228 ** by scanning an index for a range of values. The range may have an upper
127229 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
127230 ** and lower bounds are represented by pLower and pUpper respectively. For
127231 ** example, assuming that index p is on t1(a):
127232 **
127233 ** ... FROM t1 WHERE a > ? AND a < ? ...
127234 ** |_____| |_____|
127235 ** | |
127236 ** pLower pUpper
127237 **
127238 ** If either of the upper or lower bound is not present, then NULL is passed in
127239 ** place of the corresponding WhereTerm.
127240 **
127241 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
127242 ** column subject to the range constraint. Or, equivalently, the number of
127243 ** equality constraints optimized by the proposed index scan. For example,
127244 ** assuming index p is on t1(a, b), and the SQL query is:
127245 **
127246 ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
127247 **
127248 ** then nEq is set to 1 (as the range restricted column, b, is the second
127249 ** left-most column of the index). Or, if the query is:
127250 **
127251 ** ... FROM t1 WHERE a > ? AND a < ? ...
127252 **
127253 ** then nEq is set to 0.
127254 **
127255 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
127256 ** number of rows that the index scan is expected to visit without
127257 ** considering the range constraints. If nEq is 0, then *pnOut is the number of
127258 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
127259 ** to account for the range constraints pLower and pUpper.
127260 **
127261 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
127262 ** used, a single range inequality reduces the search space by a factor of 4.
127263 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
127264 ** rows visited by a factor of 64.
127265 */
127267  Parse *pParse, /* Parsing & code generating context */
127268  WhereLoopBuilder *pBuilder,
127269  WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
127270  WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
127271  WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
127272 ){
127273  int rc = SQLITE_OK;
127274  int nOut = pLoop->nOut;
127275  LogEst nNew;
127276 
127277 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127278  Index *p = pLoop->u.btree.pIndex;
127279  int nEq = pLoop->u.btree.nEq;
127280 
127281  if( p->nSample>0 && nEq<p->nSampleCol ){
127282  if( nEq==pBuilder->nRecValid ){
127283  UnpackedRecord *pRec = pBuilder->pRec;
127284  tRowcnt a[2];
127285  u8 aff;
127286 
127287  /* Variable iLower will be set to the estimate of the number of rows in
127288  ** the index that are less than the lower bound of the range query. The
127289  ** lower bound being the concatenation of $P and $L, where $P is the
127290  ** key-prefix formed by the nEq values matched against the nEq left-most
127291  ** columns of the index, and $L is the value in pLower.
127292  **
127293  ** Or, if pLower is NULL or $L cannot be extracted from it (because it
127294  ** is not a simple variable or literal value), the lower bound of the
127295  ** range is $P. Due to a quirk in the way whereKeyStats() works, even
127296  ** if $L is available, whereKeyStats() is called for both ($P) and
127297  ** ($P:$L) and the larger of the two returned values is used.
127298  **
127299  ** Similarly, iUpper is to be set to the estimate of the number of rows
127300  ** less than the upper bound of the range query. Where the upper bound
127301  ** is either ($P) or ($P:$U). Again, even if $U is available, both values
127302  ** of iUpper are requested of whereKeyStats() and the smaller used.
127303  **
127304  ** The number of rows between the two bounds is then just iUpper-iLower.
127305  */
127306  tRowcnt iLower; /* Rows less than the lower bound */
127307  tRowcnt iUpper; /* Rows less than the upper bound */
127308  int iLwrIdx = -2; /* aSample[] for the lower bound */
127309  int iUprIdx = -1; /* aSample[] for the upper bound */
127310 
127311  if( pRec ){
127312  testcase( pRec->nField!=pBuilder->nRecValid );
127313  pRec->nField = pBuilder->nRecValid;
127314  }
127315  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq);
127316  assert( nEq!=p->nKeyCol || aff==SQLITE_AFF_INTEGER );
127317  /* Determine iLower and iUpper using ($P) only. */
127318  if( nEq==0 ){
127319  iLower = 0;
127320  iUpper = p->nRowEst0;
127321  }else{
127322  /* Note: this call could be optimized away - since the same values must
127323  ** have been requested when testing key $P in whereEqualScanEst(). */
127324  whereKeyStats(pParse, p, pRec, 0, a);
127325  iLower = a[0];
127326  iUpper = a[0] + a[1];
127327  }
127328 
127329  assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
127330  assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
127331  assert( p->aSortOrder!=0 );
127332  if( p->aSortOrder[nEq] ){
127333  /* The roles of pLower and pUpper are swapped for a DESC index */
127334  SWAP(WhereTerm*, pLower, pUpper);
127335  }
127336 
127337  /* If possible, improve on the iLower estimate using ($P:$L). */
127338  if( pLower ){
127339  int bOk; /* True if value is extracted from pExpr */
127340  Expr *pExpr = pLower->pExpr->pRight;
127341  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
127342  if( rc==SQLITE_OK && bOk ){
127343  tRowcnt iNew;
127344  iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
127345  iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
127346  if( iNew>iLower ) iLower = iNew;
127347  nOut--;
127348  pLower = 0;
127349  }
127350  }
127351 
127352  /* If possible, improve on the iUpper estimate using ($P:$U). */
127353  if( pUpper ){
127354  int bOk; /* True if value is extracted from pExpr */
127355  Expr *pExpr = pUpper->pExpr->pRight;
127356  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
127357  if( rc==SQLITE_OK && bOk ){
127358  tRowcnt iNew;
127359  iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
127360  iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
127361  if( iNew<iUpper ) iUpper = iNew;
127362  nOut--;
127363  pUpper = 0;
127364  }
127365  }
127366 
127367  pBuilder->pRec = pRec;
127368  if( rc==SQLITE_OK ){
127369  if( iUpper>iLower ){
127370  nNew = sqlite3LogEst(iUpper - iLower);
127371  /* TUNING: If both iUpper and iLower are derived from the same
127372  ** sample, then assume they are 4x more selective. This brings
127373  ** the estimated selectivity more in line with what it would be
127374  ** if estimated without the use of STAT3/4 tables. */
127375  if( iLwrIdx==iUprIdx ) nNew -= 20; assert( 20==sqlite3LogEst(4) );
127376  }else{
127377  nNew = 10; assert( 10==sqlite3LogEst(2) );
127378  }
127379  if( nNew<nOut ){
127380  nOut = nNew;
127381  }
127382  WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
127383  (u32)iLower, (u32)iUpper, nOut));
127384  }
127385  }else{
127386  int bDone = 0;
127387  rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
127388  if( bDone ) return rc;
127389  }
127390  }
127391 #else
127392  UNUSED_PARAMETER(pParse);
127393  UNUSED_PARAMETER(pBuilder);
127394  assert( pLower || pUpper );
127395 #endif
127396  assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
127397  nNew = whereRangeAdjust(pLower, nOut);
127398  nNew = whereRangeAdjust(pUpper, nNew);
127399 
127400  /* TUNING: If there is both an upper and lower limit and neither limit
127401  ** has an application-defined likelihood(), assume the range is
127402  ** reduced by an additional 75%. This means that, by default, an open-ended
127403  ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
127404  ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
127405  ** match 1/64 of the index. */
127406  if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
127407  nNew -= 20;
127408  }
127409 
127410  nOut -= (pLower!=0) + (pUpper!=0);
127411  if( nNew<10 ) nNew = 10;
127412  if( nNew<nOut ) nOut = nNew;
127413 #if defined(WHERETRACE_ENABLED)
127414  if( pLoop->nOut>nOut ){
127415  WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
127416  pLoop->nOut, nOut));
127417  }
127418 #endif
127419  pLoop->nOut = (LogEst)nOut;
127420  return rc;
127421 }
127422 
127423 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127424 /*
127425 ** Estimate the number of rows that will be returned based on
127426 ** an equality constraint x=VALUE and where that VALUE occurs in
127427 ** the histogram data. This only works when x is the left-most
127428 ** column of an index and sqlite_stat3 histogram data is available
127429 ** for that index. When pExpr==NULL that means the constraint is
127430 ** "x IS NULL" instead of "x=VALUE".
127431 **
127432 ** Write the estimated row count into *pnRow and return SQLITE_OK.
127433 ** If unable to make an estimate, leave *pnRow unchanged and return
127434 ** non-zero.
127435 **
127436 ** This routine can fail if it is unable to load a collating sequence
127437 ** required for string comparison, or if unable to allocate memory
127438 ** for a UTF conversion required for comparison. The error is stored
127439 ** in the pParse structure.
127440 */
127441 static int whereEqualScanEst(
127442  Parse *pParse, /* Parsing & code generating context */
127443  WhereLoopBuilder *pBuilder,
127444  Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
127445  tRowcnt *pnRow /* Write the revised row estimate here */
127446 ){
127447  Index *p = pBuilder->pNew->u.btree.pIndex;
127448  int nEq = pBuilder->pNew->u.btree.nEq;
127449  UnpackedRecord *pRec = pBuilder->pRec;
127450  u8 aff; /* Column affinity */
127451  int rc; /* Subfunction return code */
127452  tRowcnt a[2]; /* Statistics */
127453  int bOk;
127454 
127455  assert( nEq>=1 );
127456  assert( nEq<=p->nColumn );
127457  assert( p->aSample!=0 );
127458  assert( p->nSample>0 );
127459  assert( pBuilder->nRecValid<nEq );
127460 
127461  /* If values are not available for all fields of the index to the left
127462  ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
127463  if( pBuilder->nRecValid<(nEq-1) ){
127464  return SQLITE_NOTFOUND;
127465  }
127466 
127467  /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
127468  ** below would return the same value. */
127469  if( nEq>=p->nColumn ){
127470  *pnRow = 1;
127471  return SQLITE_OK;
127472  }
127473 
127474  aff = sqlite3IndexColumnAffinity(pParse->db, p, nEq-1);
127475  rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
127476  pBuilder->pRec = pRec;
127477  if( rc!=SQLITE_OK ) return rc;
127478  if( bOk==0 ) return SQLITE_NOTFOUND;
127479  pBuilder->nRecValid = nEq;
127480 
127481  whereKeyStats(pParse, p, pRec, 0, a);
127482  WHERETRACE(0x10,("equality scan regions %s(%d): %d\n",
127483  p->zName, nEq-1, (int)a[1]));
127484  *pnRow = a[1];
127485 
127486  return rc;
127487 }
127488 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127489 
127490 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
127491 /*
127492 ** Estimate the number of rows that will be returned based on
127493 ** an IN constraint where the right-hand side of the IN operator
127494 ** is a list of values. Example:
127495 **
127496 ** WHERE x IN (1,2,3,4)
127497 **
127498 ** Write the estimated row count into *pnRow and return SQLITE_OK.
127499 ** If unable to make an estimate, leave *pnRow unchanged and return
127500 ** non-zero.
127501 **
127502 ** This routine can fail if it is unable to load a collating sequence
127503 ** required for string comparison, or if unable to allocate memory
127504 ** for a UTF conversion required for comparison. The error is stored
127505 ** in the pParse structure.
127506 */
127507 static int whereInScanEst(
127508  Parse *pParse, /* Parsing & code generating context */
127509  WhereLoopBuilder *pBuilder,
127510  ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
127511  tRowcnt *pnRow /* Write the revised row estimate here */
127512 ){
127513  Index *p = pBuilder->pNew->u.btree.pIndex;
127514  i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
127515  int nRecValid = pBuilder->nRecValid;
127516  int rc = SQLITE_OK; /* Subfunction return code */
127517  tRowcnt nEst; /* Number of rows for a single term */
127518  tRowcnt nRowEst = 0; /* New estimate of the number of rows */
127519  int i; /* Loop counter */
127520 
127521  assert( p->aSample!=0 );
127522  for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
127523  nEst = nRow0;
127524  rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
127525  nRowEst += nEst;
127526  pBuilder->nRecValid = nRecValid;
127527  }
127528 
127529  if( rc==SQLITE_OK ){
127530  if( nRowEst > nRow0 ) nRowEst = nRow0;
127531  *pnRow = nRowEst;
127532  WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
127533  }
127534  assert( pBuilder->nRecValid==nRecValid );
127535  return rc;
127536 }
127537 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
127538 
127539 
127540 #ifdef WHERETRACE_ENABLED
127541 /*
127542 ** Print the content of a WhereTerm object
127543 */
127544 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
127545  if( pTerm==0 ){
127546  sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
127547  }else{
127548  char zType[4];
127549  memcpy(zType, "...", 4);
127550  if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
127551  if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
127552  if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
127553  sqlite3DebugPrintf(
127554  "TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x wtFlags=0x%04x\n",
127555  iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
127556  pTerm->eOperator, pTerm->wtFlags);
127557  sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
127558  }
127559 }
127560 #endif
127561 
127562 #ifdef WHERETRACE_ENABLED
127563 /*
127564 ** Print a WhereLoop object for debugging purposes
127565 */
127566 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
127567  WhereInfo *pWInfo = pWC->pWInfo;
127568  int nb = 1+(pWInfo->pTabList->nSrc+3)/4;
127569  struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
127570  Table *pTab = pItem->pTab;
127571  Bitmask mAll = (((Bitmask)1)<<(nb*4)) - 1;
127572  sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
127573  p->iTab, nb, p->maskSelf, nb, p->prereq & mAll);
127574  sqlite3DebugPrintf(" %12s",
127575  pItem->zAlias ? pItem->zAlias : pTab->zName);
127576  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
127577  const char *zName;
127578  if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
127579  if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
127580  int i = sqlite3Strlen30(zName) - 1;
127581  while( zName[i]!='_' ) i--;
127582  zName += i;
127583  }
127584  sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
127585  }else{
127586  sqlite3DebugPrintf("%20s","");
127587  }
127588  }else{
127589  char *z;
127590  if( p->u.vtab.idxStr ){
127591  z = sqlite3_mprintf("(%d,\"%s\",%x)",
127592  p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
127593  }else{
127594  z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
127595  }
127596  sqlite3DebugPrintf(" %-19s", z);
127597  sqlite3_free(z);
127598  }
127599  if( p->wsFlags & WHERE_SKIPSCAN ){
127600  sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
127601  }else{
127602  sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
127603  }
127604  sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
127605  if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
127606  int i;
127607  for(i=0; i<p->nLTerm; i++){
127608  whereTermPrint(p->aLTerm[i], i);
127609  }
127610  }
127611 }
127612 #endif
127613 
127614 /*
127615 ** Convert bulk memory into a valid WhereLoop that can be passed
127616 ** to whereLoopClear harmlessly.
127617 */
127618 static void whereLoopInit(WhereLoop *p){
127619  p->aLTerm = p->aLTermSpace;
127620  p->nLTerm = 0;
127621  p->nLSlot = ArraySize(p->aLTermSpace);
127622  p->wsFlags = 0;
127623 }
127624 
127625 /*
127626 ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
127627 */
127628 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
127630  if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
127631  sqlite3_free(p->u.vtab.idxStr);
127632  p->u.vtab.needFree = 0;
127633  p->u.vtab.idxStr = 0;
127634  }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
127635  sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
127636  sqlite3DbFree(db, p->u.btree.pIndex);
127637  p->u.btree.pIndex = 0;
127638  }
127639  }
127640 }
127641 
127642 /*
127643 ** Deallocate internal memory used by a WhereLoop object
127644 */
127645 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
127646  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
127647  whereLoopClearUnion(db, p);
127648  whereLoopInit(p);
127649 }
127650 
127651 /*
127652 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
127653 */
127654 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
127655  WhereTerm **paNew;
127656  if( p->nLSlot>=n ) return SQLITE_OK;
127657  n = (n+7)&~7;
127658  paNew = sqlite3DbMallocRawNN(db, sizeof(p->aLTerm[0])*n);
127659  if( paNew==0 ) return SQLITE_NOMEM_BKPT;
127660  memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
127661  if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
127662  p->aLTerm = paNew;
127663  p->nLSlot = n;
127664  return SQLITE_OK;
127665 }
127666 
127667 /*
127668 ** Transfer content from the second pLoop into the first.
127669 */
127670 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
127671  whereLoopClearUnion(db, pTo);
127672  if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
127673  memset(&pTo->u, 0, sizeof(pTo->u));
127674  return SQLITE_NOMEM_BKPT;
127675  }
127676  memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
127677  memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
127678  if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
127679  pFrom->u.vtab.needFree = 0;
127680  }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
127681  pFrom->u.btree.pIndex = 0;
127682  }
127683  return SQLITE_OK;
127684 }
127685 
127686 /*
127687 ** Delete a WhereLoop object
127688 */
127689 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
127690  whereLoopClear(db, p);
127691  sqlite3DbFree(db, p);
127692 }
127693 
127694 /*
127695 ** Free a WhereInfo structure
127696 */
127697 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
127698  if( ALWAYS(pWInfo) ){
127699  int i;
127700  for(i=0; i<pWInfo->nLevel; i++){
127701  WhereLevel *pLevel = &pWInfo->a[i];
127702  if( pLevel->pWLoop && (pLevel->pWLoop->wsFlags & WHERE_IN_ABLE) ){
127703  sqlite3DbFree(db, pLevel->u.in.aInLoop);
127704  }
127705  }
127706  sqlite3WhereClauseClear(&pWInfo->sWC);
127707  while( pWInfo->pLoops ){
127708  WhereLoop *p = pWInfo->pLoops;
127709  pWInfo->pLoops = p->pNextLoop;
127710  whereLoopDelete(db, p);
127711  }
127712  sqlite3DbFree(db, pWInfo);
127713  }
127714 }
127715 
127716 /*
127717 ** Return TRUE if all of the following are true:
127718 **
127719 ** (1) X has the same or lower cost that Y
127720 ** (2) X is a proper subset of Y
127721 ** (3) X skips at least as many columns as Y
127722 **
127723 ** By "proper subset" we mean that X uses fewer WHERE clause terms
127724 ** than Y and that every WHERE clause term used by X is also used
127725 ** by Y.
127726 **
127727 ** If X is a proper subset of Y then Y is a better choice and ought
127728 ** to have a lower cost. This routine returns TRUE when that cost
127729 ** relationship is inverted and needs to be adjusted. The third rule
127730 ** was added because if X uses skip-scan less than Y it still might
127731 ** deserve a lower cost even if it is a proper subset of Y.
127732 */
127734  const WhereLoop *pX, /* First WhereLoop to compare */
127735  const WhereLoop *pY /* Compare against this WhereLoop */
127736 ){
127737  int i, j;
127738  if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
127739  return 0; /* X is not a subset of Y */
127740  }
127741  if( pY->nSkip > pX->nSkip ) return 0;
127742  if( pX->rRun >= pY->rRun ){
127743  if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
127744  if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
127745  }
127746  for(i=pX->nLTerm-1; i>=0; i--){
127747  if( pX->aLTerm[i]==0 ) continue;
127748  for(j=pY->nLTerm-1; j>=0; j--){
127749  if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
127750  }
127751  if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
127752  }
127753  return 1; /* All conditions meet */
127754 }
127755 
127756 /*
127757 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
127758 ** that:
127759 **
127760 ** (1) pTemplate costs less than any other WhereLoops that are a proper
127761 ** subset of pTemplate
127762 **
127763 ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
127764 ** is a proper subset.
127765 **
127766 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
127767 ** WHERE clause terms than Y and that every WHERE clause term used by X is
127768 ** also used by Y.
127769 */
127770 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
127771  if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
127772  for(; p; p=p->pNextLoop){
127773  if( p->iTab!=pTemplate->iTab ) continue;
127774  if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
127775  if( whereLoopCheaperProperSubset(p, pTemplate) ){
127776  /* Adjust pTemplate cost downward so that it is cheaper than its
127777  ** subset p. */
127778  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
127779  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
127780  pTemplate->rRun = p->rRun;
127781  pTemplate->nOut = p->nOut - 1;
127782  }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
127783  /* Adjust pTemplate cost upward so that it is costlier than p since
127784  ** pTemplate is a proper subset of p */
127785  WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
127786  pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
127787  pTemplate->rRun = p->rRun;
127788  pTemplate->nOut = p->nOut + 1;
127789  }
127790  }
127791 }
127792 
127793 /*
127794 ** Search the list of WhereLoops in *ppPrev looking for one that can be
127795 ** supplanted by pTemplate.
127796 **
127797 ** Return NULL if the WhereLoop list contains an entry that can supplant
127798 ** pTemplate, in other words if pTemplate does not belong on the list.
127799 **
127800 ** If pX is a WhereLoop that pTemplate can supplant, then return the
127801 ** link that points to pX.
127802 **
127803 ** If pTemplate cannot supplant any existing element of the list but needs
127804 ** to be added to the list, then return a pointer to the tail of the list.
127805 */
127807  WhereLoop **ppPrev,
127808  const WhereLoop *pTemplate
127809 ){
127810  WhereLoop *p;
127811  for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
127812  if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
127813  /* If either the iTab or iSortIdx values for two WhereLoop are different
127814  ** then those WhereLoops need to be considered separately. Neither is
127815  ** a candidate to replace the other. */
127816  continue;
127817  }
127818  /* In the current implementation, the rSetup value is either zero
127819  ** or the cost of building an automatic index (NlogN) and the NlogN
127820  ** is the same for compatible WhereLoops. */
127821  assert( p->rSetup==0 || pTemplate->rSetup==0
127822  || p->rSetup==pTemplate->rSetup );
127823 
127824  /* whereLoopAddBtree() always generates and inserts the automatic index
127825  ** case first. Hence compatible candidate WhereLoops never have a larger
127826  ** rSetup. Call this SETUP-INVARIANT */
127827  assert( p->rSetup>=pTemplate->rSetup );
127828 
127829  /* Any loop using an appliation-defined index (or PRIMARY KEY or
127830  ** UNIQUE constraint) with one or more == constraints is better
127831  ** than an automatic index. Unless it is a skip-scan. */
127832  if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
127833  && (pTemplate->nSkip)==0
127834  && (pTemplate->wsFlags & WHERE_INDEXED)!=0
127835  && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
127836  && (p->prereq & pTemplate->prereq)==pTemplate->prereq
127837  ){
127838  break;
127839  }
127840 
127841  /* If existing WhereLoop p is better than pTemplate, pTemplate can be
127842  ** discarded. WhereLoop p is better if:
127843  ** (1) p has no more dependencies than pTemplate, and
127844  ** (2) p has an equal or lower cost than pTemplate
127845  */
127846  if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
127847  && p->rSetup<=pTemplate->rSetup /* (2a) */
127848  && p->rRun<=pTemplate->rRun /* (2b) */
127849  && p->nOut<=pTemplate->nOut /* (2c) */
127850  ){
127851  return 0; /* Discard pTemplate */
127852  }
127853 
127854  /* If pTemplate is always better than p, then cause p to be overwritten
127855  ** with pTemplate. pTemplate is better than p if:
127856  ** (1) pTemplate has no more dependences than p, and
127857  ** (2) pTemplate has an equal or lower cost than p.
127858  */
127859  if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
127860  && p->rRun>=pTemplate->rRun /* (2a) */
127861  && p->nOut>=pTemplate->nOut /* (2b) */
127862  ){
127863  assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
127864  break; /* Cause p to be overwritten by pTemplate */
127865  }
127866  }
127867  return ppPrev;
127868 }
127869 
127870 /*
127871 ** Insert or replace a WhereLoop entry using the template supplied.
127872 **
127873 ** An existing WhereLoop entry might be overwritten if the new template
127874 ** is better and has fewer dependencies. Or the template will be ignored
127875 ** and no insert will occur if an existing WhereLoop is faster and has
127876 ** fewer dependencies than the template. Otherwise a new WhereLoop is
127877 ** added based on the template.
127878 **
127879 ** If pBuilder->pOrSet is not NULL then we care about only the
127880 ** prerequisites and rRun and nOut costs of the N best loops. That
127881 ** information is gathered in the pBuilder->pOrSet object. This special
127882 ** processing mode is used only for OR clause processing.
127883 **
127884 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
127885 ** still might overwrite similar loops with the new template if the
127886 ** new template is better. Loops may be overwritten if the following
127887 ** conditions are met:
127888 **
127889 ** (1) They have the same iTab.
127890 ** (2) They have the same iSortIdx.
127891 ** (3) The template has same or fewer dependencies than the current loop
127892 ** (4) The template has the same or lower cost than the current loop
127893 */
127894 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
127895  WhereLoop **ppPrev, *p;
127896  WhereInfo *pWInfo = pBuilder->pWInfo;
127897  sqlite3 *db = pWInfo->pParse->db;
127898  int rc;
127899 
127900  /* If pBuilder->pOrSet is defined, then only keep track of the costs
127901  ** and prereqs.
127902  */
127903  if( pBuilder->pOrSet!=0 ){
127904  if( pTemplate->nLTerm ){
127905 #if WHERETRACE_ENABLED
127906  u16 n = pBuilder->pOrSet->n;
127907  int x =
127908 #endif
127909  whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
127910  pTemplate->nOut);
127911 #if WHERETRACE_ENABLED /* 0x8 */
127912  if( sqlite3WhereTrace & 0x8 ){
127913  sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
127914  whereLoopPrint(pTemplate, pBuilder->pWC);
127915  }
127916 #endif
127917  }
127918  return SQLITE_OK;
127919  }
127920 
127921  /* Look for an existing WhereLoop to replace with pTemplate
127922  */
127923  whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
127924  ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
127925 
127926  if( ppPrev==0 ){
127927  /* There already exists a WhereLoop on the list that is better
127928  ** than pTemplate, so just ignore pTemplate */
127929 #if WHERETRACE_ENABLED /* 0x8 */
127930  if( sqlite3WhereTrace & 0x8 ){
127931  sqlite3DebugPrintf(" skip: ");
127932  whereLoopPrint(pTemplate, pBuilder->pWC);
127933  }
127934 #endif
127935  return SQLITE_OK;
127936  }else{
127937  p = *ppPrev;
127938  }
127939 
127940  /* If we reach this point it means that either p[] should be overwritten
127941  ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
127942  ** WhereLoop and insert it.
127943  */
127944 #if WHERETRACE_ENABLED /* 0x8 */
127945  if( sqlite3WhereTrace & 0x8 ){
127946  if( p!=0 ){
127947  sqlite3DebugPrintf("replace: ");
127948  whereLoopPrint(p, pBuilder->pWC);
127949  }
127950  sqlite3DebugPrintf(" add: ");
127951  whereLoopPrint(pTemplate, pBuilder->pWC);
127952  }
127953 #endif
127954  if( p==0 ){
127955  /* Allocate a new WhereLoop to add to the end of the list */
127956  *ppPrev = p = sqlite3DbMallocRawNN(db, sizeof(WhereLoop));
127957  if( p==0 ) return SQLITE_NOMEM_BKPT;
127958  whereLoopInit(p);
127959  p->pNextLoop = 0;
127960  }else{
127961  /* We will be overwriting WhereLoop p[]. But before we do, first
127962  ** go through the rest of the list and delete any other entries besides
127963  ** p[] that are also supplated by pTemplate */
127964  WhereLoop **ppTail = &p->pNextLoop;
127965  WhereLoop *pToDel;
127966  while( *ppTail ){
127967  ppTail = whereLoopFindLesser(ppTail, pTemplate);
127968  if( ppTail==0 ) break;
127969  pToDel = *ppTail;
127970  if( pToDel==0 ) break;
127971  *ppTail = pToDel->pNextLoop;
127972 #if WHERETRACE_ENABLED /* 0x8 */
127973  if( sqlite3WhereTrace & 0x8 ){
127974  sqlite3DebugPrintf(" delete: ");
127975  whereLoopPrint(pToDel, pBuilder->pWC);
127976  }
127977 #endif
127978  whereLoopDelete(db, pToDel);
127979  }
127980  }
127981  rc = whereLoopXfer(db, p, pTemplate);
127982  if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
127983  Index *pIndex = p->u.btree.pIndex;
127984  if( pIndex && pIndex->tnum==0 ){
127985  p->u.btree.pIndex = 0;
127986  }
127987  }
127988  return rc;
127989 }
127990 
127991 /*
127992 ** Adjust the WhereLoop.nOut value downward to account for terms of the
127993 ** WHERE clause that reference the loop but which are not used by an
127994 ** index.
127995 *
127996 ** For every WHERE clause term that is not used by the index
127997 ** and which has a truth probability assigned by one of the likelihood(),
127998 ** likely(), or unlikely() SQL functions, reduce the estimated number
127999 ** of output rows by the probability specified.
128000 **
128001 ** TUNING: For every WHERE clause term that is not used by the index
128002 ** and which does not have an assigned truth probability, heuristics
128003 ** described below are used to try to estimate the truth probability.
128004 ** TODO --> Perhaps this is something that could be improved by better
128005 ** table statistics.
128006 **
128007 ** Heuristic 1: Estimate the truth probability as 93.75%. The 93.75%
128008 ** value corresponds to -1 in LogEst notation, so this means decrement
128009 ** the WhereLoop.nOut field for every such WHERE clause term.
128010 **
128011 ** Heuristic 2: If there exists one or more WHERE clause terms of the
128012 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
128013 ** final output row estimate is no greater than 1/4 of the total number
128014 ** of rows in the table. In other words, assume that x==EXPR will filter
128015 ** out at least 3 out of 4 rows. If EXPR is -1 or 0 or 1, then maybe the
128016 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
128017 ** on the "x" column and so in that case only cap the output row estimate
128018 ** at 1/2 instead of 1/4.
128019 */
128021  WhereClause *pWC, /* The WHERE clause */
128022  WhereLoop *pLoop, /* The loop to adjust downward */
128023  LogEst nRow /* Number of rows in the entire table */
128024 ){
128025  WhereTerm *pTerm, *pX;
128026  Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
128027  int i, j, k;
128028  LogEst iReduce = 0; /* pLoop->nOut should not exceed nRow-iReduce */
128029 
128030  assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
128031  for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
128032  if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
128033  if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
128034  if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
128035  for(j=pLoop->nLTerm-1; j>=0; j--){
128036  pX = pLoop->aLTerm[j];
128037  if( pX==0 ) continue;
128038  if( pX==pTerm ) break;
128039  if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
128040  }
128041  if( j<0 ){
128042  if( pTerm->truthProb<=0 ){
128043  /* If a truth probability is specified using the likelihood() hints,
128044  ** then use the probability provided by the application. */
128045  pLoop->nOut += pTerm->truthProb;
128046  }else{
128047  /* In the absence of explicit truth probabilities, use heuristics to
128048  ** guess a reasonable truth probability. */
128049  pLoop->nOut--;
128050  if( pTerm->eOperator&(WO_EQ|WO_IS) ){
128051  Expr *pRight = pTerm->pExpr->pRight;
128052  testcase( pTerm->pExpr->op==TK_IS );
128053  if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
128054  k = 10;
128055  }else{
128056  k = 20;
128057  }
128058  if( iReduce<k ) iReduce = k;
128059  }
128060  }
128061  }
128062  }
128063  if( pLoop->nOut > nRow-iReduce ) pLoop->nOut = nRow - iReduce;
128064 }
128065 
128066 /*
128067 ** Adjust the cost C by the costMult facter T. This only occurs if
128068 ** compiled with -DSQLITE_ENABLE_COSTMULT
128069 */
128070 #ifdef SQLITE_ENABLE_COSTMULT
128071 # define ApplyCostMultiplier(C,T) C += T
128072 #else
128073 # define ApplyCostMultiplier(C,T)
128074 #endif
128075 
128076 /*
128077 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
128078 ** index pIndex. Try to match one more.
128079 **
128080 ** When this function is called, pBuilder->pNew->nOut contains the
128081 ** number of rows expected to be visited by filtering using the nEq
128082 ** terms only. If it is modified, this value is restored before this
128083 ** function returns.
128084 **
128085 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
128086 ** INTEGER PRIMARY KEY.
128087 */
128089  WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
128090  struct SrcList_item *pSrc, /* FROM clause term being analyzed */
128091  Index *pProbe, /* An index on pSrc */
128092  LogEst nInMul /* log(Number of iterations due to IN) */
128093 ){
128094  WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
128095  Parse *pParse = pWInfo->pParse; /* Parsing context */
128096  sqlite3 *db = pParse->db; /* Database connection malloc context */
128097  WhereLoop *pNew; /* Template WhereLoop under construction */
128098  WhereTerm *pTerm; /* A WhereTerm under consideration */
128099  int opMask; /* Valid operators for constraints */
128100  WhereScan scan; /* Iterator for WHERE terms */
128101  Bitmask saved_prereq; /* Original value of pNew->prereq */
128102  u16 saved_nLTerm; /* Original value of pNew->nLTerm */
128103  u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
128104  u16 saved_nSkip; /* Original value of pNew->nSkip */
128105  u32 saved_wsFlags; /* Original value of pNew->wsFlags */
128106  LogEst saved_nOut; /* Original value of pNew->nOut */
128107  int rc = SQLITE_OK; /* Return code */
128108  LogEst rSize; /* Number of rows in the table */
128109  LogEst rLogSize; /* Logarithm of table size */
128110  WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
128111 
128112  pNew = pBuilder->pNew;
128113  if( db->mallocFailed ) return SQLITE_NOMEM_BKPT;
128114 
128115  assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
128116  assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
128117  if( pNew->wsFlags & WHERE_BTM_LIMIT ){
128118  opMask = WO_LT|WO_LE;
128119  }else{
128121  }
128122  if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
128123 
128124  assert( pNew->u.btree.nEq<pProbe->nColumn );
128125 
128126  saved_nEq = pNew->u.btree.nEq;
128127  saved_nSkip = pNew->nSkip;
128128  saved_nLTerm = pNew->nLTerm;
128129  saved_wsFlags = pNew->wsFlags;
128130  saved_prereq = pNew->prereq;
128131  saved_nOut = pNew->nOut;
128132  pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, saved_nEq,
128133  opMask, pProbe);
128134  pNew->rSetup = 0;
128135  rSize = pProbe->aiRowLogEst[0];
128136  rLogSize = estLog(rSize);
128137  for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
128138  u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
128139  LogEst rCostIdx;
128140  LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
128141  int nIn = 0;
128142 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128143  int nRecValid = pBuilder->nRecValid;
128144 #endif
128145  if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
128146  && indexColumnNotNull(pProbe, saved_nEq)
128147  ){
128148  continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
128149  }
128150  if( pTerm->prereqRight & pNew->maskSelf ) continue;
128151 
128152  /* Do not allow the upper bound of a LIKE optimization range constraint
128153  ** to mix with a lower range bound from some other source */
128154  if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
128155 
128156  /* Do not allow IS constraints from the WHERE clause to be used by the
128157  ** right table of a LEFT JOIN. Only constraints in the ON clause are
128158  ** allowed */
128159  if( (pSrc->fg.jointype & JT_LEFT)!=0
128160  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
128161  && (eOp & (WO_IS|WO_ISNULL))!=0
128162  ){
128163  testcase( eOp & WO_IS );
128164  testcase( eOp & WO_ISNULL );
128165  continue;
128166  }
128167 
128168  pNew->wsFlags = saved_wsFlags;
128169  pNew->u.btree.nEq = saved_nEq;
128170  pNew->nLTerm = saved_nLTerm;
128171  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
128172  pNew->aLTerm[pNew->nLTerm++] = pTerm;
128173  pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
128174 
128175  assert( nInMul==0
128176  || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
128177  || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
128178  || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
128179  );
128180 
128181  if( eOp & WO_IN ){
128182  Expr *pExpr = pTerm->pExpr;
128183  pNew->wsFlags |= WHERE_COLUMN_IN;
128184  if( ExprHasProperty(pExpr, EP_xIsSelect) ){
128185  /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
128186  nIn = 46; assert( 46==sqlite3LogEst(25) );
128187  }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
128188  /* "x IN (value, value, ...)" */
128189  nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
128190  }
128191  assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
128192  ** changes "x IN (?)" into "x=?". */
128193 
128194  }else if( eOp & (WO_EQ|WO_IS) ){
128195  int iCol = pProbe->aiColumn[saved_nEq];
128196  pNew->wsFlags |= WHERE_COLUMN_EQ;
128197  assert( saved_nEq==pNew->u.btree.nEq );
128198  if( iCol==XN_ROWID
128199  || (iCol>0 && nInMul==0 && saved_nEq==pProbe->nKeyCol-1)
128200  ){
128201  if( iCol>=0 && pProbe->uniqNotNull==0 ){
128202  pNew->wsFlags |= WHERE_UNQ_WANTED;
128203  }else{
128204  pNew->wsFlags |= WHERE_ONEROW;
128205  }
128206  }
128207  }else if( eOp & WO_ISNULL ){
128208  pNew->wsFlags |= WHERE_COLUMN_NULL;
128209  }else if( eOp & (WO_GT|WO_GE) ){
128210  testcase( eOp & WO_GT );
128211  testcase( eOp & WO_GE );
128213  pBtm = pTerm;
128214  pTop = 0;
128215  if( pTerm->wtFlags & TERM_LIKEOPT ){
128216  /* Range contraints that come from the LIKE optimization are
128217  ** always used in pairs. */
128218  pTop = &pTerm[1];
128219  assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
128220  assert( pTop->wtFlags & TERM_LIKEOPT );
128221  assert( pTop->eOperator==WO_LT );
128222  if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
128223  pNew->aLTerm[pNew->nLTerm++] = pTop;
128224  pNew->wsFlags |= WHERE_TOP_LIMIT;
128225  }
128226  }else{
128227  assert( eOp & (WO_LT|WO_LE) );
128228  testcase( eOp & WO_LT );
128229  testcase( eOp & WO_LE );
128231  pTop = pTerm;
128232  pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
128233  pNew->aLTerm[pNew->nLTerm-2] : 0;
128234  }
128235 
128236  /* At this point pNew->nOut is set to the number of rows expected to
128237  ** be visited by the index scan before considering term pTerm, or the
128238  ** values of nIn and nInMul. In other words, assuming that all
128239  ** "x IN(...)" terms are replaced with "x = ?". This block updates
128240  ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
128241  assert( pNew->nOut==saved_nOut );
128242  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
128243  /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
128244  ** data, using some other estimate. */
128245  whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
128246  }else{
128247  int nEq = ++pNew->u.btree.nEq;
128248  assert( eOp & (WO_ISNULL|WO_EQ|WO_IN|WO_IS) );
128249 
128250  assert( pNew->nOut==saved_nOut );
128251  if( pTerm->truthProb<=0 && pProbe->aiColumn[saved_nEq]>=0 ){
128252  assert( (eOp & WO_IN) || nIn==0 );
128253  testcase( eOp & WO_IN );
128254  pNew->nOut += pTerm->truthProb;
128255  pNew->nOut -= nIn;
128256  }else{
128257 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128258  tRowcnt nOut = 0;
128259  if( nInMul==0
128260  && pProbe->nSample
128261  && pNew->u.btree.nEq<=pProbe->nSampleCol
128262  && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
128263  ){
128264  Expr *pExpr = pTerm->pExpr;
128265  if( (eOp & (WO_EQ|WO_ISNULL|WO_IS))!=0 ){
128266  testcase( eOp & WO_EQ );
128267  testcase( eOp & WO_IS );
128268  testcase( eOp & WO_ISNULL );
128269  rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
128270  }else{
128271  rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
128272  }
128273  if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
128274  if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
128275  if( nOut ){
128276  pNew->nOut = sqlite3LogEst(nOut);
128277  if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
128278  pNew->nOut -= nIn;
128279  }
128280  }
128281  if( nOut==0 )
128282 #endif
128283  {
128284  pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
128285  if( eOp & WO_ISNULL ){
128286  /* TUNING: If there is no likelihood() value, assume that a
128287  ** "col IS NULL" expression matches twice as many rows
128288  ** as (col=?). */
128289  pNew->nOut += 10;
128290  }
128291  }
128292  }
128293  }
128294 
128295  /* Set rCostIdx to the cost of visiting selected rows in index. Add
128296  ** it to pNew->rRun, which is currently set to the cost of the index
128297  ** seek only. Then, if this is a non-covering index, add the cost of
128298  ** visiting the rows in the main table. */
128299  rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
128300  pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
128301  if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
128302  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
128303  }
128304  ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
128305 
128306  nOutUnadjusted = pNew->nOut;
128307  pNew->rRun += nInMul + nIn;
128308  pNew->nOut += nInMul + nIn;
128309  whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
128310  rc = whereLoopInsert(pBuilder, pNew);
128311 
128312  if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
128313  pNew->nOut = saved_nOut;
128314  }else{
128315  pNew->nOut = nOutUnadjusted;
128316  }
128317 
128318  if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
128319  && pNew->u.btree.nEq<pProbe->nColumn
128320  ){
128321  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
128322  }
128323  pNew->nOut = saved_nOut;
128324 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128325  pBuilder->nRecValid = nRecValid;
128326 #endif
128327  }
128328  pNew->prereq = saved_prereq;
128329  pNew->u.btree.nEq = saved_nEq;
128330  pNew->nSkip = saved_nSkip;
128331  pNew->wsFlags = saved_wsFlags;
128332  pNew->nOut = saved_nOut;
128333  pNew->nLTerm = saved_nLTerm;
128334 
128335  /* Consider using a skip-scan if there are no WHERE clause constraints
128336  ** available for the left-most terms of the index, and if the average
128337  ** number of repeats in the left-most terms is at least 18.
128338  **
128339  ** The magic number 18 is selected on the basis that scanning 17 rows
128340  ** is almost always quicker than an index seek (even though if the index
128341  ** contains fewer than 2^17 rows we assume otherwise in other parts of
128342  ** the code). And, even if it is not, it should not be too much slower.
128343  ** On the other hand, the extra seeks could end up being significantly
128344  ** more expensive. */
128345  assert( 42==sqlite3LogEst(18) );
128346  if( saved_nEq==saved_nSkip
128347  && saved_nEq+1<pProbe->nKeyCol
128348  && pProbe->noSkipScan==0
128349  && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
128350  && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
128351  ){
128352  LogEst nIter;
128353  pNew->u.btree.nEq++;
128354  pNew->nSkip++;
128355  pNew->aLTerm[pNew->nLTerm++] = 0;
128356  pNew->wsFlags |= WHERE_SKIPSCAN;
128357  nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
128358  pNew->nOut -= nIter;
128359  /* TUNING: Because uncertainties in the estimates for skip-scan queries,
128360  ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
128361  nIter += 5;
128362  whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
128363  pNew->nOut = saved_nOut;
128364  pNew->u.btree.nEq = saved_nEq;
128365  pNew->nSkip = saved_nSkip;
128366  pNew->wsFlags = saved_wsFlags;
128367  }
128368 
128369  return rc;
128370 }
128371 
128372 /*
128373 ** Return True if it is possible that pIndex might be useful in
128374 ** implementing the ORDER BY clause in pBuilder.
128375 **
128376 ** Return False if pBuilder does not contain an ORDER BY clause or
128377 ** if there is no way for pIndex to be useful in implementing that
128378 ** ORDER BY clause.
128379 */
128381  WhereLoopBuilder *pBuilder,
128382  Index *pIndex,
128383  int iCursor
128384 ){
128385  ExprList *pOB;
128386  ExprList *aColExpr;
128387  int ii, jj;
128388 
128389  if( pIndex->bUnordered ) return 0;
128390  if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
128391  for(ii=0; ii<pOB->nExpr; ii++){
128392  Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
128393  if( pExpr->op==TK_COLUMN && pExpr->iTable==iCursor ){
128394  if( pExpr->iColumn<0 ) return 1;
128395  for(jj=0; jj<pIndex->nKeyCol; jj++){
128396  if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
128397  }
128398  }else if( (aColExpr = pIndex->aColExpr)!=0 ){
128399  for(jj=0; jj<pIndex->nKeyCol; jj++){
128400  if( pIndex->aiColumn[jj]!=XN_EXPR ) continue;
128401  if( sqlite3ExprCompare(pExpr,aColExpr->a[jj].pExpr,iCursor)==0 ){
128402  return 1;
128403  }
128404  }
128405  }
128406  }
128407  return 0;
128408 }
128409 
128410 /*
128411 ** Return a bitmask where 1s indicate that the corresponding column of
128412 ** the table is used by an index. Only the first 63 columns are considered.
128413 */
128414 static Bitmask columnsInIndex(Index *pIdx){
128415  Bitmask m = 0;
128416  int j;
128417  for(j=pIdx->nColumn-1; j>=0; j--){
128418  int x = pIdx->aiColumn[j];
128419  if( x>=0 ){
128420  testcase( x==BMS-1 );
128421  testcase( x==BMS-2 );
128422  if( x<BMS-1 ) m |= MASKBIT(x);
128423  }
128424  }
128425  return m;
128426 }
128427 
128428 /* Check to see if a partial index with pPartIndexWhere can be used
128429 ** in the current query. Return true if it can be and false if not.
128430 */
128431 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
128432  int i;
128433  WhereTerm *pTerm;
128434  while( pWhere->op==TK_AND ){
128435  if( !whereUsablePartialIndex(iTab,pWC,pWhere->pLeft) ) return 0;
128436  pWhere = pWhere->pRight;
128437  }
128438  for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
128439  Expr *pExpr = pTerm->pExpr;
128440  if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab)
128441  && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
128442  ){
128443  return 1;
128444  }
128445  }
128446  return 0;
128447 }
128448 
128449 /*
128450 ** Add all WhereLoop objects for a single table of the join where the table
128451 ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
128452 ** a b-tree table, not a virtual table.
128453 **
128454 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
128455 ** are calculated as follows:
128456 **
128457 ** For a full scan, assuming the table (or index) contains nRow rows:
128458 **
128459 ** cost = nRow * 3.0 // full-table scan
128460 ** cost = nRow * K // scan of covering index
128461 ** cost = nRow * (K+3.0) // scan of non-covering index
128462 **
128463 ** where K is a value between 1.1 and 3.0 set based on the relative
128464 ** estimated average size of the index and table records.
128465 **
128466 ** For an index scan, where nVisit is the number of index rows visited
128467 ** by the scan, and nSeek is the number of seek operations required on
128468 ** the index b-tree:
128469 **
128470 ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
128471 ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
128472 **
128473 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
128474 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
128475 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
128476 **
128477 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
128478 ** of uncertainty. For this reason, scoring is designed to pick plans that
128479 ** "do the least harm" if the estimates are inaccurate. For example, a
128480 ** log(nRow) factor is omitted from a non-covering index scan in order to
128481 ** bias the scoring in favor of using an index, since the worst-case
128482 ** performance of using an index is far better than the worst-case performance
128483 ** of a full table scan.
128484 */
128486  WhereLoopBuilder *pBuilder, /* WHERE clause information */
128487  Bitmask mPrereq /* Extra prerequesites for using this table */
128488 ){
128489  WhereInfo *pWInfo; /* WHERE analysis context */
128490  Index *pProbe; /* An index we are evaluating */
128491  Index sPk; /* A fake index object for the primary key */
128492  LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
128493  i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
128494  SrcList *pTabList; /* The FROM clause */
128495  struct SrcList_item *pSrc; /* The FROM clause btree term to add */
128496  WhereLoop *pNew; /* Template WhereLoop object */
128497  int rc = SQLITE_OK; /* Return code */
128498  int iSortIdx = 1; /* Index number */
128499  int b; /* A boolean value */
128500  LogEst rSize; /* number of rows in the table */
128501  LogEst rLogSize; /* Logarithm of the number of rows in the table */
128502  WhereClause *pWC; /* The parsed WHERE clause */
128503  Table *pTab; /* Table being queried */
128504 
128505  pNew = pBuilder->pNew;
128506  pWInfo = pBuilder->pWInfo;
128507  pTabList = pWInfo->pTabList;
128508  pSrc = pTabList->a + pNew->iTab;
128509  pTab = pSrc->pTab;
128510  pWC = pBuilder->pWC;
128511  assert( !IsVirtual(pSrc->pTab) );
128512 
128513  if( pSrc->pIBIndex ){
128514  /* An INDEXED BY clause specifies a particular index to use */
128515  pProbe = pSrc->pIBIndex;
128516  }else if( !HasRowid(pTab) ){
128517  pProbe = pTab->pIndex;
128518  }else{
128519  /* There is no INDEXED BY clause. Create a fake Index object in local
128520  ** variable sPk to represent the rowid primary key index. Make this
128521  ** fake index the first in a chain of Index objects with all of the real
128522  ** indices to follow */
128523  Index *pFirst; /* First of real indices on the table */
128524  memset(&sPk, 0, sizeof(Index));
128525  sPk.nKeyCol = 1;
128526  sPk.nColumn = 1;
128527  sPk.aiColumn = &aiColumnPk;
128528  sPk.aiRowLogEst = aiRowEstPk;
128529  sPk.onError = OE_Replace;
128530  sPk.pTable = pTab;
128531  sPk.szIdxRow = pTab->szTabRow;
128532  aiRowEstPk[0] = pTab->nRowLogEst;
128533  aiRowEstPk[1] = 0;
128534  pFirst = pSrc->pTab->pIndex;
128535  if( pSrc->fg.notIndexed==0 ){
128536  /* The real indices of the table are only considered if the
128537  ** NOT INDEXED qualifier is omitted from the FROM clause */
128538  sPk.pNext = pFirst;
128539  }
128540  pProbe = &sPk;
128541  }
128542  rSize = pTab->nRowLogEst;
128543  rLogSize = estLog(rSize);
128544 
128545 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
128546  /* Automatic indexes */
128547  if( !pBuilder->pOrSet /* Not part of an OR optimization */
128548  && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
128549  && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
128550  && pSrc->pIBIndex==0 /* Has no INDEXED BY clause */
128551  && !pSrc->fg.notIndexed /* Has no NOT INDEXED clause */
128552  && HasRowid(pTab) /* Not WITHOUT ROWID table. (FIXME: Why not?) */
128553  && !pSrc->fg.isCorrelated /* Not a correlated subquery */
128554  && !pSrc->fg.isRecursive /* Not a recursive common table expression. */
128555  ){
128556  /* Generate auto-index WhereLoops */
128557  WhereTerm *pTerm;
128558  WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
128559  for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
128560  if( pTerm->prereqRight & pNew->maskSelf ) continue;
128561  if( termCanDriveIndex(pTerm, pSrc, 0) ){
128562  pNew->u.btree.nEq = 1;
128563  pNew->nSkip = 0;
128564  pNew->u.btree.pIndex = 0;
128565  pNew->nLTerm = 1;
128566  pNew->aLTerm[0] = pTerm;
128567  /* TUNING: One-time cost for computing the automatic index is
128568  ** estimated to be X*N*log2(N) where N is the number of rows in
128569  ** the table being indexed and where X is 7 (LogEst=28) for normal
128570  ** tables or 1.375 (LogEst=4) for views and subqueries. The value
128571  ** of X is smaller for views and subqueries so that the query planner
128572  ** will be more aggressive about generating automatic indexes for
128573  ** those objects, since there is no opportunity to add schema
128574  ** indexes on subqueries and views. */
128575  pNew->rSetup = rLogSize + rSize + 4;
128576  if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
128577  pNew->rSetup += 24;
128578  }
128579  ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
128580  /* TUNING: Each index lookup yields 20 rows in the table. This
128581  ** is more than the usual guess of 10 rows, since we have no way
128582  ** of knowing how selective the index will ultimately be. It would
128583  ** not be unreasonable to make this value much larger. */
128584  pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
128585  pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
128586  pNew->wsFlags = WHERE_AUTO_INDEX;
128587  pNew->prereq = mPrereq | pTerm->prereqRight;
128588  rc = whereLoopInsert(pBuilder, pNew);
128589  }
128590  }
128591  }
128592 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
128593 
128594  /* Loop over all indices
128595  */
128596  for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
128597  if( pProbe->pPartIdxWhere!=0
128598  && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
128599  testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
128600  continue; /* Partial index inappropriate for this query */
128601  }
128602  rSize = pProbe->aiRowLogEst[0];
128603  pNew->u.btree.nEq = 0;
128604  pNew->nSkip = 0;
128605  pNew->nLTerm = 0;
128606  pNew->iSortIdx = 0;
128607  pNew->rSetup = 0;
128608  pNew->prereq = mPrereq;
128609  pNew->nOut = rSize;
128610  pNew->u.btree.pIndex = pProbe;
128611  b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
128612  /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
128613  assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
128614  if( pProbe->tnum<=0 ){
128615  /* Integer primary key index */
128616  pNew->wsFlags = WHERE_IPK;
128617 
128618  /* Full table scan */
128619  pNew->iSortIdx = b ? iSortIdx : 0;
128620  /* TUNING: Cost of full table scan is (N*3.0). */
128621  pNew->rRun = rSize + 16;
128622  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
128623  whereLoopOutputAdjust(pWC, pNew, rSize);
128624  rc = whereLoopInsert(pBuilder, pNew);
128625  pNew->nOut = rSize;
128626  if( rc ) break;
128627  }else{
128628  Bitmask m;
128629  if( pProbe->isCovering ){
128631  m = 0;
128632  }else{
128633  m = pSrc->colUsed & ~columnsInIndex(pProbe);
128634  pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
128635  }
128636 
128637  /* Full scan via index */
128638  if( b
128639  || !HasRowid(pTab)
128640  || ( m==0
128641  && pProbe->bUnordered==0
128642  && (pProbe->szIdxRow<pTab->szTabRow)
128643  && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
128644  && sqlite3GlobalConfig.bUseCis
128646  )
128647  ){
128648  pNew->iSortIdx = b ? iSortIdx : 0;
128649 
128650  /* The cost of visiting the index rows is N*K, where K is
128651  ** between 1.1 and 3.0, depending on the relative sizes of the
128652  ** index and table rows. If this is a non-covering index scan,
128653  ** also add the cost of visiting table rows (N*3.0). */
128654  pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
128655  if( m!=0 ){
128656  pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
128657  }
128658  ApplyCostMultiplier(pNew->rRun, pTab->costMult);
128659  whereLoopOutputAdjust(pWC, pNew, rSize);
128660  rc = whereLoopInsert(pBuilder, pNew);
128661  pNew->nOut = rSize;
128662  if( rc ) break;
128663  }
128664  }
128665 
128666  rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
128667 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
128668  sqlite3Stat4ProbeFree(pBuilder->pRec);
128669  pBuilder->nRecValid = 0;
128670  pBuilder->pRec = 0;
128671 #endif
128672 
128673  /* If there was an INDEXED BY clause, then only that one index is
128674  ** considered. */
128675  if( pSrc->pIBIndex ) break;
128676  }
128677  return rc;
128678 }
128679 
128680 #ifndef SQLITE_OMIT_VIRTUALTABLE
128681 
128682 /*
128683 ** Argument pIdxInfo is already populated with all constraints that may
128684 ** be used by the virtual table identified by pBuilder->pNew->iTab. This
128685 ** function marks a subset of those constraints usable, invokes the
128686 ** xBestIndex method and adds the returned plan to pBuilder.
128687 **
128688 ** A constraint is marked usable if:
128689 **
128690 ** * Argument mUsable indicates that its prerequisites are available, and
128691 **
128692 ** * It is not one of the operators specified in the mExclude mask passed
128693 ** as the fourth argument (which in practice is either WO_IN or 0).
128694 **
128695 ** Argument mPrereq is a mask of tables that must be scanned before the
128696 ** virtual table in question. These are added to the plans prerequisites
128697 ** before it is added to pBuilder.
128698 **
128699 ** Output parameter *pbIn is set to true if the plan added to pBuilder
128700 ** uses one or more WO_IN terms, or false otherwise.
128701 */
128703  WhereLoopBuilder *pBuilder,
128704  Bitmask mPrereq, /* Mask of tables that must be used. */
128705  Bitmask mUsable, /* Mask of usable tables */
128706  u16 mExclude, /* Exclude terms using these operators */
128707  sqlite3_index_info *pIdxInfo, /* Populated object for xBestIndex */
128708  int *pbIn /* OUT: True if plan uses an IN(...) op */
128709 ){
128710  WhereClause *pWC = pBuilder->pWC;
128711  struct sqlite3_index_constraint *pIdxCons;
128712  struct sqlite3_index_constraint_usage *pUsage = pIdxInfo->aConstraintUsage;
128713  int i;
128714  int mxTerm;
128715  int rc = SQLITE_OK;
128716  WhereLoop *pNew = pBuilder->pNew;
128717  Parse *pParse = pBuilder->pWInfo->pParse;
128718  struct SrcList_item *pSrc = &pBuilder->pWInfo->pTabList->a[pNew->iTab];
128719  int nConstraint = pIdxInfo->nConstraint;
128720 
128721  assert( (mUsable & mPrereq)==mPrereq );
128722  *pbIn = 0;
128723  pNew->prereq = mPrereq;
128724 
128725  /* Set the usable flag on the subset of constraints identified by
128726  ** arguments mUsable and mExclude. */
128727  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
128728  for(i=0; i<nConstraint; i++, pIdxCons++){
128729  WhereTerm *pTerm = &pWC->a[pIdxCons->iTermOffset];
128730  pIdxCons->usable = 0;
128731  if( (pTerm->prereqRight & mUsable)==pTerm->prereqRight
128732  && (pTerm->eOperator & mExclude)==0
128733  ){
128734  pIdxCons->usable = 1;
128735  }
128736  }
128737 
128738  /* Initialize the output fields of the sqlite3_index_info structure */
128739  memset(pUsage, 0, sizeof(pUsage[0])*nConstraint);
128740  assert( pIdxInfo->needToFreeIdxStr==0 );
128741  pIdxInfo->idxStr = 0;
128742  pIdxInfo->idxNum = 0;
128743  pIdxInfo->orderByConsumed = 0;
128744  pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
128745  pIdxInfo->estimatedRows = 25;
128746  pIdxInfo->idxFlags = 0;
128747  pIdxInfo->colUsed = (sqlite3_int64)pSrc->colUsed;
128748 
128749  /* Invoke the virtual table xBestIndex() method */
128750  rc = vtabBestIndex(pParse, pSrc->pTab, pIdxInfo);
128751  if( rc ) return rc;
128752 
128753  mxTerm = -1;
128754  assert( pNew->nLSlot>=nConstraint );
128755  for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
128756  pNew->u.vtab.omitMask = 0;
128757  pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
128758  for(i=0; i<nConstraint; i++, pIdxCons++){
128759  int iTerm;
128760  if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
128761  WhereTerm *pTerm;
128762  int j = pIdxCons->iTermOffset;
128763  if( iTerm>=nConstraint
128764  || j<0
128765  || j>=pWC->nTerm
128766  || pNew->aLTerm[iTerm]!=0
128767  || pIdxCons->usable==0
128768  ){
128769  rc = SQLITE_ERROR;
128770  sqlite3ErrorMsg(pParse,"%s.xBestIndex malfunction",pSrc->pTab->zName);
128771  return rc;
128772  }
128773  testcase( iTerm==nConstraint-1 );
128774  testcase( j==0 );
128775  testcase( j==pWC->nTerm-1 );
128776  pTerm = &pWC->a[j];
128777  pNew->prereq |= pTerm->prereqRight;
128778  assert( iTerm<pNew->nLSlot );
128779  pNew->aLTerm[iTerm] = pTerm;
128780  if( iTerm>mxTerm ) mxTerm = iTerm;
128781  testcase( iTerm==15 );
128782  testcase( iTerm==16 );
128783  if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
128784  if( (pTerm->eOperator & WO_IN)!=0 ){
128785  /* A virtual table that is constrained by an IN clause may not
128786  ** consume the ORDER BY clause because (1) the order of IN terms
128787  ** is not necessarily related to the order of output terms and
128788  ** (2) Multiple outputs from a single IN value will not merge
128789  ** together. */
128790  pIdxInfo->orderByConsumed = 0;
128791  pIdxInfo->idxFlags &= ~SQLITE_INDEX_SCAN_UNIQUE;
128792  *pbIn = 1; assert( (mExclude & WO_IN)==0 );
128793  }
128794  }
128795  }
128796 
128797  pNew->nLTerm = mxTerm+1;
128798  assert( pNew->nLTerm<=pNew->nLSlot );
128799  pNew->u.vtab.idxNum = pIdxInfo->idxNum;
128800  pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
128801  pIdxInfo->needToFreeIdxStr = 0;
128802  pNew->u.vtab.idxStr = pIdxInfo->idxStr;
128803  pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
128804  pIdxInfo->nOrderBy : 0);
128805  pNew->rSetup = 0;
128806  pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
128807  pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
128808 
128809  /* Set the WHERE_ONEROW flag if the xBestIndex() method indicated
128810  ** that the scan will visit at most one row. Clear it otherwise. */
128811  if( pIdxInfo->idxFlags & SQLITE_INDEX_SCAN_UNIQUE ){
128812  pNew->wsFlags |= WHERE_ONEROW;
128813  }else{
128814  pNew->wsFlags &= ~WHERE_ONEROW;
128815  }
128816  rc = whereLoopInsert(pBuilder, pNew);
128817  if( pNew->u.vtab.needFree ){
128818  sqlite3_free(pNew->u.vtab.idxStr);
128819  pNew->u.vtab.needFree = 0;
128820  }
128821  WHERETRACE(0xffff, (" bIn=%d prereqIn=%04llx prereqOut=%04llx\n",
128822  *pbIn, (sqlite3_uint64)mPrereq,
128823  (sqlite3_uint64)(pNew->prereq & ~mPrereq)));
128824 
128825  return rc;
128826 }
128827 
128828 
128829 /*
128830 ** Add all WhereLoop objects for a table of the join identified by
128831 ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
128832 **
128833 ** If there are no LEFT or CROSS JOIN joins in the query, both mPrereq and
128834 ** mUnusable are set to 0. Otherwise, mPrereq is a mask of all FROM clause
128835 ** entries that occur before the virtual table in the FROM clause and are
128836 ** separated from it by at least one LEFT or CROSS JOIN. Similarly, the
128837 ** mUnusable mask contains all FROM clause entries that occur after the
128838 ** virtual table and are separated from it by at least one LEFT or
128839 ** CROSS JOIN.
128840 **
128841 ** For example, if the query were:
128842 **
128843 ** ... FROM t1, t2 LEFT JOIN t3, t4, vt CROSS JOIN t5, t6;
128844 **
128845 ** then mPrereq corresponds to (t1, t2) and mUnusable to (t5, t6).
128846 **
128847 ** All the tables in mPrereq must be scanned before the current virtual
128848 ** table. So any terms for which all prerequisites are satisfied by
128849 ** mPrereq may be specified as "usable" in all calls to xBestIndex.
128850 ** Conversely, all tables in mUnusable must be scanned after the current
128851 ** virtual table, so any terms for which the prerequisites overlap with
128852 ** mUnusable should always be configured as "not-usable" for xBestIndex.
128853 */
128855  WhereLoopBuilder *pBuilder, /* WHERE clause information */
128856  Bitmask mPrereq, /* Tables that must be scanned before this one */
128857  Bitmask mUnusable /* Tables that must be scanned after this one */
128858 ){
128859  int rc = SQLITE_OK; /* Return code */
128860  WhereInfo *pWInfo; /* WHERE analysis context */
128861  Parse *pParse; /* The parsing context */
128862  WhereClause *pWC; /* The WHERE clause */
128863  struct SrcList_item *pSrc; /* The FROM clause term to search */
128864  sqlite3_index_info *p; /* Object to pass to xBestIndex() */
128865  int nConstraint; /* Number of constraints in p */
128866  int bIn; /* True if plan uses IN(...) operator */
128867  WhereLoop *pNew;
128868  Bitmask mBest; /* Tables used by best possible plan */
128869 
128870  assert( (mPrereq & mUnusable)==0 );
128871  pWInfo = pBuilder->pWInfo;
128872  pParse = pWInfo->pParse;
128873  pWC = pBuilder->pWC;
128874  pNew = pBuilder->pNew;
128875  pSrc = &pWInfo->pTabList->a[pNew->iTab];
128876  assert( IsVirtual(pSrc->pTab) );
128877  p = allocateIndexInfo(pParse, pWC, mUnusable, pSrc, pBuilder->pOrderBy);
128878  if( p==0 ) return SQLITE_NOMEM_BKPT;
128879  pNew->rSetup = 0;
128880  pNew->wsFlags = WHERE_VIRTUALTABLE;
128881  pNew->nLTerm = 0;
128882  pNew->u.vtab.needFree = 0;
128883  nConstraint = p->nConstraint;
128884  if( whereLoopResize(pParse->db, pNew, nConstraint) ){
128885  sqlite3DbFree(pParse->db, p);
128886  return SQLITE_NOMEM_BKPT;
128887  }
128888 
128889  /* First call xBestIndex() with all constraints usable. */
128890  WHERETRACE(0x40, (" VirtualOne: all usable\n"));
128891  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, 0, p, &bIn);
128892 
128893  /* If the call to xBestIndex() with all terms enabled produced a plan
128894  ** that does not require any source tables (IOW: a plan with mBest==0),
128895  ** then there is no point in making any further calls to xBestIndex()
128896  ** since they will all return the same result (if the xBestIndex()
128897  ** implementation is sane). */
128898  if( rc==SQLITE_OK && (mBest = (pNew->prereq & ~mPrereq))!=0 ){
128899  int seenZero = 0; /* True if a plan with no prereqs seen */
128900  int seenZeroNoIN = 0; /* Plan with no prereqs and no IN(...) seen */
128901  Bitmask mPrev = 0;
128902  Bitmask mBestNoIn = 0;
128903 
128904  /* If the plan produced by the earlier call uses an IN(...) term, call
128905  ** xBestIndex again, this time with IN(...) terms disabled. */
128906  if( bIn ){
128907  WHERETRACE(0x40, (" VirtualOne: all usable w/o IN\n"));
128908  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, ALLBITS, WO_IN, p, &bIn);
128909  assert( bIn==0 );
128910  mBestNoIn = pNew->prereq & ~mPrereq;
128911  if( mBestNoIn==0 ){
128912  seenZero = 1;
128913  seenZeroNoIN = 1;
128914  }
128915  }
128916 
128917  /* Call xBestIndex once for each distinct value of (prereqRight & ~mPrereq)
128918  ** in the set of terms that apply to the current virtual table. */
128919  while( rc==SQLITE_OK ){
128920  int i;
128921  Bitmask mNext = ALLBITS;
128922  assert( mNext>0 );
128923  for(i=0; i<nConstraint; i++){
128924  Bitmask mThis = (
128925  pWC->a[p->aConstraint[i].iTermOffset].prereqRight & ~mPrereq
128926  );
128927  if( mThis>mPrev && mThis<mNext ) mNext = mThis;
128928  }
128929  mPrev = mNext;
128930  if( mNext==ALLBITS ) break;
128931  if( mNext==mBest || mNext==mBestNoIn ) continue;
128932  WHERETRACE(0x40, (" VirtualOne: mPrev=%04llx mNext=%04llx\n",
128933  (sqlite3_uint64)mPrev, (sqlite3_uint64)mNext));
128934  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mNext|mPrereq, 0, p, &bIn);
128935  if( pNew->prereq==mPrereq ){
128936  seenZero = 1;
128937  if( bIn==0 ) seenZeroNoIN = 1;
128938  }
128939  }
128940 
128941  /* If the calls to xBestIndex() in the above loop did not find a plan
128942  ** that requires no source tables at all (i.e. one guaranteed to be
128943  ** usable), make a call here with all source tables disabled */
128944  if( rc==SQLITE_OK && seenZero==0 ){
128945  WHERETRACE(0x40, (" VirtualOne: all disabled\n"));
128946  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, 0, p, &bIn);
128947  if( bIn==0 ) seenZeroNoIN = 1;
128948  }
128949 
128950  /* If the calls to xBestIndex() have so far failed to find a plan
128951  ** that requires no source tables at all and does not use an IN(...)
128952  ** operator, make a final call to obtain one here. */
128953  if( rc==SQLITE_OK && seenZeroNoIN==0 ){
128954  WHERETRACE(0x40, (" VirtualOne: all disabled and w/o IN\n"));
128955  rc = whereLoopAddVirtualOne(pBuilder, mPrereq, mPrereq, WO_IN, p, &bIn);
128956  }
128957  }
128958 
128959  if( p->needToFreeIdxStr ) sqlite3_free(p->idxStr);
128960  sqlite3DbFree(pParse->db, p);
128961  return rc;
128962 }
128963 #endif /* SQLITE_OMIT_VIRTUALTABLE */
128964 
128965 /*
128966 ** Add WhereLoop entries to handle OR terms. This works for either
128967 ** btrees or virtual tables.
128968 */
128969 static int whereLoopAddOr(
128970  WhereLoopBuilder *pBuilder,
128971  Bitmask mPrereq,
128972  Bitmask mUnusable
128973 ){
128974  WhereInfo *pWInfo = pBuilder->pWInfo;
128975  WhereClause *pWC;
128976  WhereLoop *pNew;
128977  WhereTerm *pTerm, *pWCEnd;
128978  int rc = SQLITE_OK;
128979  int iCur;
128980  WhereClause tempWC;
128981  WhereLoopBuilder sSubBuild;
128982  WhereOrSet sSum, sCur;
128983  struct SrcList_item *pItem;
128984 
128985  pWC = pBuilder->pWC;
128986  pWCEnd = pWC->a + pWC->nTerm;
128987  pNew = pBuilder->pNew;
128988  memset(&sSum, 0, sizeof(sSum));
128989  pItem = pWInfo->pTabList->a + pNew->iTab;
128990  iCur = pItem->iCursor;
128991 
128992  for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
128993  if( (pTerm->eOperator & WO_OR)!=0
128994  && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
128995  ){
128996  WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
128997  WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
128998  WhereTerm *pOrTerm;
128999  int once = 1;
129000  int i, j;
129001 
129002  sSubBuild = *pBuilder;
129003  sSubBuild.pOrderBy = 0;
129004  sSubBuild.pOrSet = &sCur;
129005 
129006  WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
129007  for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
129008  if( (pOrTerm->eOperator & WO_AND)!=0 ){
129009  sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
129010  }else if( pOrTerm->leftCursor==iCur ){
129011  tempWC.pWInfo = pWC->pWInfo;
129012  tempWC.pOuter = pWC;
129013  tempWC.op = TK_AND;
129014  tempWC.nTerm = 1;
129015  tempWC.a = pOrTerm;
129016  sSubBuild.pWC = &tempWC;
129017  }else{
129018  continue;
129019  }
129020  sCur.n = 0;
129021 #ifdef WHERETRACE_ENABLED
129022  WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
129023  (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
129024  if( sqlite3WhereTrace & 0x400 ){
129025  for(i=0; i<sSubBuild.pWC->nTerm; i++){
129026  whereTermPrint(&sSubBuild.pWC->a[i], i);
129027  }
129028  }
129029 #endif
129030 #ifndef SQLITE_OMIT_VIRTUALTABLE
129031  if( IsVirtual(pItem->pTab) ){
129032  rc = whereLoopAddVirtual(&sSubBuild, mPrereq, mUnusable);
129033  }else
129034 #endif
129035  {
129036  rc = whereLoopAddBtree(&sSubBuild, mPrereq);
129037  }
129038  if( rc==SQLITE_OK ){
129039  rc = whereLoopAddOr(&sSubBuild, mPrereq, mUnusable);
129040  }
129041  assert( rc==SQLITE_OK || sCur.n==0 );
129042  if( sCur.n==0 ){
129043  sSum.n = 0;
129044  break;
129045  }else if( once ){
129046  whereOrMove(&sSum, &sCur);
129047  once = 0;
129048  }else{
129049  WhereOrSet sPrev;
129050  whereOrMove(&sPrev, &sSum);
129051  sSum.n = 0;
129052  for(i=0; i<sPrev.n; i++){
129053  for(j=0; j<sCur.n; j++){
129054  whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
129055  sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
129056  sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
129057  }
129058  }
129059  }
129060  }
129061  pNew->nLTerm = 1;
129062  pNew->aLTerm[0] = pTerm;
129063  pNew->wsFlags = WHERE_MULTI_OR;
129064  pNew->rSetup = 0;
129065  pNew->iSortIdx = 0;
129066  memset(&pNew->u, 0, sizeof(pNew->u));
129067  for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
129068  /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
129069  ** of all sub-scans required by the OR-scan. However, due to rounding
129070  ** errors, it may be that the cost of the OR-scan is equal to its
129071  ** most expensive sub-scan. Add the smallest possible penalty
129072  ** (equivalent to multiplying the cost by 1.07) to ensure that
129073  ** this does not happen. Otherwise, for WHERE clauses such as the
129074  ** following where there is an index on "y":
129075  **
129076  ** WHERE likelihood(x=?, 0.99) OR y=?
129077  **
129078  ** the planner may elect to "OR" together a full-table scan and an
129079  ** index lookup. And other similarly odd results. */
129080  pNew->rRun = sSum.a[i].rRun + 1;
129081  pNew->nOut = sSum.a[i].nOut;
129082  pNew->prereq = sSum.a[i].prereq;
129083  rc = whereLoopInsert(pBuilder, pNew);
129084  }
129085  WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
129086  }
129087  }
129088  return rc;
129089 }
129090 
129091 /*
129092 ** Add all WhereLoop objects for all tables
129093 */
129094 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
129095  WhereInfo *pWInfo = pBuilder->pWInfo;
129096  Bitmask mPrereq = 0;
129097  Bitmask mPrior = 0;
129098  int iTab;
129099  SrcList *pTabList = pWInfo->pTabList;
129100  struct SrcList_item *pItem;
129101  struct SrcList_item *pEnd = &pTabList->a[pWInfo->nLevel];
129102  sqlite3 *db = pWInfo->pParse->db;
129103  int rc = SQLITE_OK;
129104  WhereLoop *pNew;
129105  u8 priorJointype = 0;
129106 
129107  /* Loop over the tables in the join, from left to right */
129108  pNew = pBuilder->pNew;
129109  whereLoopInit(pNew);
129110  for(iTab=0, pItem=pTabList->a; pItem<pEnd; iTab++, pItem++){
129111  Bitmask mUnusable = 0;
129112  pNew->iTab = iTab;
129113  pNew->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, pItem->iCursor);
129114  if( ((pItem->fg.jointype|priorJointype) & (JT_LEFT|JT_CROSS))!=0 ){
129115  /* This condition is true when pItem is the FROM clause term on the
129116  ** right-hand-side of a LEFT or CROSS JOIN. */
129117  mPrereq = mPrior;
129118  }
129119  priorJointype = pItem->fg.jointype;
129120  if( IsVirtual(pItem->pTab) ){
129121  struct SrcList_item *p;
129122  for(p=&pItem[1]; p<pEnd; p++){
129123  if( mUnusable || (p->fg.jointype & (JT_LEFT|JT_CROSS)) ){
129124  mUnusable |= sqlite3WhereGetMask(&pWInfo->sMaskSet, p->iCursor);
129125  }
129126  }
129127  rc = whereLoopAddVirtual(pBuilder, mPrereq, mUnusable);
129128  }else{
129129  rc = whereLoopAddBtree(pBuilder, mPrereq);
129130  }
129131  if( rc==SQLITE_OK ){
129132  rc = whereLoopAddOr(pBuilder, mPrereq, mUnusable);
129133  }
129134  mPrior |= pNew->maskSelf;
129135  if( rc || db->mallocFailed ) break;
129136  }
129137 
129138  whereLoopClear(db, pNew);
129139  return rc;
129140 }
129141 
129142 /*
129143 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
129144 ** parameters) to see if it outputs rows in the requested ORDER BY
129145 ** (or GROUP BY) without requiring a separate sort operation. Return N:
129146 **
129147 ** N>0: N terms of the ORDER BY clause are satisfied
129148 ** N==0: No terms of the ORDER BY clause are satisfied
129149 ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
129150 **
129151 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
129152 ** strict. With GROUP BY and DISTINCT the only requirement is that
129153 ** equivalent rows appear immediately adjacent to one another. GROUP BY
129154 ** and DISTINCT do not require rows to appear in any particular order as long
129155 ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
129156 ** the pOrderBy terms can be matched in any order. With ORDER BY, the
129157 ** pOrderBy terms must be matched in strict left-to-right order.
129158 */
129160  WhereInfo *pWInfo, /* The WHERE clause */
129161  ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
129162  WherePath *pPath, /* The WherePath to check */
129163  u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
129164  u16 nLoop, /* Number of entries in pPath->aLoop[] */
129165  WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
129166  Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
129167 ){
129168  u8 revSet; /* True if rev is known */
129169  u8 rev; /* Composite sort order */
129170  u8 revIdx; /* Index sort order */
129171  u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
129172  u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
129173  u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
129174  u16 nKeyCol; /* Number of key columns in pIndex */
129175  u16 nColumn; /* Total number of ordered columns in the index */
129176  u16 nOrderBy; /* Number terms in the ORDER BY clause */
129177  int iLoop; /* Index of WhereLoop in pPath being processed */
129178  int i, j; /* Loop counters */
129179  int iCur; /* Cursor number for current WhereLoop */
129180  int iColumn; /* A column number within table iCur */
129181  WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
129182  WhereTerm *pTerm; /* A single term of the WHERE clause */
129183  Expr *pOBExpr; /* An expression from the ORDER BY clause */
129184  CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
129185  Index *pIndex; /* The index associated with pLoop */
129186  sqlite3 *db = pWInfo->pParse->db; /* Database connection */
129187  Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
129188  Bitmask obDone; /* Mask of all ORDER BY terms */
129189  Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
129190  Bitmask ready; /* Mask of inner loops */
129191 
129192  /*
129193  ** We say the WhereLoop is "one-row" if it generates no more than one
129194  ** row of output. A WhereLoop is one-row if all of the following are true:
129195  ** (a) All index columns match with WHERE_COLUMN_EQ.
129196  ** (b) The index is unique
129197  ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
129198  ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
129199  **
129200  ** We say the WhereLoop is "order-distinct" if the set of columns from
129201  ** that WhereLoop that are in the ORDER BY clause are different for every
129202  ** row of the WhereLoop. Every one-row WhereLoop is automatically
129203  ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
129204  ** is not order-distinct. To be order-distinct is not quite the same as being
129205  ** UNIQUE since a UNIQUE column or index can have multiple rows that
129206  ** are NULL and NULL values are equivalent for the purpose of order-distinct.
129207  ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
129208  **
129209  ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
129210  ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
129211  ** automatically order-distinct.
129212  */
129213 
129214  assert( pOrderBy!=0 );
129215  if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
129216 
129217  nOrderBy = pOrderBy->nExpr;
129218  testcase( nOrderBy==BMS-1 );
129219  if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
129220  isOrderDistinct = 1;
129221  obDone = MASKBIT(nOrderBy)-1;
129222  orderDistinctMask = 0;
129223  ready = 0;
129224  for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
129225  if( iLoop>0 ) ready |= pLoop->maskSelf;
129226  pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
129227  if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
129228  if( pLoop->u.vtab.isOrdered ) obSat = obDone;
129229  break;
129230  }
129231  iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
129232 
129233  /* Mark off any ORDER BY term X that is a column in the table of
129234  ** the current loop for which there is term in the WHERE
129235  ** clause of the form X IS NULL or X=? that reference only outer
129236  ** loops.
129237  */
129238  for(i=0; i<nOrderBy; i++){
129239  if( MASKBIT(i) & obSat ) continue;
129240  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
129241  if( pOBExpr->op!=TK_COLUMN ) continue;
129242  if( pOBExpr->iTable!=iCur ) continue;
129243  pTerm = sqlite3WhereFindTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
129244  ~ready, WO_EQ|WO_ISNULL|WO_IS, 0);
129245  if( pTerm==0 ) continue;
129246  if( (pTerm->eOperator&(WO_EQ|WO_IS))!=0 && pOBExpr->iColumn>=0 ){
129247  const char *z1, *z2;
129248  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
129249  if( !pColl ) pColl = db->pDfltColl;
129250  z1 = pColl->zName;
129251  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
129252  if( !pColl ) pColl = db->pDfltColl;
129253  z2 = pColl->zName;
129254  if( sqlite3StrICmp(z1, z2)!=0 ) continue;
129255  testcase( pTerm->pExpr->op==TK_IS );
129256  }
129257  obSat |= MASKBIT(i);
129258  }
129259 
129260  if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
129261  if( pLoop->wsFlags & WHERE_IPK ){
129262  pIndex = 0;
129263  nKeyCol = 0;
129264  nColumn = 1;
129265  }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
129266  return 0;
129267  }else{
129268  nKeyCol = pIndex->nKeyCol;
129269  nColumn = pIndex->nColumn;
129270  assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
129271  assert( pIndex->aiColumn[nColumn-1]==XN_ROWID
129272  || !HasRowid(pIndex->pTable));
129273  isOrderDistinct = IsUniqueIndex(pIndex);
129274  }
129275 
129276  /* Loop through all columns of the index and deal with the ones
129277  ** that are not constrained by == or IN.
129278  */
129279  rev = revSet = 0;
129280  distinctColumns = 0;
129281  for(j=0; j<nColumn; j++){
129282  u8 bOnce; /* True to run the ORDER BY search loop */
129283 
129284  /* Skip over == and IS NULL terms */
129285  if( j<pLoop->u.btree.nEq
129286  && pLoop->nSkip==0
129287  && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL|WO_IS))!=0
129288  ){
129289  if( i & WO_ISNULL ){
129290  testcase( isOrderDistinct );
129291  isOrderDistinct = 0;
129292  }
129293  continue;
129294  }
129295 
129296  /* Get the column number in the table (iColumn) and sort order
129297  ** (revIdx) for the j-th column of the index.
129298  */
129299  if( pIndex ){
129300  iColumn = pIndex->aiColumn[j];
129301  revIdx = pIndex->aSortOrder[j];
129302  if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
129303  }else{
129304  iColumn = XN_ROWID;
129305  revIdx = 0;
129306  }
129307 
129308  /* An unconstrained column that might be NULL means that this
129309  ** WhereLoop is not well-ordered
129310  */
129311  if( isOrderDistinct
129312  && iColumn>=0
129313  && j>=pLoop->u.btree.nEq
129314  && pIndex->pTable->aCol[iColumn].notNull==0
129315  ){
129316  isOrderDistinct = 0;
129317  }
129318 
129319  /* Find the ORDER BY term that corresponds to the j-th column
129320  ** of the index and mark that ORDER BY term off
129321  */
129322  bOnce = 1;
129323  isMatch = 0;
129324  for(i=0; bOnce && i<nOrderBy; i++){
129325  if( MASKBIT(i) & obSat ) continue;
129326  pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
129327  testcase( wctrlFlags & WHERE_GROUPBY );
129328  testcase( wctrlFlags & WHERE_DISTINCTBY );
129329  if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
129330  if( iColumn>=(-1) ){
129331  if( pOBExpr->op!=TK_COLUMN ) continue;
129332  if( pOBExpr->iTable!=iCur ) continue;
129333  if( pOBExpr->iColumn!=iColumn ) continue;
129334  }else{
129335  if( sqlite3ExprCompare(pOBExpr,pIndex->aColExpr->a[j].pExpr,iCur) ){
129336  continue;
129337  }
129338  }
129339  if( iColumn>=0 ){
129340  pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
129341  if( !pColl ) pColl = db->pDfltColl;
129342  if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
129343  }
129344  isMatch = 1;
129345  break;
129346  }
129347  if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
129348  /* Make sure the sort order is compatible in an ORDER BY clause.
129349  ** Sort order is irrelevant for a GROUP BY clause. */
129350  if( revSet ){
129351  if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
129352  }else{
129353  rev = revIdx ^ pOrderBy->a[i].sortOrder;
129354  if( rev ) *pRevMask |= MASKBIT(iLoop);
129355  revSet = 1;
129356  }
129357  }
129358  if( isMatch ){
129359  if( iColumn<0 ){
129360  testcase( distinctColumns==0 );
129361  distinctColumns = 1;
129362  }
129363  obSat |= MASKBIT(i);
129364  }else{
129365  /* No match found */
129366  if( j==0 || j<nKeyCol ){
129367  testcase( isOrderDistinct!=0 );
129368  isOrderDistinct = 0;
129369  }
129370  break;
129371  }
129372  } /* end Loop over all index columns */
129373  if( distinctColumns ){
129374  testcase( isOrderDistinct==0 );
129375  isOrderDistinct = 1;
129376  }
129377  } /* end-if not one-row */
129378 
129379  /* Mark off any other ORDER BY terms that reference pLoop */
129380  if( isOrderDistinct ){
129381  orderDistinctMask |= pLoop->maskSelf;
129382  for(i=0; i<nOrderBy; i++){
129383  Expr *p;
129384  Bitmask mTerm;
129385  if( MASKBIT(i) & obSat ) continue;
129386  p = pOrderBy->a[i].pExpr;
129387  mTerm = sqlite3WhereExprUsage(&pWInfo->sMaskSet,p);
129388  if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
129389  if( (mTerm&~orderDistinctMask)==0 ){
129390  obSat |= MASKBIT(i);
129391  }
129392  }
129393  }
129394  } /* End the loop over all WhereLoops from outer-most down to inner-most */
129395  if( obSat==obDone ) return (i8)nOrderBy;
129396  if( !isOrderDistinct ){
129397  for(i=nOrderBy-1; i>0; i--){
129398  Bitmask m = MASKBIT(i) - 1;
129399  if( (obSat&m)==m ) return i;
129400  }
129401  return 0;
129402  }
129403  return -1;
129404 }
129405 
129406 
129407 /*
129408 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
129409 ** the planner assumes that the specified pOrderBy list is actually a GROUP
129410 ** BY clause - and so any order that groups rows as required satisfies the
129411 ** request.
129412 **
129413 ** Normally, in this case it is not possible for the caller to determine
129414 ** whether or not the rows are really being delivered in sorted order, or
129415 ** just in some other order that provides the required grouping. However,
129416 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
129417 ** this function may be called on the returned WhereInfo object. It returns
129418 ** true if the rows really will be sorted in the specified order, or false
129419 ** otherwise.
129420 **
129421 ** For example, assuming:
129422 **
129423 ** CREATE INDEX i1 ON t1(x, Y);
129424 **
129425 ** then
129426 **
129427 ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
129428 ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
129429 */
129431  assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
129432  assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
129433  return pWInfo->sorted;
129434 }
129435 
129436 #ifdef WHERETRACE_ENABLED
129437 /* For debugging use only: */
129438 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
129439  static char zName[65];
129440  int i;
129441  for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
129442  if( pLast ) zName[i++] = pLast->cId;
129443  zName[i] = 0;
129444  return zName;
129445 }
129446 #endif
129447 
129448 /*
129449 ** Return the cost of sorting nRow rows, assuming that the keys have
129450 ** nOrderby columns and that the first nSorted columns are already in
129451 ** order.
129452 */
129453 static LogEst whereSortingCost(
129454  WhereInfo *pWInfo,
129455  LogEst nRow,
129456  int nOrderBy,
129457  int nSorted
129458 ){
129459  /* TUNING: Estimated cost of a full external sort, where N is
129460  ** the number of rows to sort is:
129461  **
129462  ** cost = (3.0 * N * log(N)).
129463  **
129464  ** Or, if the order-by clause has X terms but only the last Y
129465  ** terms are out of order, then block-sorting will reduce the
129466  ** sorting cost to:
129467  **
129468  ** cost = (3.0 * N * log(N)) * (Y/X)
129469  **
129470  ** The (Y/X) term is implemented using stack variable rScale
129471  ** below. */
129472  LogEst rScale, rSortCost;
129473  assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
129474  rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
129475  rSortCost = nRow + rScale + 16;
129476 
129477  /* Multiple by log(M) where M is the number of output rows.
129478  ** Use the LIMIT for M if it is smaller */
129479  if( (pWInfo->wctrlFlags & WHERE_USE_LIMIT)!=0 && pWInfo->iLimit<nRow ){
129480  nRow = pWInfo->iLimit;
129481  }
129482  rSortCost += estLog(nRow);
129483  return rSortCost;
129484 }
129485 
129486 /*
129487 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
129488 ** attempts to find the lowest cost path that visits each WhereLoop
129489 ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
129490 **
129491 ** Assume that the total number of output rows that will need to be sorted
129492 ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
129493 ** costs if nRowEst==0.
129494 **
129495 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
129496 ** error occurs.
129497 */
129498 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
129499  int mxChoice; /* Maximum number of simultaneous paths tracked */
129500  int nLoop; /* Number of terms in the join */
129501  Parse *pParse; /* Parsing context */
129502  sqlite3 *db; /* The database connection */
129503  int iLoop; /* Loop counter over the terms of the join */
129504  int ii, jj; /* Loop counters */
129505  int mxI = 0; /* Index of next entry to replace */
129506  int nOrderBy; /* Number of ORDER BY clause terms */
129507  LogEst mxCost = 0; /* Maximum cost of a set of paths */
129508  LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
129509  int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
129510  WherePath *aFrom; /* All nFrom paths at the previous level */
129511  WherePath *aTo; /* The nTo best paths at the current level */
129512  WherePath *pFrom; /* An element of aFrom[] that we are working on */
129513  WherePath *pTo; /* An element of aTo[] that we are working on */
129514  WhereLoop *pWLoop; /* One of the WhereLoop objects */
129515  WhereLoop **pX; /* Used to divy up the pSpace memory */
129516  LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
129517  char *pSpace; /* Temporary memory used by this routine */
129518  int nSpace; /* Bytes of space allocated at pSpace */
129519 
129520  pParse = pWInfo->pParse;
129521  db = pParse->db;
129522  nLoop = pWInfo->nLevel;
129523  /* TUNING: For simple queries, only the best path is tracked.
129524  ** For 2-way joins, the 5 best paths are followed.
129525  ** For joins of 3 or more tables, track the 10 best paths */
129526  mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
129527  assert( nLoop<=pWInfo->pTabList->nSrc );
129528  WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
129529 
129530  /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
129531  ** case the purpose of this call is to estimate the number of rows returned
129532  ** by the overall query. Once this estimate has been obtained, the caller
129533  ** will invoke this function a second time, passing the estimate as the
129534  ** nRowEst parameter. */
129535  if( pWInfo->pOrderBy==0 || nRowEst==0 ){
129536  nOrderBy = 0;
129537  }else{
129538  nOrderBy = pWInfo->pOrderBy->nExpr;
129539  }
129540 
129541  /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
129542  nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
129543  nSpace += sizeof(LogEst) * nOrderBy;
129544  pSpace = sqlite3DbMallocRawNN(db, nSpace);
129545  if( pSpace==0 ) return SQLITE_NOMEM_BKPT;
129546  aTo = (WherePath*)pSpace;
129547  aFrom = aTo+mxChoice;
129548  memset(aFrom, 0, sizeof(aFrom[0]));
129549  pX = (WhereLoop**)(aFrom+mxChoice);
129550  for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
129551  pFrom->aLoop = pX;
129552  }
129553  if( nOrderBy ){
129554  /* If there is an ORDER BY clause and it is not being ignored, set up
129555  ** space for the aSortCost[] array. Each element of the aSortCost array
129556  ** is either zero - meaning it has not yet been initialized - or the
129557  ** cost of sorting nRowEst rows of data where the first X terms of
129558  ** the ORDER BY clause are already in order, where X is the array
129559  ** index. */
129560  aSortCost = (LogEst*)pX;
129561  memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
129562  }
129563  assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
129564  assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
129565 
129566  /* Seed the search with a single WherePath containing zero WhereLoops.
129567  **
129568  ** TUNING: Do not let the number of iterations go above 28. If the cost
129569  ** of computing an automatic index is not paid back within the first 28
129570  ** rows, then do not use the automatic index. */
129571  aFrom[0].nRow = MIN(pParse->nQueryLoop, 48); assert( 48==sqlite3LogEst(28) );
129572  nFrom = 1;
129573  assert( aFrom[0].isOrdered==0 );
129574  if( nOrderBy ){
129575  /* If nLoop is zero, then there are no FROM terms in the query. Since
129576  ** in this case the query may return a maximum of one row, the results
129577  ** are already in the requested order. Set isOrdered to nOrderBy to
129578  ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
129579  ** -1, indicating that the result set may or may not be ordered,
129580  ** depending on the loops added to the current plan. */
129581  aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
129582  }
129583 
129584  /* Compute successively longer WherePaths using the previous generation
129585  ** of WherePaths as the basis for the next. Keep track of the mxChoice
129586  ** best paths at each generation */
129587  for(iLoop=0; iLoop<nLoop; iLoop++){
129588  nTo = 0;
129589  for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
129590  for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
129591  LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
129592  LogEst rCost; /* Cost of path (pFrom+pWLoop) */
129593  LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
129594  i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
129595  Bitmask maskNew; /* Mask of src visited by (..) */
129596  Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
129597 
129598  if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
129599  if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
129600  if( (pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 && pFrom->nRow<10 ){
129601  /* Do not use an automatic index if the this loop is expected
129602  ** to run less than 2 times. */
129603  assert( 10==sqlite3LogEst(2) );
129604  continue;
129605  }
129606  /* At this point, pWLoop is a candidate to be the next loop.
129607  ** Compute its cost */
129608  rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
129609  rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
129610  nOut = pFrom->nRow + pWLoop->nOut;
129611  maskNew = pFrom->maskLoop | pWLoop->maskSelf;
129612  if( isOrdered<0 ){
129613  isOrdered = wherePathSatisfiesOrderBy(pWInfo,
129614  pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
129615  iLoop, pWLoop, &revMask);
129616  }else{
129617  revMask = pFrom->revLoop;
129618  }
129619  if( isOrdered>=0 && isOrdered<nOrderBy ){
129620  if( aSortCost[isOrdered]==0 ){
129621  aSortCost[isOrdered] = whereSortingCost(
129622  pWInfo, nRowEst, nOrderBy, isOrdered
129623  );
129624  }
129625  rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
129626 
129627  WHERETRACE(0x002,
129628  ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
129629  aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
129630  rUnsorted, rCost));
129631  }else{
129632  rCost = rUnsorted;
129633  }
129634 
129635  /* Check to see if pWLoop should be added to the set of
129636  ** mxChoice best-so-far paths.
129637  **
129638  ** First look for an existing path among best-so-far paths
129639  ** that covers the same set of loops and has the same isOrdered
129640  ** setting as the current path candidate.
129641  **
129642  ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
129643  ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
129644  ** of legal values for isOrdered, -1..64.
129645  */
129646  for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
129647  if( pTo->maskLoop==maskNew
129648  && ((pTo->isOrdered^isOrdered)&0x80)==0
129649  ){
129650  testcase( jj==nTo-1 );
129651  break;
129652  }
129653  }
129654  if( jj>=nTo ){
129655  /* None of the existing best-so-far paths match the candidate. */
129656  if( nTo>=mxChoice
129657  && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
129658  ){
129659  /* The current candidate is no better than any of the mxChoice
129660  ** paths currently in the best-so-far buffer. So discard
129661  ** this candidate as not viable. */
129662 #ifdef WHERETRACE_ENABLED /* 0x4 */
129663  if( sqlite3WhereTrace&0x4 ){
129664  sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
129665  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
129666  isOrdered>=0 ? isOrdered+'0' : '?');
129667  }
129668 #endif
129669  continue;
129670  }
129671  /* If we reach this points it means that the new candidate path
129672  ** needs to be added to the set of best-so-far paths. */
129673  if( nTo<mxChoice ){
129674  /* Increase the size of the aTo set by one */
129675  jj = nTo++;
129676  }else{
129677  /* New path replaces the prior worst to keep count below mxChoice */
129678  jj = mxI;
129679  }
129680  pTo = &aTo[jj];
129681 #ifdef WHERETRACE_ENABLED /* 0x4 */
129682  if( sqlite3WhereTrace&0x4 ){
129683  sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
129684  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
129685  isOrdered>=0 ? isOrdered+'0' : '?');
129686  }
129687 #endif
129688  }else{
129689  /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
129690  ** same set of loops and has the sam isOrdered setting as the
129691  ** candidate path. Check to see if the candidate should replace
129692  ** pTo or if the candidate should be skipped */
129693  if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
129694 #ifdef WHERETRACE_ENABLED /* 0x4 */
129695  if( sqlite3WhereTrace&0x4 ){
129696  sqlite3DebugPrintf(
129697  "Skip %s cost=%-3d,%3d order=%c",
129698  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
129699  isOrdered>=0 ? isOrdered+'0' : '?');
129700  sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
129701  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
129702  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
129703  }
129704 #endif
129705  /* Discard the candidate path from further consideration */
129706  testcase( pTo->rCost==rCost );
129707  continue;
129708  }
129709  testcase( pTo->rCost==rCost+1 );
129710  /* Control reaches here if the candidate path is better than the
129711  ** pTo path. Replace pTo with the candidate. */
129712 #ifdef WHERETRACE_ENABLED /* 0x4 */
129713  if( sqlite3WhereTrace&0x4 ){
129714  sqlite3DebugPrintf(
129715  "Update %s cost=%-3d,%3d order=%c",
129716  wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
129717  isOrdered>=0 ? isOrdered+'0' : '?');
129718  sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
129719  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
129720  pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
129721  }
129722 #endif
129723  }
129724  /* pWLoop is a winner. Add it to the set of best so far */
129725  pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
129726  pTo->revLoop = revMask;
129727  pTo->nRow = nOut;
129728  pTo->rCost = rCost;
129729  pTo->rUnsorted = rUnsorted;
129730  pTo->isOrdered = isOrdered;
129731  memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
129732  pTo->aLoop[iLoop] = pWLoop;
129733  if( nTo>=mxChoice ){
129734  mxI = 0;
129735  mxCost = aTo[0].rCost;
129736  mxUnsorted = aTo[0].nRow;
129737  for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
129738  if( pTo->rCost>mxCost
129739  || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
129740  ){
129741  mxCost = pTo->rCost;
129742  mxUnsorted = pTo->rUnsorted;
129743  mxI = jj;
129744  }
129745  }
129746  }
129747  }
129748  }
129749 
129750 #ifdef WHERETRACE_ENABLED /* >=2 */
129751  if( sqlite3WhereTrace & 0x02 ){
129752  sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
129753  for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
129754  sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
129755  wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
129756  pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
129757  if( pTo->isOrdered>0 ){
129758  sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
129759  }else{
129760  sqlite3DebugPrintf("\n");
129761  }
129762  }
129763  }
129764 #endif
129765 
129766  /* Swap the roles of aFrom and aTo for the next generation */
129767  pFrom = aTo;
129768  aTo = aFrom;
129769  aFrom = pFrom;
129770  nFrom = nTo;
129771  }
129772 
129773  if( nFrom==0 ){
129774  sqlite3ErrorMsg(pParse, "no query solution");
129775  sqlite3DbFree(db, pSpace);
129776  return SQLITE_ERROR;
129777  }
129778 
129779  /* Find the lowest cost path. pFrom will be left pointing to that path */
129780  pFrom = aFrom;
129781  for(ii=1; ii<nFrom; ii++){
129782  if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
129783  }
129784  assert( pWInfo->nLevel==nLoop );
129785  /* Load the lowest cost path into pWInfo */
129786  for(iLoop=0; iLoop<nLoop; iLoop++){
129787  WhereLevel *pLevel = pWInfo->a + iLoop;
129788  pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
129789  pLevel->iFrom = pWLoop->iTab;
129790  pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
129791  }
129792  if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
129793  && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
129794  && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
129795  && nRowEst
129796  ){
129797  Bitmask notUsed;
129798  int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pDistinctSet, pFrom,
129799  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
129800  if( rc==pWInfo->pDistinctSet->nExpr ){
129801  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
129802  }
129803  }
129804  if( pWInfo->pOrderBy ){
129805  if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
129806  if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
129807  pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
129808  }
129809  }else{
129810  pWInfo->nOBSat = pFrom->isOrdered;
129811  if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
129812  pWInfo->revMask = pFrom->revLoop;
129813  }
129814  if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
129815  && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr && nLoop>0
129816  ){
129817  Bitmask revMask = 0;
129818  int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
129819  pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
129820  );
129821  assert( pWInfo->sorted==0 );
129822  if( nOrder==pWInfo->pOrderBy->nExpr ){
129823  pWInfo->sorted = 1;
129824  pWInfo->revMask = revMask;
129825  }
129826  }
129827  }
129828 
129829 
129830  pWInfo->nRowOut = pFrom->nRow;
129831 
129832  /* Free temporary memory and return success */
129833  sqlite3DbFree(db, pSpace);
129834  return SQLITE_OK;
129835 }
129836 
129837 /*
129838 ** Most queries use only a single table (they are not joins) and have
129839 ** simple == constraints against indexed fields. This routine attempts
129840 ** to plan those simple cases using much less ceremony than the
129841 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
129842 ** times for the common case.
129843 **
129844 ** Return non-zero on success, if this query can be handled by this
129845 ** no-frills query planner. Return zero if this query needs the
129846 ** general-purpose query planner.
129847 */
129848 static int whereShortCut(WhereLoopBuilder *pBuilder){
129849  WhereInfo *pWInfo;
129850  struct SrcList_item *pItem;
129851  WhereClause *pWC;
129852  WhereTerm *pTerm;
129853  WhereLoop *pLoop;
129854  int iCur;
129855  int j;
129856  Table *pTab;
129857  Index *pIdx;
129858 
129859  pWInfo = pBuilder->pWInfo;
129860  if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
129861  assert( pWInfo->pTabList->nSrc>=1 );
129862  pItem = pWInfo->pTabList->a;
129863  pTab = pItem->pTab;
129864  if( IsVirtual(pTab) ) return 0;
129865  if( pItem->fg.isIndexedBy ) return 0;
129866  iCur = pItem->iCursor;
129867  pWC = &pWInfo->sWC;
129868  pLoop = pBuilder->pNew;
129869  pLoop->wsFlags = 0;
129870  pLoop->nSkip = 0;
129871  pTerm = sqlite3WhereFindTerm(pWC, iCur, -1, 0, WO_EQ|WO_IS, 0);
129872  if( pTerm ){
129873  testcase( pTerm->eOperator & WO_IS );
129875  pLoop->aLTerm[0] = pTerm;
129876  pLoop->nLTerm = 1;
129877  pLoop->u.btree.nEq = 1;
129878  /* TUNING: Cost of a rowid lookup is 10 */
129879  pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
129880  }else{
129881  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
129882  int opMask;
129883  assert( pLoop->aLTermSpace==pLoop->aLTerm );
129884  if( !IsUniqueIndex(pIdx)
129885  || pIdx->pPartIdxWhere!=0
129886  || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
129887  ) continue;
129888  opMask = pIdx->uniqNotNull ? (WO_EQ|WO_IS) : WO_EQ;
129889  for(j=0; j<pIdx->nKeyCol; j++){
129890  pTerm = sqlite3WhereFindTerm(pWC, iCur, j, 0, opMask, pIdx);
129891  if( pTerm==0 ) break;
129892  testcase( pTerm->eOperator & WO_IS );
129893  pLoop->aLTerm[j] = pTerm;
129894  }
129895  if( j!=pIdx->nKeyCol ) continue;
129897  if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
129898  pLoop->wsFlags |= WHERE_IDX_ONLY;
129899  }
129900  pLoop->nLTerm = j;
129901  pLoop->u.btree.nEq = j;
129902  pLoop->u.btree.pIndex = pIdx;
129903  /* TUNING: Cost of a unique index lookup is 15 */
129904  pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
129905  break;
129906  }
129907  }
129908  if( pLoop->wsFlags ){
129909  pLoop->nOut = (LogEst)1;
129910  pWInfo->a[0].pWLoop = pLoop;
129911  pLoop->maskSelf = sqlite3WhereGetMask(&pWInfo->sMaskSet, iCur);
129912  pWInfo->a[0].iTabCur = iCur;
129913  pWInfo->nRowOut = 1;
129914  if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
129915  if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
129916  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
129917  }
129918 #ifdef SQLITE_DEBUG
129919  pLoop->cId = '0';
129920 #endif
129921  return 1;
129922  }
129923  return 0;
129924 }
129925 
129926 /*
129927 ** Generate the beginning of the loop used for WHERE clause processing.
129928 ** The return value is a pointer to an opaque structure that contains
129929 ** information needed to terminate the loop. Later, the calling routine
129930 ** should invoke sqlite3WhereEnd() with the return value of this function
129931 ** in order to complete the WHERE clause processing.
129932 **
129933 ** If an error occurs, this routine returns NULL.
129934 **
129935 ** The basic idea is to do a nested loop, one loop for each table in
129936 ** the FROM clause of a select. (INSERT and UPDATE statements are the
129937 ** same as a SELECT with only a single table in the FROM clause.) For
129938 ** example, if the SQL is this:
129939 **
129940 ** SELECT * FROM t1, t2, t3 WHERE ...;
129941 **
129942 ** Then the code generated is conceptually like the following:
129943 **
129944 ** foreach row1 in t1 do \ Code generated
129945 ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
129946 ** foreach row3 in t3 do /
129947 ** ...
129948 ** end \ Code generated
129949 ** end |-- by sqlite3WhereEnd()
129950 ** end /
129951 **
129952 ** Note that the loops might not be nested in the order in which they
129953 ** appear in the FROM clause if a different order is better able to make
129954 ** use of indices. Note also that when the IN operator appears in
129955 ** the WHERE clause, it might result in additional nested loops for
129956 ** scanning through all values on the right-hand side of the IN.
129957 **
129958 ** There are Btree cursors associated with each table. t1 uses cursor
129959 ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
129960 ** And so forth. This routine generates code to open those VDBE cursors
129961 ** and sqlite3WhereEnd() generates the code to close them.
129962 **
129963 ** The code that sqlite3WhereBegin() generates leaves the cursors named
129964 ** in pTabList pointing at their appropriate entries. The [...] code
129965 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
129966 ** data from the various tables of the loop.
129967 **
129968 ** If the WHERE clause is empty, the foreach loops must each scan their
129969 ** entire tables. Thus a three-way join is an O(N^3) operation. But if
129970 ** the tables have indices and there are terms in the WHERE clause that
129971 ** refer to those indices, a complete table scan can be avoided and the
129972 ** code will run much faster. Most of the work of this routine is checking
129973 ** to see if there are indices that can be used to speed up the loop.
129974 **
129975 ** Terms of the WHERE clause are also used to limit which rows actually
129976 ** make it to the "..." in the middle of the loop. After each "foreach",
129977 ** terms of the WHERE clause that use only terms in that loop and outer
129978 ** loops are evaluated and if false a jump is made around all subsequent
129979 ** inner loops (or around the "..." if the test occurs within the inner-
129980 ** most loop)
129981 **
129982 ** OUTER JOINS
129983 **
129984 ** An outer join of tables t1 and t2 is conceptally coded as follows:
129985 **
129986 ** foreach row1 in t1 do
129987 ** flag = 0
129988 ** foreach row2 in t2 do
129989 ** start:
129990 ** ...
129991 ** flag = 1
129992 ** end
129993 ** if flag==0 then
129994 ** move the row2 cursor to a null row
129995 ** goto start
129996 ** fi
129997 ** end
129998 **
129999 ** ORDER BY CLAUSE PROCESSING
130000 **
130001 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
130002 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
130003 ** if there is one. If there is no ORDER BY clause or if this routine
130004 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
130005 **
130006 ** The iIdxCur parameter is the cursor number of an index. If
130007 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
130008 ** to use for OR clause processing. The WHERE clause should use this
130009 ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
130010 ** the first cursor in an array of cursors for all indices. iIdxCur should
130011 ** be used to compute the appropriate cursor depending on which index is
130012 ** used.
130013 */
130015  Parse *pParse, /* The parser context */
130016  SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
130017  Expr *pWhere, /* The WHERE clause */
130018  ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
130019  ExprList *pDistinctSet, /* Try not to output two rows that duplicate these */
130020  u16 wctrlFlags, /* The WHERE_* flags defined in sqliteInt.h */
130021  int iAuxArg /* If WHERE_ONETABLE_ONLY is set, index cursor number
130022  ** If WHERE_USE_LIMIT, then the limit amount */
130023 ){
130024  int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
130025  int nTabList; /* Number of elements in pTabList */
130026  WhereInfo *pWInfo; /* Will become the return value of this function */
130027  Vdbe *v = pParse->pVdbe; /* The virtual database engine */
130028  Bitmask notReady; /* Cursors that are not yet positioned */
130029  WhereLoopBuilder sWLB; /* The WhereLoop builder */
130030  WhereMaskSet *pMaskSet; /* The expression mask set */
130031  WhereLevel *pLevel; /* A single level in pWInfo->a[] */
130032  WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
130033  int ii; /* Loop counter */
130034  sqlite3 *db; /* Database connection */
130035  int rc; /* Return code */
130036  u8 bFordelete = 0; /* OPFLAG_FORDELETE or zero, as appropriate */
130037 
130038  assert( (wctrlFlags & WHERE_ONEPASS_MULTIROW)==0 || (
130039  (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
130040  && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
130041  ));
130042 
130043  /* Only one of WHERE_ONETABLE_ONLY or WHERE_USE_LIMIT */
130044  assert( (wctrlFlags & WHERE_ONETABLE_ONLY)==0
130045  || (wctrlFlags & WHERE_USE_LIMIT)==0 );
130046 
130047  /* Variable initialization */
130048  db = pParse->db;
130049  memset(&sWLB, 0, sizeof(sWLB));
130050 
130051  /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
130052  testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
130053  if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
130054  sWLB.pOrderBy = pOrderBy;
130055 
130056  /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
130057  ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
130059  wctrlFlags &= ~WHERE_WANT_DISTINCT;
130060  }
130061 
130062  /* The number of tables in the FROM clause is limited by the number of
130063  ** bits in a Bitmask
130064  */
130065  testcase( pTabList->nSrc==BMS );
130066  if( pTabList->nSrc>BMS ){
130067  sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
130068  return 0;
130069  }
130070 
130071  /* This function normally generates a nested loop for all tables in
130072  ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
130073  ** only generate code for the first table in pTabList and assume that
130074  ** any cursors associated with subsequent tables are uninitialized.
130075  */
130076  nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
130077 
130078  /* Allocate and initialize the WhereInfo structure that will become the
130079  ** return value. A single allocation is used to store the WhereInfo
130080  ** struct, the contents of WhereInfo.a[], the WhereClause structure
130081  ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
130082  ** field (type Bitmask) it must be aligned on an 8-byte boundary on
130083  ** some architectures. Hence the ROUND8() below.
130084  */
130085  nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
130086  pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
130087  if( db->mallocFailed ){
130088  sqlite3DbFree(db, pWInfo);
130089  pWInfo = 0;
130090  goto whereBeginError;
130091  }
130092  pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
130093  pWInfo->nLevel = nTabList;
130094  pWInfo->pParse = pParse;
130095  pWInfo->pTabList = pTabList;
130096  pWInfo->pOrderBy = pOrderBy;
130097  pWInfo->pDistinctSet = pDistinctSet;
130098  pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
130099  pWInfo->wctrlFlags = wctrlFlags;
130100  pWInfo->iLimit = iAuxArg;
130101  pWInfo->savedNQueryLoop = pParse->nQueryLoop;
130102  assert( pWInfo->eOnePass==ONEPASS_OFF ); /* ONEPASS defaults to OFF */
130103  pMaskSet = &pWInfo->sMaskSet;
130104  sWLB.pWInfo = pWInfo;
130105  sWLB.pWC = &pWInfo->sWC;
130106  sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
130107  assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
130108  whereLoopInit(sWLB.pNew);
130109 #ifdef SQLITE_DEBUG
130110  sWLB.pNew->cId = '*';
130111 #endif
130112 
130113  /* Split the WHERE clause into separate subexpressions where each
130114  ** subexpression is separated by an AND operator.
130115  */
130116  initMaskSet(pMaskSet);
130117  sqlite3WhereClauseInit(&pWInfo->sWC, pWInfo);
130118  sqlite3WhereSplit(&pWInfo->sWC, pWhere, TK_AND);
130119 
130120  /* Special case: a WHERE clause that is constant. Evaluate the
130121  ** expression and either jump over all of the code or fall thru.
130122  */
130123  for(ii=0; ii<sWLB.pWC->nTerm; ii++){
130124  if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
130125  sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
130127  sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
130128  }
130129  }
130130 
130131  /* Special case: No FROM clause
130132  */
130133  if( nTabList==0 ){
130134  if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
130135  if( wctrlFlags & WHERE_WANT_DISTINCT ){
130136  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130137  }
130138  }
130139 
130140  /* Assign a bit from the bitmask to every term in the FROM clause.
130141  **
130142  ** The N-th term of the FROM clause is assigned a bitmask of 1<<N.
130143  **
130144  ** The rule of the previous sentence ensures thta if X is the bitmask for
130145  ** a table T, then X-1 is the bitmask for all other tables to the left of T.
130146  ** Knowing the bitmask for all tables to the left of a left join is
130147  ** important. Ticket #3015.
130148  **
130149  ** Note that bitmasks are created for all pTabList->nSrc tables in
130150  ** pTabList, not just the first nTabList tables. nTabList is normally
130151  ** equal to pTabList->nSrc but might be shortened to 1 if the
130152  ** WHERE_ONETABLE_ONLY flag is set.
130153  */
130154  for(ii=0; ii<pTabList->nSrc; ii++){
130155  createMask(pMaskSet, pTabList->a[ii].iCursor);
130156  sqlite3WhereTabFuncArgs(pParse, &pTabList->a[ii], &pWInfo->sWC);
130157  }
130158 #ifdef SQLITE_DEBUG
130159  for(ii=0; ii<pTabList->nSrc; ii++){
130160  Bitmask m = sqlite3WhereGetMask(pMaskSet, pTabList->a[ii].iCursor);
130161  assert( m==MASKBIT(ii) );
130162  }
130163 #endif
130164 
130165  /* Analyze all of the subexpressions. */
130166  sqlite3WhereExprAnalyze(pTabList, &pWInfo->sWC);
130167  if( db->mallocFailed ) goto whereBeginError;
130168 
130169  if( wctrlFlags & WHERE_WANT_DISTINCT ){
130170  if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pDistinctSet) ){
130171  /* The DISTINCT marking is pointless. Ignore it. */
130172  pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
130173  }else if( pOrderBy==0 ){
130174  /* Try to ORDER BY the result set to make distinct processing easier */
130175  pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
130176  pWInfo->pOrderBy = pDistinctSet;
130177  }
130178  }
130179 
130180  /* Construct the WhereLoop objects */
130181 #if defined(WHERETRACE_ENABLED)
130182  if( sqlite3WhereTrace & 0xffff ){
130183  sqlite3DebugPrintf("*** Optimizer Start *** (wctrlFlags: 0x%x",wctrlFlags);
130184  if( wctrlFlags & WHERE_USE_LIMIT ){
130185  sqlite3DebugPrintf(", limit: %d", iAuxArg);
130186  }
130187  sqlite3DebugPrintf(")\n");
130188  }
130189  if( sqlite3WhereTrace & 0x100 ){ /* Display all terms of the WHERE clause */
130190  int i;
130191  for(i=0; i<sWLB.pWC->nTerm; i++){
130192  whereTermPrint(&sWLB.pWC->a[i], i);
130193  }
130194  }
130195 #endif
130196 
130197  if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
130198  rc = whereLoopAddAll(&sWLB);
130199  if( rc ) goto whereBeginError;
130200 
130201 #ifdef WHERETRACE_ENABLED
130202  if( sqlite3WhereTrace ){ /* Display all of the WhereLoop objects */
130203  WhereLoop *p;
130204  int i;
130205  static const char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
130206  "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
130207  for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
130208  p->cId = zLabel[i%sizeof(zLabel)];
130209  whereLoopPrint(p, sWLB.pWC);
130210  }
130211  }
130212 #endif
130213 
130214  wherePathSolver(pWInfo, 0);
130215  if( db->mallocFailed ) goto whereBeginError;
130216  if( pWInfo->pOrderBy ){
130217  wherePathSolver(pWInfo, pWInfo->nRowOut+1);
130218  if( db->mallocFailed ) goto whereBeginError;
130219  }
130220  }
130221  if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
130222  pWInfo->revMask = ALLBITS;
130223  }
130224  if( pParse->nErr || NEVER(db->mallocFailed) ){
130225  goto whereBeginError;
130226  }
130227 #ifdef WHERETRACE_ENABLED
130228  if( sqlite3WhereTrace ){
130229  sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
130230  if( pWInfo->nOBSat>0 ){
130231  sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
130232  }
130233  switch( pWInfo->eDistinct ){
130234  case WHERE_DISTINCT_UNIQUE: {
130235  sqlite3DebugPrintf(" DISTINCT=unique");
130236  break;
130237  }
130238  case WHERE_DISTINCT_ORDERED: {
130239  sqlite3DebugPrintf(" DISTINCT=ordered");
130240  break;
130241  }
130242  case WHERE_DISTINCT_UNORDERED: {
130243  sqlite3DebugPrintf(" DISTINCT=unordered");
130244  break;
130245  }
130246  }
130247  sqlite3DebugPrintf("\n");
130248  for(ii=0; ii<pWInfo->nLevel; ii++){
130249  whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
130250  }
130251  }
130252 #endif
130253  /* Attempt to omit tables from the join that do not effect the result */
130254  if( pWInfo->nLevel>=2
130255  && pDistinctSet!=0
130257  ){
130258  Bitmask tabUsed = sqlite3WhereExprListUsage(pMaskSet, pDistinctSet);
130259  if( sWLB.pOrderBy ){
130260  tabUsed |= sqlite3WhereExprListUsage(pMaskSet, sWLB.pOrderBy);
130261  }
130262  while( pWInfo->nLevel>=2 ){
130263  WhereTerm *pTerm, *pEnd;
130264  pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
130265  if( (pWInfo->pTabList->a[pLoop->iTab].fg.jointype & JT_LEFT)==0 ) break;
130266  if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
130267  && (pLoop->wsFlags & WHERE_ONEROW)==0
130268  ){
130269  break;
130270  }
130271  if( (tabUsed & pLoop->maskSelf)!=0 ) break;
130272  pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
130273  for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
130274  if( (pTerm->prereqAll & pLoop->maskSelf)!=0
130275  && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
130276  ){
130277  break;
130278  }
130279  }
130280  if( pTerm<pEnd ) break;
130281  WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
130282  pWInfo->nLevel--;
130283  nTabList--;
130284  }
130285  }
130286  WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
130287  pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
130288 
130289  /* If the caller is an UPDATE or DELETE statement that is requesting
130290  ** to use a one-pass algorithm, determine if this is appropriate.
130291  */
130292  assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
130293  if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 ){
130294  int wsFlags = pWInfo->a[0].pWLoop->wsFlags;
130295  int bOnerow = (wsFlags & WHERE_ONEROW)!=0;
130296  if( bOnerow
130297  || ((wctrlFlags & WHERE_ONEPASS_MULTIROW)!=0
130298  && 0==(wsFlags & WHERE_VIRTUALTABLE))
130299  ){
130300  pWInfo->eOnePass = bOnerow ? ONEPASS_SINGLE : ONEPASS_MULTI;
130301  if( HasRowid(pTabList->a[0].pTab) && (wsFlags & WHERE_IDX_ONLY) ){
130302  if( wctrlFlags & WHERE_ONEPASS_MULTIROW ){
130303  bFordelete = OPFLAG_FORDELETE;
130304  }
130305  pWInfo->a[0].pWLoop->wsFlags = (wsFlags & ~WHERE_IDX_ONLY);
130306  }
130307  }
130308  }
130309 
130310  /* Open all tables in the pTabList and any indices selected for
130311  ** searching those tables.
130312  */
130313  for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
130314  Table *pTab; /* Table to open */
130315  int iDb; /* Index of database containing table/index */
130316  struct SrcList_item *pTabItem;
130317 
130318  pTabItem = &pTabList->a[pLevel->iFrom];
130319  pTab = pTabItem->pTab;
130320  iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
130321  pLoop = pLevel->pWLoop;
130322  if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
130323  /* Do nothing */
130324  }else
130325 #ifndef SQLITE_OMIT_VIRTUALTABLE
130326  if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
130327  const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
130328  int iCur = pTabItem->iCursor;
130329  sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
130330  }else if( IsVirtual(pTab) ){
130331  /* noop */
130332  }else
130333 #endif
130334  if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
130335  && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
130336  int op = OP_OpenRead;
130337  if( pWInfo->eOnePass!=ONEPASS_OFF ){
130338  op = OP_OpenWrite;
130339  pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
130340  };
130341  sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
130342  assert( pTabItem->iCursor==pLevel->iTabCur );
130343  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS-1 );
130344  testcase( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol==BMS );
130345  if( pWInfo->eOnePass==ONEPASS_OFF && pTab->nCol<BMS && HasRowid(pTab) ){
130346  Bitmask b = pTabItem->colUsed;
130347  int n = 0;
130348  for(; b; b=b>>1, n++){}
130350  assert( n<=pTab->nCol );
130351  }
130352 #ifdef SQLITE_ENABLE_CURSOR_HINTS
130353  if( pLoop->u.btree.pIndex!=0 ){
130354  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ|bFordelete);
130355  }else
130356 #endif
130357  {
130358  sqlite3VdbeChangeP5(v, bFordelete);
130359  }
130360 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
130361  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, pTabItem->iCursor, 0, 0,
130362  (const u8*)&pTabItem->colUsed, P4_INT64);
130363 #endif
130364  }else{
130365  sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
130366  }
130367  if( pLoop->wsFlags & WHERE_INDEXED ){
130368  Index *pIx = pLoop->u.btree.pIndex;
130369  int iIndexCur;
130370  int op = OP_OpenRead;
130371  /* iAuxArg is always set if to a positive value if ONEPASS is possible */
130372  assert( iAuxArg!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
130373  if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
130374  && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
130375  ){
130376  /* This is one term of an OR-optimization using the PRIMARY KEY of a
130377  ** WITHOUT ROWID table. No need for a separate index */
130378  iIndexCur = pLevel->iTabCur;
130379  op = 0;
130380  }else if( pWInfo->eOnePass!=ONEPASS_OFF ){
130381  Index *pJ = pTabItem->pTab->pIndex;
130382  iIndexCur = iAuxArg;
130383  assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
130384  while( ALWAYS(pJ) && pJ!=pIx ){
130385  iIndexCur++;
130386  pJ = pJ->pNext;
130387  }
130388  op = OP_OpenWrite;
130389  pWInfo->aiCurOnePass[1] = iIndexCur;
130390  }else if( iAuxArg && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
130391  iIndexCur = iAuxArg;
130392  if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
130393  }else{
130394  iIndexCur = pParse->nTab++;
130395  }
130396  pLevel->iIdxCur = iIndexCur;
130397  assert( pIx->pSchema==pTab->pSchema );
130398  assert( iIndexCur>=0 );
130399  if( op ){
130400  sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
130401  sqlite3VdbeSetP4KeyInfo(pParse, pIx);
130402  if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
130403  && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
130404  && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
130405  ){
130406  sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
130407  }
130408  VdbeComment((v, "%s", pIx->zName));
130409 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
130410  {
130411  u64 colUsed = 0;
130412  int ii, jj;
130413  for(ii=0; ii<pIx->nColumn; ii++){
130414  jj = pIx->aiColumn[ii];
130415  if( jj<0 ) continue;
130416  if( jj>63 ) jj = 63;
130417  if( (pTabItem->colUsed & MASKBIT(jj))==0 ) continue;
130418  colUsed |= ((u64)1)<<(ii<63 ? ii : 63);
130419  }
130420  sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed, iIndexCur, 0, 0,
130421  (u8*)&colUsed, P4_INT64);
130422  }
130423 #endif /* SQLITE_ENABLE_COLUMN_USED_MASK */
130424  }
130425  }
130426  if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
130427  }
130428  pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
130429  if( db->mallocFailed ) goto whereBeginError;
130430 
130431  /* Generate the code to do the search. Each iteration of the for
130432  ** loop below generates code for a single nested loop of the VM
130433  ** program.
130434  */
130435  notReady = ~(Bitmask)0;
130436  for(ii=0; ii<nTabList; ii++){
130437  int addrExplain;
130438  int wsFlags;
130439  pLevel = &pWInfo->a[ii];
130440  wsFlags = pLevel->pWLoop->wsFlags;
130441 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
130442  if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
130443  constructAutomaticIndex(pParse, &pWInfo->sWC,
130444  &pTabList->a[pLevel->iFrom], notReady, pLevel);
130445  if( db->mallocFailed ) goto whereBeginError;
130446  }
130447 #endif
130448  addrExplain = sqlite3WhereExplainOneScan(
130449  pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
130450  );
130451  pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
130452  notReady = sqlite3WhereCodeOneLoopStart(pWInfo, ii, notReady);
130453  pWInfo->iContinue = pLevel->addrCont;
130454  if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
130455  sqlite3WhereAddScanStatus(v, pTabList, pLevel, addrExplain);
130456  }
130457  }
130458 
130459  /* Done. */
130460  VdbeModuleComment((v, "Begin WHERE-core"));
130461  return pWInfo;
130462 
130463  /* Jump here if malloc fails */
130464 whereBeginError:
130465  if( pWInfo ){
130466  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
130467  whereInfoFree(db, pWInfo);
130468  }
130469  return 0;
130470 }
130471 
130472 /*
130473 ** Generate the end of the WHERE loop. See comments on
130474 ** sqlite3WhereBegin() for additional information.
130475 */
130477  Parse *pParse = pWInfo->pParse;
130478  Vdbe *v = pParse->pVdbe;
130479  int i;
130480  WhereLevel *pLevel;
130481  WhereLoop *pLoop;
130482  SrcList *pTabList = pWInfo->pTabList;
130483  sqlite3 *db = pParse->db;
130484 
130485  /* Generate loop termination code.
130486  */
130487  VdbeModuleComment((v, "End WHERE-core"));
130488  sqlite3ExprCacheClear(pParse);
130489  for(i=pWInfo->nLevel-1; i>=0; i--){
130490  int addr;
130491  pLevel = &pWInfo->a[i];
130492  pLoop = pLevel->pWLoop;
130493  sqlite3VdbeResolveLabel(v, pLevel->addrCont);
130494  if( pLevel->op!=OP_Noop ){
130495  sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
130496  sqlite3VdbeChangeP5(v, pLevel->p5);
130497  VdbeCoverage(v);
130498  VdbeCoverageIf(v, pLevel->op==OP_Next);
130499  VdbeCoverageIf(v, pLevel->op==OP_Prev);
130500  VdbeCoverageIf(v, pLevel->op==OP_VNext);
130501  }
130502  if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
130503  struct InLoop *pIn;
130504  int j;
130505  sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
130506  for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
130507  sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
130508  sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
130509  VdbeCoverage(v);
130510  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
130511  VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
130512  sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
130513  }
130514  }
130515  sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
130516  if( pLevel->addrSkip ){
130517  sqlite3VdbeGoto(v, pLevel->addrSkip);
130518  VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
130519  sqlite3VdbeJumpHere(v, pLevel->addrSkip);
130520  sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
130521  }
130522 #ifndef SQLITE_LIKE_DOESNT_MATCH_BLOBS
130523  if( pLevel->addrLikeRep ){
130524  sqlite3VdbeAddOp2(v, OP_DecrJumpZero, (int)(pLevel->iLikeRepCntr>>1),
130525  pLevel->addrLikeRep);
130526  VdbeCoverage(v);
130527  }
130528 #endif
130529  if( pLevel->iLeftJoin ){
130530  addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
130531  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
130532  || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
130533  if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
130534  sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
130535  }
130536  if( pLoop->wsFlags & WHERE_INDEXED ){
130537  sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
130538  }
130539  if( pLevel->op==OP_Return ){
130540  sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
130541  }else{
130542  sqlite3VdbeGoto(v, pLevel->addrFirst);
130543  }
130544  sqlite3VdbeJumpHere(v, addr);
130545  }
130546  VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
130547  pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
130548  }
130549 
130550  /* The "break" point is here, just past the end of the outer loop.
130551  ** Set it.
130552  */
130553  sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
130554 
130555  assert( pWInfo->nLevel<=pTabList->nSrc );
130556  for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
130557  int k, last;
130558  VdbeOp *pOp;
130559  Index *pIdx = 0;
130560  struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
130561  Table *pTab = pTabItem->pTab;
130562  assert( pTab!=0 );
130563  pLoop = pLevel->pWLoop;
130564 
130565  /* For a co-routine, change all OP_Column references to the table of
130566  ** the co-routine into OP_Copy of result contained in a register.
130567  ** OP_Rowid becomes OP_Null.
130568  */
130569  if( pTabItem->fg.viaCoroutine && !db->mallocFailed ){
130570  translateColumnToCopy(v, pLevel->addrBody, pLevel->iTabCur,
130571  pTabItem->regResult, 0);
130572  continue;
130573  }
130574 
130575  /* Close all of the cursors that were opened by sqlite3WhereBegin.
130576  ** Except, do not close cursors that will be reused by the OR optimization
130577  ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
130578  ** created for the ONEPASS optimization.
130579  */
130580  if( (pTab->tabFlags & TF_Ephemeral)==0
130581  && pTab->pSelect==0
130582  && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
130583  ){
130584  int ws = pLoop->wsFlags;
130585  if( pWInfo->eOnePass==ONEPASS_OFF && (ws & WHERE_IDX_ONLY)==0 ){
130586  sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
130587  }
130588  if( (ws & WHERE_INDEXED)!=0
130589  && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
130590  && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
130591  ){
130592  sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
130593  }
130594  }
130595 
130596  /* If this scan uses an index, make VDBE code substitutions to read data
130597  ** from the index instead of from the table where possible. In some cases
130598  ** this optimization prevents the table from ever being read, which can
130599  ** yield a significant performance boost.
130600  **
130601  ** Calls to the code generator in between sqlite3WhereBegin and
130602  ** sqlite3WhereEnd will have created code that references the table
130603  ** directly. This loop scans all that code looking for opcodes
130604  ** that reference the table and converts them into opcodes that
130605  ** reference the index.
130606  */
130607  if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
130608  pIdx = pLoop->u.btree.pIndex;
130609  }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
130610  pIdx = pLevel->u.pCovidx;
130611  }
130612  if( pIdx
130613  && (pWInfo->eOnePass==ONEPASS_OFF || !HasRowid(pIdx->pTable))
130614  && !db->mallocFailed
130615  ){
130616  last = sqlite3VdbeCurrentAddr(v);
130617  k = pLevel->addrBody;
130618  pOp = sqlite3VdbeGetOp(v, k);
130619  for(; k<last; k++, pOp++){
130620  if( pOp->p1!=pLevel->iTabCur ) continue;
130621  if( pOp->opcode==OP_Column ){
130622  int x = pOp->p2;
130623  assert( pIdx->pTable==pTab );
130624  if( !HasRowid(pTab) ){
130625  Index *pPk = sqlite3PrimaryKeyIndex(pTab);
130626  x = pPk->aiColumn[x];
130627  assert( x>=0 );
130628  }
130629  x = sqlite3ColumnOfIndex(pIdx, x);
130630  if( x>=0 ){
130631  pOp->p2 = x;
130632  pOp->p1 = pLevel->iIdxCur;
130633  }
130634  assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
130635  }else if( pOp->opcode==OP_Rowid ){
130636  pOp->p1 = pLevel->iIdxCur;
130637  pOp->opcode = OP_IdxRowid;
130638  }
130639  }
130640  }
130641  }
130642 
130643  /* Final cleanup
130644  */
130645  pParse->nQueryLoop = pWInfo->savedNQueryLoop;
130646  whereInfoFree(db, pWInfo);
130647  return;
130648 }
130649 
130650 /************** End of where.c ***********************************************/
130651 /************** Begin file parse.c *******************************************/
130652 /*
130653 ** 2000-05-29
130654 **
130655 ** The author disclaims copyright to this source code. In place of
130656 ** a legal notice, here is a blessing:
130657 **
130658 ** May you do good and not evil.
130659 ** May you find forgiveness for yourself and forgive others.
130660 ** May you share freely, never taking more than you give.
130661 **
130662 *************************************************************************
130663 ** Driver template for the LEMON parser generator.
130664 **
130665 ** The "lemon" program processes an LALR(1) input grammar file, then uses
130666 ** this template to construct a parser. The "lemon" program inserts text
130667 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
130668 ** interstitial "-" characters) contained in this template is changed into
130669 ** the value of the %name directive from the grammar. Otherwise, the content
130670 ** of this template is copied straight through into the generate parser
130671 ** source file.
130672 **
130673 ** The following is the concatenation of all %include directives from the
130674 ** input grammar file:
130675 */
130676 /* #include <stdio.h> */
130677 /************ Begin %include sections from the grammar ************************/
130678 
130679 /* #include "sqliteInt.h" */
130680 
130681 /*
130682 ** Disable all error recovery processing in the parser push-down
130683 ** automaton.
130684 */
130685 #define YYNOERRORRECOVERY 1
130686 
130687 /*
130688 ** Make yytestcase() the same as testcase()
130689 */
130690 #define yytestcase(X) testcase(X)
130691 
130692 /*
130693 ** Indicate that sqlite3ParserFree() will never be called with a null
130694 ** pointer.
130695 */
130696 #define YYPARSEFREENEVERNULL 1
130697 
130698 /*
130699 ** Alternative datatype for the argument to the malloc() routine passed
130700 ** into sqlite3ParserAlloc(). The default is size_t.
130701 */
130702 #define YYMALLOCARGTYPE u64
130703 
130704 /*
130705 ** An instance of this structure holds information about the
130706 ** LIMIT clause of a SELECT statement.
130707 */
130708 struct LimitVal {
130709  Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
130710  Expr *pOffset; /* The OFFSET expression. NULL if there is none */
130711 };
130712 
130713 /*
130714 ** An instance of this structure is used to store the LIKE,
130715 ** GLOB, NOT LIKE, and NOT GLOB operators.
130716 */
130717 struct LikeOp {
130718  Token eOperator; /* "like" or "glob" or "regexp" */
130719  int bNot; /* True if the NOT keyword is present */
130720 };
130721 
130722 /*
130723 ** An instance of the following structure describes the event of a
130724 ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
130725 ** TK_DELETE, or TK_INSTEAD. If the event is of the form
130726 **
130727 ** UPDATE ON (a,b,c)
130728 **
130729 ** Then the "b" IdList records the list "a,b,c".
130730 */
130731 struct TrigEvent { int a; IdList * b; };
130732 
130733 /*
130734 ** An instance of this structure holds the ATTACH key and the key type.
130735 */
130736 struct AttachKey { int type; Token key; };
130737 
130738 /*
130739 ** Disable lookaside memory allocation for objects that might be
130740 ** shared across database connections.
130741 */
130742 static void disableLookaside(Parse *pParse){
130743  pParse->disableLookaside++;
130744  pParse->db->lookaside.bDisable++;
130745 }
130746 
130747 
130748  /*
130749  ** For a compound SELECT statement, make sure p->pPrior->pNext==p for
130750  ** all elements in the list. And make sure list length does not exceed
130751  ** SQLITE_LIMIT_COMPOUND_SELECT.
130752  */
130753  static void parserDoubleLinkSelect(Parse *pParse, Select *p){
130754  if( p->pPrior ){
130755  Select *pNext = 0, *pLoop;
130756  int mxSelect, cnt = 0;
130757  for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
130758  pLoop->pNext = pNext;
130759  pLoop->selFlags |= SF_Compound;
130760  }
130761  if( (p->selFlags & SF_MultiValue)==0 &&
130762  (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0 &&
130763  cnt>mxSelect
130764  ){
130765  sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
130766  }
130767  }
130768  }
130769 
130770  /* This is a utility routine used to set the ExprSpan.zStart and
130771  ** ExprSpan.zEnd values of pOut so that the span covers the complete
130772  ** range of text beginning with pStart and going to the end of pEnd.
130773  */
130774  static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
130775  pOut->zStart = pStart->z;
130776  pOut->zEnd = &pEnd->z[pEnd->n];
130777  }
130778 
130779  /* Construct a new Expr object from a single identifier. Use the
130780  ** new Expr to populate pOut. Set the span of pOut to be the identifier
130781  ** that created the expression.
130782  */
130783  static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t){
130784  pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, &t);
130785  pOut->zStart = t.z;
130786  pOut->zEnd = &t.z[t.n];
130787  }
130788 
130789  /* This routine constructs a binary expression node out of two ExprSpan
130790  ** objects and uses the result to populate a new ExprSpan object.
130791  */
130792  static void spanBinaryExpr(
130793  Parse *pParse, /* The parsing context. Errors accumulate here */
130794  int op, /* The binary operation */
130795  ExprSpan *pLeft, /* The left operand, and output */
130796  ExprSpan *pRight /* The right operand */
130797  ){
130798  pLeft->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
130799  pLeft->zEnd = pRight->zEnd;
130800  }
130801 
130802  /* If doNot is true, then add a TK_NOT Expr-node wrapper around the
130803  ** outside of *ppExpr.
130804  */
130805  static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan){
130806  if( doNot ){
130807  pSpan->pExpr = sqlite3PExpr(pParse, TK_NOT, pSpan->pExpr, 0, 0);
130808  }
130809  }
130810 
130811  /* Construct an expression node for a unary postfix operator
130812  */
130813  static void spanUnaryPostfix(
130814  Parse *pParse, /* Parsing context to record errors */
130815  int op, /* The operator */
130816  ExprSpan *pOperand, /* The operand, and output */
130817  Token *pPostOp /* The operand token for setting the span */
130818  ){
130819  pOperand->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
130820  pOperand->zEnd = &pPostOp->z[pPostOp->n];
130821  }
130822 
130823  /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
130824  ** unary TK_ISNULL or TK_NOTNULL expression. */
130825  static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
130826  sqlite3 *db = pParse->db;
130827  if( pA && pY && pY->op==TK_NULL ){
130828  pA->op = (u8)op;
130829  sqlite3ExprDelete(db, pA->pRight);
130830  pA->pRight = 0;
130831  }
130832  }
130833 
130834  /* Construct an expression node for a unary prefix operator
130835  */
130836  static void spanUnaryPrefix(
130837  ExprSpan *pOut, /* Write the new expression node here */
130838  Parse *pParse, /* Parsing context to record errors */
130839  int op, /* The operator */
130840  ExprSpan *pOperand, /* The operand */
130841  Token *pPreOp /* The operand token for setting the span */
130842  ){
130843  pOut->zStart = pPreOp->z;
130844  pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
130845  pOut->zEnd = pOperand->zEnd;
130846  }
130847 
130848  /* Add a single new term to an ExprList that is used to store a
130849  ** list of identifiers. Report an error if the ID list contains
130850  ** a COLLATE clause or an ASC or DESC keyword, except ignore the
130851  ** error while parsing a legacy schema.
130852  */
130854  Parse *pParse,
130855  ExprList *pPrior,
130856  Token *pIdToken,
130857  int hasCollate,
130858  int sortOrder
130859  ){
130860  ExprList *p = sqlite3ExprListAppend(pParse, pPrior, 0);
130861  if( (hasCollate || sortOrder!=SQLITE_SO_UNDEFINED)
130862  && pParse->db->init.busy==0
130863  ){
130864  sqlite3ErrorMsg(pParse, "syntax error after column name \"%.*s\"",
130865  pIdToken->n, pIdToken->z);
130866  }
130867  sqlite3ExprListSetName(pParse, p, pIdToken, 1);
130868  return p;
130869  }
130870 /**************** End of %include directives **********************************/
130871 /* These constants specify the various numeric values for terminal symbols
130872 ** in a format understandable to "makeheaders". This section is blank unless
130873 ** "lemon" is run with the "-m" command-line option.
130874 ***************** Begin makeheaders token definitions *************************/
130875 /**************** End makeheaders token definitions ***************************/
130876 
130877 /* The next sections is a series of control #defines.
130878 ** various aspects of the generated parser.
130879 ** YYCODETYPE is the data type used to store the integer codes
130880 ** that represent terminal and non-terminal symbols.
130881 ** "unsigned char" is used if there are fewer than
130882 ** 256 symbols. Larger types otherwise.
130883 ** YYNOCODE is a number of type YYCODETYPE that is not used for
130884 ** any terminal or nonterminal symbol.
130885 ** YYFALLBACK If defined, this indicates that one or more tokens
130886 ** (also known as: "terminal symbols") have fall-back
130887 ** values which should be used if the original symbol
130888 ** would not parse. This permits keywords to sometimes
130889 ** be used as identifiers, for example.
130890 ** YYACTIONTYPE is the data type used for "action codes" - numbers
130891 ** that indicate what to do in response to the next
130892 ** token.
130893 ** sqlite3ParserTOKENTYPE is the data type used for minor type for terminal
130894 ** symbols. Background: A "minor type" is a semantic
130895 ** value associated with a terminal or non-terminal
130896 ** symbols. For example, for an "ID" terminal symbol,
130897 ** the minor type might be the name of the identifier.
130898 ** Each non-terminal can have a different minor type.
130899 ** Terminal symbols all have the same minor type, though.
130900 ** This macros defines the minor type for terminal
130901 ** symbols.
130902 ** YYMINORTYPE is the data type used for all minor types.
130903 ** This is typically a union of many types, one of
130904 ** which is sqlite3ParserTOKENTYPE. The entry in the union
130905 ** for terminal symbols is called "yy0".
130906 ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
130907 ** zero the stack is dynamically sized using realloc()
130908 ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
130909 ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
130910 ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
130911 ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
130912 ** YYERRORSYMBOL is the code number of the error symbol. If not
130913 ** defined, then do no error processing.
130914 ** YYNSTATE the combined number of states.
130915 ** YYNRULE the number of rules in the grammar
130916 ** YY_MAX_SHIFT Maximum value for shift actions
130917 ** YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
130918 ** YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
130919 ** YY_MIN_REDUCE Maximum value for reduce actions
130920 ** YY_ERROR_ACTION The yy_action[] code for syntax error
130921 ** YY_ACCEPT_ACTION The yy_action[] code for accept
130922 ** YY_NO_ACTION The yy_action[] code for no-op
130923 */
130924 #ifndef INTERFACE
130925 # define INTERFACE 1
130926 #endif
130927 /************* Begin control #defines *****************************************/
130928 #define YYCODETYPE unsigned char
130929 #define YYNOCODE 251
130930 #define YYACTIONTYPE unsigned short int
130931 #define YYWILDCARD 96
130932 #define sqlite3ParserTOKENTYPE Token
130933 typedef union {
130934  int yyinit;
130936  struct LimitVal yy64;
130940  struct {int value; int mask;} yy207;
130941  struct LikeOp yy318;
130946  int yy392;
130947  struct TrigEvent yy410;
130949 } YYMINORTYPE;
130950 #ifndef YYSTACKDEPTH
130951 #define YYSTACKDEPTH 100
130952 #endif
130953 #define sqlite3ParserARG_SDECL Parse *pParse;
130954 #define sqlite3ParserARG_PDECL ,Parse *pParse
130955 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
130956 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
130957 #define YYFALLBACK 1
130958 #define YYNSTATE 440
130959 #define YYNRULE 326
130960 #define YY_MAX_SHIFT 439
130961 #define YY_MIN_SHIFTREDUCE 649
130962 #define YY_MAX_SHIFTREDUCE 974
130963 #define YY_MIN_REDUCE 975
130964 #define YY_MAX_REDUCE 1300
130965 #define YY_ERROR_ACTION 1301
130966 #define YY_ACCEPT_ACTION 1302
130967 #define YY_NO_ACTION 1303
130968 /************* End control #defines *******************************************/
130969 
130970 /* Define the yytestcase() macro to be a no-op if is not already defined
130971 ** otherwise.
130972 **
130973 ** Applications can choose to define yytestcase() in the %include section
130974 ** to a macro that can assist in verifying code coverage. For production
130975 ** code the yytestcase() macro should be turned off. But it is useful
130976 ** for testing.
130977 */
130978 #ifndef yytestcase
130979 # define yytestcase(X)
130980 #endif
130981 
130982 
130983 /* Next are the tables used to determine what action to take based on the
130984 ** current state and lookahead token. These tables are used to implement
130985 ** functions that take a state number and lookahead value and return an
130986 ** action integer.
130987 **
130988 ** Suppose the action integer is N. Then the action is determined as
130989 ** follows
130990 **
130991 ** 0 <= N <= YY_MAX_SHIFT Shift N. That is, push the lookahead
130992 ** token onto the stack and goto state N.
130993 **
130994 ** N between YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
130995 ** and YY_MAX_SHIFTREDUCE reduce by rule N-YY_MIN_SHIFTREDUCE.
130996 **
130997 ** N between YY_MIN_REDUCE Reduce by rule N-YY_MIN_REDUCE
130998 ** and YY_MAX_REDUCE
130999 
131000 ** N == YY_ERROR_ACTION A syntax error has occurred.
131001 **
131002 ** N == YY_ACCEPT_ACTION The parser accepts its input.
131003 **
131004 ** N == YY_NO_ACTION No such action. Denotes unused
131005 ** slots in the yy_action[] table.
131006 **
131007 ** The action table is constructed as a single large table named yy_action[].
131008 ** Given state S and lookahead X, the action is computed as
131009 **
131010 ** yy_action[ yy_shift_ofst[S] + X ]
131011 **
131012 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
131013 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
131014 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
131015 ** and that yy_default[S] should be used instead.
131016 **
131017 ** The formula above is for computing the action when the lookahead is
131018 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
131019 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
131020 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
131021 ** YY_SHIFT_USE_DFLT.
131022 **
131023 ** The following are the tables generated in this section:
131024 **
131025 ** yy_action[] A single table containing all actions.
131026 ** yy_lookahead[] A table containing the lookahead for each entry in
131027 ** yy_action. Used to detect hash collisions.
131028 ** yy_shift_ofst[] For each state, the offset into yy_action for
131029 ** shifting terminals.
131030 ** yy_reduce_ofst[] For each state, the offset into yy_action for
131031 ** shifting non-terminals after a reduce.
131032 ** yy_default[] Default action for each state.
131033 **
131034 *********** Begin parsing tables **********************************************/
131035 #define YY_ACTTAB_COUNT (1501)
131036 static const YYACTIONTYPE yy_action[] = {
131037  /* 0 */ 315, 810, 339, 804, 5, 194, 194, 798, 92, 93,
131038  /* 10 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131039  /* 20 */ 91, 91, 91, 290, 89, 89, 89, 89, 88, 88,
131040  /* 30 */ 87, 87, 87, 86, 339, 315, 952, 952, 803, 803,
131041  /* 40 */ 803, 922, 342, 92, 93, 83, 819, 819, 831, 834,
131042  /* 50 */ 823, 823, 90, 90, 91, 91, 91, 91, 123, 89,
131043  /* 60 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131044  /* 70 */ 88, 88, 87, 87, 87, 86, 339, 772, 952, 952,
131045  /* 80 */ 315, 87, 87, 87, 86, 339, 773, 68, 92, 93,
131046  /* 90 */ 83, 819, 819, 831, 834, 823, 823, 90, 90, 91,
131047  /* 100 */ 91, 91, 91, 434, 89, 89, 89, 89, 88, 88,
131048  /* 110 */ 87, 87, 87, 86, 339, 1302, 146, 921, 2, 315,
131049  /* 120 */ 427, 24, 679, 953, 48, 86, 339, 92, 93, 83,
131050  /* 130 */ 819, 819, 831, 834, 823, 823, 90, 90, 91, 91,
131051  /* 140 */ 91, 91, 94, 89, 89, 89, 89, 88, 88, 87,
131052  /* 150 */ 87, 87, 86, 339, 933, 933, 315, 259, 412, 398,
131053  /* 160 */ 396, 57, 733, 733, 92, 93, 83, 819, 819, 831,
131054  /* 170 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 56,
131055  /* 180 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131056  /* 190 */ 339, 315, 1245, 922, 342, 268, 934, 935, 241, 92,
131057  /* 200 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131058  /* 210 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131059  /* 220 */ 88, 87, 87, 87, 86, 339, 315, 913, 1295, 682,
131060  /* 230 */ 687, 1295, 233, 397, 92, 93, 83, 819, 819, 831,
131061  /* 240 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 326,
131062  /* 250 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131063  /* 260 */ 339, 315, 85, 82, 168, 680, 431, 938, 939, 92,
131064  /* 270 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131065  /* 280 */ 91, 91, 91, 91, 291, 89, 89, 89, 89, 88,
131066  /* 290 */ 88, 87, 87, 87, 86, 339, 315, 319, 913, 1296,
131067  /* 300 */ 797, 911, 1296, 681, 92, 93, 83, 819, 819, 831,
131068  /* 310 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 335,
131069  /* 320 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131070  /* 330 */ 339, 315, 876, 876, 373, 85, 82, 168, 944, 92,
131071  /* 340 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131072  /* 350 */ 91, 91, 91, 91, 896, 89, 89, 89, 89, 88,
131073  /* 360 */ 88, 87, 87, 87, 86, 339, 315, 370, 307, 973,
131074  /* 370 */ 367, 1, 911, 433, 92, 93, 83, 819, 819, 831,
131075  /* 380 */ 834, 823, 823, 90, 90, 91, 91, 91, 91, 189,
131076  /* 390 */ 89, 89, 89, 89, 88, 88, 87, 87, 87, 86,
131077  /* 400 */ 339, 315, 720, 948, 933, 933, 149, 718, 948, 92,
131078  /* 410 */ 93, 83, 819, 819, 831, 834, 823, 823, 90, 90,
131079  /* 420 */ 91, 91, 91, 91, 434, 89, 89, 89, 89, 88,
131080  /* 430 */ 88, 87, 87, 87, 86, 339, 338, 938, 939, 947,
131081  /* 440 */ 694, 940, 974, 315, 953, 48, 934, 935, 715, 689,
131082  /* 450 */ 71, 92, 93, 83, 819, 819, 831, 834, 823, 823,
131083  /* 460 */ 90, 90, 91, 91, 91, 91, 320, 89, 89, 89,
131084  /* 470 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 412,
131085  /* 480 */ 403, 820, 820, 832, 835, 74, 92, 81, 83, 819,
131086  /* 490 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131087  /* 500 */ 91, 698, 89, 89, 89, 89, 88, 88, 87, 87,
131088  /* 510 */ 87, 86, 339, 315, 259, 654, 655, 656, 393, 111,
131089  /* 520 */ 331, 153, 93, 83, 819, 819, 831, 834, 823, 823,
131090  /* 530 */ 90, 90, 91, 91, 91, 91, 434, 89, 89, 89,
131091  /* 540 */ 89, 88, 88, 87, 87, 87, 86, 339, 315, 188,
131092  /* 550 */ 187, 186, 824, 937, 328, 219, 953, 48, 83, 819,
131093  /* 560 */ 819, 831, 834, 823, 823, 90, 90, 91, 91, 91,
131094  /* 570 */ 91, 956, 89, 89, 89, 89, 88, 88, 87, 87,
131095  /* 580 */ 87, 86, 339, 79, 429, 738, 3, 1174, 955, 348,
131096  /* 590 */ 737, 332, 792, 933, 933, 937, 79, 429, 730, 3,
131097  /* 600 */ 203, 160, 278, 391, 273, 390, 190, 892, 434, 400,
131098  /* 610 */ 741, 76, 77, 271, 287, 253, 353, 242, 78, 340,
131099  /* 620 */ 340, 85, 82, 168, 76, 77, 233, 397, 953, 48,
131100  /* 630 */ 432, 78, 340, 340, 277, 934, 935, 185, 439, 651,
131101  /* 640 */ 388, 385, 384, 432, 234, 276, 107, 418, 349, 337,
131102  /* 650 */ 336, 383, 893, 728, 215, 949, 123, 971, 308, 810,
131103  /* 660 */ 418, 436, 435, 412, 394, 798, 400, 873, 894, 123,
131104  /* 670 */ 721, 872, 810, 889, 436, 435, 215, 949, 798, 351,
131105  /* 680 */ 722, 697, 380, 434, 771, 371, 22, 434, 400, 79,
131106  /* 690 */ 429, 232, 3, 189, 413, 870, 803, 803, 803, 805,
131107  /* 700 */ 18, 54, 148, 953, 48, 956, 113, 953, 9, 803,
131108  /* 710 */ 803, 803, 805, 18, 310, 123, 748, 76, 77, 742,
131109  /* 720 */ 123, 325, 955, 866, 78, 340, 340, 113, 350, 359,
131110  /* 730 */ 85, 82, 168, 343, 960, 960, 432, 770, 412, 414,
131111  /* 740 */ 407, 23, 1240, 1240, 79, 429, 357, 3, 166, 91,
131112  /* 750 */ 91, 91, 91, 418, 89, 89, 89, 89, 88, 88,
131113  /* 760 */ 87, 87, 87, 86, 339, 810, 434, 436, 435, 792,
131114  /* 770 */ 320, 798, 76, 77, 789, 271, 123, 434, 360, 78,
131115  /* 780 */ 340, 340, 864, 85, 82, 168, 953, 9, 395, 743,
131116  /* 790 */ 360, 432, 253, 358, 252, 933, 933, 953, 30, 889,
131117  /* 800 */ 327, 216, 803, 803, 803, 805, 18, 113, 418, 89,
131118  /* 810 */ 89, 89, 89, 88, 88, 87, 87, 87, 86, 339,
131119  /* 820 */ 810, 113, 436, 435, 792, 185, 798, 288, 388, 385,
131120  /* 830 */ 384, 123, 113, 920, 2, 796, 696, 934, 935, 383,
131121  /* 840 */ 69, 429, 434, 3, 218, 110, 738, 253, 358, 252,
131122  /* 850 */ 434, 737, 933, 933, 892, 359, 222, 803, 803, 803,
131123  /* 860 */ 805, 18, 953, 47, 933, 933, 933, 933, 76, 77,
131124  /* 870 */ 953, 9, 366, 904, 217, 78, 340, 340, 677, 305,
131125  /* 880 */ 304, 303, 206, 301, 224, 259, 664, 432, 337, 336,
131126  /* 890 */ 434, 228, 247, 144, 934, 935, 933, 933, 667, 893,
131127  /* 900 */ 324, 1259, 96, 434, 418, 796, 934, 935, 934, 935,
131128  /* 910 */ 953, 48, 401, 148, 289, 894, 810, 417, 436, 435,
131129  /* 920 */ 677, 759, 798, 953, 9, 314, 220, 162, 161, 170,
131130  /* 930 */ 402, 239, 953, 8, 194, 683, 683, 410, 934, 935,
131131  /* 940 */ 238, 959, 933, 933, 225, 408, 945, 365, 957, 212,
131132  /* 950 */ 958, 172, 757, 803, 803, 803, 805, 18, 173, 365,
131133  /* 960 */ 176, 123, 171, 113, 244, 952, 246, 434, 356, 796,
131134  /* 970 */ 372, 365, 236, 960, 960, 810, 290, 804, 191, 165,
131135  /* 980 */ 852, 798, 259, 316, 934, 935, 237, 953, 34, 404,
131136  /* 990 */ 91, 91, 91, 91, 84, 89, 89, 89, 89, 88,
131137  /* 1000 */ 88, 87, 87, 87, 86, 339, 701, 952, 434, 240,
131138  /* 1010 */ 347, 758, 803, 803, 803, 434, 245, 1179, 434, 389,
131139  /* 1020 */ 434, 376, 434, 895, 167, 434, 405, 702, 953, 35,
131140  /* 1030 */ 673, 321, 221, 434, 333, 953, 11, 434, 953, 26,
131141  /* 1040 */ 953, 36, 953, 37, 251, 953, 38, 434, 259, 434,
131142  /* 1050 */ 757, 434, 329, 953, 27, 434, 223, 953, 28, 434,
131143  /* 1060 */ 690, 434, 67, 434, 65, 434, 862, 953, 39, 953,
131144  /* 1070 */ 40, 953, 41, 423, 434, 953, 10, 434, 772, 953,
131145  /* 1080 */ 42, 953, 98, 953, 43, 953, 44, 773, 434, 346,
131146  /* 1090 */ 434, 75, 434, 73, 953, 31, 434, 953, 45, 434,
131147  /* 1100 */ 259, 434, 690, 434, 757, 434, 887, 434, 953, 46,
131148  /* 1110 */ 953, 32, 953, 115, 434, 266, 953, 116, 951, 953,
131149  /* 1120 */ 117, 953, 52, 953, 33, 953, 99, 953, 49, 726,
131150  /* 1130 */ 434, 909, 434, 19, 953, 100, 434, 344, 434, 113,
131151  /* 1140 */ 434, 258, 692, 434, 259, 434, 670, 434, 20, 434,
131152  /* 1150 */ 953, 101, 953, 97, 434, 259, 953, 114, 953, 112,
131153  /* 1160 */ 953, 105, 113, 953, 104, 953, 102, 953, 103, 953,
131154  /* 1170 */ 51, 434, 148, 434, 953, 53, 167, 434, 259, 113,
131155  /* 1180 */ 300, 307, 912, 363, 311, 860, 248, 261, 209, 264,
131156  /* 1190 */ 416, 953, 50, 953, 25, 420, 727, 953, 29, 430,
131157  /* 1200 */ 321, 424, 757, 428, 322, 124, 1269, 214, 165, 710,
131158  /* 1210 */ 859, 908, 806, 794, 309, 158, 193, 361, 254, 723,
131159  /* 1220 */ 364, 67, 381, 269, 735, 199, 67, 70, 113, 700,
131160  /* 1230 */ 699, 707, 708, 884, 113, 766, 113, 855, 193, 883,
131161  /* 1240 */ 199, 869, 869, 675, 868, 868, 109, 368, 255, 260,
131162  /* 1250 */ 263, 280, 859, 265, 806, 974, 267, 711, 695, 272,
131163  /* 1260 */ 764, 282, 795, 284, 150, 744, 755, 415, 292, 293,
131164  /* 1270 */ 802, 678, 672, 661, 660, 662, 927, 6, 306, 386,
131165  /* 1280 */ 352, 786, 243, 250, 886, 362, 163, 286, 419, 298,
131166  /* 1290 */ 930, 159, 968, 196, 126, 903, 901, 965, 55, 58,
131167  /* 1300 */ 323, 275, 857, 136, 147, 694, 856, 121, 65, 354,
131168  /* 1310 */ 355, 379, 175, 61, 151, 369, 180, 871, 375, 129,
131169  /* 1320 */ 257, 756, 210, 181, 145, 131, 132, 377, 262, 663,
131170  /* 1330 */ 133, 134, 139, 783, 791, 182, 392, 183, 312, 330,
131171  /* 1340 */ 714, 888, 713, 851, 692, 195, 712, 406, 686, 705,
131172  /* 1350 */ 313, 685, 64, 839, 274, 72, 684, 334, 942, 95,
131173  /* 1360 */ 752, 279, 281, 704, 753, 751, 422, 283, 411, 750,
131174  /* 1370 */ 426, 66, 204, 409, 21, 285, 928, 669, 437, 205,
131175  /* 1380 */ 207, 208, 438, 658, 657, 652, 118, 108, 119, 226,
131176  /* 1390 */ 650, 341, 157, 235, 169, 345, 106, 734, 790, 296,
131177  /* 1400 */ 294, 295, 120, 297, 867, 865, 127, 128, 130, 724,
131178  /* 1410 */ 229, 174, 249, 882, 137, 230, 138, 135, 885, 231,
131179  /* 1420 */ 59, 60, 177, 881, 7, 178, 12, 179, 256, 874,
131180  /* 1430 */ 140, 193, 962, 374, 141, 152, 666, 378, 276, 184,
131181  /* 1440 */ 270, 122, 142, 382, 387, 62, 13, 14, 703, 63,
131182  /* 1450 */ 125, 317, 318, 227, 809, 808, 837, 732, 15, 164,
131183  /* 1460 */ 736, 4, 765, 211, 399, 213, 192, 143, 760, 70,
131184  /* 1470 */ 67, 16, 17, 838, 836, 891, 841, 890, 198, 197,
131185  /* 1480 */ 917, 154, 421, 923, 918, 155, 200, 977, 425, 840,
131186  /* 1490 */ 156, 201, 807, 676, 80, 302, 299, 977, 202, 1261,
131187  /* 1500 */ 1260,
131188 };
131189 static const YYCODETYPE yy_lookahead[] = {
131190  /* 0 */ 19, 95, 53, 97, 22, 24, 24, 101, 27, 28,
131191  /* 10 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131192  /* 20 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131193  /* 30 */ 49, 50, 51, 52, 53, 19, 55, 55, 132, 133,
131194  /* 40 */ 134, 1, 2, 27, 28, 29, 30, 31, 32, 33,
131195  /* 50 */ 34, 35, 36, 37, 38, 39, 40, 41, 92, 43,
131196  /* 60 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131197  /* 70 */ 47, 48, 49, 50, 51, 52, 53, 61, 97, 97,
131198  /* 80 */ 19, 49, 50, 51, 52, 53, 70, 26, 27, 28,
131199  /* 90 */ 29, 30, 31, 32, 33, 34, 35, 36, 37, 38,
131200  /* 100 */ 39, 40, 41, 152, 43, 44, 45, 46, 47, 48,
131201  /* 110 */ 49, 50, 51, 52, 53, 144, 145, 146, 147, 19,
131202  /* 120 */ 249, 22, 172, 172, 173, 52, 53, 27, 28, 29,
131203  /* 130 */ 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
131204  /* 140 */ 40, 41, 81, 43, 44, 45, 46, 47, 48, 49,
131205  /* 150 */ 50, 51, 52, 53, 55, 56, 19, 152, 207, 208,
131206  /* 160 */ 115, 24, 117, 118, 27, 28, 29, 30, 31, 32,
131207  /* 170 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 79,
131208  /* 180 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131209  /* 190 */ 53, 19, 0, 1, 2, 23, 97, 98, 193, 27,
131210  /* 200 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131211  /* 210 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131212  /* 220 */ 48, 49, 50, 51, 52, 53, 19, 22, 23, 172,
131213  /* 230 */ 23, 26, 119, 120, 27, 28, 29, 30, 31, 32,
131214  /* 240 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131215  /* 250 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131216  /* 260 */ 53, 19, 221, 222, 223, 23, 168, 169, 170, 27,
131217  /* 270 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131218  /* 280 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131219  /* 290 */ 48, 49, 50, 51, 52, 53, 19, 157, 22, 23,
131220  /* 300 */ 23, 96, 26, 172, 27, 28, 29, 30, 31, 32,
131221  /* 310 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 187,
131222  /* 320 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131223  /* 330 */ 53, 19, 108, 109, 110, 221, 222, 223, 185, 27,
131224  /* 340 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131225  /* 350 */ 38, 39, 40, 41, 240, 43, 44, 45, 46, 47,
131226  /* 360 */ 48, 49, 50, 51, 52, 53, 19, 227, 22, 23,
131227  /* 370 */ 230, 22, 96, 152, 27, 28, 29, 30, 31, 32,
131228  /* 380 */ 33, 34, 35, 36, 37, 38, 39, 40, 41, 30,
131229  /* 390 */ 43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
131230  /* 400 */ 53, 19, 190, 191, 55, 56, 24, 190, 191, 27,
131231  /* 410 */ 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
131232  /* 420 */ 38, 39, 40, 41, 152, 43, 44, 45, 46, 47,
131233  /* 430 */ 48, 49, 50, 51, 52, 53, 168, 169, 170, 179,
131234  /* 440 */ 180, 171, 96, 19, 172, 173, 97, 98, 188, 179,
131235  /* 450 */ 138, 27, 28, 29, 30, 31, 32, 33, 34, 35,
131236  /* 460 */ 36, 37, 38, 39, 40, 41, 107, 43, 44, 45,
131237  /* 470 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 207,
131238  /* 480 */ 208, 30, 31, 32, 33, 138, 27, 28, 29, 30,
131239  /* 490 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131240  /* 500 */ 41, 181, 43, 44, 45, 46, 47, 48, 49, 50,
131241  /* 510 */ 51, 52, 53, 19, 152, 7, 8, 9, 49, 22,
131242  /* 520 */ 19, 24, 28, 29, 30, 31, 32, 33, 34, 35,
131243  /* 530 */ 36, 37, 38, 39, 40, 41, 152, 43, 44, 45,
131244  /* 540 */ 46, 47, 48, 49, 50, 51, 52, 53, 19, 108,
131245  /* 550 */ 109, 110, 101, 55, 53, 193, 172, 173, 29, 30,
131246  /* 560 */ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
131247  /* 570 */ 41, 152, 43, 44, 45, 46, 47, 48, 49, 50,
131248  /* 580 */ 51, 52, 53, 19, 20, 116, 22, 23, 169, 170,
131249  /* 590 */ 121, 207, 85, 55, 56, 97, 19, 20, 195, 22,
131250  /* 600 */ 99, 100, 101, 102, 103, 104, 105, 12, 152, 206,
131251  /* 610 */ 210, 47, 48, 112, 152, 108, 109, 110, 54, 55,
131252  /* 620 */ 56, 221, 222, 223, 47, 48, 119, 120, 172, 173,
131253  /* 630 */ 66, 54, 55, 56, 101, 97, 98, 99, 148, 149,
131254  /* 640 */ 102, 103, 104, 66, 154, 112, 156, 83, 229, 47,
131255  /* 650 */ 48, 113, 57, 163, 194, 195, 92, 246, 247, 95,
131256  /* 660 */ 83, 97, 98, 207, 208, 101, 206, 59, 73, 92,
131257  /* 670 */ 75, 63, 95, 163, 97, 98, 194, 195, 101, 219,
131258  /* 680 */ 85, 181, 19, 152, 175, 77, 196, 152, 206, 19,
131259  /* 690 */ 20, 199, 22, 30, 163, 11, 132, 133, 134, 135,
131260  /* 700 */ 136, 209, 152, 172, 173, 152, 196, 172, 173, 132,
131261  /* 710 */ 133, 134, 135, 136, 164, 92, 213, 47, 48, 49,
131262  /* 720 */ 92, 186, 169, 170, 54, 55, 56, 196, 100, 219,
131263  /* 730 */ 221, 222, 223, 243, 132, 133, 66, 175, 207, 208,
131264  /* 740 */ 152, 231, 119, 120, 19, 20, 236, 22, 152, 38,
131265  /* 750 */ 39, 40, 41, 83, 43, 44, 45, 46, 47, 48,
131266  /* 760 */ 49, 50, 51, 52, 53, 95, 152, 97, 98, 85,
131267  /* 770 */ 107, 101, 47, 48, 163, 112, 92, 152, 152, 54,
131268  /* 780 */ 55, 56, 229, 221, 222, 223, 172, 173, 163, 49,
131269  /* 790 */ 152, 66, 108, 109, 110, 55, 56, 172, 173, 163,
131270  /* 800 */ 186, 22, 132, 133, 134, 135, 136, 196, 83, 43,
131271  /* 810 */ 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
131272  /* 820 */ 95, 196, 97, 98, 85, 99, 101, 152, 102, 103,
131273  /* 830 */ 104, 92, 196, 146, 147, 152, 181, 97, 98, 113,
131274  /* 840 */ 19, 20, 152, 22, 218, 22, 116, 108, 109, 110,
131275  /* 850 */ 152, 121, 55, 56, 12, 219, 218, 132, 133, 134,
131276  /* 860 */ 135, 136, 172, 173, 55, 56, 55, 56, 47, 48,
131277  /* 870 */ 172, 173, 236, 152, 5, 54, 55, 56, 55, 10,
131278  /* 880 */ 11, 12, 13, 14, 186, 152, 17, 66, 47, 48,
131279  /* 890 */ 152, 210, 16, 84, 97, 98, 55, 56, 21, 57,
131280  /* 900 */ 217, 122, 22, 152, 83, 152, 97, 98, 97, 98,
131281  /* 910 */ 172, 173, 152, 152, 224, 73, 95, 75, 97, 98,
131282  /* 920 */ 97, 124, 101, 172, 173, 164, 193, 47, 48, 60,
131283  /* 930 */ 163, 62, 172, 173, 24, 55, 56, 186, 97, 98,
131284  /* 940 */ 71, 100, 55, 56, 183, 207, 185, 152, 107, 23,
131285  /* 950 */ 109, 82, 26, 132, 133, 134, 135, 136, 89, 152,
131286  /* 960 */ 26, 92, 93, 196, 88, 55, 90, 152, 91, 152,
131287  /* 970 */ 217, 152, 152, 132, 133, 95, 152, 97, 211, 212,
131288  /* 980 */ 103, 101, 152, 114, 97, 98, 152, 172, 173, 19,
131289  /* 990 */ 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
131290  /* 1000 */ 48, 49, 50, 51, 52, 53, 65, 97, 152, 152,
131291  /* 1010 */ 141, 124, 132, 133, 134, 152, 140, 140, 152, 78,
131292  /* 1020 */ 152, 233, 152, 193, 98, 152, 56, 86, 172, 173,
131293  /* 1030 */ 166, 167, 237, 152, 217, 172, 173, 152, 172, 173,
131294  /* 1040 */ 172, 173, 172, 173, 237, 172, 173, 152, 152, 152,
131295  /* 1050 */ 124, 152, 111, 172, 173, 152, 237, 172, 173, 152,
131296  /* 1060 */ 55, 152, 26, 152, 130, 152, 152, 172, 173, 172,
131297  /* 1070 */ 173, 172, 173, 249, 152, 172, 173, 152, 61, 172,
131298  /* 1080 */ 173, 172, 173, 172, 173, 172, 173, 70, 152, 193,
131299  /* 1090 */ 152, 137, 152, 139, 172, 173, 152, 172, 173, 152,
131300  /* 1100 */ 152, 152, 97, 152, 26, 152, 163, 152, 172, 173,
131301  /* 1110 */ 172, 173, 172, 173, 152, 16, 172, 173, 26, 172,
131302  /* 1120 */ 173, 172, 173, 172, 173, 172, 173, 172, 173, 163,
131303  /* 1130 */ 152, 152, 152, 22, 172, 173, 152, 241, 152, 196,
131304  /* 1140 */ 152, 193, 106, 152, 152, 152, 163, 152, 37, 152,
131305  /* 1150 */ 172, 173, 172, 173, 152, 152, 172, 173, 172, 173,
131306  /* 1160 */ 172, 173, 196, 172, 173, 172, 173, 172, 173, 172,
131307  /* 1170 */ 173, 152, 152, 152, 172, 173, 98, 152, 152, 196,
131308  /* 1180 */ 160, 22, 23, 19, 164, 193, 152, 88, 232, 90,
131309  /* 1190 */ 191, 172, 173, 172, 173, 163, 193, 172, 173, 166,
131310  /* 1200 */ 167, 163, 124, 163, 244, 245, 23, 211, 212, 26,
131311  /* 1210 */ 55, 23, 55, 23, 26, 123, 26, 152, 23, 193,
131312  /* 1220 */ 56, 26, 23, 23, 23, 26, 26, 26, 196, 100,
131313  /* 1230 */ 101, 7, 8, 152, 196, 23, 196, 23, 26, 152,
131314  /* 1240 */ 26, 132, 133, 23, 132, 133, 26, 152, 152, 152,
131315  /* 1250 */ 152, 210, 97, 152, 97, 96, 152, 152, 152, 152,
131316  /* 1260 */ 152, 210, 152, 210, 197, 152, 152, 152, 152, 152,
131317  /* 1270 */ 152, 152, 152, 152, 152, 152, 152, 198, 150, 176,
131318  /* 1280 */ 214, 201, 214, 238, 201, 238, 184, 214, 226, 200,
131319  /* 1290 */ 155, 198, 67, 122, 242, 159, 159, 69, 239, 239,
131320  /* 1300 */ 159, 175, 175, 22, 220, 180, 175, 27, 130, 18,
131321  /* 1310 */ 159, 18, 158, 137, 220, 159, 158, 235, 74, 189,
131322  /* 1320 */ 234, 159, 159, 158, 22, 192, 192, 177, 159, 159,
131323  /* 1330 */ 192, 192, 189, 201, 189, 158, 107, 158, 177, 76,
131324  /* 1340 */ 174, 201, 174, 201, 106, 159, 174, 125, 174, 182,
131325  /* 1350 */ 177, 176, 107, 159, 174, 137, 174, 53, 174, 129,
131326  /* 1360 */ 216, 215, 215, 182, 216, 216, 177, 215, 126, 216,
131327  /* 1370 */ 177, 128, 25, 127, 26, 215, 13, 162, 161, 153,
131328  /* 1380 */ 153, 6, 151, 151, 151, 151, 165, 178, 165, 178,
131329  /* 1390 */ 4, 3, 22, 142, 15, 94, 16, 205, 120, 202,
131330  /* 1400 */ 204, 203, 165, 201, 23, 23, 131, 111, 123, 20,
131331  /* 1410 */ 225, 125, 16, 1, 131, 228, 111, 123, 56, 228,
131332  /* 1420 */ 37, 37, 64, 1, 5, 122, 22, 107, 140, 80,
131333  /* 1430 */ 80, 26, 87, 72, 107, 24, 20, 19, 112, 105,
131334  /* 1440 */ 23, 68, 22, 79, 79, 22, 22, 22, 58, 22,
131335  /* 1450 */ 245, 248, 248, 79, 23, 23, 23, 116, 22, 122,
131336  /* 1460 */ 23, 22, 56, 23, 26, 23, 64, 22, 124, 26,
131337  /* 1470 */ 26, 64, 64, 23, 23, 23, 11, 23, 22, 26,
131338  /* 1480 */ 23, 22, 24, 1, 23, 22, 26, 250, 24, 23,
131339  /* 1490 */ 22, 122, 23, 23, 22, 15, 23, 250, 122, 122,
131340  /* 1500 */ 122,
131341 };
131342 #define YY_SHIFT_USE_DFLT (-95)
131343 #define YY_SHIFT_COUNT (439)
131344 #define YY_SHIFT_MIN (-94)
131345 #define YY_SHIFT_MAX (1482)
131346 static const short yy_shift_ofst[] = {
131347  /* 0 */ 40, 564, 869, 577, 725, 725, 725, 739, -19, 16,
131348  /* 10 */ 16, 100, 725, 725, 725, 725, 725, 725, 725, 841,
131349  /* 20 */ 841, 538, 507, 684, 623, 61, 137, 172, 207, 242,
131350  /* 30 */ 277, 312, 347, 382, 424, 424, 424, 424, 424, 424,
131351  /* 40 */ 424, 424, 424, 424, 424, 424, 424, 424, 424, 459,
131352  /* 50 */ 424, 494, 529, 529, 670, 725, 725, 725, 725, 725,
131353  /* 60 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131354  /* 70 */ 725, 725, 725, 725, 725, 725, 725, 725, 725, 725,
131355  /* 80 */ 725, 725, 725, 821, 725, 725, 725, 725, 725, 725,
131356  /* 90 */ 725, 725, 725, 725, 725, 725, 725, 952, 711, 711,
131357  /* 100 */ 711, 711, 711, 766, 23, 32, 811, 877, 663, 602,
131358  /* 110 */ 602, 811, 73, 113, -51, -95, -95, -95, 501, 501,
131359  /* 120 */ 501, 595, 595, 809, 205, 276, 811, 811, 811, 811,
131360  /* 130 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131361  /* 140 */ 811, 811, 811, 811, 811, 811, 192, 628, 498, 498,
131362  /* 150 */ 113, -34, -34, -34, -34, -34, -34, -95, -95, -95,
131363  /* 160 */ 880, -94, -94, 726, 740, 99, 797, 887, 349, 811,
131364  /* 170 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 811,
131365  /* 180 */ 811, 811, 811, 811, 811, 811, 941, 941, 941, 811,
131366  /* 190 */ 811, 926, 811, 811, 811, -18, 811, 811, 842, 811,
131367  /* 200 */ 811, 811, 811, 811, 811, 811, 811, 811, 811, 224,
131368  /* 210 */ 608, 910, 910, 910, 1078, 45, 469, 508, 934, 970,
131369  /* 220 */ 970, 1164, 934, 1164, 1036, 1183, 359, 1017, 970, 954,
131370  /* 230 */ 1017, 1017, 1092, 730, 497, 1225, 1171, 1171, 1228, 1228,
131371  /* 240 */ 1171, 1281, 1280, 1178, 1291, 1291, 1291, 1291, 1171, 1293,
131372  /* 250 */ 1178, 1281, 1280, 1280, 1178, 1171, 1293, 1176, 1244, 1171,
131373  /* 260 */ 1171, 1293, 1302, 1171, 1293, 1171, 1293, 1302, 1229, 1229,
131374  /* 270 */ 1229, 1263, 1302, 1229, 1238, 1229, 1263, 1229, 1229, 1222,
131375  /* 280 */ 1245, 1222, 1245, 1222, 1245, 1222, 1245, 1171, 1171, 1218,
131376  /* 290 */ 1302, 1304, 1304, 1302, 1230, 1242, 1243, 1246, 1178, 1347,
131377  /* 300 */ 1348, 1363, 1363, 1375, 1375, 1375, 1375, -95, -95, -95,
131378  /* 310 */ -95, -95, -95, -95, -95, 451, 876, 346, 1159, 1099,
131379  /* 320 */ 441, 823, 1188, 1111, 1190, 1195, 1199, 1200, 1005, 1129,
131380  /* 330 */ 1224, 533, 1201, 1212, 1155, 1214, 1109, 1112, 1220, 1157,
131381  /* 340 */ 779, 1386, 1388, 1370, 1251, 1379, 1301, 1380, 1381, 1382,
131382  /* 350 */ 1278, 1275, 1296, 1285, 1389, 1286, 1396, 1412, 1294, 1283,
131383  /* 360 */ 1383, 1384, 1305, 1362, 1358, 1303, 1422, 1419, 1404, 1320,
131384  /* 370 */ 1288, 1349, 1405, 1350, 1345, 1361, 1327, 1411, 1416, 1418,
131385  /* 380 */ 1326, 1334, 1420, 1364, 1423, 1424, 1417, 1425, 1365, 1390,
131386  /* 390 */ 1427, 1374, 1373, 1431, 1432, 1433, 1341, 1436, 1437, 1439,
131387  /* 400 */ 1438, 1337, 1440, 1442, 1406, 1402, 1445, 1344, 1443, 1407,
131388  /* 410 */ 1444, 1408, 1443, 1450, 1451, 1452, 1453, 1454, 1456, 1465,
131389  /* 420 */ 1457, 1459, 1458, 1460, 1461, 1463, 1464, 1460, 1466, 1468,
131390  /* 430 */ 1469, 1470, 1472, 1369, 1376, 1377, 1378, 1473, 1480, 1482,
131391 };
131392 #define YY_REDUCE_USE_DFLT (-130)
131393 #define YY_REDUCE_COUNT (314)
131394 #define YY_REDUCE_MIN (-129)
131395 #define YY_REDUCE_MAX (1237)
131396 static const short yy_reduce_ofst[] = {
131397  /* 0 */ -29, 531, 490, 625, -49, 272, 456, 510, 400, 509,
131398  /* 10 */ 562, 114, 535, 614, 698, 384, 738, 751, 690, 419,
131399  /* 20 */ 553, 761, 460, 636, 767, 41, 41, 41, 41, 41,
131400  /* 30 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131401  /* 40 */ 41, 41, 41, 41, 41, 41, 41, 41, 41, 41,
131402  /* 50 */ 41, 41, 41, 41, 760, 815, 856, 863, 866, 868,
131403  /* 60 */ 870, 873, 881, 885, 895, 897, 899, 903, 907, 909,
131404  /* 70 */ 911, 913, 922, 925, 936, 938, 940, 944, 947, 949,
131405  /* 80 */ 951, 953, 955, 962, 978, 980, 984, 986, 988, 991,
131406  /* 90 */ 993, 995, 997, 1002, 1019, 1021, 1025, 41, 41, 41,
131407  /* 100 */ 41, 41, 41, 41, 41, 41, 896, 140, 260, 98,
131408  /* 110 */ 268, 1020, 41, 482, 41, 41, 41, 41, 270, 270,
131409  /* 120 */ 270, 212, 217, -129, 411, 411, 550, 5, 626, 362,
131410  /* 130 */ 733, 830, 992, 1003, 1026, 795, 683, 807, 638, 819,
131411  /* 140 */ 753, 948, 62, 817, 824, 132, 687, 611, 864, 1033,
131412  /* 150 */ 403, 943, 966, 983, 1032, 1038, 1040, 960, 996, 492,
131413  /* 160 */ -50, 57, 131, 153, 221, 462, 588, 596, 675, 721,
131414  /* 170 */ 820, 834, 857, 914, 979, 1034, 1065, 1081, 1087, 1095,
131415  /* 180 */ 1096, 1097, 1098, 1101, 1104, 1105, 320, 500, 655, 1106,
131416  /* 190 */ 1107, 503, 1108, 1110, 1113, 681, 1114, 1115, 999, 1116,
131417  /* 200 */ 1117, 1118, 221, 1119, 1120, 1121, 1122, 1123, 1124, 788,
131418  /* 210 */ 956, 1041, 1051, 1053, 503, 1067, 1079, 1128, 1080, 1066,
131419  /* 220 */ 1068, 1045, 1083, 1047, 1103, 1102, 1125, 1126, 1073, 1062,
131420  /* 230 */ 1127, 1131, 1089, 1093, 1135, 1052, 1136, 1137, 1059, 1060,
131421  /* 240 */ 1141, 1084, 1130, 1132, 1133, 1134, 1138, 1139, 1151, 1154,
131422  /* 250 */ 1140, 1094, 1143, 1145, 1142, 1156, 1158, 1082, 1086, 1162,
131423  /* 260 */ 1163, 1165, 1150, 1169, 1177, 1170, 1179, 1161, 1166, 1168,
131424  /* 270 */ 1172, 1167, 1173, 1174, 1175, 1180, 1181, 1182, 1184, 1144,
131425  /* 280 */ 1146, 1148, 1147, 1149, 1152, 1153, 1160, 1186, 1194, 1185,
131426  /* 290 */ 1189, 1187, 1191, 1193, 1192, 1196, 1198, 1197, 1202, 1215,
131427  /* 300 */ 1217, 1226, 1227, 1231, 1232, 1233, 1234, 1203, 1204, 1205,
131428  /* 310 */ 1221, 1223, 1209, 1211, 1237,
131429 };
131430 static const YYACTIONTYPE yy_default[] = {
131431  /* 0 */ 1250, 1240, 1240, 1240, 1174, 1174, 1174, 1240, 1071, 1100,
131432  /* 10 */ 1100, 1224, 1301, 1301, 1301, 1301, 1301, 1301, 1173, 1301,
131433  /* 20 */ 1301, 1301, 1301, 1240, 1075, 1106, 1301, 1301, 1301, 1301,
131434  /* 30 */ 1301, 1301, 1301, 1301, 1223, 1225, 1114, 1113, 1206, 1087,
131435  /* 40 */ 1111, 1104, 1108, 1175, 1169, 1170, 1168, 1172, 1176, 1301,
131436  /* 50 */ 1107, 1138, 1153, 1137, 1301, 1301, 1301, 1301, 1301, 1301,
131437  /* 60 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131438  /* 70 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131439  /* 80 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131440  /* 90 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1147, 1152, 1159,
131441  /* 100 */ 1151, 1148, 1140, 1139, 1141, 1142, 1301, 994, 1042, 1301,
131442  /* 110 */ 1301, 1301, 1143, 1301, 1144, 1156, 1155, 1154, 1231, 1258,
131443  /* 120 */ 1257, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131444  /* 130 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131445  /* 140 */ 1301, 1301, 1301, 1301, 1301, 1301, 1250, 1240, 1000, 1000,
131446  /* 150 */ 1301, 1240, 1240, 1240, 1240, 1240, 1240, 1236, 1075, 1066,
131447  /* 160 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131448  /* 170 */ 1228, 1226, 1301, 1187, 1301, 1301, 1301, 1301, 1301, 1301,
131449  /* 180 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131450  /* 190 */ 1301, 1301, 1301, 1301, 1301, 1071, 1301, 1301, 1301, 1301,
131451  /* 200 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1252, 1301,
131452  /* 210 */ 1201, 1071, 1071, 1071, 1073, 1055, 1065, 979, 1110, 1089,
131453  /* 220 */ 1089, 1290, 1110, 1290, 1017, 1272, 1014, 1100, 1089, 1171,
131454  /* 230 */ 1100, 1100, 1072, 1065, 1301, 1293, 1080, 1080, 1292, 1292,
131455  /* 240 */ 1080, 1119, 1045, 1110, 1051, 1051, 1051, 1051, 1080, 991,
131456  /* 250 */ 1110, 1119, 1045, 1045, 1110, 1080, 991, 1205, 1287, 1080,
131457  /* 260 */ 1080, 991, 1180, 1080, 991, 1080, 991, 1180, 1043, 1043,
131458  /* 270 */ 1043, 1032, 1180, 1043, 1017, 1043, 1032, 1043, 1043, 1093,
131459  /* 280 */ 1088, 1093, 1088, 1093, 1088, 1093, 1088, 1080, 1080, 1301,
131460  /* 290 */ 1180, 1184, 1184, 1180, 1105, 1094, 1103, 1101, 1110, 997,
131461  /* 300 */ 1035, 1255, 1255, 1251, 1251, 1251, 1251, 1298, 1298, 1236,
131462  /* 310 */ 1267, 1267, 1019, 1019, 1267, 1301, 1301, 1301, 1301, 1301,
131463  /* 320 */ 1301, 1262, 1301, 1189, 1301, 1301, 1301, 1301, 1301, 1301,
131464  /* 330 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131465  /* 340 */ 1125, 1301, 975, 1233, 1301, 1301, 1232, 1301, 1301, 1301,
131466  /* 350 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131467  /* 360 */ 1301, 1301, 1301, 1301, 1301, 1289, 1301, 1301, 1301, 1301,
131468  /* 370 */ 1301, 1301, 1204, 1203, 1301, 1301, 1301, 1301, 1301, 1301,
131469  /* 380 */ 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131470  /* 390 */ 1301, 1301, 1301, 1301, 1301, 1301, 1057, 1301, 1301, 1301,
131471  /* 400 */ 1276, 1301, 1301, 1301, 1301, 1301, 1301, 1301, 1102, 1301,
131472  /* 410 */ 1095, 1301, 1280, 1301, 1301, 1301, 1301, 1301, 1301, 1301,
131473  /* 420 */ 1301, 1301, 1301, 1242, 1301, 1301, 1301, 1241, 1301, 1301,
131474  /* 430 */ 1301, 1301, 1301, 1127, 1301, 1126, 1130, 1301, 985, 1301,
131475 };
131476 /********** End of lemon-generated parsing tables *****************************/
131477 
131478 /* The next table maps tokens (terminal symbols) into fallback tokens.
131479 ** If a construct like the following:
131480 **
131481 ** %fallback ID X Y Z.
131482 **
131483 ** appears in the grammar, then ID becomes a fallback token for X, Y,
131484 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
131485 ** but it does not parse, the type of the token is changed to ID and
131486 ** the parse is retried before an error is thrown.
131487 **
131488 ** This feature can be used, for example, to cause some keywords in a language
131489 ** to revert to identifiers if they keyword does not apply in the context where
131490 ** it appears.
131491 */
131492 #ifdef YYFALLBACK
131493 static const YYCODETYPE yyFallback[] = {
131494  0, /* $ => nothing */
131495  0, /* SEMI => nothing */
131496  55, /* EXPLAIN => ID */
131497  55, /* QUERY => ID */
131498  55, /* PLAN => ID */
131499  55, /* BEGIN => ID */
131500  0, /* TRANSACTION => nothing */
131501  55, /* DEFERRED => ID */
131502  55, /* IMMEDIATE => ID */
131503  55, /* EXCLUSIVE => ID */
131504  0, /* COMMIT => nothing */
131505  55, /* END => ID */
131506  55, /* ROLLBACK => ID */
131507  55, /* SAVEPOINT => ID */
131508  55, /* RELEASE => ID */
131509  0, /* TO => nothing */
131510  0, /* TABLE => nothing */
131511  0, /* CREATE => nothing */
131512  55, /* IF => ID */
131513  0, /* NOT => nothing */
131514  0, /* EXISTS => nothing */
131515  55, /* TEMP => ID */
131516  0, /* LP => nothing */
131517  0, /* RP => nothing */
131518  0, /* AS => nothing */
131519  55, /* WITHOUT => ID */
131520  0, /* COMMA => nothing */
131521  0, /* OR => nothing */
131522  0, /* AND => nothing */
131523  0, /* IS => nothing */
131524  55, /* MATCH => ID */
131525  55, /* LIKE_KW => ID */
131526  0, /* BETWEEN => nothing */
131527  0, /* IN => nothing */
131528  0, /* ISNULL => nothing */
131529  0, /* NOTNULL => nothing */
131530  0, /* NE => nothing */
131531  0, /* EQ => nothing */
131532  0, /* GT => nothing */
131533  0, /* LE => nothing */
131534  0, /* LT => nothing */
131535  0, /* GE => nothing */
131536  0, /* ESCAPE => nothing */
131537  0, /* BITAND => nothing */
131538  0, /* BITOR => nothing */
131539  0, /* LSHIFT => nothing */
131540  0, /* RSHIFT => nothing */
131541  0, /* PLUS => nothing */
131542  0, /* MINUS => nothing */
131543  0, /* STAR => nothing */
131544  0, /* SLASH => nothing */
131545  0, /* REM => nothing */
131546  0, /* CONCAT => nothing */
131547  0, /* COLLATE => nothing */
131548  0, /* BITNOT => nothing */
131549  0, /* ID => nothing */
131550  0, /* INDEXED => nothing */
131551  55, /* ABORT => ID */
131552  55, /* ACTION => ID */
131553  55, /* AFTER => ID */
131554  55, /* ANALYZE => ID */
131555  55, /* ASC => ID */
131556  55, /* ATTACH => ID */
131557  55, /* BEFORE => ID */
131558  55, /* BY => ID */
131559  55, /* CASCADE => ID */
131560  55, /* CAST => ID */
131561  55, /* COLUMNKW => ID */
131562  55, /* CONFLICT => ID */
131563  55, /* DATABASE => ID */
131564  55, /* DESC => ID */
131565  55, /* DETACH => ID */
131566  55, /* EACH => ID */
131567  55, /* FAIL => ID */
131568  55, /* FOR => ID */
131569  55, /* IGNORE => ID */
131570  55, /* INITIALLY => ID */
131571  55, /* INSTEAD => ID */
131572  55, /* NO => ID */
131573  55, /* KEY => ID */
131574  55, /* OF => ID */
131575  55, /* OFFSET => ID */
131576  55, /* PRAGMA => ID */
131577  55, /* RAISE => ID */
131578  55, /* RECURSIVE => ID */
131579  55, /* REPLACE => ID */
131580  55, /* RESTRICT => ID */
131581  55, /* ROW => ID */
131582  55, /* TRIGGER => ID */
131583  55, /* VACUUM => ID */
131584  55, /* VIEW => ID */
131585  55, /* VIRTUAL => ID */
131586  55, /* WITH => ID */
131587  55, /* REINDEX => ID */
131588  55, /* RENAME => ID */
131589  55, /* CTIME_KW => ID */
131590 };
131591 #endif /* YYFALLBACK */
131592 
131593 /* The following structure represents a single element of the
131594 ** parser's stack. Information stored includes:
131595 **
131596 ** + The state number for the parser at this level of the stack.
131597 **
131598 ** + The value of the token stored at this level of the stack.
131599 ** (In other words, the "major" token.)
131600 **
131601 ** + The semantic value stored at this level of the stack. This is
131602 ** the information used by the action routines in the grammar.
131603 ** It is sometimes called the "minor" token.
131604 **
131605 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
131606 ** actually contains the reduce action for the second half of the
131607 ** SHIFTREDUCE.
131608 */
131610  YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
131611  YYCODETYPE major; /* The major token value. This is the code
131612  ** number for the token at this stack level */
131613  YYMINORTYPE minor; /* The user-supplied minor token value. This
131614  ** is the value of the token */
131615 };
131617 
131618 /* The state of the parser is completely contained in an instance of
131619 ** the following structure */
131620 struct yyParser {
131621  int yyidx; /* Index of top element in stack */
131622 #ifdef YYTRACKMAXSTACKDEPTH
131623  int yyidxMax; /* Maximum value of yyidx */
131624 #endif
131625 #ifndef YYNOERRORRECOVERY
131626  int yyerrcnt; /* Shifts left before out of the error */
131627 #endif
131628  sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
131629 #if YYSTACKDEPTH<=0
131630  int yystksz; /* Current side of the stack */
131631  yyStackEntry *yystack; /* The parser's stack */
131632 #else
131633  yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
131634 #endif
131635 };
131636 typedef struct yyParser yyParser;
131637 
131638 #ifndef NDEBUG
131639 /* #include <stdio.h> */
131640 static FILE *yyTraceFILE = 0;
131641 static char *yyTracePrompt = 0;
131642 #endif /* NDEBUG */
131643 
131644 #ifndef NDEBUG
131645 /*
131646 ** Turn parser tracing on by giving a stream to which to write the trace
131647 ** and a prompt to preface each trace message. Tracing is turned off
131648 ** by making either argument NULL
131649 **
131650 ** Inputs:
131651 ** <ul>
131652 ** <li> A FILE* to which trace output should be written.
131653 ** If NULL, then tracing is turned off.
131654 ** <li> A prefix string written at the beginning of every
131655 ** line of trace output. If NULL, then tracing is
131656 ** turned off.
131657 ** </ul>
131658 **
131659 ** Outputs:
131660 ** None.
131661 */
131662 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
131663  yyTraceFILE = TraceFILE;
131664  yyTracePrompt = zTracePrompt;
131665  if( yyTraceFILE==0 ) yyTracePrompt = 0;
131666  else if( yyTracePrompt==0 ) yyTraceFILE = 0;
131667 }
131668 #endif /* NDEBUG */
131669 
131670 #ifndef NDEBUG
131671 /* For tracing shifts, the names of all terminals and nonterminals
131672 ** are required. The following table supplies these names */
131673 static const char *const yyTokenName[] = {
131674  "$", "SEMI", "EXPLAIN", "QUERY",
131675  "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
131676  "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
131677  "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
131678  "TABLE", "CREATE", "IF", "NOT",
131679  "EXISTS", "TEMP", "LP", "RP",
131680  "AS", "WITHOUT", "COMMA", "OR",
131681  "AND", "IS", "MATCH", "LIKE_KW",
131682  "BETWEEN", "IN", "ISNULL", "NOTNULL",
131683  "NE", "EQ", "GT", "LE",
131684  "LT", "GE", "ESCAPE", "BITAND",
131685  "BITOR", "LSHIFT", "RSHIFT", "PLUS",
131686  "MINUS", "STAR", "SLASH", "REM",
131687  "CONCAT", "COLLATE", "BITNOT", "ID",
131688  "INDEXED", "ABORT", "ACTION", "AFTER",
131689  "ANALYZE", "ASC", "ATTACH", "BEFORE",
131690  "BY", "CASCADE", "CAST", "COLUMNKW",
131691  "CONFLICT", "DATABASE", "DESC", "DETACH",
131692  "EACH", "FAIL", "FOR", "IGNORE",
131693  "INITIALLY", "INSTEAD", "NO", "KEY",
131694  "OF", "OFFSET", "PRAGMA", "RAISE",
131695  "RECURSIVE", "REPLACE", "RESTRICT", "ROW",
131696  "TRIGGER", "VACUUM", "VIEW", "VIRTUAL",
131697  "WITH", "REINDEX", "RENAME", "CTIME_KW",
131698  "ANY", "STRING", "JOIN_KW", "CONSTRAINT",
131699  "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
131700  "CHECK", "REFERENCES", "AUTOINCR", "ON",
131701  "INSERT", "DELETE", "UPDATE", "SET",
131702  "DEFERRABLE", "FOREIGN", "DROP", "UNION",
131703  "ALL", "EXCEPT", "INTERSECT", "SELECT",
131704  "VALUES", "DISTINCT", "DOT", "FROM",
131705  "JOIN", "USING", "ORDER", "GROUP",
131706  "HAVING", "LIMIT", "WHERE", "INTO",
131707  "INTEGER", "FLOAT", "BLOB", "VARIABLE",
131708  "CASE", "WHEN", "THEN", "ELSE",
131709  "INDEX", "ALTER", "ADD", "error",
131710  "input", "cmdlist", "ecmd", "explain",
131711  "cmdx", "cmd", "transtype", "trans_opt",
131712  "nm", "savepoint_opt", "create_table", "create_table_args",
131713  "createkw", "temp", "ifnotexists", "dbnm",
131714  "columnlist", "conslist_opt", "table_options", "select",
131715  "columnname", "carglist", "typetoken", "typename",
131716  "signed", "plus_num", "minus_num", "ccons",
131717  "term", "expr", "onconf", "sortorder",
131718  "autoinc", "eidlist_opt", "refargs", "defer_subclause",
131719  "refarg", "refact", "init_deferred_pred_opt", "conslist",
131720  "tconscomma", "tcons", "sortlist", "eidlist",
131721  "defer_subclause_opt", "orconf", "resolvetype", "raisetype",
131722  "ifexists", "fullname", "selectnowith", "oneselect",
131723  "with", "multiselect_op", "distinct", "selcollist",
131724  "from", "where_opt", "groupby_opt", "having_opt",
131725  "orderby_opt", "limit_opt", "values", "nexprlist",
131726  "exprlist", "sclp", "as", "seltablist",
131727  "stl_prefix", "joinop", "indexed_opt", "on_opt",
131728  "using_opt", "idlist", "setlist", "insert_cmd",
131729  "idlist_opt", "likeop", "between_op", "in_op",
131730  "case_operand", "case_exprlist", "case_else", "uniqueflag",
131731  "collate", "nmnum", "trigger_decl", "trigger_cmd_list",
131732  "trigger_time", "trigger_event", "foreach_clause", "when_clause",
131733  "trigger_cmd", "trnm", "tridxby", "database_kw_opt",
131734  "key_opt", "add_column_fullname", "kwcolumn_opt", "create_vtab",
131735  "vtabarglist", "vtabarg", "vtabargtoken", "lp",
131736  "anylist", "wqlist",
131737 };
131738 #endif /* NDEBUG */
131739 
131740 #ifndef NDEBUG
131741 /* For tracing reduce actions, the names of all rules are required.
131742 */
131743 static const char *const yyRuleName[] = {
131744  /* 0 */ "explain ::= EXPLAIN",
131745  /* 1 */ "explain ::= EXPLAIN QUERY PLAN",
131746  /* 2 */ "cmdx ::= cmd",
131747  /* 3 */ "cmd ::= BEGIN transtype trans_opt",
131748  /* 4 */ "transtype ::=",
131749  /* 5 */ "transtype ::= DEFERRED",
131750  /* 6 */ "transtype ::= IMMEDIATE",
131751  /* 7 */ "transtype ::= EXCLUSIVE",
131752  /* 8 */ "cmd ::= COMMIT trans_opt",
131753  /* 9 */ "cmd ::= END trans_opt",
131754  /* 10 */ "cmd ::= ROLLBACK trans_opt",
131755  /* 11 */ "cmd ::= SAVEPOINT nm",
131756  /* 12 */ "cmd ::= RELEASE savepoint_opt nm",
131757  /* 13 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
131758  /* 14 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
131759  /* 15 */ "createkw ::= CREATE",
131760  /* 16 */ "ifnotexists ::=",
131761  /* 17 */ "ifnotexists ::= IF NOT EXISTS",
131762  /* 18 */ "temp ::= TEMP",
131763  /* 19 */ "temp ::=",
131764  /* 20 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
131765  /* 21 */ "create_table_args ::= AS select",
131766  /* 22 */ "table_options ::=",
131767  /* 23 */ "table_options ::= WITHOUT nm",
131768  /* 24 */ "columnname ::= nm typetoken",
131769  /* 25 */ "typetoken ::=",
131770  /* 26 */ "typetoken ::= typename LP signed RP",
131771  /* 27 */ "typetoken ::= typename LP signed COMMA signed RP",
131772  /* 28 */ "typename ::= typename ID|STRING",
131773  /* 29 */ "ccons ::= CONSTRAINT nm",
131774  /* 30 */ "ccons ::= DEFAULT term",
131775  /* 31 */ "ccons ::= DEFAULT LP expr RP",
131776  /* 32 */ "ccons ::= DEFAULT PLUS term",
131777  /* 33 */ "ccons ::= DEFAULT MINUS term",
131778  /* 34 */ "ccons ::= DEFAULT ID|INDEXED",
131779  /* 35 */ "ccons ::= NOT NULL onconf",
131780  /* 36 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
131781  /* 37 */ "ccons ::= UNIQUE onconf",
131782  /* 38 */ "ccons ::= CHECK LP expr RP",
131783  /* 39 */ "ccons ::= REFERENCES nm eidlist_opt refargs",
131784  /* 40 */ "ccons ::= defer_subclause",
131785  /* 41 */ "ccons ::= COLLATE ID|STRING",
131786  /* 42 */ "autoinc ::=",
131787  /* 43 */ "autoinc ::= AUTOINCR",
131788  /* 44 */ "refargs ::=",
131789  /* 45 */ "refargs ::= refargs refarg",
131790  /* 46 */ "refarg ::= MATCH nm",
131791  /* 47 */ "refarg ::= ON INSERT refact",
131792  /* 48 */ "refarg ::= ON DELETE refact",
131793  /* 49 */ "refarg ::= ON UPDATE refact",
131794  /* 50 */ "refact ::= SET NULL",
131795  /* 51 */ "refact ::= SET DEFAULT",
131796  /* 52 */ "refact ::= CASCADE",
131797  /* 53 */ "refact ::= RESTRICT",
131798  /* 54 */ "refact ::= NO ACTION",
131799  /* 55 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
131800  /* 56 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
131801  /* 57 */ "init_deferred_pred_opt ::=",
131802  /* 58 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
131803  /* 59 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
131804  /* 60 */ "conslist_opt ::=",
131805  /* 61 */ "tconscomma ::= COMMA",
131806  /* 62 */ "tcons ::= CONSTRAINT nm",
131807  /* 63 */ "tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf",
131808  /* 64 */ "tcons ::= UNIQUE LP sortlist RP onconf",
131809  /* 65 */ "tcons ::= CHECK LP expr RP onconf",
131810  /* 66 */ "tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt",
131811  /* 67 */ "defer_subclause_opt ::=",
131812  /* 68 */ "onconf ::=",
131813  /* 69 */ "onconf ::= ON CONFLICT resolvetype",
131814  /* 70 */ "orconf ::=",
131815  /* 71 */ "orconf ::= OR resolvetype",
131816  /* 72 */ "resolvetype ::= IGNORE",
131817  /* 73 */ "resolvetype ::= REPLACE",
131818  /* 74 */ "cmd ::= DROP TABLE ifexists fullname",
131819  /* 75 */ "ifexists ::= IF EXISTS",
131820  /* 76 */ "ifexists ::=",
131821  /* 77 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select",
131822  /* 78 */ "cmd ::= DROP VIEW ifexists fullname",
131823  /* 79 */ "cmd ::= select",
131824  /* 80 */ "select ::= with selectnowith",
131825  /* 81 */ "selectnowith ::= selectnowith multiselect_op oneselect",
131826  /* 82 */ "multiselect_op ::= UNION",
131827  /* 83 */ "multiselect_op ::= UNION ALL",
131828  /* 84 */ "multiselect_op ::= EXCEPT|INTERSECT",
131829  /* 85 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
131830  /* 86 */ "values ::= VALUES LP nexprlist RP",
131831  /* 87 */ "values ::= values COMMA LP exprlist RP",
131832  /* 88 */ "distinct ::= DISTINCT",
131833  /* 89 */ "distinct ::= ALL",
131834  /* 90 */ "distinct ::=",
131835  /* 91 */ "sclp ::=",
131836  /* 92 */ "selcollist ::= sclp expr as",
131837  /* 93 */ "selcollist ::= sclp STAR",
131838  /* 94 */ "selcollist ::= sclp nm DOT STAR",
131839  /* 95 */ "as ::= AS nm",
131840  /* 96 */ "as ::=",
131841  /* 97 */ "from ::=",
131842  /* 98 */ "from ::= FROM seltablist",
131843  /* 99 */ "stl_prefix ::= seltablist joinop",
131844  /* 100 */ "stl_prefix ::=",
131845  /* 101 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
131846  /* 102 */ "seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt",
131847  /* 103 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
131848  /* 104 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
131849  /* 105 */ "dbnm ::=",
131850  /* 106 */ "dbnm ::= DOT nm",
131851  /* 107 */ "fullname ::= nm dbnm",
131852  /* 108 */ "joinop ::= COMMA|JOIN",
131853  /* 109 */ "joinop ::= JOIN_KW JOIN",
131854  /* 110 */ "joinop ::= JOIN_KW nm JOIN",
131855  /* 111 */ "joinop ::= JOIN_KW nm nm JOIN",
131856  /* 112 */ "on_opt ::= ON expr",
131857  /* 113 */ "on_opt ::=",
131858  /* 114 */ "indexed_opt ::=",
131859  /* 115 */ "indexed_opt ::= INDEXED BY nm",
131860  /* 116 */ "indexed_opt ::= NOT INDEXED",
131861  /* 117 */ "using_opt ::= USING LP idlist RP",
131862  /* 118 */ "using_opt ::=",
131863  /* 119 */ "orderby_opt ::=",
131864  /* 120 */ "orderby_opt ::= ORDER BY sortlist",
131865  /* 121 */ "sortlist ::= sortlist COMMA expr sortorder",
131866  /* 122 */ "sortlist ::= expr sortorder",
131867  /* 123 */ "sortorder ::= ASC",
131868  /* 124 */ "sortorder ::= DESC",
131869  /* 125 */ "sortorder ::=",
131870  /* 126 */ "groupby_opt ::=",
131871  /* 127 */ "groupby_opt ::= GROUP BY nexprlist",
131872  /* 128 */ "having_opt ::=",
131873  /* 129 */ "having_opt ::= HAVING expr",
131874  /* 130 */ "limit_opt ::=",
131875  /* 131 */ "limit_opt ::= LIMIT expr",
131876  /* 132 */ "limit_opt ::= LIMIT expr OFFSET expr",
131877  /* 133 */ "limit_opt ::= LIMIT expr COMMA expr",
131878  /* 134 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
131879  /* 135 */ "where_opt ::=",
131880  /* 136 */ "where_opt ::= WHERE expr",
131881  /* 137 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
131882  /* 138 */ "setlist ::= setlist COMMA nm EQ expr",
131883  /* 139 */ "setlist ::= nm EQ expr",
131884  /* 140 */ "cmd ::= with insert_cmd INTO fullname idlist_opt select",
131885  /* 141 */ "cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES",
131886  /* 142 */ "insert_cmd ::= INSERT orconf",
131887  /* 143 */ "insert_cmd ::= REPLACE",
131888  /* 144 */ "idlist_opt ::=",
131889  /* 145 */ "idlist_opt ::= LP idlist RP",
131890  /* 146 */ "idlist ::= idlist COMMA nm",
131891  /* 147 */ "idlist ::= nm",
131892  /* 148 */ "expr ::= LP expr RP",
131893  /* 149 */ "term ::= NULL",
131894  /* 150 */ "expr ::= ID|INDEXED",
131895  /* 151 */ "expr ::= JOIN_KW",
131896  /* 152 */ "expr ::= nm DOT nm",
131897  /* 153 */ "expr ::= nm DOT nm DOT nm",
131898  /* 154 */ "term ::= INTEGER|FLOAT|BLOB",
131899  /* 155 */ "term ::= STRING",
131900  /* 156 */ "expr ::= VARIABLE",
131901  /* 157 */ "expr ::= expr COLLATE ID|STRING",
131902  /* 158 */ "expr ::= CAST LP expr AS typetoken RP",
131903  /* 159 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
131904  /* 160 */ "expr ::= ID|INDEXED LP STAR RP",
131905  /* 161 */ "term ::= CTIME_KW",
131906  /* 162 */ "expr ::= expr AND expr",
131907  /* 163 */ "expr ::= expr OR expr",
131908  /* 164 */ "expr ::= expr LT|GT|GE|LE expr",
131909  /* 165 */ "expr ::= expr EQ|NE expr",
131910  /* 166 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
131911  /* 167 */ "expr ::= expr PLUS|MINUS expr",
131912  /* 168 */ "expr ::= expr STAR|SLASH|REM expr",
131913  /* 169 */ "expr ::= expr CONCAT expr",
131914  /* 170 */ "likeop ::= LIKE_KW|MATCH",
131915  /* 171 */ "likeop ::= NOT LIKE_KW|MATCH",
131916  /* 172 */ "expr ::= expr likeop expr",
131917  /* 173 */ "expr ::= expr likeop expr ESCAPE expr",
131918  /* 174 */ "expr ::= expr ISNULL|NOTNULL",
131919  /* 175 */ "expr ::= expr NOT NULL",
131920  /* 176 */ "expr ::= expr IS expr",
131921  /* 177 */ "expr ::= expr IS NOT expr",
131922  /* 178 */ "expr ::= NOT expr",
131923  /* 179 */ "expr ::= BITNOT expr",
131924  /* 180 */ "expr ::= MINUS expr",
131925  /* 181 */ "expr ::= PLUS expr",
131926  /* 182 */ "between_op ::= BETWEEN",
131927  /* 183 */ "between_op ::= NOT BETWEEN",
131928  /* 184 */ "expr ::= expr between_op expr AND expr",
131929  /* 185 */ "in_op ::= IN",
131930  /* 186 */ "in_op ::= NOT IN",
131931  /* 187 */ "expr ::= expr in_op LP exprlist RP",
131932  /* 188 */ "expr ::= LP select RP",
131933  /* 189 */ "expr ::= expr in_op LP select RP",
131934  /* 190 */ "expr ::= expr in_op nm dbnm",
131935  /* 191 */ "expr ::= EXISTS LP select RP",
131936  /* 192 */ "expr ::= CASE case_operand case_exprlist case_else END",
131937  /* 193 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
131938  /* 194 */ "case_exprlist ::= WHEN expr THEN expr",
131939  /* 195 */ "case_else ::= ELSE expr",
131940  /* 196 */ "case_else ::=",
131941  /* 197 */ "case_operand ::= expr",
131942  /* 198 */ "case_operand ::=",
131943  /* 199 */ "exprlist ::=",
131944  /* 200 */ "nexprlist ::= nexprlist COMMA expr",
131945  /* 201 */ "nexprlist ::= expr",
131946  /* 202 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt",
131947  /* 203 */ "uniqueflag ::= UNIQUE",
131948  /* 204 */ "uniqueflag ::=",
131949  /* 205 */ "eidlist_opt ::=",
131950  /* 206 */ "eidlist_opt ::= LP eidlist RP",
131951  /* 207 */ "eidlist ::= eidlist COMMA nm collate sortorder",
131952  /* 208 */ "eidlist ::= nm collate sortorder",
131953  /* 209 */ "collate ::=",
131954  /* 210 */ "collate ::= COLLATE ID|STRING",
131955  /* 211 */ "cmd ::= DROP INDEX ifexists fullname",
131956  /* 212 */ "cmd ::= VACUUM",
131957  /* 213 */ "cmd ::= VACUUM nm",
131958  /* 214 */ "cmd ::= PRAGMA nm dbnm",
131959  /* 215 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
131960  /* 216 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
131961  /* 217 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
131962  /* 218 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
131963  /* 219 */ "plus_num ::= PLUS INTEGER|FLOAT",
131964  /* 220 */ "minus_num ::= MINUS INTEGER|FLOAT",
131965  /* 221 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
131966  /* 222 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
131967  /* 223 */ "trigger_time ::= BEFORE",
131968  /* 224 */ "trigger_time ::= AFTER",
131969  /* 225 */ "trigger_time ::= INSTEAD OF",
131970  /* 226 */ "trigger_time ::=",
131971  /* 227 */ "trigger_event ::= DELETE|INSERT",
131972  /* 228 */ "trigger_event ::= UPDATE",
131973  /* 229 */ "trigger_event ::= UPDATE OF idlist",
131974  /* 230 */ "when_clause ::=",
131975  /* 231 */ "when_clause ::= WHEN expr",
131976  /* 232 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
131977  /* 233 */ "trigger_cmd_list ::= trigger_cmd SEMI",
131978  /* 234 */ "trnm ::= nm DOT nm",
131979  /* 235 */ "tridxby ::= INDEXED BY nm",
131980  /* 236 */ "tridxby ::= NOT INDEXED",
131981  /* 237 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
131982  /* 238 */ "trigger_cmd ::= insert_cmd INTO trnm idlist_opt select",
131983  /* 239 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
131984  /* 240 */ "trigger_cmd ::= select",
131985  /* 241 */ "expr ::= RAISE LP IGNORE RP",
131986  /* 242 */ "expr ::= RAISE LP raisetype COMMA nm RP",
131987  /* 243 */ "raisetype ::= ROLLBACK",
131988  /* 244 */ "raisetype ::= ABORT",
131989  /* 245 */ "raisetype ::= FAIL",
131990  /* 246 */ "cmd ::= DROP TRIGGER ifexists fullname",
131991  /* 247 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
131992  /* 248 */ "cmd ::= DETACH database_kw_opt expr",
131993  /* 249 */ "key_opt ::=",
131994  /* 250 */ "key_opt ::= KEY expr",
131995  /* 251 */ "cmd ::= REINDEX",
131996  /* 252 */ "cmd ::= REINDEX nm dbnm",
131997  /* 253 */ "cmd ::= ANALYZE",
131998  /* 254 */ "cmd ::= ANALYZE nm dbnm",
131999  /* 255 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
132000  /* 256 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist",
132001  /* 257 */ "add_column_fullname ::= fullname",
132002  /* 258 */ "cmd ::= create_vtab",
132003  /* 259 */ "cmd ::= create_vtab LP vtabarglist RP",
132004  /* 260 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
132005  /* 261 */ "vtabarg ::=",
132006  /* 262 */ "vtabargtoken ::= ANY",
132007  /* 263 */ "vtabargtoken ::= lp anylist RP",
132008  /* 264 */ "lp ::= LP",
132009  /* 265 */ "with ::=",
132010  /* 266 */ "with ::= WITH wqlist",
132011  /* 267 */ "with ::= WITH RECURSIVE wqlist",
132012  /* 268 */ "wqlist ::= nm eidlist_opt AS LP select RP",
132013  /* 269 */ "wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP",
132014  /* 270 */ "input ::= cmdlist",
132015  /* 271 */ "cmdlist ::= cmdlist ecmd",
132016  /* 272 */ "cmdlist ::= ecmd",
132017  /* 273 */ "ecmd ::= SEMI",
132018  /* 274 */ "ecmd ::= explain cmdx SEMI",
132019  /* 275 */ "explain ::=",
132020  /* 276 */ "trans_opt ::=",
132021  /* 277 */ "trans_opt ::= TRANSACTION",
132022  /* 278 */ "trans_opt ::= TRANSACTION nm",
132023  /* 279 */ "savepoint_opt ::= SAVEPOINT",
132024  /* 280 */ "savepoint_opt ::=",
132025  /* 281 */ "cmd ::= create_table create_table_args",
132026  /* 282 */ "columnlist ::= columnlist COMMA columnname carglist",
132027  /* 283 */ "columnlist ::= columnname carglist",
132028  /* 284 */ "nm ::= ID|INDEXED",
132029  /* 285 */ "nm ::= STRING",
132030  /* 286 */ "nm ::= JOIN_KW",
132031  /* 287 */ "typetoken ::= typename",
132032  /* 288 */ "typename ::= ID|STRING",
132033  /* 289 */ "signed ::= plus_num",
132034  /* 290 */ "signed ::= minus_num",
132035  /* 291 */ "carglist ::= carglist ccons",
132036  /* 292 */ "carglist ::=",
132037  /* 293 */ "ccons ::= NULL onconf",
132038  /* 294 */ "conslist_opt ::= COMMA conslist",
132039  /* 295 */ "conslist ::= conslist tconscomma tcons",
132040  /* 296 */ "conslist ::= tcons",
132041  /* 297 */ "tconscomma ::=",
132042  /* 298 */ "defer_subclause_opt ::= defer_subclause",
132043  /* 299 */ "resolvetype ::= raisetype",
132044  /* 300 */ "selectnowith ::= oneselect",
132045  /* 301 */ "oneselect ::= values",
132046  /* 302 */ "sclp ::= selcollist COMMA",
132047  /* 303 */ "as ::= ID|STRING",
132048  /* 304 */ "expr ::= term",
132049  /* 305 */ "exprlist ::= nexprlist",
132050  /* 306 */ "nmnum ::= plus_num",
132051  /* 307 */ "nmnum ::= nm",
132052  /* 308 */ "nmnum ::= ON",
132053  /* 309 */ "nmnum ::= DELETE",
132054  /* 310 */ "nmnum ::= DEFAULT",
132055  /* 311 */ "plus_num ::= INTEGER|FLOAT",
132056  /* 312 */ "foreach_clause ::=",
132057  /* 313 */ "foreach_clause ::= FOR EACH ROW",
132058  /* 314 */ "trnm ::= nm",
132059  /* 315 */ "tridxby ::=",
132060  /* 316 */ "database_kw_opt ::= DATABASE",
132061  /* 317 */ "database_kw_opt ::=",
132062  /* 318 */ "kwcolumn_opt ::=",
132063  /* 319 */ "kwcolumn_opt ::= COLUMNKW",
132064  /* 320 */ "vtabarglist ::= vtabarg",
132065  /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
132066  /* 322 */ "vtabarg ::= vtabarg vtabargtoken",
132067  /* 323 */ "anylist ::=",
132068  /* 324 */ "anylist ::= anylist LP anylist RP",
132069  /* 325 */ "anylist ::= anylist ANY",
132070 };
132071 #endif /* NDEBUG */
132072 
132073 
132074 #if YYSTACKDEPTH<=0
132075 /*
132076 ** Try to increase the size of the parser stack.
132077 */
132078 static void yyGrowStack(yyParser *p){
132079  int newSize;
132080  yyStackEntry *pNew;
132081 
132082  newSize = p->yystksz*2 + 100;
132083  pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
132084  if( pNew ){
132085  p->yystack = pNew;
132086  p->yystksz = newSize;
132087 #ifndef NDEBUG
132088  if( yyTraceFILE ){
132089  fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
132090  yyTracePrompt, p->yystksz);
132091  }
132092 #endif
132093  }
132094 }
132095 #endif
132096 
132097 /* Datatype of the argument to the memory allocated passed as the
132098 ** second argument to sqlite3ParserAlloc() below. This can be changed by
132099 ** putting an appropriate #define in the %include section of the input
132100 ** grammar.
132101 */
132102 #ifndef YYMALLOCARGTYPE
132103 # define YYMALLOCARGTYPE size_t
132104 #endif
132105 
132106 /*
132107 ** This function allocates a new parser.
132108 ** The only argument is a pointer to a function which works like
132109 ** malloc.
132110 **
132111 ** Inputs:
132112 ** A pointer to the function used to allocate memory.
132113 **
132114 ** Outputs:
132115 ** A pointer to a parser. This pointer is used in subsequent calls
132116 ** to sqlite3Parser and sqlite3ParserFree.
132117 */
132119  yyParser *pParser;
132120  pParser = (yyParser*)(*mallocProc)( (YYMALLOCARGTYPE)sizeof(yyParser) );
132121  if( pParser ){
132122  pParser->yyidx = -1;
132123 #ifdef YYTRACKMAXSTACKDEPTH
132124  pParser->yyidxMax = 0;
132125 #endif
132126 #if YYSTACKDEPTH<=0
132127  pParser->yystack = NULL;
132128  pParser->yystksz = 0;
132129  yyGrowStack(pParser);
132130 #endif
132131  }
132132  return pParser;
132133 }
132134 
132135 /* The following function deletes the "minor type" or semantic value
132136 ** associated with a symbol. The symbol can be either a terminal
132137 ** or nonterminal. "yymajor" is the symbol code, and "yypminor" is
132138 ** a pointer to the value to be deleted. The code used to do the
132139 ** deletions is derived from the %destructor and/or %token_destructor
132140 ** directives of the input grammar.
132141 */
132142 static void yy_destructor(
132143  yyParser *yypParser, /* The parser */
132144  YYCODETYPE yymajor, /* Type code for object to destroy */
132145  YYMINORTYPE *yypminor /* The object to be destroyed */
132146 ){
132148  switch( yymajor ){
132149  /* Here is inserted the actions which take place when a
132150  ** terminal or non-terminal is destroyed. This can happen
132151  ** when the symbol is popped from the stack during a
132152  ** reduce or during error processing or when a parser is
132153  ** being destroyed before it is finished parsing.
132154  **
132155  ** Note: during a reduce, the only symbols destroyed are those
132156  ** which appear on the RHS of the rule, but which are *not* used
132157  ** inside the C code.
132158  */
132159 /********* Begin destructor definitions ***************************************/
132160  case 163: /* select */
132161  case 194: /* selectnowith */
132162  case 195: /* oneselect */
132163  case 206: /* values */
132164 {
132165 sqlite3SelectDelete(pParse->db, (yypminor->yy159));
132166 }
132167  break;
132168  case 172: /* term */
132169  case 173: /* expr */
132170 {
132171 sqlite3ExprDelete(pParse->db, (yypminor->yy342).pExpr);
132172 }
132173  break;
132174  case 177: /* eidlist_opt */
132175  case 186: /* sortlist */
132176  case 187: /* eidlist */
132177  case 199: /* selcollist */
132178  case 202: /* groupby_opt */
132179  case 204: /* orderby_opt */
132180  case 207: /* nexprlist */
132181  case 208: /* exprlist */
132182  case 209: /* sclp */
132183  case 218: /* setlist */
132184  case 225: /* case_exprlist */
132185 {
132186 sqlite3ExprListDelete(pParse->db, (yypminor->yy442));
132187 }
132188  break;
132189  case 193: /* fullname */
132190  case 200: /* from */
132191  case 211: /* seltablist */
132192  case 212: /* stl_prefix */
132193 {
132194 sqlite3SrcListDelete(pParse->db, (yypminor->yy347));
132195 }
132196  break;
132197  case 196: /* with */
132198  case 249: /* wqlist */
132199 {
132200 sqlite3WithDelete(pParse->db, (yypminor->yy331));
132201 }
132202  break;
132203  case 201: /* where_opt */
132204  case 203: /* having_opt */
132205  case 215: /* on_opt */
132206  case 224: /* case_operand */
132207  case 226: /* case_else */
132208  case 235: /* when_clause */
132209  case 240: /* key_opt */
132210 {
132211 sqlite3ExprDelete(pParse->db, (yypminor->yy122));
132212 }
132213  break;
132214  case 216: /* using_opt */
132215  case 217: /* idlist */
132216  case 220: /* idlist_opt */
132217 {
132218 sqlite3IdListDelete(pParse->db, (yypminor->yy180));
132219 }
132220  break;
132221  case 231: /* trigger_cmd_list */
132222  case 236: /* trigger_cmd */
132223 {
132224 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy327));
132225 }
132226  break;
132227  case 233: /* trigger_event */
132228 {
132229 sqlite3IdListDelete(pParse->db, (yypminor->yy410).b);
132230 }
132231  break;
132232 /********* End destructor definitions *****************************************/
132233  default: break; /* If no destructor action specified: do nothing */
132234  }
132235 }
132236 
132237 /*
132238 ** Pop the parser's stack once.
132239 **
132240 ** If there is a destructor routine associated with the token which
132241 ** is popped from the stack, then call it.
132242 */
132243 static void yy_pop_parser_stack(yyParser *pParser){
132244  yyStackEntry *yytos;
132245  assert( pParser->yyidx>=0 );
132246  yytos = &pParser->yystack[pParser->yyidx--];
132247 #ifndef NDEBUG
132248  if( yyTraceFILE ){
132249  fprintf(yyTraceFILE,"%sPopping %s\n",
132250  yyTracePrompt,
132251  yyTokenName[yytos->major]);
132252  }
132253 #endif
132254  yy_destructor(pParser, yytos->major, &yytos->minor);
132255 }
132256 
132257 /*
132258 ** Deallocate and destroy a parser. Destructors are called for
132259 ** all stack elements before shutting the parser down.
132260 **
132261 ** If the YYPARSEFREENEVERNULL macro exists (for example because it
132262 ** is defined in a %include section of the input grammar) then it is
132263 ** assumed that the input pointer is never NULL.
132264 */
132266  void *p, /* The parser to be deleted */
132267  void (*freeProc)(void*) /* Function used to reclaim memory */
132268 ){
132269  yyParser *pParser = (yyParser*)p;
132270 #ifndef YYPARSEFREENEVERNULL
132271  if( pParser==0 ) return;
132272 #endif
132273  while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
132274 #if YYSTACKDEPTH<=0
132275  free(pParser->yystack);
132276 #endif
132277  (*freeProc)((void*)pParser);
132278 }
132279 
132280 /*
132281 ** Return the peak depth of the stack for a parser.
132282 */
132283 #ifdef YYTRACKMAXSTACKDEPTH
132284 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
132285  yyParser *pParser = (yyParser*)p;
132286  return pParser->yyidxMax;
132287 }
132288 #endif
132289 
132290 /*
132291 ** Find the appropriate action for a parser given the terminal
132292 ** look-ahead token iLookAhead.
132293 */
132294 static unsigned int yy_find_shift_action(
132295  yyParser *pParser, /* The parser */
132296  YYCODETYPE iLookAhead /* The look-ahead token */
132297 ){
132298  int i;
132299  int stateno = pParser->yystack[pParser->yyidx].stateno;
132300 
132301  if( stateno>=YY_MIN_REDUCE ) return stateno;
132302  assert( stateno <= YY_SHIFT_COUNT );
132303  do{
132304  i = yy_shift_ofst[stateno];
132305  if( i==YY_SHIFT_USE_DFLT ) return yy_default[stateno];
132306  assert( iLookAhead!=YYNOCODE );
132307  i += iLookAhead;
132308  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
132309  if( iLookAhead>0 ){
132310 #ifdef YYFALLBACK
132311  YYCODETYPE iFallback; /* Fallback token */
132312  if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
132313  && (iFallback = yyFallback[iLookAhead])!=0 ){
132314 #ifndef NDEBUG
132315  if( yyTraceFILE ){
132316  fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
132317  yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
132318  }
132319 #endif
132320  assert( yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
132321  iLookAhead = iFallback;
132322  continue;
132323  }
132324 #endif
132325 #ifdef YYWILDCARD
132326  {
132327  int j = i - iLookAhead + YYWILDCARD;
132328  if(
132329 #if YY_SHIFT_MIN+YYWILDCARD<0
132330  j>=0 &&
132331 #endif
132332 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
132333  j<YY_ACTTAB_COUNT &&
132334 #endif
132335  yy_lookahead[j]==YYWILDCARD
132336  ){
132337 #ifndef NDEBUG
132338  if( yyTraceFILE ){
132339  fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
132340  yyTracePrompt, yyTokenName[iLookAhead],
132341  yyTokenName[YYWILDCARD]);
132342  }
132343 #endif /* NDEBUG */
132344  return yy_action[j];
132345  }
132346  }
132347 #endif /* YYWILDCARD */
132348  }
132349  return yy_default[stateno];
132350  }else{
132351  return yy_action[i];
132352  }
132353  }while(1);
132354 }
132355 
132356 /*
132357 ** Find the appropriate action for a parser given the non-terminal
132358 ** look-ahead token iLookAhead.
132359 */
132361  int stateno, /* Current state number */
132362  YYCODETYPE iLookAhead /* The look-ahead token */
132363 ){
132364  int i;
132365 #ifdef YYERRORSYMBOL
132366  if( stateno>YY_REDUCE_COUNT ){
132367  return yy_default[stateno];
132368  }
132369 #else
132370  assert( stateno<=YY_REDUCE_COUNT );
132371 #endif
132372  i = yy_reduce_ofst[stateno];
132373  assert( i!=YY_REDUCE_USE_DFLT );
132374  assert( iLookAhead!=YYNOCODE );
132375  i += iLookAhead;
132376 #ifdef YYERRORSYMBOL
132377  if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
132378  return yy_default[stateno];
132379  }
132380 #else
132381  assert( i>=0 && i<YY_ACTTAB_COUNT );
132382  assert( yy_lookahead[i]==iLookAhead );
132383 #endif
132384  return yy_action[i];
132385 }
132386 
132387 /*
132388 ** The following routine is called if the stack overflows.
132389 */
132390 static void yyStackOverflow(yyParser *yypParser){
132392  yypParser->yyidx--;
132393 #ifndef NDEBUG
132394  if( yyTraceFILE ){
132395  fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
132396  }
132397 #endif
132398  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
132399  /* Here code is inserted which will execute if the parser
132400  ** stack every overflows */
132401 /******** Begin %stack_overflow code ******************************************/
132402 
132403  sqlite3ErrorMsg(pParse, "parser stack overflow");
132404 /******** End %stack_overflow code ********************************************/
132405  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
132406 }
132407 
132408 /*
132409 ** Print tracing information for a SHIFT action
132410 */
132411 #ifndef NDEBUG
132412 static void yyTraceShift(yyParser *yypParser, int yyNewState){
132413  if( yyTraceFILE ){
132414  if( yyNewState<YYNSTATE ){
132415  fprintf(yyTraceFILE,"%sShift '%s', go to state %d\n",
132416  yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major],
132417  yyNewState);
132418  }else{
132419  fprintf(yyTraceFILE,"%sShift '%s'\n",
132420  yyTracePrompt,yyTokenName[yypParser->yystack[yypParser->yyidx].major]);
132421  }
132422  }
132423 }
132424 #else
132425 # define yyTraceShift(X,Y)
132426 #endif
132427 
132428 /*
132429 ** Perform a shift action.
132430 */
132431 static void yy_shift(
132432  yyParser *yypParser, /* The parser to be shifted */
132433  int yyNewState, /* The new state to shift in */
132434  int yyMajor, /* The major token to shift in */
132435  sqlite3ParserTOKENTYPE yyMinor /* The minor token to shift in */
132436 ){
132437  yyStackEntry *yytos;
132438  yypParser->yyidx++;
132439 #ifdef YYTRACKMAXSTACKDEPTH
132440  if( yypParser->yyidx>yypParser->yyidxMax ){
132441  yypParser->yyidxMax = yypParser->yyidx;
132442  }
132443 #endif
132444 #if YYSTACKDEPTH>0
132445  if( yypParser->yyidx>=YYSTACKDEPTH ){
132446  yyStackOverflow(yypParser);
132447  return;
132448  }
132449 #else
132450  if( yypParser->yyidx>=yypParser->yystksz ){
132451  yyGrowStack(yypParser);
132452  if( yypParser->yyidx>=yypParser->yystksz ){
132453  yyStackOverflow(yypParser);
132454  return;
132455  }
132456  }
132457 #endif
132458  yytos = &yypParser->yystack[yypParser->yyidx];
132459  yytos->stateno = (YYACTIONTYPE)yyNewState;
132460  yytos->major = (YYCODETYPE)yyMajor;
132461  yytos->minor.yy0 = yyMinor;
132462  yyTraceShift(yypParser, yyNewState);
132463 }
132464 
132465 /* The following table contains information about every rule that
132466 ** is used during the reduce.
132467 */
132468 static const struct {
132469  YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
132470  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
132471 } yyRuleInfo[] = {
132472  { 147, 1 },
132473  { 147, 3 },
132474  { 148, 1 },
132475  { 149, 3 },
132476  { 150, 0 },
132477  { 150, 1 },
132478  { 150, 1 },
132479  { 150, 1 },
132480  { 149, 2 },
132481  { 149, 2 },
132482  { 149, 2 },
132483  { 149, 2 },
132484  { 149, 3 },
132485  { 149, 5 },
132486  { 154, 6 },
132487  { 156, 1 },
132488  { 158, 0 },
132489  { 158, 3 },
132490  { 157, 1 },
132491  { 157, 0 },
132492  { 155, 5 },
132493  { 155, 2 },
132494  { 162, 0 },
132495  { 162, 2 },
132496  { 164, 2 },
132497  { 166, 0 },
132498  { 166, 4 },
132499  { 166, 6 },
132500  { 167, 2 },
132501  { 171, 2 },
132502  { 171, 2 },
132503  { 171, 4 },
132504  { 171, 3 },
132505  { 171, 3 },
132506  { 171, 2 },
132507  { 171, 3 },
132508  { 171, 5 },
132509  { 171, 2 },
132510  { 171, 4 },
132511  { 171, 4 },
132512  { 171, 1 },
132513  { 171, 2 },
132514  { 176, 0 },
132515  { 176, 1 },
132516  { 178, 0 },
132517  { 178, 2 },
132518  { 180, 2 },
132519  { 180, 3 },
132520  { 180, 3 },
132521  { 180, 3 },
132522  { 181, 2 },
132523  { 181, 2 },
132524  { 181, 1 },
132525  { 181, 1 },
132526  { 181, 2 },
132527  { 179, 3 },
132528  { 179, 2 },
132529  { 182, 0 },
132530  { 182, 2 },
132531  { 182, 2 },
132532  { 161, 0 },
132533  { 184, 1 },
132534  { 185, 2 },
132535  { 185, 7 },
132536  { 185, 5 },
132537  { 185, 5 },
132538  { 185, 10 },
132539  { 188, 0 },
132540  { 174, 0 },
132541  { 174, 3 },
132542  { 189, 0 },
132543  { 189, 2 },
132544  { 190, 1 },
132545  { 190, 1 },
132546  { 149, 4 },
132547  { 192, 2 },
132548  { 192, 0 },
132549  { 149, 9 },
132550  { 149, 4 },
132551  { 149, 1 },
132552  { 163, 2 },
132553  { 194, 3 },
132554  { 197, 1 },
132555  { 197, 2 },
132556  { 197, 1 },
132557  { 195, 9 },
132558  { 206, 4 },
132559  { 206, 5 },
132560  { 198, 1 },
132561  { 198, 1 },
132562  { 198, 0 },
132563  { 209, 0 },
132564  { 199, 3 },
132565  { 199, 2 },
132566  { 199, 4 },
132567  { 210, 2 },
132568  { 210, 0 },
132569  { 200, 0 },
132570  { 200, 2 },
132571  { 212, 2 },
132572  { 212, 0 },
132573  { 211, 7 },
132574  { 211, 9 },
132575  { 211, 7 },
132576  { 211, 7 },
132577  { 159, 0 },
132578  { 159, 2 },
132579  { 193, 2 },
132580  { 213, 1 },
132581  { 213, 2 },
132582  { 213, 3 },
132583  { 213, 4 },
132584  { 215, 2 },
132585  { 215, 0 },
132586  { 214, 0 },
132587  { 214, 3 },
132588  { 214, 2 },
132589  { 216, 4 },
132590  { 216, 0 },
132591  { 204, 0 },
132592  { 204, 3 },
132593  { 186, 4 },
132594  { 186, 2 },
132595  { 175, 1 },
132596  { 175, 1 },
132597  { 175, 0 },
132598  { 202, 0 },
132599  { 202, 3 },
132600  { 203, 0 },
132601  { 203, 2 },
132602  { 205, 0 },
132603  { 205, 2 },
132604  { 205, 4 },
132605  { 205, 4 },
132606  { 149, 6 },
132607  { 201, 0 },
132608  { 201, 2 },
132609  { 149, 8 },
132610  { 218, 5 },
132611  { 218, 3 },
132612  { 149, 6 },
132613  { 149, 7 },
132614  { 219, 2 },
132615  { 219, 1 },
132616  { 220, 0 },
132617  { 220, 3 },
132618  { 217, 3 },
132619  { 217, 1 },
132620  { 173, 3 },
132621  { 172, 1 },
132622  { 173, 1 },
132623  { 173, 1 },
132624  { 173, 3 },
132625  { 173, 5 },
132626  { 172, 1 },
132627  { 172, 1 },
132628  { 173, 1 },
132629  { 173, 3 },
132630  { 173, 6 },
132631  { 173, 5 },
132632  { 173, 4 },
132633  { 172, 1 },
132634  { 173, 3 },
132635  { 173, 3 },
132636  { 173, 3 },
132637  { 173, 3 },
132638  { 173, 3 },
132639  { 173, 3 },
132640  { 173, 3 },
132641  { 173, 3 },
132642  { 221, 1 },
132643  { 221, 2 },
132644  { 173, 3 },
132645  { 173, 5 },
132646  { 173, 2 },
132647  { 173, 3 },
132648  { 173, 3 },
132649  { 173, 4 },
132650  { 173, 2 },
132651  { 173, 2 },
132652  { 173, 2 },
132653  { 173, 2 },
132654  { 222, 1 },
132655  { 222, 2 },
132656  { 173, 5 },
132657  { 223, 1 },
132658  { 223, 2 },
132659  { 173, 5 },
132660  { 173, 3 },
132661  { 173, 5 },
132662  { 173, 4 },
132663  { 173, 4 },
132664  { 173, 5 },
132665  { 225, 5 },
132666  { 225, 4 },
132667  { 226, 2 },
132668  { 226, 0 },
132669  { 224, 1 },
132670  { 224, 0 },
132671  { 208, 0 },
132672  { 207, 3 },
132673  { 207, 1 },
132674  { 149, 12 },
132675  { 227, 1 },
132676  { 227, 0 },
132677  { 177, 0 },
132678  { 177, 3 },
132679  { 187, 5 },
132680  { 187, 3 },
132681  { 228, 0 },
132682  { 228, 2 },
132683  { 149, 4 },
132684  { 149, 1 },
132685  { 149, 2 },
132686  { 149, 3 },
132687  { 149, 5 },
132688  { 149, 6 },
132689  { 149, 5 },
132690  { 149, 6 },
132691  { 169, 2 },
132692  { 170, 2 },
132693  { 149, 5 },
132694  { 230, 11 },
132695  { 232, 1 },
132696  { 232, 1 },
132697  { 232, 2 },
132698  { 232, 0 },
132699  { 233, 1 },
132700  { 233, 1 },
132701  { 233, 3 },
132702  { 235, 0 },
132703  { 235, 2 },
132704  { 231, 3 },
132705  { 231, 2 },
132706  { 237, 3 },
132707  { 238, 3 },
132708  { 238, 2 },
132709  { 236, 7 },
132710  { 236, 5 },
132711  { 236, 5 },
132712  { 236, 1 },
132713  { 173, 4 },
132714  { 173, 6 },
132715  { 191, 1 },
132716  { 191, 1 },
132717  { 191, 1 },
132718  { 149, 4 },
132719  { 149, 6 },
132720  { 149, 3 },
132721  { 240, 0 },
132722  { 240, 2 },
132723  { 149, 1 },
132724  { 149, 3 },
132725  { 149, 1 },
132726  { 149, 3 },
132727  { 149, 6 },
132728  { 149, 7 },
132729  { 241, 1 },
132730  { 149, 1 },
132731  { 149, 4 },
132732  { 243, 8 },
132733  { 245, 0 },
132734  { 246, 1 },
132735  { 246, 3 },
132736  { 247, 1 },
132737  { 196, 0 },
132738  { 196, 2 },
132739  { 196, 3 },
132740  { 249, 6 },
132741  { 249, 8 },
132742  { 144, 1 },
132743  { 145, 2 },
132744  { 145, 1 },
132745  { 146, 1 },
132746  { 146, 3 },
132747  { 147, 0 },
132748  { 151, 0 },
132749  { 151, 1 },
132750  { 151, 2 },
132751  { 153, 1 },
132752  { 153, 0 },
132753  { 149, 2 },
132754  { 160, 4 },
132755  { 160, 2 },
132756  { 152, 1 },
132757  { 152, 1 },
132758  { 152, 1 },
132759  { 166, 1 },
132760  { 167, 1 },
132761  { 168, 1 },
132762  { 168, 1 },
132763  { 165, 2 },
132764  { 165, 0 },
132765  { 171, 2 },
132766  { 161, 2 },
132767  { 183, 3 },
132768  { 183, 1 },
132769  { 184, 0 },
132770  { 188, 1 },
132771  { 190, 1 },
132772  { 194, 1 },
132773  { 195, 1 },
132774  { 209, 2 },
132775  { 210, 1 },
132776  { 173, 1 },
132777  { 208, 1 },
132778  { 229, 1 },
132779  { 229, 1 },
132780  { 229, 1 },
132781  { 229, 1 },
132782  { 229, 1 },
132783  { 169, 1 },
132784  { 234, 0 },
132785  { 234, 3 },
132786  { 237, 1 },
132787  { 238, 0 },
132788  { 239, 1 },
132789  { 239, 0 },
132790  { 242, 0 },
132791  { 242, 1 },
132792  { 244, 1 },
132793  { 244, 3 },
132794  { 245, 2 },
132795  { 248, 0 },
132796  { 248, 4 },
132797  { 248, 2 },
132798 };
132799 
132800 static void yy_accept(yyParser*); /* Forward Declaration */
132801 
132802 /*
132803 ** Perform a reduce action and the shift that must immediately
132804 ** follow the reduce.
132805 */
132806 static void yy_reduce(
132807  yyParser *yypParser, /* The parser */
132808  unsigned int yyruleno /* Number of the rule by which to reduce */
132809 ){
132810  int yygoto; /* The next state */
132811  int yyact; /* The next action */
132812  yyStackEntry *yymsp; /* The top of the parser's stack */
132813  int yysize; /* Amount to pop the stack */
132815  yymsp = &yypParser->yystack[yypParser->yyidx];
132816 #ifndef NDEBUG
132817  if( yyTraceFILE && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
132818  yysize = yyRuleInfo[yyruleno].nrhs;
132819  fprintf(yyTraceFILE, "%sReduce [%s], go to state %d.\n", yyTracePrompt,
132820  yyRuleName[yyruleno], yymsp[-yysize].stateno);
132821  }
132822 #endif /* NDEBUG */
132823 
132824  /* Check that the stack is large enough to grow by a single entry
132825  ** if the RHS of the rule is empty. This ensures that there is room
132826  ** enough on the stack to push the LHS value */
132827  if( yyRuleInfo[yyruleno].nrhs==0 ){
132828 #ifdef YYTRACKMAXSTACKDEPTH
132829  if( yypParser->yyidx>yypParser->yyidxMax ){
132830  yypParser->yyidxMax = yypParser->yyidx;
132831  }
132832 #endif
132833 #if YYSTACKDEPTH>0
132834  if( yypParser->yyidx>=YYSTACKDEPTH-1 ){
132835  yyStackOverflow(yypParser);
132836  return;
132837  }
132838 #else
132839  if( yypParser->yyidx>=yypParser->yystksz-1 ){
132840  yyGrowStack(yypParser);
132841  if( yypParser->yyidx>=yypParser->yystksz-1 ){
132842  yyStackOverflow(yypParser);
132843  return;
132844  }
132845  }
132846 #endif
132847  }
132848 
132849  switch( yyruleno ){
132850  /* Beginning here are the reduction cases. A typical example
132851  ** follows:
132852  ** case 0:
132853  ** #line <lineno> <grammarfile>
132854  ** { ... } // User supplied code
132855  ** #line <lineno> <thisfile>
132856  ** break;
132857  */
132858 /********** Begin reduce actions **********************************************/
132859  YYMINORTYPE yylhsminor;
132860  case 0: /* explain ::= EXPLAIN */
132861 { pParse->explain = 1; }
132862  break;
132863  case 1: /* explain ::= EXPLAIN QUERY PLAN */
132864 { pParse->explain = 2; }
132865  break;
132866  case 2: /* cmdx ::= cmd */
132867 { sqlite3FinishCoding(pParse); }
132868  break;
132869  case 3: /* cmd ::= BEGIN transtype trans_opt */
132870 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy392);}
132871  break;
132872  case 4: /* transtype ::= */
132873 {yymsp[1].minor.yy392 = TK_DEFERRED;}
132874  break;
132875  case 5: /* transtype ::= DEFERRED */
132876  case 6: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==6);
132877  case 7: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==7);
132878 {yymsp[0].minor.yy392 = yymsp[0].major; /*A-overwrites-X*/}
132879  break;
132880  case 8: /* cmd ::= COMMIT trans_opt */
132881  case 9: /* cmd ::= END trans_opt */ yytestcase(yyruleno==9);
132882 {sqlite3CommitTransaction(pParse);}
132883  break;
132884  case 10: /* cmd ::= ROLLBACK trans_opt */
132885 {sqlite3RollbackTransaction(pParse);}
132886  break;
132887  case 11: /* cmd ::= SAVEPOINT nm */
132888 {
132889  sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
132890 }
132891  break;
132892  case 12: /* cmd ::= RELEASE savepoint_opt nm */
132893 {
132894  sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
132895 }
132896  break;
132897  case 13: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
132898 {
132899  sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
132900 }
132901  break;
132902  case 14: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
132903 {
132904  sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy392,0,0,yymsp[-2].minor.yy392);
132905 }
132906  break;
132907  case 15: /* createkw ::= CREATE */
132908 {disableLookaside(pParse);}
132909  break;
132910  case 16: /* ifnotexists ::= */
132911  case 19: /* temp ::= */ yytestcase(yyruleno==19);
132912  case 22: /* table_options ::= */ yytestcase(yyruleno==22);
132913  case 42: /* autoinc ::= */ yytestcase(yyruleno==42);
132914  case 57: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==57);
132915  case 67: /* defer_subclause_opt ::= */ yytestcase(yyruleno==67);
132916  case 76: /* ifexists ::= */ yytestcase(yyruleno==76);
132917  case 90: /* distinct ::= */ yytestcase(yyruleno==90);
132918  case 209: /* collate ::= */ yytestcase(yyruleno==209);
132919 {yymsp[1].minor.yy392 = 0;}
132920  break;
132921  case 17: /* ifnotexists ::= IF NOT EXISTS */
132922 {yymsp[-2].minor.yy392 = 1;}
132923  break;
132924  case 18: /* temp ::= TEMP */
132925  case 43: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==43);
132926 {yymsp[0].minor.yy392 = 1;}
132927  break;
132928  case 20: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
132929 {
132930  sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy392,0);
132931 }
132932  break;
132933  case 21: /* create_table_args ::= AS select */
132934 {
132935  sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy159);
132936  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
132937 }
132938  break;
132939  case 23: /* table_options ::= WITHOUT nm */
132940 {
132941  if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
132943  }else{
132944  yymsp[-1].minor.yy392 = 0;
132945  sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
132946  }
132947 }
132948  break;
132949  case 24: /* columnname ::= nm typetoken */
132950 {sqlite3AddColumn(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
132951  break;
132952  case 25: /* typetoken ::= */
132953  case 60: /* conslist_opt ::= */ yytestcase(yyruleno==60);
132954  case 96: /* as ::= */ yytestcase(yyruleno==96);
132955 {yymsp[1].minor.yy0.n = 0; yymsp[1].minor.yy0.z = 0;}
132956  break;
132957  case 26: /* typetoken ::= typename LP signed RP */
132958 {
132959  yymsp[-3].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
132960 }
132961  break;
132962  case 27: /* typetoken ::= typename LP signed COMMA signed RP */
132963 {
132964  yymsp[-5].minor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
132965 }
132966  break;
132967  case 28: /* typename ::= typename ID|STRING */
132968 {yymsp[-1].minor.yy0.n=yymsp[0].minor.yy0.n+(int)(yymsp[0].minor.yy0.z-yymsp[-1].minor.yy0.z);}
132969  break;
132970  case 29: /* ccons ::= CONSTRAINT nm */
132971  case 62: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==62);
132972 {pParse->constraintName = yymsp[0].minor.yy0;}
132973  break;
132974  case 30: /* ccons ::= DEFAULT term */
132975  case 32: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==32);
132976 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy342);}
132977  break;
132978  case 31: /* ccons ::= DEFAULT LP expr RP */
132979 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy342);}
132980  break;
132981  case 33: /* ccons ::= DEFAULT MINUS term */
132982 {
132983  ExprSpan v;
132984  v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy342.pExpr, 0, 0);
132985  v.zStart = yymsp[-1].minor.yy0.z;
132986  v.zEnd = yymsp[0].minor.yy342.zEnd;
132987  sqlite3AddDefaultValue(pParse,&v);
132988 }
132989  break;
132990  case 34: /* ccons ::= DEFAULT ID|INDEXED */
132991 {
132992  ExprSpan v;
132993  spanExpr(&v, pParse, TK_STRING, yymsp[0].minor.yy0);
132994  sqlite3AddDefaultValue(pParse,&v);
132995 }
132996  break;
132997  case 35: /* ccons ::= NOT NULL onconf */
132998 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy392);}
132999  break;
133000  case 36: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
133001 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy392,yymsp[0].minor.yy392,yymsp[-2].minor.yy392);}
133002  break;
133003  case 37: /* ccons ::= UNIQUE onconf */
133004 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy392,0,0,0,0);}
133005  break;
133006  case 38: /* ccons ::= CHECK LP expr RP */
133007 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy342.pExpr);}
133008  break;
133009  case 39: /* ccons ::= REFERENCES nm eidlist_opt refargs */
133010 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy442,yymsp[0].minor.yy392);}
133011  break;
133012  case 40: /* ccons ::= defer_subclause */
133013 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy392);}
133014  break;
133015  case 41: /* ccons ::= COLLATE ID|STRING */
133016 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
133017  break;
133018  case 44: /* refargs ::= */
133019 { yymsp[1].minor.yy392 = OE_None*0x0101; /* EV: R-19803-45884 */}
133020  break;
133021  case 45: /* refargs ::= refargs refarg */
133022 { yymsp[-1].minor.yy392 = (yymsp[-1].minor.yy392 & ~yymsp[0].minor.yy207.mask) | yymsp[0].minor.yy207.value; }
133023  break;
133024  case 46: /* refarg ::= MATCH nm */
133025 { yymsp[-1].minor.yy207.value = 0; yymsp[-1].minor.yy207.mask = 0x000000; }
133026  break;
133027  case 47: /* refarg ::= ON INSERT refact */
133028 { yymsp[-2].minor.yy207.value = 0; yymsp[-2].minor.yy207.mask = 0x000000; }
133029  break;
133030  case 48: /* refarg ::= ON DELETE refact */
133031 { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy392; yymsp[-2].minor.yy207.mask = 0x0000ff; }
133032  break;
133033  case 49: /* refarg ::= ON UPDATE refact */
133034 { yymsp[-2].minor.yy207.value = yymsp[0].minor.yy392<<8; yymsp[-2].minor.yy207.mask = 0x00ff00; }
133035  break;
133036  case 50: /* refact ::= SET NULL */
133037 { yymsp[-1].minor.yy392 = OE_SetNull; /* EV: R-33326-45252 */}
133038  break;
133039  case 51: /* refact ::= SET DEFAULT */
133040 { yymsp[-1].minor.yy392 = OE_SetDflt; /* EV: R-33326-45252 */}
133041  break;
133042  case 52: /* refact ::= CASCADE */
133043 { yymsp[0].minor.yy392 = OE_Cascade; /* EV: R-33326-45252 */}
133044  break;
133045  case 53: /* refact ::= RESTRICT */
133046 { yymsp[0].minor.yy392 = OE_Restrict; /* EV: R-33326-45252 */}
133047  break;
133048  case 54: /* refact ::= NO ACTION */
133049 { yymsp[-1].minor.yy392 = OE_None; /* EV: R-33326-45252 */}
133050  break;
133051  case 55: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */
133052 {yymsp[-2].minor.yy392 = 0;}
133053  break;
133054  case 56: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
133055  case 71: /* orconf ::= OR resolvetype */ yytestcase(yyruleno==71);
133056  case 142: /* insert_cmd ::= INSERT orconf */ yytestcase(yyruleno==142);
133057 {yymsp[-1].minor.yy392 = yymsp[0].minor.yy392;}
133058  break;
133059  case 58: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */
133060  case 75: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==75);
133061  case 183: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==183);
133062  case 186: /* in_op ::= NOT IN */ yytestcase(yyruleno==186);
133063  case 210: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==210);
133064 {yymsp[-1].minor.yy392 = 1;}
133065  break;
133066  case 59: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */
133067 {yymsp[-1].minor.yy392 = 0;}
133068  break;
133069  case 61: /* tconscomma ::= COMMA */
133070 {pParse->constraintName.n = 0;}
133071  break;
133072  case 63: /* tcons ::= PRIMARY KEY LP sortlist autoinc RP onconf */
133073 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy442,yymsp[0].minor.yy392,yymsp[-2].minor.yy392,0);}
133074  break;
133075  case 64: /* tcons ::= UNIQUE LP sortlist RP onconf */
133076 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy442,yymsp[0].minor.yy392,0,0,0,0);}
133077  break;
133078  case 65: /* tcons ::= CHECK LP expr RP onconf */
133079 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy342.pExpr);}
133080  break;
133081  case 66: /* tcons ::= FOREIGN KEY LP eidlist RP REFERENCES nm eidlist_opt refargs defer_subclause_opt */
133082 {
133083  sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy442, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[-1].minor.yy392);
133084  sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy392);
133085 }
133086  break;
133087  case 68: /* onconf ::= */
133088  case 70: /* orconf ::= */ yytestcase(yyruleno==70);
133089 {yymsp[1].minor.yy392 = OE_Default;}
133090  break;
133091  case 69: /* onconf ::= ON CONFLICT resolvetype */
133092 {yymsp[-2].minor.yy392 = yymsp[0].minor.yy392;}
133093  break;
133094  case 72: /* resolvetype ::= IGNORE */
133095 {yymsp[0].minor.yy392 = OE_Ignore;}
133096  break;
133097  case 73: /* resolvetype ::= REPLACE */
133098  case 143: /* insert_cmd ::= REPLACE */ yytestcase(yyruleno==143);
133099 {yymsp[0].minor.yy392 = OE_Replace;}
133100  break;
133101  case 74: /* cmd ::= DROP TABLE ifexists fullname */
133102 {
133103  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 0, yymsp[-1].minor.yy392);
133104 }
133105  break;
133106  case 77: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm eidlist_opt AS select */
133107 {
133108  sqlite3CreateView(pParse, &yymsp[-8].minor.yy0, &yymsp[-4].minor.yy0, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy442, yymsp[0].minor.yy159, yymsp[-7].minor.yy392, yymsp[-5].minor.yy392);
133109 }
133110  break;
133111  case 78: /* cmd ::= DROP VIEW ifexists fullname */
133112 {
133113  sqlite3DropTable(pParse, yymsp[0].minor.yy347, 1, yymsp[-1].minor.yy392);
133114 }
133115  break;
133116  case 79: /* cmd ::= select */
133117 {
133118  SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
133119  sqlite3Select(pParse, yymsp[0].minor.yy159, &dest);
133120  sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy159);
133121 }
133122  break;
133123  case 80: /* select ::= with selectnowith */
133124 {
133125  Select *p = yymsp[0].minor.yy159;
133126  if( p ){
133127  p->pWith = yymsp[-1].minor.yy331;
133128  parserDoubleLinkSelect(pParse, p);
133129  }else{
133130  sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy331);
133131  }
133132  yymsp[-1].minor.yy159 = p; /*A-overwrites-W*/
133133 }
133134  break;
133135  case 81: /* selectnowith ::= selectnowith multiselect_op oneselect */
133136 {
133137  Select *pRhs = yymsp[0].minor.yy159;
133138  Select *pLhs = yymsp[-2].minor.yy159;
133139  if( pRhs && pRhs->pPrior ){
133140  SrcList *pFrom;
133141  Token x;
133142  x.n = 0;
133143  parserDoubleLinkSelect(pParse, pRhs);
133144  pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
133145  pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
133146  }
133147  if( pRhs ){
133148  pRhs->op = (u8)yymsp[-1].minor.yy392;
133149  pRhs->pPrior = pLhs;
133150  if( ALWAYS(pLhs) ) pLhs->selFlags &= ~SF_MultiValue;
133151  pRhs->selFlags &= ~SF_MultiValue;
133152  if( yymsp[-1].minor.yy392!=TK_ALL ) pParse->hasCompound = 1;
133153  }else{
133154  sqlite3SelectDelete(pParse->db, pLhs);
133155  }
133156  yymsp[-2].minor.yy159 = pRhs;
133157 }
133158  break;
133159  case 82: /* multiselect_op ::= UNION */
133160  case 84: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==84);
133161 {yymsp[0].minor.yy392 = yymsp[0].major; /*A-overwrites-OP*/}
133162  break;
133163  case 83: /* multiselect_op ::= UNION ALL */
133164 {yymsp[-1].minor.yy392 = TK_ALL;}
133165  break;
133166  case 85: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
133167 {
133168 #if SELECTTRACE_ENABLED
133169  Token s = yymsp[-8].minor.yy0; /*A-overwrites-S*/
133170 #endif
133171  yymsp[-8].minor.yy159 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy442,yymsp[-5].minor.yy347,yymsp[-4].minor.yy122,yymsp[-3].minor.yy442,yymsp[-2].minor.yy122,yymsp[-1].minor.yy442,yymsp[-7].minor.yy392,yymsp[0].minor.yy64.pLimit,yymsp[0].minor.yy64.pOffset);
133172 #if SELECTTRACE_ENABLED
133173  /* Populate the Select.zSelName[] string that is used to help with
133174  ** query planner debugging, to differentiate between multiple Select
133175  ** objects in a complex query.
133176  **
133177  ** If the SELECT keyword is immediately followed by a C-style comment
133178  ** then extract the first few alphanumeric characters from within that
133179  ** comment to be the zSelName value. Otherwise, the label is #N where
133180  ** is an integer that is incremented with each SELECT statement seen.
133181  */
133182  if( yymsp[-8].minor.yy159!=0 ){
133183  const char *z = s.z+6;
133184  int i;
133185  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy159->zSelName), yymsp[-8].minor.yy159->zSelName, "#%d",
133186  ++pParse->nSelect);
133187  while( z[0]==' ' ) z++;
133188  if( z[0]=='/' && z[1]=='*' ){
133189  z += 2;
133190  while( z[0]==' ' ) z++;
133191  for(i=0; sqlite3Isalnum(z[i]); i++){}
133192  sqlite3_snprintf(sizeof(yymsp[-8].minor.yy159->zSelName), yymsp[-8].minor.yy159->zSelName, "%.*s", i, z);
133193  }
133194  }
133195 #endif /* SELECTRACE_ENABLED */
133196 }
133197  break;
133198  case 86: /* values ::= VALUES LP nexprlist RP */
133199 {
133200  yymsp[-3].minor.yy159 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy442,0,0,0,0,0,SF_Values,0,0);
133201 }
133202  break;
133203  case 87: /* values ::= values COMMA LP exprlist RP */
133204 {
133205  Select *pRight, *pLeft = yymsp[-4].minor.yy159;
133206  pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy442,0,0,0,0,0,SF_Values|SF_MultiValue,0,0);
133207  if( ALWAYS(pLeft) ) pLeft->selFlags &= ~SF_MultiValue;
133208  if( pRight ){
133209  pRight->op = TK_ALL;
133210  pRight->pPrior = pLeft;
133211  yymsp[-4].minor.yy159 = pRight;
133212  }else{
133213  yymsp[-4].minor.yy159 = pLeft;
133214  }
133215 }
133216  break;
133217  case 88: /* distinct ::= DISTINCT */
133218 {yymsp[0].minor.yy392 = SF_Distinct;}
133219  break;
133220  case 89: /* distinct ::= ALL */
133221 {yymsp[0].minor.yy392 = SF_All;}
133222  break;
133223  case 91: /* sclp ::= */
133224  case 119: /* orderby_opt ::= */ yytestcase(yyruleno==119);
133225  case 126: /* groupby_opt ::= */ yytestcase(yyruleno==126);
133226  case 199: /* exprlist ::= */ yytestcase(yyruleno==199);
133227  case 205: /* eidlist_opt ::= */ yytestcase(yyruleno==205);
133228 {yymsp[1].minor.yy442 = 0;}
133229  break;
133230  case 92: /* selcollist ::= sclp expr as */
133231 {
133232  yymsp[-2].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy442, yymsp[-1].minor.yy342.pExpr);
133233  if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yymsp[-2].minor.yy442, &yymsp[0].minor.yy0, 1);
133234  sqlite3ExprListSetSpan(pParse,yymsp[-2].minor.yy442,&yymsp[-1].minor.yy342);
133235 }
133236  break;
133237  case 93: /* selcollist ::= sclp STAR */
133238 {
133239  Expr *p = sqlite3Expr(pParse->db, TK_ASTERISK, 0);
133240  yymsp[-1].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy442, p);
133241 }
133242  break;
133243  case 94: /* selcollist ::= sclp nm DOT STAR */
133244 {
133245  Expr *pRight = sqlite3PExpr(pParse, TK_ASTERISK, 0, 0, &yymsp[0].minor.yy0);
133246  Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
133247  Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
133248  yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, pDot);
133249 }
133250  break;
133251  case 95: /* as ::= AS nm */
133252  case 106: /* dbnm ::= DOT nm */ yytestcase(yyruleno==106);
133253  case 219: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==219);
133254  case 220: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==220);
133255 {yymsp[-1].minor.yy0 = yymsp[0].minor.yy0;}
133256  break;
133257  case 97: /* from ::= */
133258 {yymsp[1].minor.yy347 = sqlite3DbMallocZero(pParse->db, sizeof(*yymsp[1].minor.yy347));}
133259  break;
133260  case 98: /* from ::= FROM seltablist */
133261 {
133262  yymsp[-1].minor.yy347 = yymsp[0].minor.yy347;
133263  sqlite3SrcListShiftJoinType(yymsp[-1].minor.yy347);
133264 }
133265  break;
133266  case 99: /* stl_prefix ::= seltablist joinop */
133267 {
133268  if( ALWAYS(yymsp[-1].minor.yy347 && yymsp[-1].minor.yy347->nSrc>0) ) yymsp[-1].minor.yy347->a[yymsp[-1].minor.yy347->nSrc-1].fg.jointype = (u8)yymsp[0].minor.yy392;
133269 }
133270  break;
133271  case 100: /* stl_prefix ::= */
133272 {yymsp[1].minor.yy347 = 0;}
133273  break;
133274  case 101: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
133275 {
133276  yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
133277  sqlite3SrcListIndexedBy(pParse, yymsp[-6].minor.yy347, &yymsp[-2].minor.yy0);
133278 }
133279  break;
133280  case 102: /* seltablist ::= stl_prefix nm dbnm LP exprlist RP as on_opt using_opt */
133281 {
133282  yymsp[-8].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-8].minor.yy347,&yymsp[-7].minor.yy0,&yymsp[-6].minor.yy0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
133283  sqlite3SrcListFuncArgs(pParse, yymsp[-8].minor.yy347, yymsp[-4].minor.yy442);
133284 }
133285  break;
133286  case 103: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
133287 {
133288  yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy159,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
133289  }
133290  break;
133291  case 104: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
133292 {
133293  if( yymsp[-6].minor.yy347==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy122==0 && yymsp[0].minor.yy180==0 ){
133294  yymsp[-6].minor.yy347 = yymsp[-4].minor.yy347;
133295  }else if( yymsp[-4].minor.yy347->nSrc==1 ){
133296  yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
133297  if( yymsp[-6].minor.yy347 ){
133298  struct SrcList_item *pNew = &yymsp[-6].minor.yy347->a[yymsp[-6].minor.yy347->nSrc-1];
133299  struct SrcList_item *pOld = yymsp[-4].minor.yy347->a;
133300  pNew->zName = pOld->zName;
133301  pNew->zDatabase = pOld->zDatabase;
133302  pNew->pSelect = pOld->pSelect;
133303  pOld->zName = pOld->zDatabase = 0;
133304  pOld->pSelect = 0;
133305  }
133306  sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy347);
133307  }else{
133308  Select *pSubquery;
133309  sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy347);
133310  pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy347,0,0,0,0,SF_NestedFrom,0,0);
133311  yymsp[-6].minor.yy347 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy347,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy122,yymsp[0].minor.yy180);
133312  }
133313  }
133314  break;
133315  case 105: /* dbnm ::= */
133316  case 114: /* indexed_opt ::= */ yytestcase(yyruleno==114);
133317 {yymsp[1].minor.yy0.z=0; yymsp[1].minor.yy0.n=0;}
133318  break;
133319  case 107: /* fullname ::= nm dbnm */
133320 {yymsp[-1].minor.yy347 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/}
133321  break;
133322  case 108: /* joinop ::= COMMA|JOIN */
133323 { yymsp[0].minor.yy392 = JT_INNER; }
133324  break;
133325  case 109: /* joinop ::= JOIN_KW JOIN */
133326 {yymsp[-1].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); /*X-overwrites-A*/}
133327  break;
133328  case 110: /* joinop ::= JOIN_KW nm JOIN */
133329 {yymsp[-2].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); /*X-overwrites-A*/}
133330  break;
133331  case 111: /* joinop ::= JOIN_KW nm nm JOIN */
133332 {yymsp[-3].minor.yy392 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0);/*X-overwrites-A*/}
133333  break;
133334  case 112: /* on_opt ::= ON expr */
133335  case 129: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==129);
133336  case 136: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==136);
133337  case 195: /* case_else ::= ELSE expr */ yytestcase(yyruleno==195);
133338 {yymsp[-1].minor.yy122 = yymsp[0].minor.yy342.pExpr;}
133339  break;
133340  case 113: /* on_opt ::= */
133341  case 128: /* having_opt ::= */ yytestcase(yyruleno==128);
133342  case 135: /* where_opt ::= */ yytestcase(yyruleno==135);
133343  case 196: /* case_else ::= */ yytestcase(yyruleno==196);
133344  case 198: /* case_operand ::= */ yytestcase(yyruleno==198);
133345 {yymsp[1].minor.yy122 = 0;}
133346  break;
133347  case 115: /* indexed_opt ::= INDEXED BY nm */
133348 {yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;}
133349  break;
133350  case 116: /* indexed_opt ::= NOT INDEXED */
133351 {yymsp[-1].minor.yy0.z=0; yymsp[-1].minor.yy0.n=1;}
133352  break;
133353  case 117: /* using_opt ::= USING LP idlist RP */
133354 {yymsp[-3].minor.yy180 = yymsp[-1].minor.yy180;}
133355  break;
133356  case 118: /* using_opt ::= */
133357  case 144: /* idlist_opt ::= */ yytestcase(yyruleno==144);
133358 {yymsp[1].minor.yy180 = 0;}
133359  break;
133360  case 120: /* orderby_opt ::= ORDER BY sortlist */
133361  case 127: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==127);
133362 {yymsp[-2].minor.yy442 = yymsp[0].minor.yy442;}
133363  break;
133364  case 121: /* sortlist ::= sortlist COMMA expr sortorder */
133365 {
133366  yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442,yymsp[-1].minor.yy342.pExpr);
133367  sqlite3ExprListSetSortOrder(yymsp[-3].minor.yy442,yymsp[0].minor.yy392);
133368 }
133369  break;
133370  case 122: /* sortlist ::= expr sortorder */
133371 {
133372  yymsp[-1].minor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy342.pExpr); /*A-overwrites-Y*/
133373  sqlite3ExprListSetSortOrder(yymsp[-1].minor.yy442,yymsp[0].minor.yy392);
133374 }
133375  break;
133376  case 123: /* sortorder ::= ASC */
133377 {yymsp[0].minor.yy392 = SQLITE_SO_ASC;}
133378  break;
133379  case 124: /* sortorder ::= DESC */
133380 {yymsp[0].minor.yy392 = SQLITE_SO_DESC;}
133381  break;
133382  case 125: /* sortorder ::= */
133383 {yymsp[1].minor.yy392 = SQLITE_SO_UNDEFINED;}
133384  break;
133385  case 130: /* limit_opt ::= */
133386 {yymsp[1].minor.yy64.pLimit = 0; yymsp[1].minor.yy64.pOffset = 0;}
133387  break;
133388  case 131: /* limit_opt ::= LIMIT expr */
133389 {yymsp[-1].minor.yy64.pLimit = yymsp[0].minor.yy342.pExpr; yymsp[-1].minor.yy64.pOffset = 0;}
133390  break;
133391  case 132: /* limit_opt ::= LIMIT expr OFFSET expr */
133392 {yymsp[-3].minor.yy64.pLimit = yymsp[-2].minor.yy342.pExpr; yymsp[-3].minor.yy64.pOffset = yymsp[0].minor.yy342.pExpr;}
133393  break;
133394  case 133: /* limit_opt ::= LIMIT expr COMMA expr */
133395 {yymsp[-3].minor.yy64.pOffset = yymsp[-2].minor.yy342.pExpr; yymsp[-3].minor.yy64.pLimit = yymsp[0].minor.yy342.pExpr;}
133396  break;
133397  case 134: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
133398 {
133399  sqlite3WithPush(pParse, yymsp[-5].minor.yy331, 1);
133400  sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy347, &yymsp[-1].minor.yy0);
133401  sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy347,yymsp[0].minor.yy122);
133402 }
133403  break;
133404  case 137: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
133405 {
133406  sqlite3WithPush(pParse, yymsp[-7].minor.yy331, 1);
133407  sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy347, &yymsp[-3].minor.yy0);
133408  sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy442,"set list");
133409  sqlite3Update(pParse,yymsp[-4].minor.yy347,yymsp[-1].minor.yy442,yymsp[0].minor.yy122,yymsp[-5].minor.yy392);
133410 }
133411  break;
133412  case 138: /* setlist ::= setlist COMMA nm EQ expr */
133413 {
133414  yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
133415  sqlite3ExprListSetName(pParse, yymsp[-4].minor.yy442, &yymsp[-2].minor.yy0, 1);
133416 }
133417  break;
133418  case 139: /* setlist ::= nm EQ expr */
133419 {
133420  yylhsminor.yy442 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy342.pExpr);
133421  sqlite3ExprListSetName(pParse, yylhsminor.yy442, &yymsp[-2].minor.yy0, 1);
133422 }
133423  yymsp[-2].minor.yy442 = yylhsminor.yy442;
133424  break;
133425  case 140: /* cmd ::= with insert_cmd INTO fullname idlist_opt select */
133426 {
133427  sqlite3WithPush(pParse, yymsp[-5].minor.yy331, 1);
133428  sqlite3Insert(pParse, yymsp[-2].minor.yy347, yymsp[0].minor.yy159, yymsp[-1].minor.yy180, yymsp[-4].minor.yy392);
133429 }
133430  break;
133431  case 141: /* cmd ::= with insert_cmd INTO fullname idlist_opt DEFAULT VALUES */
133432 {
133433  sqlite3WithPush(pParse, yymsp[-6].minor.yy331, 1);
133434  sqlite3Insert(pParse, yymsp[-3].minor.yy347, 0, yymsp[-2].minor.yy180, yymsp[-5].minor.yy392);
133435 }
133436  break;
133437  case 145: /* idlist_opt ::= LP idlist RP */
133438 {yymsp[-2].minor.yy180 = yymsp[-1].minor.yy180;}
133439  break;
133440  case 146: /* idlist ::= idlist COMMA nm */
133441 {yymsp[-2].minor.yy180 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy180,&yymsp[0].minor.yy0);}
133442  break;
133443  case 147: /* idlist ::= nm */
133444 {yymsp[0].minor.yy180 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0); /*A-overwrites-Y*/}
133445  break;
133446  case 148: /* expr ::= LP expr RP */
133447 {spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/ yymsp[-2].minor.yy342.pExpr = yymsp[-1].minor.yy342.pExpr;}
133448  break;
133449  case 149: /* term ::= NULL */
133450  case 154: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==154);
133451  case 155: /* term ::= STRING */ yytestcase(yyruleno==155);
133452 {spanExpr(&yymsp[0].minor.yy342,pParse,yymsp[0].major,yymsp[0].minor.yy0);/*A-overwrites-X*/}
133453  break;
133454  case 150: /* expr ::= ID|INDEXED */
133455  case 151: /* expr ::= JOIN_KW */ yytestcase(yyruleno==151);
133456 {spanExpr(&yymsp[0].minor.yy342,pParse,TK_ID,yymsp[0].minor.yy0); /*A-overwrites-X*/}
133457  break;
133458  case 152: /* expr ::= nm DOT nm */
133459 {
133460  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
133461  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
133462  spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
133463  yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
133464 }
133465  break;
133466  case 153: /* expr ::= nm DOT nm DOT nm */
133467 {
133468  Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
133469  Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
133470  Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
133471  Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
133472  spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
133473  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
133474 }
133475  break;
133476  case 156: /* expr ::= VARIABLE */
133477 {
133478  if( !(yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1])) ){
133479  spanExpr(&yymsp[0].minor.yy342, pParse, TK_VARIABLE, yymsp[0].minor.yy0);
133480  sqlite3ExprAssignVarNumber(pParse, yymsp[0].minor.yy342.pExpr);
133481  }else{
133482  /* When doing a nested parse, one can include terms in an expression
133483  ** that look like this: #1 #2 ... These terms refer to registers
133484  ** in the virtual machine. #N is the N-th register. */
133485  Token t = yymsp[0].minor.yy0; /*A-overwrites-X*/
133486  assert( t.n>=2 );
133487  spanSet(&yymsp[0].minor.yy342, &t, &t);
133488  if( pParse->nested==0 ){
133489  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &t);
133490  yymsp[0].minor.yy342.pExpr = 0;
133491  }else{
133492  yymsp[0].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &t);
133493  if( yymsp[0].minor.yy342.pExpr ) sqlite3GetInt32(&t.z[1], &yymsp[0].minor.yy342.pExpr->iTable);
133494  }
133495  }
133496 }
133497  break;
133498  case 157: /* expr ::= expr COLLATE ID|STRING */
133499 {
133500  yymsp[-2].minor.yy342.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy342.pExpr, &yymsp[0].minor.yy0, 1);
133501  yymsp[-2].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
133502 }
133503  break;
133504  case 158: /* expr ::= CAST LP expr AS typetoken RP */
133505 {
133506  spanSet(&yymsp[-5].minor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
133507  yymsp[-5].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy342.pExpr, 0, &yymsp[-1].minor.yy0);
133508 }
133509  break;
133510  case 159: /* expr ::= ID|INDEXED LP distinct exprlist RP */
133511 {
133512  if( yymsp[-1].minor.yy442 && yymsp[-1].minor.yy442->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
133513  sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
133514  }
133515  yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy442, &yymsp[-4].minor.yy0);
133516  spanSet(&yylhsminor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
133517  if( yymsp[-2].minor.yy392==SF_Distinct && yylhsminor.yy342.pExpr ){
133518  yylhsminor.yy342.pExpr->flags |= EP_Distinct;
133519  }
133520 }
133521  yymsp[-4].minor.yy342 = yylhsminor.yy342;
133522  break;
133523  case 160: /* expr ::= ID|INDEXED LP STAR RP */
133524 {
133525  yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
133526  spanSet(&yylhsminor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
133527 }
133528  yymsp[-3].minor.yy342 = yylhsminor.yy342;
133529  break;
133530  case 161: /* term ::= CTIME_KW */
133531 {
133532  yylhsminor.yy342.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
133533  spanSet(&yylhsminor.yy342, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
133534 }
133535  yymsp[0].minor.yy342 = yylhsminor.yy342;
133536  break;
133537  case 162: /* expr ::= expr AND expr */
133538  case 163: /* expr ::= expr OR expr */ yytestcase(yyruleno==163);
133539  case 164: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==164);
133540  case 165: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==165);
133541  case 166: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==166);
133542  case 167: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==167);
133543  case 168: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==168);
133544  case 169: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==169);
133545 {spanBinaryExpr(pParse,yymsp[-1].major,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);}
133546  break;
133547  case 170: /* likeop ::= LIKE_KW|MATCH */
133548 {yymsp[0].minor.yy318.eOperator = yymsp[0].minor.yy0; yymsp[0].minor.yy318.bNot = 0;/*A-overwrites-X*/}
133549  break;
133550  case 171: /* likeop ::= NOT LIKE_KW|MATCH */
133551 {yymsp[-1].minor.yy318.eOperator = yymsp[0].minor.yy0; yymsp[-1].minor.yy318.bNot = 1;}
133552  break;
133553  case 172: /* expr ::= expr likeop expr */
133554 {
133555  ExprList *pList;
133556  pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy342.pExpr);
133557  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy342.pExpr);
133558  yymsp[-2].minor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy318.eOperator);
133559  exprNot(pParse, yymsp[-1].minor.yy318.bNot, &yymsp[-2].minor.yy342);
133560  yymsp[-2].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
133561  if( yymsp[-2].minor.yy342.pExpr ) yymsp[-2].minor.yy342.pExpr->flags |= EP_InfixFunc;
133562 }
133563  break;
133564  case 173: /* expr ::= expr likeop expr ESCAPE expr */
133565 {
133566  ExprList *pList;
133567  pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
133568  pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy342.pExpr);
133569  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
133570  yymsp[-4].minor.yy342.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy318.eOperator);
133571  exprNot(pParse, yymsp[-3].minor.yy318.bNot, &yymsp[-4].minor.yy342);
133572  yymsp[-4].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
133573  if( yymsp[-4].minor.yy342.pExpr ) yymsp[-4].minor.yy342.pExpr->flags |= EP_InfixFunc;
133574 }
133575  break;
133576  case 174: /* expr ::= expr ISNULL|NOTNULL */
133577 {spanUnaryPostfix(pParse,yymsp[0].major,&yymsp[-1].minor.yy342,&yymsp[0].minor.yy0);}
133578  break;
133579  case 175: /* expr ::= expr NOT NULL */
133580 {spanUnaryPostfix(pParse,TK_NOTNULL,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy0);}
133581  break;
133582  case 176: /* expr ::= expr IS expr */
133583 {
133584  spanBinaryExpr(pParse,TK_IS,&yymsp[-2].minor.yy342,&yymsp[0].minor.yy342);
133585  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yymsp[-2].minor.yy342.pExpr, TK_ISNULL);
133586 }
133587  break;
133588  case 177: /* expr ::= expr IS NOT expr */
133589 {
133590  spanBinaryExpr(pParse,TK_ISNOT,&yymsp[-3].minor.yy342,&yymsp[0].minor.yy342);
133591  binaryToUnaryIfNull(pParse, yymsp[0].minor.yy342.pExpr, yymsp[-3].minor.yy342.pExpr, TK_NOTNULL);
133592 }
133593  break;
133594  case 178: /* expr ::= NOT expr */
133595  case 179: /* expr ::= BITNOT expr */ yytestcase(yyruleno==179);
133596 {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,yymsp[-1].major,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
133597  break;
133598  case 180: /* expr ::= MINUS expr */
133599 {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,TK_UMINUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
133600  break;
133601  case 181: /* expr ::= PLUS expr */
133602 {spanUnaryPrefix(&yymsp[-1].minor.yy342,pParse,TK_UPLUS,&yymsp[0].minor.yy342,&yymsp[-1].minor.yy0);/*A-overwrites-B*/}
133603  break;
133604  case 182: /* between_op ::= BETWEEN */
133605  case 185: /* in_op ::= IN */ yytestcase(yyruleno==185);
133606 {yymsp[0].minor.yy392 = 0;}
133607  break;
133608  case 184: /* expr ::= expr between_op expr AND expr */
133609 {
133610  ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
133611  pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy342.pExpr);
133612  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy342.pExpr, 0, 0);
133613  if( yymsp[-4].minor.yy342.pExpr ){
133614  yymsp[-4].minor.yy342.pExpr->x.pList = pList;
133615  }else{
133616  sqlite3ExprListDelete(pParse->db, pList);
133617  }
133618  exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
133619  yymsp[-4].minor.yy342.zEnd = yymsp[0].minor.yy342.zEnd;
133620 }
133621  break;
133622  case 187: /* expr ::= expr in_op LP exprlist RP */
133623 {
133624  if( yymsp[-1].minor.yy442==0 ){
133625  /* Expressions of the form
133626  **
133627  ** expr1 IN ()
133628  ** expr1 NOT IN ()
133629  **
133630  ** simplify to constants 0 (false) and 1 (true), respectively,
133631  ** regardless of the value of expr1.
133632  */
133633  sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy342.pExpr);
133634  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy392]);
133635  }else if( yymsp[-1].minor.yy442->nExpr==1 ){
133636  /* Expressions of the form:
133637  **
133638  ** expr1 IN (?1)
133639  ** expr1 NOT IN (?2)
133640  **
133641  ** with exactly one value on the RHS can be simplified to something
133642  ** like this:
133643  **
133644  ** expr1 == ?1
133645  ** expr1 <> ?2
133646  **
133647  ** But, the RHS of the == or <> is marked with the EP_Generic flag
133648  ** so that it may not contribute to the computation of comparison
133649  ** affinity or the collating sequence to use for comparison. Otherwise,
133650  ** the semantics would be subtly different from IN or NOT IN.
133651  */
133652  Expr *pRHS = yymsp[-1].minor.yy442->a[0].pExpr;
133653  yymsp[-1].minor.yy442->a[0].pExpr = 0;
133654  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
133655  /* pRHS cannot be NULL because a malloc error would have been detected
133656  ** before now and control would have never reached this point */
133657  if( ALWAYS(pRHS) ){
133658  pRHS->flags &= ~EP_Collate;
133659  pRHS->flags |= EP_Generic;
133660  }
133661  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy392 ? TK_NE : TK_EQ, yymsp[-4].minor.yy342.pExpr, pRHS, 0);
133662  }else{
133663  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
133664  if( yymsp[-4].minor.yy342.pExpr ){
133665  yymsp[-4].minor.yy342.pExpr->x.pList = yymsp[-1].minor.yy442;
133666  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
133667  }else{
133668  sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy442);
133669  }
133670  exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
133671  }
133672  yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
133673  }
133674  break;
133675  case 188: /* expr ::= LP select RP */
133676 {
133677  spanSet(&yymsp[-2].minor.yy342,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
133678  yymsp[-2].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
133679  sqlite3PExprAddSelect(pParse, yymsp[-2].minor.yy342.pExpr, yymsp[-1].minor.yy159);
133680  }
133681  break;
133682  case 189: /* expr ::= expr in_op LP select RP */
133683 {
133684  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy342.pExpr, 0, 0);
133685  sqlite3PExprAddSelect(pParse, yymsp[-4].minor.yy342.pExpr, yymsp[-1].minor.yy159);
133686  exprNot(pParse, yymsp[-3].minor.yy392, &yymsp[-4].minor.yy342);
133687  yymsp[-4].minor.yy342.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
133688  }
133689  break;
133690  case 190: /* expr ::= expr in_op nm dbnm */
133691 {
133692  SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
133693  Select *pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
133694  yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy342.pExpr, 0, 0);
133695  sqlite3PExprAddSelect(pParse, yymsp[-3].minor.yy342.pExpr, pSelect);
133696  exprNot(pParse, yymsp[-2].minor.yy392, &yymsp[-3].minor.yy342);
133697  yymsp[-3].minor.yy342.zEnd = yymsp[0].minor.yy0.z ? &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] : &yymsp[-1].minor.yy0.z[yymsp[-1].minor.yy0.n];
133698  }
133699  break;
133700  case 191: /* expr ::= EXISTS LP select RP */
133701 {
133702  Expr *p;
133703  spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-B*/
133704  p = yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
133705  sqlite3PExprAddSelect(pParse, p, yymsp[-1].minor.yy159);
133706  }
133707  break;
133708  case 192: /* expr ::= CASE case_operand case_exprlist case_else END */
133709 {
133710  spanSet(&yymsp[-4].minor.yy342,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-C*/
133711  yymsp[-4].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy122, 0, 0);
133712  if( yymsp[-4].minor.yy342.pExpr ){
133713  yymsp[-4].minor.yy342.pExpr->x.pList = yymsp[-1].minor.yy122 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[-1].minor.yy122) : yymsp[-2].minor.yy442;
133714  sqlite3ExprSetHeightAndFlags(pParse, yymsp[-4].minor.yy342.pExpr);
133715  }else{
133716  sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy442);
133717  sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy122);
133718  }
133719 }
133720  break;
133721  case 193: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
133722 {
133723  yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[-2].minor.yy342.pExpr);
133724  yymsp[-4].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy442, yymsp[0].minor.yy342.pExpr);
133725 }
133726  break;
133727  case 194: /* case_exprlist ::= WHEN expr THEN expr */
133728 {
133729  yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy342.pExpr);
133730  yymsp[-3].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy442, yymsp[0].minor.yy342.pExpr);
133731 }
133732  break;
133733  case 197: /* case_operand ::= expr */
133734 {yymsp[0].minor.yy122 = yymsp[0].minor.yy342.pExpr; /*A-overwrites-X*/}
133735  break;
133736  case 200: /* nexprlist ::= nexprlist COMMA expr */
133737 {yymsp[-2].minor.yy442 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy442,yymsp[0].minor.yy342.pExpr);}
133738  break;
133739  case 201: /* nexprlist ::= expr */
133740 {yymsp[0].minor.yy442 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy342.pExpr); /*A-overwrites-Y*/}
133741  break;
133742  case 202: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP sortlist RP where_opt */
133743 {
133744  sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
133745  sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy442, yymsp[-10].minor.yy392,
133746  &yymsp[-11].minor.yy0, yymsp[0].minor.yy122, SQLITE_SO_ASC, yymsp[-8].minor.yy392);
133747 }
133748  break;
133749  case 203: /* uniqueflag ::= UNIQUE */
133750  case 244: /* raisetype ::= ABORT */ yytestcase(yyruleno==244);
133751 {yymsp[0].minor.yy392 = OE_Abort;}
133752  break;
133753  case 204: /* uniqueflag ::= */
133754 {yymsp[1].minor.yy392 = OE_None;}
133755  break;
133756  case 206: /* eidlist_opt ::= LP eidlist RP */
133757 {yymsp[-2].minor.yy442 = yymsp[-1].minor.yy442;}
133758  break;
133759  case 207: /* eidlist ::= eidlist COMMA nm collate sortorder */
133760 {
133761  yymsp[-4].minor.yy442 = parserAddExprIdListTerm(pParse, yymsp[-4].minor.yy442, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy392, yymsp[0].minor.yy392);
133762 }
133763  break;
133764  case 208: /* eidlist ::= nm collate sortorder */
133765 {
133766  yymsp[-2].minor.yy442 = parserAddExprIdListTerm(pParse, 0, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy392, yymsp[0].minor.yy392); /*A-overwrites-Y*/
133767 }
133768  break;
133769  case 211: /* cmd ::= DROP INDEX ifexists fullname */
133770 {sqlite3DropIndex(pParse, yymsp[0].minor.yy347, yymsp[-1].minor.yy392);}
133771  break;
133772  case 212: /* cmd ::= VACUUM */
133773  case 213: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==213);
133774 {sqlite3Vacuum(pParse);}
133775  break;
133776  case 214: /* cmd ::= PRAGMA nm dbnm */
133777 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
133778  break;
133779  case 215: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
133780 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
133781  break;
133782  case 216: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
133783 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
133784  break;
133785  case 217: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
133786 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
133787  break;
133788  case 218: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
133789 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
133790  break;
133791  case 221: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
133792 {
133793  Token all;
133794  all.z = yymsp[-3].minor.yy0.z;
133795  all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
133796  sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy327, &all);
133797 }
133798  break;
133799  case 222: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
133800 {
133801  sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy392, yymsp[-4].minor.yy410.a, yymsp[-4].minor.yy410.b, yymsp[-2].minor.yy347, yymsp[0].minor.yy122, yymsp[-10].minor.yy392, yymsp[-8].minor.yy392);
133802  yymsp[-10].minor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0); /*A-overwrites-T*/
133803 }
133804  break;
133805  case 223: /* trigger_time ::= BEFORE */
133806 { yymsp[0].minor.yy392 = TK_BEFORE; }
133807  break;
133808  case 224: /* trigger_time ::= AFTER */
133809 { yymsp[0].minor.yy392 = TK_AFTER; }
133810  break;
133811  case 225: /* trigger_time ::= INSTEAD OF */
133812 { yymsp[-1].minor.yy392 = TK_INSTEAD;}
133813  break;
133814  case 226: /* trigger_time ::= */
133815 { yymsp[1].minor.yy392 = TK_BEFORE; }
133816  break;
133817  case 227: /* trigger_event ::= DELETE|INSERT */
133818  case 228: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==228);
133819 {yymsp[0].minor.yy410.a = yymsp[0].major; /*A-overwrites-X*/ yymsp[0].minor.yy410.b = 0;}
133820  break;
133821  case 229: /* trigger_event ::= UPDATE OF idlist */
133822 {yymsp[-2].minor.yy410.a = TK_UPDATE; yymsp[-2].minor.yy410.b = yymsp[0].minor.yy180;}
133823  break;
133824  case 230: /* when_clause ::= */
133825  case 249: /* key_opt ::= */ yytestcase(yyruleno==249);
133826 { yymsp[1].minor.yy122 = 0; }
133827  break;
133828  case 231: /* when_clause ::= WHEN expr */
133829  case 250: /* key_opt ::= KEY expr */ yytestcase(yyruleno==250);
133830 { yymsp[-1].minor.yy122 = yymsp[0].minor.yy342.pExpr; }
133831  break;
133832  case 232: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
133833 {
133834  assert( yymsp[-2].minor.yy327!=0 );
133835  yymsp[-2].minor.yy327->pLast->pNext = yymsp[-1].minor.yy327;
133836  yymsp[-2].minor.yy327->pLast = yymsp[-1].minor.yy327;
133837 }
133838  break;
133839  case 233: /* trigger_cmd_list ::= trigger_cmd SEMI */
133840 {
133841  assert( yymsp[-1].minor.yy327!=0 );
133842  yymsp[-1].minor.yy327->pLast = yymsp[-1].minor.yy327;
133843 }
133844  break;
133845  case 234: /* trnm ::= nm DOT nm */
133846 {
133847  yymsp[-2].minor.yy0 = yymsp[0].minor.yy0;
133848  sqlite3ErrorMsg(pParse,
133849  "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
133850  "statements within triggers");
133851 }
133852  break;
133853  case 235: /* tridxby ::= INDEXED BY nm */
133854 {
133855  sqlite3ErrorMsg(pParse,
133856  "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
133857  "within triggers");
133858 }
133859  break;
133860  case 236: /* tridxby ::= NOT INDEXED */
133861 {
133862  sqlite3ErrorMsg(pParse,
133863  "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
133864  "within triggers");
133865 }
133866  break;
133867  case 237: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
133868 {yymsp[-6].minor.yy327 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy442, yymsp[0].minor.yy122, yymsp[-5].minor.yy392);}
133869  break;
133870  case 238: /* trigger_cmd ::= insert_cmd INTO trnm idlist_opt select */
133871 {yymsp[-4].minor.yy327 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy180, yymsp[0].minor.yy159, yymsp[-4].minor.yy392);/*A-overwrites-R*/}
133872  break;
133873  case 239: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
133874 {yymsp[-4].minor.yy327 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy122);}
133875  break;
133876  case 240: /* trigger_cmd ::= select */
133877 {yymsp[0].minor.yy327 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy159); /*A-overwrites-X*/}
133878  break;
133879  case 241: /* expr ::= RAISE LP IGNORE RP */
133880 {
133881  spanSet(&yymsp[-3].minor.yy342,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
133882  yymsp[-3].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
133883  if( yymsp[-3].minor.yy342.pExpr ){
133884  yymsp[-3].minor.yy342.pExpr->affinity = OE_Ignore;
133885  }
133886 }
133887  break;
133888  case 242: /* expr ::= RAISE LP raisetype COMMA nm RP */
133889 {
133890  spanSet(&yymsp[-5].minor.yy342,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0); /*A-overwrites-X*/
133891  yymsp[-5].minor.yy342.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
133892  if( yymsp[-5].minor.yy342.pExpr ) {
133893  yymsp[-5].minor.yy342.pExpr->affinity = (char)yymsp[-3].minor.yy392;
133894  }
133895 }
133896  break;
133897  case 243: /* raisetype ::= ROLLBACK */
133898 {yymsp[0].minor.yy392 = OE_Rollback;}
133899  break;
133900  case 245: /* raisetype ::= FAIL */
133901 {yymsp[0].minor.yy392 = OE_Fail;}
133902  break;
133903  case 246: /* cmd ::= DROP TRIGGER ifexists fullname */
133904 {
133905  sqlite3DropTrigger(pParse,yymsp[0].minor.yy347,yymsp[-1].minor.yy392);
133906 }
133907  break;
133908  case 247: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
133909 {
133910  sqlite3Attach(pParse, yymsp[-3].minor.yy342.pExpr, yymsp[-1].minor.yy342.pExpr, yymsp[0].minor.yy122);
133911 }
133912  break;
133913  case 248: /* cmd ::= DETACH database_kw_opt expr */
133914 {
133915  sqlite3Detach(pParse, yymsp[0].minor.yy342.pExpr);
133916 }
133917  break;
133918  case 251: /* cmd ::= REINDEX */
133919 {sqlite3Reindex(pParse, 0, 0);}
133920  break;
133921  case 252: /* cmd ::= REINDEX nm dbnm */
133922 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
133923  break;
133924  case 253: /* cmd ::= ANALYZE */
133925 {sqlite3Analyze(pParse, 0, 0);}
133926  break;
133927  case 254: /* cmd ::= ANALYZE nm dbnm */
133928 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
133929  break;
133930  case 255: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
133931 {
133932  sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy347,&yymsp[0].minor.yy0);
133933 }
133934  break;
133935  case 256: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt columnname carglist */
133936 {
133937  yymsp[-1].minor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-1].minor.yy0.z) + pParse->sLastToken.n;
133938  sqlite3AlterFinishAddColumn(pParse, &yymsp[-1].minor.yy0);
133939 }
133940  break;
133941  case 257: /* add_column_fullname ::= fullname */
133942 {
133943  disableLookaside(pParse);
133944  sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy347);
133945 }
133946  break;
133947  case 258: /* cmd ::= create_vtab */
133948 {sqlite3VtabFinishParse(pParse,0);}
133949  break;
133950  case 259: /* cmd ::= create_vtab LP vtabarglist RP */
133951 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
133952  break;
133953  case 260: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
133954 {
133955  sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy392);
133956 }
133957  break;
133958  case 261: /* vtabarg ::= */
133959 {sqlite3VtabArgInit(pParse);}
133960  break;
133961  case 262: /* vtabargtoken ::= ANY */
133962  case 263: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==263);
133963  case 264: /* lp ::= LP */ yytestcase(yyruleno==264);
133964 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
133965  break;
133966  case 265: /* with ::= */
133967 {yymsp[1].minor.yy331 = 0;}
133968  break;
133969  case 266: /* with ::= WITH wqlist */
133970 { yymsp[-1].minor.yy331 = yymsp[0].minor.yy331; }
133971  break;
133972  case 267: /* with ::= WITH RECURSIVE wqlist */
133973 { yymsp[-2].minor.yy331 = yymsp[0].minor.yy331; }
133974  break;
133975  case 268: /* wqlist ::= nm eidlist_opt AS LP select RP */
133976 {
133977  yymsp[-5].minor.yy331 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy442, yymsp[-1].minor.yy159); /*A-overwrites-X*/
133978 }
133979  break;
133980  case 269: /* wqlist ::= wqlist COMMA nm eidlist_opt AS LP select RP */
133981 {
133982  yymsp[-7].minor.yy331 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy331, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy442, yymsp[-1].minor.yy159);
133983 }
133984  break;
133985  default:
133986  /* (270) input ::= cmdlist */ yytestcase(yyruleno==270);
133987  /* (271) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==271);
133988  /* (272) cmdlist ::= ecmd */ yytestcase(yyruleno==272);
133989  /* (273) ecmd ::= SEMI */ yytestcase(yyruleno==273);
133990  /* (274) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==274);
133991  /* (275) explain ::= */ yytestcase(yyruleno==275);
133992  /* (276) trans_opt ::= */ yytestcase(yyruleno==276);
133993  /* (277) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==277);
133994  /* (278) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==278);
133995  /* (279) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==279);
133996  /* (280) savepoint_opt ::= */ yytestcase(yyruleno==280);
133997  /* (281) cmd ::= create_table create_table_args */ yytestcase(yyruleno==281);
133998  /* (282) columnlist ::= columnlist COMMA columnname carglist */ yytestcase(yyruleno==282);
133999  /* (283) columnlist ::= columnname carglist */ yytestcase(yyruleno==283);
134000  /* (284) nm ::= ID|INDEXED */ yytestcase(yyruleno==284);
134001  /* (285) nm ::= STRING */ yytestcase(yyruleno==285);
134002  /* (286) nm ::= JOIN_KW */ yytestcase(yyruleno==286);
134003  /* (287) typetoken ::= typename */ yytestcase(yyruleno==287);
134004  /* (288) typename ::= ID|STRING */ yytestcase(yyruleno==288);
134005  /* (289) signed ::= plus_num */ yytestcase(yyruleno==289);
134006  /* (290) signed ::= minus_num */ yytestcase(yyruleno==290);
134007  /* (291) carglist ::= carglist ccons */ yytestcase(yyruleno==291);
134008  /* (292) carglist ::= */ yytestcase(yyruleno==292);
134009  /* (293) ccons ::= NULL onconf */ yytestcase(yyruleno==293);
134010  /* (294) conslist_opt ::= COMMA conslist */ yytestcase(yyruleno==294);
134011  /* (295) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==295);
134012  /* (296) conslist ::= tcons */ yytestcase(yyruleno==296);
134013  /* (297) tconscomma ::= */ yytestcase(yyruleno==297);
134014  /* (298) defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==298);
134015  /* (299) resolvetype ::= raisetype */ yytestcase(yyruleno==299);
134016  /* (300) selectnowith ::= oneselect */ yytestcase(yyruleno==300);
134017  /* (301) oneselect ::= values */ yytestcase(yyruleno==301);
134018  /* (302) sclp ::= selcollist COMMA */ yytestcase(yyruleno==302);
134019  /* (303) as ::= ID|STRING */ yytestcase(yyruleno==303);
134020  /* (304) expr ::= term */ yytestcase(yyruleno==304);
134021  /* (305) exprlist ::= nexprlist */ yytestcase(yyruleno==305);
134022  /* (306) nmnum ::= plus_num */ yytestcase(yyruleno==306);
134023  /* (307) nmnum ::= nm */ yytestcase(yyruleno==307);
134024  /* (308) nmnum ::= ON */ yytestcase(yyruleno==308);
134025  /* (309) nmnum ::= DELETE */ yytestcase(yyruleno==309);
134026  /* (310) nmnum ::= DEFAULT */ yytestcase(yyruleno==310);
134027  /* (311) plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==311);
134028  /* (312) foreach_clause ::= */ yytestcase(yyruleno==312);
134029  /* (313) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==313);
134030  /* (314) trnm ::= nm */ yytestcase(yyruleno==314);
134031  /* (315) tridxby ::= */ yytestcase(yyruleno==315);
134032  /* (316) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==316);
134033  /* (317) database_kw_opt ::= */ yytestcase(yyruleno==317);
134034  /* (318) kwcolumn_opt ::= */ yytestcase(yyruleno==318);
134035  /* (319) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==319);
134036  /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
134037  /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
134038  /* (322) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==322);
134039  /* (323) anylist ::= */ yytestcase(yyruleno==323);
134040  /* (324) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==324);
134041  /* (325) anylist ::= anylist ANY */ yytestcase(yyruleno==325);
134042  break;
134043 /********** End reduce actions ************************************************/
134044  };
134045  assert( yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
134046  yygoto = yyRuleInfo[yyruleno].lhs;
134047  yysize = yyRuleInfo[yyruleno].nrhs;
134048  yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
134049  if( yyact <= YY_MAX_SHIFTREDUCE ){
134050  if( yyact>YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134051  yypParser->yyidx -= yysize - 1;
134052  yymsp -= yysize-1;
134053  yymsp->stateno = (YYACTIONTYPE)yyact;
134054  yymsp->major = (YYCODETYPE)yygoto;
134055  yyTraceShift(yypParser, yyact);
134056  }else{
134057  assert( yyact == YY_ACCEPT_ACTION );
134058  yypParser->yyidx -= yysize;
134059  yy_accept(yypParser);
134060  }
134061 }
134062 
134063 /*
134064 ** The following code executes when the parse fails
134065 */
134066 #ifndef YYNOERRORRECOVERY
134067 static void yy_parse_failed(
134068  yyParser *yypParser /* The parser */
134069 ){
134071 #ifndef NDEBUG
134072  if( yyTraceFILE ){
134073  fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
134074  }
134075 #endif
134076  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
134077  /* Here code is inserted which will be executed whenever the
134078  ** parser fails */
134079 /************ Begin %parse_failure code ***************************************/
134080 /************ End %parse_failure code *****************************************/
134081  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134082 }
134083 #endif /* YYNOERRORRECOVERY */
134084 
134085 /*
134086 ** The following code executes when a syntax error first occurs.
134087 */
134088 static void yy_syntax_error(
134089  yyParser *yypParser, /* The parser */
134090  int yymajor, /* The major type of the error token */
134091  sqlite3ParserTOKENTYPE yyminor /* The minor type of the error token */
134092 ){
134094 #define TOKEN yyminor
134095 /************ Begin %syntax_error code ****************************************/
134096 
134097  UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
134098  assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
134099  sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
134100 /************ End %syntax_error code ******************************************/
134101  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134102 }
134103 
134104 /*
134105 ** The following is executed when the parser accepts
134106 */
134107 static void yy_accept(
134108  yyParser *yypParser /* The parser */
134109 ){
134111 #ifndef NDEBUG
134112  if( yyTraceFILE ){
134113  fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
134114  }
134115 #endif
134116  while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
134117  /* Here code is inserted which will be executed whenever the
134118  ** parser accepts */
134119 /*********** Begin %parse_accept code *****************************************/
134120 /*********** End %parse_accept code *******************************************/
134121  sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
134122 }
134123 
134124 /* The main parser program.
134125 ** The first argument is a pointer to a structure obtained from
134126 ** "sqlite3ParserAlloc" which describes the current state of the parser.
134127 ** The second argument is the major token number. The third is
134128 ** the minor token. The fourth optional argument is whatever the
134129 ** user wants (and specified in the grammar) and is available for
134130 ** use by the action routines.
134131 **
134132 ** Inputs:
134133 ** <ul>
134134 ** <li> A pointer to the parser (an opaque structure.)
134135 ** <li> The major token number.
134136 ** <li> The minor token number.
134137 ** <li> An option argument of a grammar-specified type.
134138 ** </ul>
134139 **
134140 ** Outputs:
134141 ** None.
134142 */
134144  void *yyp, /* The parser */
134145  int yymajor, /* The major token code number */
134146  sqlite3ParserTOKENTYPE yyminor /* The value for the token */
134147  sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
134148 ){
134149  YYMINORTYPE yyminorunion;
134150  unsigned int yyact; /* The parser action. */
134151 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
134152  int yyendofinput; /* True if we are at the end of input */
134153 #endif
134154 #ifdef YYERRORSYMBOL
134155  int yyerrorhit = 0; /* True if yymajor has invoked an error */
134156 #endif
134157  yyParser *yypParser; /* The parser */
134158 
134159  /* (re)initialize the parser, if necessary */
134160  yypParser = (yyParser*)yyp;
134161  if( yypParser->yyidx<0 ){
134162 #if YYSTACKDEPTH<=0
134163  if( yypParser->yystksz <=0 ){
134164  yyStackOverflow(yypParser);
134165  return;
134166  }
134167 #endif
134168  yypParser->yyidx = 0;
134169 #ifndef YYNOERRORRECOVERY
134170  yypParser->yyerrcnt = -1;
134171 #endif
134172  yypParser->yystack[0].stateno = 0;
134173  yypParser->yystack[0].major = 0;
134174 #ifndef NDEBUG
134175  if( yyTraceFILE ){
134176  fprintf(yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
134177  yyTracePrompt);
134178  }
134179 #endif
134180  }
134181 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
134182  yyendofinput = (yymajor==0);
134183 #endif
134185 
134186 #ifndef NDEBUG
134187  if( yyTraceFILE ){
134188  fprintf(yyTraceFILE,"%sInput '%s'\n",yyTracePrompt,yyTokenName[yymajor]);
134189  }
134190 #endif
134191 
134192  do{
134193  yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
134194  if( yyact <= YY_MAX_SHIFTREDUCE ){
134195  if( yyact > YY_MAX_SHIFT ) yyact += YY_MIN_REDUCE - YY_MIN_SHIFTREDUCE;
134196  yy_shift(yypParser,yyact,yymajor,yyminor);
134197 #ifndef YYNOERRORRECOVERY
134198  yypParser->yyerrcnt--;
134199 #endif
134200  yymajor = YYNOCODE;
134201  }else if( yyact <= YY_MAX_REDUCE ){
134202  yy_reduce(yypParser,yyact-YY_MIN_REDUCE);
134203  }else{
134204  assert( yyact == YY_ERROR_ACTION );
134205  yyminorunion.yy0 = yyminor;
134206 #ifdef YYERRORSYMBOL
134207  int yymx;
134208 #endif
134209 #ifndef NDEBUG
134210  if( yyTraceFILE ){
134211  fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
134212  }
134213 #endif
134214 #ifdef YYERRORSYMBOL
134215  /* A syntax error has occurred.
134216  ** The response to an error depends upon whether or not the
134217  ** grammar defines an error token "ERROR".
134218  **
134219  ** This is what we do if the grammar does define ERROR:
134220  **
134221  ** * Call the %syntax_error function.
134222  **
134223  ** * Begin popping the stack until we enter a state where
134224  ** it is legal to shift the error symbol, then shift
134225  ** the error symbol.
134226  **
134227  ** * Set the error count to three.
134228  **
134229  ** * Begin accepting and shifting new tokens. No new error
134230  ** processing will occur until three tokens have been
134231  ** shifted successfully.
134232  **
134233  */
134234  if( yypParser->yyerrcnt<0 ){
134235  yy_syntax_error(yypParser,yymajor,yyminor);
134236  }
134237  yymx = yypParser->yystack[yypParser->yyidx].major;
134238  if( yymx==YYERRORSYMBOL || yyerrorhit ){
134239 #ifndef NDEBUG
134240  if( yyTraceFILE ){
134241  fprintf(yyTraceFILE,"%sDiscard input token %s\n",
134242  yyTracePrompt,yyTokenName[yymajor]);
134243  }
134244 #endif
134245  yy_destructor(yypParser, (YYCODETYPE)yymajor, &yyminorunion);
134246  yymajor = YYNOCODE;
134247  }else{
134248  while(
134249  yypParser->yyidx >= 0 &&
134250  yymx != YYERRORSYMBOL &&
134251  (yyact = yy_find_reduce_action(
134252  yypParser->yystack[yypParser->yyidx].stateno,
134253  YYERRORSYMBOL)) >= YY_MIN_REDUCE
134254  ){
134255  yy_pop_parser_stack(yypParser);
134256  }
134257  if( yypParser->yyidx < 0 || yymajor==0 ){
134258  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
134259  yy_parse_failed(yypParser);
134260  yymajor = YYNOCODE;
134261  }else if( yymx!=YYERRORSYMBOL ){
134262  yy_shift(yypParser,yyact,YYERRORSYMBOL,yyminor);
134263  }
134264  }
134265  yypParser->yyerrcnt = 3;
134266  yyerrorhit = 1;
134267 #elif defined(YYNOERRORRECOVERY)
134268  /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
134269  ** do any kind of error recovery. Instead, simply invoke the syntax
134270  ** error routine and continue going as if nothing had happened.
134271  **
134272  ** Applications can set this macro (for example inside %include) if
134273  ** they intend to abandon the parse upon the first syntax error seen.
134274  */
134275  yy_syntax_error(yypParser,yymajor, yyminor);
134276  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
134277  yymajor = YYNOCODE;
134278 
134279 #else /* YYERRORSYMBOL is not defined */
134280  /* This is what we do if the grammar does not define ERROR:
134281  **
134282  ** * Report an error message, and throw away the input token.
134283  **
134284  ** * If the input token is $, then fail the parse.
134285  **
134286  ** As before, subsequent error messages are suppressed until
134287  ** three input tokens have been successfully shifted.
134288  */
134289  if( yypParser->yyerrcnt<=0 ){
134290  yy_syntax_error(yypParser,yymajor, yyminor);
134291  }
134292  yypParser->yyerrcnt = 3;
134293  yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
134294  if( yyendofinput ){
134295  yy_parse_failed(yypParser);
134296  }
134297  yymajor = YYNOCODE;
134298 #endif
134299  }
134300  }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
134301 #ifndef NDEBUG
134302  if( yyTraceFILE ){
134303  int i;
134304  fprintf(yyTraceFILE,"%sReturn. Stack=",yyTracePrompt);
134305  for(i=1; i<=yypParser->yyidx; i++)
134306  fprintf(yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
134307  yyTokenName[yypParser->yystack[i].major]);
134308  fprintf(yyTraceFILE,"]\n");
134309  }
134310 #endif
134311  return;
134312 }
134313 
134314 /************** End of parse.c ***********************************************/
134315 /************** Begin file tokenize.c ****************************************/
134316 /*
134317 ** 2001 September 15
134318 **
134319 ** The author disclaims copyright to this source code. In place of
134320 ** a legal notice, here is a blessing:
134321 **
134322 ** May you do good and not evil.
134323 ** May you find forgiveness for yourself and forgive others.
134324 ** May you share freely, never taking more than you give.
134325 **
134326 *************************************************************************
134327 ** An tokenizer for SQL
134328 **
134329 ** This file contains C code that splits an SQL input string up into
134330 ** individual tokens and sends those tokens one-by-one over to the
134331 ** parser for analysis.
134332 */
134333 /* #include "sqliteInt.h" */
134334 /* #include <stdlib.h> */
134335 
134336 /* Character classes for tokenizing
134337 **
134338 ** In the sqlite3GetToken() function, a switch() on aiClass[c] is implemented
134339 ** using a lookup table, whereas a switch() directly on c uses a binary search.
134340 ** The lookup table is much faster. To maximize speed, and to ensure that
134341 ** a lookup table is used, all of the classes need to be small integers and
134342 ** all of them need to be used within the switch.
134343 */
134344 #define CC_X 0 /* The letter 'x', or start of BLOB literal */
134345 #define CC_KYWD 1 /* Alphabetics or '_'. Usable in a keyword */
134346 #define CC_ID 2 /* unicode characters usable in IDs */
134347 #define CC_DIGIT 3 /* Digits */
134348 #define CC_DOLLAR 4 /* '$' */
134349 #define CC_VARALPHA 5 /* '@', '#', ':'. Alphabetic SQL variables */
134350 #define CC_VARNUM 6 /* '?'. Numeric SQL variables */
134351 #define CC_SPACE 7 /* Space characters */
134352 #define CC_QUOTE 8 /* '"', '\'', or '`'. String literals, quoted ids */
134353 #define CC_QUOTE2 9 /* '['. [...] style quoted ids */
134354 #define CC_PIPE 10 /* '|'. Bitwise OR or concatenate */
134355 #define CC_MINUS 11 /* '-'. Minus or SQL-style comment */
134356 #define CC_LT 12 /* '<'. Part of < or <= or <> */
134357 #define CC_GT 13 /* '>'. Part of > or >= */
134358 #define CC_EQ 14 /* '='. Part of = or == */
134359 #define CC_BANG 15 /* '!'. Part of != */
134360 #define CC_SLASH 16 /* '/'. / or c-style comment */
134361 #define CC_LP 17 /* '(' */
134362 #define CC_RP 18 /* ')' */
134363 #define CC_SEMI 19 /* ';' */
134364 #define CC_PLUS 20 /* '+' */
134365 #define CC_STAR 21 /* '*' */
134366 #define CC_PERCENT 22 /* '%' */
134367 #define CC_COMMA 23 /* ',' */
134368 #define CC_AND 24 /* '&' */
134369 #define CC_TILDA 25 /* '~' */
134370 #define CC_DOT 26 /* '.' */
134371 #define CC_ILLEGAL 27 /* Illegal character */
134372 
134373 static const unsigned char aiClass[] = {
134374 #ifdef SQLITE_ASCII
134375 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
134376 /* 0x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 7, 7, 27, 7, 7, 27, 27,
134377 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
134378 /* 2x */ 7, 15, 8, 5, 4, 22, 24, 8, 17, 18, 21, 20, 23, 11, 26, 16,
134379 /* 3x */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 19, 12, 14, 13, 6,
134380 /* 4x */ 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
134381 /* 5x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 9, 27, 27, 27, 1,
134382 /* 6x */ 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
134383 /* 7x */ 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 10, 27, 25, 27,
134384 /* 8x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134385 /* 9x */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134386 /* Ax */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134387 /* Bx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134388 /* Cx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134389 /* Dx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134390 /* Ex */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
134391 /* Fx */ 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
134392 #endif
134393 #ifdef SQLITE_EBCDIC
134394 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xa xb xc xd xe xf */
134395 /* 0x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 7, 7, 27, 27,
134396 /* 1x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
134397 /* 2x */ 27, 27, 27, 27, 27, 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
134398 /* 3x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
134399 /* 4x */ 7, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 12, 17, 20, 10,
134400 /* 5x */ 24, 27, 27, 27, 27, 27, 27, 27, 27, 27, 15, 4, 21, 18, 19, 27,
134401 /* 6x */ 11, 16, 27, 27, 27, 27, 27, 27, 27, 27, 27, 23, 22, 1, 13, 7,
134402 /* 7x */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 8, 5, 5, 5, 8, 14, 8,
134403 /* 8x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
134404 /* 9x */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
134405 /* 9x */ 25, 1, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
134406 /* Bx */ 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 9, 27, 27, 27, 27, 27,
134407 /* Cx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
134408 /* Dx */ 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 27, 27, 27, 27, 27,
134409 /* Ex */ 27, 27, 1, 1, 1, 1, 1, 0, 1, 1, 27, 27, 27, 27, 27, 27,
134410 /* Fx */ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 27, 27, 27, 27, 27, 27,
134411 #endif
134412 };
134413 
134414 /*
134415 ** The charMap() macro maps alphabetic characters (only) into their
134416 ** lower-case ASCII equivalent. On ASCII machines, this is just
134417 ** an upper-to-lower case map. On EBCDIC machines we also need
134418 ** to adjust the encoding. The mapping is only valid for alphabetics
134419 ** which are the only characters for which this feature is used.
134420 **
134421 ** Used by keywordhash.h
134422 */
134423 #ifdef SQLITE_ASCII
134424 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
134425 #endif
134426 #ifdef SQLITE_EBCDIC
134427 # define charMap(X) ebcdicToAscii[(unsigned char)X]
134428 const unsigned char ebcdicToAscii[] = {
134429 /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
134430  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
134431  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
134432  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
134433  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
134434  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
134435  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
134436  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
134437  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
134438  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
134439  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
134440  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
134441  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
134442  0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
134443  0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
134444  0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
134445  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
134446 };
134447 #endif
134448 
134449 /*
134450 ** The sqlite3KeywordCode function looks up an identifier to determine if
134451 ** it is a keyword. If it is a keyword, the token code of that keyword is
134452 ** returned. If the input is not a keyword, TK_ID is returned.
134453 **
134454 ** The implementation of this routine was generated by a program,
134455 ** mkkeywordhash.c, located in the tool subdirectory of the distribution.
134456 ** The output of the mkkeywordhash.c program is written into a file
134457 ** named keywordhash.h and then included into this source file by
134458 ** the #include below.
134459 */
134460 /************** Include keywordhash.h in the middle of tokenize.c ************/
134461 /************** Begin file keywordhash.h *************************************/
134462 /***** This file contains automatically generated code ******
134463 **
134464 ** The code in this file has been automatically generated by
134465 **
134466 ** sqlite/tool/mkkeywordhash.c
134467 **
134468 ** The code in this file implements a function that determines whether
134469 ** or not a given identifier is really an SQL keyword. The same thing
134470 ** might be implemented more directly using a hand-written hash table.
134471 ** But by using this automatically generated code, the size of the code
134472 ** is substantially reduced. This is important for embedded applications
134473 ** on platforms with limited memory.
134474 */
134475 /* Hash score: 182 */
134476 static int keywordCode(const char *z, int n, int *pType){
134477  /* zText[] encodes 834 bytes of keywords in 554 bytes */
134478  /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
134479  /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
134480  /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
134481  /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
134482  /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
134483  /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
134484  /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
134485  /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
134486  /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
134487  /* VACUUMVIEWINITIALLY */
134488  static const char zText[553] = {
134489  'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
134490  'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
134491  'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
134492  'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
134493  'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
134494  'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
134495  'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
134496  'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
134497  'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
134498  'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
134499  'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
134500  'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
134501  'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
134502  'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
134503  'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
134504  'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
134505  'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
134506  'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
134507  'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
134508  'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
134509  'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
134510  'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
134511  'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
134512  'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
134513  'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
134514  'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
134515  'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
134516  'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
134517  'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
134518  'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
134519  'V','I','E','W','I','N','I','T','I','A','L','L','Y',
134520  };
134521  static const unsigned char aHash[127] = {
134522  76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
134523  42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
134524  121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
134525  0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
134526  0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
134527  96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
134528  100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
134529  39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
134530  62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
134531  29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
134532  };
134533  static const unsigned char aNext[124] = {
134534  0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
134535  0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
134536  0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
134537  0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
134538  0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
134539  0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
134540  0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
134541  10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
134542  0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
134543  73, 83, 0, 35, 68, 0, 0,
134544  };
134545  static const unsigned char aLen[124] = {
134546  7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
134547  7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
134548  11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
134549  4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
134550  6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
134551  7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
134552  7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
134553  13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
134554  2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
134555  3, 5, 5, 6, 4, 9, 3,
134556  };
134557  static const unsigned short int aOffset[124] = {
134558  0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
134559  36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
134560  86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
134561  159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
134562  199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
134563  250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
134564  320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
134565  387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
134566  460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
134567  521, 524, 529, 534, 540, 544, 549,
134568  };
134569  static const unsigned char aCode[124] = {
134595  };
134596  int i, j;
134597  const char *zKW;
134598  if( n>=2 ){
134599  i = ((charMap(z[0])*4) ^ (charMap(z[n-1])*3) ^ n) % 127;
134600  for(i=((int)aHash[i])-1; i>=0; i=((int)aNext[i])-1){
134601  if( aLen[i]!=n ) continue;
134602  j = 0;
134603  zKW = &zText[aOffset[i]];
134604 #ifdef SQLITE_ASCII
134605  while( j<n && (z[j]&~0x20)==zKW[j] ){ j++; }
134606 #endif
134607 #ifdef SQLITE_EBCDIC
134608  while( j<n && toupper(z[j])==zKW[j] ){ j++; }
134609 #endif
134610  if( j<n ) continue;
134611  testcase( i==0 ); /* REINDEX */
134612  testcase( i==1 ); /* INDEXED */
134613  testcase( i==2 ); /* INDEX */
134614  testcase( i==3 ); /* DESC */
134615  testcase( i==4 ); /* ESCAPE */
134616  testcase( i==5 ); /* EACH */
134617  testcase( i==6 ); /* CHECK */
134618  testcase( i==7 ); /* KEY */
134619  testcase( i==8 ); /* BEFORE */
134620  testcase( i==9 ); /* FOREIGN */
134621  testcase( i==10 ); /* FOR */
134622  testcase( i==11 ); /* IGNORE */
134623  testcase( i==12 ); /* REGEXP */
134624  testcase( i==13 ); /* EXPLAIN */
134625  testcase( i==14 ); /* INSTEAD */
134626  testcase( i==15 ); /* ADD */
134627  testcase( i==16 ); /* DATABASE */
134628  testcase( i==17 ); /* AS */
134629  testcase( i==18 ); /* SELECT */
134630  testcase( i==19 ); /* TABLE */
134631  testcase( i==20 ); /* LEFT */
134632  testcase( i==21 ); /* THEN */
134633  testcase( i==22 ); /* END */
134634  testcase( i==23 ); /* DEFERRABLE */
134635  testcase( i==24 ); /* ELSE */
134636  testcase( i==25 ); /* EXCEPT */
134637  testcase( i==26 ); /* TRANSACTION */
134638  testcase( i==27 ); /* ACTION */
134639  testcase( i==28 ); /* ON */
134640  testcase( i==29 ); /* NATURAL */
134641  testcase( i==30 ); /* ALTER */
134642  testcase( i==31 ); /* RAISE */
134643  testcase( i==32 ); /* EXCLUSIVE */
134644  testcase( i==33 ); /* EXISTS */
134645  testcase( i==34 ); /* SAVEPOINT */
134646  testcase( i==35 ); /* INTERSECT */
134647  testcase( i==36 ); /* TRIGGER */
134648  testcase( i==37 ); /* REFERENCES */
134649  testcase( i==38 ); /* CONSTRAINT */
134650  testcase( i==39 ); /* INTO */
134651  testcase( i==40 ); /* OFFSET */
134652  testcase( i==41 ); /* OF */
134653  testcase( i==42 ); /* SET */
134654  testcase( i==43 ); /* TEMPORARY */
134655  testcase( i==44 ); /* TEMP */
134656  testcase( i==45 ); /* OR */
134657  testcase( i==46 ); /* UNIQUE */
134658  testcase( i==47 ); /* QUERY */
134659  testcase( i==48 ); /* WITHOUT */
134660  testcase( i==49 ); /* WITH */
134661  testcase( i==50 ); /* OUTER */
134662  testcase( i==51 ); /* RELEASE */
134663  testcase( i==52 ); /* ATTACH */
134664  testcase( i==53 ); /* HAVING */
134665  testcase( i==54 ); /* GROUP */
134666  testcase( i==55 ); /* UPDATE */
134667  testcase( i==56 ); /* BEGIN */
134668  testcase( i==57 ); /* INNER */
134669  testcase( i==58 ); /* RECURSIVE */
134670  testcase( i==59 ); /* BETWEEN */
134671  testcase( i==60 ); /* NOTNULL */
134672  testcase( i==61 ); /* NOT */
134673  testcase( i==62 ); /* NO */
134674  testcase( i==63 ); /* NULL */
134675  testcase( i==64 ); /* LIKE */
134676  testcase( i==65 ); /* CASCADE */
134677  testcase( i==66 ); /* ASC */
134678  testcase( i==67 ); /* DELETE */
134679  testcase( i==68 ); /* CASE */
134680  testcase( i==69 ); /* COLLATE */
134681  testcase( i==70 ); /* CREATE */
134682  testcase( i==71 ); /* CURRENT_DATE */
134683  testcase( i==72 ); /* DETACH */
134684  testcase( i==73 ); /* IMMEDIATE */
134685  testcase( i==74 ); /* JOIN */
134686  testcase( i==75 ); /* INSERT */
134687  testcase( i==76 ); /* MATCH */
134688  testcase( i==77 ); /* PLAN */
134689  testcase( i==78 ); /* ANALYZE */
134690  testcase( i==79 ); /* PRAGMA */
134691  testcase( i==80 ); /* ABORT */
134692  testcase( i==81 ); /* VALUES */
134693  testcase( i==82 ); /* VIRTUAL */
134694  testcase( i==83 ); /* LIMIT */
134695  testcase( i==84 ); /* WHEN */
134696  testcase( i==85 ); /* WHERE */
134697  testcase( i==86 ); /* RENAME */
134698  testcase( i==87 ); /* AFTER */
134699  testcase( i==88 ); /* REPLACE */
134700  testcase( i==89 ); /* AND */
134701  testcase( i==90 ); /* DEFAULT */
134702  testcase( i==91 ); /* AUTOINCREMENT */
134703  testcase( i==92 ); /* TO */
134704  testcase( i==93 ); /* IN */
134705  testcase( i==94 ); /* CAST */
134706  testcase( i==95 ); /* COLUMN */
134707  testcase( i==96 ); /* COMMIT */
134708  testcase( i==97 ); /* CONFLICT */
134709  testcase( i==98 ); /* CROSS */
134710  testcase( i==99 ); /* CURRENT_TIMESTAMP */
134711  testcase( i==100 ); /* CURRENT_TIME */
134712  testcase( i==101 ); /* PRIMARY */
134713  testcase( i==102 ); /* DEFERRED */
134714  testcase( i==103 ); /* DISTINCT */
134715  testcase( i==104 ); /* IS */
134716  testcase( i==105 ); /* DROP */
134717  testcase( i==106 ); /* FAIL */
134718  testcase( i==107 ); /* FROM */
134719  testcase( i==108 ); /* FULL */
134720  testcase( i==109 ); /* GLOB */
134721  testcase( i==110 ); /* BY */
134722  testcase( i==111 ); /* IF */
134723  testcase( i==112 ); /* ISNULL */
134724  testcase( i==113 ); /* ORDER */
134725  testcase( i==114 ); /* RESTRICT */
134726  testcase( i==115 ); /* RIGHT */
134727  testcase( i==116 ); /* ROLLBACK */
134728  testcase( i==117 ); /* ROW */
134729  testcase( i==118 ); /* UNION */
134730  testcase( i==119 ); /* USING */
134731  testcase( i==120 ); /* VACUUM */
134732  testcase( i==121 ); /* VIEW */
134733  testcase( i==122 ); /* INITIALLY */
134734  testcase( i==123 ); /* ALL */
134735  *pType = aCode[i];
134736  break;
134737  }
134738  }
134739  return n;
134740 }
134741 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
134742  int id = TK_ID;
134743  keywordCode((char*)z, n, &id);
134744  return id;
134745 }
134746 #define SQLITE_N_KEYWORD 124
134747 
134748 /************** End of keywordhash.h *****************************************/
134749 /************** Continuing where we left off in tokenize.c *******************/
134750 
134751 
134752 /*
134753 ** If X is a character that can be used in an identifier then
134754 ** IdChar(X) will be true. Otherwise it is false.
134755 **
134756 ** For ASCII, any character with the high-order bit set is
134757 ** allowed in an identifier. For 7-bit characters,
134758 ** sqlite3IsIdChar[X] must be 1.
134759 **
134760 ** For EBCDIC, the rules are more complex but have the same
134761 ** end result.
134762 **
134763 ** Ticket #1066. the SQL standard does not allow '$' in the
134764 ** middle of identifiers. But many SQL implementations do.
134765 ** SQLite will allow '$' in identifiers for compatibility.
134766 ** But the feature is undocumented.
134767 */
134768 #ifdef SQLITE_ASCII
134769 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
134770 #endif
134771 #ifdef SQLITE_EBCDIC
134772 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
134773 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
134774  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
134775  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
134776  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
134777  0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
134778  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
134779  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
134780  1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
134781  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
134782  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
134783  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
134784  0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
134785  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
134786 };
134787 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
134788 #endif
134789 
134790 /* Make the IdChar function accessible from ctime.c */
134791 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
134792 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
134793 #endif
134794 
134795 
134796 /*
134797 ** Return the length (in bytes) of the token that begins at z[0].
134798 ** Store the token type in *tokenType before returning.
134799 */
134800 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
134801  int i, c;
134802  switch( aiClass[*z] ){ /* Switch on the character-class of the first byte
134803  ** of the token. See the comment on the CC_ defines
134804  ** above. */
134805  case CC_SPACE: {
134806  testcase( z[0]==' ' );
134807  testcase( z[0]=='\t' );
134808  testcase( z[0]=='\n' );
134809  testcase( z[0]=='\f' );
134810  testcase( z[0]=='\r' );
134811  for(i=1; sqlite3Isspace(z[i]); i++){}
134812  *tokenType = TK_SPACE;
134813  return i;
134814  }
134815  case CC_MINUS: {
134816  if( z[1]=='-' ){
134817  for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
134818  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
134819  return i;
134820  }
134821  *tokenType = TK_MINUS;
134822  return 1;
134823  }
134824  case CC_LP: {
134825  *tokenType = TK_LP;
134826  return 1;
134827  }
134828  case CC_RP: {
134829  *tokenType = TK_RP;
134830  return 1;
134831  }
134832  case CC_SEMI: {
134833  *tokenType = TK_SEMI;
134834  return 1;
134835  }
134836  case CC_PLUS: {
134837  *tokenType = TK_PLUS;
134838  return 1;
134839  }
134840  case CC_STAR: {
134841  *tokenType = TK_STAR;
134842  return 1;
134843  }
134844  case CC_SLASH: {
134845  if( z[1]!='*' || z[2]==0 ){
134846  *tokenType = TK_SLASH;
134847  return 1;
134848  }
134849  for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
134850  if( c ) i++;
134851  *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
134852  return i;
134853  }
134854  case CC_PERCENT: {
134855  *tokenType = TK_REM;
134856  return 1;
134857  }
134858  case CC_EQ: {
134859  *tokenType = TK_EQ;
134860  return 1 + (z[1]=='=');
134861  }
134862  case CC_LT: {
134863  if( (c=z[1])=='=' ){
134864  *tokenType = TK_LE;
134865  return 2;
134866  }else if( c=='>' ){
134867  *tokenType = TK_NE;
134868  return 2;
134869  }else if( c=='<' ){
134870  *tokenType = TK_LSHIFT;
134871  return 2;
134872  }else{
134873  *tokenType = TK_LT;
134874  return 1;
134875  }
134876  }
134877  case CC_GT: {
134878  if( (c=z[1])=='=' ){
134879  *tokenType = TK_GE;
134880  return 2;
134881  }else if( c=='>' ){
134882  *tokenType = TK_RSHIFT;
134883  return 2;
134884  }else{
134885  *tokenType = TK_GT;
134886  return 1;
134887  }
134888  }
134889  case CC_BANG: {
134890  if( z[1]!='=' ){
134891  *tokenType = TK_ILLEGAL;
134892  return 1;
134893  }else{
134894  *tokenType = TK_NE;
134895  return 2;
134896  }
134897  }
134898  case CC_PIPE: {
134899  if( z[1]!='|' ){
134900  *tokenType = TK_BITOR;
134901  return 1;
134902  }else{
134903  *tokenType = TK_CONCAT;
134904  return 2;
134905  }
134906  }
134907  case CC_COMMA: {
134908  *tokenType = TK_COMMA;
134909  return 1;
134910  }
134911  case CC_AND: {
134912  *tokenType = TK_BITAND;
134913  return 1;
134914  }
134915  case CC_TILDA: {
134916  *tokenType = TK_BITNOT;
134917  return 1;
134918  }
134919  case CC_QUOTE: {
134920  int delim = z[0];
134921  testcase( delim=='`' );
134922  testcase( delim=='\'' );
134923  testcase( delim=='"' );
134924  for(i=1; (c=z[i])!=0; i++){
134925  if( c==delim ){
134926  if( z[i+1]==delim ){
134927  i++;
134928  }else{
134929  break;
134930  }
134931  }
134932  }
134933  if( c=='\'' ){
134934  *tokenType = TK_STRING;
134935  return i+1;
134936  }else if( c!=0 ){
134937  *tokenType = TK_ID;
134938  return i+1;
134939  }else{
134940  *tokenType = TK_ILLEGAL;
134941  return i;
134942  }
134943  }
134944  case CC_DOT: {
134945 #ifndef SQLITE_OMIT_FLOATING_POINT
134946  if( !sqlite3Isdigit(z[1]) )
134947 #endif
134948  {
134949  *tokenType = TK_DOT;
134950  return 1;
134951  }
134952  /* If the next character is a digit, this is a floating point
134953  ** number that begins with ".". Fall thru into the next case */
134954  }
134955  case CC_DIGIT: {
134956  testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
134957  testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
134958  testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
134959  testcase( z[0]=='9' );
134960  *tokenType = TK_INTEGER;
134961 #ifndef SQLITE_OMIT_HEX_INTEGER
134962  if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
134963  for(i=3; sqlite3Isxdigit(z[i]); i++){}
134964  return i;
134965  }
134966 #endif
134967  for(i=0; sqlite3Isdigit(z[i]); i++){}
134968 #ifndef SQLITE_OMIT_FLOATING_POINT
134969  if( z[i]=='.' ){
134970  i++;
134971  while( sqlite3Isdigit(z[i]) ){ i++; }
134972  *tokenType = TK_FLOAT;
134973  }
134974  if( (z[i]=='e' || z[i]=='E') &&
134975  ( sqlite3Isdigit(z[i+1])
134976  || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
134977  )
134978  ){
134979  i += 2;
134980  while( sqlite3Isdigit(z[i]) ){ i++; }
134981  *tokenType = TK_FLOAT;
134982  }
134983 #endif
134984  while( IdChar(z[i]) ){
134985  *tokenType = TK_ILLEGAL;
134986  i++;
134987  }
134988  return i;
134989  }
134990  case CC_QUOTE2: {
134991  for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
134992  *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
134993  return i;
134994  }
134995  case CC_VARNUM: {
134996  *tokenType = TK_VARIABLE;
134997  for(i=1; sqlite3Isdigit(z[i]); i++){}
134998  return i;
134999  }
135000  case CC_DOLLAR:
135001  case CC_VARALPHA: {
135002  int n = 0;
135003  testcase( z[0]=='$' ); testcase( z[0]=='@' );
135004  testcase( z[0]==':' ); testcase( z[0]=='#' );
135005  *tokenType = TK_VARIABLE;
135006  for(i=1; (c=z[i])!=0; i++){
135007  if( IdChar(c) ){
135008  n++;
135009 #ifndef SQLITE_OMIT_TCL_VARIABLE
135010  }else if( c=='(' && n>0 ){
135011  do{
135012  i++;
135013  }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
135014  if( c==')' ){
135015  i++;
135016  }else{
135017  *tokenType = TK_ILLEGAL;
135018  }
135019  break;
135020  }else if( c==':' && z[i+1]==':' ){
135021  i++;
135022 #endif
135023  }else{
135024  break;
135025  }
135026  }
135027  if( n==0 ) *tokenType = TK_ILLEGAL;
135028  return i;
135029  }
135030  case CC_KYWD: {
135031  for(i=1; aiClass[z[i]]<=CC_KYWD; i++){}
135032  if( IdChar(z[i]) ){
135033  /* This token started out using characters that can appear in keywords,
135034  ** but z[i] is a character not allowed within keywords, so this must
135035  ** be an identifier instead */
135036  i++;
135037  break;
135038  }
135039  *tokenType = TK_ID;
135040  return keywordCode((char*)z, i, tokenType);
135041  }
135042  case CC_X: {
135043 #ifndef SQLITE_OMIT_BLOB_LITERAL
135044  testcase( z[0]=='x' ); testcase( z[0]=='X' );
135045  if( z[1]=='\'' ){
135046  *tokenType = TK_BLOB;
135047  for(i=2; sqlite3Isxdigit(z[i]); i++){}
135048  if( z[i]!='\'' || i%2 ){
135049  *tokenType = TK_ILLEGAL;
135050  while( z[i] && z[i]!='\'' ){ i++; }
135051  }
135052  if( z[i] ) i++;
135053  return i;
135054  }
135055 #endif
135056  /* If it is not a BLOB literal, then it must be an ID, since no
135057  ** SQL keywords start with the letter 'x'. Fall through */
135058  }
135059  case CC_ID: {
135060  i = 1;
135061  break;
135062  }
135063  default: {
135064  *tokenType = TK_ILLEGAL;
135065  return 1;
135066  }
135067  }
135068  while( IdChar(z[i]) ){ i++; }
135069  *tokenType = TK_ID;
135070  return i;
135071 }
135072 
135073 /*
135074 ** Run the parser on the given SQL string. The parser structure is
135075 ** passed in. An SQLITE_ status code is returned. If an error occurs
135076 ** then an and attempt is made to write an error message into
135077 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
135078 ** error message.
135079 */
135080 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
135081  int nErr = 0; /* Number of errors encountered */
135082  int i; /* Loop counter */
135083  void *pEngine; /* The LEMON-generated LALR(1) parser */
135084  int tokenType; /* type of the next token */
135085  int lastTokenParsed = -1; /* type of the previous token */
135086  sqlite3 *db = pParse->db; /* The database connection */
135087  int mxSqlLen; /* Max length of an SQL string */
135088 
135089  assert( zSql!=0 );
135090  mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
135091  if( db->nVdbeActive==0 ){
135092  db->u1.isInterrupted = 0;
135093  }
135094  pParse->rc = SQLITE_OK;
135095  pParse->zTail = zSql;
135096  i = 0;
135097  assert( pzErrMsg!=0 );
135098  /* sqlite3ParserTrace(stdout, "parser: "); */
135099  pEngine = sqlite3ParserAlloc(sqlite3Malloc);
135100  if( pEngine==0 ){
135101  sqlite3OomFault(db);
135102  return SQLITE_NOMEM_BKPT;
135103  }
135104  assert( pParse->pNewTable==0 );
135105  assert( pParse->pNewTrigger==0 );
135106  assert( pParse->nVar==0 );
135107  assert( pParse->nzVar==0 );
135108  assert( pParse->azVar==0 );
135109  while( zSql[i]!=0 ){
135110  assert( i>=0 );
135111  pParse->sLastToken.z = &zSql[i];
135112  pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
135113  i += pParse->sLastToken.n;
135114  if( i>mxSqlLen ){
135115  pParse->rc = SQLITE_TOOBIG;
135116  break;
135117  }
135118  if( tokenType>=TK_SPACE ){
135119  assert( tokenType==TK_SPACE || tokenType==TK_ILLEGAL );
135120  if( db->u1.isInterrupted ){
135121  pParse->rc = SQLITE_INTERRUPT;
135122  break;
135123  }
135124  if( tokenType==TK_ILLEGAL ){
135125  sqlite3ErrorMsg(pParse, "unrecognized token: \"%T\"",
135126  &pParse->sLastToken);
135127  break;
135128  }
135129  }else{
135130  sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
135131  lastTokenParsed = tokenType;
135132  if( pParse->rc!=SQLITE_OK || db->mallocFailed ) break;
135133  }
135134  }
135135  assert( nErr==0 );
135136  pParse->zTail = &zSql[i];
135137  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
135138  assert( zSql[i]==0 );
135139  if( lastTokenParsed!=TK_SEMI ){
135140  sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
135141  }
135142  if( pParse->rc==SQLITE_OK && db->mallocFailed==0 ){
135143  sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
135144  }
135145  }
135146 #ifdef YYTRACKMAXSTACKDEPTH
135149  sqlite3ParserStackPeak(pEngine)
135150  );
135152 #endif /* YYDEBUG */
135153  sqlite3ParserFree(pEngine, sqlite3_free);
135154  if( db->mallocFailed ){
135155  pParse->rc = SQLITE_NOMEM_BKPT;
135156  }
135157  if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
135158  pParse->zErrMsg = sqlite3MPrintf(db, "%s", sqlite3ErrStr(pParse->rc));
135159  }
135160  assert( pzErrMsg!=0 );
135161  if( pParse->zErrMsg ){
135162  *pzErrMsg = pParse->zErrMsg;
135163  sqlite3_log(pParse->rc, "%s", *pzErrMsg);
135164  pParse->zErrMsg = 0;
135165  nErr++;
135166  }
135167  if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
135168  sqlite3VdbeDelete(pParse->pVdbe);
135169  pParse->pVdbe = 0;
135170  }
135171 #ifndef SQLITE_OMIT_SHARED_CACHE
135172  if( pParse->nested==0 ){
135173  sqlite3DbFree(db, pParse->aTableLock);
135174  pParse->aTableLock = 0;
135175  pParse->nTableLock = 0;
135176  }
135177 #endif
135178 #ifndef SQLITE_OMIT_VIRTUALTABLE
135179  sqlite3_free(pParse->apVtabLock);
135180 #endif
135181 
135182  if( !IN_DECLARE_VTAB ){
135183  /* If the pParse->declareVtab flag is set, do not delete any table
135184  ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
135185  ** will take responsibility for freeing the Table structure.
135186  */
135187  sqlite3DeleteTable(db, pParse->pNewTable);
135188  }
135189 
135190  if( pParse->pWithToFree ) sqlite3WithDelete(db, pParse->pWithToFree);
135191  sqlite3DeleteTrigger(db, pParse->pNewTrigger);
135192  for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
135193  sqlite3DbFree(db, pParse->azVar);
135194  while( pParse->pAinc ){
135195  AutoincInfo *p = pParse->pAinc;
135196  pParse->pAinc = p->pNext;
135197  sqlite3DbFree(db, p);
135198  }
135199  while( pParse->pZombieTab ){
135200  Table *p = pParse->pZombieTab;
135201  pParse->pZombieTab = p->pNextZombie;
135202  sqlite3DeleteTable(db, p);
135203  }
135204  assert( nErr==0 || pParse->rc!=SQLITE_OK );
135205  return nErr;
135206 }
135207 
135208 /************** End of tokenize.c ********************************************/
135209 /************** Begin file complete.c ****************************************/
135210 /*
135211 ** 2001 September 15
135212 **
135213 ** The author disclaims copyright to this source code. In place of
135214 ** a legal notice, here is a blessing:
135215 **
135216 ** May you do good and not evil.
135217 ** May you find forgiveness for yourself and forgive others.
135218 ** May you share freely, never taking more than you give.
135219 **
135220 *************************************************************************
135221 ** An tokenizer for SQL
135222 **
135223 ** This file contains C code that implements the sqlite3_complete() API.
135224 ** This code used to be part of the tokenizer.c source file. But by
135225 ** separating it out, the code will be automatically omitted from
135226 ** static links that do not use it.
135227 */
135228 /* #include "sqliteInt.h" */
135229 #ifndef SQLITE_OMIT_COMPLETE
135230 
135231 /*
135232 ** This is defined in tokenize.c. We just have to import the definition.
135233 */
135234 #ifndef SQLITE_AMALGAMATION
135235 #ifdef SQLITE_ASCII
135236 #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
135237 #endif
135238 #ifdef SQLITE_EBCDIC
135239 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
135240 #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
135241 #endif
135242 #endif /* SQLITE_AMALGAMATION */
135243 
135244 
135245 /*
135246 ** Token types used by the sqlite3_complete() routine. See the header
135247 ** comments on that procedure for additional information.
135248 */
135249 #define tkSEMI 0
135250 #define tkWS 1
135251 #define tkOTHER 2
135252 #ifndef SQLITE_OMIT_TRIGGER
135253 #define tkEXPLAIN 3
135254 #define tkCREATE 4
135255 #define tkTEMP 5
135256 #define tkTRIGGER 6
135257 #define tkEND 7
135258 #endif
135259 
135260 /*
135261 ** Return TRUE if the given SQL string ends in a semicolon.
135262 **
135263 ** Special handling is require for CREATE TRIGGER statements.
135264 ** Whenever the CREATE TRIGGER keywords are seen, the statement
135265 ** must end with ";END;".
135266 **
135267 ** This implementation uses a state machine with 8 states:
135268 **
135269 ** (0) INVALID We have not yet seen a non-whitespace character.
135270 **
135271 ** (1) START At the beginning or end of an SQL statement. This routine
135272 ** returns 1 if it ends in the START state and 0 if it ends
135273 ** in any other state.
135274 **
135275 ** (2) NORMAL We are in the middle of statement which ends with a single
135276 ** semicolon.
135277 **
135278 ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
135279 ** a statement.
135280 **
135281 ** (4) CREATE The keyword CREATE has been seen at the beginning of a
135282 ** statement, possibly preceded by EXPLAIN and/or followed by
135283 ** TEMP or TEMPORARY
135284 **
135285 ** (5) TRIGGER We are in the middle of a trigger definition that must be
135286 ** ended by a semicolon, the keyword END, and another semicolon.
135287 **
135288 ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
135289 ** the end of a trigger definition.
135290 **
135291 ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
135292 ** of a trigger definition.
135293 **
135294 ** Transitions between states above are determined by tokens extracted
135295 ** from the input. The following tokens are significant:
135296 **
135297 ** (0) tkSEMI A semicolon.
135298 ** (1) tkWS Whitespace.
135299 ** (2) tkOTHER Any other SQL token.
135300 ** (3) tkEXPLAIN The "explain" keyword.
135301 ** (4) tkCREATE The "create" keyword.
135302 ** (5) tkTEMP The "temp" or "temporary" keyword.
135303 ** (6) tkTRIGGER The "trigger" keyword.
135304 ** (7) tkEND The "end" keyword.
135305 **
135306 ** Whitespace never causes a state transition and is always ignored.
135307 ** This means that a SQL string of all whitespace is invalid.
135308 **
135309 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
135310 ** to recognize the end of a trigger can be omitted. All we have to do
135311 ** is look for a semicolon that is not part of an string or comment.
135312 */
135314  u8 state = 0; /* Current state, using numbers defined in header comment */
135315  u8 token; /* Value of the next token */
135316 
135317 #ifndef SQLITE_OMIT_TRIGGER
135318  /* A complex statement machine used to detect the end of a CREATE TRIGGER
135319  ** statement. This is the normal case.
135320  */
135321  static const u8 trans[8][8] = {
135322  /* Token: */
135323  /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
135324  /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
135325  /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
135326  /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
135327  /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
135328  /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
135329  /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
135330  /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
135331  /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
135332  };
135333 #else
135334  /* If triggers are not supported by this compile then the statement machine
135335  ** used to detect the end of a statement is much simpler
135336  */
135337  static const u8 trans[3][3] = {
135338  /* Token: */
135339  /* State: ** SEMI WS OTHER */
135340  /* 0 INVALID: */ { 1, 0, 2, },
135341  /* 1 START: */ { 1, 1, 2, },
135342  /* 2 NORMAL: */ { 1, 2, 2, },
135343  };
135344 #endif /* SQLITE_OMIT_TRIGGER */
135345 
135346 #ifdef SQLITE_ENABLE_API_ARMOR
135347  if( zSql==0 ){
135349  return 0;
135350  }
135351 #endif
135352 
135353  while( *zSql ){
135354  switch( *zSql ){
135355  case ';': { /* A semicolon */
135356  token = tkSEMI;
135357  break;
135358  }
135359  case ' ':
135360  case '\r':
135361  case '\t':
135362  case '\n':
135363  case '\f': { /* White space is ignored */
135364  token = tkWS;
135365  break;
135366  }
135367  case '/': { /* C-style comments */
135368  if( zSql[1]!='*' ){
135369  token = tkOTHER;
135370  break;
135371  }
135372  zSql += 2;
135373  while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
135374  if( zSql[0]==0 ) return 0;
135375  zSql++;
135376  token = tkWS;
135377  break;
135378  }
135379  case '-': { /* SQL-style comments from "--" to end of line */
135380  if( zSql[1]!='-' ){
135381  token = tkOTHER;
135382  break;
135383  }
135384  while( *zSql && *zSql!='\n' ){ zSql++; }
135385  if( *zSql==0 ) return state==1;
135386  token = tkWS;
135387  break;
135388  }
135389  case '[': { /* Microsoft-style identifiers in [...] */
135390  zSql++;
135391  while( *zSql && *zSql!=']' ){ zSql++; }
135392  if( *zSql==0 ) return 0;
135393  token = tkOTHER;
135394  break;
135395  }
135396  case '`': /* Grave-accent quoted symbols used by MySQL */
135397  case '"': /* single- and double-quoted strings */
135398  case '\'': {
135399  int c = *zSql;
135400  zSql++;
135401  while( *zSql && *zSql!=c ){ zSql++; }
135402  if( *zSql==0 ) return 0;
135403  token = tkOTHER;
135404  break;
135405  }
135406  default: {
135407 #ifdef SQLITE_EBCDIC
135408  unsigned char c;
135409 #endif
135410  if( IdChar((u8)*zSql) ){
135411  /* Keywords and unquoted identifiers */
135412  int nId;
135413  for(nId=1; IdChar(zSql[nId]); nId++){}
135414 #ifdef SQLITE_OMIT_TRIGGER
135415  token = tkOTHER;
135416 #else
135417  switch( *zSql ){
135418  case 'c': case 'C': {
135419  if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
135420  token = tkCREATE;
135421  }else{
135422  token = tkOTHER;
135423  }
135424  break;
135425  }
135426  case 't': case 'T': {
135427  if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
135428  token = tkTRIGGER;
135429  }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
135430  token = tkTEMP;
135431  }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
135432  token = tkTEMP;
135433  }else{
135434  token = tkOTHER;
135435  }
135436  break;
135437  }
135438  case 'e': case 'E': {
135439  if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
135440  token = tkEND;
135441  }else
135442 #ifndef SQLITE_OMIT_EXPLAIN
135443  if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
135444  token = tkEXPLAIN;
135445  }else
135446 #endif
135447  {
135448  token = tkOTHER;
135449  }
135450  break;
135451  }
135452  default: {
135453  token = tkOTHER;
135454  break;
135455  }
135456  }
135457 #endif /* SQLITE_OMIT_TRIGGER */
135458  zSql += nId-1;
135459  }else{
135460  /* Operators and special symbols */
135461  token = tkOTHER;
135462  }
135463  break;
135464  }
135465  }
135466  state = trans[state][token];
135467  zSql++;
135468  }
135469  return state==1;
135470 }
135471 
135472 #ifndef SQLITE_OMIT_UTF16
135473 /*
135474 ** This routine is the same as the sqlite3_complete() routine described
135475 ** above, except that the parameter is required to be UTF-16 encoded, not
135476 ** UTF-8.
135477 */
135479  sqlite3_value *pVal;
135480  char const *zSql8;
135481  int rc;
135482 
135483 #ifndef SQLITE_OMIT_AUTOINIT
135484  rc = sqlite3_initialize();
135485  if( rc ) return rc;
135486 #endif
135487  pVal = sqlite3ValueNew(0);
135489  zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
135490  if( zSql8 ){
135491  rc = sqlite3_complete(zSql8);
135492  }else{
135493  rc = SQLITE_NOMEM_BKPT;
135494  }
135495  sqlite3ValueFree(pVal);
135496  return rc & 0xff;
135497 }
135498 #endif /* SQLITE_OMIT_UTF16 */
135499 #endif /* SQLITE_OMIT_COMPLETE */
135500 
135501 /************** End of complete.c ********************************************/
135502 /************** Begin file main.c ********************************************/
135503 /*
135504 ** 2001 September 15
135505 **
135506 ** The author disclaims copyright to this source code. In place of
135507 ** a legal notice, here is a blessing:
135508 **
135509 ** May you do good and not evil.
135510 ** May you find forgiveness for yourself and forgive others.
135511 ** May you share freely, never taking more than you give.
135512 **
135513 *************************************************************************
135514 ** Main file for the SQLite library. The routines in this file
135515 ** implement the programmer interface to the library. Routines in
135516 ** other files are for internal use by SQLite and should not be
135517 ** accessed by users of the library.
135518 */
135519 /* #include "sqliteInt.h" */
135520 
135521 #ifdef SQLITE_ENABLE_FTS3
135522 /************** Include fts3.h in the middle of main.c ***********************/
135523 /************** Begin file fts3.h ********************************************/
135524 /*
135525 ** 2006 Oct 10
135526 **
135527 ** The author disclaims copyright to this source code. In place of
135528 ** a legal notice, here is a blessing:
135529 **
135530 ** May you do good and not evil.
135531 ** May you find forgiveness for yourself and forgive others.
135532 ** May you share freely, never taking more than you give.
135533 **
135534 ******************************************************************************
135535 **
135536 ** This header file is used by programs that want to link against the
135537 ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
135538 */
135539 /* #include "sqlite3.h" */
135540 
135541 #if 0
135542 extern "C" {
135543 #endif /* __cplusplus */
135544 
135545 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
135546 
135547 #if 0
135548 } /* extern "C" */
135549 #endif /* __cplusplus */
135550 
135551 /************** End of fts3.h ************************************************/
135552 /************** Continuing where we left off in main.c ***********************/
135553 #endif
135554 #ifdef SQLITE_ENABLE_RTREE
135555 /************** Include rtree.h in the middle of main.c **********************/
135556 /************** Begin file rtree.h *******************************************/
135557 /*
135558 ** 2008 May 26
135559 **
135560 ** The author disclaims copyright to this source code. In place of
135561 ** a legal notice, here is a blessing:
135562 **
135563 ** May you do good and not evil.
135564 ** May you find forgiveness for yourself and forgive others.
135565 ** May you share freely, never taking more than you give.
135566 **
135567 ******************************************************************************
135568 **
135569 ** This header file is used by programs that want to link against the
135570 ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
135571 */
135572 /* #include "sqlite3.h" */
135573 
135574 #if 0
135575 extern "C" {
135576 #endif /* __cplusplus */
135577 
135578 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
135579 
135580 #if 0
135581 } /* extern "C" */
135582 #endif /* __cplusplus */
135583 
135584 /************** End of rtree.h ***********************************************/
135585 /************** Continuing where we left off in main.c ***********************/
135586 #endif
135587 #ifdef SQLITE_ENABLE_ICU
135588 /************** Include sqliteicu.h in the middle of main.c ******************/
135589 /************** Begin file sqliteicu.h ***************************************/
135590 /*
135591 ** 2008 May 26
135592 **
135593 ** The author disclaims copyright to this source code. In place of
135594 ** a legal notice, here is a blessing:
135595 **
135596 ** May you do good and not evil.
135597 ** May you find forgiveness for yourself and forgive others.
135598 ** May you share freely, never taking more than you give.
135599 **
135600 ******************************************************************************
135601 **
135602 ** This header file is used by programs that want to link against the
135603 ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
135604 */
135605 /* #include "sqlite3.h" */
135606 
135607 #if 0
135608 extern "C" {
135609 #endif /* __cplusplus */
135610 
135611 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
135612 
135613 #if 0
135614 } /* extern "C" */
135615 #endif /* __cplusplus */
135616 
135617 
135618 /************** End of sqliteicu.h *******************************************/
135619 /************** Continuing where we left off in main.c ***********************/
135620 #endif
135621 #ifdef SQLITE_ENABLE_JSON1
135622 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3*);
135623 #endif
135624 #ifdef SQLITE_ENABLE_FTS5
135625 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3*);
135626 #endif
135627 
135628 #ifndef SQLITE_AMALGAMATION
135629 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
135630 ** contains the text of SQLITE_VERSION macro.
135631 */
135632 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
135633 #endif
135634 
135635 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
135636 ** a pointer to the to the sqlite3_version[] string constant.
135637 */
135639 
135640 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
135641 ** pointer to a string constant whose value is the same as the
135642 ** SQLITE_SOURCE_ID C preprocessor macro.
135643 */
135645 
135646 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
135647 ** returns an integer equal to SQLITE_VERSION_NUMBER.
135648 */
135650 
135651 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
135652 ** zero if and only if SQLite was compiled with mutexing code omitted due to
135653 ** the SQLITE_THREADSAFE compile-time option being set to 0.
135654 */
135656 
135657 /*
135658 ** When compiling the test fixture or with debugging enabled (on Win32),
135659 ** this variable being set to non-zero will cause OSTRACE macros to emit
135660 ** extra diagnostic information.
135661 */
135662 #ifdef SQLITE_HAVE_OS_TRACE
135663 # ifndef SQLITE_DEBUG_OS_TRACE
135664 # define SQLITE_DEBUG_OS_TRACE 0
135665 # endif
135666  int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
135667 #endif
135668 
135669 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
135670 /*
135671 ** If the following function pointer is not NULL and if
135672 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
135673 ** I/O active are written using this function. These messages
135674 ** are intended for debugging activity only.
135675 */
135676 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
135677 #endif
135678 
135679 /*
135680 ** If the following global variable points to a string which is the
135681 ** name of a directory, then that directory will be used to store
135682 ** temporary files.
135683 **
135684 ** See also the "PRAGMA temp_store_directory" SQL command.
135685 */
135686 SQLITE_API char *sqlite3_temp_directory = 0;
135687 
135688 /*
135689 ** If the following global variable points to a string which is the
135690 ** name of a directory, then that directory will be used to store
135691 ** all database files specified with a relative pathname.
135692 **
135693 ** See also the "PRAGMA data_store_directory" SQL command.
135694 */
135695 SQLITE_API char *sqlite3_data_directory = 0;
135696 
135697 /*
135698 ** Initialize SQLite.
135699 **
135700 ** This routine must be called to initialize the memory allocation,
135701 ** VFS, and mutex subsystems prior to doing any serious work with
135702 ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
135703 ** this routine will be called automatically by key routines such as
135704 ** sqlite3_open().
135705 **
135706 ** This routine is a no-op except on its very first call for the process,
135707 ** or for the first call after a call to sqlite3_shutdown.
135708 **
135709 ** The first thread to call this routine runs the initialization to
135710 ** completion. If subsequent threads call this routine before the first
135711 ** thread has finished the initialization process, then the subsequent
135712 ** threads must block until the first thread finishes with the initialization.
135713 **
135714 ** The first thread might call this routine recursively. Recursive
135715 ** calls to this routine should not block, of course. Otherwise the
135716 ** initialization process would never complete.
135717 **
135718 ** Let X be the first thread to enter this routine. Let Y be some other
135719 ** thread. Then while the initial invocation of this routine by X is
135720 ** incomplete, it is required that:
135721 **
135722 ** * Calls to this routine from Y must block until the outer-most
135723 ** call by X completes.
135724 **
135725 ** * Recursive calls to this routine from thread X return immediately
135726 ** without blocking.
135727 */
135729  MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
135730  int rc; /* Result code */
135731 #ifdef SQLITE_EXTRA_INIT
135732  int bRunExtraInit = 0; /* Extra initialization needed */
135733 #endif
135734 
135735 #ifdef SQLITE_OMIT_WSD
135736  rc = sqlite3_wsd_init(4096, 24);
135737  if( rc!=SQLITE_OK ){
135738  return rc;
135739  }
135740 #endif
135741 
135742  /* If the following assert() fails on some obscure processor/compiler
135743  ** combination, the work-around is to set the correct pointer
135744  ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
135745  assert( SQLITE_PTRSIZE==sizeof(char*) );
135746 
135747  /* If SQLite is already completely initialized, then this call
135748  ** to sqlite3_initialize() should be a no-op. But the initialization
135749  ** must be complete. So isInit must not be set until the very end
135750  ** of this routine.
135751  */
135752  if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
135753 
135754  /* Make sure the mutex subsystem is initialized. If unable to
135755  ** initialize the mutex subsystem, return early with the error.
135756  ** If the system is so sick that we are unable to allocate a mutex,
135757  ** there is not much SQLite is going to be able to do.
135758  **
135759  ** The mutex subsystem must take care of serializing its own
135760  ** initialization.
135761  */
135762  rc = sqlite3MutexInit();
135763  if( rc ) return rc;
135764 
135765  /* Initialize the malloc() system and the recursive pInitMutex mutex.
135766  ** This operation is protected by the STATIC_MASTER mutex. Note that
135767  ** MutexAlloc() is called for a static mutex prior to initializing the
135768  ** malloc subsystem - this implies that the allocation of a static
135769  ** mutex must not require support from the malloc subsystem.
135770  */
135772  sqlite3_mutex_enter(pMaster);
135773  sqlite3GlobalConfig.isMutexInit = 1;
135774  if( !sqlite3GlobalConfig.isMallocInit ){
135775  rc = sqlite3MallocInit();
135776  }
135777  if( rc==SQLITE_OK ){
135778  sqlite3GlobalConfig.isMallocInit = 1;
135779  if( !sqlite3GlobalConfig.pInitMutex ){
135780  sqlite3GlobalConfig.pInitMutex =
135782  if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
135783  rc = SQLITE_NOMEM_BKPT;
135784  }
135785  }
135786  }
135787  if( rc==SQLITE_OK ){
135788  sqlite3GlobalConfig.nRefInitMutex++;
135789  }
135790  sqlite3_mutex_leave(pMaster);
135791 
135792  /* If rc is not SQLITE_OK at this point, then either the malloc
135793  ** subsystem could not be initialized or the system failed to allocate
135794  ** the pInitMutex mutex. Return an error in either case. */
135795  if( rc!=SQLITE_OK ){
135796  return rc;
135797  }
135798 
135799  /* Do the rest of the initialization under the recursive mutex so
135800  ** that we will be able to handle recursive calls into
135801  ** sqlite3_initialize(). The recursive calls normally come through
135802  ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
135803  ** recursive calls might also be possible.
135804  **
135805  ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
135806  ** to the xInit method, so the xInit method need not be threadsafe.
135807  **
135808  ** The following mutex is what serializes access to the appdef pcache xInit
135809  ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
135810  ** call to sqlite3PcacheInitialize().
135811  */
135813  if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
135814  sqlite3GlobalConfig.inProgress = 1;
135815 #ifdef SQLITE_ENABLE_SQLLOG
135816  {
135817  extern void sqlite3_init_sqllog(void);
135818  sqlite3_init_sqllog();
135819  }
135820 #endif
135821  memset(&sqlite3BuiltinFunctions, 0, sizeof(sqlite3BuiltinFunctions));
135823  if( sqlite3GlobalConfig.isPCacheInit==0 ){
135824  rc = sqlite3PcacheInitialize();
135825  }
135826  if( rc==SQLITE_OK ){
135827  sqlite3GlobalConfig.isPCacheInit = 1;
135828  rc = sqlite3OsInit();
135829  }
135830  if( rc==SQLITE_OK ){
135832  sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
135833  sqlite3GlobalConfig.isInit = 1;
135834 #ifdef SQLITE_EXTRA_INIT
135835  bRunExtraInit = 1;
135836 #endif
135837  }
135838  sqlite3GlobalConfig.inProgress = 0;
135839  }
135841 
135842  /* Go back under the static mutex and clean up the recursive
135843  ** mutex to prevent a resource leak.
135844  */
135845  sqlite3_mutex_enter(pMaster);
135846  sqlite3GlobalConfig.nRefInitMutex--;
135847  if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
135848  assert( sqlite3GlobalConfig.nRefInitMutex==0 );
135850  sqlite3GlobalConfig.pInitMutex = 0;
135851  }
135852  sqlite3_mutex_leave(pMaster);
135853 
135854  /* The following is just a sanity check to make sure SQLite has
135855  ** been compiled correctly. It is important to run this code, but
135856  ** we don't want to run it too often and soak up CPU cycles for no
135857  ** reason. So we run it once during initialization.
135858  */
135859 #ifndef NDEBUG
135860 #ifndef SQLITE_OMIT_FLOATING_POINT
135861  /* This section of code's only "output" is via assert() statements. */
135862  if ( rc==SQLITE_OK ){
135863  u64 x = (((u64)1)<<63)-1;
135864  double y;
135865  assert(sizeof(x)==8);
135866  assert(sizeof(x)==sizeof(y));
135867  memcpy(&y, &x, 8);
135868  assert( sqlite3IsNaN(y) );
135869  }
135870 #endif
135871 #endif
135872 
135873  /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
135874  ** compile-time option.
135875  */
135876 #ifdef SQLITE_EXTRA_INIT
135877  if( bRunExtraInit ){
135878  int SQLITE_EXTRA_INIT(const char*);
135879  rc = SQLITE_EXTRA_INIT(0);
135880  }
135881 #endif
135882 
135883  return rc;
135884 }
135885 
135886 /*
135887 ** Undo the effects of sqlite3_initialize(). Must not be called while
135888 ** there are outstanding database connections or memory allocations or
135889 ** while any part of SQLite is otherwise in use in any thread. This
135890 ** routine is not threadsafe. But it is safe to invoke this routine
135891 ** on when SQLite is already shut down. If SQLite is already shut down
135892 ** when this routine is invoked, then this routine is a harmless no-op.
135893 */
135895 #ifdef SQLITE_OMIT_WSD
135896  int rc = sqlite3_wsd_init(4096, 24);
135897  if( rc!=SQLITE_OK ){
135898  return rc;
135899  }
135900 #endif
135901 
135902  if( sqlite3GlobalConfig.isInit ){
135903 #ifdef SQLITE_EXTRA_SHUTDOWN
135904  void SQLITE_EXTRA_SHUTDOWN(void);
135905  SQLITE_EXTRA_SHUTDOWN();
135906 #endif
135907  sqlite3_os_end();
135909  sqlite3GlobalConfig.isInit = 0;
135910  }
135911  if( sqlite3GlobalConfig.isPCacheInit ){
135913  sqlite3GlobalConfig.isPCacheInit = 0;
135914  }
135915  if( sqlite3GlobalConfig.isMallocInit ){
135916  sqlite3MallocEnd();
135917  sqlite3GlobalConfig.isMallocInit = 0;
135918 
135919 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
135920  /* The heap subsystem has now been shutdown and these values are supposed
135921  ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
135922  ** which would rely on that heap subsystem; therefore, make sure these
135923  ** values cannot refer to heap memory that was just invalidated when the
135924  ** heap subsystem was shutdown. This is only done if the current call to
135925  ** this function resulted in the heap subsystem actually being shutdown.
135926  */
135927  sqlite3_data_directory = 0;
135928  sqlite3_temp_directory = 0;
135929 #endif
135930  }
135931  if( sqlite3GlobalConfig.isMutexInit ){
135932  sqlite3MutexEnd();
135933  sqlite3GlobalConfig.isMutexInit = 0;
135934  }
135935 
135936  return SQLITE_OK;
135937 }
135938 
135939 /*
135940 ** This API allows applications to modify the global configuration of
135941 ** the SQLite library at run-time.
135942 **
135943 ** This routine should only be called when there are no outstanding
135944 ** database connections or memory allocations. This routine is not
135945 ** threadsafe. Failure to heed these warnings can lead to unpredictable
135946 ** behavior.
135947 */
135949  va_list ap;
135950  int rc = SQLITE_OK;
135951 
135952  /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
135953  ** the SQLite library is in use. */
135954  if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
135955 
135956  va_start(ap, op);
135957  switch( op ){
135958 
135959  /* Mutex configuration options are only available in a threadsafe
135960  ** compile.
135961  */
135962 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-54466-46756 */
135964  /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
135965  ** Single-thread. */
135966  sqlite3GlobalConfig.bCoreMutex = 0; /* Disable mutex on core */
135967  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
135968  break;
135969  }
135970 #endif
135971 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
135972  case SQLITE_CONFIG_MULTITHREAD: {
135973  /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
135974  ** Multi-thread. */
135975  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
135976  sqlite3GlobalConfig.bFullMutex = 0; /* Disable mutex on connections */
135977  break;
135978  }
135979 #endif
135980 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
135981  case SQLITE_CONFIG_SERIALIZED: {
135982  /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
135983  ** Serialized. */
135984  sqlite3GlobalConfig.bCoreMutex = 1; /* Enable mutex on core */
135985  sqlite3GlobalConfig.bFullMutex = 1; /* Enable mutex on connections */
135986  break;
135987  }
135988 #endif
135989 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
135990  case SQLITE_CONFIG_MUTEX: {
135991  /* Specify an alternative mutex implementation */
135992  sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
135993  break;
135994  }
135995 #endif
135996 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
135997  case SQLITE_CONFIG_GETMUTEX: {
135998  /* Retrieve the current mutex implementation */
135999  *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
136000  break;
136001  }
136002 #endif
136003 
136004  case SQLITE_CONFIG_MALLOC: {
136005  /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
136006  ** single argument which is a pointer to an instance of the
136007  ** sqlite3_mem_methods structure. The argument specifies alternative
136008  ** low-level memory allocation routines to be used in place of the memory
136009  ** allocation routines built into SQLite. */
136010  sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
136011  break;
136012  }
136013  case SQLITE_CONFIG_GETMALLOC: {
136014  /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
136015  ** single argument which is a pointer to an instance of the
136016  ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
136017  ** filled with the currently defined memory allocation routines. */
136018  if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
136019  *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
136020  break;
136021  }
136022  case SQLITE_CONFIG_MEMSTATUS: {
136023  /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
136024  ** single argument of type int, interpreted as a boolean, which enables
136025  ** or disables the collection of memory allocation statistics. */
136026  sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
136027  break;
136028  }
136029  case SQLITE_CONFIG_SCRATCH: {
136030  /* EVIDENCE-OF: R-08404-60887 There are three arguments to
136031  ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
136032  ** which the scratch allocations will be drawn, the size of each scratch
136033  ** allocation (sz), and the maximum number of scratch allocations (N). */
136034  sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
136035  sqlite3GlobalConfig.szScratch = va_arg(ap, int);
136036  sqlite3GlobalConfig.nScratch = va_arg(ap, int);
136037  break;
136038  }
136039  case SQLITE_CONFIG_PAGECACHE: {
136040  /* EVIDENCE-OF: R-18761-36601 There are three arguments to
136041  ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory (pMem),
136042  ** the size of each page cache line (sz), and the number of cache lines
136043  ** (N). */
136044  sqlite3GlobalConfig.pPage = va_arg(ap, void*);
136045  sqlite3GlobalConfig.szPage = va_arg(ap, int);
136046  sqlite3GlobalConfig.nPage = va_arg(ap, int);
136047  break;
136048  }
136050  /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
136051  ** a single parameter which is a pointer to an integer and writes into
136052  ** that integer the number of extra bytes per page required for each page
136053  ** in SQLITE_CONFIG_PAGECACHE. */
136054  *va_arg(ap, int*) =
136058  break;
136059  }
136060 
136061  case SQLITE_CONFIG_PCACHE: {
136062  /* no-op */
136063  break;
136064  }
136065  case SQLITE_CONFIG_GETPCACHE: {
136066  /* now an error */
136067  rc = SQLITE_ERROR;
136068  break;
136069  }
136070 
136071  case SQLITE_CONFIG_PCACHE2: {
136072  /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
136073  ** single argument which is a pointer to an sqlite3_pcache_methods2
136074  ** object. This object specifies the interface to a custom page cache
136075  ** implementation. */
136076  sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
136077  break;
136078  }
136079  case SQLITE_CONFIG_GETPCACHE2: {
136080  /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
136081  ** single argument which is a pointer to an sqlite3_pcache_methods2
136082  ** object. SQLite copies of the current page cache implementation into
136083  ** that object. */
136084  if( sqlite3GlobalConfig.pcache2.xInit==0 ){
136086  }
136087  *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
136088  break;
136089  }
136090 
136091 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
136092 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
136093 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
136094 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
136095  case SQLITE_CONFIG_HEAP: {
136096  /* EVIDENCE-OF: R-19854-42126 There are three arguments to
136097  ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
136098  ** number of bytes in the memory buffer, and the minimum allocation size.
136099  */
136100  sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
136101  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
136102  sqlite3GlobalConfig.mnReq = va_arg(ap, int);
136103 
136104  if( sqlite3GlobalConfig.mnReq<1 ){
136105  sqlite3GlobalConfig.mnReq = 1;
136106  }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
136107  /* cap min request size at 2^12 */
136108  sqlite3GlobalConfig.mnReq = (1<<12);
136109  }
136110 
136111  if( sqlite3GlobalConfig.pHeap==0 ){
136112  /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
136113  ** is NULL, then SQLite reverts to using its default memory allocator
136114  ** (the system malloc() implementation), undoing any prior invocation of
136115  ** SQLITE_CONFIG_MALLOC.
136116  **
136117  ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
136118  ** revert to its default implementation when sqlite3_initialize() is run
136119  */
136120  memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
136121  }else{
136122  /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
136123  ** alternative memory allocator is engaged to handle all of SQLites
136124  ** memory allocation needs. */
136125 #ifdef SQLITE_ENABLE_MEMSYS3
136126  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
136127 #endif
136128 #ifdef SQLITE_ENABLE_MEMSYS5
136129  sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
136130 #endif
136131  }
136132  break;
136133  }
136134 #endif
136135 
136136  case SQLITE_CONFIG_LOOKASIDE: {
136137  sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
136138  sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
136139  break;
136140  }
136141 
136142  /* Record a pointer to the logger function and its first argument.
136143  ** The default is NULL. Logging is disabled if the function pointer is
136144  ** NULL.
136145  */
136146  case SQLITE_CONFIG_LOG: {
136147  /* MSVC is picky about pulling func ptrs from va lists.
136148  ** http://support.microsoft.com/kb/47961
136149  ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
136150  */
136151  typedef void(*LOGFUNC_t)(void*,int,const char*);
136152  sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
136153  sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
136154  break;
136155  }
136156 
136157  /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
136158  ** can be changed at start-time using the
136159  ** sqlite3_config(SQLITE_CONFIG_URI,1) or
136160  ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
136161  */
136162  case SQLITE_CONFIG_URI: {
136163  /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
136164  ** argument of type int. If non-zero, then URI handling is globally
136165  ** enabled. If the parameter is zero, then URI handling is globally
136166  ** disabled. */
136167  sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
136168  break;
136169  }
136170 
136172  /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
136173  ** option takes a single integer argument which is interpreted as a
136174  ** boolean in order to enable or disable the use of covering indices for
136175  ** full table scans in the query optimizer. */
136176  sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
136177  break;
136178  }
136179 
136180 #ifdef SQLITE_ENABLE_SQLLOG
136181  case SQLITE_CONFIG_SQLLOG: {
136182  typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
136183  sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
136184  sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
136185  break;
136186  }
136187 #endif
136188 
136189  case SQLITE_CONFIG_MMAP_SIZE: {
136190  /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
136191  ** integer (sqlite3_int64) values that are the default mmap size limit
136192  ** (the default setting for PRAGMA mmap_size) and the maximum allowed
136193  ** mmap size limit. */
136194  sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
136195  sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
136196  /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
136197  ** negative, then that argument is changed to its compile-time default.
136198  **
136199  ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
136200  ** silently truncated if necessary so that it does not exceed the
136201  ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
136202  ** compile-time option.
136203  */
136204  if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
136205  mxMmap = SQLITE_MAX_MMAP_SIZE;
136206  }
136207  if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
136208  if( szMmap>mxMmap) szMmap = mxMmap;
136209  sqlite3GlobalConfig.mxMmap = mxMmap;
136210  sqlite3GlobalConfig.szMmap = szMmap;
136211  break;
136212  }
136213 
136214 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
136216  /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
136217  ** unsigned integer value that specifies the maximum size of the created
136218  ** heap. */
136219  sqlite3GlobalConfig.nHeap = va_arg(ap, int);
136220  break;
136221  }
136222 #endif
136223 
136224  case SQLITE_CONFIG_PMASZ: {
136225  sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
136226  break;
136227  }
136228 
136230  sqlite3GlobalConfig.nStmtSpill = va_arg(ap, int);
136231  break;
136232  }
136233 
136234  default: {
136235  rc = SQLITE_ERROR;
136236  break;
136237  }
136238  }
136239  va_end(ap);
136240  return rc;
136241 }
136242 
136243 /*
136244 ** Set up the lookaside buffers for a database connection.
136245 ** Return SQLITE_OK on success.
136246 ** If lookaside is already active, return SQLITE_BUSY.
136247 **
136248 ** The sz parameter is the number of bytes in each lookaside slot.
136249 ** The cnt parameter is the number of slots. If pStart is NULL the
136250 ** space for the lookaside memory is obtained from sqlite3_malloc().
136251 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
136252 ** the lookaside memory.
136253 */
136254 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
136255 #ifndef SQLITE_OMIT_LOOKASIDE
136256  void *pStart;
136257  if( db->lookaside.nOut ){
136258  return SQLITE_BUSY;
136259  }
136260  /* Free any existing lookaside buffer for this handle before
136261  ** allocating a new one so we don't have to have space for
136262  ** both at the same time.
136263  */
136264  if( db->lookaside.bMalloced ){
136266  }
136267  /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
136268  ** than a pointer to be useful.
136269  */
136270  sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
136271  if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
136272  if( cnt<0 ) cnt = 0;
136273  if( sz==0 || cnt==0 ){
136274  sz = 0;
136275  pStart = 0;
136276  }else if( pBuf==0 ){
136278  pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
136280  if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
136281  }else{
136282  pStart = pBuf;
136283  }
136284  db->lookaside.pStart = pStart;
136285  db->lookaside.pFree = 0;
136286  db->lookaside.sz = (u16)sz;
136287  if( pStart ){
136288  int i;
136289  LookasideSlot *p;
136290  assert( sz > (int)sizeof(LookasideSlot*) );
136291  p = (LookasideSlot*)pStart;
136292  for(i=cnt-1; i>=0; i--){
136293  p->pNext = db->lookaside.pFree;
136294  db->lookaside.pFree = p;
136295  p = (LookasideSlot*)&((u8*)p)[sz];
136296  }
136297  db->lookaside.pEnd = p;
136298  db->lookaside.bDisable = 0;
136299  db->lookaside.bMalloced = pBuf==0 ?1:0;
136300  }else{
136301  db->lookaside.pStart = db;
136302  db->lookaside.pEnd = db;
136303  db->lookaside.bDisable = 1;
136304  db->lookaside.bMalloced = 0;
136305  }
136306 #endif /* SQLITE_OMIT_LOOKASIDE */
136307  return SQLITE_OK;
136308 }
136309 
136310 /*
136311 ** Return the mutex associated with a database connection.
136312 */
136314 #ifdef SQLITE_ENABLE_API_ARMOR
136315  if( !sqlite3SafetyCheckOk(db) ){
136317  return 0;
136318  }
136319 #endif
136320  return db->mutex;
136321 }
136322 
136323 /*
136324 ** Free up as much memory as we can from the given database
136325 ** connection.
136326 */
136328  int i;
136329 
136330 #ifdef SQLITE_ENABLE_API_ARMOR
136331  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
136332 #endif
136333  sqlite3_mutex_enter(db->mutex);
136334  sqlite3BtreeEnterAll(db);
136335  for(i=0; i<db->nDb; i++){
136336  Btree *pBt = db->aDb[i].pBt;
136337  if( pBt ){
136338  Pager *pPager = sqlite3BtreePager(pBt);
136339  sqlite3PagerShrink(pPager);
136340  }
136341  }
136342  sqlite3BtreeLeaveAll(db);
136343  sqlite3_mutex_leave(db->mutex);
136344  return SQLITE_OK;
136345 }
136346 
136347 /*
136348 ** Flush any dirty pages in the pager-cache for any attached database
136349 ** to disk.
136350 */
136352  int i;
136353  int rc = SQLITE_OK;
136354  int bSeenBusy = 0;
136355 
136356 #ifdef SQLITE_ENABLE_API_ARMOR
136357  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
136358 #endif
136359  sqlite3_mutex_enter(db->mutex);
136360  sqlite3BtreeEnterAll(db);
136361  for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
136362  Btree *pBt = db->aDb[i].pBt;
136363  if( pBt && sqlite3BtreeIsInTrans(pBt) ){
136364  Pager *pPager = sqlite3BtreePager(pBt);
136365  rc = sqlite3PagerFlush(pPager);
136366  if( rc==SQLITE_BUSY ){
136367  bSeenBusy = 1;
136368  rc = SQLITE_OK;
136369  }
136370  }
136371  }
136372  sqlite3BtreeLeaveAll(db);
136373  sqlite3_mutex_leave(db->mutex);
136374  return ((rc==SQLITE_OK && bSeenBusy) ? SQLITE_BUSY : rc);
136375 }
136376 
136377 /*
136378 ** Configuration settings for an individual database connection
136379 */
136380 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
136381  va_list ap;
136382  int rc;
136383  va_start(ap, op);
136384  switch( op ){
136385  case SQLITE_DBCONFIG_LOOKASIDE: {
136386  void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
136387  int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
136388  int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
136389  rc = setupLookaside(db, pBuf, sz, cnt);
136390  break;
136391  }
136392  default: {
136393  static const struct {
136394  int op; /* The opcode */
136395  u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
136396  } aFlagOp[] = {
136401  };
136402  unsigned int i;
136403  rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
136404  for(i=0; i<ArraySize(aFlagOp); i++){
136405  if( aFlagOp[i].op==op ){
136406  int onoff = va_arg(ap, int);
136407  int *pRes = va_arg(ap, int*);
136408  int oldFlags = db->flags;
136409  if( onoff>0 ){
136410  db->flags |= aFlagOp[i].mask;
136411  }else if( onoff==0 ){
136412  db->flags &= ~aFlagOp[i].mask;
136413  }
136414  if( oldFlags!=db->flags ){
136416  }
136417  if( pRes ){
136418  *pRes = (db->flags & aFlagOp[i].mask)!=0;
136419  }
136420  rc = SQLITE_OK;
136421  break;
136422  }
136423  }
136424  break;
136425  }
136426  }
136427  va_end(ap);
136428  return rc;
136429 }
136430 
136431 
136432 /*
136433 ** Return true if the buffer z[0..n-1] contains all spaces.
136434 */
136435 static int allSpaces(const char *z, int n){
136436  while( n>0 && z[n-1]==' ' ){ n--; }
136437  return n==0;
136438 }
136439 
136440 /*
136441 ** This is the default collating function named "BINARY" which is always
136442 ** available.
136443 **
136444 ** If the padFlag argument is not NULL then space padding at the end
136445 ** of strings is ignored. This implements the RTRIM collation.
136446 */
136447 static int binCollFunc(
136448  void *padFlag,
136449  int nKey1, const void *pKey1,
136450  int nKey2, const void *pKey2
136451 ){
136452  int rc, n;
136453  n = nKey1<nKey2 ? nKey1 : nKey2;
136454  /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
136455  ** strings byte by byte using the memcmp() function from the standard C
136456  ** library. */
136457  rc = memcmp(pKey1, pKey2, n);
136458  if( rc==0 ){
136459  if( padFlag
136460  && allSpaces(((char*)pKey1)+n, nKey1-n)
136461  && allSpaces(((char*)pKey2)+n, nKey2-n)
136462  ){
136463  /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
136464  ** spaces at the end of either string do not change the result. In other
136465  ** words, strings will compare equal to one another as long as they
136466  ** differ only in the number of spaces at the end.
136467  */
136468  }else{
136469  rc = nKey1 - nKey2;
136470  }
136471  }
136472  return rc;
136473 }
136474 
136475 /*
136476 ** Another built-in collating sequence: NOCASE.
136477 **
136478 ** This collating sequence is intended to be used for "case independent
136479 ** comparison". SQLite's knowledge of upper and lower case equivalents
136480 ** extends only to the 26 characters used in the English language.
136481 **
136482 ** At the moment there is only a UTF-8 implementation.
136483 */
136485  void *NotUsed,
136486  int nKey1, const void *pKey1,
136487  int nKey2, const void *pKey2
136488 ){
136489  int r = sqlite3StrNICmp(
136490  (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
136491  UNUSED_PARAMETER(NotUsed);
136492  if( 0==r ){
136493  r = nKey1-nKey2;
136494  }
136495  return r;
136496 }
136497 
136498 /*
136499 ** Return the ROWID of the most recent insert
136500 */
136502 #ifdef SQLITE_ENABLE_API_ARMOR
136503  if( !sqlite3SafetyCheckOk(db) ){
136505  return 0;
136506  }
136507 #endif
136508  return db->lastRowid;
136509 }
136510 
136511 /*
136512 ** Return the number of changes in the most recent call to sqlite3_exec().
136513 */
136515 #ifdef SQLITE_ENABLE_API_ARMOR
136516  if( !sqlite3SafetyCheckOk(db) ){
136518  return 0;
136519  }
136520 #endif
136521  return db->nChange;
136522 }
136523 
136524 /*
136525 ** Return the number of changes since the database handle was opened.
136526 */
136528 #ifdef SQLITE_ENABLE_API_ARMOR
136529  if( !sqlite3SafetyCheckOk(db) ){
136531  return 0;
136532  }
136533 #endif
136534  return db->nTotalChange;
136535 }
136536 
136537 /*
136538 ** Close all open savepoints. This function only manipulates fields of the
136539 ** database handle object, it does not close any savepoints that may be open
136540 ** at the b-tree/pager level.
136541 */
136543  while( db->pSavepoint ){
136544  Savepoint *pTmp = db->pSavepoint;
136545  db->pSavepoint = pTmp->pNext;
136546  sqlite3DbFree(db, pTmp);
136547  }
136548  db->nSavepoint = 0;
136549  db->nStatement = 0;
136550  db->isTransactionSavepoint = 0;
136551 }
136552 
136553 /*
136554 ** Invoke the destructor function associated with FuncDef p, if any. Except,
136555 ** if this is not the last copy of the function, do not invoke it. Multiple
136556 ** copies of a single function are created when create_function() is called
136557 ** with SQLITE_ANY as the encoding.
136558 */
136559 static void functionDestroy(sqlite3 *db, FuncDef *p){
136560  FuncDestructor *pDestructor = p->u.pDestructor;
136561  if( pDestructor ){
136562  pDestructor->nRef--;
136563  if( pDestructor->nRef==0 ){
136564  pDestructor->xDestroy(pDestructor->pUserData);
136565  sqlite3DbFree(db, pDestructor);
136566  }
136567  }
136568 }
136569 
136570 /*
136571 ** Disconnect all sqlite3_vtab objects that belong to database connection
136572 ** db. This is called when db is being closed.
136573 */
136574 static void disconnectAllVtab(sqlite3 *db){
136575 #ifndef SQLITE_OMIT_VIRTUALTABLE
136576  int i;
136577  HashElem *p;
136578  sqlite3BtreeEnterAll(db);
136579  for(i=0; i<db->nDb; i++){
136580  Schema *pSchema = db->aDb[i].pSchema;
136581  if( db->aDb[i].pSchema ){
136582  for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
136583  Table *pTab = (Table *)sqliteHashData(p);
136584  if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
136585  }
136586  }
136587  }
136588  for(p=sqliteHashFirst(&db->aModule); p; p=sqliteHashNext(p)){
136589  Module *pMod = (Module *)sqliteHashData(p);
136590  if( pMod->pEpoTab ){
136591  sqlite3VtabDisconnect(db, pMod->pEpoTab);
136592  }
136593  }
136594  sqlite3VtabUnlockList(db);
136595  sqlite3BtreeLeaveAll(db);
136596 #else
136597  UNUSED_PARAMETER(db);
136598 #endif
136599 }
136600 
136601 /*
136602 ** Return TRUE if database connection db has unfinalized prepared
136603 ** statements or unfinished sqlite3_backup objects.
136604 */
136605 static int connectionIsBusy(sqlite3 *db){
136606  int j;
136607  assert( sqlite3_mutex_held(db->mutex) );
136608  if( db->pVdbe ) return 1;
136609  for(j=0; j<db->nDb; j++){
136610  Btree *pBt = db->aDb[j].pBt;
136611  if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
136612  }
136613  return 0;
136614 }
136615 
136616 /*
136617 ** Close an existing SQLite database
136618 */
136619 static int sqlite3Close(sqlite3 *db, int forceZombie){
136620  if( !db ){
136621  /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
136622  ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
136623  return SQLITE_OK;
136624  }
136625  if( !sqlite3SafetyCheckSickOrOk(db) ){
136626  return SQLITE_MISUSE_BKPT;
136627  }
136628  sqlite3_mutex_enter(db->mutex);
136629 
136630  /* Force xDisconnect calls on all virtual tables */
136631  disconnectAllVtab(db);
136632 
136633  /* If a transaction is open, the disconnectAllVtab() call above
136634  ** will not have called the xDisconnect() method on any virtual
136635  ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
136636  ** call will do so. We need to do this before the check for active
136637  ** SQL statements below, as the v-table implementation may be storing
136638  ** some prepared statements internally.
136639  */
136640  sqlite3VtabRollback(db);
136641 
136642  /* Legacy behavior (sqlite3_close() behavior) is to return
136643  ** SQLITE_BUSY if the connection can not be closed immediately.
136644  */
136645  if( !forceZombie && connectionIsBusy(db) ){
136646  sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
136647  "statements or unfinished backups");
136648  sqlite3_mutex_leave(db->mutex);
136649  return SQLITE_BUSY;
136650  }
136651 
136652 #ifdef SQLITE_ENABLE_SQLLOG
136653  if( sqlite3GlobalConfig.xSqllog ){
136654  /* Closing the handle. Fourth parameter is passed the value 2. */
136655  sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
136656  }
136657 #endif
136658 
136659  /* Convert the connection into a zombie and then close it.
136660  */
136661  db->magic = SQLITE_MAGIC_ZOMBIE;
136663  return SQLITE_OK;
136664 }
136665 
136666 /*
136667 ** Two variations on the public interface for closing a database
136668 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
136669 ** leaves the connection option if there are unfinalized prepared
136670 ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
136671 ** version forces the connection to become a zombie if there are
136672 ** unclosed resources, and arranges for deallocation when the last
136673 ** prepare statement or sqlite3_backup closes.
136674 */
136675 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
136676 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
136677 
136678 
136679 /*
136680 ** Close the mutex on database connection db.
136681 **
136682 ** Furthermore, if database connection db is a zombie (meaning that there
136683 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
136684 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
136685 ** finished, then free all resources.
136686 */
136688  HashElem *i; /* Hash table iterator */
136689  int j;
136690 
136691  /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
136692  ** or if the connection has not yet been closed by sqlite3_close_v2(),
136693  ** then just leave the mutex and return.
136694  */
136695  if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
136696  sqlite3_mutex_leave(db->mutex);
136697  return;
136698  }
136699 
136700  /* If we reach this point, it means that the database connection has
136701  ** closed all sqlite3_stmt and sqlite3_backup objects and has been
136702  ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
136703  ** go ahead and free all resources.
136704  */
136705 
136706  /* If a transaction is open, roll it back. This also ensures that if
136707  ** any database schemas have been modified by an uncommitted transaction
136708  ** they are reset. And that the required b-tree mutex is held to make
136709  ** the pager rollback and schema reset an atomic operation. */
136711 
136712  /* Free any outstanding Savepoint structures. */
136714 
136715  /* Close all database connections */
136716  for(j=0; j<db->nDb; j++){
136717  struct Db *pDb = &db->aDb[j];
136718  if( pDb->pBt ){
136719  sqlite3BtreeClose(pDb->pBt);
136720  pDb->pBt = 0;
136721  if( j!=1 ){
136722  pDb->pSchema = 0;
136723  }
136724  }
136725  }
136726  /* Clear the TEMP schema separately and last */
136727  if( db->aDb[1].pSchema ){
136728  sqlite3SchemaClear(db->aDb[1].pSchema);
136729  }
136730  sqlite3VtabUnlockList(db);
136731 
136732  /* Free up the array of auxiliary databases */
136734  assert( db->nDb<=2 );
136735  assert( db->aDb==db->aDbStatic );
136736 
136737  /* Tell the code in notify.c that the connection no longer holds any
136738  ** locks and does not require any further unlock-notify callbacks.
136739  */
136741 
136742  for(i=sqliteHashFirst(&db->aFunc); i; i=sqliteHashNext(i)){
136743  FuncDef *pNext, *p;
136744  p = sqliteHashData(i);
136745  do{
136746  functionDestroy(db, p);
136747  pNext = p->pNext;
136748  sqlite3DbFree(db, p);
136749  p = pNext;
136750  }while( p );
136751  }
136752  sqlite3HashClear(&db->aFunc);
136753  for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
136754  CollSeq *pColl = (CollSeq *)sqliteHashData(i);
136755  /* Invoke any destructors registered for collation sequence user data. */
136756  for(j=0; j<3; j++){
136757  if( pColl[j].xDel ){
136758  pColl[j].xDel(pColl[j].pUser);
136759  }
136760  }
136761  sqlite3DbFree(db, pColl);
136762  }
136763  sqlite3HashClear(&db->aCollSeq);
136764 #ifndef SQLITE_OMIT_VIRTUALTABLE
136765  for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
136766  Module *pMod = (Module *)sqliteHashData(i);
136767  if( pMod->xDestroy ){
136768  pMod->xDestroy(pMod->pAux);
136769  }
136770  sqlite3VtabEponymousTableClear(db, pMod);
136771  sqlite3DbFree(db, pMod);
136772  }
136773  sqlite3HashClear(&db->aModule);
136774 #endif
136775 
136776  sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
136777  sqlite3ValueFree(db->pErr);
136779 #if SQLITE_USER_AUTHENTICATION
136780  sqlite3_free(db->auth.zAuthUser);
136781  sqlite3_free(db->auth.zAuthPW);
136782 #endif
136783 
136784  db->magic = SQLITE_MAGIC_ERROR;
136785 
136786  /* The temp-database schema is allocated differently from the other schema
136787  ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
136788  ** So it needs to be freed here. Todo: Why not roll the temp schema into
136789  ** the same sqliteMalloc() as the one that allocates the database
136790  ** structure?
136791  */
136792  sqlite3DbFree(db, db->aDb[1].pSchema);
136793  sqlite3_mutex_leave(db->mutex);
136794  db->magic = SQLITE_MAGIC_CLOSED;
136795  sqlite3_mutex_free(db->mutex);
136796  assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
136797  if( db->lookaside.bMalloced ){
136799  }
136800  sqlite3_free(db);
136801 }
136802 
136803 /*
136804 ** Rollback all database files. If tripCode is not SQLITE_OK, then
136805 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
136806 ** breaker") and made to return tripCode if there are any further
136807 ** attempts to use that cursor. Read cursors remain open and valid
136808 ** but are "saved" in case the table pages are moved around.
136809 */
136810 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
136811  int i;
136812  int inTrans = 0;
136813  int schemaChange;
136814  assert( sqlite3_mutex_held(db->mutex) );
136816 
136817  /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
136818  ** This is important in case the transaction being rolled back has
136819  ** modified the database schema. If the b-tree mutexes are not taken
136820  ** here, then another shared-cache connection might sneak in between
136821  ** the database rollback and schema reset, which can cause false
136822  ** corruption reports in some cases. */
136823  sqlite3BtreeEnterAll(db);
136824  schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
136825 
136826  for(i=0; i<db->nDb; i++){
136827  Btree *p = db->aDb[i].pBt;
136828  if( p ){
136829  if( sqlite3BtreeIsInTrans(p) ){
136830  inTrans = 1;
136831  }
136832  sqlite3BtreeRollback(p, tripCode, !schemaChange);
136833  }
136834  }
136835  sqlite3VtabRollback(db);
136837 
136838  if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
136841  }
136842  sqlite3BtreeLeaveAll(db);
136843 
136844  /* Any deferred constraint violations have now been resolved. */
136845  db->nDeferredCons = 0;
136846  db->nDeferredImmCons = 0;
136847  db->flags &= ~SQLITE_DeferFKs;
136848 
136849  /* If one has been configured, invoke the rollback-hook callback */
136850  if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
136851  db->xRollbackCallback(db->pRollbackArg);
136852  }
136853 }
136854 
136855 /*
136856 ** Return a static string containing the name corresponding to the error code
136857 ** specified in the argument.
136858 */
136859 #if defined(SQLITE_NEED_ERR_NAME)
136860 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
136861  const char *zName = 0;
136862  int i, origRc = rc;
136863  for(i=0; i<2 && zName==0; i++, rc &= 0xff){
136864  switch( rc ){
136865  case SQLITE_OK: zName = "SQLITE_OK"; break;
136866  case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
136867  case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
136868  case SQLITE_PERM: zName = "SQLITE_PERM"; break;
136869  case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
136870  case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
136871  case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
136872  case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
136873  case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
136874  case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
136875  case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
136876  case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
136877  case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
136878  case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
136879  case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
136880  case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
136881  case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
136882  case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
136883  case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
136884  case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
136885  case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
136886  case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
136887  case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
136888  case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
136889  case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
136890  case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
136891  case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
136892  case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
136893  case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
136894  case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
136895  case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
136897  zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
136898  case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
136899  case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
136900  case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
136901  case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
136902  case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
136903  case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
136904  case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
136905  case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
136906  case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
136907  case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
136908  case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
136909  case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
136910  case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
136911  case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
136912  case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
136913  case SQLITE_FULL: zName = "SQLITE_FULL"; break;
136914  case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
136915  case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
136916  case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
136917  case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
136918  case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
136919  case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
136920  case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
136921  case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
136922  case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
136923  case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
136924  case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
136925  case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
136927  zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
136928  case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
136930  zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
136931  case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
136933  zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
136934  case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
136936  zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
136937  case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
136938  case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
136939  case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
136940  case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
136941  case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
136942  case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
136943  case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
136944  case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
136945  case SQLITE_ROW: zName = "SQLITE_ROW"; break;
136946  case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
136947  case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
136949  zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
136950  case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
136951  case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
136952  case SQLITE_DONE: zName = "SQLITE_DONE"; break;
136953  }
136954  }
136955  if( zName==0 ){
136956  static char zBuf[50];
136957  sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
136958  zName = zBuf;
136959  }
136960  return zName;
136961 }
136962 #endif
136963 
136964 /*
136965 ** Return a static string that describes the kind of error specified in the
136966 ** argument.
136967 */
136968 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
136969  static const char* const aMsg[] = {
136970  /* SQLITE_OK */ "not an error",
136971  /* SQLITE_ERROR */ "SQL logic error or missing database",
136972  /* SQLITE_INTERNAL */ 0,
136973  /* SQLITE_PERM */ "access permission denied",
136974  /* SQLITE_ABORT */ "callback requested query abort",
136975  /* SQLITE_BUSY */ "database is locked",
136976  /* SQLITE_LOCKED */ "database table is locked",
136977  /* SQLITE_NOMEM */ "out of memory",
136978  /* SQLITE_READONLY */ "attempt to write a readonly database",
136979  /* SQLITE_INTERRUPT */ "interrupted",
136980  /* SQLITE_IOERR */ "disk I/O error",
136981  /* SQLITE_CORRUPT */ "database disk image is malformed",
136982  /* SQLITE_NOTFOUND */ "unknown operation",
136983  /* SQLITE_FULL */ "database or disk is full",
136984  /* SQLITE_CANTOPEN */ "unable to open database file",
136985  /* SQLITE_PROTOCOL */ "locking protocol",
136986  /* SQLITE_EMPTY */ "table contains no data",
136987  /* SQLITE_SCHEMA */ "database schema has changed",
136988  /* SQLITE_TOOBIG */ "string or blob too big",
136989  /* SQLITE_CONSTRAINT */ "constraint failed",
136990  /* SQLITE_MISMATCH */ "datatype mismatch",
136991  /* SQLITE_MISUSE */ "library routine called out of sequence",
136992  /* SQLITE_NOLFS */ "large file support is disabled",
136993  /* SQLITE_AUTH */ "authorization denied",
136994  /* SQLITE_FORMAT */ "auxiliary database format error",
136995  /* SQLITE_RANGE */ "bind or column index out of range",
136996  /* SQLITE_NOTADB */ "file is encrypted or is not a database",
136997  };
136998  const char *zErr = "unknown error";
136999  switch( rc ){
137000  case SQLITE_ABORT_ROLLBACK: {
137001  zErr = "abort due to ROLLBACK";
137002  break;
137003  }
137004  default: {
137005  rc &= 0xff;
137006  if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
137007  zErr = aMsg[rc];
137008  }
137009  break;
137010  }
137011  }
137012  return zErr;
137013 }
137014 
137015 /*
137016 ** This routine implements a busy callback that sleeps and tries
137017 ** again until a timeout value is reached. The timeout value is
137018 ** an integer number of milliseconds passed in as the first
137019 ** argument.
137020 */
137022  void *ptr, /* Database connection */
137023  int count /* Number of times table has been busy */
137024 ){
137025 #if SQLITE_OS_WIN || HAVE_USLEEP
137026  static const u8 delays[] =
137027  { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
137028  static const u8 totals[] =
137029  { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
137030 # define NDELAY ArraySize(delays)
137031  sqlite3 *db = (sqlite3 *)ptr;
137032  int timeout = db->busyTimeout;
137033  int delay, prior;
137034 
137035  assert( count>=0 );
137036  if( count < NDELAY ){
137037  delay = delays[count];
137038  prior = totals[count];
137039  }else{
137040  delay = delays[NDELAY-1];
137041  prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
137042  }
137043  if( prior + delay > timeout ){
137044  delay = timeout - prior;
137045  if( delay<=0 ) return 0;
137046  }
137047  sqlite3OsSleep(db->pVfs, delay*1000);
137048  return 1;
137049 #else
137050  sqlite3 *db = (sqlite3 *)ptr;
137051  int timeout = ((sqlite3 *)ptr)->busyTimeout;
137052  if( (count+1)*1000 > timeout ){
137053  return 0;
137054  }
137055  sqlite3OsSleep(db->pVfs, 1000000);
137056  return 1;
137057 #endif
137058 }
137059 
137060 /*
137061 ** Invoke the given busy handler.
137062 **
137063 ** This routine is called when an operation failed with a lock.
137064 ** If this routine returns non-zero, the lock is retried. If it
137065 ** returns 0, the operation aborts with an SQLITE_BUSY error.
137066 */
137068  int rc;
137069  if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
137070  rc = p->xFunc(p->pArg, p->nBusy);
137071  if( rc==0 ){
137072  p->nBusy = -1;
137073  }else{
137074  p->nBusy++;
137075  }
137076  return rc;
137077 }
137078 
137079 /*
137080 ** This routine sets the busy callback for an Sqlite database to the
137081 ** given callback function with the given argument.
137082 */
137084  sqlite3 *db,
137085  int (*xBusy)(void*,int),
137086  void *pArg
137087 ){
137088 #ifdef SQLITE_ENABLE_API_ARMOR
137089  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137090 #endif
137091  sqlite3_mutex_enter(db->mutex);
137092  db->busyHandler.xFunc = xBusy;
137093  db->busyHandler.pArg = pArg;
137094  db->busyHandler.nBusy = 0;
137095  db->busyTimeout = 0;
137096  sqlite3_mutex_leave(db->mutex);
137097  return SQLITE_OK;
137098 }
137099 
137100 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
137101 /*
137102 ** This routine sets the progress callback for an Sqlite database to the
137103 ** given callback function with the given argument. The progress callback will
137104 ** be invoked every nOps opcodes.
137105 */
137107  sqlite3 *db,
137108  int nOps,
137109  int (*xProgress)(void*),
137110  void *pArg
137111 ){
137112 #ifdef SQLITE_ENABLE_API_ARMOR
137113  if( !sqlite3SafetyCheckOk(db) ){
137115  return;
137116  }
137117 #endif
137118  sqlite3_mutex_enter(db->mutex);
137119  if( nOps>0 ){
137120  db->xProgress = xProgress;
137121  db->nProgressOps = (unsigned)nOps;
137122  db->pProgressArg = pArg;
137123  }else{
137124  db->xProgress = 0;
137125  db->nProgressOps = 0;
137126  db->pProgressArg = 0;
137127  }
137128  sqlite3_mutex_leave(db->mutex);
137129 }
137130 #endif
137131 
137132 
137133 /*
137134 ** This routine installs a default busy handler that waits for the
137135 ** specified number of milliseconds before returning 0.
137136 */
137138 #ifdef SQLITE_ENABLE_API_ARMOR
137139  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137140 #endif
137141  if( ms>0 ){
137143  db->busyTimeout = ms;
137144  }else{
137145  sqlite3_busy_handler(db, 0, 0);
137146  }
137147  return SQLITE_OK;
137148 }
137149 
137150 /*
137151 ** Cause any pending operation to stop at its earliest opportunity.
137152 */
137154 #ifdef SQLITE_ENABLE_API_ARMOR
137155  if( !sqlite3SafetyCheckOk(db) ){
137157  return;
137158  }
137159 #endif
137160  db->u1.isInterrupted = 1;
137161 }
137162 
137163 
137164 /*
137165 ** This function is exactly the same as sqlite3_create_function(), except
137166 ** that it is designed to be called by internal code. The difference is
137167 ** that if a malloc() fails in sqlite3_create_function(), an error code
137168 ** is returned and the mallocFailed flag cleared.
137169 */
137171  sqlite3 *db,
137172  const char *zFunctionName,
137173  int nArg,
137174  int enc,
137175  void *pUserData,
137176  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
137177  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
137178  void (*xFinal)(sqlite3_context*),
137179  FuncDestructor *pDestructor
137180 ){
137181  FuncDef *p;
137182  int nName;
137183  int extraFlags;
137184 
137185  assert( sqlite3_mutex_held(db->mutex) );
137186  if( zFunctionName==0 ||
137187  (xSFunc && (xFinal || xStep)) ||
137188  (!xSFunc && (xFinal && !xStep)) ||
137189  (!xSFunc && (!xFinal && xStep)) ||
137190  (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
137191  (255<(nName = sqlite3Strlen30( zFunctionName))) ){
137192  return SQLITE_MISUSE_BKPT;
137193  }
137194 
137196  extraFlags = enc & SQLITE_DETERMINISTIC;
137197  enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
137198 
137199 #ifndef SQLITE_OMIT_UTF16
137200  /* If SQLITE_UTF16 is specified as the encoding type, transform this
137201  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
137202  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
137203  **
137204  ** If SQLITE_ANY is specified, add three versions of the function
137205  ** to the hash table.
137206  */
137207  if( enc==SQLITE_UTF16 ){
137208  enc = SQLITE_UTF16NATIVE;
137209  }else if( enc==SQLITE_ANY ){
137210  int rc;
137211  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
137212  pUserData, xSFunc, xStep, xFinal, pDestructor);
137213  if( rc==SQLITE_OK ){
137214  rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
137215  pUserData, xSFunc, xStep, xFinal, pDestructor);
137216  }
137217  if( rc!=SQLITE_OK ){
137218  return rc;
137219  }
137220  enc = SQLITE_UTF16BE;
137221  }
137222 #else
137223  enc = SQLITE_UTF8;
137224 #endif
137225 
137226  /* Check if an existing function is being overridden or deleted. If so,
137227  ** and there are active VMs, then return SQLITE_BUSY. If a function
137228  ** is being overridden/deleted but there are no active VMs, allow the
137229  ** operation to continue but invalidate all precompiled statements.
137230  */
137231  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 0);
137232  if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
137233  if( db->nVdbeActive ){
137235  "unable to delete/modify user-function due to active statements");
137236  assert( !db->mallocFailed );
137237  return SQLITE_BUSY;
137238  }else{
137240  }
137241  }
137242 
137243  p = sqlite3FindFunction(db, zFunctionName, nArg, (u8)enc, 1);
137244  assert(p || db->mallocFailed);
137245  if( !p ){
137246  return SQLITE_NOMEM_BKPT;
137247  }
137248 
137249  /* If an older version of the function with a configured destructor is
137250  ** being replaced invoke the destructor function here. */
137251  functionDestroy(db, p);
137252 
137253  if( pDestructor ){
137254  pDestructor->nRef++;
137255  }
137256  p->u.pDestructor = pDestructor;
137257  p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
137258  testcase( p->funcFlags & SQLITE_DETERMINISTIC );
137259  p->xSFunc = xSFunc ? xSFunc : xStep;
137260  p->xFinalize = xFinal;
137261  p->pUserData = pUserData;
137262  p->nArg = (u16)nArg;
137263  return SQLITE_OK;
137264 }
137265 
137266 /*
137267 ** Create new user functions.
137268 */
137270  sqlite3 *db,
137271  const char *zFunc,
137272  int nArg,
137273  int enc,
137274  void *p,
137275  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
137276  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
137277  void (*xFinal)(sqlite3_context*)
137278 ){
137279  return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xSFunc, xStep,
137280  xFinal, 0);
137281 }
137282 
137284  sqlite3 *db,
137285  const char *zFunc,
137286  int nArg,
137287  int enc,
137288  void *p,
137289  void (*xSFunc)(sqlite3_context*,int,sqlite3_value **),
137290  void (*xStep)(sqlite3_context*,int,sqlite3_value **),
137291  void (*xFinal)(sqlite3_context*),
137292  void (*xDestroy)(void *)
137293 ){
137294  int rc = SQLITE_ERROR;
137295  FuncDestructor *pArg = 0;
137296 
137297 #ifdef SQLITE_ENABLE_API_ARMOR
137298  if( !sqlite3SafetyCheckOk(db) ){
137299  return SQLITE_MISUSE_BKPT;
137300  }
137301 #endif
137302  sqlite3_mutex_enter(db->mutex);
137303  if( xDestroy ){
137304  pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
137305  if( !pArg ){
137306  xDestroy(p);
137307  goto out;
137308  }
137309  pArg->xDestroy = xDestroy;
137310  pArg->pUserData = p;
137311  }
137312  rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xSFunc, xStep, xFinal, pArg);
137313  if( pArg && pArg->nRef==0 ){
137314  assert( rc!=SQLITE_OK );
137315  xDestroy(p);
137316  sqlite3DbFree(db, pArg);
137317  }
137318 
137319  out:
137320  rc = sqlite3ApiExit(db, rc);
137321  sqlite3_mutex_leave(db->mutex);
137322  return rc;
137323 }
137324 
137325 #ifndef SQLITE_OMIT_UTF16
137327  sqlite3 *db,
137328  const void *zFunctionName,
137329  int nArg,
137330  int eTextRep,
137331  void *p,
137332  void (*xSFunc)(sqlite3_context*,int,sqlite3_value**),
137333  void (*xStep)(sqlite3_context*,int,sqlite3_value**),
137334  void (*xFinal)(sqlite3_context*)
137335 ){
137336  int rc;
137337  char *zFunc8;
137338 
137339 #ifdef SQLITE_ENABLE_API_ARMOR
137340  if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
137341 #endif
137342  sqlite3_mutex_enter(db->mutex);
137343  assert( !db->mallocFailed );
137344  zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
137345  rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xSFunc,xStep,xFinal,0);
137346  sqlite3DbFree(db, zFunc8);
137347  rc = sqlite3ApiExit(db, rc);
137348  sqlite3_mutex_leave(db->mutex);
137349  return rc;
137350 }
137351 #endif
137352 
137353 
137354 /*
137355 ** Declare that a function has been overloaded by a virtual table.
137356 **
137357 ** If the function already exists as a regular global function, then
137358 ** this routine is a no-op. If the function does not exist, then create
137359 ** a new one that always throws a run-time error.
137360 **
137361 ** When virtual tables intend to provide an overloaded function, they
137362 ** should call this routine to make sure the global function exists.
137363 ** A global function must exist in order for name resolution to work
137364 ** properly.
137365 */
137367  sqlite3 *db,
137368  const char *zName,
137369  int nArg
137370 ){
137371  int rc = SQLITE_OK;
137372 
137373 #ifdef SQLITE_ENABLE_API_ARMOR
137374  if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
137375  return SQLITE_MISUSE_BKPT;
137376  }
137377 #endif
137378  sqlite3_mutex_enter(db->mutex);
137379  if( sqlite3FindFunction(db, zName, nArg, SQLITE_UTF8, 0)==0 ){
137380  rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
137381  0, sqlite3InvalidFunction, 0, 0, 0);
137382  }
137383  rc = sqlite3ApiExit(db, rc);
137384  sqlite3_mutex_leave(db->mutex);
137385  return rc;
137386 }
137387 
137388 #ifndef SQLITE_OMIT_TRACE
137389 /*
137390 ** Register a trace function. The pArg from the previously registered trace
137391 ** is returned.
137392 **
137393 ** A NULL trace function means that no tracing is executes. A non-NULL
137394 ** trace is a pointer to a function that is invoked at the start of each
137395 ** SQL statement.
137396 */
137397 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
137398  void *pOld;
137399 
137400 #ifdef SQLITE_ENABLE_API_ARMOR
137401  if( !sqlite3SafetyCheckOk(db) ){
137403  return 0;
137404  }
137405 #endif
137406  sqlite3_mutex_enter(db->mutex);
137407  pOld = db->pTraceArg;
137408  db->xTrace = xTrace;
137409  db->pTraceArg = pArg;
137410  sqlite3_mutex_leave(db->mutex);
137411  return pOld;
137412 }
137413 /*
137414 ** Register a profile function. The pArg from the previously registered
137415 ** profile function is returned.
137416 **
137417 ** A NULL profile function means that no profiling is executes. A non-NULL
137418 ** profile is a pointer to a function that is invoked at the conclusion of
137419 ** each SQL statement that is run.
137420 */
137422  sqlite3 *db,
137423  void (*xProfile)(void*,const char*,sqlite_uint64),
137424  void *pArg
137425 ){
137426  void *pOld;
137427 
137428 #ifdef SQLITE_ENABLE_API_ARMOR
137429  if( !sqlite3SafetyCheckOk(db) ){
137431  return 0;
137432  }
137433 #endif
137434  sqlite3_mutex_enter(db->mutex);
137435  pOld = db->pProfileArg;
137436  db->xProfile = xProfile;
137437  db->pProfileArg = pArg;
137438  sqlite3_mutex_leave(db->mutex);
137439  return pOld;
137440 }
137441 #endif /* SQLITE_OMIT_TRACE */
137442 
137443 /*
137444 ** Register a function to be invoked when a transaction commits.
137445 ** If the invoked function returns non-zero, then the commit becomes a
137446 ** rollback.
137447 */
137449  sqlite3 *db, /* Attach the hook to this database */
137450  int (*xCallback)(void*), /* Function to invoke on each commit */
137451  void *pArg /* Argument to the function */
137452 ){
137453  void *pOld;
137454 
137455 #ifdef SQLITE_ENABLE_API_ARMOR
137456  if( !sqlite3SafetyCheckOk(db) ){
137458  return 0;
137459  }
137460 #endif
137461  sqlite3_mutex_enter(db->mutex);
137462  pOld = db->pCommitArg;
137463  db->xCommitCallback = xCallback;
137464  db->pCommitArg = pArg;
137465  sqlite3_mutex_leave(db->mutex);
137466  return pOld;
137467 }
137468 
137469 /*
137470 ** Register a callback to be invoked each time a row is updated,
137471 ** inserted or deleted using this database connection.
137472 */
137474  sqlite3 *db, /* Attach the hook to this database */
137475  void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
137476  void *pArg /* Argument to the function */
137477 ){
137478  void *pRet;
137479 
137480 #ifdef SQLITE_ENABLE_API_ARMOR
137481  if( !sqlite3SafetyCheckOk(db) ){
137483  return 0;
137484  }
137485 #endif
137486  sqlite3_mutex_enter(db->mutex);
137487  pRet = db->pUpdateArg;
137488  db->xUpdateCallback = xCallback;
137489  db->pUpdateArg = pArg;
137490  sqlite3_mutex_leave(db->mutex);
137491  return pRet;
137492 }
137493 
137494 /*
137495 ** Register a callback to be invoked each time a transaction is rolled
137496 ** back by this database connection.
137497 */
137499  sqlite3 *db, /* Attach the hook to this database */
137500  void (*xCallback)(void*), /* Callback function */
137501  void *pArg /* Argument to the function */
137502 ){
137503  void *pRet;
137504 
137505 #ifdef SQLITE_ENABLE_API_ARMOR
137506  if( !sqlite3SafetyCheckOk(db) ){
137508  return 0;
137509  }
137510 #endif
137511  sqlite3_mutex_enter(db->mutex);
137512  pRet = db->pRollbackArg;
137513  db->xRollbackCallback = xCallback;
137514  db->pRollbackArg = pArg;
137515  sqlite3_mutex_leave(db->mutex);
137516  return pRet;
137517 }
137518 
137519 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
137520 /*
137521 ** Register a callback to be invoked each time a row is updated,
137522 ** inserted or deleted using this database connection.
137523 */
137525  sqlite3 *db, /* Attach the hook to this database */
137526  void(*xCallback)( /* Callback function */
137527  void*,sqlite3*,int,char const*,char const*,sqlite3_int64,sqlite3_int64),
137528  void *pArg /* First callback argument */
137529 ){
137530  void *pRet;
137531  sqlite3_mutex_enter(db->mutex);
137532  pRet = db->pPreUpdateArg;
137533  db->xPreUpdateCallback = xCallback;
137534  db->pPreUpdateArg = pArg;
137535  sqlite3_mutex_leave(db->mutex);
137536  return pRet;
137537 }
137538 #endif /* SQLITE_ENABLE_PREUPDATE_HOOK */
137539 
137540 #ifndef SQLITE_OMIT_WAL
137541 /*
137542 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
137543 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
137544 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
137545 ** wal_autocheckpoint()).
137546 */
137548  void *pClientData, /* Argument */
137549  sqlite3 *db, /* Connection */
137550  const char *zDb, /* Database */
137551  int nFrame /* Size of WAL */
137552 ){
137553  if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
137555  sqlite3_wal_checkpoint(db, zDb);
137557  }
137558  return SQLITE_OK;
137559 }
137560 #endif /* SQLITE_OMIT_WAL */
137561 
137562 /*
137563 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
137564 ** a database after committing a transaction if there are nFrame or
137565 ** more frames in the log file. Passing zero or a negative value as the
137566 ** nFrame parameter disables automatic checkpoints entirely.
137567 **
137568 ** The callback registered by this function replaces any existing callback
137569 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
137570 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
137571 ** configured by this function.
137572 */
137574 #ifdef SQLITE_OMIT_WAL
137575  UNUSED_PARAMETER(db);
137576  UNUSED_PARAMETER(nFrame);
137577 #else
137578 #ifdef SQLITE_ENABLE_API_ARMOR
137579  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137580 #endif
137581  if( nFrame>0 ){
137583  }else{
137584  sqlite3_wal_hook(db, 0, 0);
137585  }
137586 #endif
137587  return SQLITE_OK;
137588 }
137589 
137590 /*
137591 ** Register a callback to be invoked each time a transaction is written
137592 ** into the write-ahead-log by this database connection.
137593 */
137595  sqlite3 *db, /* Attach the hook to this db handle */
137596  int(*xCallback)(void *, sqlite3*, const char*, int),
137597  void *pArg /* First argument passed to xCallback() */
137598 ){
137599 #ifndef SQLITE_OMIT_WAL
137600  void *pRet;
137601 #ifdef SQLITE_ENABLE_API_ARMOR
137602  if( !sqlite3SafetyCheckOk(db) ){
137604  return 0;
137605  }
137606 #endif
137607  sqlite3_mutex_enter(db->mutex);
137608  pRet = db->pWalArg;
137609  db->xWalCallback = xCallback;
137610  db->pWalArg = pArg;
137611  sqlite3_mutex_leave(db->mutex);
137612  return pRet;
137613 #else
137614  return 0;
137615 #endif
137616 }
137617 
137618 /*
137619 ** Checkpoint database zDb.
137620 */
137622  sqlite3 *db, /* Database handle */
137623  const char *zDb, /* Name of attached database (or NULL) */
137624  int eMode, /* SQLITE_CHECKPOINT_* value */
137625  int *pnLog, /* OUT: Size of WAL log in frames */
137626  int *pnCkpt /* OUT: Total number of frames checkpointed */
137627 ){
137628 #ifdef SQLITE_OMIT_WAL
137629  return SQLITE_OK;
137630 #else
137631  int rc; /* Return code */
137632  int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
137633 
137634 #ifdef SQLITE_ENABLE_API_ARMOR
137635  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
137636 #endif
137637 
137638  /* Initialize the output variables to -1 in case an error occurs. */
137639  if( pnLog ) *pnLog = -1;
137640  if( pnCkpt ) *pnCkpt = -1;
137641 
137646  if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
137647  /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
137648  ** mode: */
137649  return SQLITE_MISUSE;
137650  }
137651 
137652  sqlite3_mutex_enter(db->mutex);
137653  if( zDb && zDb[0] ){
137654  iDb = sqlite3FindDbName(db, zDb);
137655  }
137656  if( iDb<0 ){
137657  rc = SQLITE_ERROR;
137658  sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
137659  }else{
137660  db->busyHandler.nBusy = 0;
137661  rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
137662  sqlite3Error(db, rc);
137663  }
137664  rc = sqlite3ApiExit(db, rc);
137665  sqlite3_mutex_leave(db->mutex);
137666  return rc;
137667 #endif
137668 }
137669 
137670 
137671 /*
137672 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
137673 ** to contains a zero-length string, all attached databases are
137674 ** checkpointed.
137675 */
137676 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
137677  /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
137678  ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
137680 }
137681 
137682 #ifndef SQLITE_OMIT_WAL
137683 /*
137684 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
137685 ** not currently open in WAL mode.
137686 **
137687 ** If a transaction is open on the database being checkpointed, this
137688 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
137689 ** an error occurs while running the checkpoint, an SQLite error code is
137690 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
137691 **
137692 ** The mutex on database handle db should be held by the caller. The mutex
137693 ** associated with the specific b-tree being checkpointed is taken by
137694 ** this function while the checkpoint is running.
137695 **
137696 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
137697 ** checkpointed. If an error is encountered it is returned immediately -
137698 ** no attempt is made to checkpoint any remaining databases.
137699 **
137700 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
137701 */
137702 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
137703  int rc = SQLITE_OK; /* Return code */
137704  int i; /* Used to iterate through attached dbs */
137705  int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
137706 
137707  assert( sqlite3_mutex_held(db->mutex) );
137708  assert( !pnLog || *pnLog==-1 );
137709  assert( !pnCkpt || *pnCkpt==-1 );
137710 
137711  for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
137712  if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
137713  rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
137714  pnLog = 0;
137715  pnCkpt = 0;
137716  if( rc==SQLITE_BUSY ){
137717  bBusy = 1;
137718  rc = SQLITE_OK;
137719  }
137720  }
137721  }
137722 
137723  return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
137724 }
137725 #endif /* SQLITE_OMIT_WAL */
137726 
137727 /*
137728 ** This function returns true if main-memory should be used instead of
137729 ** a temporary file for transient pager files and statement journals.
137730 ** The value returned depends on the value of db->temp_store (runtime
137731 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
137732 ** following table describes the relationship between these two values
137733 ** and this functions return value.
137734 **
137735 ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
137736 ** ----------------- -------------- ------------------------------
137737 ** 0 any file (return 0)
137738 ** 1 1 file (return 0)
137739 ** 1 2 memory (return 1)
137740 ** 1 0 file (return 0)
137741 ** 2 1 file (return 0)
137742 ** 2 2 memory (return 1)
137743 ** 2 0 memory (return 1)
137744 ** 3 any memory (return 1)
137745 */
137746 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
137747 #if SQLITE_TEMP_STORE==1
137748  return ( db->temp_store==2 );
137749 #endif
137750 #if SQLITE_TEMP_STORE==2
137751  return ( db->temp_store!=1 );
137752 #endif
137753 #if SQLITE_TEMP_STORE==3
137754  UNUSED_PARAMETER(db);
137755  return 1;
137756 #endif
137757 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
137758  UNUSED_PARAMETER(db);
137759  return 0;
137760 #endif
137761 }
137762 
137763 /*
137764 ** Return UTF-8 encoded English language explanation of the most recent
137765 ** error.
137766 */
137767 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
137768  const char *z;
137769  if( !db ){
137771  }
137772  if( !sqlite3SafetyCheckSickOrOk(db) ){
137774  }
137775  sqlite3_mutex_enter(db->mutex);
137776  if( db->mallocFailed ){
137778  }else{
137779  testcase( db->pErr==0 );
137780  z = (char*)sqlite3_value_text(db->pErr);
137781  assert( !db->mallocFailed );
137782  if( z==0 ){
137783  z = sqlite3ErrStr(db->errCode);
137784  }
137785  }
137786  sqlite3_mutex_leave(db->mutex);
137787  return z;
137788 }
137789 
137790 #ifndef SQLITE_OMIT_UTF16
137791 /*
137792 ** Return UTF-16 encoded English language explanation of the most recent
137793 ** error.
137794 */
137796  static const u16 outOfMem[] = {
137797  'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
137798  };
137799  static const u16 misuse[] = {
137800  'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
137801  'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
137802  'c', 'a', 'l', 'l', 'e', 'd', ' ',
137803  'o', 'u', 't', ' ',
137804  'o', 'f', ' ',
137805  's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
137806  };
137807 
137808  const void *z;
137809  if( !db ){
137810  return (void *)outOfMem;
137811  }
137812  if( !sqlite3SafetyCheckSickOrOk(db) ){
137813  return (void *)misuse;
137814  }
137815  sqlite3_mutex_enter(db->mutex);
137816  if( db->mallocFailed ){
137817  z = (void *)outOfMem;
137818  }else{
137819  z = sqlite3_value_text16(db->pErr);
137820  if( z==0 ){
137822  z = sqlite3_value_text16(db->pErr);
137823  }
137824  /* A malloc() may have failed within the call to sqlite3_value_text16()
137825  ** above. If this is the case, then the db->mallocFailed flag needs to
137826  ** be cleared before returning. Do this directly, instead of via
137827  ** sqlite3ApiExit(), to avoid setting the database handle error message.
137828  */
137829  sqlite3OomClear(db);
137830  }
137831  sqlite3_mutex_leave(db->mutex);
137832  return z;
137833 }
137834 #endif /* SQLITE_OMIT_UTF16 */
137835 
137836 /*
137837 ** Return the most recent error code generated by an SQLite routine. If NULL is
137838 ** passed to this function, we assume a malloc() failed during sqlite3_open().
137839 */
137841  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
137842  return SQLITE_MISUSE_BKPT;
137843  }
137844  if( !db || db->mallocFailed ){
137845  return SQLITE_NOMEM_BKPT;
137846  }
137847  return db->errCode & db->errMask;
137848 }
137850  if( db && !sqlite3SafetyCheckSickOrOk(db) ){
137851  return SQLITE_MISUSE_BKPT;
137852  }
137853  if( !db || db->mallocFailed ){
137854  return SQLITE_NOMEM_BKPT;
137855  }
137856  return db->errCode;
137857 }
137859  return db ? db->iSysErrno : 0;
137860 }
137861 
137862 /*
137863 ** Return a string that describes the kind of error specified in the
137864 ** argument. For now, this simply calls the internal sqlite3ErrStr()
137865 ** function.
137866 */
137868  return sqlite3ErrStr(rc);
137869 }
137870 
137871 /*
137872 ** Create a new collating function for database "db". The name is zName
137873 ** and the encoding is enc.
137874 */
137875 static int createCollation(
137876  sqlite3* db,
137877  const char *zName,
137878  u8 enc,
137879  void* pCtx,
137880  int(*xCompare)(void*,int,const void*,int,const void*),
137881  void(*xDel)(void*)
137882 ){
137883  CollSeq *pColl;
137884  int enc2;
137885 
137886  assert( sqlite3_mutex_held(db->mutex) );
137887 
137888  /* If SQLITE_UTF16 is specified as the encoding type, transform this
137889  ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
137890  ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
137891  */
137892  enc2 = enc;
137893  testcase( enc2==SQLITE_UTF16 );
137894  testcase( enc2==SQLITE_UTF16_ALIGNED );
137895  if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
137896  enc2 = SQLITE_UTF16NATIVE;
137897  }
137898  if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
137899  return SQLITE_MISUSE_BKPT;
137900  }
137901 
137902  /* Check if this call is removing or replacing an existing collation
137903  ** sequence. If so, and there are active VMs, return busy. If there
137904  ** are no active VMs, invalidate any pre-compiled statements.
137905  */
137906  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
137907  if( pColl && pColl->xCmp ){
137908  if( db->nVdbeActive ){
137910  "unable to delete/modify collation sequence due to active statements");
137911  return SQLITE_BUSY;
137912  }
137914 
137915  /* If collation sequence pColl was created directly by a call to
137916  ** sqlite3_create_collation, and not generated by synthCollSeq(),
137917  ** then any copies made by synthCollSeq() need to be invalidated.
137918  ** Also, collation destructor - CollSeq.xDel() - function may need
137919  ** to be called.
137920  */
137921  if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
137922  CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
137923  int j;
137924  for(j=0; j<3; j++){
137925  CollSeq *p = &aColl[j];
137926  if( p->enc==pColl->enc ){
137927  if( p->xDel ){
137928  p->xDel(p->pUser);
137929  }
137930  p->xCmp = 0;
137931  }
137932  }
137933  }
137934  }
137935 
137936  pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
137937  if( pColl==0 ) return SQLITE_NOMEM_BKPT;
137938  pColl->xCmp = xCompare;
137939  pColl->pUser = pCtx;
137940  pColl->xDel = xDel;
137941  pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
137942  sqlite3Error(db, SQLITE_OK);
137943  return SQLITE_OK;
137944 }
137945 
137946 
137947 /*
137948 ** This array defines hard upper bounds on limit values. The
137949 ** initializer must be kept in sync with the SQLITE_LIMIT_*
137950 ** #defines in sqlite3.h.
137951 */
137952 static const int aHardLimit[] = {
137962  SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
137965 };
137966 
137967 /*
137968 ** Make sure the hard limits are set to reasonable values
137969 */
137970 #if SQLITE_MAX_LENGTH<100
137971 # error SQLITE_MAX_LENGTH must be at least 100
137972 #endif
137973 #if SQLITE_MAX_SQL_LENGTH<100
137974 # error SQLITE_MAX_SQL_LENGTH must be at least 100
137975 #endif
137976 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
137977 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
137978 #endif
137979 #if SQLITE_MAX_COMPOUND_SELECT<2
137980 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
137981 #endif
137982 #if SQLITE_MAX_VDBE_OP<40
137983 # error SQLITE_MAX_VDBE_OP must be at least 40
137984 #endif
137985 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>127
137986 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 127
137987 #endif
137988 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
137989 # error SQLITE_MAX_ATTACHED must be between 0 and 125
137990 #endif
137991 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
137992 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
137993 #endif
137994 #if SQLITE_MAX_COLUMN>32767
137995 # error SQLITE_MAX_COLUMN must not exceed 32767
137996 #endif
137997 #if SQLITE_MAX_TRIGGER_DEPTH<1
137998 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
137999 #endif
138000 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
138001 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
138002 #endif
138003 
138004 
138005 /*
138006 ** Change the value of a limit. Report the old value.
138007 ** If an invalid limit index is supplied, report -1.
138008 ** Make no changes but still report the old value if the
138009 ** new limit is negative.
138010 **
138011 ** A new lower limit does not shrink existing constructs.
138012 ** It merely prevents new constructs that exceed the limit
138013 ** from forming.
138014 */
138015 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
138016  int oldLimit;
138017 
138018 #ifdef SQLITE_ENABLE_API_ARMOR
138019  if( !sqlite3SafetyCheckOk(db) ){
138021  return -1;
138022  }
138023 #endif
138024 
138025  /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
138026  ** there is a hard upper bound set at compile-time by a C preprocessor
138027  ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
138028  ** "_MAX_".)
138029  */
138030  assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
138032  assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
138044 
138045 
138046  if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
138047  return -1;
138048  }
138049  oldLimit = db->aLimit[limitId];
138050  if( newLimit>=0 ){ /* IMP: R-52476-28732 */
138051  if( newLimit>aHardLimit[limitId] ){
138052  newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
138053  }
138054  db->aLimit[limitId] = newLimit;
138055  }
138056  return oldLimit; /* IMP: R-53341-35419 */
138057 }
138058 
138059 /*
138060 ** This function is used to parse both URIs and non-URI filenames passed by the
138061 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
138062 ** URIs specified as part of ATTACH statements.
138063 **
138064 ** The first argument to this function is the name of the VFS to use (or
138065 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
138066 ** query parameter. The second argument contains the URI (or non-URI filename)
138067 ** itself. When this function is called the *pFlags variable should contain
138068 ** the default flags to open the database handle with. The value stored in
138069 ** *pFlags may be updated before returning if the URI filename contains
138070 ** "cache=xxx" or "mode=xxx" query parameters.
138071 **
138072 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
138073 ** the VFS that should be used to open the database file. *pzFile is set to
138074 ** point to a buffer containing the name of the file to open. It is the
138075 ** responsibility of the caller to eventually call sqlite3_free() to release
138076 ** this buffer.
138077 **
138078 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
138079 ** may be set to point to a buffer containing an English language error
138080 ** message. It is the responsibility of the caller to eventually release
138081 ** this buffer by calling sqlite3_free().
138082 */
138084  const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
138085  const char *zUri, /* Nul-terminated URI to parse */
138086  unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
138087  sqlite3_vfs **ppVfs, /* OUT: VFS to use */
138088  char **pzFile, /* OUT: Filename component of URI */
138089  char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
138090 ){
138091  int rc = SQLITE_OK;
138092  unsigned int flags = *pFlags;
138093  const char *zVfs = zDefaultVfs;
138094  char *zFile;
138095  char c;
138096  int nUri = sqlite3Strlen30(zUri);
138097 
138098  assert( *pzErrMsg==0 );
138099 
138100  if( ((flags & SQLITE_OPEN_URI) /* IMP: R-48725-32206 */
138101  || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
138102  && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
138103  ){
138104  char *zOpt;
138105  int eState; /* Parser state when parsing URI */
138106  int iIn; /* Input character index */
138107  int iOut = 0; /* Output character index */
138108  u64 nByte = nUri+2; /* Bytes of space to allocate */
138109 
138110  /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
138111  ** method that there may be extra parameters following the file-name. */
138112  flags |= SQLITE_OPEN_URI;
138113 
138114  for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
138115  zFile = sqlite3_malloc64(nByte);
138116  if( !zFile ) return SQLITE_NOMEM_BKPT;
138117 
138118  iIn = 5;
138119 #ifdef SQLITE_ALLOW_URI_AUTHORITY
138120  if( strncmp(zUri+5, "///", 3)==0 ){
138121  iIn = 7;
138122  /* The following condition causes URIs with five leading / characters
138123  ** like file://///host/path to be converted into UNCs like //host/path.
138124  ** The correct URI for that UNC has only two or four leading / characters
138125  ** file://host/path or file:////host/path. But 5 leading slashes is a
138126  ** common error, we are told, so we handle it as a special case. */
138127  if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
138128  }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
138129  iIn = 16;
138130  }
138131 #else
138132  /* Discard the scheme and authority segments of the URI. */
138133  if( zUri[5]=='/' && zUri[6]=='/' ){
138134  iIn = 7;
138135  while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
138136  if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
138137  *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
138138  iIn-7, &zUri[7]);
138139  rc = SQLITE_ERROR;
138140  goto parse_uri_out;
138141  }
138142  }
138143 #endif
138144 
138145  /* Copy the filename and any query parameters into the zFile buffer.
138146  ** Decode %HH escape codes along the way.
138147  **
138148  ** Within this loop, variable eState may be set to 0, 1 or 2, depending
138149  ** on the parsing context. As follows:
138150  **
138151  ** 0: Parsing file-name.
138152  ** 1: Parsing name section of a name=value query parameter.
138153  ** 2: Parsing value section of a name=value query parameter.
138154  */
138155  eState = 0;
138156  while( (c = zUri[iIn])!=0 && c!='#' ){
138157  iIn++;
138158  if( c=='%'
138159  && sqlite3Isxdigit(zUri[iIn])
138160  && sqlite3Isxdigit(zUri[iIn+1])
138161  ){
138162  int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
138163  octet += sqlite3HexToInt(zUri[iIn++]);
138164 
138165  assert( octet>=0 && octet<256 );
138166  if( octet==0 ){
138167  /* This branch is taken when "%00" appears within the URI. In this
138168  ** case we ignore all text in the remainder of the path, name or
138169  ** value currently being parsed. So ignore the current character
138170  ** and skip to the next "?", "=" or "&", as appropriate. */
138171  while( (c = zUri[iIn])!=0 && c!='#'
138172  && (eState!=0 || c!='?')
138173  && (eState!=1 || (c!='=' && c!='&'))
138174  && (eState!=2 || c!='&')
138175  ){
138176  iIn++;
138177  }
138178  continue;
138179  }
138180  c = octet;
138181  }else if( eState==1 && (c=='&' || c=='=') ){
138182  if( zFile[iOut-1]==0 ){
138183  /* An empty option name. Ignore this option altogether. */
138184  while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
138185  continue;
138186  }
138187  if( c=='&' ){
138188  zFile[iOut++] = '\0';
138189  }else{
138190  eState = 2;
138191  }
138192  c = 0;
138193  }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
138194  c = 0;
138195  eState = 1;
138196  }
138197  zFile[iOut++] = c;
138198  }
138199  if( eState==1 ) zFile[iOut++] = '\0';
138200  zFile[iOut++] = '\0';
138201  zFile[iOut++] = '\0';
138202 
138203  /* Check if there were any options specified that should be interpreted
138204  ** here. Options that are interpreted here include "vfs" and those that
138205  ** correspond to flags that may be passed to the sqlite3_open_v2()
138206  ** method. */
138207  zOpt = &zFile[sqlite3Strlen30(zFile)+1];
138208  while( zOpt[0] ){
138209  int nOpt = sqlite3Strlen30(zOpt);
138210  char *zVal = &zOpt[nOpt+1];
138211  int nVal = sqlite3Strlen30(zVal);
138212 
138213  if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
138214  zVfs = zVal;
138215  }else{
138216  struct OpenMode {
138217  const char *z;
138218  int mode;
138219  } *aMode = 0;
138220  char *zModeType = 0;
138221  int mask = 0;
138222  int limit = 0;
138223 
138224  if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
138225  static struct OpenMode aCacheMode[] = {
138226  { "shared", SQLITE_OPEN_SHAREDCACHE },
138227  { "private", SQLITE_OPEN_PRIVATECACHE },
138228  { 0, 0 }
138229  };
138230 
138232  aMode = aCacheMode;
138233  limit = mask;
138234  zModeType = "cache";
138235  }
138236  if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
138237  static struct OpenMode aOpenMode[] = {
138238  { "ro", SQLITE_OPEN_READONLY },
138239  { "rw", SQLITE_OPEN_READWRITE },
138241  { "memory", SQLITE_OPEN_MEMORY },
138242  { 0, 0 }
138243  };
138244 
138247  aMode = aOpenMode;
138248  limit = mask & flags;
138249  zModeType = "access";
138250  }
138251 
138252  if( aMode ){
138253  int i;
138254  int mode = 0;
138255  for(i=0; aMode[i].z; i++){
138256  const char *z = aMode[i].z;
138257  if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
138258  mode = aMode[i].mode;
138259  break;
138260  }
138261  }
138262  if( mode==0 ){
138263  *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
138264  rc = SQLITE_ERROR;
138265  goto parse_uri_out;
138266  }
138267  if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
138268  *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
138269  zModeType, zVal);
138270  rc = SQLITE_PERM;
138271  goto parse_uri_out;
138272  }
138273  flags = (flags & ~mask) | mode;
138274  }
138275  }
138276 
138277  zOpt = &zVal[nVal+1];
138278  }
138279 
138280  }else{
138281  zFile = sqlite3_malloc64(nUri+2);
138282  if( !zFile ) return SQLITE_NOMEM_BKPT;
138283  memcpy(zFile, zUri, nUri);
138284  zFile[nUri] = '\0';
138285  zFile[nUri+1] = '\0';
138286  flags &= ~SQLITE_OPEN_URI;
138287  }
138288 
138289  *ppVfs = sqlite3_vfs_find(zVfs);
138290  if( *ppVfs==0 ){
138291  *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
138292  rc = SQLITE_ERROR;
138293  }
138294  parse_uri_out:
138295  if( rc!=SQLITE_OK ){
138296  sqlite3_free(zFile);
138297  zFile = 0;
138298  }
138299  *pFlags = flags;
138300  *pzFile = zFile;
138301  return rc;
138302 }
138303 
138304 
138305 /*
138306 ** This routine does the work of opening a database on behalf of
138307 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
138308 ** is UTF-8 encoded.
138309 */
138310 static int openDatabase(
138311  const char *zFilename, /* Database filename UTF-8 encoded */
138312  sqlite3 **ppDb, /* OUT: Returned database handle */
138313  unsigned int flags, /* Operational flags */
138314  const char *zVfs /* Name of the VFS to use */
138315 ){
138316  sqlite3 *db; /* Store allocated handle here */
138317  int rc; /* Return code */
138318  int isThreadsafe; /* True for threadsafe connections */
138319  char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
138320  char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
138321 
138322 #ifdef SQLITE_ENABLE_API_ARMOR
138323  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
138324 #endif
138325  *ppDb = 0;
138326 #ifndef SQLITE_OMIT_AUTOINIT
138327  rc = sqlite3_initialize();
138328  if( rc ) return rc;
138329 #endif
138330 
138331  /* Only allow sensible combinations of bits in the flags argument.
138332  ** Throw an error if any non-sense combination is used. If we
138333  ** do not block illegal combinations here, it could trigger
138334  ** assert() statements in deeper layers. Sensible combinations
138335  ** are:
138336  **
138337  ** 1: SQLITE_OPEN_READONLY
138338  ** 2: SQLITE_OPEN_READWRITE
138339  ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
138340  */
138341  assert( SQLITE_OPEN_READONLY == 0x01 );
138342  assert( SQLITE_OPEN_READWRITE == 0x02 );
138343  assert( SQLITE_OPEN_CREATE == 0x04 );
138344  testcase( (1<<(flags&7))==0x02 ); /* READONLY */
138345  testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
138346  testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
138347  if( ((1<<(flags&7)) & 0x46)==0 ){
138348  return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
138349  }
138350 
138351  if( sqlite3GlobalConfig.bCoreMutex==0 ){
138352  isThreadsafe = 0;
138353  }else if( flags & SQLITE_OPEN_NOMUTEX ){
138354  isThreadsafe = 0;
138355  }else if( flags & SQLITE_OPEN_FULLMUTEX ){
138356  isThreadsafe = 1;
138357  }else{
138358  isThreadsafe = sqlite3GlobalConfig.bFullMutex;
138359  }
138360  if( flags & SQLITE_OPEN_PRIVATECACHE ){
138361  flags &= ~SQLITE_OPEN_SHAREDCACHE;
138362  }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
138363  flags |= SQLITE_OPEN_SHAREDCACHE;
138364  }
138365 
138366  /* Remove harmful bits from the flags parameter
138367  **
138368  ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
138369  ** dealt with in the previous code block. Besides these, the only
138370  ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
138371  ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
138372  ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
138373  ** off all other flags.
138374  */
138375  flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
138384  SQLITE_OPEN_NOMUTEX |
138385  SQLITE_OPEN_FULLMUTEX |
138387  );
138388 
138389  /* Allocate the sqlite data structure */
138390  db = sqlite3MallocZero( sizeof(sqlite3) );
138391  if( db==0 ) goto opendb_out;
138392  if( isThreadsafe ){
138394  if( db->mutex==0 ){
138395  sqlite3_free(db);
138396  db = 0;
138397  goto opendb_out;
138398  }
138399  }
138400  sqlite3_mutex_enter(db->mutex);
138401  db->errMask = 0xff;
138402  db->nDb = 2;
138403  db->magic = SQLITE_MAGIC_BUSY;
138404  db->aDb = db->aDbStatic;
138405 
138406  assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
138407  memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
138409  db->autoCommit = 1;
138410  db->nextAutovac = -1;
138411  db->szMmap = sqlite3GlobalConfig.szMmap;
138412  db->nextPagesize = 0;
138413  db->nMaxSorterMmap = 0x7FFFFFFF;
138415 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
138416  | SQLITE_AutoIndex
138417 #endif
138418 #if SQLITE_DEFAULT_CKPTFULLFSYNC
138420 #endif
138421 #if SQLITE_DEFAULT_FILE_FORMAT<4
138423 #endif
138424 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
138426 #endif
138427 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
138429 #endif
138430 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
138432 #endif
138433 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
138435 #endif
138436 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
138438 #endif
138439 #if defined(SQLITE_ENABLE_FTS3_TOKENIZER)
138441 #endif
138442  ;
138443  sqlite3HashInit(&db->aCollSeq);
138444 #ifndef SQLITE_OMIT_VIRTUALTABLE
138445  sqlite3HashInit(&db->aModule);
138446 #endif
138447 
138448  /* Add the default collation sequence BINARY. BINARY works for both UTF-8
138449  ** and UTF-16, so add a version for each to avoid any unnecessary
138450  ** conversions. The only error that can occur here is a malloc() failure.
138451  **
138452  ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
138453  ** functions:
138454  */
138455  createCollation(db, sqlite3StrBINARY, SQLITE_UTF8, 0, binCollFunc, 0);
138456  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16BE, 0, binCollFunc, 0);
138457  createCollation(db, sqlite3StrBINARY, SQLITE_UTF16LE, 0, binCollFunc, 0);
138458  createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
138459  createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
138460  if( db->mallocFailed ){
138461  goto opendb_out;
138462  }
138463  /* EVIDENCE-OF: R-08308-17224 The default collating function for all
138464  ** strings is BINARY.
138465  */
138466  db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, sqlite3StrBINARY, 0);
138467  assert( db->pDfltColl!=0 );
138468 
138469  /* Parse the filename/URI argument. */
138470  db->openFlags = flags;
138471  rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
138472  if( rc!=SQLITE_OK ){
138473  if( rc==SQLITE_NOMEM ) sqlite3OomFault(db);
138474  sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
138475  sqlite3_free(zErrMsg);
138476  goto opendb_out;
138477  }
138478 
138479  /* Open the backend database driver */
138480  rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
138481  flags | SQLITE_OPEN_MAIN_DB);
138482  if( rc!=SQLITE_OK ){
138483  if( rc==SQLITE_IOERR_NOMEM ){
138484  rc = SQLITE_NOMEM_BKPT;
138485  }
138486  sqlite3Error(db, rc);
138487  goto opendb_out;
138488  }
138489  sqlite3BtreeEnter(db->aDb[0].pBt);
138490  db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
138491  if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
138492  sqlite3BtreeLeave(db->aDb[0].pBt);
138493  db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
138494 
138495  /* The default safety_level for the main database is FULL; for the temp
138496  ** database it is OFF. This matches the pager layer defaults.
138497  */
138498  db->aDb[0].zName = "main";
138500  db->aDb[1].zName = "temp";
138502 
138503  db->magic = SQLITE_MAGIC_OPEN;
138504  if( db->mallocFailed ){
138505  goto opendb_out;
138506  }
138507 
138508  /* Register all built-in functions, but do not attempt to read the
138509  ** database schema yet. This is delayed until the first time the database
138510  ** is accessed.
138511  */
138512  sqlite3Error(db, SQLITE_OK);
138514 
138515  /* Load automatic extensions - extensions that have been registered
138516  ** using the sqlite3_automatic_extension() API.
138517  */
138518  rc = sqlite3_errcode(db);
138519  if( rc==SQLITE_OK ){
138521  rc = sqlite3_errcode(db);
138522  if( rc!=SQLITE_OK ){
138523  goto opendb_out;
138524  }
138525  }
138526 
138527 #ifdef SQLITE_ENABLE_FTS1
138528  if( !db->mallocFailed ){
138529  extern int sqlite3Fts1Init(sqlite3*);
138530  rc = sqlite3Fts1Init(db);
138531  }
138532 #endif
138533 
138534 #ifdef SQLITE_ENABLE_FTS2
138535  if( !db->mallocFailed && rc==SQLITE_OK ){
138536  extern int sqlite3Fts2Init(sqlite3*);
138537  rc = sqlite3Fts2Init(db);
138538  }
138539 #endif
138540 
138541 #ifdef SQLITE_ENABLE_FTS3 /* automatically defined by SQLITE_ENABLE_FTS4 */
138542  if( !db->mallocFailed && rc==SQLITE_OK ){
138543  rc = sqlite3Fts3Init(db);
138544  }
138545 #endif
138546 
138547 #ifdef SQLITE_ENABLE_FTS5
138548  if( !db->mallocFailed && rc==SQLITE_OK ){
138549  rc = sqlite3Fts5Init(db);
138550  }
138551 #endif
138552 
138553 #ifdef SQLITE_ENABLE_ICU
138554  if( !db->mallocFailed && rc==SQLITE_OK ){
138555  rc = sqlite3IcuInit(db);
138556  }
138557 #endif
138558 
138559 #ifdef SQLITE_ENABLE_RTREE
138560  if( !db->mallocFailed && rc==SQLITE_OK){
138561  rc = sqlite3RtreeInit(db);
138562  }
138563 #endif
138564 
138565 #ifdef SQLITE_ENABLE_DBSTAT_VTAB
138566  if( !db->mallocFailed && rc==SQLITE_OK){
138567  rc = sqlite3DbstatRegister(db);
138568  }
138569 #endif
138570 
138571 #ifdef SQLITE_ENABLE_JSON1
138572  if( !db->mallocFailed && rc==SQLITE_OK){
138573  rc = sqlite3Json1Init(db);
138574  }
138575 #endif
138576 
138577  /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
138578  ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
138579  ** mode. Doing nothing at all also makes NORMAL the default.
138580  */
138581 #ifdef SQLITE_DEFAULT_LOCKING_MODE
138582  db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
138584  SQLITE_DEFAULT_LOCKING_MODE);
138585 #endif
138586 
138587  if( rc ) sqlite3Error(db, rc);
138588 
138589  /* Enable the lookaside-malloc subsystem */
138590  setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
138591  sqlite3GlobalConfig.nLookaside);
138592 
138594 
138595 opendb_out:
138596  if( db ){
138597  assert( db->mutex!=0 || isThreadsafe==0
138598  || sqlite3GlobalConfig.bFullMutex==0 );
138599  sqlite3_mutex_leave(db->mutex);
138600  }
138601  rc = sqlite3_errcode(db);
138602  assert( db!=0 || rc==SQLITE_NOMEM );
138603  if( rc==SQLITE_NOMEM ){
138604  sqlite3_close(db);
138605  db = 0;
138606  }else if( rc!=SQLITE_OK ){
138607  db->magic = SQLITE_MAGIC_SICK;
138608  }
138609  *ppDb = db;
138610 #ifdef SQLITE_ENABLE_SQLLOG
138611  if( sqlite3GlobalConfig.xSqllog ){
138612  /* Opening a db handle. Fourth parameter is passed 0. */
138613  void *pArg = sqlite3GlobalConfig.pSqllogArg;
138614  sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
138615  }
138616 #endif
138617 #if defined(SQLITE_HAS_CODEC)
138618  if( rc==SQLITE_OK ){
138619  const char *zHexKey = sqlite3_uri_parameter(zOpen, "hexkey");
138620  if( zHexKey && zHexKey[0] ){
138621  u8 iByte;
138622  int i;
138623  char zKey[40];
138624  for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zHexKey[i]); i++){
138625  iByte = (iByte<<4) + sqlite3HexToInt(zHexKey[i]);
138626  if( (i&1)!=0 ) zKey[i/2] = iByte;
138627  }
138628  sqlite3_key_v2(db, 0, zKey, i/2);
138629  }
138630  }
138631 #endif
138632  sqlite3_free(zOpen);
138633  return rc & 0xff;
138634 }
138635 
138636 /*
138637 ** Open a new database handle.
138638 */
138640  const char *zFilename,
138641  sqlite3 **ppDb
138642 ){
138643  return openDatabase(zFilename, ppDb,
138645 }
138647  const char *filename, /* Database filename (UTF-8) */
138648  sqlite3 **ppDb, /* OUT: SQLite db handle */
138649  int flags, /* Flags */
138650  const char *zVfs /* Name of VFS module to use */
138651 ){
138652  return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
138653 }
138654 
138655 #ifndef SQLITE_OMIT_UTF16
138656 /*
138657 ** Open a new database handle.
138658 */
138660  const void *zFilename,
138661  sqlite3 **ppDb
138662 ){
138663  char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
138664  sqlite3_value *pVal;
138665  int rc;
138666 
138667 #ifdef SQLITE_ENABLE_API_ARMOR
138668  if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
138669 #endif
138670  *ppDb = 0;
138671 #ifndef SQLITE_OMIT_AUTOINIT
138672  rc = sqlite3_initialize();
138673  if( rc ) return rc;
138674 #endif
138675  if( zFilename==0 ) zFilename = "\000\000";
138676  pVal = sqlite3ValueNew(0);
138677  sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
138678  zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
138679  if( zFilename8 ){
138680  rc = openDatabase(zFilename8, ppDb,
138682  assert( *ppDb || rc==SQLITE_NOMEM );
138683  if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
138684  SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
138685  }
138686  }else{
138687  rc = SQLITE_NOMEM_BKPT;
138688  }
138689  sqlite3ValueFree(pVal);
138690 
138691  return rc & 0xff;
138692 }
138693 #endif /* SQLITE_OMIT_UTF16 */
138694 
138695 /*
138696 ** Register a new collation sequence with the database handle db.
138697 */
138699  sqlite3* db,
138700  const char *zName,
138701  int enc,
138702  void* pCtx,
138703  int(*xCompare)(void*,int,const void*,int,const void*)
138704 ){
138705  return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
138706 }
138707 
138708 /*
138709 ** Register a new collation sequence with the database handle db.
138710 */
138712  sqlite3* db,
138713  const char *zName,
138714  int enc,
138715  void* pCtx,
138716  int(*xCompare)(void*,int,const void*,int,const void*),
138717  void(*xDel)(void*)
138718 ){
138719  int rc;
138720 
138721 #ifdef SQLITE_ENABLE_API_ARMOR
138722  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
138723 #endif
138724  sqlite3_mutex_enter(db->mutex);
138725  assert( !db->mallocFailed );
138726  rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
138727  rc = sqlite3ApiExit(db, rc);
138728  sqlite3_mutex_leave(db->mutex);
138729  return rc;
138730 }
138731 
138732 #ifndef SQLITE_OMIT_UTF16
138733 /*
138734 ** Register a new collation sequence with the database handle db.
138735 */
138737  sqlite3* db,
138738  const void *zName,
138739  int enc,
138740  void* pCtx,
138741  int(*xCompare)(void*,int,const void*,int,const void*)
138742 ){
138743  int rc = SQLITE_OK;
138744  char *zName8;
138745 
138746 #ifdef SQLITE_ENABLE_API_ARMOR
138747  if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
138748 #endif
138749  sqlite3_mutex_enter(db->mutex);
138750  assert( !db->mallocFailed );
138751  zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
138752  if( zName8 ){
138753  rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
138754  sqlite3DbFree(db, zName8);
138755  }
138756  rc = sqlite3ApiExit(db, rc);
138757  sqlite3_mutex_leave(db->mutex);
138758  return rc;
138759 }
138760 #endif /* SQLITE_OMIT_UTF16 */
138761 
138762 /*
138763 ** Register a collation sequence factory callback with the database handle
138764 ** db. Replace any previously installed collation sequence factory.
138765 */
138767  sqlite3 *db,
138768  void *pCollNeededArg,
138769  void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
138770 ){
138771 #ifdef SQLITE_ENABLE_API_ARMOR
138772  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138773 #endif
138774  sqlite3_mutex_enter(db->mutex);
138775  db->xCollNeeded = xCollNeeded;
138776  db->xCollNeeded16 = 0;
138777  db->pCollNeededArg = pCollNeededArg;
138778  sqlite3_mutex_leave(db->mutex);
138779  return SQLITE_OK;
138780 }
138781 
138782 #ifndef SQLITE_OMIT_UTF16
138783 /*
138784 ** Register a collation sequence factory callback with the database handle
138785 ** db. Replace any previously installed collation sequence factory.
138786 */
138788  sqlite3 *db,
138789  void *pCollNeededArg,
138790  void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
138791 ){
138792 #ifdef SQLITE_ENABLE_API_ARMOR
138793  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
138794 #endif
138795  sqlite3_mutex_enter(db->mutex);
138796  db->xCollNeeded = 0;
138797  db->xCollNeeded16 = xCollNeeded16;
138798  db->pCollNeededArg = pCollNeededArg;
138799  sqlite3_mutex_leave(db->mutex);
138800  return SQLITE_OK;
138801 }
138802 #endif /* SQLITE_OMIT_UTF16 */
138803 
138804 #ifndef SQLITE_OMIT_DEPRECATED
138805 /*
138806 ** This function is now an anachronism. It used to be used to recover from a
138807 ** malloc() failure, but SQLite now does this automatically.
138808 */
138810  return SQLITE_OK;
138811 }
138812 #endif
138813 
138814 /*
138815 ** Test to see whether or not the database connection is in autocommit
138816 ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
138817 ** by default. Autocommit is disabled by a BEGIN statement and reenabled
138818 ** by the next COMMIT or ROLLBACK.
138819 */
138821 #ifdef SQLITE_ENABLE_API_ARMOR
138822  if( !sqlite3SafetyCheckOk(db) ){
138824  return 0;
138825  }
138826 #endif
138827  return db->autoCommit;
138828 }
138829 
138830 /*
138831 ** The following routines are substitutes for constants SQLITE_CORRUPT,
138832 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_NOMEM and possibly other error
138833 ** constants. They serve two purposes:
138834 **
138835 ** 1. Serve as a convenient place to set a breakpoint in a debugger
138836 ** to detect when version error conditions occurs.
138837 **
138838 ** 2. Invoke sqlite3_log() to provide the source code location where
138839 ** a low-level error is first detected.
138840 */
138841 static int reportError(int iErr, int lineno, const char *zType){
138842  sqlite3_log(iErr, "%s at line %d of [%.10s]",
138843  zType, lineno, 20+sqlite3_sourceid());
138844  return iErr;
138845 }
138847  testcase( sqlite3GlobalConfig.xLog!=0 );
138848  return reportError(SQLITE_CORRUPT, lineno, "database corruption");
138849 }
138851  testcase( sqlite3GlobalConfig.xLog!=0 );
138852  return reportError(SQLITE_MISUSE, lineno, "misuse");
138853 }
138855  testcase( sqlite3GlobalConfig.xLog!=0 );
138856  return reportError(SQLITE_CANTOPEN, lineno, "cannot open file");
138857 }
138858 #ifdef SQLITE_DEBUG
138859 SQLITE_PRIVATE int sqlite3NomemError(int lineno){
138860  testcase( sqlite3GlobalConfig.xLog!=0 );
138861  return reportError(SQLITE_NOMEM, lineno, "OOM");
138862 }
138863 SQLITE_PRIVATE int sqlite3IoerrnomemError(int lineno){
138864  testcase( sqlite3GlobalConfig.xLog!=0 );
138865  return reportError(SQLITE_IOERR_NOMEM, lineno, "I/O OOM error");
138866 }
138867 #endif
138868 
138869 #ifndef SQLITE_OMIT_DEPRECATED
138870 /*
138871 ** This is a convenience routine that makes sure that all thread-specific
138872 ** data for this thread has been deallocated.
138873 **
138874 ** SQLite no longer uses thread-specific data so this routine is now a
138875 ** no-op. It is retained for historical compatibility.
138876 */
138878 }
138879 #endif
138880 
138881 /*
138882 ** Return meta information about a specific column of a database table.
138883 ** See comment in sqlite3.h (sqlite.h.in) for details.
138884 */
138886  sqlite3 *db, /* Connection handle */
138887  const char *zDbName, /* Database name or NULL */
138888  const char *zTableName, /* Table name */
138889  const char *zColumnName, /* Column name */
138890  char const **pzDataType, /* OUTPUT: Declared data type */
138891  char const **pzCollSeq, /* OUTPUT: Collation sequence name */
138892  int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
138893  int *pPrimaryKey, /* OUTPUT: True if column part of PK */
138894  int *pAutoinc /* OUTPUT: True if column is auto-increment */
138895 ){
138896  int rc;
138897  char *zErrMsg = 0;
138898  Table *pTab = 0;
138899  Column *pCol = 0;
138900  int iCol = 0;
138901  char const *zDataType = 0;
138902  char const *zCollSeq = 0;
138903  int notnull = 0;
138904  int primarykey = 0;
138905  int autoinc = 0;
138906 
138907 
138908 #ifdef SQLITE_ENABLE_API_ARMOR
138909  if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
138910  return SQLITE_MISUSE_BKPT;
138911  }
138912 #endif
138913 
138914  /* Ensure the database schema has been loaded */
138915  sqlite3_mutex_enter(db->mutex);
138916  sqlite3BtreeEnterAll(db);
138917  rc = sqlite3Init(db, &zErrMsg);
138918  if( SQLITE_OK!=rc ){
138919  goto error_out;
138920  }
138921 
138922  /* Locate the table in question */
138923  pTab = sqlite3FindTable(db, zTableName, zDbName);
138924  if( !pTab || pTab->pSelect ){
138925  pTab = 0;
138926  goto error_out;
138927  }
138928 
138929  /* Find the column for which info is requested */
138930  if( zColumnName==0 ){
138931  /* Query for existance of table only */
138932  }else{
138933  for(iCol=0; iCol<pTab->nCol; iCol++){
138934  pCol = &pTab->aCol[iCol];
138935  if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
138936  break;
138937  }
138938  }
138939  if( iCol==pTab->nCol ){
138940  if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
138941  iCol = pTab->iPKey;
138942  pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
138943  }else{
138944  pTab = 0;
138945  goto error_out;
138946  }
138947  }
138948  }
138949 
138950  /* The following block stores the meta information that will be returned
138951  ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
138952  ** and autoinc. At this point there are two possibilities:
138953  **
138954  ** 1. The specified column name was rowid", "oid" or "_rowid_"
138955  ** and there is no explicitly declared IPK column.
138956  **
138957  ** 2. The table is not a view and the column name identified an
138958  ** explicitly declared column. Copy meta information from *pCol.
138959  */
138960  if( pCol ){
138961  zDataType = sqlite3ColumnType(pCol,0);
138962  zCollSeq = pCol->zColl;
138963  notnull = pCol->notNull!=0;
138964  primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
138965  autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
138966  }else{
138967  zDataType = "INTEGER";
138968  primarykey = 1;
138969  }
138970  if( !zCollSeq ){
138971  zCollSeq = sqlite3StrBINARY;
138972  }
138973 
138974 error_out:
138975  sqlite3BtreeLeaveAll(db);
138976 
138977  /* Whether the function call succeeded or failed, set the output parameters
138978  ** to whatever their local counterparts contain. If an error did occur,
138979  ** this has the effect of zeroing all output parameters.
138980  */
138981  if( pzDataType ) *pzDataType = zDataType;
138982  if( pzCollSeq ) *pzCollSeq = zCollSeq;
138983  if( pNotNull ) *pNotNull = notnull;
138984  if( pPrimaryKey ) *pPrimaryKey = primarykey;
138985  if( pAutoinc ) *pAutoinc = autoinc;
138986 
138987  if( SQLITE_OK==rc && !pTab ){
138988  sqlite3DbFree(db, zErrMsg);
138989  zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
138990  zColumnName);
138991  rc = SQLITE_ERROR;
138992  }
138993  sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
138994  sqlite3DbFree(db, zErrMsg);
138995  rc = sqlite3ApiExit(db, rc);
138996  sqlite3_mutex_leave(db->mutex);
138997  return rc;
138998 }
138999 
139000 /*
139001 ** Sleep for a little while. Return the amount of time slept.
139002 */
139004  sqlite3_vfs *pVfs;
139005  int rc;
139006  pVfs = sqlite3_vfs_find(0);
139007  if( pVfs==0 ) return 0;
139008 
139009  /* This function works in milliseconds, but the underlying OsSleep()
139010  ** API uses microseconds. Hence the 1000's.
139011  */
139012  rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
139013  return rc;
139014 }
139015 
139016 /*
139017 ** Enable or disable the extended result codes.
139018 */
139020 #ifdef SQLITE_ENABLE_API_ARMOR
139021  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139022 #endif
139023  sqlite3_mutex_enter(db->mutex);
139024  db->errMask = onoff ? 0xffffffff : 0xff;
139025  sqlite3_mutex_leave(db->mutex);
139026  return SQLITE_OK;
139027 }
139028 
139029 /*
139030 ** Invoke the xFileControl method on a particular database.
139031 */
139032 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
139033  int rc = SQLITE_ERROR;
139034  Btree *pBtree;
139035 
139036 #ifdef SQLITE_ENABLE_API_ARMOR
139037  if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
139038 #endif
139039  sqlite3_mutex_enter(db->mutex);
139040  pBtree = sqlite3DbNameToBtree(db, zDbName);
139041  if( pBtree ){
139042  Pager *pPager;
139043  sqlite3_file *fd;
139044  sqlite3BtreeEnter(pBtree);
139045  pPager = sqlite3BtreePager(pBtree);
139046  assert( pPager!=0 );
139047  fd = sqlite3PagerFile(pPager);
139048  assert( fd!=0 );
139049  if( op==SQLITE_FCNTL_FILE_POINTER ){
139050  *(sqlite3_file**)pArg = fd;
139051  rc = SQLITE_OK;
139052  }else if( op==SQLITE_FCNTL_VFS_POINTER ){
139053  *(sqlite3_vfs**)pArg = sqlite3PagerVfs(pPager);
139054  rc = SQLITE_OK;
139055  }else if( op==SQLITE_FCNTL_JOURNAL_POINTER ){
139056  *(sqlite3_file**)pArg = sqlite3PagerJrnlFile(pPager);
139057  rc = SQLITE_OK;
139058  }else if( fd->pMethods ){
139059  rc = sqlite3OsFileControl(fd, op, pArg);
139060  }else{
139061  rc = SQLITE_NOTFOUND;
139062  }
139063  sqlite3BtreeLeave(pBtree);
139064  }
139065  sqlite3_mutex_leave(db->mutex);
139066  return rc;
139067 }
139068 
139069 /*
139070 ** Interface to the testing logic.
139071 */
139073  int rc = 0;
139074 #ifdef SQLITE_OMIT_BUILTIN_TEST
139075  UNUSED_PARAMETER(op);
139076 #else
139077  va_list ap;
139078  va_start(ap, op);
139079  switch( op ){
139080 
139081  /*
139082  ** Save the current state of the PRNG.
139083  */
139084  case SQLITE_TESTCTRL_PRNG_SAVE: {
139086  break;
139087  }
139088 
139089  /*
139090  ** Restore the state of the PRNG to the last state saved using
139091  ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
139092  ** this verb acts like PRNG_RESET.
139093  */
139096  break;
139097  }
139098 
139099  /*
139100  ** Reset the PRNG back to its uninitialized state. The next call
139101  ** to sqlite3_randomness() will reseed the PRNG using a single call
139102  ** to the xRandomness method of the default VFS.
139103  */
139105  sqlite3_randomness(0,0);
139106  break;
139107  }
139108 
139109  /*
139110  ** sqlite3_test_control(BITVEC_TEST, size, program)
139111  **
139112  ** Run a test against a Bitvec object of size. The program argument
139113  ** is an array of integers that defines the test. Return -1 on a
139114  ** memory allocation error, 0 on success, or non-zero for an error.
139115  ** See the sqlite3BitvecBuiltinTest() for additional information.
139116  */
139118  int sz = va_arg(ap, int);
139119  int *aProg = va_arg(ap, int*);
139120  rc = sqlite3BitvecBuiltinTest(sz, aProg);
139121  break;
139122  }
139123 
139124  /*
139125  ** sqlite3_test_control(FAULT_INSTALL, xCallback)
139126  **
139127  ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
139128  ** if xCallback is not NULL.
139129  **
139130  ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
139131  ** is called immediately after installing the new callback and the return
139132  ** value from sqlite3FaultSim(0) becomes the return from
139133  ** sqlite3_test_control().
139134  */
139136  /* MSVC is picky about pulling func ptrs from va lists.
139137  ** http://support.microsoft.com/kb/47961
139138  ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
139139  */
139140  typedef int(*TESTCALLBACKFUNC_t)(int);
139141  sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
139142  rc = sqlite3FaultSim(0);
139143  break;
139144  }
139145 
139146  /*
139147  ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
139148  **
139149  ** Register hooks to call to indicate which malloc() failures
139150  ** are benign.
139151  */
139153  typedef void (*void_function)(void);
139154  void_function xBenignBegin;
139155  void_function xBenignEnd;
139156  xBenignBegin = va_arg(ap, void_function);
139157  xBenignEnd = va_arg(ap, void_function);
139158  sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
139159  break;
139160  }
139161 
139162  /*
139163  ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
139164  **
139165  ** Set the PENDING byte to the value in the argument, if X>0.
139166  ** Make no changes if X==0. Return the value of the pending byte
139167  ** as it existing before this routine was called.
139168  **
139169  ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
139170  ** an incompatible database file format. Changing the PENDING byte
139171  ** while any database connection is open results in undefined and
139172  ** deleterious behavior.
139173  */
139175  rc = PENDING_BYTE;
139176 #ifndef SQLITE_OMIT_WSD
139177  {
139178  unsigned int newVal = va_arg(ap, unsigned int);
139179  if( newVal ) sqlite3PendingByte = newVal;
139180  }
139181 #endif
139182  break;
139183  }
139184 
139185  /*
139186  ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
139187  **
139188  ** This action provides a run-time test to see whether or not
139189  ** assert() was enabled at compile-time. If X is true and assert()
139190  ** is enabled, then the return value is true. If X is true and
139191  ** assert() is disabled, then the return value is zero. If X is
139192  ** false and assert() is enabled, then the assertion fires and the
139193  ** process aborts. If X is false and assert() is disabled, then the
139194  ** return value is zero.
139195  */
139196  case SQLITE_TESTCTRL_ASSERT: {
139197  volatile int x = 0;
139198  assert( /*side-effects-ok*/ (x = va_arg(ap,int))!=0 );
139199  rc = x;
139200  break;
139201  }
139202 
139203 
139204  /*
139205  ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
139206  **
139207  ** This action provides a run-time test to see how the ALWAYS and
139208  ** NEVER macros were defined at compile-time.
139209  **
139210  ** The return value is ALWAYS(X).
139211  **
139212  ** The recommended test is X==2. If the return value is 2, that means
139213  ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
139214  ** default setting. If the return value is 1, then ALWAYS() is either
139215  ** hard-coded to true or else it asserts if its argument is false.
139216  ** The first behavior (hard-coded to true) is the case if
139217  ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
139218  ** behavior (assert if the argument to ALWAYS() is false) is the case if
139219  ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
139220  **
139221  ** The run-time test procedure might look something like this:
139222  **
139223  ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
139224  ** // ALWAYS() and NEVER() are no-op pass-through macros
139225  ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
139226  ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
139227  ** }else{
139228  ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
139229  ** }
139230  */
139231  case SQLITE_TESTCTRL_ALWAYS: {
139232  int x = va_arg(ap,int);
139233  rc = ALWAYS(x);
139234  break;
139235  }
139236 
139237  /*
139238  ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
139239  **
139240  ** The integer returned reveals the byte-order of the computer on which
139241  ** SQLite is running:
139242  **
139243  ** 1 big-endian, determined at run-time
139244  ** 10 little-endian, determined at run-time
139245  ** 432101 big-endian, determined at compile-time
139246  ** 123410 little-endian, determined at compile-time
139247  */
139248  case SQLITE_TESTCTRL_BYTEORDER: {
139250  break;
139251  }
139252 
139253  /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
139254  **
139255  ** Set the nReserve size to N for the main database on the database
139256  ** connection db.
139257  */
139258  case SQLITE_TESTCTRL_RESERVE: {
139259  sqlite3 *db = va_arg(ap, sqlite3*);
139260  int x = va_arg(ap,int);
139261  sqlite3_mutex_enter(db->mutex);
139262  sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
139263  sqlite3_mutex_leave(db->mutex);
139264  break;
139265  }
139266 
139267  /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
139268  **
139269  ** Enable or disable various optimizations for testing purposes. The
139270  ** argument N is a bitmask of optimizations to be disabled. For normal
139271  ** operation N should be 0. The idea is that a test program (like the
139272  ** SQL Logic Test or SLT test module) can run the same SQL multiple times
139273  ** with various optimizations disabled to verify that the same answer
139274  ** is obtained in every case.
139275  */
139277  sqlite3 *db = va_arg(ap, sqlite3*);
139278  db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
139279  break;
139280  }
139281 
139282 #ifdef SQLITE_N_KEYWORD
139283  /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
139284  **
139285  ** If zWord is a keyword recognized by the parser, then return the
139286  ** number of keywords. Or if zWord is not a keyword, return 0.
139287  **
139288  ** This test feature is only available in the amalgamation since
139289  ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
139290  ** is built using separate source files.
139291  */
139292  case SQLITE_TESTCTRL_ISKEYWORD: {
139293  const char *zWord = va_arg(ap, const char*);
139294  int n = sqlite3Strlen30(zWord);
139295  rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
139296  break;
139297  }
139298 #endif
139299 
139300  /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
139301  **
139302  ** Pass pFree into sqlite3ScratchFree().
139303  ** If sz>0 then allocate a scratch buffer into pNew.
139304  */
139306  void *pFree, **ppNew;
139307  int sz;
139308  sz = va_arg(ap, int);
139309  ppNew = va_arg(ap, void**);
139310  pFree = va_arg(ap, void*);
139311  if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
139312  sqlite3ScratchFree(pFree);
139313  break;
139314  }
139315 
139316  /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
139317  **
139318  ** If parameter onoff is non-zero, configure the wrappers so that all
139319  ** subsequent calls to localtime() and variants fail. If onoff is zero,
139320  ** undo this setting.
139321  */
139323  sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
139324  break;
139325  }
139326 
139327  /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
139328  **
139329  ** Set or clear a flag that indicates that the database file is always well-
139330  ** formed and never corrupt. This flag is clear by default, indicating that
139331  ** database files might have arbitrary corruption. Setting the flag during
139332  ** testing causes certain assert() statements in the code to be activated
139333  ** that demonstrat invariants on well-formed database files.
139334  */
139336  sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
139337  break;
139338  }
139339 
139340 
139341  /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
139342  **
139343  ** Set the VDBE coverage callback function to xCallback with context
139344  ** pointer ptr.
139345  */
139347 #ifdef SQLITE_VDBE_COVERAGE
139348  typedef void (*branch_callback)(void*,int,u8,u8);
139349  sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
139350  sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
139351 #endif
139352  break;
139353  }
139354 
139355  /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
139357  sqlite3 *db = va_arg(ap, sqlite3*);
139358  db->nMaxSorterMmap = va_arg(ap, int);
139359  break;
139360  }
139361 
139362  /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
139363  **
139364  ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
139365  ** not.
139366  */
139367  case SQLITE_TESTCTRL_ISINIT: {
139368  if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
139369  break;
139370  }
139371 
139372  /* sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
139373  **
139374  ** This test control is used to create imposter tables. "db" is a pointer
139375  ** to the database connection. dbName is the database name (ex: "main" or
139376  ** "temp") which will receive the imposter. "onOff" turns imposter mode on
139377  ** or off. "tnum" is the root page of the b-tree to which the imposter
139378  ** table should connect.
139379  **
139380  ** Enable imposter mode only when the schema has already been parsed. Then
139381  ** run a single CREATE TABLE statement to construct the imposter table in
139382  ** the parsed schema. Then turn imposter mode back off again.
139383  **
139384  ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
139385  ** the schema to be reparsed the next time it is needed. This has the
139386  ** effect of erasing all imposter tables.
139387  */
139388  case SQLITE_TESTCTRL_IMPOSTER: {
139389  sqlite3 *db = va_arg(ap, sqlite3*);
139390  sqlite3_mutex_enter(db->mutex);
139391  db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
139392  db->init.busy = db->init.imposterTable = va_arg(ap,int);
139393  db->init.newTnum = va_arg(ap,int);
139394  if( db->init.busy==0 && db->init.newTnum>0 ){
139396  }
139397  sqlite3_mutex_leave(db->mutex);
139398  break;
139399  }
139400  }
139401  va_end(ap);
139402 #endif /* SQLITE_OMIT_BUILTIN_TEST */
139403  return rc;
139404 }
139405 
139406 /*
139407 ** This is a utility routine, useful to VFS implementations, that checks
139408 ** to see if a database file was a URI that contained a specific query
139409 ** parameter, and if so obtains the value of the query parameter.
139410 **
139411 ** The zFilename argument is the filename pointer passed into the xOpen()
139412 ** method of a VFS implementation. The zParam argument is the name of the
139413 ** query parameter we seek. This routine returns the value of the zParam
139414 ** parameter if it exists. If the parameter does not exist, this routine
139415 ** returns a NULL pointer.
139416 */
139417 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
139418  if( zFilename==0 || zParam==0 ) return 0;
139419  zFilename += sqlite3Strlen30(zFilename) + 1;
139420  while( zFilename[0] ){
139421  int x = strcmp(zFilename, zParam);
139422  zFilename += sqlite3Strlen30(zFilename) + 1;
139423  if( x==0 ) return zFilename;
139424  zFilename += sqlite3Strlen30(zFilename) + 1;
139425  }
139426  return 0;
139427 }
139428 
139429 /*
139430 ** Return a boolean value for a query parameter.
139431 */
139432 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
139433  const char *z = sqlite3_uri_parameter(zFilename, zParam);
139434  bDflt = bDflt!=0;
139435  return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
139436 }
139437 
139438 /*
139439 ** Return a 64-bit integer value for a query parameter.
139440 */
139442  const char *zFilename, /* Filename as passed to xOpen */
139443  const char *zParam, /* URI parameter sought */
139444  sqlite3_int64 bDflt /* return if parameter is missing */
139445 ){
139446  const char *z = sqlite3_uri_parameter(zFilename, zParam);
139447  sqlite3_int64 v;
139448  if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
139449  bDflt = v;
139450  }
139451  return bDflt;
139452 }
139453 
139454 /*
139455 ** Return the Btree pointer identified by zDbName. Return NULL if not found.
139456 */
139457 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
139458  int i;
139459  for(i=0; i<db->nDb; i++){
139460  if( db->aDb[i].pBt
139461  && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
139462  ){
139463  return db->aDb[i].pBt;
139464  }
139465  }
139466  return 0;
139467 }
139468 
139469 /*
139470 ** Return the filename of the database associated with a database
139471 ** connection.
139472 */
139473 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
139474  Btree *pBt;
139475 #ifdef SQLITE_ENABLE_API_ARMOR
139476  if( !sqlite3SafetyCheckOk(db) ){
139478  return 0;
139479  }
139480 #endif
139481  pBt = sqlite3DbNameToBtree(db, zDbName);
139482  return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
139483 }
139484 
139485 /*
139486 ** Return 1 if database is read-only or 0 if read/write. Return -1 if
139487 ** no such database exists.
139488 */
139489 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
139490  Btree *pBt;
139491 #ifdef SQLITE_ENABLE_API_ARMOR
139492  if( !sqlite3SafetyCheckOk(db) ){
139494  return -1;
139495  }
139496 #endif
139497  pBt = sqlite3DbNameToBtree(db, zDbName);
139498  return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
139499 }
139500 
139501 #ifdef SQLITE_ENABLE_SNAPSHOT
139502 /*
139503 ** Obtain a snapshot handle for the snapshot of database zDb currently
139504 ** being read by handle db.
139505 */
139507  sqlite3 *db,
139508  const char *zDb,
139509  sqlite3_snapshot **ppSnapshot
139510 ){
139511  int rc = SQLITE_ERROR;
139512 #ifndef SQLITE_OMIT_WAL
139513  int iDb;
139514 
139515 #ifdef SQLITE_ENABLE_API_ARMOR
139516  if( !sqlite3SafetyCheckOk(db) ){
139517  return SQLITE_MISUSE_BKPT;
139518  }
139519 #endif
139520  sqlite3_mutex_enter(db->mutex);
139521 
139522  iDb = sqlite3FindDbName(db, zDb);
139523  if( iDb==0 || iDb>1 ){
139524  Btree *pBt = db->aDb[iDb].pBt;
139525  if( 0==sqlite3BtreeIsInTrans(pBt) ){
139526  rc = sqlite3BtreeBeginTrans(pBt, 0);
139527  if( rc==SQLITE_OK ){
139528  rc = sqlite3PagerSnapshotGet(sqlite3BtreePager(pBt), ppSnapshot);
139529  }
139530  }
139531  }
139532 
139533  sqlite3_mutex_leave(db->mutex);
139534 #endif /* SQLITE_OMIT_WAL */
139535  return rc;
139536 }
139537 
139538 /*
139539 ** Open a read-transaction on the snapshot idendified by pSnapshot.
139540 */
139542  sqlite3 *db,
139543  const char *zDb,
139544  sqlite3_snapshot *pSnapshot
139545 ){
139546  int rc = SQLITE_ERROR;
139547 #ifndef SQLITE_OMIT_WAL
139548 
139549 #ifdef SQLITE_ENABLE_API_ARMOR
139550  if( !sqlite3SafetyCheckOk(db) ){
139551  return SQLITE_MISUSE_BKPT;
139552  }
139553 #endif
139554  sqlite3_mutex_enter(db->mutex);
139555  if( db->autoCommit==0 ){
139556  int iDb;
139557  iDb = sqlite3FindDbName(db, zDb);
139558  if( iDb==0 || iDb>1 ){
139559  Btree *pBt = db->aDb[iDb].pBt;
139560  if( 0==sqlite3BtreeIsInReadTrans(pBt) ){
139561  rc = sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), pSnapshot);
139562  if( rc==SQLITE_OK ){
139563  rc = sqlite3BtreeBeginTrans(pBt, 0);
139564  sqlite3PagerSnapshotOpen(sqlite3BtreePager(pBt), 0);
139565  }
139566  }
139567  }
139568  }
139569 
139570  sqlite3_mutex_leave(db->mutex);
139571 #endif /* SQLITE_OMIT_WAL */
139572  return rc;
139573 }
139574 
139575 /*
139576 ** Free a snapshot handle obtained from sqlite3_snapshot_get().
139577 */
139579  sqlite3_free(pSnapshot);
139580 }
139581 #endif /* SQLITE_ENABLE_SNAPSHOT */
139582 
139583 /************** End of main.c ************************************************/
139584 /************** Begin file notify.c ******************************************/
139585 /*
139586 ** 2009 March 3
139587 **
139588 ** The author disclaims copyright to this source code. In place of
139589 ** a legal notice, here is a blessing:
139590 **
139591 ** May you do good and not evil.
139592 ** May you find forgiveness for yourself and forgive others.
139593 ** May you share freely, never taking more than you give.
139594 **
139595 *************************************************************************
139596 **
139597 ** This file contains the implementation of the sqlite3_unlock_notify()
139598 ** API method and its associated functionality.
139599 */
139600 /* #include "sqliteInt.h" */
139601 /* #include "btreeInt.h" */
139602 
139603 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
139604 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
139605 
139606 /*
139607 ** Public interfaces:
139608 **
139609 ** sqlite3ConnectionBlocked()
139610 ** sqlite3ConnectionUnlocked()
139611 ** sqlite3ConnectionClosed()
139612 ** sqlite3_unlock_notify()
139613 */
139614 
139615 #define assertMutexHeld() \
139616  assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
139617 
139618 /*
139619 ** Head of a linked list of all sqlite3 objects created by this process
139620 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
139621 ** is not NULL. This variable may only accessed while the STATIC_MASTER
139622 ** mutex is held.
139623 */
139624 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
139625 
139626 #ifndef NDEBUG
139627 /*
139628 ** This function is a complex assert() that verifies the following
139629 ** properties of the blocked connections list:
139630 **
139631 ** 1) Each entry in the list has a non-NULL value for either
139632 ** pUnlockConnection or pBlockingConnection, or both.
139633 **
139634 ** 2) All entries in the list that share a common value for
139635 ** xUnlockNotify are grouped together.
139636 **
139637 ** 3) If the argument db is not NULL, then none of the entries in the
139638 ** blocked connections list have pUnlockConnection or pBlockingConnection
139639 ** set to db. This is used when closing connection db.
139640 */
139641 static void checkListProperties(sqlite3 *db){
139642  sqlite3 *p;
139643  for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
139644  int seen = 0;
139645  sqlite3 *p2;
139646 
139647  /* Verify property (1) */
139648  assert( p->pUnlockConnection || p->pBlockingConnection );
139649 
139650  /* Verify property (2) */
139651  for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
139652  if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
139653  assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
139654  assert( db==0 || p->pUnlockConnection!=db );
139655  assert( db==0 || p->pBlockingConnection!=db );
139656  }
139657  }
139658 }
139659 #else
139660 # define checkListProperties(x)
139661 #endif
139662 
139663 /*
139664 ** Remove connection db from the blocked connections list. If connection
139665 ** db is not currently a part of the list, this function is a no-op.
139666 */
139667 static void removeFromBlockedList(sqlite3 *db){
139668  sqlite3 **pp;
139669  assertMutexHeld();
139670  for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
139671  if( *pp==db ){
139672  *pp = (*pp)->pNextBlocked;
139673  break;
139674  }
139675  }
139676 }
139677 
139678 /*
139679 ** Add connection db to the blocked connections list. It is assumed
139680 ** that it is not already a part of the list.
139681 */
139682 static void addToBlockedList(sqlite3 *db){
139683  sqlite3 **pp;
139684  assertMutexHeld();
139685  for(
139686  pp=&sqlite3BlockedList;
139687  *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
139688  pp=&(*pp)->pNextBlocked
139689  );
139690  db->pNextBlocked = *pp;
139691  *pp = db;
139692 }
139693 
139694 /*
139695 ** Obtain the STATIC_MASTER mutex.
139696 */
139697 static void enterMutex(void){
139699  checkListProperties(0);
139700 }
139701 
139702 /*
139703 ** Release the STATIC_MASTER mutex.
139704 */
139705 static void leaveMutex(void){
139706  assertMutexHeld();
139707  checkListProperties(0);
139709 }
139710 
139711 /*
139712 ** Register an unlock-notify callback.
139713 **
139714 ** This is called after connection "db" has attempted some operation
139715 ** but has received an SQLITE_LOCKED error because another connection
139716 ** (call it pOther) in the same process was busy using the same shared
139717 ** cache. pOther is found by looking at db->pBlockingConnection.
139718 **
139719 ** If there is no blocking connection, the callback is invoked immediately,
139720 ** before this routine returns.
139721 **
139722 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
139723 ** a deadlock.
139724 **
139725 ** Otherwise, make arrangements to invoke xNotify when pOther drops
139726 ** its locks.
139727 **
139728 ** Each call to this routine overrides any prior callbacks registered
139729 ** on the same "db". If xNotify==0 then any prior callbacks are immediately
139730 ** cancelled.
139731 */
139733  sqlite3 *db,
139734  void (*xNotify)(void **, int),
139735  void *pArg
139736 ){
139737  int rc = SQLITE_OK;
139738 
139739  sqlite3_mutex_enter(db->mutex);
139740  enterMutex();
139741 
139742  if( xNotify==0 ){
139743  removeFromBlockedList(db);
139744  db->pBlockingConnection = 0;
139745  db->pUnlockConnection = 0;
139746  db->xUnlockNotify = 0;
139747  db->pUnlockArg = 0;
139748  }else if( 0==db->pBlockingConnection ){
139749  /* The blocking transaction has been concluded. Or there never was a
139750  ** blocking transaction. In either case, invoke the notify callback
139751  ** immediately.
139752  */
139753  xNotify(&pArg, 1);
139754  }else{
139755  sqlite3 *p;
139756 
139757  for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
139758  if( p ){
139759  rc = SQLITE_LOCKED; /* Deadlock detected. */
139760  }else{
139761  db->pUnlockConnection = db->pBlockingConnection;
139762  db->xUnlockNotify = xNotify;
139763  db->pUnlockArg = pArg;
139764  removeFromBlockedList(db);
139765  addToBlockedList(db);
139766  }
139767  }
139768 
139769  leaveMutex();
139770  assert( !db->mallocFailed );
139771  sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
139772  sqlite3_mutex_leave(db->mutex);
139773  return rc;
139774 }
139775 
139776 /*
139777 ** This function is called while stepping or preparing a statement
139778 ** associated with connection db. The operation will return SQLITE_LOCKED
139779 ** to the user because it requires a lock that will not be available
139780 ** until connection pBlocker concludes its current transaction.
139781 */
139782 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
139783  enterMutex();
139784  if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
139785  addToBlockedList(db);
139786  }
139787  db->pBlockingConnection = pBlocker;
139788  leaveMutex();
139789 }
139790 
139791 /*
139792 ** This function is called when
139793 ** the transaction opened by database db has just finished. Locks held
139794 ** by database connection db have been released.
139795 **
139796 ** This function loops through each entry in the blocked connections
139797 ** list and does the following:
139798 **
139799 ** 1) If the sqlite3.pBlockingConnection member of a list entry is
139800 ** set to db, then set pBlockingConnection=0.
139801 **
139802 ** 2) If the sqlite3.pUnlockConnection member of a list entry is
139803 ** set to db, then invoke the configured unlock-notify callback and
139804 ** set pUnlockConnection=0.
139805 **
139806 ** 3) If the two steps above mean that pBlockingConnection==0 and
139807 ** pUnlockConnection==0, remove the entry from the blocked connections
139808 ** list.
139809 */
139810 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
139811  void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
139812  int nArg = 0; /* Number of entries in aArg[] */
139813  sqlite3 **pp; /* Iterator variable */
139814  void **aArg; /* Arguments to the unlock callback */
139815  void **aDyn = 0; /* Dynamically allocated space for aArg[] */
139816  void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
139817 
139818  aArg = aStatic;
139819  enterMutex(); /* Enter STATIC_MASTER mutex */
139820 
139821  /* This loop runs once for each entry in the blocked-connections list. */
139822  for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
139823  sqlite3 *p = *pp;
139824 
139825  /* Step 1. */
139826  if( p->pBlockingConnection==db ){
139827  p->pBlockingConnection = 0;
139828  }
139829 
139830  /* Step 2. */
139831  if( p->pUnlockConnection==db ){
139832  assert( p->xUnlockNotify );
139833  if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
139834  xUnlockNotify(aArg, nArg);
139835  nArg = 0;
139836  }
139837 
139839  assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
139840  assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
139841  if( (!aDyn && nArg==(int)ArraySize(aStatic))
139842  || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
139843  ){
139844  /* The aArg[] array needs to grow. */
139845  void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
139846  if( pNew ){
139847  memcpy(pNew, aArg, nArg*sizeof(void *));
139848  sqlite3_free(aDyn);
139849  aDyn = aArg = pNew;
139850  }else{
139851  /* This occurs when the array of context pointers that need to
139852  ** be passed to the unlock-notify callback is larger than the
139853  ** aStatic[] array allocated on the stack and the attempt to
139854  ** allocate a larger array from the heap has failed.
139855  **
139856  ** This is a difficult situation to handle. Returning an error
139857  ** code to the caller is insufficient, as even if an error code
139858  ** is returned the transaction on connection db will still be
139859  ** closed and the unlock-notify callbacks on blocked connections
139860  ** will go unissued. This might cause the application to wait
139861  ** indefinitely for an unlock-notify callback that will never
139862  ** arrive.
139863  **
139864  ** Instead, invoke the unlock-notify callback with the context
139865  ** array already accumulated. We can then clear the array and
139866  ** begin accumulating any further context pointers without
139867  ** requiring any dynamic allocation. This is sub-optimal because
139868  ** it means that instead of one callback with a large array of
139869  ** context pointers the application will receive two or more
139870  ** callbacks with smaller arrays of context pointers, which will
139871  ** reduce the applications ability to prioritize multiple
139872  ** connections. But it is the best that can be done under the
139873  ** circumstances.
139874  */
139875  xUnlockNotify(aArg, nArg);
139876  nArg = 0;
139877  }
139878  }
139880 
139881  aArg[nArg++] = p->pUnlockArg;
139882  xUnlockNotify = p->xUnlockNotify;
139883  p->pUnlockConnection = 0;
139884  p->xUnlockNotify = 0;
139885  p->pUnlockArg = 0;
139886  }
139887 
139888  /* Step 3. */
139889  if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
139890  /* Remove connection p from the blocked connections list. */
139891  *pp = p->pNextBlocked;
139892  p->pNextBlocked = 0;
139893  }else{
139894  pp = &p->pNextBlocked;
139895  }
139896  }
139897 
139898  if( nArg!=0 ){
139899  xUnlockNotify(aArg, nArg);
139900  }
139901  sqlite3_free(aDyn);
139902  leaveMutex(); /* Leave STATIC_MASTER mutex */
139903 }
139904 
139905 /*
139906 ** This is called when the database connection passed as an argument is
139907 ** being closed. The connection is removed from the blocked list.
139908 */
139909 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
139911  enterMutex();
139912  removeFromBlockedList(db);
139913  checkListProperties(db);
139914  leaveMutex();
139915 }
139916 #endif
139917 
139918 /************** End of notify.c **********************************************/
139919 /************** Begin file fts3.c ********************************************/
139920 /*
139921 ** 2006 Oct 10
139922 **
139923 ** The author disclaims copyright to this source code. In place of
139924 ** a legal notice, here is a blessing:
139925 **
139926 ** May you do good and not evil.
139927 ** May you find forgiveness for yourself and forgive others.
139928 ** May you share freely, never taking more than you give.
139929 **
139930 ******************************************************************************
139931 **
139932 ** This is an SQLite module implementing full-text search.
139933 */
139934 
139935 /*
139936 ** The code in this file is only compiled if:
139937 **
139938 ** * The FTS3 module is being built as an extension
139939 ** (in which case SQLITE_CORE is not defined), or
139940 **
139941 ** * The FTS3 module is being built into the core of
139942 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
139943 */
139944 
139945 /* The full-text index is stored in a series of b+tree (-like)
139946 ** structures called segments which map terms to doclists. The
139947 ** structures are like b+trees in layout, but are constructed from the
139948 ** bottom up in optimal fashion and are not updatable. Since trees
139949 ** are built from the bottom up, things will be described from the
139950 ** bottom up.
139951 **
139952 **
139953 **** Varints ****
139954 ** The basic unit of encoding is a variable-length integer called a
139955 ** varint. We encode variable-length integers in little-endian order
139956 ** using seven bits * per byte as follows:
139957 **
139958 ** KEY:
139959 ** A = 0xxxxxxx 7 bits of data and one flag bit
139960 ** B = 1xxxxxxx 7 bits of data and one flag bit
139961 **
139962 ** 7 bits - A
139963 ** 14 bits - BA
139964 ** 21 bits - BBA
139965 ** and so on.
139966 **
139967 ** This is similar in concept to how sqlite encodes "varints" but
139968 ** the encoding is not the same. SQLite varints are big-endian
139969 ** are are limited to 9 bytes in length whereas FTS3 varints are
139970 ** little-endian and can be up to 10 bytes in length (in theory).
139971 **
139972 ** Example encodings:
139973 **
139974 ** 1: 0x01
139975 ** 127: 0x7f
139976 ** 128: 0x81 0x00
139977 **
139978 **
139979 **** Document lists ****
139980 ** A doclist (document list) holds a docid-sorted list of hits for a
139981 ** given term. Doclists hold docids and associated token positions.
139982 ** A docid is the unique integer identifier for a single document.
139983 ** A position is the index of a word within the document. The first
139984 ** word of the document has a position of 0.
139985 **
139986 ** FTS3 used to optionally store character offsets using a compile-time
139987 ** option. But that functionality is no longer supported.
139988 **
139989 ** A doclist is stored like this:
139990 **
139991 ** array {
139992 ** varint docid; (delta from previous doclist)
139993 ** array { (position list for column 0)
139994 ** varint position; (2 more than the delta from previous position)
139995 ** }
139996 ** array {
139997 ** varint POS_COLUMN; (marks start of position list for new column)
139998 ** varint column; (index of new column)
139999 ** array {
140000 ** varint position; (2 more than the delta from previous position)
140001 ** }
140002 ** }
140003 ** varint POS_END; (marks end of positions for this document.
140004 ** }
140005 **
140006 ** Here, array { X } means zero or more occurrences of X, adjacent in
140007 ** memory. A "position" is an index of a token in the token stream
140008 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
140009 ** in the same logical place as the position element, and act as sentinals
140010 ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
140011 ** The positions numbers are not stored literally but rather as two more
140012 ** than the difference from the prior position, or the just the position plus
140013 ** 2 for the first position. Example:
140014 **
140015 ** label: A B C D E F G H I J K
140016 ** value: 123 5 9 1 1 14 35 0 234 72 0
140017 **
140018 ** The 123 value is the first docid. For column zero in this document
140019 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
140020 ** at D signals the start of a new column; the 1 at E indicates that the
140021 ** new column is column number 1. There are two positions at 12 and 45
140022 ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
140023 ** 234 at I is the delta to next docid (357). It has one position 70
140024 ** (72-2) and then terminates with the 0 at K.
140025 **
140026 ** A "position-list" is the list of positions for multiple columns for
140027 ** a single docid. A "column-list" is the set of positions for a single
140028 ** column. Hence, a position-list consists of one or more column-lists,
140029 ** a document record consists of a docid followed by a position-list and
140030 ** a doclist consists of one or more document records.
140031 **
140032 ** A bare doclist omits the position information, becoming an
140033 ** array of varint-encoded docids.
140034 **
140035 **** Segment leaf nodes ****
140036 ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
140037 ** nodes are written using LeafWriter, and read using LeafReader (to
140038 ** iterate through a single leaf node's data) and LeavesReader (to
140039 ** iterate through a segment's entire leaf layer). Leaf nodes have
140040 ** the format:
140041 **
140042 ** varint iHeight; (height from leaf level, always 0)
140043 ** varint nTerm; (length of first term)
140044 ** char pTerm[nTerm]; (content of first term)
140045 ** varint nDoclist; (length of term's associated doclist)
140046 ** char pDoclist[nDoclist]; (content of doclist)
140047 ** array {
140048 ** (further terms are delta-encoded)
140049 ** varint nPrefix; (length of prefix shared with previous term)
140050 ** varint nSuffix; (length of unshared suffix)
140051 ** char pTermSuffix[nSuffix];(unshared suffix of next term)
140052 ** varint nDoclist; (length of term's associated doclist)
140053 ** char pDoclist[nDoclist]; (content of doclist)
140054 ** }
140055 **
140056 ** Here, array { X } means zero or more occurrences of X, adjacent in
140057 ** memory.
140058 **
140059 ** Leaf nodes are broken into blocks which are stored contiguously in
140060 ** the %_segments table in sorted order. This means that when the end
140061 ** of a node is reached, the next term is in the node with the next
140062 ** greater node id.
140063 **
140064 ** New data is spilled to a new leaf node when the current node
140065 ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
140066 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
140067 ** node (a leaf node with a single term and doclist). The goal of
140068 ** these settings is to pack together groups of small doclists while
140069 ** making it efficient to directly access large doclists. The
140070 ** assumption is that large doclists represent terms which are more
140071 ** likely to be query targets.
140072 **
140073 ** TODO(shess) It may be useful for blocking decisions to be more
140074 ** dynamic. For instance, it may make more sense to have a 2.5k leaf
140075 ** node rather than splitting into 2k and .5k nodes. My intuition is
140076 ** that this might extend through 2x or 4x the pagesize.
140077 **
140078 **
140079 **** Segment interior nodes ****
140080 ** Segment interior nodes store blockids for subtree nodes and terms
140081 ** to describe what data is stored by the each subtree. Interior
140082 ** nodes are written using InteriorWriter, and read using
140083 ** InteriorReader. InteriorWriters are created as needed when
140084 ** SegmentWriter creates new leaf nodes, or when an interior node
140085 ** itself grows too big and must be split. The format of interior
140086 ** nodes:
140087 **
140088 ** varint iHeight; (height from leaf level, always >0)
140089 ** varint iBlockid; (block id of node's leftmost subtree)
140090 ** optional {
140091 ** varint nTerm; (length of first term)
140092 ** char pTerm[nTerm]; (content of first term)
140093 ** array {
140094 ** (further terms are delta-encoded)
140095 ** varint nPrefix; (length of shared prefix with previous term)
140096 ** varint nSuffix; (length of unshared suffix)
140097 ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
140098 ** }
140099 ** }
140100 **
140101 ** Here, optional { X } means an optional element, while array { X }
140102 ** means zero or more occurrences of X, adjacent in memory.
140103 **
140104 ** An interior node encodes n terms separating n+1 subtrees. The
140105 ** subtree blocks are contiguous, so only the first subtree's blockid
140106 ** is encoded. The subtree at iBlockid will contain all terms less
140107 ** than the first term encoded (or all terms if no term is encoded).
140108 ** Otherwise, for terms greater than or equal to pTerm[i] but less
140109 ** than pTerm[i+1], the subtree for that term will be rooted at
140110 ** iBlockid+i. Interior nodes only store enough term data to
140111 ** distinguish adjacent children (if the rightmost term of the left
140112 ** child is "something", and the leftmost term of the right child is
140113 ** "wicked", only "w" is stored).
140114 **
140115 ** New data is spilled to a new interior node at the same height when
140116 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
140117 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
140118 ** interior nodes and making the tree too skinny. The interior nodes
140119 ** at a given height are naturally tracked by interior nodes at
140120 ** height+1, and so on.
140121 **
140122 **
140123 **** Segment directory ****
140124 ** The segment directory in table %_segdir stores meta-information for
140125 ** merging and deleting segments, and also the root node of the
140126 ** segment's tree.
140127 **
140128 ** The root node is the top node of the segment's tree after encoding
140129 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
140130 ** This could be either a leaf node or an interior node. If the top
140131 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
140132 ** and a new root interior node is generated (which should always fit
140133 ** within ROOT_MAX because it only needs space for 2 varints, the
140134 ** height and the blockid of the previous root).
140135 **
140136 ** The meta-information in the segment directory is:
140137 ** level - segment level (see below)
140138 ** idx - index within level
140139 ** - (level,idx uniquely identify a segment)
140140 ** start_block - first leaf node
140141 ** leaves_end_block - last leaf node
140142 ** end_block - last block (including interior nodes)
140143 ** root - contents of root node
140144 **
140145 ** If the root node is a leaf node, then start_block,
140146 ** leaves_end_block, and end_block are all 0.
140147 **
140148 **
140149 **** Segment merging ****
140150 ** To amortize update costs, segments are grouped into levels and
140151 ** merged in batches. Each increase in level represents exponentially
140152 ** more documents.
140153 **
140154 ** New documents (actually, document updates) are tokenized and
140155 ** written individually (using LeafWriter) to a level 0 segment, with
140156 ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
140157 ** level 0 segments are merged into a single level 1 segment. Level 1
140158 ** is populated like level 0, and eventually MERGE_COUNT level 1
140159 ** segments are merged to a single level 2 segment (representing
140160 ** MERGE_COUNT^2 updates), and so on.
140161 **
140162 ** A segment merge traverses all segments at a given level in
140163 ** parallel, performing a straightforward sorted merge. Since segment
140164 ** leaf nodes are written in to the %_segments table in order, this
140165 ** merge traverses the underlying sqlite disk structures efficiently.
140166 ** After the merge, all segment blocks from the merged level are
140167 ** deleted.
140168 **
140169 ** MERGE_COUNT controls how often we merge segments. 16 seems to be
140170 ** somewhat of a sweet spot for insertion performance. 32 and 64 show
140171 ** very similar performance numbers to 16 on insertion, though they're
140172 ** a tiny bit slower (perhaps due to more overhead in merge-time
140173 ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
140174 ** 16, 2 about 66% slower than 16.
140175 **
140176 ** At query time, high MERGE_COUNT increases the number of segments
140177 ** which need to be scanned and merged. For instance, with 100k docs
140178 ** inserted:
140179 **
140180 ** MERGE_COUNT segments
140181 ** 16 25
140182 ** 8 12
140183 ** 4 10
140184 ** 2 6
140185 **
140186 ** This appears to have only a moderate impact on queries for very
140187 ** frequent terms (which are somewhat dominated by segment merge
140188 ** costs), and infrequent and non-existent terms still seem to be fast
140189 ** even with many segments.
140190 **
140191 ** TODO(shess) That said, it would be nice to have a better query-side
140192 ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
140193 ** optimizations to things like doclist merging will swing the sweet
140194 ** spot around.
140195 **
140196 **
140197 **
140198 **** Handling of deletions and updates ****
140199 ** Since we're using a segmented structure, with no docid-oriented
140200 ** index into the term index, we clearly cannot simply update the term
140201 ** index when a document is deleted or updated. For deletions, we
140202 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
140203 ** we simply write the new doclist. Segment merges overwrite older
140204 ** data for a particular docid with newer data, so deletes or updates
140205 ** will eventually overtake the earlier data and knock it out. The
140206 ** query logic likewise merges doclists so that newer data knocks out
140207 ** older data.
140208 */
140209 
140210 /************** Include fts3Int.h in the middle of fts3.c ********************/
140211 /************** Begin file fts3Int.h *****************************************/
140212 /*
140213 ** 2009 Nov 12
140214 **
140215 ** The author disclaims copyright to this source code. In place of
140216 ** a legal notice, here is a blessing:
140217 **
140218 ** May you do good and not evil.
140219 ** May you find forgiveness for yourself and forgive others.
140220 ** May you share freely, never taking more than you give.
140221 **
140222 ******************************************************************************
140223 **
140224 */
140225 #ifndef _FTSINT_H
140226 #define _FTSINT_H
140227 
140228 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
140229 # define NDEBUG 1
140230 #endif
140231 
140232 /* FTS3/FTS4 require virtual tables */
140233 #ifdef SQLITE_OMIT_VIRTUALTABLE
140234 # undef SQLITE_ENABLE_FTS3
140235 # undef SQLITE_ENABLE_FTS4
140236 #endif
140237 
140238 /*
140239 ** FTS4 is really an extension for FTS3. It is enabled using the
140240 ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
140241 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
140242 */
140243 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
140244 # define SQLITE_ENABLE_FTS3
140245 #endif
140246 
140247 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140248 
140249 /* If not building as part of the core, include sqlite3ext.h. */
140250 #ifndef SQLITE_CORE
140251 /* # include "sqlite3ext.h" */
140253 #endif
140254 
140255 /* #include "sqlite3.h" */
140256 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
140257 /************** Begin file fts3_tokenizer.h **********************************/
140258 /*
140259 ** 2006 July 10
140260 **
140261 ** The author disclaims copyright to this source code.
140262 **
140263 *************************************************************************
140264 ** Defines the interface to tokenizers used by fulltext-search. There
140265 ** are three basic components:
140266 **
140267 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
140268 ** interface functions. This is essentially the class structure for
140269 ** tokenizers.
140270 **
140271 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
140272 ** including customization information defined at creation time.
140273 **
140274 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
140275 ** tokens from a particular input.
140276 */
140277 #ifndef _FTS3_TOKENIZER_H_
140278 #define _FTS3_TOKENIZER_H_
140279 
140280 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
140281 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
140282 ** we will need a way to register the API consistently.
140283 */
140284 /* #include "sqlite3.h" */
140285 
140286 /*
140287 ** Structures used by the tokenizer interface. When a new tokenizer
140288 ** implementation is registered, the caller provides a pointer to
140289 ** an sqlite3_tokenizer_module containing pointers to the callback
140290 ** functions that make up an implementation.
140291 **
140292 ** When an fts3 table is created, it passes any arguments passed to
140293 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
140294 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
140295 ** implementation. The xCreate() function in turn returns an
140296 ** sqlite3_tokenizer structure representing the specific tokenizer to
140297 ** be used for the fts3 table (customized by the tokenizer clause arguments).
140298 **
140299 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
140300 ** method is called. It returns an sqlite3_tokenizer_cursor object
140301 ** that may be used to tokenize a specific input buffer based on
140302 ** the tokenization rules supplied by a specific sqlite3_tokenizer
140303 ** object.
140304 */
140305 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
140306 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
140307 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
140308 
140309 struct sqlite3_tokenizer_module {
140310 
140311  /*
140312  ** Structure version. Should always be set to 0 or 1.
140313  */
140314  int iVersion;
140315 
140316  /*
140317  ** Create a new tokenizer. The values in the argv[] array are the
140318  ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
140319  ** TABLE statement that created the fts3 table. For example, if
140320  ** the following SQL is executed:
140321  **
140322  ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
140323  **
140324  ** then argc is set to 2, and the argv[] array contains pointers
140325  ** to the strings "arg1" and "arg2".
140326  **
140327  ** This method should return either SQLITE_OK (0), or an SQLite error
140328  ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
140329  ** to point at the newly created tokenizer structure. The generic
140330  ** sqlite3_tokenizer.pModule variable should not be initialized by
140331  ** this callback. The caller will do so.
140332  */
140333  int (*xCreate)(
140334  int argc, /* Size of argv array */
140335  const char *const*argv, /* Tokenizer argument strings */
140336  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
140337  );
140338 
140339  /*
140340  ** Destroy an existing tokenizer. The fts3 module calls this method
140341  ** exactly once for each successful call to xCreate().
140342  */
140343  int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
140344 
140345  /*
140346  ** Create a tokenizer cursor to tokenize an input buffer. The caller
140347  ** is responsible for ensuring that the input buffer remains valid
140348  ** until the cursor is closed (using the xClose() method).
140349  */
140350  int (*xOpen)(
140351  sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
140352  const char *pInput, int nBytes, /* Input buffer */
140353  sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
140354  );
140355 
140356  /*
140357  ** Destroy an existing tokenizer cursor. The fts3 module calls this
140358  ** method exactly once for each successful call to xOpen().
140359  */
140360  int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
140361 
140362  /*
140363  ** Retrieve the next token from the tokenizer cursor pCursor. This
140364  ** method should either return SQLITE_OK and set the values of the
140365  ** "OUT" variables identified below, or SQLITE_DONE to indicate that
140366  ** the end of the buffer has been reached, or an SQLite error code.
140367  **
140368  ** *ppToken should be set to point at a buffer containing the
140369  ** normalized version of the token (i.e. after any case-folding and/or
140370  ** stemming has been performed). *pnBytes should be set to the length
140371  ** of this buffer in bytes. The input text that generated the token is
140372  ** identified by the byte offsets returned in *piStartOffset and
140373  ** *piEndOffset. *piStartOffset should be set to the index of the first
140374  ** byte of the token in the input buffer. *piEndOffset should be set
140375  ** to the index of the first byte just past the end of the token in
140376  ** the input buffer.
140377  **
140378  ** The buffer *ppToken is set to point at is managed by the tokenizer
140379  ** implementation. It is only required to be valid until the next call
140380  ** to xNext() or xClose().
140381  */
140382  /* TODO(shess) current implementation requires pInput to be
140383  ** nul-terminated. This should either be fixed, or pInput/nBytes
140384  ** should be converted to zInput.
140385  */
140386  int (*xNext)(
140387  sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
140388  const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
140389  int *piStartOffset, /* OUT: Byte offset of token in input buffer */
140390  int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
140391  int *piPosition /* OUT: Number of tokens returned before this one */
140392  );
140393 
140394  /***********************************************************************
140395  ** Methods below this point are only available if iVersion>=1.
140396  */
140397 
140398  /*
140399  ** Configure the language id of a tokenizer cursor.
140400  */
140401  int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
140402 };
140403 
140404 struct sqlite3_tokenizer {
140405  const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
140406  /* Tokenizer implementations will typically add additional fields */
140407 };
140408 
140409 struct sqlite3_tokenizer_cursor {
140410  sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
140411  /* Tokenizer implementations will typically add additional fields */
140412 };
140413 
140414 int fts3_global_term_cnt(int iTerm, int iCol);
140415 int fts3_term_cnt(int iTerm, int iCol);
140416 
140417 
140418 #endif /* _FTS3_TOKENIZER_H_ */
140419 
140420 /************** End of fts3_tokenizer.h **************************************/
140421 /************** Continuing where we left off in fts3Int.h ********************/
140422 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
140423 /************** Begin file fts3_hash.h ***************************************/
140424 /*
140425 ** 2001 September 22
140426 **
140427 ** The author disclaims copyright to this source code. In place of
140428 ** a legal notice, here is a blessing:
140429 **
140430 ** May you do good and not evil.
140431 ** May you find forgiveness for yourself and forgive others.
140432 ** May you share freely, never taking more than you give.
140433 **
140434 *************************************************************************
140435 ** This is the header file for the generic hash-table implementation
140436 ** used in SQLite. We've modified it slightly to serve as a standalone
140437 ** hash table implementation for the full-text indexing module.
140438 **
140439 */
140440 #ifndef _FTS3_HASH_H_
140441 #define _FTS3_HASH_H_
140442 
140443 /* Forward declarations of structures. */
140444 typedef struct Fts3Hash Fts3Hash;
140445 typedef struct Fts3HashElem Fts3HashElem;
140446 
140447 /* A complete hash table is an instance of the following structure.
140448 ** The internals of this structure are intended to be opaque -- client
140449 ** code should not attempt to access or modify the fields of this structure
140450 ** directly. Change this structure only by using the routines below.
140451 ** However, many of the "procedures" and "functions" for modifying and
140452 ** accessing this structure are really macros, so we can't really make
140453 ** this structure opaque.
140454 */
140455 struct Fts3Hash {
140456  char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
140457  char copyKey; /* True if copy of key made on insert */
140458  int count; /* Number of entries in this table */
140459  Fts3HashElem *first; /* The first element of the array */
140460  int htsize; /* Number of buckets in the hash table */
140461  struct _fts3ht { /* the hash table */
140462  int count; /* Number of entries with this hash */
140463  Fts3HashElem *chain; /* Pointer to first entry with this hash */
140464  } *ht;
140465 };
140466 
140467 /* Each element in the hash table is an instance of the following
140468 ** structure. All elements are stored on a single doubly-linked list.
140469 **
140470 ** Again, this structure is intended to be opaque, but it can't really
140471 ** be opaque because it is used by macros.
140472 */
140473 struct Fts3HashElem {
140474  Fts3HashElem *next, *prev; /* Next and previous elements in the table */
140475  void *data; /* Data associated with this element */
140476  void *pKey; int nKey; /* Key associated with this element */
140477 };
140478 
140479 /*
140480 ** There are 2 different modes of operation for a hash table:
140481 **
140482 ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
140483 ** (including the null-terminator, if any). Case
140484 ** is respected in comparisons.
140485 **
140486 ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
140487 ** memcmp() is used to compare keys.
140488 **
140489 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
140490 */
140491 #define FTS3_HASH_STRING 1
140492 #define FTS3_HASH_BINARY 2
140493 
140494 /*
140495 ** Access routines. To delete, insert a NULL pointer.
140496 */
140497 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
140498 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
140499 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
140500 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
140501 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
140502 
140503 /*
140504 ** Shorthand for the functions above
140505 */
140506 #define fts3HashInit sqlite3Fts3HashInit
140507 #define fts3HashInsert sqlite3Fts3HashInsert
140508 #define fts3HashFind sqlite3Fts3HashFind
140509 #define fts3HashClear sqlite3Fts3HashClear
140510 #define fts3HashFindElem sqlite3Fts3HashFindElem
140511 
140512 /*
140513 ** Macros for looping over all elements of a hash table. The idiom is
140514 ** like this:
140515 **
140516 ** Fts3Hash h;
140517 ** Fts3HashElem *p;
140518 ** ...
140519 ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
140520 ** SomeStructure *pData = fts3HashData(p);
140521 ** // do something with pData
140522 ** }
140523 */
140524 #define fts3HashFirst(H) ((H)->first)
140525 #define fts3HashNext(E) ((E)->next)
140526 #define fts3HashData(E) ((E)->data)
140527 #define fts3HashKey(E) ((E)->pKey)
140528 #define fts3HashKeysize(E) ((E)->nKey)
140529 
140530 /*
140531 ** Number of entries in a hash table
140532 */
140533 #define fts3HashCount(H) ((H)->count)
140534 
140535 #endif /* _FTS3_HASH_H_ */
140536 
140537 /************** End of fts3_hash.h *******************************************/
140538 /************** Continuing where we left off in fts3Int.h ********************/
140539 
140540 /*
140541 ** This constant determines the maximum depth of an FTS expression tree
140542 ** that the library will create and use. FTS uses recursion to perform
140543 ** various operations on the query tree, so the disadvantage of a large
140544 ** limit is that it may allow very large queries to use large amounts
140545 ** of stack space (perhaps causing a stack overflow).
140546 */
140547 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
140548 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
140549 #endif
140550 
140551 
140552 /*
140553 ** This constant controls how often segments are merged. Once there are
140554 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
140555 ** segment of level N+1.
140556 */
140557 #define FTS3_MERGE_COUNT 16
140558 
140559 /*
140560 ** This is the maximum amount of data (in bytes) to store in the
140561 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
140562 ** populated as documents are inserted/updated/deleted in a transaction
140563 ** and used to create a new segment when the transaction is committed.
140564 ** However if this limit is reached midway through a transaction, a new
140565 ** segment is created and the hash table cleared immediately.
140566 */
140567 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
140568 
140569 /*
140570 ** Macro to return the number of elements in an array. SQLite has a
140571 ** similar macro called ArraySize(). Use a different name to avoid
140572 ** a collision when building an amalgamation with built-in FTS3.
140573 */
140574 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
140575 
140576 
140577 #ifndef MIN
140578 # define MIN(x,y) ((x)<(y)?(x):(y))
140579 #endif
140580 #ifndef MAX
140581 # define MAX(x,y) ((x)>(y)?(x):(y))
140582 #endif
140583 
140584 /*
140585 ** Maximum length of a varint encoded integer. The varint format is different
140586 ** from that used by SQLite, so the maximum length is 10, not 9.
140587 */
140588 #define FTS3_VARINT_MAX 10
140589 
140590 /*
140591 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
140592 ** in the document set and zero or more prefix indexes. All indexes are stored
140593 ** as one or more b+-trees in the %_segments and %_segdir tables.
140594 **
140595 ** It is possible to determine which index a b+-tree belongs to based on the
140596 ** value stored in the "%_segdir.level" column. Given this value L, the index
140597 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
140598 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
140599 ** between 1024 and 2047 to index 1, and so on.
140600 **
140601 ** It is considered impossible for an index to use more than 1024 levels. In
140602 ** theory though this may happen, but only after at least
140603 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
140604 */
140605 #define FTS3_SEGDIR_MAXLEVEL 1024
140606 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
140607 
140608 /*
140609 ** The testcase() macro is only used by the amalgamation. If undefined,
140610 ** make it a no-op.
140611 */
140612 #ifndef testcase
140613 # define testcase(X)
140614 #endif
140615 
140616 /*
140617 ** Terminator values for position-lists and column-lists.
140618 */
140619 #define POS_COLUMN (1) /* Column-list terminator */
140620 #define POS_END (0) /* Position-list terminator */
140621 
140622 /*
140623 ** This section provides definitions to allow the
140624 ** FTS3 extension to be compiled outside of the
140625 ** amalgamation.
140626 */
140627 #ifndef SQLITE_AMALGAMATION
140628 /*
140629 ** Macros indicating that conditional expressions are always true or
140630 ** false.
140631 */
140632 #ifdef SQLITE_COVERAGE_TEST
140633 # define ALWAYS(x) (1)
140634 # define NEVER(X) (0)
140635 #elif defined(SQLITE_DEBUG)
140636 # define ALWAYS(x) sqlite3Fts3Always((x)!=0)
140637 # define NEVER(x) sqlite3Fts3Never((x)!=0)
140638 SQLITE_PRIVATE int sqlite3Fts3Always(int b);
140639 SQLITE_PRIVATE int sqlite3Fts3Never(int b);
140640 #else
140641 # define ALWAYS(x) (x)
140642 # define NEVER(x) (x)
140643 #endif
140644 
140645 /*
140646 ** Internal types used by SQLite.
140647 */
140648 typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
140649 typedef short int i16; /* 2-byte (or larger) signed integer */
140650 typedef unsigned int u32; /* 4-byte unsigned integer */
140651 typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
140652 typedef sqlite3_int64 i64; /* 8-byte signed integer */
140653 
140654 /*
140655 ** Macro used to suppress compiler warnings for unused parameters.
140656 */
140657 #define UNUSED_PARAMETER(x) (void)(x)
140658 
140659 /*
140660 ** Activate assert() only if SQLITE_TEST is enabled.
140661 */
140662 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
140663 # define NDEBUG 1
140664 #endif
140665 
140666 /*
140667 ** The TESTONLY macro is used to enclose variable declarations or
140668 ** other bits of code that are needed to support the arguments
140669 ** within testcase() and assert() macros.
140670 */
140671 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
140672 # define TESTONLY(X) X
140673 #else
140674 # define TESTONLY(X)
140675 #endif
140676 
140677 #endif /* SQLITE_AMALGAMATION */
140678 
140679 #ifdef SQLITE_DEBUG
140680 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
140681 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
140682 #else
140683 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
140684 #endif
140685 
140686 typedef struct Fts3Table Fts3Table;
140687 typedef struct Fts3Cursor Fts3Cursor;
140688 typedef struct Fts3Expr Fts3Expr;
140689 typedef struct Fts3Phrase Fts3Phrase;
140690 typedef struct Fts3PhraseToken Fts3PhraseToken;
140691 
140692 typedef struct Fts3Doclist Fts3Doclist;
140693 typedef struct Fts3SegFilter Fts3SegFilter;
140694 typedef struct Fts3DeferredToken Fts3DeferredToken;
140695 typedef struct Fts3SegReader Fts3SegReader;
140696 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
140697 
140698 typedef struct MatchinfoBuffer MatchinfoBuffer;
140699 
140700 /*
140701 ** A connection to a fulltext index is an instance of the following
140702 ** structure. The xCreate and xConnect methods create an instance
140703 ** of this structure and xDestroy and xDisconnect free that instance.
140704 ** All other methods receive a pointer to the structure as one of their
140705 ** arguments.
140706 */
140707 struct Fts3Table {
140708  sqlite3_vtab base; /* Base class used by SQLite core */
140709  sqlite3 *db; /* The database connection */
140710  const char *zDb; /* logical database name */
140711  const char *zName; /* virtual table name */
140712  int nColumn; /* number of named columns in virtual table */
140713  char **azColumn; /* column names. malloced */
140714  u8 *abNotindexed; /* True for 'notindexed' columns */
140715  sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
140716  char *zContentTbl; /* content=xxx option, or NULL */
140717  char *zLanguageid; /* languageid=xxx option, or NULL */
140718  int nAutoincrmerge; /* Value configured by 'automerge' */
140719  u32 nLeafAdd; /* Number of leaf blocks added this trans */
140720 
140721  /* Precompiled statements used by the implementation. Each of these
140722  ** statements is run and reset within a single virtual table API call.
140723  */
140724  sqlite3_stmt *aStmt[40];
140725 
140726  char *zReadExprlist;
140727  char *zWriteExprlist;
140728 
140729  int nNodeSize; /* Soft limit for node size */
140730  u8 bFts4; /* True for FTS4, false for FTS3 */
140731  u8 bHasStat; /* True if %_stat table exists (2==unknown) */
140732  u8 bHasDocsize; /* True if %_docsize table exists */
140733  u8 bDescIdx; /* True if doclists are in reverse order */
140734  u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
140735  int nPgsz; /* Page size for host database */
140736  char *zSegmentsTbl; /* Name of %_segments table */
140737  sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
140738 
140739  /*
140740  ** The following array of hash tables is used to buffer pending index
140741  ** updates during transactions. All pending updates buffered at any one
140742  ** time must share a common language-id (see the FTS4 langid= feature).
140743  ** The current language id is stored in variable iPrevLangid.
140744  **
140745  ** A single FTS4 table may have multiple full-text indexes. For each index
140746  ** there is an entry in the aIndex[] array. Index 0 is an index of all the
140747  ** terms that appear in the document set. Each subsequent index in aIndex[]
140748  ** is an index of prefixes of a specific length.
140749  **
140750  ** Variable nPendingData contains an estimate the memory consumed by the
140751  ** pending data structures, including hash table overhead, but not including
140752  ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
140753  ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
140754  ** recently inserted record.
140755  */
140756  int nIndex; /* Size of aIndex[] */
140757  struct Fts3Index {
140758  int nPrefix; /* Prefix length (0 for main terms index) */
140759  Fts3Hash hPending; /* Pending terms table for this index */
140760  } *aIndex;
140761  int nMaxPendingData; /* Max pending data before flush to disk */
140762  int nPendingData; /* Current bytes of pending data */
140763  sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
140764  int iPrevLangid; /* Langid of recently inserted document */
140765  int bPrevDelete; /* True if last operation was a delete */
140766 
140767 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
140768  /* State variables used for validating that the transaction control
140769  ** methods of the virtual table are called at appropriate times. These
140770  ** values do not contribute to FTS functionality; they are used for
140771  ** verifying the operation of the SQLite core.
140772  */
140773  int inTransaction; /* True after xBegin but before xCommit/xRollback */
140774  int mxSavepoint; /* Largest valid xSavepoint integer */
140775 #endif
140776 
140777 #ifdef SQLITE_TEST
140778  /* True to disable the incremental doclist optimization. This is controled
140779  ** by special insert command 'test-no-incr-doclist'. */
140780  int bNoIncrDoclist;
140781 #endif
140782 };
140783 
140784 /*
140785 ** When the core wants to read from the virtual table, it creates a
140786 ** virtual table cursor (an instance of the following structure) using
140787 ** the xOpen method. Cursors are destroyed using the xClose method.
140788 */
140789 struct Fts3Cursor {
140790  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
140791  i16 eSearch; /* Search strategy (see below) */
140792  u8 isEof; /* True if at End Of Results */
140793  u8 isRequireSeek; /* True if must seek pStmt to %_content row */
140794  sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
140795  Fts3Expr *pExpr; /* Parsed MATCH query string */
140796  int iLangid; /* Language being queried for */
140797  int nPhrase; /* Number of matchable phrases in query */
140798  Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
140799  sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
140800  char *pNextId; /* Pointer into the body of aDoclist */
140801  char *aDoclist; /* List of docids for full-text queries */
140802  int nDoclist; /* Size of buffer at aDoclist */
140803  u8 bDesc; /* True to sort in descending order */
140804  int eEvalmode; /* An FTS3_EVAL_XX constant */
140805  int nRowAvg; /* Average size of database rows, in pages */
140806  sqlite3_int64 nDoc; /* Documents in table */
140807  i64 iMinDocid; /* Minimum docid to return */
140808  i64 iMaxDocid; /* Maximum docid to return */
140809  int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
140810  MatchinfoBuffer *pMIBuffer; /* Buffer for matchinfo data */
140811 };
140812 
140813 #define FTS3_EVAL_FILTER 0
140814 #define FTS3_EVAL_NEXT 1
140815 #define FTS3_EVAL_MATCHINFO 2
140816 
140817 /*
140818 ** The Fts3Cursor.eSearch member is always set to one of the following.
140819 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
140820 ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
140821 ** of the column to be searched. For example, in
140822 **
140823 ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
140824 ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
140825 **
140826 ** Because the LHS of the MATCH operator is 2nd column "b",
140827 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
140828 ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
140829 ** indicating that all columns should be searched,
140830 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
140831 */
140832 #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
140833 #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
140834 #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
140835 
140836 /*
140837 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
140838 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
140839 ** above. The upper 16-bits contain a combination of the following
140840 ** bits, used to describe extra constraints on full-text searches.
140841 */
140842 #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
140843 #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
140844 #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
140845 
140846 struct Fts3Doclist {
140847  char *aAll; /* Array containing doclist (or NULL) */
140848  int nAll; /* Size of a[] in bytes */
140849  char *pNextDocid; /* Pointer to next docid */
140850 
140851  sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
140852  int bFreeList; /* True if pList should be sqlite3_free()d */
140853  char *pList; /* Pointer to position list following iDocid */
140854  int nList; /* Length of position list */
140855 };
140856 
140857 /*
140858 ** A "phrase" is a sequence of one or more tokens that must match in
140859 ** sequence. A single token is the base case and the most common case.
140860 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
140861 ** nToken will be the number of tokens in the string.
140862 */
140863 struct Fts3PhraseToken {
140864  char *z; /* Text of the token */
140865  int n; /* Number of bytes in buffer z */
140866  int isPrefix; /* True if token ends with a "*" character */
140867  int bFirst; /* True if token must appear at position 0 */
140868 
140869  /* Variables above this point are populated when the expression is
140870  ** parsed (by code in fts3_expr.c). Below this point the variables are
140871  ** used when evaluating the expression. */
140872  Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
140873  Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
140874 };
140875 
140876 struct Fts3Phrase {
140877  /* Cache of doclist for this phrase. */
140878  Fts3Doclist doclist;
140879  int bIncr; /* True if doclist is loaded incrementally */
140880  int iDoclistToken;
140881 
140882  /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
140883  ** OR condition. */
140884  char *pOrPoslist;
140885  i64 iOrDocid;
140886 
140887  /* Variables below this point are populated by fts3_expr.c when parsing
140888  ** a MATCH expression. Everything above is part of the evaluation phase.
140889  */
140890  int nToken; /* Number of tokens in the phrase */
140891  int iColumn; /* Index of column this phrase must match */
140892  Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
140893 };
140894 
140895 /*
140896 ** A tree of these objects forms the RHS of a MATCH operator.
140897 **
140898 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
140899 ** points to a malloced buffer, size nDoclist bytes, containing the results
140900 ** of this phrase query in FTS3 doclist format. As usual, the initial
140901 ** "Length" field found in doclists stored on disk is omitted from this
140902 ** buffer.
140903 **
140904 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
140905 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
140906 ** where nCol is the number of columns in the queried FTS table. The array
140907 ** is populated as follows:
140908 **
140909 ** aMI[iCol*3 + 0] = Undefined
140910 ** aMI[iCol*3 + 1] = Number of occurrences
140911 ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
140912 **
140913 ** The aMI array is allocated using sqlite3_malloc(). It should be freed
140914 ** when the expression node is.
140915 */
140916 struct Fts3Expr {
140917  int eType; /* One of the FTSQUERY_XXX values defined below */
140918  int nNear; /* Valid if eType==FTSQUERY_NEAR */
140919  Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
140920  Fts3Expr *pLeft; /* Left operand */
140921  Fts3Expr *pRight; /* Right operand */
140922  Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
140923 
140924  /* The following are used by the fts3_eval.c module. */
140925  sqlite3_int64 iDocid; /* Current docid */
140926  u8 bEof; /* True this expression is at EOF already */
140927  u8 bStart; /* True if iDocid is valid */
140928  u8 bDeferred; /* True if this expression is entirely deferred */
140929 
140930  /* The following are used by the fts3_snippet.c module. */
140931  int iPhrase; /* Index of this phrase in matchinfo() results */
140932  u32 *aMI; /* See above */
140933 };
140934 
140935 /*
140936 ** Candidate values for Fts3Query.eType. Note that the order of the first
140937 ** four values is in order of precedence when parsing expressions. For
140938 ** example, the following:
140939 **
140940 ** "a OR b AND c NOT d NEAR e"
140941 **
140942 ** is equivalent to:
140943 **
140944 ** "a OR (b AND (c NOT (d NEAR e)))"
140945 */
140946 #define FTSQUERY_NEAR 1
140947 #define FTSQUERY_NOT 2
140948 #define FTSQUERY_AND 3
140949 #define FTSQUERY_OR 4
140950 #define FTSQUERY_PHRASE 5
140951 
140952 
140953 /* fts3_write.c */
140954 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
140955 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
140956 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
140957 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
140958 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
140959  sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
140960 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
140961  Fts3Table*,int,const char*,int,int,Fts3SegReader**);
140962 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
140963 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
140964 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
140965 
140966 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
140967 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
140968 
140969 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
140970 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
140971 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
140972 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
140973 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
140974 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
140975 #else
140976 # define sqlite3Fts3FreeDeferredTokens(x)
140977 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
140978 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
140979 # define sqlite3Fts3FreeDeferredDoclists(x)
140980 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
140981 #endif
140982 
140983 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
140984 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
140985 
140986 /* Special values interpreted by sqlite3SegReaderCursor() */
140987 #define FTS3_SEGCURSOR_PENDING -1
140988 #define FTS3_SEGCURSOR_ALL -2
140989 
140990 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
140991 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
140992 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
140993 
140994 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
140995  int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
140996 
140997 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
140998 #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
140999 #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
141000 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
141001 #define FTS3_SEGMENT_PREFIX 0x00000008
141002 #define FTS3_SEGMENT_SCAN 0x00000010
141003 #define FTS3_SEGMENT_FIRST 0x00000020
141004 
141005 /* Type passed as 4th argument to SegmentReaderIterate() */
141006 struct Fts3SegFilter {
141007  const char *zTerm;
141008  int nTerm;
141009  int iCol;
141010  int flags;
141011 };
141012 
141013 struct Fts3MultiSegReader {
141014  /* Used internally by sqlite3Fts3SegReaderXXX() calls */
141015  Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
141016  int nSegment; /* Size of apSegment array */
141017  int nAdvance; /* How many seg-readers to advance */
141018  Fts3SegFilter *pFilter; /* Pointer to filter object */
141019  char *aBuffer; /* Buffer to merge doclists in */
141020  int nBuffer; /* Allocated size of aBuffer[] in bytes */
141021 
141022  int iColFilter; /* If >=0, filter for this column */
141023  int bRestart;
141024 
141025  /* Used by fts3.c only. */
141026  int nCost; /* Cost of running iterator */
141027  int bLookup; /* True if a lookup of a single entry. */
141028 
141029  /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
141030  char *zTerm; /* Pointer to term buffer */
141031  int nTerm; /* Size of zTerm in bytes */
141032  char *aDoclist; /* Pointer to doclist buffer */
141033  int nDoclist; /* Size of aDoclist[] in bytes */
141034 };
141035 
141036 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
141037 
141038 #define fts3GetVarint32(p, piVal) ( \
141039  (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
141040 )
141041 
141042 /* fts3.c */
141043 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char**,const char*,...);
141044 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
141045 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
141046 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
141047 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
141048 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
141049 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
141050 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
141051 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
141052 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
141053 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc);
141054 
141055 /* fts3_tokenizer.c */
141056 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
141057 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
141058 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
141059  sqlite3_tokenizer **, char **
141060 );
141061 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
141062 
141063 /* fts3_snippet.c */
141064 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
141065 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
141066  const char *, const char *, int, int
141067 );
141068 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
141069 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p);
141070 
141071 /* fts3_expr.c */
141072 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
141073  char **, int, int, int, const char *, int, Fts3Expr **, char **
141074 );
141075 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
141076 #ifdef SQLITE_TEST
141077 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
141078 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
141079 #endif
141080 
141081 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
141082  sqlite3_tokenizer_cursor **
141083 );
141084 
141085 /* fts3_aux.c */
141086 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
141087 
141088 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
141089 
141090 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
141091  Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
141092 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
141093  Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
141094 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
141095 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
141096 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
141097 
141098 /* fts3_tokenize_vtab.c */
141099 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
141100 
141101 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
141102 #ifndef SQLITE_DISABLE_FTS3_UNICODE
141103 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
141104 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
141105 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
141106 #endif
141107 
141108 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
141109 #endif /* _FTSINT_H */
141110 
141111 /************** End of fts3Int.h *********************************************/
141112 /************** Continuing where we left off in fts3.c ***********************/
141113 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141114 
141115 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
141116 # define SQLITE_CORE 1
141117 #endif
141118 
141119 /* #include <assert.h> */
141120 /* #include <stdlib.h> */
141121 /* #include <stddef.h> */
141122 /* #include <stdio.h> */
141123 /* #include <string.h> */
141124 /* #include <stdarg.h> */
141125 
141126 /* #include "fts3.h" */
141127 #ifndef SQLITE_CORE
141128 /* # include "sqlite3ext.h" */
141130 #endif
141131 
141132 static int fts3EvalNext(Fts3Cursor *pCsr);
141133 static int fts3EvalStart(Fts3Cursor *pCsr);
141134 static int fts3TermSegReaderCursor(
141135  Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
141136 
141137 #ifndef SQLITE_AMALGAMATION
141138 # if defined(SQLITE_DEBUG)
141139 SQLITE_PRIVATE int sqlite3Fts3Always(int b) { assert( b ); return b; }
141140 SQLITE_PRIVATE int sqlite3Fts3Never(int b) { assert( !b ); return b; }
141141 # endif
141142 #endif
141143 
141144 /*
141145 ** Write a 64-bit variable-length integer to memory starting at p[0].
141146 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
141147 ** The number of bytes written is returned.
141148 */
141149 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
141150  unsigned char *q = (unsigned char *) p;
141151  sqlite_uint64 vu = v;
141152  do{
141153  *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
141154  vu >>= 7;
141155  }while( vu!=0 );
141156  q[-1] &= 0x7f; /* turn off high bit in final byte */
141157  assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
141158  return (int) (q - (unsigned char *)p);
141159 }
141160 
141161 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
141162  v = (v & mask1) | ( (*ptr++) << shift ); \
141163  if( (v & mask2)==0 ){ var = v; return ret; }
141164 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
141165  v = (*ptr++); \
141166  if( (v & mask2)==0 ){ var = v; return ret; }
141167 
141168 /*
141169 ** Read a 64-bit variable-length integer from memory starting at p[0].
141170 ** Return the number of bytes read, or 0 on error.
141171 ** The value is stored in *v.
141172 */
141173 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
141174  const char *pStart = p;
141175  u32 a;
141176  u64 b;
141177  int shift;
141178 
141179  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
141180  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
141181  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
141182  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
141183  b = (a & 0x0FFFFFFF );
141184 
141185  for(shift=28; shift<=63; shift+=7){
141186  u64 c = *p++;
141187  b += (c&0x7F) << shift;
141188  if( (c & 0x80)==0 ) break;
141189  }
141190  *v = b;
141191  return (int)(p - pStart);
141192 }
141193 
141194 /*
141195 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
141196 ** 32-bit integer before it is returned.
141197 */
141198 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
141199  u32 a;
141200 
141201 #ifndef fts3GetVarint32
141202  GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
141203 #else
141204  a = (*p++);
141205  assert( a & 0x80 );
141206 #endif
141207 
141208  GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
141209  GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
141210  GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
141211  a = (a & 0x0FFFFFFF );
141212  *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
141213  return 5;
141214 }
141215 
141216 /*
141217 ** Return the number of bytes required to encode v as a varint
141218 */
141219 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
141220  int i = 0;
141221  do{
141222  i++;
141223  v >>= 7;
141224  }while( v!=0 );
141225  return i;
141226 }
141227 
141228 /*
141229 ** Convert an SQL-style quoted string into a normal string by removing
141230 ** the quote characters. The conversion is done in-place. If the
141231 ** input does not begin with a quote character, then this routine
141232 ** is a no-op.
141233 **
141234 ** Examples:
141235 **
141236 ** "abc" becomes abc
141237 ** 'xyz' becomes xyz
141238 ** [pqr] becomes pqr
141239 ** `mno` becomes mno
141240 **
141241 */
141242 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
141243  char quote; /* Quote character (if any ) */
141244 
141245  quote = z[0];
141246  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
141247  int iIn = 1; /* Index of next byte to read from input */
141248  int iOut = 0; /* Index of next byte to write to output */
141249 
141250  /* If the first byte was a '[', then the close-quote character is a ']' */
141251  if( quote=='[' ) quote = ']';
141252 
141253  while( z[iIn] ){
141254  if( z[iIn]==quote ){
141255  if( z[iIn+1]!=quote ) break;
141256  z[iOut++] = quote;
141257  iIn += 2;
141258  }else{
141259  z[iOut++] = z[iIn++];
141260  }
141261  }
141262  z[iOut] = '\0';
141263  }
141264 }
141265 
141266 /*
141267 ** Read a single varint from the doclist at *pp and advance *pp to point
141268 ** to the first byte past the end of the varint. Add the value of the varint
141269 ** to *pVal.
141270 */
141271 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
141272  sqlite3_int64 iVal;
141273  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
141274  *pVal += iVal;
141275 }
141276 
141277 /*
141278 ** When this function is called, *pp points to the first byte following a
141279 ** varint that is part of a doclist (or position-list, or any other list
141280 ** of varints). This function moves *pp to point to the start of that varint,
141281 ** and sets *pVal by the varint value.
141282 **
141283 ** Argument pStart points to the first byte of the doclist that the
141284 ** varint is part of.
141285 */
141286 static void fts3GetReverseVarint(
141287  char **pp,
141288  char *pStart,
141289  sqlite3_int64 *pVal
141290 ){
141291  sqlite3_int64 iVal;
141292  char *p;
141293 
141294  /* Pointer p now points at the first byte past the varint we are
141295  ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
141296  ** clear on character p[-1]. */
141297  for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
141298  p++;
141299  *pp = p;
141300 
141301  sqlite3Fts3GetVarint(p, &iVal);
141302  *pVal = iVal;
141303 }
141304 
141305 /*
141306 ** The xDisconnect() virtual table method.
141307 */
141308 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
141309  Fts3Table *p = (Fts3Table *)pVtab;
141310  int i;
141311 
141312  assert( p->nPendingData==0 );
141313  assert( p->pSegments==0 );
141314 
141315  /* Free any prepared statements held */
141316  for(i=0; i<SizeofArray(p->aStmt); i++){
141317  sqlite3_finalize(p->aStmt[i]);
141318  }
141319  sqlite3_free(p->zSegmentsTbl);
141320  sqlite3_free(p->zReadExprlist);
141321  sqlite3_free(p->zWriteExprlist);
141322  sqlite3_free(p->zContentTbl);
141323  sqlite3_free(p->zLanguageid);
141324 
141325  /* Invoke the tokenizer destructor to free the tokenizer. */
141326  p->pTokenizer->pModule->xDestroy(p->pTokenizer);
141327 
141328  sqlite3_free(p);
141329  return SQLITE_OK;
141330 }
141331 
141332 /*
141333 ** Write an error message into *pzErr
141334 */
141335 SQLITE_PRIVATE void sqlite3Fts3ErrMsg(char **pzErr, const char *zFormat, ...){
141336  va_list ap;
141337  sqlite3_free(*pzErr);
141338  va_start(ap, zFormat);
141339  *pzErr = sqlite3_vmprintf(zFormat, ap);
141340  va_end(ap);
141341 }
141342 
141343 /*
141344 ** Construct one or more SQL statements from the format string given
141345 ** and then evaluate those statements. The success code is written
141346 ** into *pRc.
141347 **
141348 ** If *pRc is initially non-zero then this routine is a no-op.
141349 */
141350 static void fts3DbExec(
141351  int *pRc, /* Success code */
141352  sqlite3 *db, /* Database in which to run SQL */
141353  const char *zFormat, /* Format string for SQL */
141354  ... /* Arguments to the format string */
141355 ){
141356  va_list ap;
141357  char *zSql;
141358  if( *pRc ) return;
141359  va_start(ap, zFormat);
141360  zSql = sqlite3_vmprintf(zFormat, ap);
141361  va_end(ap);
141362  if( zSql==0 ){
141363  *pRc = SQLITE_NOMEM;
141364  }else{
141365  *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
141366  sqlite3_free(zSql);
141367  }
141368 }
141369 
141370 /*
141371 ** The xDestroy() virtual table method.
141372 */
141373 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
141374  Fts3Table *p = (Fts3Table *)pVtab;
141375  int rc = SQLITE_OK; /* Return code */
141376  const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
141377  sqlite3 *db = p->db; /* Database handle */
141378 
141379  /* Drop the shadow tables */
141380  if( p->zContentTbl==0 ){
141381  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
141382  }
141383  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
141384  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
141385  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
141386  fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
141387 
141388  /* If everything has worked, invoke fts3DisconnectMethod() to free the
141389  ** memory associated with the Fts3Table structure and return SQLITE_OK.
141390  ** Otherwise, return an SQLite error code.
141391  */
141392  return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
141393 }
141394 
141395 
141396 /*
141397 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
141398 ** passed as the first argument. This is done as part of the xConnect()
141399 ** and xCreate() methods.
141400 **
141401 ** If *pRc is non-zero when this function is called, it is a no-op.
141402 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
141403 ** before returning.
141404 */
141405 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
141406  if( *pRc==SQLITE_OK ){
141407  int i; /* Iterator variable */
141408  int rc; /* Return code */
141409  char *zSql; /* SQL statement passed to declare_vtab() */
141410  char *zCols; /* List of user defined columns */
141411  const char *zLanguageid;
141412 
141413  zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
141415 
141416  /* Create a list of user columns for the virtual table */
141417  zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
141418  for(i=1; zCols && i<p->nColumn; i++){
141419  zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
141420  }
141421 
141422  /* Create the whole "CREATE TABLE" statement to pass to SQLite */
141423  zSql = sqlite3_mprintf(
141424  "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
141425  zCols, p->zName, zLanguageid
141426  );
141427  if( !zCols || !zSql ){
141428  rc = SQLITE_NOMEM;
141429  }else{
141430  rc = sqlite3_declare_vtab(p->db, zSql);
141431  }
141432 
141433  sqlite3_free(zSql);
141434  sqlite3_free(zCols);
141435  *pRc = rc;
141436  }
141437 }
141438 
141439 /*
141440 ** Create the %_stat table if it does not already exist.
141441 */
141442 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
141443  fts3DbExec(pRc, p->db,
141444  "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
141445  "(id INTEGER PRIMARY KEY, value BLOB);",
141446  p->zDb, p->zName
141447  );
141448  if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
141449 }
141450 
141451 /*
141452 ** Create the backing store tables (%_content, %_segments and %_segdir)
141453 ** required by the FTS3 table passed as the only argument. This is done
141454 ** as part of the vtab xCreate() method.
141455 **
141456 ** If the p->bHasDocsize boolean is true (indicating that this is an
141457 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
141458 ** %_stat tables required by FTS4.
141459 */
141460 static int fts3CreateTables(Fts3Table *p){
141461  int rc = SQLITE_OK; /* Return code */
141462  int i; /* Iterator variable */
141463  sqlite3 *db = p->db; /* The database connection */
141464 
141465  if( p->zContentTbl==0 ){
141466  const char *zLanguageid = p->zLanguageid;
141467  char *zContentCols; /* Columns of %_content table */
141468 
141469  /* Create a list of user columns for the content table */
141470  zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
141471  for(i=0; zContentCols && i<p->nColumn; i++){
141472  char *z = p->azColumn[i];
141473  zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
141474  }
141475  if( zLanguageid && zContentCols ){
141476  zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
141477  }
141478  if( zContentCols==0 ) rc = SQLITE_NOMEM;
141479 
141480  /* Create the content table */
141481  fts3DbExec(&rc, db,
141482  "CREATE TABLE %Q.'%q_content'(%s)",
141483  p->zDb, p->zName, zContentCols
141484  );
141485  sqlite3_free(zContentCols);
141486  }
141487 
141488  /* Create other tables */
141489  fts3DbExec(&rc, db,
141490  "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
141491  p->zDb, p->zName
141492  );
141493  fts3DbExec(&rc, db,
141494  "CREATE TABLE %Q.'%q_segdir'("
141495  "level INTEGER,"
141496  "idx INTEGER,"
141497  "start_block INTEGER,"
141498  "leaves_end_block INTEGER,"
141499  "end_block INTEGER,"
141500  "root BLOB,"
141501  "PRIMARY KEY(level, idx)"
141502  ");",
141503  p->zDb, p->zName
141504  );
141505  if( p->bHasDocsize ){
141506  fts3DbExec(&rc, db,
141507  "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
141508  p->zDb, p->zName
141509  );
141510  }
141511  assert( p->bHasStat==p->bFts4 );
141512  if( p->bHasStat ){
141513  sqlite3Fts3CreateStatTable(&rc, p);
141514  }
141515  return rc;
141516 }
141517 
141518 /*
141519 ** Store the current database page-size in bytes in p->nPgsz.
141520 **
141521 ** If *pRc is non-zero when this function is called, it is a no-op.
141522 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
141523 ** before returning.
141524 */
141525 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
141526  if( *pRc==SQLITE_OK ){
141527  int rc; /* Return code */
141528  char *zSql; /* SQL text "PRAGMA %Q.page_size" */
141529  sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
141530 
141531  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
141532  if( !zSql ){
141533  rc = SQLITE_NOMEM;
141534  }else{
141535  rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
141536  if( rc==SQLITE_OK ){
141537  sqlite3_step(pStmt);
141538  p->nPgsz = sqlite3_column_int(pStmt, 0);
141539  rc = sqlite3_finalize(pStmt);
141540  }else if( rc==SQLITE_AUTH ){
141541  p->nPgsz = 1024;
141542  rc = SQLITE_OK;
141543  }
141544  }
141545  assert( p->nPgsz>0 || rc!=SQLITE_OK );
141546  sqlite3_free(zSql);
141547  *pRc = rc;
141548  }
141549 }
141550 
141551 /*
141552 ** "Special" FTS4 arguments are column specifications of the following form:
141553 **
141554 ** <key> = <value>
141555 **
141556 ** There may not be whitespace surrounding the "=" character. The <value>
141557 ** term may be quoted, but the <key> may not.
141558 */
141559 static int fts3IsSpecialColumn(
141560  const char *z,
141561  int *pnKey,
141562  char **pzValue
141563 ){
141564  char *zValue;
141565  const char *zCsr = z;
141566 
141567  while( *zCsr!='=' ){
141568  if( *zCsr=='\0' ) return 0;
141569  zCsr++;
141570  }
141571 
141572  *pnKey = (int)(zCsr-z);
141573  zValue = sqlite3_mprintf("%s", &zCsr[1]);
141574  if( zValue ){
141575  sqlite3Fts3Dequote(zValue);
141576  }
141577  *pzValue = zValue;
141578  return 1;
141579 }
141580 
141581 /*
141582 ** Append the output of a printf() style formatting to an existing string.
141583 */
141584 static void fts3Appendf(
141585  int *pRc, /* IN/OUT: Error code */
141586  char **pz, /* IN/OUT: Pointer to string buffer */
141587  const char *zFormat, /* Printf format string to append */
141588  ... /* Arguments for printf format string */
141589 ){
141590  if( *pRc==SQLITE_OK ){
141591  va_list ap;
141592  char *z;
141593  va_start(ap, zFormat);
141594  z = sqlite3_vmprintf(zFormat, ap);
141595  va_end(ap);
141596  if( z && *pz ){
141597  char *z2 = sqlite3_mprintf("%s%s", *pz, z);
141598  sqlite3_free(z);
141599  z = z2;
141600  }
141601  if( z==0 ) *pRc = SQLITE_NOMEM;
141602  sqlite3_free(*pz);
141603  *pz = z;
141604  }
141605 }
141606 
141607 /*
141608 ** Return a copy of input string zInput enclosed in double-quotes (") and
141609 ** with all double quote characters escaped. For example:
141610 **
141611 ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
141612 **
141613 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
141614 ** is the callers responsibility to call sqlite3_free() to release this
141615 ** memory.
141616 */
141617 static char *fts3QuoteId(char const *zInput){
141618  int nRet;
141619  char *zRet;
141620  nRet = 2 + (int)strlen(zInput)*2 + 1;
141621  zRet = sqlite3_malloc(nRet);
141622  if( zRet ){
141623  int i;
141624  char *z = zRet;
141625  *(z++) = '"';
141626  for(i=0; zInput[i]; i++){
141627  if( zInput[i]=='"' ) *(z++) = '"';
141628  *(z++) = zInput[i];
141629  }
141630  *(z++) = '"';
141631  *(z++) = '\0';
141632  }
141633  return zRet;
141634 }
141635 
141636 /*
141637 ** Return a list of comma separated SQL expressions and a FROM clause that
141638 ** could be used in a SELECT statement such as the following:
141639 **
141640 ** SELECT <list of expressions> FROM %_content AS x ...
141641 **
141642 ** to return the docid, followed by each column of text data in order
141643 ** from left to write. If parameter zFunc is not NULL, then instead of
141644 ** being returned directly each column of text data is passed to an SQL
141645 ** function named zFunc first. For example, if zFunc is "unzip" and the
141646 ** table has the three user-defined columns "a", "b", and "c", the following
141647 ** string is returned:
141648 **
141649 ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
141650 **
141651 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
141652 ** is the responsibility of the caller to eventually free it.
141653 **
141654 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
141655 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
141656 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
141657 ** no error occurs, *pRc is left unmodified.
141658 */
141659 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
141660  char *zRet = 0;
141661  char *zFree = 0;
141662  char *zFunction;
141663  int i;
141664 
141665  if( p->zContentTbl==0 ){
141666  if( !zFunc ){
141667  zFunction = "";
141668  }else{
141669  zFree = zFunction = fts3QuoteId(zFunc);
141670  }
141671  fts3Appendf(pRc, &zRet, "docid");
141672  for(i=0; i<p->nColumn; i++){
141673  fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
141674  }
141675  if( p->zLanguageid ){
141676  fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
141677  }
141678  sqlite3_free(zFree);
141679  }else{
141680  fts3Appendf(pRc, &zRet, "rowid");
141681  for(i=0; i<p->nColumn; i++){
141682  fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
141683  }
141684  if( p->zLanguageid ){
141685  fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
141686  }
141687  }
141688  fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
141689  p->zDb,
141690  (p->zContentTbl ? p->zContentTbl : p->zName),
141691  (p->zContentTbl ? "" : "_content")
141692  );
141693  return zRet;
141694 }
141695 
141696 /*
141697 ** Return a list of N comma separated question marks, where N is the number
141698 ** of columns in the %_content table (one for the docid plus one for each
141699 ** user-defined text column).
141700 **
141701 ** If argument zFunc is not NULL, then all but the first question mark
141702 ** is preceded by zFunc and an open bracket, and followed by a closed
141703 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
141704 ** user-defined text columns, the following string is returned:
141705 **
141706 ** "?, zip(?), zip(?), zip(?)"
141707 **
141708 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
141709 ** is the responsibility of the caller to eventually free it.
141710 **
141711 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
141712 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
141713 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
141714 ** no error occurs, *pRc is left unmodified.
141715 */
141716 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
141717  char *zRet = 0;
141718  char *zFree = 0;
141719  char *zFunction;
141720  int i;
141721 
141722  if( !zFunc ){
141723  zFunction = "";
141724  }else{
141725  zFree = zFunction = fts3QuoteId(zFunc);
141726  }
141727  fts3Appendf(pRc, &zRet, "?");
141728  for(i=0; i<p->nColumn; i++){
141729  fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
141730  }
141731  if( p->zLanguageid ){
141732  fts3Appendf(pRc, &zRet, ", ?");
141733  }
141734  sqlite3_free(zFree);
141735  return zRet;
141736 }
141737 
141738 /*
141739 ** This function interprets the string at (*pp) as a non-negative integer
141740 ** value. It reads the integer and sets *pnOut to the value read, then
141741 ** sets *pp to point to the byte immediately following the last byte of
141742 ** the integer value.
141743 **
141744 ** Only decimal digits ('0'..'9') may be part of an integer value.
141745 **
141746 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
141747 ** the output value undefined. Otherwise SQLITE_OK is returned.
141748 **
141749 ** This function is used when parsing the "prefix=" FTS4 parameter.
141750 */
141751 static int fts3GobbleInt(const char **pp, int *pnOut){
141752  const int MAX_NPREFIX = 10000000;
141753  const char *p; /* Iterator pointer */
141754  int nInt = 0; /* Output value */
141755 
141756  for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
141757  nInt = nInt * 10 + (p[0] - '0');
141758  if( nInt>MAX_NPREFIX ){
141759  nInt = 0;
141760  break;
141761  }
141762  }
141763  if( p==*pp ) return SQLITE_ERROR;
141764  *pnOut = nInt;
141765  *pp = p;
141766  return SQLITE_OK;
141767 }
141768 
141769 /*
141770 ** This function is called to allocate an array of Fts3Index structures
141771 ** representing the indexes maintained by the current FTS table. FTS tables
141772 ** always maintain the main "terms" index, but may also maintain one or
141773 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
141774 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
141775 **
141776 ** Argument zParam is passed the value of the "prefix=" option if one was
141777 ** specified, or NULL otherwise.
141778 **
141779 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
141780 ** the allocated array. *pnIndex is set to the number of elements in the
141781 ** array. If an error does occur, an SQLite error code is returned.
141782 **
141783 ** Regardless of whether or not an error is returned, it is the responsibility
141784 ** of the caller to call sqlite3_free() on the output array to free it.
141785 */
141786 static int fts3PrefixParameter(
141787  const char *zParam, /* ABC in prefix=ABC parameter to parse */
141788  int *pnIndex, /* OUT: size of *apIndex[] array */
141789  struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
141790 ){
141791  struct Fts3Index *aIndex; /* Allocated array */
141792  int nIndex = 1; /* Number of entries in array */
141793 
141794  if( zParam && zParam[0] ){
141795  const char *p;
141796  nIndex++;
141797  for(p=zParam; *p; p++){
141798  if( *p==',' ) nIndex++;
141799  }
141800  }
141801 
141802  aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
141803  *apIndex = aIndex;
141804  if( !aIndex ){
141805  return SQLITE_NOMEM;
141806  }
141807 
141808  memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
141809  if( zParam ){
141810  const char *p = zParam;
141811  int i;
141812  for(i=1; i<nIndex; i++){
141813  int nPrefix = 0;
141814  if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
141815  assert( nPrefix>=0 );
141816  if( nPrefix==0 ){
141817  nIndex--;
141818  i--;
141819  }else{
141820  aIndex[i].nPrefix = nPrefix;
141821  }
141822  p++;
141823  }
141824  }
141825 
141826  *pnIndex = nIndex;
141827  return SQLITE_OK;
141828 }
141829 
141830 /*
141831 ** This function is called when initializing an FTS4 table that uses the
141832 ** content=xxx option. It determines the number of and names of the columns
141833 ** of the new FTS4 table.
141834 **
141835 ** The third argument passed to this function is the value passed to the
141836 ** config=xxx option (i.e. "xxx"). This function queries the database for
141837 ** a table of that name. If found, the output variables are populated
141838 ** as follows:
141839 **
141840 ** *pnCol: Set to the number of columns table xxx has,
141841 **
141842 ** *pnStr: Set to the total amount of space required to store a copy
141843 ** of each columns name, including the nul-terminator.
141844 **
141845 ** *pazCol: Set to point to an array of *pnCol strings. Each string is
141846 ** the name of the corresponding column in table xxx. The array
141847 ** and its contents are allocated using a single allocation. It
141848 ** is the responsibility of the caller to free this allocation
141849 ** by eventually passing the *pazCol value to sqlite3_free().
141850 **
141851 ** If the table cannot be found, an error code is returned and the output
141852 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
141853 ** returned (and the output variables are undefined).
141854 */
141855 static int fts3ContentColumns(
141856  sqlite3 *db, /* Database handle */
141857  const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
141858  const char *zTbl, /* Name of content table */
141859  const char ***pazCol, /* OUT: Malloc'd array of column names */
141860  int *pnCol, /* OUT: Size of array *pazCol */
141861  int *pnStr, /* OUT: Bytes of string content */
141862  char **pzErr /* OUT: error message */
141863 ){
141864  int rc = SQLITE_OK; /* Return code */
141865  char *zSql; /* "SELECT *" statement on zTbl */
141866  sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
141867 
141868  zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
141869  if( !zSql ){
141870  rc = SQLITE_NOMEM;
141871  }else{
141872  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
141873  if( rc!=SQLITE_OK ){
141874  sqlite3Fts3ErrMsg(pzErr, "%s", sqlite3_errmsg(db));
141875  }
141876  }
141877  sqlite3_free(zSql);
141878 
141879  if( rc==SQLITE_OK ){
141880  const char **azCol; /* Output array */
141881  int nStr = 0; /* Size of all column names (incl. 0x00) */
141882  int nCol; /* Number of table columns */
141883  int i; /* Used to iterate through columns */
141884 
141885  /* Loop through the returned columns. Set nStr to the number of bytes of
141886  ** space required to store a copy of each column name, including the
141887  ** nul-terminator byte. */
141888  nCol = sqlite3_column_count(pStmt);
141889  for(i=0; i<nCol; i++){
141890  const char *zCol = sqlite3_column_name(pStmt, i);
141891  nStr += (int)strlen(zCol) + 1;
141892  }
141893 
141894  /* Allocate and populate the array to return. */
141895  azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
141896  if( azCol==0 ){
141897  rc = SQLITE_NOMEM;
141898  }else{
141899  char *p = (char *)&azCol[nCol];
141900  for(i=0; i<nCol; i++){
141901  const char *zCol = sqlite3_column_name(pStmt, i);
141902  int n = (int)strlen(zCol)+1;
141903  memcpy(p, zCol, n);
141904  azCol[i] = p;
141905  p += n;
141906  }
141907  }
141908  sqlite3_finalize(pStmt);
141909 
141910  /* Set the output variables. */
141911  *pnCol = nCol;
141912  *pnStr = nStr;
141913  *pazCol = azCol;
141914  }
141915 
141916  return rc;
141917 }
141918 
141919 /*
141920 ** This function is the implementation of both the xConnect and xCreate
141921 ** methods of the FTS3 virtual table.
141922 **
141923 ** The argv[] array contains the following:
141924 **
141925 ** argv[0] -> module name ("fts3" or "fts4")
141926 ** argv[1] -> database name
141927 ** argv[2] -> table name
141928 ** argv[...] -> "column name" and other module argument fields.
141929 */
141930 static int fts3InitVtab(
141931  int isCreate, /* True for xCreate, false for xConnect */
141932  sqlite3 *db, /* The SQLite database connection */
141933  void *pAux, /* Hash table containing tokenizers */
141934  int argc, /* Number of elements in argv array */
141935  const char * const *argv, /* xCreate/xConnect argument array */
141936  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
141937  char **pzErr /* Write any error message here */
141938 ){
141939  Fts3Hash *pHash = (Fts3Hash *)pAux;
141940  Fts3Table *p = 0; /* Pointer to allocated vtab */
141941  int rc = SQLITE_OK; /* Return code */
141942  int i; /* Iterator variable */
141943  int nByte; /* Size of allocation used for *p */
141944  int iCol; /* Column index */
141945  int nString = 0; /* Bytes required to hold all column names */
141946  int nCol = 0; /* Number of columns in the FTS table */
141947  char *zCsr; /* Space for holding column names */
141948  int nDb; /* Bytes required to hold database name */
141949  int nName; /* Bytes required to hold table name */
141950  int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
141951  const char **aCol; /* Array of column names */
141952  sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
141953 
141954  int nIndex = 0; /* Size of aIndex[] array */
141955  struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
141956 
141957  /* The results of parsing supported FTS4 key=value options: */
141958  int bNoDocsize = 0; /* True to omit %_docsize table */
141959  int bDescIdx = 0; /* True to store descending indexes */
141960  char *zPrefix = 0; /* Prefix parameter value (or NULL) */
141961  char *zCompress = 0; /* compress=? parameter (or NULL) */
141962  char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
141963  char *zContent = 0; /* content=? parameter (or NULL) */
141964  char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
141965  char **azNotindexed = 0; /* The set of notindexed= columns */
141966  int nNotindexed = 0; /* Size of azNotindexed[] array */
141967 
141968  assert( strlen(argv[0])==4 );
141969  assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
141970  || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
141971  );
141972 
141973  nDb = (int)strlen(argv[1]) + 1;
141974  nName = (int)strlen(argv[2]) + 1;
141975 
141976  nByte = sizeof(const char *) * (argc-2);
141977  aCol = (const char **)sqlite3_malloc(nByte);
141978  if( aCol ){
141979  memset((void*)aCol, 0, nByte);
141980  azNotindexed = (char **)sqlite3_malloc(nByte);
141981  }
141982  if( azNotindexed ){
141983  memset(azNotindexed, 0, nByte);
141984  }
141985  if( !aCol || !azNotindexed ){
141986  rc = SQLITE_NOMEM;
141987  goto fts3_init_out;
141988  }
141989 
141990  /* Loop through all of the arguments passed by the user to the FTS3/4
141991  ** module (i.e. all the column names and special arguments). This loop
141992  ** does the following:
141993  **
141994  ** + Figures out the number of columns the FTSX table will have, and
141995  ** the number of bytes of space that must be allocated to store copies
141996  ** of the column names.
141997  **
141998  ** + If there is a tokenizer specification included in the arguments,
141999  ** initializes the tokenizer pTokenizer.
142000  */
142001  for(i=3; rc==SQLITE_OK && i<argc; i++){
142002  char const *z = argv[i];
142003  int nKey;
142004  char *zVal;
142005 
142006  /* Check if this is a tokenizer specification */
142007  if( !pTokenizer
142008  && strlen(z)>8
142009  && 0==sqlite3_strnicmp(z, "tokenize", 8)
142010  && 0==sqlite3Fts3IsIdChar(z[8])
142011  ){
142012  rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
142013  }
142014 
142015  /* Check if it is an FTS4 special argument. */
142016  else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
142017  struct Fts4Option {
142018  const char *zOpt;
142019  int nOpt;
142020  } aFts4Opt[] = {
142021  { "matchinfo", 9 }, /* 0 -> MATCHINFO */
142022  { "prefix", 6 }, /* 1 -> PREFIX */
142023  { "compress", 8 }, /* 2 -> COMPRESS */
142024  { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
142025  { "order", 5 }, /* 4 -> ORDER */
142026  { "content", 7 }, /* 5 -> CONTENT */
142027  { "languageid", 10 }, /* 6 -> LANGUAGEID */
142028  { "notindexed", 10 } /* 7 -> NOTINDEXED */
142029  };
142030 
142031  int iOpt;
142032  if( !zVal ){
142033  rc = SQLITE_NOMEM;
142034  }else{
142035  for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
142036  struct Fts4Option *pOp = &aFts4Opt[iOpt];
142037  if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
142038  break;
142039  }
142040  }
142041  if( iOpt==SizeofArray(aFts4Opt) ){
142042  sqlite3Fts3ErrMsg(pzErr, "unrecognized parameter: %s", z);
142043  rc = SQLITE_ERROR;
142044  }else{
142045  switch( iOpt ){
142046  case 0: /* MATCHINFO */
142047  if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
142048  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo: %s", zVal);
142049  rc = SQLITE_ERROR;
142050  }
142051  bNoDocsize = 1;
142052  break;
142053 
142054  case 1: /* PREFIX */
142055  sqlite3_free(zPrefix);
142056  zPrefix = zVal;
142057  zVal = 0;
142058  break;
142059 
142060  case 2: /* COMPRESS */
142061  sqlite3_free(zCompress);
142062  zCompress = zVal;
142063  zVal = 0;
142064  break;
142065 
142066  case 3: /* UNCOMPRESS */
142067  sqlite3_free(zUncompress);
142068  zUncompress = zVal;
142069  zVal = 0;
142070  break;
142071 
142072  case 4: /* ORDER */
142073  if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
142074  && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
142075  ){
142076  sqlite3Fts3ErrMsg(pzErr, "unrecognized order: %s", zVal);
142077  rc = SQLITE_ERROR;
142078  }
142079  bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
142080  break;
142081 
142082  case 5: /* CONTENT */
142083  sqlite3_free(zContent);
142084  zContent = zVal;
142085  zVal = 0;
142086  break;
142087 
142088  case 6: /* LANGUAGEID */
142089  assert( iOpt==6 );
142090  sqlite3_free(zLanguageid);
142091  zLanguageid = zVal;
142092  zVal = 0;
142093  break;
142094 
142095  case 7: /* NOTINDEXED */
142096  azNotindexed[nNotindexed++] = zVal;
142097  zVal = 0;
142098  break;
142099  }
142100  }
142101  sqlite3_free(zVal);
142102  }
142103  }
142104 
142105  /* Otherwise, the argument is a column name. */
142106  else {
142107  nString += (int)(strlen(z) + 1);
142108  aCol[nCol++] = z;
142109  }
142110  }
142111 
142112  /* If a content=xxx option was specified, the following:
142113  **
142114  ** 1. Ignore any compress= and uncompress= options.
142115  **
142116  ** 2. If no column names were specified as part of the CREATE VIRTUAL
142117  ** TABLE statement, use all columns from the content table.
142118  */
142119  if( rc==SQLITE_OK && zContent ){
142120  sqlite3_free(zCompress);
142121  sqlite3_free(zUncompress);
142122  zCompress = 0;
142123  zUncompress = 0;
142124  if( nCol==0 ){
142125  sqlite3_free((void*)aCol);
142126  aCol = 0;
142127  rc = fts3ContentColumns(db, argv[1], zContent,&aCol,&nCol,&nString,pzErr);
142128 
142129  /* If a languageid= option was specified, remove the language id
142130  ** column from the aCol[] array. */
142131  if( rc==SQLITE_OK && zLanguageid ){
142132  int j;
142133  for(j=0; j<nCol; j++){
142134  if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
142135  int k;
142136  for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
142137  nCol--;
142138  break;
142139  }
142140  }
142141  }
142142  }
142143  }
142144  if( rc!=SQLITE_OK ) goto fts3_init_out;
142145 
142146  if( nCol==0 ){
142147  assert( nString==0 );
142148  aCol[0] = "content";
142149  nString = 8;
142150  nCol = 1;
142151  }
142152 
142153  if( pTokenizer==0 ){
142154  rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
142155  if( rc!=SQLITE_OK ) goto fts3_init_out;
142156  }
142157  assert( pTokenizer );
142158 
142159  rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
142160  if( rc==SQLITE_ERROR ){
142161  assert( zPrefix );
142162  sqlite3Fts3ErrMsg(pzErr, "error parsing prefix parameter: %s", zPrefix);
142163  }
142164  if( rc!=SQLITE_OK ) goto fts3_init_out;
142165 
142166  /* Allocate and populate the Fts3Table structure. */
142167  nByte = sizeof(Fts3Table) + /* Fts3Table */
142168  nCol * sizeof(char *) + /* azColumn */
142169  nIndex * sizeof(struct Fts3Index) + /* aIndex */
142170  nCol * sizeof(u8) + /* abNotindexed */
142171  nName + /* zName */
142172  nDb + /* zDb */
142173  nString; /* Space for azColumn strings */
142174  p = (Fts3Table*)sqlite3_malloc(nByte);
142175  if( p==0 ){
142176  rc = SQLITE_NOMEM;
142177  goto fts3_init_out;
142178  }
142179  memset(p, 0, nByte);
142180  p->db = db;
142181  p->nColumn = nCol;
142182  p->nPendingData = 0;
142183  p->azColumn = (char **)&p[1];
142184  p->pTokenizer = pTokenizer;
142185  p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
142186  p->bHasDocsize = (isFts4 && bNoDocsize==0);
142187  p->bHasStat = isFts4;
142188  p->bFts4 = isFts4;
142189  p->bDescIdx = bDescIdx;
142190  p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
142191  p->zContentTbl = zContent;
142192  p->zLanguageid = zLanguageid;
142193  zContent = 0;
142194  zLanguageid = 0;
142195  TESTONLY( p->inTransaction = -1 );
142196  TESTONLY( p->mxSavepoint = -1 );
142197 
142198  p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
142199  memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
142200  p->nIndex = nIndex;
142201  for(i=0; i<nIndex; i++){
142202  fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
142203  }
142204  p->abNotindexed = (u8 *)&p->aIndex[nIndex];
142205 
142206  /* Fill in the zName and zDb fields of the vtab structure. */
142207  zCsr = (char *)&p->abNotindexed[nCol];
142208  p->zName = zCsr;
142209  memcpy(zCsr, argv[2], nName);
142210  zCsr += nName;
142211  p->zDb = zCsr;
142212  memcpy(zCsr, argv[1], nDb);
142213  zCsr += nDb;
142214 
142215  /* Fill in the azColumn array */
142216  for(iCol=0; iCol<nCol; iCol++){
142217  char *z;
142218  int n = 0;
142219  z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
142220  memcpy(zCsr, z, n);
142221  zCsr[n] = '\0';
142222  sqlite3Fts3Dequote(zCsr);
142223  p->azColumn[iCol] = zCsr;
142224  zCsr += n+1;
142225  assert( zCsr <= &((char *)p)[nByte] );
142226  }
142227 
142228  /* Fill in the abNotindexed array */
142229  for(iCol=0; iCol<nCol; iCol++){
142230  int n = (int)strlen(p->azColumn[iCol]);
142231  for(i=0; i<nNotindexed; i++){
142232  char *zNot = azNotindexed[i];
142233  if( zNot && n==(int)strlen(zNot)
142234  && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
142235  ){
142236  p->abNotindexed[iCol] = 1;
142237  sqlite3_free(zNot);
142238  azNotindexed[i] = 0;
142239  }
142240  }
142241  }
142242  for(i=0; i<nNotindexed; i++){
142243  if( azNotindexed[i] ){
142244  sqlite3Fts3ErrMsg(pzErr, "no such column: %s", azNotindexed[i]);
142245  rc = SQLITE_ERROR;
142246  }
142247  }
142248 
142249  if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
142250  char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
142251  rc = SQLITE_ERROR;
142252  sqlite3Fts3ErrMsg(pzErr, "missing %s parameter in fts4 constructor", zMiss);
142253  }
142254  p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
142255  p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
142256  if( rc!=SQLITE_OK ) goto fts3_init_out;
142257 
142258  /* If this is an xCreate call, create the underlying tables in the
142259  ** database. TODO: For xConnect(), it could verify that said tables exist.
142260  */
142261  if( isCreate ){
142262  rc = fts3CreateTables(p);
142263  }
142264 
142265  /* Check to see if a legacy fts3 table has been "upgraded" by the
142266  ** addition of a %_stat table so that it can use incremental merge.
142267  */
142268  if( !isFts4 && !isCreate ){
142269  p->bHasStat = 2;
142270  }
142271 
142272  /* Figure out the page-size for the database. This is required in order to
142273  ** estimate the cost of loading large doclists from the database. */
142274  fts3DatabasePageSize(&rc, p);
142275  p->nNodeSize = p->nPgsz-35;
142276 
142277  /* Declare the table schema to SQLite. */
142278  fts3DeclareVtab(&rc, p);
142279 
142280 fts3_init_out:
142281  sqlite3_free(zPrefix);
142282  sqlite3_free(aIndex);
142283  sqlite3_free(zCompress);
142284  sqlite3_free(zUncompress);
142285  sqlite3_free(zContent);
142286  sqlite3_free(zLanguageid);
142287  for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
142288  sqlite3_free((void *)aCol);
142289  sqlite3_free((void *)azNotindexed);
142290  if( rc!=SQLITE_OK ){
142291  if( p ){
142292  fts3DisconnectMethod((sqlite3_vtab *)p);
142293  }else if( pTokenizer ){
142294  pTokenizer->pModule->xDestroy(pTokenizer);
142295  }
142296  }else{
142297  assert( p->pSegments==0 );
142298  *ppVTab = &p->base;
142299  }
142300  return rc;
142301 }
142302 
142303 /*
142304 ** The xConnect() and xCreate() methods for the virtual table. All the
142305 ** work is done in function fts3InitVtab().
142306 */
142307 static int fts3ConnectMethod(
142308  sqlite3 *db, /* Database connection */
142309  void *pAux, /* Pointer to tokenizer hash table */
142310  int argc, /* Number of elements in argv array */
142311  const char * const *argv, /* xCreate/xConnect argument array */
142312  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
142313  char **pzErr /* OUT: sqlite3_malloc'd error message */
142314 ){
142315  return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
142316 }
142317 static int fts3CreateMethod(
142318  sqlite3 *db, /* Database connection */
142319  void *pAux, /* Pointer to tokenizer hash table */
142320  int argc, /* Number of elements in argv array */
142321  const char * const *argv, /* xCreate/xConnect argument array */
142322  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
142323  char **pzErr /* OUT: sqlite3_malloc'd error message */
142324 ){
142325  return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
142326 }
142327 
142328 /*
142329 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
142330 ** extension is currently being used by a version of SQLite too old to
142331 ** support estimatedRows. In that case this function is a no-op.
142332 */
142333 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
142334 #if SQLITE_VERSION_NUMBER>=3008002
142335  if( sqlite3_libversion_number()>=3008002 ){
142336  pIdxInfo->estimatedRows = nRow;
142337  }
142338 #endif
142339 }
142340 
142341 /*
142342 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
142343 ** extension is currently being used by a version of SQLite too old to
142344 ** support index-info flags. In that case this function is a no-op.
142345 */
142346 static void fts3SetUniqueFlag(sqlite3_index_info *pIdxInfo){
142347 #if SQLITE_VERSION_NUMBER>=3008012
142348  if( sqlite3_libversion_number()>=3008012 ){
142349  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
142350  }
142351 #endif
142352 }
142353 
142354 /*
142355 ** Implementation of the xBestIndex method for FTS3 tables. There
142356 ** are three possible strategies, in order of preference:
142357 **
142358 ** 1. Direct lookup by rowid or docid.
142359 ** 2. Full-text search using a MATCH operator on a non-docid column.
142360 ** 3. Linear scan of %_content table.
142361 */
142362 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
142363  Fts3Table *p = (Fts3Table *)pVTab;
142364  int i; /* Iterator variable */
142365  int iCons = -1; /* Index of constraint to use */
142366 
142367  int iLangidCons = -1; /* Index of langid=x constraint, if present */
142368  int iDocidGe = -1; /* Index of docid>=x constraint, if present */
142369  int iDocidLe = -1; /* Index of docid<=x constraint, if present */
142370  int iIdx;
142371 
142372  /* By default use a full table scan. This is an expensive option,
142373  ** so search through the constraints to see if a more efficient
142374  ** strategy is possible.
142375  */
142376  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
142377  pInfo->estimatedCost = 5000000;
142378  for(i=0; i<pInfo->nConstraint; i++){
142379  int bDocid; /* True if this constraint is on docid */
142380  struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
142381  if( pCons->usable==0 ){
142382  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
142383  /* There exists an unusable MATCH constraint. This means that if
142384  ** the planner does elect to use the results of this call as part
142385  ** of the overall query plan the user will see an "unable to use
142386  ** function MATCH in the requested context" error. To discourage
142387  ** this, return a very high cost here. */
142388  pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
142389  pInfo->estimatedCost = 1e50;
142390  fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
142391  return SQLITE_OK;
142392  }
142393  continue;
142394  }
142395 
142396  bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
142397 
142398  /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
142399  if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
142400  pInfo->idxNum = FTS3_DOCID_SEARCH;
142401  pInfo->estimatedCost = 1.0;
142402  iCons = i;
142403  }
142404 
142405  /* A MATCH constraint. Use a full-text search.
142406  **
142407  ** If there is more than one MATCH constraint available, use the first
142408  ** one encountered. If there is both a MATCH constraint and a direct
142409  ** rowid/docid lookup, prefer the MATCH strategy. This is done even
142410  ** though the rowid/docid lookup is faster than a MATCH query, selecting
142411  ** it would lead to an "unable to use function MATCH in the requested
142412  ** context" error.
142413  */
142414  if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
142415  && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
142416  ){
142417  pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
142418  pInfo->estimatedCost = 2.0;
142419  iCons = i;
142420  }
142421 
142422  /* Equality constraint on the langid column */
142423  if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
142424  && pCons->iColumn==p->nColumn + 2
142425  ){
142426  iLangidCons = i;
142427  }
142428 
142429  if( bDocid ){
142430  switch( pCons->op ){
142433  iDocidGe = i;
142434  break;
142435 
142438  iDocidLe = i;
142439  break;
142440  }
142441  }
142442  }
142443 
142444  /* If using a docid=? or rowid=? strategy, set the UNIQUE flag. */
142445  if( pInfo->idxNum==FTS3_DOCID_SEARCH ) fts3SetUniqueFlag(pInfo);
142446 
142447  iIdx = 1;
142448  if( iCons>=0 ){
142449  pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
142450  pInfo->aConstraintUsage[iCons].omit = 1;
142451  }
142452  if( iLangidCons>=0 ){
142453  pInfo->idxNum |= FTS3_HAVE_LANGID;
142454  pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
142455  }
142456  if( iDocidGe>=0 ){
142457  pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
142458  pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
142459  }
142460  if( iDocidLe>=0 ){
142461  pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
142462  pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
142463  }
142464 
142465  /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
142466  ** docid) order. Both ascending and descending are possible.
142467  */
142468  if( pInfo->nOrderBy==1 ){
142469  struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
142470  if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
142471  if( pOrder->desc ){
142472  pInfo->idxStr = "DESC";
142473  }else{
142474  pInfo->idxStr = "ASC";
142475  }
142476  pInfo->orderByConsumed = 1;
142477  }
142478  }
142479 
142480  assert( p->pSegments==0 );
142481  return SQLITE_OK;
142482 }
142483 
142484 /*
142485 ** Implementation of xOpen method.
142486 */
142487 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
142488  sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
142489 
142490  UNUSED_PARAMETER(pVTab);
142491 
142492  /* Allocate a buffer large enough for an Fts3Cursor structure. If the
142493  ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
142494  ** if the allocation fails, return SQLITE_NOMEM.
142495  */
142496  *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
142497  if( !pCsr ){
142498  return SQLITE_NOMEM;
142499  }
142500  memset(pCsr, 0, sizeof(Fts3Cursor));
142501  return SQLITE_OK;
142502 }
142503 
142504 /*
142505 ** Close the cursor. For additional information see the documentation
142506 ** on the xClose method of the virtual table interface.
142507 */
142508 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
142509  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
142510  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
142511  sqlite3_finalize(pCsr->pStmt);
142512  sqlite3Fts3ExprFree(pCsr->pExpr);
142513  sqlite3Fts3FreeDeferredTokens(pCsr);
142514  sqlite3_free(pCsr->aDoclist);
142515  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
142516  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
142517  sqlite3_free(pCsr);
142518  return SQLITE_OK;
142519 }
142520 
142521 /*
142522 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
142523 ** compose and prepare an SQL statement of the form:
142524 **
142525 ** "SELECT <columns> FROM %_content WHERE rowid = ?"
142526 **
142527 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
142528 ** it. If an error occurs, return an SQLite error code.
142529 **
142530 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
142531 */
142532 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
142533  int rc = SQLITE_OK;
142534  if( pCsr->pStmt==0 ){
142535  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
142536  char *zSql;
142537  zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
142538  if( !zSql ) return SQLITE_NOMEM;
142539  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
142540  sqlite3_free(zSql);
142541  }
142542  *ppStmt = pCsr->pStmt;
142543  return rc;
142544 }
142545 
142546 /*
142547 ** Position the pCsr->pStmt statement so that it is on the row
142548 ** of the %_content table that contains the last match. Return
142549 ** SQLITE_OK on success.
142550 */
142551 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
142552  int rc = SQLITE_OK;
142553  if( pCsr->isRequireSeek ){
142554  sqlite3_stmt *pStmt = 0;
142555 
142556  rc = fts3CursorSeekStmt(pCsr, &pStmt);
142557  if( rc==SQLITE_OK ){
142558  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
142559  pCsr->isRequireSeek = 0;
142560  if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
142561  return SQLITE_OK;
142562  }else{
142563  rc = sqlite3_reset(pCsr->pStmt);
142564  if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
142565  /* If no row was found and no error has occurred, then the %_content
142566  ** table is missing a row that is present in the full-text index.
142567  ** The data structures are corrupt. */
142568  rc = FTS_CORRUPT_VTAB;
142569  pCsr->isEof = 1;
142570  }
142571  }
142572  }
142573  }
142574 
142575  if( rc!=SQLITE_OK && pContext ){
142576  sqlite3_result_error_code(pContext, rc);
142577  }
142578  return rc;
142579 }
142580 
142581 /*
142582 ** This function is used to process a single interior node when searching
142583 ** a b-tree for a term or term prefix. The node data is passed to this
142584 ** function via the zNode/nNode parameters. The term to search for is
142585 ** passed in zTerm/nTerm.
142586 **
142587 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
142588 ** of the child node that heads the sub-tree that may contain the term.
142589 **
142590 ** If piLast is not NULL, then *piLast is set to the right-most child node
142591 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
142592 ** a prefix.
142593 **
142594 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
142595 */
142596 static int fts3ScanInteriorNode(
142597  const char *zTerm, /* Term to select leaves for */
142598  int nTerm, /* Size of term zTerm in bytes */
142599  const char *zNode, /* Buffer containing segment interior node */
142600  int nNode, /* Size of buffer at zNode */
142601  sqlite3_int64 *piFirst, /* OUT: Selected child node */
142602  sqlite3_int64 *piLast /* OUT: Selected child node */
142603 ){
142604  int rc = SQLITE_OK; /* Return code */
142605  const char *zCsr = zNode; /* Cursor to iterate through node */
142606  const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
142607  char *zBuffer = 0; /* Buffer to load terms into */
142608  int nAlloc = 0; /* Size of allocated buffer */
142609  int isFirstTerm = 1; /* True when processing first term on page */
142610  sqlite3_int64 iChild; /* Block id of child node to descend to */
142611 
142612  /* Skip over the 'height' varint that occurs at the start of every
142613  ** interior node. Then load the blockid of the left-child of the b-tree
142614  ** node into variable iChild.
142615  **
142616  ** Even if the data structure on disk is corrupted, this (reading two
142617  ** varints from the buffer) does not risk an overread. If zNode is a
142618  ** root node, then the buffer comes from a SELECT statement. SQLite does
142619  ** not make this guarantee explicitly, but in practice there are always
142620  ** either more than 20 bytes of allocated space following the nNode bytes of
142621  ** contents, or two zero bytes. Or, if the node is read from the %_segments
142622  ** table, then there are always 20 bytes of zeroed padding following the
142623  ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
142624  */
142625  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
142626  zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
142627  if( zCsr>zEnd ){
142628  return FTS_CORRUPT_VTAB;
142629  }
142630 
142631  while( zCsr<zEnd && (piFirst || piLast) ){
142632  int cmp; /* memcmp() result */
142633  int nSuffix; /* Size of term suffix */
142634  int nPrefix = 0; /* Size of term prefix */
142635  int nBuffer; /* Total term size */
142636 
142637  /* Load the next term on the node into zBuffer. Use realloc() to expand
142638  ** the size of zBuffer if required. */
142639  if( !isFirstTerm ){
142640  zCsr += fts3GetVarint32(zCsr, &nPrefix);
142641  }
142642  isFirstTerm = 0;
142643  zCsr += fts3GetVarint32(zCsr, &nSuffix);
142644 
142645  if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
142646  rc = FTS_CORRUPT_VTAB;
142647  goto finish_scan;
142648  }
142649  if( nPrefix+nSuffix>nAlloc ){
142650  char *zNew;
142651  nAlloc = (nPrefix+nSuffix) * 2;
142652  zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
142653  if( !zNew ){
142654  rc = SQLITE_NOMEM;
142655  goto finish_scan;
142656  }
142657  zBuffer = zNew;
142658  }
142659  assert( zBuffer );
142660  memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
142661  nBuffer = nPrefix + nSuffix;
142662  zCsr += nSuffix;
142663 
142664  /* Compare the term we are searching for with the term just loaded from
142665  ** the interior node. If the specified term is greater than or equal
142666  ** to the term from the interior node, then all terms on the sub-tree
142667  ** headed by node iChild are smaller than zTerm. No need to search
142668  ** iChild.
142669  **
142670  ** If the interior node term is larger than the specified term, then
142671  ** the tree headed by iChild may contain the specified term.
142672  */
142673  cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
142674  if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
142675  *piFirst = iChild;
142676  piFirst = 0;
142677  }
142678 
142679  if( piLast && cmp<0 ){
142680  *piLast = iChild;
142681  piLast = 0;
142682  }
142683 
142684  iChild++;
142685  };
142686 
142687  if( piFirst ) *piFirst = iChild;
142688  if( piLast ) *piLast = iChild;
142689 
142690  finish_scan:
142691  sqlite3_free(zBuffer);
142692  return rc;
142693 }
142694 
142695 
142696 /*
142697 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
142698 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
142699 ** contains a term. This function searches the sub-tree headed by the zNode
142700 ** node for the range of leaf nodes that may contain the specified term
142701 ** or terms for which the specified term is a prefix.
142702 **
142703 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
142704 ** left-most leaf node in the tree that may contain the specified term.
142705 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
142706 ** right-most leaf node that may contain a term for which the specified
142707 ** term is a prefix.
142708 **
142709 ** It is possible that the range of returned leaf nodes does not contain
142710 ** the specified term or any terms for which it is a prefix. However, if the
142711 ** segment does contain any such terms, they are stored within the identified
142712 ** range. Because this function only inspects interior segment nodes (and
142713 ** never loads leaf nodes into memory), it is not possible to be sure.
142714 **
142715 ** If an error occurs, an error code other than SQLITE_OK is returned.
142716 */
142717 static int fts3SelectLeaf(
142718  Fts3Table *p, /* Virtual table handle */
142719  const char *zTerm, /* Term to select leaves for */
142720  int nTerm, /* Size of term zTerm in bytes */
142721  const char *zNode, /* Buffer containing segment interior node */
142722  int nNode, /* Size of buffer at zNode */
142723  sqlite3_int64 *piLeaf, /* Selected leaf node */
142724  sqlite3_int64 *piLeaf2 /* Selected leaf node */
142725 ){
142726  int rc = SQLITE_OK; /* Return code */
142727  int iHeight; /* Height of this node in tree */
142728 
142729  assert( piLeaf || piLeaf2 );
142730 
142731  fts3GetVarint32(zNode, &iHeight);
142732  rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
142733  assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
142734 
142735  if( rc==SQLITE_OK && iHeight>1 ){
142736  char *zBlob = 0; /* Blob read from %_segments table */
142737  int nBlob = 0; /* Size of zBlob in bytes */
142738 
142739  if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
142740  rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
142741  if( rc==SQLITE_OK ){
142742  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
142743  }
142744  sqlite3_free(zBlob);
142745  piLeaf = 0;
142746  zBlob = 0;
142747  }
142748 
142749  if( rc==SQLITE_OK ){
142750  rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
142751  }
142752  if( rc==SQLITE_OK ){
142753  rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
142754  }
142755  sqlite3_free(zBlob);
142756  }
142757 
142758  return rc;
142759 }
142760 
142761 /*
142762 ** This function is used to create delta-encoded serialized lists of FTS3
142763 ** varints. Each call to this function appends a single varint to a list.
142764 */
142765 static void fts3PutDeltaVarint(
142766  char **pp, /* IN/OUT: Output pointer */
142767  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
142768  sqlite3_int64 iVal /* Write this value to the list */
142769 ){
142770  assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
142771  *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
142772  *piPrev = iVal;
142773 }
142774 
142775 /*
142776 ** When this function is called, *ppPoslist is assumed to point to the
142777 ** start of a position-list. After it returns, *ppPoslist points to the
142778 ** first byte after the position-list.
142779 **
142780 ** A position list is list of positions (delta encoded) and columns for
142781 ** a single document record of a doclist. So, in other words, this
142782 ** routine advances *ppPoslist so that it points to the next docid in
142783 ** the doclist, or to the first byte past the end of the doclist.
142784 **
142785 ** If pp is not NULL, then the contents of the position list are copied
142786 ** to *pp. *pp is set to point to the first byte past the last byte copied
142787 ** before this function returns.
142788 */
142789 static void fts3PoslistCopy(char **pp, char **ppPoslist){
142790  char *pEnd = *ppPoslist;
142791  char c = 0;
142792 
142793  /* The end of a position list is marked by a zero encoded as an FTS3
142794  ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
142795  ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
142796  ** of some other, multi-byte, value.
142797  **
142798  ** The following while-loop moves pEnd to point to the first byte that is not
142799  ** immediately preceded by a byte with the 0x80 bit set. Then increments
142800  ** pEnd once more so that it points to the byte immediately following the
142801  ** last byte in the position-list.
142802  */
142803  while( *pEnd | c ){
142804  c = *pEnd++ & 0x80;
142805  testcase( c!=0 && (*pEnd)==0 );
142806  }
142807  pEnd++; /* Advance past the POS_END terminator byte */
142808 
142809  if( pp ){
142810  int n = (int)(pEnd - *ppPoslist);
142811  char *p = *pp;
142812  memcpy(p, *ppPoslist, n);
142813  p += n;
142814  *pp = p;
142815  }
142816  *ppPoslist = pEnd;
142817 }
142818 
142819 /*
142820 ** When this function is called, *ppPoslist is assumed to point to the
142821 ** start of a column-list. After it returns, *ppPoslist points to the
142822 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
142823 **
142824 ** A column-list is list of delta-encoded positions for a single column
142825 ** within a single document within a doclist.
142826 **
142827 ** The column-list is terminated either by a POS_COLUMN varint (1) or
142828 ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
142829 ** the POS_COLUMN or POS_END that terminates the column-list.
142830 **
142831 ** If pp is not NULL, then the contents of the column-list are copied
142832 ** to *pp. *pp is set to point to the first byte past the last byte copied
142833 ** before this function returns. The POS_COLUMN or POS_END terminator
142834 ** is not copied into *pp.
142835 */
142836 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
142837  char *pEnd = *ppPoslist;
142838  char c = 0;
142839 
142840  /* A column-list is terminated by either a 0x01 or 0x00 byte that is
142841  ** not part of a multi-byte varint.
142842  */
142843  while( 0xFE & (*pEnd | c) ){
142844  c = *pEnd++ & 0x80;
142845  testcase( c!=0 && ((*pEnd)&0xfe)==0 );
142846  }
142847  if( pp ){
142848  int n = (int)(pEnd - *ppPoslist);
142849  char *p = *pp;
142850  memcpy(p, *ppPoslist, n);
142851  p += n;
142852  *pp = p;
142853  }
142854  *ppPoslist = pEnd;
142855 }
142856 
142857 /*
142858 ** Value used to signify the end of an position-list. This is safe because
142859 ** it is not possible to have a document with 2^31 terms.
142860 */
142861 #define POSITION_LIST_END 0x7fffffff
142862 
142863 /*
142864 ** This function is used to help parse position-lists. When this function is
142865 ** called, *pp may point to the start of the next varint in the position-list
142866 ** being parsed, or it may point to 1 byte past the end of the position-list
142867 ** (in which case **pp will be a terminator bytes POS_END (0) or
142868 ** (1)).
142869 **
142870 ** If *pp points past the end of the current position-list, set *pi to
142871 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
142872 ** increment the current value of *pi by the value read, and set *pp to
142873 ** point to the next value before returning.
142874 **
142875 ** Before calling this routine *pi must be initialized to the value of
142876 ** the previous position, or zero if we are reading the first position
142877 ** in the position-list. Because positions are delta-encoded, the value
142878 ** of the previous position is needed in order to compute the value of
142879 ** the next position.
142880 */
142881 static void fts3ReadNextPos(
142882  char **pp, /* IN/OUT: Pointer into position-list buffer */
142883  sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
142884 ){
142885  if( (**pp)&0xFE ){
142886  fts3GetDeltaVarint(pp, pi);
142887  *pi -= 2;
142888  }else{
142889  *pi = POSITION_LIST_END;
142890  }
142891 }
142892 
142893 /*
142894 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
142895 ** the value of iCol encoded as a varint to *pp. This will start a new
142896 ** column list.
142897 **
142898 ** Set *pp to point to the byte just after the last byte written before
142899 ** returning (do not modify it if iCol==0). Return the total number of bytes
142900 ** written (0 if iCol==0).
142901 */
142902 static int fts3PutColNumber(char **pp, int iCol){
142903  int n = 0; /* Number of bytes written */
142904  if( iCol ){
142905  char *p = *pp; /* Output pointer */
142906  n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
142907  *p = 0x01;
142908  *pp = &p[n];
142909  }
142910  return n;
142911 }
142912 
142913 /*
142914 ** Compute the union of two position lists. The output written
142915 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
142916 ** order and with any duplicates removed. All pointers are
142917 ** updated appropriately. The caller is responsible for insuring
142918 ** that there is enough space in *pp to hold the complete output.
142919 */
142920 static void fts3PoslistMerge(
142921  char **pp, /* Output buffer */
142922  char **pp1, /* Left input list */
142923  char **pp2 /* Right input list */
142924 ){
142925  char *p = *pp;
142926  char *p1 = *pp1;
142927  char *p2 = *pp2;
142928 
142929  while( *p1 || *p2 ){
142930  int iCol1; /* The current column index in pp1 */
142931  int iCol2; /* The current column index in pp2 */
142932 
142933  if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
142934  else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
142935  else iCol1 = 0;
142936 
142937  if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
142938  else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
142939  else iCol2 = 0;
142940 
142941  if( iCol1==iCol2 ){
142942  sqlite3_int64 i1 = 0; /* Last position from pp1 */
142943  sqlite3_int64 i2 = 0; /* Last position from pp2 */
142944  sqlite3_int64 iPrev = 0;
142945  int n = fts3PutColNumber(&p, iCol1);
142946  p1 += n;
142947  p2 += n;
142948 
142949  /* At this point, both p1 and p2 point to the start of column-lists
142950  ** for the same column (the column with index iCol1 and iCol2).
142951  ** A column-list is a list of non-negative delta-encoded varints, each
142952  ** incremented by 2 before being stored. Each list is terminated by a
142953  ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
142954  ** and writes the results to buffer p. p is left pointing to the byte
142955  ** after the list written. No terminator (POS_END or POS_COLUMN) is
142956  ** written to the output.
142957  */
142958  fts3GetDeltaVarint(&p1, &i1);
142959  fts3GetDeltaVarint(&p2, &i2);
142960  do {
142961  fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
142962  iPrev -= 2;
142963  if( i1==i2 ){
142964  fts3ReadNextPos(&p1, &i1);
142965  fts3ReadNextPos(&p2, &i2);
142966  }else if( i1<i2 ){
142967  fts3ReadNextPos(&p1, &i1);
142968  }else{
142969  fts3ReadNextPos(&p2, &i2);
142970  }
142971  }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
142972  }else if( iCol1<iCol2 ){
142973  p1 += fts3PutColNumber(&p, iCol1);
142974  fts3ColumnlistCopy(&p, &p1);
142975  }else{
142976  p2 += fts3PutColNumber(&p, iCol2);
142977  fts3ColumnlistCopy(&p, &p2);
142978  }
142979  }
142980 
142981  *p++ = POS_END;
142982  *pp = p;
142983  *pp1 = p1 + 1;
142984  *pp2 = p2 + 1;
142985 }
142986 
142987 /*
142988 ** This function is used to merge two position lists into one. When it is
142989 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
142990 ** the part of a doclist that follows each document id. For example, if a row
142991 ** contains:
142992 **
142993 ** 'a b c'|'x y z'|'a b b a'
142994 **
142995 ** Then the position list for this row for token 'b' would consist of:
142996 **
142997 ** 0x02 0x01 0x02 0x03 0x03 0x00
142998 **
142999 ** When this function returns, both *pp1 and *pp2 are left pointing to the
143000 ** byte following the 0x00 terminator of their respective position lists.
143001 **
143002 ** If isSaveLeft is 0, an entry is added to the output position list for
143003 ** each position in *pp2 for which there exists one or more positions in
143004 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
143005 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
143006 ** slots before it.
143007 **
143008 ** e.g. nToken==1 searches for adjacent positions.
143009 */
143010 static int fts3PoslistPhraseMerge(
143011  char **pp, /* IN/OUT: Preallocated output buffer */
143012  int nToken, /* Maximum difference in token positions */
143013  int isSaveLeft, /* Save the left position */
143014  int isExact, /* If *pp1 is exactly nTokens before *pp2 */
143015  char **pp1, /* IN/OUT: Left input list */
143016  char **pp2 /* IN/OUT: Right input list */
143017 ){
143018  char *p = *pp;
143019  char *p1 = *pp1;
143020  char *p2 = *pp2;
143021  int iCol1 = 0;
143022  int iCol2 = 0;
143023 
143024  /* Never set both isSaveLeft and isExact for the same invocation. */
143025  assert( isSaveLeft==0 || isExact==0 );
143026 
143027  assert( p!=0 && *p1!=0 && *p2!=0 );
143028  if( *p1==POS_COLUMN ){
143029  p1++;
143030  p1 += fts3GetVarint32(p1, &iCol1);
143031  }
143032  if( *p2==POS_COLUMN ){
143033  p2++;
143034  p2 += fts3GetVarint32(p2, &iCol2);
143035  }
143036 
143037  while( 1 ){
143038  if( iCol1==iCol2 ){
143039  char *pSave = p;
143040  sqlite3_int64 iPrev = 0;
143041  sqlite3_int64 iPos1 = 0;
143042  sqlite3_int64 iPos2 = 0;
143043 
143044  if( iCol1 ){
143045  *p++ = POS_COLUMN;
143046  p += sqlite3Fts3PutVarint(p, iCol1);
143047  }
143048 
143049  assert( *p1!=POS_END && *p1!=POS_COLUMN );
143050  assert( *p2!=POS_END && *p2!=POS_COLUMN );
143051  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
143052  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143053 
143054  while( 1 ){
143055  if( iPos2==iPos1+nToken
143056  || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
143057  ){
143058  sqlite3_int64 iSave;
143059  iSave = isSaveLeft ? iPos1 : iPos2;
143060  fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
143061  pSave = 0;
143062  assert( p );
143063  }
143064  if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
143065  if( (*p2&0xFE)==0 ) break;
143066  fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
143067  }else{
143068  if( (*p1&0xFE)==0 ) break;
143069  fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
143070  }
143071  }
143072 
143073  if( pSave ){
143074  assert( pp && p );
143075  p = pSave;
143076  }
143077 
143078  fts3ColumnlistCopy(0, &p1);
143079  fts3ColumnlistCopy(0, &p2);
143080  assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
143081  if( 0==*p1 || 0==*p2 ) break;
143082 
143083  p1++;
143084  p1 += fts3GetVarint32(p1, &iCol1);
143085  p2++;
143086  p2 += fts3GetVarint32(p2, &iCol2);
143087  }
143088 
143089  /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
143090  ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
143091  ** end of the position list, or the 0x01 that precedes the next
143092  ** column-number in the position list.
143093  */
143094  else if( iCol1<iCol2 ){
143095  fts3ColumnlistCopy(0, &p1);
143096  if( 0==*p1 ) break;
143097  p1++;
143098  p1 += fts3GetVarint32(p1, &iCol1);
143099  }else{
143100  fts3ColumnlistCopy(0, &p2);
143101  if( 0==*p2 ) break;
143102  p2++;
143103  p2 += fts3GetVarint32(p2, &iCol2);
143104  }
143105  }
143106 
143107  fts3PoslistCopy(0, &p2);
143108  fts3PoslistCopy(0, &p1);
143109  *pp1 = p1;
143110  *pp2 = p2;
143111  if( *pp==p ){
143112  return 0;
143113  }
143114  *p++ = 0x00;
143115  *pp = p;
143116  return 1;
143117 }
143118 
143119 /*
143120 ** Merge two position-lists as required by the NEAR operator. The argument
143121 ** position lists correspond to the left and right phrases of an expression
143122 ** like:
143123 **
143124 ** "phrase 1" NEAR "phrase number 2"
143125 **
143126 ** Position list *pp1 corresponds to the left-hand side of the NEAR
143127 ** expression and *pp2 to the right. As usual, the indexes in the position
143128 ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
143129 ** in the example above).
143130 **
143131 ** The output position list - written to *pp - is a copy of *pp2 with those
143132 ** entries that are not sufficiently NEAR entries in *pp1 removed.
143133 */
143134 static int fts3PoslistNearMerge(
143135  char **pp, /* Output buffer */
143136  char *aTmp, /* Temporary buffer space */
143137  int nRight, /* Maximum difference in token positions */
143138  int nLeft, /* Maximum difference in token positions */
143139  char **pp1, /* IN/OUT: Left input list */
143140  char **pp2 /* IN/OUT: Right input list */
143141 ){
143142  char *p1 = *pp1;
143143  char *p2 = *pp2;
143144 
143145  char *pTmp1 = aTmp;
143146  char *pTmp2;
143147  char *aTmp2;
143148  int res = 1;
143149 
143150  fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
143151  aTmp2 = pTmp2 = pTmp1;
143152  *pp1 = p1;
143153  *pp2 = p2;
143154  fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
143155  if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
143156  fts3PoslistMerge(pp, &aTmp, &aTmp2);
143157  }else if( pTmp1!=aTmp ){
143158  fts3PoslistCopy(pp, &aTmp);
143159  }else if( pTmp2!=aTmp2 ){
143160  fts3PoslistCopy(pp, &aTmp2);
143161  }else{
143162  res = 0;
143163  }
143164 
143165  return res;
143166 }
143167 
143168 /*
143169 ** An instance of this function is used to merge together the (potentially
143170 ** large number of) doclists for each term that matches a prefix query.
143171 ** See function fts3TermSelectMerge() for details.
143172 */
143173 typedef struct TermSelect TermSelect;
143174 struct TermSelect {
143175  char *aaOutput[16]; /* Malloc'd output buffers */
143176  int anOutput[16]; /* Size each output buffer in bytes */
143177 };
143178 
143179 /*
143180 ** This function is used to read a single varint from a buffer. Parameter
143181 ** pEnd points 1 byte past the end of the buffer. When this function is
143182 ** called, if *pp points to pEnd or greater, then the end of the buffer
143183 ** has been reached. In this case *pp is set to 0 and the function returns.
143184 **
143185 ** If *pp does not point to or past pEnd, then a single varint is read
143186 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
143187 **
143188 ** If bDescIdx is false, the value read is added to *pVal before returning.
143189 ** If it is true, the value read is subtracted from *pVal before this
143190 ** function returns.
143191 */
143192 static void fts3GetDeltaVarint3(
143193  char **pp, /* IN/OUT: Point to read varint from */
143194  char *pEnd, /* End of buffer */
143195  int bDescIdx, /* True if docids are descending */
143196  sqlite3_int64 *pVal /* IN/OUT: Integer value */
143197 ){
143198  if( *pp>=pEnd ){
143199  *pp = 0;
143200  }else{
143201  sqlite3_int64 iVal;
143202  *pp += sqlite3Fts3GetVarint(*pp, &iVal);
143203  if( bDescIdx ){
143204  *pVal -= iVal;
143205  }else{
143206  *pVal += iVal;
143207  }
143208  }
143209 }
143210 
143211 /*
143212 ** This function is used to write a single varint to a buffer. The varint
143213 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
143214 ** end of the value written.
143215 **
143216 ** If *pbFirst is zero when this function is called, the value written to
143217 ** the buffer is that of parameter iVal.
143218 **
143219 ** If *pbFirst is non-zero when this function is called, then the value
143220 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
143221 ** (if bDescIdx is non-zero).
143222 **
143223 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
143224 ** to the value of parameter iVal.
143225 */
143226 static void fts3PutDeltaVarint3(
143227  char **pp, /* IN/OUT: Output pointer */
143228  int bDescIdx, /* True for descending docids */
143229  sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
143230  int *pbFirst, /* IN/OUT: True after first int written */
143231  sqlite3_int64 iVal /* Write this value to the list */
143232 ){
143233  sqlite3_int64 iWrite;
143234  if( bDescIdx==0 || *pbFirst==0 ){
143235  iWrite = iVal - *piPrev;
143236  }else{
143237  iWrite = *piPrev - iVal;
143238  }
143239  assert( *pbFirst || *piPrev==0 );
143240  assert( *pbFirst==0 || iWrite>0 );
143241  *pp += sqlite3Fts3PutVarint(*pp, iWrite);
143242  *piPrev = iVal;
143243  *pbFirst = 1;
143244 }
143245 
143246 
143247 /*
143248 ** This macro is used by various functions that merge doclists. The two
143249 ** arguments are 64-bit docid values. If the value of the stack variable
143250 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
143251 ** Otherwise, (i2-i1).
143252 **
143253 ** Using this makes it easier to write code that can merge doclists that are
143254 ** sorted in either ascending or descending order.
143255 */
143256 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
143257 
143258 /*
143259 ** This function does an "OR" merge of two doclists (output contains all
143260 ** positions contained in either argument doclist). If the docids in the
143261 ** input doclists are sorted in ascending order, parameter bDescDoclist
143262 ** should be false. If they are sorted in ascending order, it should be
143263 ** passed a non-zero value.
143264 **
143265 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
143266 ** containing the output doclist and SQLITE_OK is returned. In this case
143267 ** *pnOut is set to the number of bytes in the output doclist.
143268 **
143269 ** If an error occurs, an SQLite error code is returned. The output values
143270 ** are undefined in this case.
143271 */
143272 static int fts3DoclistOrMerge(
143273  int bDescDoclist, /* True if arguments are desc */
143274  char *a1, int n1, /* First doclist */
143275  char *a2, int n2, /* Second doclist */
143276  char **paOut, int *pnOut /* OUT: Malloc'd doclist */
143277 ){
143278  sqlite3_int64 i1 = 0;
143279  sqlite3_int64 i2 = 0;
143280  sqlite3_int64 iPrev = 0;
143281  char *pEnd1 = &a1[n1];
143282  char *pEnd2 = &a2[n2];
143283  char *p1 = a1;
143284  char *p2 = a2;
143285  char *p;
143286  char *aOut;
143287  int bFirstOut = 0;
143288 
143289  *paOut = 0;
143290  *pnOut = 0;
143291 
143292  /* Allocate space for the output. Both the input and output doclists
143293  ** are delta encoded. If they are in ascending order (bDescDoclist==0),
143294  ** then the first docid in each list is simply encoded as a varint. For
143295  ** each subsequent docid, the varint stored is the difference between the
143296  ** current and previous docid (a positive number - since the list is in
143297  ** ascending order).
143298  **
143299  ** The first docid written to the output is therefore encoded using the
143300  ** same number of bytes as it is in whichever of the input lists it is
143301  ** read from. And each subsequent docid read from the same input list
143302  ** consumes either the same or less bytes as it did in the input (since
143303  ** the difference between it and the previous value in the output must
143304  ** be a positive value less than or equal to the delta value read from
143305  ** the input list). The same argument applies to all but the first docid
143306  ** read from the 'other' list. And to the contents of all position lists
143307  ** that will be copied and merged from the input to the output.
143308  **
143309  ** However, if the first docid copied to the output is a negative number,
143310  ** then the encoding of the first docid from the 'other' input list may
143311  ** be larger in the output than it was in the input (since the delta value
143312  ** may be a larger positive integer than the actual docid).
143313  **
143314  ** The space required to store the output is therefore the sum of the
143315  ** sizes of the two inputs, plus enough space for exactly one of the input
143316  ** docids to grow.
143317  **
143318  ** A symetric argument may be made if the doclists are in descending
143319  ** order.
143320  */
143321  aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
143322  if( !aOut ) return SQLITE_NOMEM;
143323 
143324  p = aOut;
143325  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
143326  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
143327  while( p1 || p2 ){
143328  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
143329 
143330  if( p2 && p1 && iDiff==0 ){
143331  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
143332  fts3PoslistMerge(&p, &p1, &p2);
143333  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
143334  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
143335  }else if( !p2 || (p1 && iDiff<0) ){
143336  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
143337  fts3PoslistCopy(&p, &p1);
143338  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
143339  }else{
143340  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
143341  fts3PoslistCopy(&p, &p2);
143342  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
143343  }
143344  }
143345 
143346  *paOut = aOut;
143347  *pnOut = (int)(p-aOut);
143348  assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
143349  return SQLITE_OK;
143350 }
143351 
143352 /*
143353 ** This function does a "phrase" merge of two doclists. In a phrase merge,
143354 ** the output contains a copy of each position from the right-hand input
143355 ** doclist for which there is a position in the left-hand input doclist
143356 ** exactly nDist tokens before it.
143357 **
143358 ** If the docids in the input doclists are sorted in ascending order,
143359 ** parameter bDescDoclist should be false. If they are sorted in ascending
143360 ** order, it should be passed a non-zero value.
143361 **
143362 ** The right-hand input doclist is overwritten by this function.
143363 */
143364 static int fts3DoclistPhraseMerge(
143365  int bDescDoclist, /* True if arguments are desc */
143366  int nDist, /* Distance from left to right (1=adjacent) */
143367  char *aLeft, int nLeft, /* Left doclist */
143368  char **paRight, int *pnRight /* IN/OUT: Right/output doclist */
143369 ){
143370  sqlite3_int64 i1 = 0;
143371  sqlite3_int64 i2 = 0;
143372  sqlite3_int64 iPrev = 0;
143373  char *aRight = *paRight;
143374  char *pEnd1 = &aLeft[nLeft];
143375  char *pEnd2 = &aRight[*pnRight];
143376  char *p1 = aLeft;
143377  char *p2 = aRight;
143378  char *p;
143379  int bFirstOut = 0;
143380  char *aOut;
143381 
143382  assert( nDist>0 );
143383  if( bDescDoclist ){
143384  aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
143385  if( aOut==0 ) return SQLITE_NOMEM;
143386  }else{
143387  aOut = aRight;
143388  }
143389  p = aOut;
143390 
143391  fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
143392  fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
143393 
143394  while( p1 && p2 ){
143395  sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
143396  if( iDiff==0 ){
143397  char *pSave = p;
143398  sqlite3_int64 iPrevSave = iPrev;
143399  int bFirstOutSave = bFirstOut;
143400 
143401  fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
143402  if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
143403  p = pSave;
143404  iPrev = iPrevSave;
143405  bFirstOut = bFirstOutSave;
143406  }
143407  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
143408  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
143409  }else if( iDiff<0 ){
143410  fts3PoslistCopy(0, &p1);
143411  fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
143412  }else{
143413  fts3PoslistCopy(0, &p2);
143414  fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
143415  }
143416  }
143417 
143418  *pnRight = (int)(p - aOut);
143419  if( bDescDoclist ){
143420  sqlite3_free(aRight);
143421  *paRight = aOut;
143422  }
143423 
143424  return SQLITE_OK;
143425 }
143426 
143427 /*
143428 ** Argument pList points to a position list nList bytes in size. This
143429 ** function checks to see if the position list contains any entries for
143430 ** a token in position 0 (of any column). If so, it writes argument iDelta
143431 ** to the output buffer pOut, followed by a position list consisting only
143432 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
143433 ** The value returned is the number of bytes written to pOut (if any).
143434 */
143435 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
143436  sqlite3_int64 iDelta, /* Varint that may be written to pOut */
143437  char *pList, /* Position list (no 0x00 term) */
143438  int nList, /* Size of pList in bytes */
143439  char *pOut /* Write output here */
143440 ){
143441  int nOut = 0;
143442  int bWritten = 0; /* True once iDelta has been written */
143443  char *p = pList;
143444  char *pEnd = &pList[nList];
143445 
143446  if( *p!=0x01 ){
143447  if( *p==0x02 ){
143448  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
143449  pOut[nOut++] = 0x02;
143450  bWritten = 1;
143451  }
143452  fts3ColumnlistCopy(0, &p);
143453  }
143454 
143455  while( p<pEnd && *p==0x01 ){
143456  sqlite3_int64 iCol;
143457  p++;
143458  p += sqlite3Fts3GetVarint(p, &iCol);
143459  if( *p==0x02 ){
143460  if( bWritten==0 ){
143461  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
143462  bWritten = 1;
143463  }
143464  pOut[nOut++] = 0x01;
143465  nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
143466  pOut[nOut++] = 0x02;
143467  }
143468  fts3ColumnlistCopy(0, &p);
143469  }
143470  if( bWritten ){
143471  pOut[nOut++] = 0x00;
143472  }
143473 
143474  return nOut;
143475 }
143476 
143477 
143478 /*
143479 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
143480 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
143481 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
143482 **
143483 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
143484 ** the responsibility of the caller to free any doclists left in the
143485 ** TermSelect.aaOutput[] array.
143486 */
143487 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
143488  char *aOut = 0;
143489  int nOut = 0;
143490  int i;
143491 
143492  /* Loop through the doclists in the aaOutput[] array. Merge them all
143493  ** into a single doclist.
143494  */
143495  for(i=0; i<SizeofArray(pTS->aaOutput); i++){
143496  if( pTS->aaOutput[i] ){
143497  if( !aOut ){
143498  aOut = pTS->aaOutput[i];
143499  nOut = pTS->anOutput[i];
143500  pTS->aaOutput[i] = 0;
143501  }else{
143502  int nNew;
143503  char *aNew;
143504 
143505  int rc = fts3DoclistOrMerge(p->bDescIdx,
143506  pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
143507  );
143508  if( rc!=SQLITE_OK ){
143509  sqlite3_free(aOut);
143510  return rc;
143511  }
143512 
143513  sqlite3_free(pTS->aaOutput[i]);
143514  sqlite3_free(aOut);
143515  pTS->aaOutput[i] = 0;
143516  aOut = aNew;
143517  nOut = nNew;
143518  }
143519  }
143520  }
143521 
143522  pTS->aaOutput[0] = aOut;
143523  pTS->anOutput[0] = nOut;
143524  return SQLITE_OK;
143525 }
143526 
143527 /*
143528 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
143529 ** as the first argument. The merge is an "OR" merge (see function
143530 ** fts3DoclistOrMerge() for details).
143531 **
143532 ** This function is called with the doclist for each term that matches
143533 ** a queried prefix. It merges all these doclists into one, the doclist
143534 ** for the specified prefix. Since there can be a very large number of
143535 ** doclists to merge, the merging is done pair-wise using the TermSelect
143536 ** object.
143537 **
143538 ** This function returns SQLITE_OK if the merge is successful, or an
143539 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
143540 */
143541 static int fts3TermSelectMerge(
143542  Fts3Table *p, /* FTS table handle */
143543  TermSelect *pTS, /* TermSelect object to merge into */
143544  char *aDoclist, /* Pointer to doclist */
143545  int nDoclist /* Size of aDoclist in bytes */
143546 ){
143547  if( pTS->aaOutput[0]==0 ){
143548  /* If this is the first term selected, copy the doclist to the output
143549  ** buffer using memcpy().
143550  **
143551  ** Add FTS3_VARINT_MAX bytes of unused space to the end of the
143552  ** allocation. This is so as to ensure that the buffer is big enough
143553  ** to hold the current doclist AND'd with any other doclist. If the
143554  ** doclists are stored in order=ASC order, this padding would not be
143555  ** required (since the size of [doclistA AND doclistB] is always less
143556  ** than or equal to the size of [doclistA] in that case). But this is
143557  ** not true for order=DESC. For example, a doclist containing (1, -1)
143558  ** may be smaller than (-1), as in the first example the -1 may be stored
143559  ** as a single-byte delta, whereas in the second it must be stored as a
143560  ** FTS3_VARINT_MAX byte varint.
143561  **
143562  ** Similar padding is added in the fts3DoclistOrMerge() function.
143563  */
143564  pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
143565  pTS->anOutput[0] = nDoclist;
143566  if( pTS->aaOutput[0] ){
143567  memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
143568  }else{
143569  return SQLITE_NOMEM;
143570  }
143571  }else{
143572  char *aMerge = aDoclist;
143573  int nMerge = nDoclist;
143574  int iOut;
143575 
143576  for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
143577  if( pTS->aaOutput[iOut]==0 ){
143578  assert( iOut>0 );
143579  pTS->aaOutput[iOut] = aMerge;
143580  pTS->anOutput[iOut] = nMerge;
143581  break;
143582  }else{
143583  char *aNew;
143584  int nNew;
143585 
143586  int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
143587  pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
143588  );
143589  if( rc!=SQLITE_OK ){
143590  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
143591  return rc;
143592  }
143593 
143594  if( aMerge!=aDoclist ) sqlite3_free(aMerge);
143595  sqlite3_free(pTS->aaOutput[iOut]);
143596  pTS->aaOutput[iOut] = 0;
143597 
143598  aMerge = aNew;
143599  nMerge = nNew;
143600  if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
143601  pTS->aaOutput[iOut] = aMerge;
143602  pTS->anOutput[iOut] = nMerge;
143603  }
143604  }
143605  }
143606  }
143607  return SQLITE_OK;
143608 }
143609 
143610 /*
143611 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
143612 */
143613 static int fts3SegReaderCursorAppend(
143614  Fts3MultiSegReader *pCsr,
143615  Fts3SegReader *pNew
143616 ){
143617  if( (pCsr->nSegment%16)==0 ){
143618  Fts3SegReader **apNew;
143619  int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
143620  apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
143621  if( !apNew ){
143622  sqlite3Fts3SegReaderFree(pNew);
143623  return SQLITE_NOMEM;
143624  }
143625  pCsr->apSegment = apNew;
143626  }
143627  pCsr->apSegment[pCsr->nSegment++] = pNew;
143628  return SQLITE_OK;
143629 }
143630 
143631 /*
143632 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
143633 ** 8th argument.
143634 **
143635 ** This function returns SQLITE_OK if successful, or an SQLite error code
143636 ** otherwise.
143637 */
143638 static int fts3SegReaderCursor(
143639  Fts3Table *p, /* FTS3 table handle */
143640  int iLangid, /* Language id */
143641  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
143642  int iLevel, /* Level of segments to scan */
143643  const char *zTerm, /* Term to query for */
143644  int nTerm, /* Size of zTerm in bytes */
143645  int isPrefix, /* True for a prefix search */
143646  int isScan, /* True to scan from zTerm to EOF */
143647  Fts3MultiSegReader *pCsr /* Cursor object to populate */
143648 ){
143649  int rc = SQLITE_OK; /* Error code */
143650  sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
143651  int rc2; /* Result of sqlite3_reset() */
143652 
143653  /* If iLevel is less than 0 and this is not a scan, include a seg-reader
143654  ** for the pending-terms. If this is a scan, then this call must be being
143655  ** made by an fts4aux module, not an FTS table. In this case calling
143656  ** Fts3SegReaderPending might segfault, as the data structures used by
143657  ** fts4aux are not completely populated. So it's easiest to filter these
143658  ** calls out here. */
143659  if( iLevel<0 && p->aIndex ){
143660  Fts3SegReader *pSeg = 0;
143661  rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix||isScan, &pSeg);
143662  if( rc==SQLITE_OK && pSeg ){
143663  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
143664  }
143665  }
143666 
143667  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
143668  if( rc==SQLITE_OK ){
143669  rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
143670  }
143671 
143672  while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
143673  Fts3SegReader *pSeg = 0;
143674 
143675  /* Read the values returned by the SELECT into local variables. */
143676  sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
143677  sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
143678  sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
143679  int nRoot = sqlite3_column_bytes(pStmt, 4);
143680  char const *zRoot = sqlite3_column_blob(pStmt, 4);
143681 
143682  /* If zTerm is not NULL, and this segment is not stored entirely on its
143683  ** root node, the range of leaves scanned can be reduced. Do this. */
143684  if( iStartBlock && zTerm ){
143685  sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
143686  rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
143687  if( rc!=SQLITE_OK ) goto finished;
143688  if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
143689  }
143690 
143691  rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
143692  (isPrefix==0 && isScan==0),
143693  iStartBlock, iLeavesEndBlock,
143694  iEndBlock, zRoot, nRoot, &pSeg
143695  );
143696  if( rc!=SQLITE_OK ) goto finished;
143697  rc = fts3SegReaderCursorAppend(pCsr, pSeg);
143698  }
143699  }
143700 
143701  finished:
143702  rc2 = sqlite3_reset(pStmt);
143703  if( rc==SQLITE_DONE ) rc = rc2;
143704 
143705  return rc;
143706 }
143707 
143708 /*
143709 ** Set up a cursor object for iterating through a full-text index or a
143710 ** single level therein.
143711 */
143712 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
143713  Fts3Table *p, /* FTS3 table handle */
143714  int iLangid, /* Language-id to search */
143715  int iIndex, /* Index to search (from 0 to p->nIndex-1) */
143716  int iLevel, /* Level of segments to scan */
143717  const char *zTerm, /* Term to query for */
143718  int nTerm, /* Size of zTerm in bytes */
143719  int isPrefix, /* True for a prefix search */
143720  int isScan, /* True to scan from zTerm to EOF */
143721  Fts3MultiSegReader *pCsr /* Cursor object to populate */
143722 ){
143723  assert( iIndex>=0 && iIndex<p->nIndex );
143724  assert( iLevel==FTS3_SEGCURSOR_ALL
143725  || iLevel==FTS3_SEGCURSOR_PENDING
143726  || iLevel>=0
143727  );
143728  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
143729  assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
143730  assert( isPrefix==0 || isScan==0 );
143731 
143732  memset(pCsr, 0, sizeof(Fts3MultiSegReader));
143733  return fts3SegReaderCursor(
143734  p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
143735  );
143736 }
143737 
143738 /*
143739 ** In addition to its current configuration, have the Fts3MultiSegReader
143740 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
143741 **
143742 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
143743 */
143744 static int fts3SegReaderCursorAddZero(
143745  Fts3Table *p, /* FTS virtual table handle */
143746  int iLangid,
143747  const char *zTerm, /* Term to scan doclist of */
143748  int nTerm, /* Number of bytes in zTerm */
143749  Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
143750 ){
143751  return fts3SegReaderCursor(p,
143752  iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
143753  );
143754 }
143755 
143756 /*
143757 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
143758 ** if isPrefix is true, to scan the doclist for all terms for which
143759 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
143760 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
143761 ** an SQLite error code.
143762 **
143763 ** It is the responsibility of the caller to free this object by eventually
143764 ** passing it to fts3SegReaderCursorFree()
143765 **
143766 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
143767 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
143768 */
143769 static int fts3TermSegReaderCursor(
143770  Fts3Cursor *pCsr, /* Virtual table cursor handle */
143771  const char *zTerm, /* Term to query for */
143772  int nTerm, /* Size of zTerm in bytes */
143773  int isPrefix, /* True for a prefix search */
143774  Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
143775 ){
143776  Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
143777  int rc = SQLITE_NOMEM; /* Return code */
143778 
143779  pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
143780  if( pSegcsr ){
143781  int i;
143782  int bFound = 0; /* True once an index has been found */
143783  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
143784 
143785  if( isPrefix ){
143786  for(i=1; bFound==0 && i<p->nIndex; i++){
143787  if( p->aIndex[i].nPrefix==nTerm ){
143788  bFound = 1;
143789  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
143790  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
143791  );
143792  pSegcsr->bLookup = 1;
143793  }
143794  }
143795 
143796  for(i=1; bFound==0 && i<p->nIndex; i++){
143797  if( p->aIndex[i].nPrefix==nTerm+1 ){
143798  bFound = 1;
143799  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
143800  i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
143801  );
143802  if( rc==SQLITE_OK ){
143803  rc = fts3SegReaderCursorAddZero(
143804  p, pCsr->iLangid, zTerm, nTerm, pSegcsr
143805  );
143806  }
143807  }
143808  }
143809  }
143810 
143811  if( bFound==0 ){
143812  rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
143813  0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
143814  );
143815  pSegcsr->bLookup = !isPrefix;
143816  }
143817  }
143818 
143819  *ppSegcsr = pSegcsr;
143820  return rc;
143821 }
143822 
143823 /*
143824 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
143825 */
143826 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
143827  sqlite3Fts3SegReaderFinish(pSegcsr);
143828  sqlite3_free(pSegcsr);
143829 }
143830 
143831 /*
143832 ** This function retrieves the doclist for the specified term (or term
143833 ** prefix) from the database.
143834 */
143835 static int fts3TermSelect(
143836  Fts3Table *p, /* Virtual table handle */
143837  Fts3PhraseToken *pTok, /* Token to query for */
143838  int iColumn, /* Column to query (or -ve for all columns) */
143839  int *pnOut, /* OUT: Size of buffer at *ppOut */
143840  char **ppOut /* OUT: Malloced result buffer */
143841 ){
143842  int rc; /* Return code */
143843  Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
143844  TermSelect tsc; /* Object for pair-wise doclist merging */
143845  Fts3SegFilter filter; /* Segment term filter configuration */
143846 
143847  pSegcsr = pTok->pSegcsr;
143848  memset(&tsc, 0, sizeof(TermSelect));
143849 
143850  filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
143851  | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
143852  | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
143853  | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
143854  filter.iCol = iColumn;
143855  filter.zTerm = pTok->z;
143856  filter.nTerm = pTok->n;
143857 
143858  rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
143859  while( SQLITE_OK==rc
143860  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
143861  ){
143862  rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
143863  }
143864 
143865  if( rc==SQLITE_OK ){
143866  rc = fts3TermSelectFinishMerge(p, &tsc);
143867  }
143868  if( rc==SQLITE_OK ){
143869  *ppOut = tsc.aaOutput[0];
143870  *pnOut = tsc.anOutput[0];
143871  }else{
143872  int i;
143873  for(i=0; i<SizeofArray(tsc.aaOutput); i++){
143874  sqlite3_free(tsc.aaOutput[i]);
143875  }
143876  }
143877 
143878  fts3SegReaderCursorFree(pSegcsr);
143879  pTok->pSegcsr = 0;
143880  return rc;
143881 }
143882 
143883 /*
143884 ** This function counts the total number of docids in the doclist stored
143885 ** in buffer aList[], size nList bytes.
143886 **
143887 ** If the isPoslist argument is true, then it is assumed that the doclist
143888 ** contains a position-list following each docid. Otherwise, it is assumed
143889 ** that the doclist is simply a list of docids stored as delta encoded
143890 ** varints.
143891 */
143892 static int fts3DoclistCountDocids(char *aList, int nList){
143893  int nDoc = 0; /* Return value */
143894  if( aList ){
143895  char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
143896  char *p = aList; /* Cursor */
143897  while( p<aEnd ){
143898  nDoc++;
143899  while( (*p++)&0x80 ); /* Skip docid varint */
143900  fts3PoslistCopy(0, &p); /* Skip over position list */
143901  }
143902  }
143903 
143904  return nDoc;
143905 }
143906 
143907 /*
143908 ** Advance the cursor to the next row in the %_content table that
143909 ** matches the search criteria. For a MATCH search, this will be
143910 ** the next row that matches. For a full-table scan, this will be
143911 ** simply the next row in the %_content table. For a docid lookup,
143912 ** this routine simply sets the EOF flag.
143913 **
143914 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
143915 ** even if we reach end-of-file. The fts3EofMethod() will be called
143916 ** subsequently to determine whether or not an EOF was hit.
143917 */
143918 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
143919  int rc;
143920  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
143921  if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
143922  if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
143923  pCsr->isEof = 1;
143924  rc = sqlite3_reset(pCsr->pStmt);
143925  }else{
143926  pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
143927  rc = SQLITE_OK;
143928  }
143929  }else{
143930  rc = fts3EvalNext((Fts3Cursor *)pCursor);
143931  }
143932  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
143933  return rc;
143934 }
143935 
143936 /*
143937 ** The following are copied from sqliteInt.h.
143938 **
143939 ** Constants for the largest and smallest possible 64-bit signed integers.
143940 ** These macros are designed to work correctly on both 32-bit and 64-bit
143941 ** compilers.
143942 */
143943 #ifndef SQLITE_AMALGAMATION
143944 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
143945 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
143946 #endif
143947 
143948 /*
143949 ** If the numeric type of argument pVal is "integer", then return it
143950 ** converted to a 64-bit signed integer. Otherwise, return a copy of
143951 ** the second parameter, iDefault.
143952 */
143953 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
143954  if( pVal ){
143955  int eType = sqlite3_value_numeric_type(pVal);
143956  if( eType==SQLITE_INTEGER ){
143957  return sqlite3_value_int64(pVal);
143958  }
143959  }
143960  return iDefault;
143961 }
143962 
143963 /*
143964 ** This is the xFilter interface for the virtual table. See
143965 ** the virtual table xFilter method documentation for additional
143966 ** information.
143967 **
143968 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
143969 ** the %_content table.
143970 **
143971 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
143972 ** in the %_content table.
143973 **
143974 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
143975 ** column on the left-hand side of the MATCH operator is column
143976 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
143977 ** side of the MATCH operator.
143978 */
143979 static int fts3FilterMethod(
143980  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
143981  int idxNum, /* Strategy index */
143982  const char *idxStr, /* Unused */
143983  int nVal, /* Number of elements in apVal */
143984  sqlite3_value **apVal /* Arguments for the indexing scheme */
143985 ){
143986  int rc = SQLITE_OK;
143987  char *zSql; /* SQL statement used to access %_content */
143988  int eSearch;
143989  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
143990  Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
143991 
143992  sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
143993  sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
143994  sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
143995  sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
143996  int iIdx;
143997 
143998  UNUSED_PARAMETER(idxStr);
143999  UNUSED_PARAMETER(nVal);
144000 
144001  eSearch = (idxNum & 0x0000FFFF);
144002  assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
144003  assert( p->pSegments==0 );
144004 
144005  /* Collect arguments into local variables */
144006  iIdx = 0;
144007  if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
144008  if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
144009  if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
144010  if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
144011  assert( iIdx==nVal );
144012 
144013  /* In case the cursor has been used before, clear it now. */
144014  sqlite3_finalize(pCsr->pStmt);
144015  sqlite3_free(pCsr->aDoclist);
144016  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
144017  sqlite3Fts3ExprFree(pCsr->pExpr);
144018  memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
144019 
144020  /* Set the lower and upper bounds on docids to return */
144021  pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
144022  pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
144023 
144024  if( idxStr ){
144025  pCsr->bDesc = (idxStr[0]=='D');
144026  }else{
144027  pCsr->bDesc = p->bDescIdx;
144028  }
144029  pCsr->eSearch = (i16)eSearch;
144030 
144031  if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
144032  int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
144033  const char *zQuery = (const char *)sqlite3_value_text(pCons);
144034 
144035  if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
144036  return SQLITE_NOMEM;
144037  }
144038 
144039  pCsr->iLangid = 0;
144040  if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
144041 
144042  assert( p->base.zErrMsg==0 );
144043  rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
144044  p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
144045  &p->base.zErrMsg
144046  );
144047  if( rc!=SQLITE_OK ){
144048  return rc;
144049  }
144050 
144051  rc = fts3EvalStart(pCsr);
144052  sqlite3Fts3SegmentsClose(p);
144053  if( rc!=SQLITE_OK ) return rc;
144054  pCsr->pNextId = pCsr->aDoclist;
144055  pCsr->iPrevId = 0;
144056  }
144057 
144058  /* Compile a SELECT statement for this cursor. For a full-table-scan, the
144059  ** statement loops through all rows of the %_content table. For a
144060  ** full-text query or docid lookup, the statement retrieves a single
144061  ** row by docid.
144062  */
144063  if( eSearch==FTS3_FULLSCAN_SEARCH ){
144064  if( pDocidGe || pDocidLe ){
144065  zSql = sqlite3_mprintf(
144066  "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
144067  p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
144068  (pCsr->bDesc ? "DESC" : "ASC")
144069  );
144070  }else{
144071  zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s",
144072  p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
144073  );
144074  }
144075  if( zSql ){
144076  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
144077  sqlite3_free(zSql);
144078  }else{
144079  rc = SQLITE_NOMEM;
144080  }
144081  }else if( eSearch==FTS3_DOCID_SEARCH ){
144082  rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
144083  if( rc==SQLITE_OK ){
144084  rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
144085  }
144086  }
144087  if( rc!=SQLITE_OK ) return rc;
144088 
144089  return fts3NextMethod(pCursor);
144090 }
144091 
144092 /*
144093 ** This is the xEof method of the virtual table. SQLite calls this
144094 ** routine to find out if it has reached the end of a result set.
144095 */
144096 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
144097  return ((Fts3Cursor *)pCursor)->isEof;
144098 }
144099 
144100 /*
144101 ** This is the xRowid method. The SQLite core calls this routine to
144102 ** retrieve the rowid for the current row of the result set. fts3
144103 ** exposes %_content.docid as the rowid for the virtual table. The
144104 ** rowid should be written to *pRowid.
144105 */
144106 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
144107  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
144108  *pRowid = pCsr->iPrevId;
144109  return SQLITE_OK;
144110 }
144111 
144112 /*
144113 ** This is the xColumn method, called by SQLite to request a value from
144114 ** the row that the supplied cursor currently points to.
144115 **
144116 ** If:
144117 **
144118 ** (iCol < p->nColumn) -> The value of the iCol'th user column.
144119 ** (iCol == p->nColumn) -> Magic column with the same name as the table.
144120 ** (iCol == p->nColumn+1) -> Docid column
144121 ** (iCol == p->nColumn+2) -> Langid column
144122 */
144123 static int fts3ColumnMethod(
144124  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
144125  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
144126  int iCol /* Index of column to read value from */
144127 ){
144128  int rc = SQLITE_OK; /* Return Code */
144129  Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
144130  Fts3Table *p = (Fts3Table *)pCursor->pVtab;
144131 
144132  /* The column value supplied by SQLite must be in range. */
144133  assert( iCol>=0 && iCol<=p->nColumn+2 );
144134 
144135  if( iCol==p->nColumn+1 ){
144136  /* This call is a request for the "docid" column. Since "docid" is an
144137  ** alias for "rowid", use the xRowid() method to obtain the value.
144138  */
144139  sqlite3_result_int64(pCtx, pCsr->iPrevId);
144140  }else if( iCol==p->nColumn ){
144141  /* The extra column whose name is the same as the table.
144142  ** Return a blob which is a pointer to the cursor. */
144143  sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
144144  }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
144145  sqlite3_result_int64(pCtx, pCsr->iLangid);
144146  }else{
144147  /* The requested column is either a user column (one that contains
144148  ** indexed data), or the language-id column. */
144149  rc = fts3CursorSeek(0, pCsr);
144150 
144151  if( rc==SQLITE_OK ){
144152  if( iCol==p->nColumn+2 ){
144153  int iLangid = 0;
144154  if( p->zLanguageid ){
144155  iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
144156  }
144157  sqlite3_result_int(pCtx, iLangid);
144158  }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
144159  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
144160  }
144161  }
144162  }
144163 
144164  assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
144165  return rc;
144166 }
144167 
144168 /*
144169 ** This function is the implementation of the xUpdate callback used by
144170 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
144171 ** inserted, updated or deleted.
144172 */
144173 static int fts3UpdateMethod(
144174  sqlite3_vtab *pVtab, /* Virtual table handle */
144175  int nArg, /* Size of argument array */
144176  sqlite3_value **apVal, /* Array of arguments */
144177  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
144178 ){
144179  return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
144180 }
144181 
144182 /*
144183 ** Implementation of xSync() method. Flush the contents of the pending-terms
144184 ** hash-table to the database.
144185 */
144186 static int fts3SyncMethod(sqlite3_vtab *pVtab){
144187 
144188  /* Following an incremental-merge operation, assuming that the input
144189  ** segments are not completely consumed (the usual case), they are updated
144190  ** in place to remove the entries that have already been merged. This
144191  ** involves updating the leaf block that contains the smallest unmerged
144192  ** entry and each block (if any) between the leaf and the root node. So
144193  ** if the height of the input segment b-trees is N, and input segments
144194  ** are merged eight at a time, updating the input segments at the end
144195  ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
144196  ** small - often between 0 and 2. So the overhead of the incremental
144197  ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
144198  ** dwarfing the actual productive work accomplished, the incremental merge
144199  ** is only attempted if it will write at least 64 leaf blocks. Hence
144200  ** nMinMerge.
144201  **
144202  ** Of course, updating the input segments also involves deleting a bunch
144203  ** of blocks from the segments table. But this is not considered overhead
144204  ** as it would also be required by a crisis-merge that used the same input
144205  ** segments.
144206  */
144207  const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
144208 
144209  Fts3Table *p = (Fts3Table*)pVtab;
144210  int rc = sqlite3Fts3PendingTermsFlush(p);
144211 
144212  if( rc==SQLITE_OK
144213  && p->nLeafAdd>(nMinMerge/16)
144214  && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
144215  ){
144216  int mxLevel = 0; /* Maximum relative level value in db */
144217  int A; /* Incr-merge parameter A */
144218 
144219  rc = sqlite3Fts3MaxLevel(p, &mxLevel);
144220  assert( rc==SQLITE_OK || mxLevel==0 );
144221  A = p->nLeafAdd * mxLevel;
144222  A += (A/2);
144223  if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
144224  }
144225  sqlite3Fts3SegmentsClose(p);
144226  return rc;
144227 }
144228 
144229 /*
144230 ** If it is currently unknown whether or not the FTS table has an %_stat
144231 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
144232 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
144233 ** if an error occurs.
144234 */
144235 static int fts3SetHasStat(Fts3Table *p){
144236  int rc = SQLITE_OK;
144237  if( p->bHasStat==2 ){
144238  const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
144239  char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
144240  if( zSql ){
144241  sqlite3_stmt *pStmt = 0;
144242  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
144243  if( rc==SQLITE_OK ){
144244  int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
144245  rc = sqlite3_finalize(pStmt);
144246  if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
144247  }
144248  sqlite3_free(zSql);
144249  }else{
144250  rc = SQLITE_NOMEM;
144251  }
144252  }
144253  return rc;
144254 }
144255 
144256 /*
144257 ** Implementation of xBegin() method.
144258 */
144259 static int fts3BeginMethod(sqlite3_vtab *pVtab){
144260  Fts3Table *p = (Fts3Table*)pVtab;
144261  UNUSED_PARAMETER(pVtab);
144262  assert( p->pSegments==0 );
144263  assert( p->nPendingData==0 );
144264  assert( p->inTransaction!=1 );
144265  TESTONLY( p->inTransaction = 1 );
144266  TESTONLY( p->mxSavepoint = -1; );
144267  p->nLeafAdd = 0;
144268  return fts3SetHasStat(p);
144269 }
144270 
144271 /*
144272 ** Implementation of xCommit() method. This is a no-op. The contents of
144273 ** the pending-terms hash-table have already been flushed into the database
144274 ** by fts3SyncMethod().
144275 */
144276 static int fts3CommitMethod(sqlite3_vtab *pVtab){
144277  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
144278  UNUSED_PARAMETER(pVtab);
144279  assert( p->nPendingData==0 );
144280  assert( p->inTransaction!=0 );
144281  assert( p->pSegments==0 );
144282  TESTONLY( p->inTransaction = 0 );
144283  TESTONLY( p->mxSavepoint = -1; );
144284  return SQLITE_OK;
144285 }
144286 
144287 /*
144288 ** Implementation of xRollback(). Discard the contents of the pending-terms
144289 ** hash-table. Any changes made to the database are reverted by SQLite.
144290 */
144291 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
144292  Fts3Table *p = (Fts3Table*)pVtab;
144293  sqlite3Fts3PendingTermsClear(p);
144294  assert( p->inTransaction!=0 );
144295  TESTONLY( p->inTransaction = 0 );
144296  TESTONLY( p->mxSavepoint = -1; );
144297  return SQLITE_OK;
144298 }
144299 
144300 /*
144301 ** When called, *ppPoslist must point to the byte immediately following the
144302 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
144303 ** moves *ppPoslist so that it instead points to the first byte of the
144304 ** same position list.
144305 */
144306 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
144307  char *p = &(*ppPoslist)[-2];
144308  char c = 0;
144309 
144310  /* Skip backwards passed any trailing 0x00 bytes added by NearTrim() */
144311  while( p>pStart && (c=*p--)==0 );
144312 
144313  /* Search backwards for a varint with value zero (the end of the previous
144314  ** poslist). This is an 0x00 byte preceded by some byte that does not
144315  ** have the 0x80 bit set. */
144316  while( p>pStart && (*p & 0x80) | c ){
144317  c = *p--;
144318  }
144319  assert( p==pStart || c==0 );
144320 
144321  /* At this point p points to that preceding byte without the 0x80 bit
144322  ** set. So to find the start of the poslist, skip forward 2 bytes then
144323  ** over a varint.
144324  **
144325  ** Normally. The other case is that p==pStart and the poslist to return
144326  ** is the first in the doclist. In this case do not skip forward 2 bytes.
144327  ** The second part of the if condition (c==0 && *ppPoslist>&p[2])
144328  ** is required for cases where the first byte of a doclist and the
144329  ** doclist is empty. For example, if the first docid is 10, a doclist
144330  ** that begins with:
144331  **
144332  ** 0x0A 0x00 <next docid delta varint>
144333  */
144334  if( p>pStart || (c==0 && *ppPoslist>&p[2]) ){ p = &p[2]; }
144335  while( *p++&0x80 );
144336  *ppPoslist = p;
144337 }
144338 
144339 /*
144340 ** Helper function used by the implementation of the overloaded snippet(),
144341 ** offsets() and optimize() SQL functions.
144342 **
144343 ** If the value passed as the third argument is a blob of size
144344 ** sizeof(Fts3Cursor*), then the blob contents are copied to the
144345 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
144346 ** message is written to context pContext and SQLITE_ERROR returned. The
144347 ** string passed via zFunc is used as part of the error message.
144348 */
144349 static int fts3FunctionArg(
144350  sqlite3_context *pContext, /* SQL function call context */
144351  const char *zFunc, /* Function name */
144352  sqlite3_value *pVal, /* argv[0] passed to function */
144353  Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
144354 ){
144355  Fts3Cursor *pRet;
144356  if( sqlite3_value_type(pVal)!=SQLITE_BLOB
144357  || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
144358  ){
144359  char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
144360  sqlite3_result_error(pContext, zErr, -1);
144361  sqlite3_free(zErr);
144362  return SQLITE_ERROR;
144363  }
144364  memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
144365  *ppCsr = pRet;
144366  return SQLITE_OK;
144367 }
144368 
144369 /*
144370 ** Implementation of the snippet() function for FTS3
144371 */
144372 static void fts3SnippetFunc(
144373  sqlite3_context *pContext, /* SQLite function call context */
144374  int nVal, /* Size of apVal[] array */
144375  sqlite3_value **apVal /* Array of arguments */
144376 ){
144377  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
144378  const char *zStart = "<b>";
144379  const char *zEnd = "</b>";
144380  const char *zEllipsis = "<b>...</b>";
144381  int iCol = -1;
144382  int nToken = 15; /* Default number of tokens in snippet */
144383 
144384  /* There must be at least one argument passed to this function (otherwise
144385  ** the non-overloaded version would have been called instead of this one).
144386  */
144387  assert( nVal>=1 );
144388 
144389  if( nVal>6 ){
144390  sqlite3_result_error(pContext,
144391  "wrong number of arguments to function snippet()", -1);
144392  return;
144393  }
144394  if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
144395 
144396  switch( nVal ){
144397  case 6: nToken = sqlite3_value_int(apVal[5]);
144398  case 5: iCol = sqlite3_value_int(apVal[4]);
144399  case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
144400  case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
144401  case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
144402  }
144403  if( !zEllipsis || !zEnd || !zStart ){
144404  sqlite3_result_error_nomem(pContext);
144405  }else if( nToken==0 ){
144406  sqlite3_result_text(pContext, "", -1, SQLITE_STATIC);
144407  }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
144408  sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
144409  }
144410 }
144411 
144412 /*
144413 ** Implementation of the offsets() function for FTS3
144414 */
144415 static void fts3OffsetsFunc(
144416  sqlite3_context *pContext, /* SQLite function call context */
144417  int nVal, /* Size of argument array */
144418  sqlite3_value **apVal /* Array of arguments */
144419 ){
144420  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
144421 
144422  UNUSED_PARAMETER(nVal);
144423 
144424  assert( nVal==1 );
144425  if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
144426  assert( pCsr );
144427  if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
144428  sqlite3Fts3Offsets(pContext, pCsr);
144429  }
144430 }
144431 
144432 /*
144433 ** Implementation of the special optimize() function for FTS3. This
144434 ** function merges all segments in the database to a single segment.
144435 ** Example usage is:
144436 **
144437 ** SELECT optimize(t) FROM t LIMIT 1;
144438 **
144439 ** where 't' is the name of an FTS3 table.
144440 */
144441 static void fts3OptimizeFunc(
144442  sqlite3_context *pContext, /* SQLite function call context */
144443  int nVal, /* Size of argument array */
144444  sqlite3_value **apVal /* Array of arguments */
144445 ){
144446  int rc; /* Return code */
144447  Fts3Table *p; /* Virtual table handle */
144448  Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
144449 
144450  UNUSED_PARAMETER(nVal);
144451 
144452  assert( nVal==1 );
144453  if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
144454  p = (Fts3Table *)pCursor->base.pVtab;
144455  assert( p );
144456 
144457  rc = sqlite3Fts3Optimize(p);
144458 
144459  switch( rc ){
144460  case SQLITE_OK:
144461  sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
144462  break;
144463  case SQLITE_DONE:
144464  sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
144465  break;
144466  default:
144467  sqlite3_result_error_code(pContext, rc);
144468  break;
144469  }
144470 }
144471 
144472 /*
144473 ** Implementation of the matchinfo() function for FTS3
144474 */
144475 static void fts3MatchinfoFunc(
144476  sqlite3_context *pContext, /* SQLite function call context */
144477  int nVal, /* Size of argument array */
144478  sqlite3_value **apVal /* Array of arguments */
144479 ){
144480  Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
144481  assert( nVal==1 || nVal==2 );
144482  if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
144483  const char *zArg = 0;
144484  if( nVal>1 ){
144485  zArg = (const char *)sqlite3_value_text(apVal[1]);
144486  }
144487  sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
144488  }
144489 }
144490 
144491 /*
144492 ** This routine implements the xFindFunction method for the FTS3
144493 ** virtual table.
144494 */
144495 static int fts3FindFunctionMethod(
144496  sqlite3_vtab *pVtab, /* Virtual table handle */
144497  int nArg, /* Number of SQL function arguments */
144498  const char *zName, /* Name of SQL function */
144499  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
144500  void **ppArg /* Unused */
144501 ){
144502  struct Overloaded {
144503  const char *zName;
144504  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
144505  } aOverload[] = {
144506  { "snippet", fts3SnippetFunc },
144507  { "offsets", fts3OffsetsFunc },
144508  { "optimize", fts3OptimizeFunc },
144509  { "matchinfo", fts3MatchinfoFunc },
144510  };
144511  int i; /* Iterator variable */
144512 
144513  UNUSED_PARAMETER(pVtab);
144514  UNUSED_PARAMETER(nArg);
144515  UNUSED_PARAMETER(ppArg);
144516 
144517  for(i=0; i<SizeofArray(aOverload); i++){
144518  if( strcmp(zName, aOverload[i].zName)==0 ){
144519  *pxFunc = aOverload[i].xFunc;
144520  return 1;
144521  }
144522  }
144523 
144524  /* No function of the specified name was found. Return 0. */
144525  return 0;
144526 }
144527 
144528 /*
144529 ** Implementation of FTS3 xRename method. Rename an fts3 table.
144530 */
144531 static int fts3RenameMethod(
144532  sqlite3_vtab *pVtab, /* Virtual table handle */
144533  const char *zName /* New name of table */
144534 ){
144535  Fts3Table *p = (Fts3Table *)pVtab;
144536  sqlite3 *db = p->db; /* Database connection */
144537  int rc; /* Return Code */
144538 
144539  /* At this point it must be known if the %_stat table exists or not.
144540  ** So bHasStat may not be 2. */
144541  rc = fts3SetHasStat(p);
144542 
144543  /* As it happens, the pending terms table is always empty here. This is
144544  ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
144545  ** always opens a savepoint transaction. And the xSavepoint() method
144546  ** flushes the pending terms table. But leave the (no-op) call to
144547  ** PendingTermsFlush() in in case that changes.
144548  */
144549  assert( p->nPendingData==0 );
144550  if( rc==SQLITE_OK ){
144551  rc = sqlite3Fts3PendingTermsFlush(p);
144552  }
144553 
144554  if( p->zContentTbl==0 ){
144555  fts3DbExec(&rc, db,
144556  "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
144557  p->zDb, p->zName, zName
144558  );
144559  }
144560 
144561  if( p->bHasDocsize ){
144562  fts3DbExec(&rc, db,
144563  "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
144564  p->zDb, p->zName, zName
144565  );
144566  }
144567  if( p->bHasStat ){
144568  fts3DbExec(&rc, db,
144569  "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
144570  p->zDb, p->zName, zName
144571  );
144572  }
144573  fts3DbExec(&rc, db,
144574  "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
144575  p->zDb, p->zName, zName
144576  );
144577  fts3DbExec(&rc, db,
144578  "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
144579  p->zDb, p->zName, zName
144580  );
144581  return rc;
144582 }
144583 
144584 /*
144585 ** The xSavepoint() method.
144586 **
144587 ** Flush the contents of the pending-terms table to disk.
144588 */
144589 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
144590  int rc = SQLITE_OK;
144591  UNUSED_PARAMETER(iSavepoint);
144592  assert( ((Fts3Table *)pVtab)->inTransaction );
144593  assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
144594  TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
144595  if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
144596  rc = fts3SyncMethod(pVtab);
144597  }
144598  return rc;
144599 }
144600 
144601 /*
144602 ** The xRelease() method.
144603 **
144604 ** This is a no-op.
144605 */
144606 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
144607  TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
144608  UNUSED_PARAMETER(iSavepoint);
144609  UNUSED_PARAMETER(pVtab);
144610  assert( p->inTransaction );
144611  assert( p->mxSavepoint >= iSavepoint );
144612  TESTONLY( p->mxSavepoint = iSavepoint-1 );
144613  return SQLITE_OK;
144614 }
144615 
144616 /*
144617 ** The xRollbackTo() method.
144618 **
144619 ** Discard the contents of the pending terms table.
144620 */
144621 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
144622  Fts3Table *p = (Fts3Table*)pVtab;
144623  UNUSED_PARAMETER(iSavepoint);
144624  assert( p->inTransaction );
144625  assert( p->mxSavepoint >= iSavepoint );
144626  TESTONLY( p->mxSavepoint = iSavepoint );
144627  sqlite3Fts3PendingTermsClear(p);
144628  return SQLITE_OK;
144629 }
144630 
144631 static const sqlite3_module fts3Module = {
144632  /* iVersion */ 2,
144633  /* xCreate */ fts3CreateMethod,
144634  /* xConnect */ fts3ConnectMethod,
144635  /* xBestIndex */ fts3BestIndexMethod,
144636  /* xDisconnect */ fts3DisconnectMethod,
144637  /* xDestroy */ fts3DestroyMethod,
144638  /* xOpen */ fts3OpenMethod,
144639  /* xClose */ fts3CloseMethod,
144640  /* xFilter */ fts3FilterMethod,
144641  /* xNext */ fts3NextMethod,
144642  /* xEof */ fts3EofMethod,
144643  /* xColumn */ fts3ColumnMethod,
144644  /* xRowid */ fts3RowidMethod,
144645  /* xUpdate */ fts3UpdateMethod,
144646  /* xBegin */ fts3BeginMethod,
144647  /* xSync */ fts3SyncMethod,
144648  /* xCommit */ fts3CommitMethod,
144649  /* xRollback */ fts3RollbackMethod,
144650  /* xFindFunction */ fts3FindFunctionMethod,
144651  /* xRename */ fts3RenameMethod,
144652  /* xSavepoint */ fts3SavepointMethod,
144653  /* xRelease */ fts3ReleaseMethod,
144654  /* xRollbackTo */ fts3RollbackToMethod,
144655 };
144656 
144657 /*
144658 ** This function is registered as the module destructor (called when an
144659 ** FTS3 enabled database connection is closed). It frees the memory
144660 ** allocated for the tokenizer hash table.
144661 */
144662 static void hashDestroy(void *p){
144663  Fts3Hash *pHash = (Fts3Hash *)p;
144664  sqlite3Fts3HashClear(pHash);
144665  sqlite3_free(pHash);
144666 }
144667 
144668 /*
144669 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
144670 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
144671 ** respectively. The following three forward declarations are for functions
144672 ** declared in these files used to retrieve the respective implementations.
144673 **
144674 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
144675 ** to by the argument to point to the "simple" tokenizer implementation.
144676 ** And so on.
144677 */
144678 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
144679 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
144680 #ifndef SQLITE_DISABLE_FTS3_UNICODE
144681 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
144682 #endif
144683 #ifdef SQLITE_ENABLE_ICU
144684 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
144685 #endif
144686 
144687 /*
144688 ** Initialize the fts3 extension. If this extension is built as part
144689 ** of the sqlite library, then this function is called directly by
144690 ** SQLite. If fts3 is built as a dynamically loadable extension, this
144691 ** function is called by the sqlite3_extension_init() entry point.
144692 */
144693 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
144694  int rc = SQLITE_OK;
144695  Fts3Hash *pHash = 0;
144696  const sqlite3_tokenizer_module *pSimple = 0;
144697  const sqlite3_tokenizer_module *pPorter = 0;
144698 #ifndef SQLITE_DISABLE_FTS3_UNICODE
144699  const sqlite3_tokenizer_module *pUnicode = 0;
144700 #endif
144701 
144702 #ifdef SQLITE_ENABLE_ICU
144703  const sqlite3_tokenizer_module *pIcu = 0;
144704  sqlite3Fts3IcuTokenizerModule(&pIcu);
144705 #endif
144706 
144707 #ifndef SQLITE_DISABLE_FTS3_UNICODE
144708  sqlite3Fts3UnicodeTokenizer(&pUnicode);
144709 #endif
144710 
144711 #ifdef SQLITE_TEST
144712  rc = sqlite3Fts3InitTerm(db);
144713  if( rc!=SQLITE_OK ) return rc;
144714 #endif
144715 
144716  rc = sqlite3Fts3InitAux(db);
144717  if( rc!=SQLITE_OK ) return rc;
144718 
144719  sqlite3Fts3SimpleTokenizerModule(&pSimple);
144720  sqlite3Fts3PorterTokenizerModule(&pPorter);
144721 
144722  /* Allocate and initialize the hash-table used to store tokenizers. */
144723  pHash = sqlite3_malloc(sizeof(Fts3Hash));
144724  if( !pHash ){
144725  rc = SQLITE_NOMEM;
144726  }else{
144727  sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
144728  }
144729 
144730  /* Load the built-in tokenizers into the hash table */
144731  if( rc==SQLITE_OK ){
144732  if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
144733  || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
144734 
144735 #ifndef SQLITE_DISABLE_FTS3_UNICODE
144736  || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
144737 #endif
144738 #ifdef SQLITE_ENABLE_ICU
144739  || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
144740 #endif
144741  ){
144742  rc = SQLITE_NOMEM;
144743  }
144744  }
144745 
144746 #ifdef SQLITE_TEST
144747  if( rc==SQLITE_OK ){
144748  rc = sqlite3Fts3ExprInitTestInterface(db);
144749  }
144750 #endif
144751 
144752  /* Create the virtual table wrapper around the hash-table and overload
144753  ** the two scalar functions. If this is successful, register the
144754  ** module with sqlite.
144755  */
144756  if( SQLITE_OK==rc
144757  && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
144758  && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
144759  && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
144760  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
144761  && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
144762  && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
144763  ){
144765  db, "fts3", &fts3Module, (void *)pHash, hashDestroy
144766  );
144767  if( rc==SQLITE_OK ){
144769  db, "fts4", &fts3Module, (void *)pHash, 0
144770  );
144771  }
144772  if( rc==SQLITE_OK ){
144773  rc = sqlite3Fts3InitTok(db, (void *)pHash);
144774  }
144775  return rc;
144776  }
144777 
144778 
144779  /* An error has occurred. Delete the hash table and return the error code. */
144780  assert( rc!=SQLITE_OK );
144781  if( pHash ){
144782  sqlite3Fts3HashClear(pHash);
144783  sqlite3_free(pHash);
144784  }
144785  return rc;
144786 }
144787 
144788 /*
144789 ** Allocate an Fts3MultiSegReader for each token in the expression headed
144790 ** by pExpr.
144791 **
144792 ** An Fts3SegReader object is a cursor that can seek or scan a range of
144793 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
144794 ** Fts3SegReader objects internally to provide an interface to seek or scan
144795 ** within the union of all segments of a b-tree. Hence the name.
144796 **
144797 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
144798 ** segment b-tree (if the term is not a prefix or it is a prefix for which
144799 ** there exists prefix b-tree of the right length) then it may be traversed
144800 ** and merged incrementally. Otherwise, it has to be merged into an in-memory
144801 ** doclist and then traversed.
144802 */
144803 static void fts3EvalAllocateReaders(
144804  Fts3Cursor *pCsr, /* FTS cursor handle */
144805  Fts3Expr *pExpr, /* Allocate readers for this expression */
144806  int *pnToken, /* OUT: Total number of tokens in phrase. */
144807  int *pnOr, /* OUT: Total number of OR nodes in expr. */
144808  int *pRc /* IN/OUT: Error code */
144809 ){
144810  if( pExpr && SQLITE_OK==*pRc ){
144811  if( pExpr->eType==FTSQUERY_PHRASE ){
144812  int i;
144813  int nToken = pExpr->pPhrase->nToken;
144814  *pnToken += nToken;
144815  for(i=0; i<nToken; i++){
144816  Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
144817  int rc = fts3TermSegReaderCursor(pCsr,
144818  pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
144819  );
144820  if( rc!=SQLITE_OK ){
144821  *pRc = rc;
144822  return;
144823  }
144824  }
144825  assert( pExpr->pPhrase->iDoclistToken==0 );
144826  pExpr->pPhrase->iDoclistToken = -1;
144827  }else{
144828  *pnOr += (pExpr->eType==FTSQUERY_OR);
144829  fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
144830  fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
144831  }
144832  }
144833 }
144834 
144835 /*
144836 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
144837 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
144838 **
144839 ** This function assumes that pList points to a buffer allocated using
144840 ** sqlite3_malloc(). This function takes responsibility for eventually
144841 ** freeing the buffer.
144842 **
144843 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
144844 */
144845 static int fts3EvalPhraseMergeToken(
144846  Fts3Table *pTab, /* FTS Table pointer */
144847  Fts3Phrase *p, /* Phrase to merge pList/nList into */
144848  int iToken, /* Token pList/nList corresponds to */
144849  char *pList, /* Pointer to doclist */
144850  int nList /* Number of bytes in pList */
144851 ){
144852  int rc = SQLITE_OK;
144853  assert( iToken!=p->iDoclistToken );
144854 
144855  if( pList==0 ){
144856  sqlite3_free(p->doclist.aAll);
144857  p->doclist.aAll = 0;
144858  p->doclist.nAll = 0;
144859  }
144860 
144861  else if( p->iDoclistToken<0 ){
144862  p->doclist.aAll = pList;
144863  p->doclist.nAll = nList;
144864  }
144865 
144866  else if( p->doclist.aAll==0 ){
144867  sqlite3_free(pList);
144868  }
144869 
144870  else {
144871  char *pLeft;
144872  char *pRight;
144873  int nLeft;
144874  int nRight;
144875  int nDiff;
144876 
144877  if( p->iDoclistToken<iToken ){
144878  pLeft = p->doclist.aAll;
144879  nLeft = p->doclist.nAll;
144880  pRight = pList;
144881  nRight = nList;
144882  nDiff = iToken - p->iDoclistToken;
144883  }else{
144884  pRight = p->doclist.aAll;
144885  nRight = p->doclist.nAll;
144886  pLeft = pList;
144887  nLeft = nList;
144888  nDiff = p->iDoclistToken - iToken;
144889  }
144890 
144891  rc = fts3DoclistPhraseMerge(
144892  pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
144893  );
144894  sqlite3_free(pLeft);
144895  p->doclist.aAll = pRight;
144896  p->doclist.nAll = nRight;
144897  }
144898 
144899  if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
144900  return rc;
144901 }
144902 
144903 /*
144904 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
144905 ** does not take deferred tokens into account.
144906 **
144907 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144908 */
144909 static int fts3EvalPhraseLoad(
144910  Fts3Cursor *pCsr, /* FTS Cursor handle */
144911  Fts3Phrase *p /* Phrase object */
144912 ){
144913  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
144914  int iToken;
144915  int rc = SQLITE_OK;
144916 
144917  for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
144918  Fts3PhraseToken *pToken = &p->aToken[iToken];
144919  assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
144920 
144921  if( pToken->pSegcsr ){
144922  int nThis = 0;
144923  char *pThis = 0;
144924  rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
144925  if( rc==SQLITE_OK ){
144926  rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
144927  }
144928  }
144929  assert( pToken->pSegcsr==0 );
144930  }
144931 
144932  return rc;
144933 }
144934 
144935 /*
144936 ** This function is called on each phrase after the position lists for
144937 ** any deferred tokens have been loaded into memory. It updates the phrases
144938 ** current position list to include only those positions that are really
144939 ** instances of the phrase (after considering deferred tokens). If this
144940 ** means that the phrase does not appear in the current row, doclist.pList
144941 ** and doclist.nList are both zeroed.
144942 **
144943 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
144944 */
144945 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
144946  int iToken; /* Used to iterate through phrase tokens */
144947  char *aPoslist = 0; /* Position list for deferred tokens */
144948  int nPoslist = 0; /* Number of bytes in aPoslist */
144949  int iPrev = -1; /* Token number of previous deferred token */
144950 
144951  assert( pPhrase->doclist.bFreeList==0 );
144952 
144953  for(iToken=0; iToken<pPhrase->nToken; iToken++){
144954  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
144955  Fts3DeferredToken *pDeferred = pToken->pDeferred;
144956 
144957  if( pDeferred ){
144958  char *pList;
144959  int nList;
144960  int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
144961  if( rc!=SQLITE_OK ) return rc;
144962 
144963  if( pList==0 ){
144964  sqlite3_free(aPoslist);
144965  pPhrase->doclist.pList = 0;
144966  pPhrase->doclist.nList = 0;
144967  return SQLITE_OK;
144968 
144969  }else if( aPoslist==0 ){
144970  aPoslist = pList;
144971  nPoslist = nList;
144972 
144973  }else{
144974  char *aOut = pList;
144975  char *p1 = aPoslist;
144976  char *p2 = aOut;
144977 
144978  assert( iPrev>=0 );
144979  fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
144980  sqlite3_free(aPoslist);
144981  aPoslist = pList;
144982  nPoslist = (int)(aOut - aPoslist);
144983  if( nPoslist==0 ){
144984  sqlite3_free(aPoslist);
144985  pPhrase->doclist.pList = 0;
144986  pPhrase->doclist.nList = 0;
144987  return SQLITE_OK;
144988  }
144989  }
144990  iPrev = iToken;
144991  }
144992  }
144993 
144994  if( iPrev>=0 ){
144995  int nMaxUndeferred = pPhrase->iDoclistToken;
144996  if( nMaxUndeferred<0 ){
144997  pPhrase->doclist.pList = aPoslist;
144998  pPhrase->doclist.nList = nPoslist;
144999  pPhrase->doclist.iDocid = pCsr->iPrevId;
145000  pPhrase->doclist.bFreeList = 1;
145001  }else{
145002  int nDistance;
145003  char *p1;
145004  char *p2;
145005  char *aOut;
145006 
145007  if( nMaxUndeferred>iPrev ){
145008  p1 = aPoslist;
145009  p2 = pPhrase->doclist.pList;
145010  nDistance = nMaxUndeferred - iPrev;
145011  }else{
145012  p1 = pPhrase->doclist.pList;
145013  p2 = aPoslist;
145014  nDistance = iPrev - nMaxUndeferred;
145015  }
145016 
145017  aOut = (char *)sqlite3_malloc(nPoslist+8);
145018  if( !aOut ){
145019  sqlite3_free(aPoslist);
145020  return SQLITE_NOMEM;
145021  }
145022 
145023  pPhrase->doclist.pList = aOut;
145024  if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
145025  pPhrase->doclist.bFreeList = 1;
145026  pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
145027  }else{
145028  sqlite3_free(aOut);
145029  pPhrase->doclist.pList = 0;
145030  pPhrase->doclist.nList = 0;
145031  }
145032  sqlite3_free(aPoslist);
145033  }
145034  }
145035 
145036  return SQLITE_OK;
145037 }
145038 
145039 /*
145040 ** Maximum number of tokens a phrase may have to be considered for the
145041 ** incremental doclists strategy.
145042 */
145043 #define MAX_INCR_PHRASE_TOKENS 4
145044 
145045 /*
145046 ** This function is called for each Fts3Phrase in a full-text query
145047 ** expression to initialize the mechanism for returning rows. Once this
145048 ** function has been called successfully on an Fts3Phrase, it may be
145049 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
145050 **
145051 ** If parameter bOptOk is true, then the phrase may (or may not) use the
145052 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
145053 ** memory within this call.
145054 **
145055 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
145056 */
145057 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
145058  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145059  int rc = SQLITE_OK; /* Error code */
145060  int i;
145061 
145062  /* Determine if doclists may be loaded from disk incrementally. This is
145063  ** possible if the bOptOk argument is true, the FTS doclists will be
145064  ** scanned in forward order, and the phrase consists of
145065  ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
145066  ** tokens or prefix tokens that cannot use a prefix-index. */
145067  int bHaveIncr = 0;
145068  int bIncrOk = (bOptOk
145069  && pCsr->bDesc==pTab->bDescIdx
145070  && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
145071 #ifdef SQLITE_TEST
145072  && pTab->bNoIncrDoclist==0
145073 #endif
145074  );
145075  for(i=0; bIncrOk==1 && i<p->nToken; i++){
145076  Fts3PhraseToken *pToken = &p->aToken[i];
145077  if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
145078  bIncrOk = 0;
145079  }
145080  if( pToken->pSegcsr ) bHaveIncr = 1;
145081  }
145082 
145083  if( bIncrOk && bHaveIncr ){
145084  /* Use the incremental approach. */
145085  int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
145086  for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
145087  Fts3PhraseToken *pToken = &p->aToken[i];
145088  Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
145089  if( pSegcsr ){
145090  rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
145091  }
145092  }
145093  p->bIncr = 1;
145094  }else{
145095  /* Load the full doclist for the phrase into memory. */
145096  rc = fts3EvalPhraseLoad(pCsr, p);
145097  p->bIncr = 0;
145098  }
145099 
145100  assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
145101  return rc;
145102 }
145103 
145104 /*
145105 ** This function is used to iterate backwards (from the end to start)
145106 ** through doclists. It is used by this module to iterate through phrase
145107 ** doclists in reverse and by the fts3_write.c module to iterate through
145108 ** pending-terms lists when writing to databases with "order=desc".
145109 **
145110 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
145111 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
145112 ** function iterates from the end of the doclist to the beginning.
145113 */
145114 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
145115  int bDescIdx, /* True if the doclist is desc */
145116  char *aDoclist, /* Pointer to entire doclist */
145117  int nDoclist, /* Length of aDoclist in bytes */
145118  char **ppIter, /* IN/OUT: Iterator pointer */
145119  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
145120  int *pnList, /* OUT: List length pointer */
145121  u8 *pbEof /* OUT: End-of-file flag */
145122 ){
145123  char *p = *ppIter;
145124 
145125  assert( nDoclist>0 );
145126  assert( *pbEof==0 );
145127  assert( p || *piDocid==0 );
145128  assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
145129 
145130  if( p==0 ){
145131  sqlite3_int64 iDocid = 0;
145132  char *pNext = 0;
145133  char *pDocid = aDoclist;
145134  char *pEnd = &aDoclist[nDoclist];
145135  int iMul = 1;
145136 
145137  while( pDocid<pEnd ){
145138  sqlite3_int64 iDelta;
145139  pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
145140  iDocid += (iMul * iDelta);
145141  pNext = pDocid;
145142  fts3PoslistCopy(0, &pDocid);
145143  while( pDocid<pEnd && *pDocid==0 ) pDocid++;
145144  iMul = (bDescIdx ? -1 : 1);
145145  }
145146 
145147  *pnList = (int)(pEnd - pNext);
145148  *ppIter = pNext;
145149  *piDocid = iDocid;
145150  }else{
145151  int iMul = (bDescIdx ? -1 : 1);
145152  sqlite3_int64 iDelta;
145153  fts3GetReverseVarint(&p, aDoclist, &iDelta);
145154  *piDocid -= (iMul * iDelta);
145155 
145156  if( p==aDoclist ){
145157  *pbEof = 1;
145158  }else{
145159  char *pSave = p;
145160  fts3ReversePoslist(aDoclist, &p);
145161  *pnList = (int)(pSave - p);
145162  }
145163  *ppIter = p;
145164  }
145165 }
145166 
145167 /*
145168 ** Iterate forwards through a doclist.
145169 */
145170 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
145171  int bDescIdx, /* True if the doclist is desc */
145172  char *aDoclist, /* Pointer to entire doclist */
145173  int nDoclist, /* Length of aDoclist in bytes */
145174  char **ppIter, /* IN/OUT: Iterator pointer */
145175  sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
145176  u8 *pbEof /* OUT: End-of-file flag */
145177 ){
145178  char *p = *ppIter;
145179 
145180  assert( nDoclist>0 );
145181  assert( *pbEof==0 );
145182  assert( p || *piDocid==0 );
145183  assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
145184 
145185  if( p==0 ){
145186  p = aDoclist;
145187  p += sqlite3Fts3GetVarint(p, piDocid);
145188  }else{
145189  fts3PoslistCopy(0, &p);
145190  while( p<&aDoclist[nDoclist] && *p==0 ) p++;
145191  if( p>=&aDoclist[nDoclist] ){
145192  *pbEof = 1;
145193  }else{
145194  sqlite3_int64 iVar;
145195  p += sqlite3Fts3GetVarint(p, &iVar);
145196  *piDocid += ((bDescIdx ? -1 : 1) * iVar);
145197  }
145198  }
145199 
145200  *ppIter = p;
145201 }
145202 
145203 /*
145204 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
145205 ** to true if EOF is reached.
145206 */
145207 static void fts3EvalDlPhraseNext(
145208  Fts3Table *pTab,
145209  Fts3Doclist *pDL,
145210  u8 *pbEof
145211 ){
145212  char *pIter; /* Used to iterate through aAll */
145213  char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
145214 
145215  if( pDL->pNextDocid ){
145216  pIter = pDL->pNextDocid;
145217  }else{
145218  pIter = pDL->aAll;
145219  }
145220 
145221  if( pIter>=pEnd ){
145222  /* We have already reached the end of this doclist. EOF. */
145223  *pbEof = 1;
145224  }else{
145225  sqlite3_int64 iDelta;
145226  pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
145227  if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
145228  pDL->iDocid += iDelta;
145229  }else{
145230  pDL->iDocid -= iDelta;
145231  }
145232  pDL->pList = pIter;
145233  fts3PoslistCopy(0, &pIter);
145234  pDL->nList = (int)(pIter - pDL->pList);
145235 
145236  /* pIter now points just past the 0x00 that terminates the position-
145237  ** list for document pDL->iDocid. However, if this position-list was
145238  ** edited in place by fts3EvalNearTrim(), then pIter may not actually
145239  ** point to the start of the next docid value. The following line deals
145240  ** with this case by advancing pIter past the zero-padding added by
145241  ** fts3EvalNearTrim(). */
145242  while( pIter<pEnd && *pIter==0 ) pIter++;
145243 
145244  pDL->pNextDocid = pIter;
145245  assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
145246  *pbEof = 0;
145247  }
145248 }
145249 
145250 /*
145251 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
145252 */
145253 typedef struct TokenDoclist TokenDoclist;
145254 struct TokenDoclist {
145255  int bIgnore;
145256  sqlite3_int64 iDocid;
145257  char *pList;
145258  int nList;
145259 };
145260 
145261 /*
145262 ** Token pToken is an incrementally loaded token that is part of a
145263 ** multi-token phrase. Advance it to the next matching document in the
145264 ** database and populate output variable *p with the details of the new
145265 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
145266 **
145267 ** If an error occurs, return an SQLite error code. Otherwise, return
145268 ** SQLITE_OK.
145269 */
145270 static int incrPhraseTokenNext(
145271  Fts3Table *pTab, /* Virtual table handle */
145272  Fts3Phrase *pPhrase, /* Phrase to advance token of */
145273  int iToken, /* Specific token to advance */
145274  TokenDoclist *p, /* OUT: Docid and doclist for new entry */
145275  u8 *pbEof /* OUT: True if iterator is at EOF */
145276 ){
145277  int rc = SQLITE_OK;
145278 
145279  if( pPhrase->iDoclistToken==iToken ){
145280  assert( p->bIgnore==0 );
145281  assert( pPhrase->aToken[iToken].pSegcsr==0 );
145282  fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
145283  p->pList = pPhrase->doclist.pList;
145284  p->nList = pPhrase->doclist.nList;
145285  p->iDocid = pPhrase->doclist.iDocid;
145286  }else{
145287  Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
145288  assert( pToken->pDeferred==0 );
145289  assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
145290  if( pToken->pSegcsr ){
145291  assert( p->bIgnore==0 );
145292  rc = sqlite3Fts3MsrIncrNext(
145293  pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
145294  );
145295  if( p->pList==0 ) *pbEof = 1;
145296  }else{
145297  p->bIgnore = 1;
145298  }
145299  }
145300 
145301  return rc;
145302 }
145303 
145304 
145305 /*
145306 ** The phrase iterator passed as the second argument:
145307 **
145308 ** * features at least one token that uses an incremental doclist, and
145309 **
145310 ** * does not contain any deferred tokens.
145311 **
145312 ** Advance it to the next matching documnent in the database and populate
145313 ** the Fts3Doclist.pList and nList fields.
145314 **
145315 ** If there is no "next" entry and no error occurs, then *pbEof is set to
145316 ** 1 before returning. Otherwise, if no error occurs and the iterator is
145317 ** successfully advanced, *pbEof is set to 0.
145318 **
145319 ** If an error occurs, return an SQLite error code. Otherwise, return
145320 ** SQLITE_OK.
145321 */
145322 static int fts3EvalIncrPhraseNext(
145323  Fts3Cursor *pCsr, /* FTS Cursor handle */
145324  Fts3Phrase *p, /* Phrase object to advance to next docid */
145325  u8 *pbEof /* OUT: Set to 1 if EOF */
145326 ){
145327  int rc = SQLITE_OK;
145328  Fts3Doclist *pDL = &p->doclist;
145329  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145330  u8 bEof = 0;
145331 
145332  /* This is only called if it is guaranteed that the phrase has at least
145333  ** one incremental token. In which case the bIncr flag is set. */
145334  assert( p->bIncr==1 );
145335 
145336  if( p->nToken==1 && p->bIncr ){
145337  rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
145338  &pDL->iDocid, &pDL->pList, &pDL->nList
145339  );
145340  if( pDL->pList==0 ) bEof = 1;
145341  }else{
145342  int bDescDoclist = pCsr->bDesc;
145343  struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
145344 
145345  memset(a, 0, sizeof(a));
145346  assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
145347  assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
145348 
145349  while( bEof==0 ){
145350  int bMaxSet = 0;
145351  sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
145352  int i; /* Used to iterate through tokens */
145353 
145354  /* Advance the iterator for each token in the phrase once. */
145355  for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
145356  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
145357  if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
145358  iMax = a[i].iDocid;
145359  bMaxSet = 1;
145360  }
145361  }
145362  assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
145363  assert( rc!=SQLITE_OK || bMaxSet );
145364 
145365  /* Keep advancing iterators until they all point to the same document */
145366  for(i=0; i<p->nToken; i++){
145367  while( rc==SQLITE_OK && bEof==0
145368  && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
145369  ){
145370  rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
145371  if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
145372  iMax = a[i].iDocid;
145373  i = 0;
145374  }
145375  }
145376  }
145377 
145378  /* Check if the current entries really are a phrase match */
145379  if( bEof==0 ){
145380  int nList = 0;
145381  int nByte = a[p->nToken-1].nList;
145382  char *aDoclist = sqlite3_malloc(nByte+1);
145383  if( !aDoclist ) return SQLITE_NOMEM;
145384  memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
145385 
145386  for(i=0; i<(p->nToken-1); i++){
145387  if( a[i].bIgnore==0 ){
145388  char *pL = a[i].pList;
145389  char *pR = aDoclist;
145390  char *pOut = aDoclist;
145391  int nDist = p->nToken-1-i;
145392  int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
145393  if( res==0 ) break;
145394  nList = (int)(pOut - aDoclist);
145395  }
145396  }
145397  if( i==(p->nToken-1) ){
145398  pDL->iDocid = iMax;
145399  pDL->pList = aDoclist;
145400  pDL->nList = nList;
145401  pDL->bFreeList = 1;
145402  break;
145403  }
145404  sqlite3_free(aDoclist);
145405  }
145406  }
145407  }
145408 
145409  *pbEof = bEof;
145410  return rc;
145411 }
145412 
145413 /*
145414 ** Attempt to move the phrase iterator to point to the next matching docid.
145415 ** If an error occurs, return an SQLite error code. Otherwise, return
145416 ** SQLITE_OK.
145417 **
145418 ** If there is no "next" entry and no error occurs, then *pbEof is set to
145419 ** 1 before returning. Otherwise, if no error occurs and the iterator is
145420 ** successfully advanced, *pbEof is set to 0.
145421 */
145422 static int fts3EvalPhraseNext(
145423  Fts3Cursor *pCsr, /* FTS Cursor handle */
145424  Fts3Phrase *p, /* Phrase object to advance to next docid */
145425  u8 *pbEof /* OUT: Set to 1 if EOF */
145426 ){
145427  int rc = SQLITE_OK;
145428  Fts3Doclist *pDL = &p->doclist;
145429  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145430 
145431  if( p->bIncr ){
145432  rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
145433  }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
145434  sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
145435  &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
145436  );
145437  pDL->pList = pDL->pNextDocid;
145438  }else{
145439  fts3EvalDlPhraseNext(pTab, pDL, pbEof);
145440  }
145441 
145442  return rc;
145443 }
145444 
145445 /*
145446 **
145447 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
145448 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
145449 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
145450 ** expressions for which all descendent tokens are deferred.
145451 **
145452 ** If parameter bOptOk is zero, then it is guaranteed that the
145453 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
145454 ** each phrase in the expression (subject to deferred token processing).
145455 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
145456 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
145457 **
145458 ** If an error occurs within this function, *pRc is set to an SQLite error
145459 ** code before returning.
145460 */
145461 static void fts3EvalStartReaders(
145462  Fts3Cursor *pCsr, /* FTS Cursor handle */
145463  Fts3Expr *pExpr, /* Expression to initialize phrases in */
145464  int *pRc /* IN/OUT: Error code */
145465 ){
145466  if( pExpr && SQLITE_OK==*pRc ){
145467  if( pExpr->eType==FTSQUERY_PHRASE ){
145468  int nToken = pExpr->pPhrase->nToken;
145469  if( nToken ){
145470  int i;
145471  for(i=0; i<nToken; i++){
145472  if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
145473  }
145474  pExpr->bDeferred = (i==nToken);
145475  }
145476  *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
145477  }else{
145478  fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
145479  fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
145480  pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
145481  }
145482  }
145483 }
145484 
145485 /*
145486 ** An array of the following structures is assembled as part of the process
145487 ** of selecting tokens to defer before the query starts executing (as part
145488 ** of the xFilter() method). There is one element in the array for each
145489 ** token in the FTS expression.
145490 **
145491 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
145492 ** to phrases that are connected only by AND and NEAR operators (not OR or
145493 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
145494 ** separately. The root of a tokens AND/NEAR cluster is stored in
145495 ** Fts3TokenAndCost.pRoot.
145496 */
145497 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
145498 struct Fts3TokenAndCost {
145499  Fts3Phrase *pPhrase; /* The phrase the token belongs to */
145500  int iToken; /* Position of token in phrase */
145501  Fts3PhraseToken *pToken; /* The token itself */
145502  Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
145503  int nOvfl; /* Number of overflow pages to load doclist */
145504  int iCol; /* The column the token must match */
145505 };
145506 
145507 /*
145508 ** This function is used to populate an allocated Fts3TokenAndCost array.
145509 **
145510 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
145511 ** Otherwise, if an error occurs during execution, *pRc is set to an
145512 ** SQLite error code.
145513 */
145514 static void fts3EvalTokenCosts(
145515  Fts3Cursor *pCsr, /* FTS Cursor handle */
145516  Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
145517  Fts3Expr *pExpr, /* Expression to consider */
145518  Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
145519  Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
145520  int *pRc /* IN/OUT: Error code */
145521 ){
145522  if( *pRc==SQLITE_OK ){
145523  if( pExpr->eType==FTSQUERY_PHRASE ){
145524  Fts3Phrase *pPhrase = pExpr->pPhrase;
145525  int i;
145526  for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
145527  Fts3TokenAndCost *pTC = (*ppTC)++;
145528  pTC->pPhrase = pPhrase;
145529  pTC->iToken = i;
145530  pTC->pRoot = pRoot;
145531  pTC->pToken = &pPhrase->aToken[i];
145532  pTC->iCol = pPhrase->iColumn;
145533  *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
145534  }
145535  }else if( pExpr->eType!=FTSQUERY_NOT ){
145536  assert( pExpr->eType==FTSQUERY_OR
145537  || pExpr->eType==FTSQUERY_AND
145538  || pExpr->eType==FTSQUERY_NEAR
145539  );
145540  assert( pExpr->pLeft && pExpr->pRight );
145541  if( pExpr->eType==FTSQUERY_OR ){
145542  pRoot = pExpr->pLeft;
145543  **ppOr = pRoot;
145544  (*ppOr)++;
145545  }
145546  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
145547  if( pExpr->eType==FTSQUERY_OR ){
145548  pRoot = pExpr->pRight;
145549  **ppOr = pRoot;
145550  (*ppOr)++;
145551  }
145552  fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
145553  }
145554  }
145555 }
145556 
145557 /*
145558 ** Determine the average document (row) size in pages. If successful,
145559 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
145560 ** an SQLite error code.
145561 **
145562 ** The average document size in pages is calculated by first calculating
145563 ** determining the average size in bytes, B. If B is less than the amount
145564 ** of data that will fit on a single leaf page of an intkey table in
145565 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
145566 ** the number of overflow pages consumed by a record B bytes in size.
145567 */
145568 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
145569  if( pCsr->nRowAvg==0 ){
145570  /* The average document size, which is required to calculate the cost
145571  ** of each doclist, has not yet been determined. Read the required
145572  ** data from the %_stat table to calculate it.
145573  **
145574  ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
145575  ** varints, where nCol is the number of columns in the FTS3 table.
145576  ** The first varint is the number of documents currently stored in
145577  ** the table. The following nCol varints contain the total amount of
145578  ** data stored in all rows of each column of the table, from left
145579  ** to right.
145580  */
145581  int rc;
145582  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
145583  sqlite3_stmt *pStmt;
145584  sqlite3_int64 nDoc = 0;
145585  sqlite3_int64 nByte = 0;
145586  const char *pEnd;
145587  const char *a;
145588 
145589  rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
145590  if( rc!=SQLITE_OK ) return rc;
145591  a = sqlite3_column_blob(pStmt, 0);
145592  assert( a );
145593 
145594  pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
145595  a += sqlite3Fts3GetVarint(a, &nDoc);
145596  while( a<pEnd ){
145597  a += sqlite3Fts3GetVarint(a, &nByte);
145598  }
145599  if( nDoc==0 || nByte==0 ){
145600  sqlite3_reset(pStmt);
145601  return FTS_CORRUPT_VTAB;
145602  }
145603 
145604  pCsr->nDoc = nDoc;
145605  pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
145606  assert( pCsr->nRowAvg>0 );
145607  rc = sqlite3_reset(pStmt);
145608  if( rc!=SQLITE_OK ) return rc;
145609  }
145610 
145611  *pnPage = pCsr->nRowAvg;
145612  return SQLITE_OK;
145613 }
145614 
145615 /*
145616 ** This function is called to select the tokens (if any) that will be
145617 ** deferred. The array aTC[] has already been populated when this is
145618 ** called.
145619 **
145620 ** This function is called once for each AND/NEAR cluster in the
145621 ** expression. Each invocation determines which tokens to defer within
145622 ** the cluster with root node pRoot. See comments above the definition
145623 ** of struct Fts3TokenAndCost for more details.
145624 **
145625 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
145626 ** called on each token to defer. Otherwise, an SQLite error code is
145627 ** returned.
145628 */
145629 static int fts3EvalSelectDeferred(
145630  Fts3Cursor *pCsr, /* FTS Cursor handle */
145631  Fts3Expr *pRoot, /* Consider tokens with this root node */
145632  Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
145633  int nTC /* Number of entries in aTC[] */
145634 ){
145635  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145636  int nDocSize = 0; /* Number of pages per doc loaded */
145637  int rc = SQLITE_OK; /* Return code */
145638  int ii; /* Iterator variable for various purposes */
145639  int nOvfl = 0; /* Total overflow pages used by doclists */
145640  int nToken = 0; /* Total number of tokens in cluster */
145641 
145642  int nMinEst = 0; /* The minimum count for any phrase so far. */
145643  int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
145644 
145645  /* Tokens are never deferred for FTS tables created using the content=xxx
145646  ** option. The reason being that it is not guaranteed that the content
145647  ** table actually contains the same data as the index. To prevent this from
145648  ** causing any problems, the deferred token optimization is completely
145649  ** disabled for content=xxx tables. */
145650  if( pTab->zContentTbl ){
145651  return SQLITE_OK;
145652  }
145653 
145654  /* Count the tokens in this AND/NEAR cluster. If none of the doclists
145655  ** associated with the tokens spill onto overflow pages, or if there is
145656  ** only 1 token, exit early. No tokens to defer in this case. */
145657  for(ii=0; ii<nTC; ii++){
145658  if( aTC[ii].pRoot==pRoot ){
145659  nOvfl += aTC[ii].nOvfl;
145660  nToken++;
145661  }
145662  }
145663  if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
145664 
145665  /* Obtain the average docsize (in pages). */
145666  rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
145667  assert( rc!=SQLITE_OK || nDocSize>0 );
145668 
145669 
145670  /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
145671  ** of the number of overflow pages that will be loaded by the pager layer
145672  ** to retrieve the entire doclist for the token from the full-text index.
145673  ** Load the doclists for tokens that are either:
145674  **
145675  ** a. The cheapest token in the entire query (i.e. the one visited by the
145676  ** first iteration of this loop), or
145677  **
145678  ** b. Part of a multi-token phrase.
145679  **
145680  ** After each token doclist is loaded, merge it with the others from the
145681  ** same phrase and count the number of documents that the merged doclist
145682  ** contains. Set variable "nMinEst" to the smallest number of documents in
145683  ** any phrase doclist for which 1 or more token doclists have been loaded.
145684  ** Let nOther be the number of other phrases for which it is certain that
145685  ** one or more tokens will not be deferred.
145686  **
145687  ** Then, for each token, defer it if loading the doclist would result in
145688  ** loading N or more overflow pages into memory, where N is computed as:
145689  **
145690  ** (nMinEst + 4^nOther - 1) / (4^nOther)
145691  */
145692  for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
145693  int iTC; /* Used to iterate through aTC[] array. */
145694  Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
145695 
145696  /* Set pTC to point to the cheapest remaining token. */
145697  for(iTC=0; iTC<nTC; iTC++){
145698  if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
145699  && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
145700  ){
145701  pTC = &aTC[iTC];
145702  }
145703  }
145704  assert( pTC );
145705 
145706  if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
145707  /* The number of overflow pages to load for this (and therefore all
145708  ** subsequent) tokens is greater than the estimated number of pages
145709  ** that will be loaded if all subsequent tokens are deferred.
145710  */
145711  Fts3PhraseToken *pToken = pTC->pToken;
145712  rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
145713  fts3SegReaderCursorFree(pToken->pSegcsr);
145714  pToken->pSegcsr = 0;
145715  }else{
145716  /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
145717  ** for-loop. Except, limit the value to 2^24 to prevent it from
145718  ** overflowing the 32-bit integer it is stored in. */
145719  if( ii<12 ) nLoad4 = nLoad4*4;
145720 
145721  if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
145722  /* Either this is the cheapest token in the entire query, or it is
145723  ** part of a multi-token phrase. Either way, the entire doclist will
145724  ** (eventually) be loaded into memory. It may as well be now. */
145725  Fts3PhraseToken *pToken = pTC->pToken;
145726  int nList = 0;
145727  char *pList = 0;
145728  rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
145729  assert( rc==SQLITE_OK || pList==0 );
145730  if( rc==SQLITE_OK ){
145731  rc = fts3EvalPhraseMergeToken(
145732  pTab, pTC->pPhrase, pTC->iToken,pList,nList
145733  );
145734  }
145735  if( rc==SQLITE_OK ){
145736  int nCount;
145737  nCount = fts3DoclistCountDocids(
145738  pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
145739  );
145740  if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
145741  }
145742  }
145743  }
145744  pTC->pToken = 0;
145745  }
145746 
145747  return rc;
145748 }
145749 
145750 /*
145751 ** This function is called from within the xFilter method. It initializes
145752 ** the full-text query currently stored in pCsr->pExpr. To iterate through
145753 ** the results of a query, the caller does:
145754 **
145755 ** fts3EvalStart(pCsr);
145756 ** while( 1 ){
145757 ** fts3EvalNext(pCsr);
145758 ** if( pCsr->bEof ) break;
145759 ** ... return row pCsr->iPrevId to the caller ...
145760 ** }
145761 */
145762 static int fts3EvalStart(Fts3Cursor *pCsr){
145763  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
145764  int rc = SQLITE_OK;
145765  int nToken = 0;
145766  int nOr = 0;
145767 
145768  /* Allocate a MultiSegReader for each token in the expression. */
145769  fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
145770 
145771  /* Determine which, if any, tokens in the expression should be deferred. */
145772 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
145773  if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
145774  Fts3TokenAndCost *aTC;
145775  Fts3Expr **apOr;
145776  aTC = (Fts3TokenAndCost *)sqlite3_malloc(
145777  sizeof(Fts3TokenAndCost) * nToken
145778  + sizeof(Fts3Expr *) * nOr * 2
145779  );
145780  apOr = (Fts3Expr **)&aTC[nToken];
145781 
145782  if( !aTC ){
145783  rc = SQLITE_NOMEM;
145784  }else{
145785  int ii;
145786  Fts3TokenAndCost *pTC = aTC;
145787  Fts3Expr **ppOr = apOr;
145788 
145789  fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
145790  nToken = (int)(pTC-aTC);
145791  nOr = (int)(ppOr-apOr);
145792 
145793  if( rc==SQLITE_OK ){
145794  rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
145795  for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
145796  rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
145797  }
145798  }
145799 
145800  sqlite3_free(aTC);
145801  }
145802  }
145803 #endif
145804 
145805  fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
145806  return rc;
145807 }
145808 
145809 /*
145810 ** Invalidate the current position list for phrase pPhrase.
145811 */
145812 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
145813  if( pPhrase->doclist.bFreeList ){
145814  sqlite3_free(pPhrase->doclist.pList);
145815  }
145816  pPhrase->doclist.pList = 0;
145817  pPhrase->doclist.nList = 0;
145818  pPhrase->doclist.bFreeList = 0;
145819 }
145820 
145821 /*
145822 ** This function is called to edit the position list associated with
145823 ** the phrase object passed as the fifth argument according to a NEAR
145824 ** condition. For example:
145825 **
145826 ** abc NEAR/5 "def ghi"
145827 **
145828 ** Parameter nNear is passed the NEAR distance of the expression (5 in
145829 ** the example above). When this function is called, *paPoslist points to
145830 ** the position list, and *pnToken is the number of phrase tokens in, the
145831 ** phrase on the other side of the NEAR operator to pPhrase. For example,
145832 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
145833 ** the position list associated with phrase "abc".
145834 **
145835 ** All positions in the pPhrase position list that are not sufficiently
145836 ** close to a position in the *paPoslist position list are removed. If this
145837 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
145838 **
145839 ** Before returning, *paPoslist is set to point to the position lsit
145840 ** associated with pPhrase. And *pnToken is set to the number of tokens in
145841 ** pPhrase.
145842 */
145843 static int fts3EvalNearTrim(
145844  int nNear, /* NEAR distance. As in "NEAR/nNear". */
145845  char *aTmp, /* Temporary space to use */
145846  char **paPoslist, /* IN/OUT: Position list */
145847  int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
145848  Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
145849 ){
145850  int nParam1 = nNear + pPhrase->nToken;
145851  int nParam2 = nNear + *pnToken;
145852  int nNew;
145853  char *p2;
145854  char *pOut;
145855  int res;
145856 
145857  assert( pPhrase->doclist.pList );
145858 
145859  p2 = pOut = pPhrase->doclist.pList;
145860  res = fts3PoslistNearMerge(
145861  &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
145862  );
145863  if( res ){
145864  nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
145865  assert( pPhrase->doclist.pList[nNew]=='\0' );
145866  assert( nNew<=pPhrase->doclist.nList && nNew>0 );
145867  memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
145868  pPhrase->doclist.nList = nNew;
145869  *paPoslist = pPhrase->doclist.pList;
145870  *pnToken = pPhrase->nToken;
145871  }
145872 
145873  return res;
145874 }
145875 
145876 /*
145877 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
145878 ** Otherwise, it advances the expression passed as the second argument to
145879 ** point to the next matching row in the database. Expressions iterate through
145880 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
145881 ** or descending if it is non-zero.
145882 **
145883 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
145884 ** successful, the following variables in pExpr are set:
145885 **
145886 ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
145887 ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
145888 **
145889 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
145890 ** at EOF, then the following variables are populated with the position list
145891 ** for the phrase for the visited row:
145892 **
145893 ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
145894 ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
145895 **
145896 ** It says above that this function advances the expression to the next
145897 ** matching row. This is usually true, but there are the following exceptions:
145898 **
145899 ** 1. Deferred tokens are not taken into account. If a phrase consists
145900 ** entirely of deferred tokens, it is assumed to match every row in
145901 ** the db. In this case the position-list is not populated at all.
145902 **
145903 ** Or, if a phrase contains one or more deferred tokens and one or
145904 ** more non-deferred tokens, then the expression is advanced to the
145905 ** next possible match, considering only non-deferred tokens. In other
145906 ** words, if the phrase is "A B C", and "B" is deferred, the expression
145907 ** is advanced to the next row that contains an instance of "A * C",
145908 ** where "*" may match any single token. The position list in this case
145909 ** is populated as for "A * C" before returning.
145910 **
145911 ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
145912 ** advanced to point to the next row that matches "x AND y".
145913 **
145914 ** See sqlite3Fts3EvalTestDeferred() for details on testing if a row is
145915 ** really a match, taking into account deferred tokens and NEAR operators.
145916 */
145917 static void fts3EvalNextRow(
145918  Fts3Cursor *pCsr, /* FTS Cursor handle */
145919  Fts3Expr *pExpr, /* Expr. to advance to next matching row */
145920  int *pRc /* IN/OUT: Error code */
145921 ){
145922  if( *pRc==SQLITE_OK ){
145923  int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
145924  assert( pExpr->bEof==0 );
145925  pExpr->bStart = 1;
145926 
145927  switch( pExpr->eType ){
145928  case FTSQUERY_NEAR:
145929  case FTSQUERY_AND: {
145930  Fts3Expr *pLeft = pExpr->pLeft;
145931  Fts3Expr *pRight = pExpr->pRight;
145932  assert( !pLeft->bDeferred || !pRight->bDeferred );
145933 
145934  if( pLeft->bDeferred ){
145935  /* LHS is entirely deferred. So we assume it matches every row.
145936  ** Advance the RHS iterator to find the next row visited. */
145937  fts3EvalNextRow(pCsr, pRight, pRc);
145938  pExpr->iDocid = pRight->iDocid;
145939  pExpr->bEof = pRight->bEof;
145940  }else if( pRight->bDeferred ){
145941  /* RHS is entirely deferred. So we assume it matches every row.
145942  ** Advance the LHS iterator to find the next row visited. */
145943  fts3EvalNextRow(pCsr, pLeft, pRc);
145944  pExpr->iDocid = pLeft->iDocid;
145945  pExpr->bEof = pLeft->bEof;
145946  }else{
145947  /* Neither the RHS or LHS are deferred. */
145948  fts3EvalNextRow(pCsr, pLeft, pRc);
145949  fts3EvalNextRow(pCsr, pRight, pRc);
145950  while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
145951  sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
145952  if( iDiff==0 ) break;
145953  if( iDiff<0 ){
145954  fts3EvalNextRow(pCsr, pLeft, pRc);
145955  }else{
145956  fts3EvalNextRow(pCsr, pRight, pRc);
145957  }
145958  }
145959  pExpr->iDocid = pLeft->iDocid;
145960  pExpr->bEof = (pLeft->bEof || pRight->bEof);
145961  if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
145962  if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
145963  Fts3Doclist *pDl = &pRight->pPhrase->doclist;
145964  while( *pRc==SQLITE_OK && pRight->bEof==0 ){
145965  memset(pDl->pList, 0, pDl->nList);
145966  fts3EvalNextRow(pCsr, pRight, pRc);
145967  }
145968  }
145969  if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
145970  Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
145971  while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
145972  memset(pDl->pList, 0, pDl->nList);
145973  fts3EvalNextRow(pCsr, pLeft, pRc);
145974  }
145975  }
145976  }
145977  }
145978  break;
145979  }
145980 
145981  case FTSQUERY_OR: {
145982  Fts3Expr *pLeft = pExpr->pLeft;
145983  Fts3Expr *pRight = pExpr->pRight;
145984  sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
145985 
145986  assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
145987  assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
145988 
145989  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
145990  fts3EvalNextRow(pCsr, pLeft, pRc);
145991  }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
145992  fts3EvalNextRow(pCsr, pRight, pRc);
145993  }else{
145994  fts3EvalNextRow(pCsr, pLeft, pRc);
145995  fts3EvalNextRow(pCsr, pRight, pRc);
145996  }
145997 
145998  pExpr->bEof = (pLeft->bEof && pRight->bEof);
145999  iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
146000  if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
146001  pExpr->iDocid = pLeft->iDocid;
146002  }else{
146003  pExpr->iDocid = pRight->iDocid;
146004  }
146005 
146006  break;
146007  }
146008 
146009  case FTSQUERY_NOT: {
146010  Fts3Expr *pLeft = pExpr->pLeft;
146011  Fts3Expr *pRight = pExpr->pRight;
146012 
146013  if( pRight->bStart==0 ){
146014  fts3EvalNextRow(pCsr, pRight, pRc);
146015  assert( *pRc!=SQLITE_OK || pRight->bStart );
146016  }
146017 
146018  fts3EvalNextRow(pCsr, pLeft, pRc);
146019  if( pLeft->bEof==0 ){
146020  while( !*pRc
146021  && !pRight->bEof
146022  && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
146023  ){
146024  fts3EvalNextRow(pCsr, pRight, pRc);
146025  }
146026  }
146027  pExpr->iDocid = pLeft->iDocid;
146028  pExpr->bEof = pLeft->bEof;
146029  break;
146030  }
146031 
146032  default: {
146033  Fts3Phrase *pPhrase = pExpr->pPhrase;
146034  fts3EvalInvalidatePoslist(pPhrase);
146035  *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
146036  pExpr->iDocid = pPhrase->doclist.iDocid;
146037  break;
146038  }
146039  }
146040  }
146041 }
146042 
146043 /*
146044 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
146045 ** cluster, then this function returns 1 immediately.
146046 **
146047 ** Otherwise, it checks if the current row really does match the NEAR
146048 ** expression, using the data currently stored in the position lists
146049 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
146050 **
146051 ** If the current row is a match, the position list associated with each
146052 ** phrase in the NEAR expression is edited in place to contain only those
146053 ** phrase instances sufficiently close to their peers to satisfy all NEAR
146054 ** constraints. In this case it returns 1. If the NEAR expression does not
146055 ** match the current row, 0 is returned. The position lists may or may not
146056 ** be edited if 0 is returned.
146057 */
146058 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
146059  int res = 1;
146060 
146061  /* The following block runs if pExpr is the root of a NEAR query.
146062  ** For example, the query:
146063  **
146064  ** "w" NEAR "x" NEAR "y" NEAR "z"
146065  **
146066  ** which is represented in tree form as:
146067  **
146068  ** |
146069  ** +--NEAR--+ <-- root of NEAR query
146070  ** | |
146071  ** +--NEAR--+ "z"
146072  ** | |
146073  ** +--NEAR--+ "y"
146074  ** | |
146075  ** "w" "x"
146076  **
146077  ** The right-hand child of a NEAR node is always a phrase. The
146078  ** left-hand child may be either a phrase or a NEAR node. There are
146079  ** no exceptions to this - it's the way the parser in fts3_expr.c works.
146080  */
146081  if( *pRc==SQLITE_OK
146082  && pExpr->eType==FTSQUERY_NEAR
146083  && pExpr->bEof==0
146084  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
146085  ){
146086  Fts3Expr *p;
146087  int nTmp = 0; /* Bytes of temp space */
146088  char *aTmp; /* Temp space for PoslistNearMerge() */
146089 
146090  /* Allocate temporary working space. */
146091  for(p=pExpr; p->pLeft; p=p->pLeft){
146092  nTmp += p->pRight->pPhrase->doclist.nList;
146093  }
146094  nTmp += p->pPhrase->doclist.nList;
146095  if( nTmp==0 ){
146096  res = 0;
146097  }else{
146098  aTmp = sqlite3_malloc(nTmp*2);
146099  if( !aTmp ){
146100  *pRc = SQLITE_NOMEM;
146101  res = 0;
146102  }else{
146103  char *aPoslist = p->pPhrase->doclist.pList;
146104  int nToken = p->pPhrase->nToken;
146105 
146106  for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
146107  Fts3Phrase *pPhrase = p->pRight->pPhrase;
146108  int nNear = p->nNear;
146109  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
146110  }
146111 
146112  aPoslist = pExpr->pRight->pPhrase->doclist.pList;
146113  nToken = pExpr->pRight->pPhrase->nToken;
146114  for(p=pExpr->pLeft; p && res; p=p->pLeft){
146115  int nNear;
146116  Fts3Phrase *pPhrase;
146117  assert( p->pParent && p->pParent->pLeft==p );
146118  nNear = p->pParent->nNear;
146119  pPhrase = (
146120  p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
146121  );
146122  res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
146123  }
146124  }
146125 
146126  sqlite3_free(aTmp);
146127  }
146128  }
146129 
146130  return res;
146131 }
146132 
146133 /*
146134 ** This function is a helper function for sqlite3Fts3EvalTestDeferred().
146135 ** Assuming no error occurs or has occurred, It returns non-zero if the
146136 ** expression passed as the second argument matches the row that pCsr
146137 ** currently points to, or zero if it does not.
146138 **
146139 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146140 ** If an error occurs during execution of this function, *pRc is set to
146141 ** the appropriate SQLite error code. In this case the returned value is
146142 ** undefined.
146143 */
146144 static int fts3EvalTestExpr(
146145  Fts3Cursor *pCsr, /* FTS cursor handle */
146146  Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
146147  int *pRc /* IN/OUT: Error code */
146148 ){
146149  int bHit = 1; /* Return value */
146150  if( *pRc==SQLITE_OK ){
146151  switch( pExpr->eType ){
146152  case FTSQUERY_NEAR:
146153  case FTSQUERY_AND:
146154  bHit = (
146155  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
146156  && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
146157  && fts3EvalNearTest(pExpr, pRc)
146158  );
146159 
146160  /* If the NEAR expression does not match any rows, zero the doclist for
146161  ** all phrases involved in the NEAR. This is because the snippet(),
146162  ** offsets() and matchinfo() functions are not supposed to recognize
146163  ** any instances of phrases that are part of unmatched NEAR queries.
146164  ** For example if this expression:
146165  **
146166  ** ... MATCH 'a OR (b NEAR c)'
146167  **
146168  ** is matched against a row containing:
146169  **
146170  ** 'a b d e'
146171  **
146172  ** then any snippet() should ony highlight the "a" term, not the "b"
146173  ** (as "b" is part of a non-matching NEAR clause).
146174  */
146175  if( bHit==0
146176  && pExpr->eType==FTSQUERY_NEAR
146177  && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
146178  ){
146179  Fts3Expr *p;
146180  for(p=pExpr; p->pPhrase==0; p=p->pLeft){
146181  if( p->pRight->iDocid==pCsr->iPrevId ){
146182  fts3EvalInvalidatePoslist(p->pRight->pPhrase);
146183  }
146184  }
146185  if( p->iDocid==pCsr->iPrevId ){
146186  fts3EvalInvalidatePoslist(p->pPhrase);
146187  }
146188  }
146189 
146190  break;
146191 
146192  case FTSQUERY_OR: {
146193  int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
146194  int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
146195  bHit = bHit1 || bHit2;
146196  break;
146197  }
146198 
146199  case FTSQUERY_NOT:
146200  bHit = (
146201  fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
146202  && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
146203  );
146204  break;
146205 
146206  default: {
146207 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
146208  if( pCsr->pDeferred
146209  && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
146210  ){
146211  Fts3Phrase *pPhrase = pExpr->pPhrase;
146212  assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
146213  if( pExpr->bDeferred ){
146214  fts3EvalInvalidatePoslist(pPhrase);
146215  }
146216  *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
146217  bHit = (pPhrase->doclist.pList!=0);
146218  pExpr->iDocid = pCsr->iPrevId;
146219  }else
146220 #endif
146221  {
146222  bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
146223  }
146224  break;
146225  }
146226  }
146227  }
146228  return bHit;
146229 }
146230 
146231 /*
146232 ** This function is called as the second part of each xNext operation when
146233 ** iterating through the results of a full-text query. At this point the
146234 ** cursor points to a row that matches the query expression, with the
146235 ** following caveats:
146236 **
146237 ** * Up until this point, "NEAR" operators in the expression have been
146238 ** treated as "AND".
146239 **
146240 ** * Deferred tokens have not yet been considered.
146241 **
146242 ** If *pRc is not SQLITE_OK when this function is called, it immediately
146243 ** returns 0. Otherwise, it tests whether or not after considering NEAR
146244 ** operators and deferred tokens the current row is still a match for the
146245 ** expression. It returns 1 if both of the following are true:
146246 **
146247 ** 1. *pRc is SQLITE_OK when this function returns, and
146248 **
146249 ** 2. After scanning the current FTS table row for the deferred tokens,
146250 ** it is determined that the row does *not* match the query.
146251 **
146252 ** Or, if no error occurs and it seems the current row does match the FTS
146253 ** query, return 0.
146254 */
146255 SQLITE_PRIVATE int sqlite3Fts3EvalTestDeferred(Fts3Cursor *pCsr, int *pRc){
146256  int rc = *pRc;
146257  int bMiss = 0;
146258  if( rc==SQLITE_OK ){
146259 
146260  /* If there are one or more deferred tokens, load the current row into
146261  ** memory and scan it to determine the position list for each deferred
146262  ** token. Then, see if this row is really a match, considering deferred
146263  ** tokens and NEAR operators (neither of which were taken into account
146264  ** earlier, by fts3EvalNextRow()).
146265  */
146266  if( pCsr->pDeferred ){
146267  rc = fts3CursorSeek(0, pCsr);
146268  if( rc==SQLITE_OK ){
146269  rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
146270  }
146271  }
146272  bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
146273 
146274  /* Free the position-lists accumulated for each deferred token above. */
146275  sqlite3Fts3FreeDeferredDoclists(pCsr);
146276  *pRc = rc;
146277  }
146278  return (rc==SQLITE_OK && bMiss);
146279 }
146280 
146281 /*
146282 ** Advance to the next document that matches the FTS expression in
146283 ** Fts3Cursor.pExpr.
146284 */
146285 static int fts3EvalNext(Fts3Cursor *pCsr){
146286  int rc = SQLITE_OK; /* Return Code */
146287  Fts3Expr *pExpr = pCsr->pExpr;
146288  assert( pCsr->isEof==0 );
146289  if( pExpr==0 ){
146290  pCsr->isEof = 1;
146291  }else{
146292  do {
146293  if( pCsr->isRequireSeek==0 ){
146294  sqlite3_reset(pCsr->pStmt);
146295  }
146296  assert( sqlite3_data_count(pCsr->pStmt)==0 );
146297  fts3EvalNextRow(pCsr, pExpr, &rc);
146298  pCsr->isEof = pExpr->bEof;
146299  pCsr->isRequireSeek = 1;
146300  pCsr->isMatchinfoNeeded = 1;
146301  pCsr->iPrevId = pExpr->iDocid;
146302  }while( pCsr->isEof==0 && sqlite3Fts3EvalTestDeferred(pCsr, &rc) );
146303  }
146304 
146305  /* Check if the cursor is past the end of the docid range specified
146306  ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
146307  if( rc==SQLITE_OK && (
146308  (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
146309  || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
146310  )){
146311  pCsr->isEof = 1;
146312  }
146313 
146314  return rc;
146315 }
146316 
146317 /*
146318 ** Restart interation for expression pExpr so that the next call to
146319 ** fts3EvalNext() visits the first row. Do not allow incremental
146320 ** loading or merging of phrase doclists for this iteration.
146321 **
146322 ** If *pRc is other than SQLITE_OK when this function is called, it is
146323 ** a no-op. If an error occurs within this function, *pRc is set to an
146324 ** SQLite error code before returning.
146325 */
146326 static void fts3EvalRestart(
146327  Fts3Cursor *pCsr,
146328  Fts3Expr *pExpr,
146329  int *pRc
146330 ){
146331  if( pExpr && *pRc==SQLITE_OK ){
146332  Fts3Phrase *pPhrase = pExpr->pPhrase;
146333 
146334  if( pPhrase ){
146335  fts3EvalInvalidatePoslist(pPhrase);
146336  if( pPhrase->bIncr ){
146337  int i;
146338  for(i=0; i<pPhrase->nToken; i++){
146339  Fts3PhraseToken *pToken = &pPhrase->aToken[i];
146340  assert( pToken->pDeferred==0 );
146341  if( pToken->pSegcsr ){
146342  sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
146343  }
146344  }
146345  *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
146346  }
146347  pPhrase->doclist.pNextDocid = 0;
146348  pPhrase->doclist.iDocid = 0;
146349  pPhrase->pOrPoslist = 0;
146350  }
146351 
146352  pExpr->iDocid = 0;
146353  pExpr->bEof = 0;
146354  pExpr->bStart = 0;
146355 
146356  fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
146357  fts3EvalRestart(pCsr, pExpr->pRight, pRc);
146358  }
146359 }
146360 
146361 /*
146362 ** After allocating the Fts3Expr.aMI[] array for each phrase in the
146363 ** expression rooted at pExpr, the cursor iterates through all rows matched
146364 ** by pExpr, calling this function for each row. This function increments
146365 ** the values in Fts3Expr.aMI[] according to the position-list currently
146366 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
146367 ** expression nodes.
146368 */
146369 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
146370  if( pExpr ){
146371  Fts3Phrase *pPhrase = pExpr->pPhrase;
146372  if( pPhrase && pPhrase->doclist.pList ){
146373  int iCol = 0;
146374  char *p = pPhrase->doclist.pList;
146375 
146376  assert( *p );
146377  while( 1 ){
146378  u8 c = 0;
146379  int iCnt = 0;
146380  while( 0xFE & (*p | c) ){
146381  if( (c&0x80)==0 ) iCnt++;
146382  c = *p++ & 0x80;
146383  }
146384 
146385  /* aMI[iCol*3 + 1] = Number of occurrences
146386  ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
146387  */
146388  pExpr->aMI[iCol*3 + 1] += iCnt;
146389  pExpr->aMI[iCol*3 + 2] += (iCnt>0);
146390  if( *p==0x00 ) break;
146391  p++;
146392  p += fts3GetVarint32(p, &iCol);
146393  }
146394  }
146395 
146396  fts3EvalUpdateCounts(pExpr->pLeft);
146397  fts3EvalUpdateCounts(pExpr->pRight);
146398  }
146399 }
146400 
146401 /*
146402 ** Expression pExpr must be of type FTSQUERY_PHRASE.
146403 **
146404 ** If it is not already allocated and populated, this function allocates and
146405 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
146406 ** of a NEAR expression, then it also allocates and populates the same array
146407 ** for all other phrases that are part of the NEAR expression.
146408 **
146409 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
146410 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
146411 */
146412 static int fts3EvalGatherStats(
146413  Fts3Cursor *pCsr, /* Cursor object */
146414  Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
146415 ){
146416  int rc = SQLITE_OK; /* Return code */
146417 
146418  assert( pExpr->eType==FTSQUERY_PHRASE );
146419  if( pExpr->aMI==0 ){
146420  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146421  Fts3Expr *pRoot; /* Root of NEAR expression */
146422  Fts3Expr *p; /* Iterator used for several purposes */
146423 
146424  sqlite3_int64 iPrevId = pCsr->iPrevId;
146425  sqlite3_int64 iDocid;
146426  u8 bEof;
146427 
146428  /* Find the root of the NEAR expression */
146429  pRoot = pExpr;
146430  while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
146431  pRoot = pRoot->pParent;
146432  }
146433  iDocid = pRoot->iDocid;
146434  bEof = pRoot->bEof;
146435  assert( pRoot->bStart );
146436 
146437  /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
146438  for(p=pRoot; p; p=p->pLeft){
146439  Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
146440  assert( pE->aMI==0 );
146441  pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
146442  if( !pE->aMI ) return SQLITE_NOMEM;
146443  memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
146444  }
146445 
146446  fts3EvalRestart(pCsr, pRoot, &rc);
146447 
146448  while( pCsr->isEof==0 && rc==SQLITE_OK ){
146449 
146450  do {
146451  /* Ensure the %_content statement is reset. */
146452  if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
146453  assert( sqlite3_data_count(pCsr->pStmt)==0 );
146454 
146455  /* Advance to the next document */
146456  fts3EvalNextRow(pCsr, pRoot, &rc);
146457  pCsr->isEof = pRoot->bEof;
146458  pCsr->isRequireSeek = 1;
146459  pCsr->isMatchinfoNeeded = 1;
146460  pCsr->iPrevId = pRoot->iDocid;
146461  }while( pCsr->isEof==0
146462  && pRoot->eType==FTSQUERY_NEAR
146463  && sqlite3Fts3EvalTestDeferred(pCsr, &rc)
146464  );
146465 
146466  if( rc==SQLITE_OK && pCsr->isEof==0 ){
146467  fts3EvalUpdateCounts(pRoot);
146468  }
146469  }
146470 
146471  pCsr->isEof = 0;
146472  pCsr->iPrevId = iPrevId;
146473 
146474  if( bEof ){
146475  pRoot->bEof = bEof;
146476  }else{
146477  /* Caution: pRoot may iterate through docids in ascending or descending
146478  ** order. For this reason, even though it seems more defensive, the
146479  ** do loop can not be written:
146480  **
146481  ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
146482  */
146483  fts3EvalRestart(pCsr, pRoot, &rc);
146484  do {
146485  fts3EvalNextRow(pCsr, pRoot, &rc);
146486  assert( pRoot->bEof==0 );
146487  }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
146488  }
146489  }
146490  return rc;
146491 }
146492 
146493 /*
146494 ** This function is used by the matchinfo() module to query a phrase
146495 ** expression node for the following information:
146496 **
146497 ** 1. The total number of occurrences of the phrase in each column of
146498 ** the FTS table (considering all rows), and
146499 **
146500 ** 2. For each column, the number of rows in the table for which the
146501 ** column contains at least one instance of the phrase.
146502 **
146503 ** If no error occurs, SQLITE_OK is returned and the values for each column
146504 ** written into the array aiOut as follows:
146505 **
146506 ** aiOut[iCol*3 + 1] = Number of occurrences
146507 ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
146508 **
146509 ** Caveats:
146510 **
146511 ** * If a phrase consists entirely of deferred tokens, then all output
146512 ** values are set to the number of documents in the table. In other
146513 ** words we assume that very common tokens occur exactly once in each
146514 ** column of each row of the table.
146515 **
146516 ** * If a phrase contains some deferred tokens (and some non-deferred
146517 ** tokens), count the potential occurrence identified by considering
146518 ** the non-deferred tokens instead of actual phrase occurrences.
146519 **
146520 ** * If the phrase is part of a NEAR expression, then only phrase instances
146521 ** that meet the NEAR constraint are included in the counts.
146522 */
146523 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
146524  Fts3Cursor *pCsr, /* FTS cursor handle */
146525  Fts3Expr *pExpr, /* Phrase expression */
146526  u32 *aiOut /* Array to write results into (see above) */
146527 ){
146528  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146529  int rc = SQLITE_OK;
146530  int iCol;
146531 
146532  if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
146533  assert( pCsr->nDoc>0 );
146534  for(iCol=0; iCol<pTab->nColumn; iCol++){
146535  aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
146536  aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
146537  }
146538  }else{
146539  rc = fts3EvalGatherStats(pCsr, pExpr);
146540  if( rc==SQLITE_OK ){
146541  assert( pExpr->aMI );
146542  for(iCol=0; iCol<pTab->nColumn; iCol++){
146543  aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
146544  aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
146545  }
146546  }
146547  }
146548 
146549  return rc;
146550 }
146551 
146552 /*
146553 ** The expression pExpr passed as the second argument to this function
146554 ** must be of type FTSQUERY_PHRASE.
146555 **
146556 ** The returned value is either NULL or a pointer to a buffer containing
146557 ** a position-list indicating the occurrences of the phrase in column iCol
146558 ** of the current row.
146559 **
146560 ** More specifically, the returned buffer contains 1 varint for each
146561 ** occurrence of the phrase in the column, stored using the normal (delta+2)
146562 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
146563 ** if the requested column contains "a b X c d X X" and the position-list
146564 ** for 'X' is requested, the buffer returned may contain:
146565 **
146566 ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
146567 **
146568 ** This function works regardless of whether or not the phrase is deferred,
146569 ** incremental, or neither.
146570 */
146571 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
146572  Fts3Cursor *pCsr, /* FTS3 cursor object */
146573  Fts3Expr *pExpr, /* Phrase to return doclist for */
146574  int iCol, /* Column to return position list for */
146575  char **ppOut /* OUT: Pointer to position list */
146576 ){
146577  Fts3Phrase *pPhrase = pExpr->pPhrase;
146578  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
146579  char *pIter;
146580  int iThis;
146581  sqlite3_int64 iDocid;
146582 
146583  /* If this phrase is applies specifically to some column other than
146584  ** column iCol, return a NULL pointer. */
146585  *ppOut = 0;
146586  assert( iCol>=0 && iCol<pTab->nColumn );
146587  if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
146588  return SQLITE_OK;
146589  }
146590 
146591  iDocid = pExpr->iDocid;
146592  pIter = pPhrase->doclist.pList;
146593  if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
146594  int rc = SQLITE_OK;
146595  int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
146596  int bOr = 0;
146597  u8 bTreeEof = 0;
146598  Fts3Expr *p; /* Used to iterate from pExpr to root */
146599  Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
146600  int bMatch;
146601 
146602  /* Check if this phrase descends from an OR expression node. If not,
146603  ** return NULL. Otherwise, the entry that corresponds to docid
146604  ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
146605  ** tree that the node is part of has been marked as EOF, but the node
146606  ** itself is not EOF, then it may point to an earlier entry. */
146607  pNear = pExpr;
146608  for(p=pExpr->pParent; p; p=p->pParent){
146609  if( p->eType==FTSQUERY_OR ) bOr = 1;
146610  if( p->eType==FTSQUERY_NEAR ) pNear = p;
146611  if( p->bEof ) bTreeEof = 1;
146612  }
146613  if( bOr==0 ) return SQLITE_OK;
146614 
146615  /* This is the descendent of an OR node. In this case we cannot use
146616  ** an incremental phrase. Load the entire doclist for the phrase
146617  ** into memory in this case. */
146618  if( pPhrase->bIncr ){
146619  int bEofSave = pNear->bEof;
146620  fts3EvalRestart(pCsr, pNear, &rc);
146621  while( rc==SQLITE_OK && !pNear->bEof ){
146622  fts3EvalNextRow(pCsr, pNear, &rc);
146623  if( bEofSave==0 && pNear->iDocid==iDocid ) break;
146624  }
146625  assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
146626  }
146627  if( bTreeEof ){
146628  while( rc==SQLITE_OK && !pNear->bEof ){
146629  fts3EvalNextRow(pCsr, pNear, &rc);
146630  }
146631  }
146632  if( rc!=SQLITE_OK ) return rc;
146633 
146634  bMatch = 1;
146635  for(p=pNear; p; p=p->pLeft){
146636  u8 bEof = 0;
146637  Fts3Expr *pTest = p;
146638  Fts3Phrase *pPh;
146639  assert( pTest->eType==FTSQUERY_NEAR || pTest->eType==FTSQUERY_PHRASE );
146640  if( pTest->eType==FTSQUERY_NEAR ) pTest = pTest->pRight;
146641  assert( pTest->eType==FTSQUERY_PHRASE );
146642  pPh = pTest->pPhrase;
146643 
146644  pIter = pPh->pOrPoslist;
146645  iDocid = pPh->iOrDocid;
146646  if( pCsr->bDesc==bDescDoclist ){
146647  bEof = !pPh->doclist.nAll ||
146648  (pIter >= (pPh->doclist.aAll + pPh->doclist.nAll));
146649  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
146650  sqlite3Fts3DoclistNext(
146651  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
146652  &pIter, &iDocid, &bEof
146653  );
146654  }
146655  }else{
146656  bEof = !pPh->doclist.nAll || (pIter && pIter<=pPh->doclist.aAll);
146657  while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
146658  int dummy;
146659  sqlite3Fts3DoclistPrev(
146660  bDescDoclist, pPh->doclist.aAll, pPh->doclist.nAll,
146661  &pIter, &iDocid, &dummy, &bEof
146662  );
146663  }
146664  }
146665  pPh->pOrPoslist = pIter;
146666  pPh->iOrDocid = iDocid;
146667  if( bEof || iDocid!=pCsr->iPrevId ) bMatch = 0;
146668  }
146669 
146670  if( bMatch ){
146671  pIter = pPhrase->pOrPoslist;
146672  }else{
146673  pIter = 0;
146674  }
146675  }
146676  if( pIter==0 ) return SQLITE_OK;
146677 
146678  if( *pIter==0x01 ){
146679  pIter++;
146680  pIter += fts3GetVarint32(pIter, &iThis);
146681  }else{
146682  iThis = 0;
146683  }
146684  while( iThis<iCol ){
146685  fts3ColumnlistCopy(0, &pIter);
146686  if( *pIter==0x00 ) return SQLITE_OK;
146687  pIter++;
146688  pIter += fts3GetVarint32(pIter, &iThis);
146689  }
146690  if( *pIter==0x00 ){
146691  pIter = 0;
146692  }
146693 
146694  *ppOut = ((iCol==iThis)?pIter:0);
146695  return SQLITE_OK;
146696 }
146697 
146698 /*
146699 ** Free all components of the Fts3Phrase structure that were allocated by
146700 ** the eval module. Specifically, this means to free:
146701 **
146702 ** * the contents of pPhrase->doclist, and
146703 ** * any Fts3MultiSegReader objects held by phrase tokens.
146704 */
146705 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
146706  if( pPhrase ){
146707  int i;
146708  sqlite3_free(pPhrase->doclist.aAll);
146709  fts3EvalInvalidatePoslist(pPhrase);
146710  memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
146711  for(i=0; i<pPhrase->nToken; i++){
146712  fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
146713  pPhrase->aToken[i].pSegcsr = 0;
146714  }
146715  }
146716 }
146717 
146718 
146719 /*
146720 ** Return SQLITE_CORRUPT_VTAB.
146721 */
146722 #ifdef SQLITE_DEBUG
146723 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
146724  return SQLITE_CORRUPT_VTAB;
146725 }
146726 #endif
146727 
146728 #if !SQLITE_CORE
146729 /*
146730 ** Initialize API pointer table, if required.
146731 */
146732 #ifdef _WIN32
146733 __declspec(dllexport)
146734 #endif
146735 SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
146736  sqlite3 *db,
146737  char **pzErrMsg,
146738  const sqlite3_api_routines *pApi
146739 ){
146740  SQLITE_EXTENSION_INIT2(pApi)
146741  return sqlite3Fts3Init(db);
146742 }
146743 #endif
146744 
146745 #endif
146746 
146747 /************** End of fts3.c ************************************************/
146748 /************** Begin file fts3_aux.c ****************************************/
146749 /*
146750 ** 2011 Jan 27
146751 **
146752 ** The author disclaims copyright to this source code. In place of
146753 ** a legal notice, here is a blessing:
146754 **
146755 ** May you do good and not evil.
146756 ** May you find forgiveness for yourself and forgive others.
146757 ** May you share freely, never taking more than you give.
146758 **
146759 ******************************************************************************
146760 **
146761 */
146762 /* #include "fts3Int.h" */
146763 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
146764 
146765 /* #include <string.h> */
146766 /* #include <assert.h> */
146767 
146768 typedef struct Fts3auxTable Fts3auxTable;
146769 typedef struct Fts3auxCursor Fts3auxCursor;
146770 
146771 struct Fts3auxTable {
146772  sqlite3_vtab base; /* Base class used by SQLite core */
146773  Fts3Table *pFts3Tab;
146774 };
146775 
146776 struct Fts3auxCursor {
146777  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
146778  Fts3MultiSegReader csr; /* Must be right after "base" */
146779  Fts3SegFilter filter;
146780  char *zStop;
146781  int nStop; /* Byte-length of string zStop */
146782  int iLangid; /* Language id to query */
146783  int isEof; /* True if cursor is at EOF */
146784  sqlite3_int64 iRowid; /* Current rowid */
146785 
146786  int iCol; /* Current value of 'col' column */
146787  int nStat; /* Size of aStat[] array */
146788  struct Fts3auxColstats {
146789  sqlite3_int64 nDoc; /* 'documents' values for current csr row */
146790  sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
146791  } *aStat;
146792 };
146793 
146794 /*
146795 ** Schema of the terms table.
146796 */
146797 #define FTS3_AUX_SCHEMA \
146798  "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
146799 
146800 /*
146801 ** This function does all the work for both the xConnect and xCreate methods.
146802 ** These tables have no persistent representation of their own, so xConnect
146803 ** and xCreate are identical operations.
146804 */
146805 static int fts3auxConnectMethod(
146806  sqlite3 *db, /* Database connection */
146807  void *pUnused, /* Unused */
146808  int argc, /* Number of elements in argv array */
146809  const char * const *argv, /* xCreate/xConnect argument array */
146810  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
146811  char **pzErr /* OUT: sqlite3_malloc'd error message */
146812 ){
146813  char const *zDb; /* Name of database (e.g. "main") */
146814  char const *zFts3; /* Name of fts3 table */
146815  int nDb; /* Result of strlen(zDb) */
146816  int nFts3; /* Result of strlen(zFts3) */
146817  int nByte; /* Bytes of space to allocate here */
146818  int rc; /* value returned by declare_vtab() */
146819  Fts3auxTable *p; /* Virtual table object to return */
146820 
146821  UNUSED_PARAMETER(pUnused);
146822 
146823  /* The user should invoke this in one of two forms:
146824  **
146825  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
146826  ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
146827  */
146828  if( argc!=4 && argc!=5 ) goto bad_args;
146829 
146830  zDb = argv[1];
146831  nDb = (int)strlen(zDb);
146832  if( argc==5 ){
146833  if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
146834  zDb = argv[3];
146835  nDb = (int)strlen(zDb);
146836  zFts3 = argv[4];
146837  }else{
146838  goto bad_args;
146839  }
146840  }else{
146841  zFts3 = argv[3];
146842  }
146843  nFts3 = (int)strlen(zFts3);
146844 
146845  rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
146846  if( rc!=SQLITE_OK ) return rc;
146847 
146848  nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
146849  p = (Fts3auxTable *)sqlite3_malloc(nByte);
146850  if( !p ) return SQLITE_NOMEM;
146851  memset(p, 0, nByte);
146852 
146853  p->pFts3Tab = (Fts3Table *)&p[1];
146854  p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
146855  p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
146856  p->pFts3Tab->db = db;
146857  p->pFts3Tab->nIndex = 1;
146858 
146859  memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
146860  memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
146861  sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
146862 
146863  *ppVtab = (sqlite3_vtab *)p;
146864  return SQLITE_OK;
146865 
146866  bad_args:
146867  sqlite3Fts3ErrMsg(pzErr, "invalid arguments to fts4aux constructor");
146868  return SQLITE_ERROR;
146869 }
146870 
146871 /*
146872 ** This function does the work for both the xDisconnect and xDestroy methods.
146873 ** These tables have no persistent representation of their own, so xDisconnect
146874 ** and xDestroy are identical operations.
146875 */
146876 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
146877  Fts3auxTable *p = (Fts3auxTable *)pVtab;
146878  Fts3Table *pFts3 = p->pFts3Tab;
146879  int i;
146880 
146881  /* Free any prepared statements held */
146882  for(i=0; i<SizeofArray(pFts3->aStmt); i++){
146883  sqlite3_finalize(pFts3->aStmt[i]);
146884  }
146885  sqlite3_free(pFts3->zSegmentsTbl);
146886  sqlite3_free(p);
146887  return SQLITE_OK;
146888 }
146889 
146890 #define FTS4AUX_EQ_CONSTRAINT 1
146891 #define FTS4AUX_GE_CONSTRAINT 2
146892 #define FTS4AUX_LE_CONSTRAINT 4
146893 
146894 /*
146895 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
146896 */
146897 static int fts3auxBestIndexMethod(
146898  sqlite3_vtab *pVTab,
146899  sqlite3_index_info *pInfo
146900 ){
146901  int i;
146902  int iEq = -1;
146903  int iGe = -1;
146904  int iLe = -1;
146905  int iLangid = -1;
146906  int iNext = 1; /* Next free argvIndex value */
146907 
146908  UNUSED_PARAMETER(pVTab);
146909 
146910  /* This vtab delivers always results in "ORDER BY term ASC" order. */
146911  if( pInfo->nOrderBy==1
146912  && pInfo->aOrderBy[0].iColumn==0
146913  && pInfo->aOrderBy[0].desc==0
146914  ){
146915  pInfo->orderByConsumed = 1;
146916  }
146917 
146918  /* Search for equality and range constraints on the "term" column.
146919  ** And equality constraints on the hidden "languageid" column. */
146920  for(i=0; i<pInfo->nConstraint; i++){
146921  if( pInfo->aConstraint[i].usable ){
146922  int op = pInfo->aConstraint[i].op;
146923  int iCol = pInfo->aConstraint[i].iColumn;
146924 
146925  if( iCol==0 ){
146926  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
146927  if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
146928  if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
146929  if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
146930  if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
146931  }
146932  if( iCol==4 ){
146933  if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
146934  }
146935  }
146936  }
146937 
146938  if( iEq>=0 ){
146939  pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
146940  pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
146941  pInfo->estimatedCost = 5;
146942  }else{
146943  pInfo->idxNum = 0;
146944  pInfo->estimatedCost = 20000;
146945  if( iGe>=0 ){
146946  pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
146947  pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
146948  pInfo->estimatedCost /= 2;
146949  }
146950  if( iLe>=0 ){
146951  pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
146952  pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
146953  pInfo->estimatedCost /= 2;
146954  }
146955  }
146956  if( iLangid>=0 ){
146957  pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
146958  pInfo->estimatedCost--;
146959  }
146960 
146961  return SQLITE_OK;
146962 }
146963 
146964 /*
146965 ** xOpen - Open a cursor.
146966 */
146967 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
146968  Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
146969 
146970  UNUSED_PARAMETER(pVTab);
146971 
146972  pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
146973  if( !pCsr ) return SQLITE_NOMEM;
146974  memset(pCsr, 0, sizeof(Fts3auxCursor));
146975 
146976  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
146977  return SQLITE_OK;
146978 }
146979 
146980 /*
146981 ** xClose - Close a cursor.
146982 */
146983 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
146984  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
146985  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
146986 
146987  sqlite3Fts3SegmentsClose(pFts3);
146988  sqlite3Fts3SegReaderFinish(&pCsr->csr);
146989  sqlite3_free((void *)pCsr->filter.zTerm);
146990  sqlite3_free(pCsr->zStop);
146991  sqlite3_free(pCsr->aStat);
146992  sqlite3_free(pCsr);
146993  return SQLITE_OK;
146994 }
146995 
146996 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
146997  if( nSize>pCsr->nStat ){
146998  struct Fts3auxColstats *aNew;
146999  aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
147000  sizeof(struct Fts3auxColstats) * nSize
147001  );
147002  if( aNew==0 ) return SQLITE_NOMEM;
147003  memset(&aNew[pCsr->nStat], 0,
147004  sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
147005  );
147006  pCsr->aStat = aNew;
147007  pCsr->nStat = nSize;
147008  }
147009  return SQLITE_OK;
147010 }
147011 
147012 /*
147013 ** xNext - Advance the cursor to the next row, if any.
147014 */
147015 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
147016  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147017  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147018  int rc;
147019 
147020  /* Increment our pretend rowid value. */
147021  pCsr->iRowid++;
147022 
147023  for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
147024  if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
147025  }
147026 
147027  rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
147028  if( rc==SQLITE_ROW ){
147029  int i = 0;
147030  int nDoclist = pCsr->csr.nDoclist;
147031  char *aDoclist = pCsr->csr.aDoclist;
147032  int iCol;
147033 
147034  int eState = 0;
147035 
147036  if( pCsr->zStop ){
147037  int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
147038  int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
147039  if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
147040  pCsr->isEof = 1;
147041  return SQLITE_OK;
147042  }
147043  }
147044 
147045  if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
147046  memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
147047  iCol = 0;
147048 
147049  while( i<nDoclist ){
147050  sqlite3_int64 v = 0;
147051 
147052  i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
147053  switch( eState ){
147054  /* State 0. In this state the integer just read was a docid. */
147055  case 0:
147056  pCsr->aStat[0].nDoc++;
147057  eState = 1;
147058  iCol = 0;
147059  break;
147060 
147061  /* State 1. In this state we are expecting either a 1, indicating
147062  ** that the following integer will be a column number, or the
147063  ** start of a position list for column 0.
147064  **
147065  ** The only difference between state 1 and state 2 is that if the
147066  ** integer encountered in state 1 is not 0 or 1, then we need to
147067  ** increment the column 0 "nDoc" count for this term.
147068  */
147069  case 1:
147070  assert( iCol==0 );
147071  if( v>1 ){
147072  pCsr->aStat[1].nDoc++;
147073  }
147074  eState = 2;
147075  /* fall through */
147076 
147077  case 2:
147078  if( v==0 ){ /* 0x00. Next integer will be a docid. */
147079  eState = 0;
147080  }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
147081  eState = 3;
147082  }else{ /* 2 or greater. A position. */
147083  pCsr->aStat[iCol+1].nOcc++;
147084  pCsr->aStat[0].nOcc++;
147085  }
147086  break;
147087 
147088  /* State 3. The integer just read is a column number. */
147089  default: assert( eState==3 );
147090  iCol = (int)v;
147091  if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
147092  pCsr->aStat[iCol+1].nDoc++;
147093  eState = 2;
147094  break;
147095  }
147096  }
147097 
147098  pCsr->iCol = 0;
147099  rc = SQLITE_OK;
147100  }else{
147101  pCsr->isEof = 1;
147102  }
147103  return rc;
147104 }
147105 
147106 /*
147107 ** xFilter - Initialize a cursor to point at the start of its data.
147108 */
147109 static int fts3auxFilterMethod(
147110  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
147111  int idxNum, /* Strategy index */
147112  const char *idxStr, /* Unused */
147113  int nVal, /* Number of elements in apVal */
147114  sqlite3_value **apVal /* Arguments for the indexing scheme */
147115 ){
147116  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147117  Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
147118  int rc;
147119  int isScan = 0;
147120  int iLangVal = 0; /* Language id to query */
147121 
147122  int iEq = -1; /* Index of term=? value in apVal */
147123  int iGe = -1; /* Index of term>=? value in apVal */
147124  int iLe = -1; /* Index of term<=? value in apVal */
147125  int iLangid = -1; /* Index of languageid=? value in apVal */
147126  int iNext = 0;
147127 
147128  UNUSED_PARAMETER(nVal);
147129  UNUSED_PARAMETER(idxStr);
147130 
147131  assert( idxStr==0 );
147132  assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
147133  || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
147134  || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
147135  );
147136 
147137  if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
147138  iEq = iNext++;
147139  }else{
147140  isScan = 1;
147141  if( idxNum & FTS4AUX_GE_CONSTRAINT ){
147142  iGe = iNext++;
147143  }
147144  if( idxNum & FTS4AUX_LE_CONSTRAINT ){
147145  iLe = iNext++;
147146  }
147147  }
147148  if( iNext<nVal ){
147149  iLangid = iNext++;
147150  }
147151 
147152  /* In case this cursor is being reused, close and zero it. */
147153  testcase(pCsr->filter.zTerm);
147154  sqlite3Fts3SegReaderFinish(&pCsr->csr);
147155  sqlite3_free((void *)pCsr->filter.zTerm);
147156  sqlite3_free(pCsr->aStat);
147157  memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
147158 
147159  pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
147160  if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
147161 
147162  if( iEq>=0 || iGe>=0 ){
147163  const unsigned char *zStr = sqlite3_value_text(apVal[0]);
147164  assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
147165  if( zStr ){
147166  pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
147167  pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
147168  if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
147169  }
147170  }
147171 
147172  if( iLe>=0 ){
147173  pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
147174  pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
147175  if( pCsr->zStop==0 ) return SQLITE_NOMEM;
147176  }
147177 
147178  if( iLangid>=0 ){
147179  iLangVal = sqlite3_value_int(apVal[iLangid]);
147180 
147181  /* If the user specified a negative value for the languageid, use zero
147182  ** instead. This works, as the "languageid=?" constraint will also
147183  ** be tested by the VDBE layer. The test will always be false (since
147184  ** this module will not return a row with a negative languageid), and
147185  ** so the overall query will return zero rows. */
147186  if( iLangVal<0 ) iLangVal = 0;
147187  }
147188  pCsr->iLangid = iLangVal;
147189 
147190  rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
147191  pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
147192  );
147193  if( rc==SQLITE_OK ){
147194  rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
147195  }
147196 
147197  if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
147198  return rc;
147199 }
147200 
147201 /*
147202 ** xEof - Return true if the cursor is at EOF, or false otherwise.
147203 */
147204 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
147205  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147206  return pCsr->isEof;
147207 }
147208 
147209 /*
147210 ** xColumn - Return a column value.
147211 */
147212 static int fts3auxColumnMethod(
147213  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
147214  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
147215  int iCol /* Index of column to read value from */
147216 ){
147217  Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
147218 
147219  assert( p->isEof==0 );
147220  switch( iCol ){
147221  case 0: /* term */
147222  sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
147223  break;
147224 
147225  case 1: /* col */
147226  if( p->iCol ){
147227  sqlite3_result_int(pCtx, p->iCol-1);
147228  }else{
147229  sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
147230  }
147231  break;
147232 
147233  case 2: /* documents */
147234  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
147235  break;
147236 
147237  case 3: /* occurrences */
147238  sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
147239  break;
147240 
147241  default: /* languageid */
147242  assert( iCol==4 );
147243  sqlite3_result_int(pCtx, p->iLangid);
147244  break;
147245  }
147246 
147247  return SQLITE_OK;
147248 }
147249 
147250 /*
147251 ** xRowid - Return the current rowid for the cursor.
147252 */
147253 static int fts3auxRowidMethod(
147254  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
147255  sqlite_int64 *pRowid /* OUT: Rowid value */
147256 ){
147257  Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
147258  *pRowid = pCsr->iRowid;
147259  return SQLITE_OK;
147260 }
147261 
147262 /*
147263 ** Register the fts3aux module with database connection db. Return SQLITE_OK
147264 ** if successful or an error code if sqlite3_create_module() fails.
147265 */
147266 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
147267  static const sqlite3_module fts3aux_module = {
147268  0, /* iVersion */
147269  fts3auxConnectMethod, /* xCreate */
147270  fts3auxConnectMethod, /* xConnect */
147271  fts3auxBestIndexMethod, /* xBestIndex */
147272  fts3auxDisconnectMethod, /* xDisconnect */
147273  fts3auxDisconnectMethod, /* xDestroy */
147274  fts3auxOpenMethod, /* xOpen */
147275  fts3auxCloseMethod, /* xClose */
147276  fts3auxFilterMethod, /* xFilter */
147277  fts3auxNextMethod, /* xNext */
147278  fts3auxEofMethod, /* xEof */
147279  fts3auxColumnMethod, /* xColumn */
147280  fts3auxRowidMethod, /* xRowid */
147281  0, /* xUpdate */
147282  0, /* xBegin */
147283  0, /* xSync */
147284  0, /* xCommit */
147285  0, /* xRollback */
147286  0, /* xFindFunction */
147287  0, /* xRename */
147288  0, /* xSavepoint */
147289  0, /* xRelease */
147290  0 /* xRollbackTo */
147291  };
147292  int rc; /* Return code */
147293 
147294  rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
147295  return rc;
147296 }
147297 
147298 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
147299 
147300 /************** End of fts3_aux.c ********************************************/
147301 /************** Begin file fts3_expr.c ***************************************/
147302 /*
147303 ** 2008 Nov 28
147304 **
147305 ** The author disclaims copyright to this source code. In place of
147306 ** a legal notice, here is a blessing:
147307 **
147308 ** May you do good and not evil.
147309 ** May you find forgiveness for yourself and forgive others.
147310 ** May you share freely, never taking more than you give.
147311 **
147312 ******************************************************************************
147313 **
147314 ** This module contains code that implements a parser for fts3 query strings
147315 ** (the right-hand argument to the MATCH operator). Because the supported
147316 ** syntax is relatively simple, the whole tokenizer/parser system is
147317 ** hand-coded.
147318 */
147319 /* #include "fts3Int.h" */
147320 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
147321 
147322 /*
147323 ** By default, this module parses the legacy syntax that has been
147324 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
147325 ** is defined, then it uses the new syntax. The differences between
147326 ** the new and the old syntaxes are:
147327 **
147328 ** a) The new syntax supports parenthesis. The old does not.
147329 **
147330 ** b) The new syntax supports the AND and NOT operators. The old does not.
147331 **
147332 ** c) The old syntax supports the "-" token qualifier. This is not
147333 ** supported by the new syntax (it is replaced by the NOT operator).
147334 **
147335 ** d) When using the old syntax, the OR operator has a greater precedence
147336 ** than an implicit AND. When using the new, both implicity and explicit
147337 ** AND operators have a higher precedence than OR.
147338 **
147339 ** If compiled with SQLITE_TEST defined, then this module exports the
147340 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
147341 ** to zero causes the module to use the old syntax. If it is set to
147342 ** non-zero the new syntax is activated. This is so both syntaxes can
147343 ** be tested using a single build of testfixture.
147344 **
147345 ** The following describes the syntax supported by the fts3 MATCH
147346 ** operator in a similar format to that used by the lemon parser
147347 ** generator. This module does not use actually lemon, it uses a
147348 ** custom parser.
147349 **
147350 ** query ::= andexpr (OR andexpr)*.
147351 **
147352 ** andexpr ::= notexpr (AND? notexpr)*.
147353 **
147354 ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
147355 ** notexpr ::= LP query RP.
147356 **
147357 ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
147358 **
147359 ** distance_opt ::= .
147360 ** distance_opt ::= / INTEGER.
147361 **
147362 ** phrase ::= TOKEN.
147363 ** phrase ::= COLUMN:TOKEN.
147364 ** phrase ::= "TOKEN TOKEN TOKEN...".
147365 */
147366 
147367 #ifdef SQLITE_TEST
147368 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
147369 #else
147370 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
147371 # define sqlite3_fts3_enable_parentheses 1
147372 # else
147373 # define sqlite3_fts3_enable_parentheses 0
147374 # endif
147375 #endif
147376 
147377 /*
147378 ** Default span for NEAR operators.
147379 */
147380 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
147381 
147382 /* #include <string.h> */
147383 /* #include <assert.h> */
147384 
147385 /*
147386 ** isNot:
147387 ** This variable is used by function getNextNode(). When getNextNode() is
147388 ** called, it sets ParseContext.isNot to true if the 'next node' is a
147389 ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
147390 ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
147391 ** zero.
147392 */
147393 typedef struct ParseContext ParseContext;
147394 struct ParseContext {
147395  sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
147396  int iLangid; /* Language id used with tokenizer */
147397  const char **azCol; /* Array of column names for fts3 table */
147398  int bFts4; /* True to allow FTS4-only syntax */
147399  int nCol; /* Number of entries in azCol[] */
147400  int iDefaultCol; /* Default column to query */
147401  int isNot; /* True if getNextNode() sees a unary - */
147402  sqlite3_context *pCtx; /* Write error message here */
147403  int nNest; /* Number of nested brackets */
147404 };
147405 
147406 /*
147407 ** This function is equivalent to the standard isspace() function.
147408 **
147409 ** The standard isspace() can be awkward to use safely, because although it
147410 ** is defined to accept an argument of type int, its behavior when passed
147411 ** an integer that falls outside of the range of the unsigned char type
147412 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
147413 ** is defined to accept an argument of type char, and always returns 0 for
147414 ** any values that fall outside of the range of the unsigned char type (i.e.
147415 ** negative values).
147416 */
147417 static int fts3isspace(char c){
147418  return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
147419 }
147420 
147421 /*
147422 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
147423 ** zero the memory before returning a pointer to it. If unsuccessful,
147424 ** return NULL.
147425 */
147426 static void *fts3MallocZero(int nByte){
147427  void *pRet = sqlite3_malloc(nByte);
147428  if( pRet ) memset(pRet, 0, nByte);
147429  return pRet;
147430 }
147431 
147432 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
147433  sqlite3_tokenizer *pTokenizer,
147434  int iLangid,
147435  const char *z,
147436  int n,
147437  sqlite3_tokenizer_cursor **ppCsr
147438 ){
147439  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
147440  sqlite3_tokenizer_cursor *pCsr = 0;
147441  int rc;
147442 
147443  rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
147444  assert( rc==SQLITE_OK || pCsr==0 );
147445  if( rc==SQLITE_OK ){
147446  pCsr->pTokenizer = pTokenizer;
147447  if( pModule->iVersion>=1 ){
147448  rc = pModule->xLanguageid(pCsr, iLangid);
147449  if( rc!=SQLITE_OK ){
147450  pModule->xClose(pCsr);
147451  pCsr = 0;
147452  }
147453  }
147454  }
147455  *ppCsr = pCsr;
147456  return rc;
147457 }
147458 
147459 /*
147460 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
147461 ** call fts3ExprParse(). So this forward declaration is required.
147462 */
147463 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
147464 
147465 /*
147466 ** Extract the next token from buffer z (length n) using the tokenizer
147467 ** and other information (column names etc.) in pParse. Create an Fts3Expr
147468 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
147469 ** single token and set *ppExpr to point to it. If the end of the buffer is
147470 ** reached before a token is found, set *ppExpr to zero. It is the
147471 ** responsibility of the caller to eventually deallocate the allocated
147472 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
147473 **
147474 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
147475 ** fails.
147476 */
147477 static int getNextToken(
147478  ParseContext *pParse, /* fts3 query parse context */
147479  int iCol, /* Value for Fts3Phrase.iColumn */
147480  const char *z, int n, /* Input string */
147481  Fts3Expr **ppExpr, /* OUT: expression */
147482  int *pnConsumed /* OUT: Number of bytes consumed */
147483 ){
147484  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
147485  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
147486  int rc;
147487  sqlite3_tokenizer_cursor *pCursor;
147488  Fts3Expr *pRet = 0;
147489  int i = 0;
147490 
147491  /* Set variable i to the maximum number of bytes of input to tokenize. */
147492  for(i=0; i<n; i++){
147493  if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
147494  if( z[i]=='"' ) break;
147495  }
147496 
147497  *pnConsumed = i;
147498  rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
147499  if( rc==SQLITE_OK ){
147500  const char *zToken;
147501  int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
147502  int nByte; /* total space to allocate */
147503 
147504  rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
147505  if( rc==SQLITE_OK ){
147506  nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
147507  pRet = (Fts3Expr *)fts3MallocZero(nByte);
147508  if( !pRet ){
147509  rc = SQLITE_NOMEM;
147510  }else{
147511  pRet->eType = FTSQUERY_PHRASE;
147512  pRet->pPhrase = (Fts3Phrase *)&pRet[1];
147513  pRet->pPhrase->nToken = 1;
147514  pRet->pPhrase->iColumn = iCol;
147515  pRet->pPhrase->aToken[0].n = nToken;
147516  pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
147517  memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
147518 
147519  if( iEnd<n && z[iEnd]=='*' ){
147520  pRet->pPhrase->aToken[0].isPrefix = 1;
147521  iEnd++;
147522  }
147523 
147524  while( 1 ){
147525  if( !sqlite3_fts3_enable_parentheses
147526  && iStart>0 && z[iStart-1]=='-'
147527  ){
147528  pParse->isNot = 1;
147529  iStart--;
147530  }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
147531  pRet->pPhrase->aToken[0].bFirst = 1;
147532  iStart--;
147533  }else{
147534  break;
147535  }
147536  }
147537 
147538  }
147539  *pnConsumed = iEnd;
147540  }else if( i && rc==SQLITE_DONE ){
147541  rc = SQLITE_OK;
147542  }
147543 
147544  pModule->xClose(pCursor);
147545  }
147546 
147547  *ppExpr = pRet;
147548  return rc;
147549 }
147550 
147551 
147552 /*
147553 ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
147554 ** then free the old allocation.
147555 */
147556 static void *fts3ReallocOrFree(void *pOrig, int nNew){
147557  void *pRet = sqlite3_realloc(pOrig, nNew);
147558  if( !pRet ){
147559  sqlite3_free(pOrig);
147560  }
147561  return pRet;
147562 }
147563 
147564 /*
147565 ** Buffer zInput, length nInput, contains the contents of a quoted string
147566 ** that appeared as part of an fts3 query expression. Neither quote character
147567 ** is included in the buffer. This function attempts to tokenize the entire
147568 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
147569 ** containing the results.
147570 **
147571 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
147572 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
147573 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
147574 ** to 0.
147575 */
147576 static int getNextString(
147577  ParseContext *pParse, /* fts3 query parse context */
147578  const char *zInput, int nInput, /* Input string */
147579  Fts3Expr **ppExpr /* OUT: expression */
147580 ){
147581  sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
147582  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
147583  int rc;
147584  Fts3Expr *p = 0;
147585  sqlite3_tokenizer_cursor *pCursor = 0;
147586  char *zTemp = 0;
147587  int nTemp = 0;
147588 
147589  const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
147590  int nToken = 0;
147591 
147592  /* The final Fts3Expr data structure, including the Fts3Phrase,
147593  ** Fts3PhraseToken structures token buffers are all stored as a single
147594  ** allocation so that the expression can be freed with a single call to
147595  ** sqlite3_free(). Setting this up requires a two pass approach.
147596  **
147597  ** The first pass, in the block below, uses a tokenizer cursor to iterate
147598  ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
147599  ** to assemble data in two dynamic buffers:
147600  **
147601  ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
147602  ** structure, followed by the array of Fts3PhraseToken
147603  ** structures. This pass only populates the Fts3PhraseToken array.
147604  **
147605  ** Buffer zTemp: Contains copies of all tokens.
147606  **
147607  ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
147608  ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
147609  ** structures.
147610  */
147611  rc = sqlite3Fts3OpenTokenizer(
147612  pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
147613  if( rc==SQLITE_OK ){
147614  int ii;
147615  for(ii=0; rc==SQLITE_OK; ii++){
147616  const char *zByte;
147617  int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
147618  rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
147619  if( rc==SQLITE_OK ){
147620  Fts3PhraseToken *pToken;
147621 
147622  p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
147623  if( !p ) goto no_mem;
147624 
147625  zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
147626  if( !zTemp ) goto no_mem;
147627 
147628  assert( nToken==ii );
147629  pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
147630  memset(pToken, 0, sizeof(Fts3PhraseToken));
147631 
147632  memcpy(&zTemp[nTemp], zByte, nByte);
147633  nTemp += nByte;
147634 
147635  pToken->n = nByte;
147636  pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
147637  pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
147638  nToken = ii+1;
147639  }
147640  }
147641 
147642  pModule->xClose(pCursor);
147643  pCursor = 0;
147644  }
147645 
147646  if( rc==SQLITE_DONE ){
147647  int jj;
147648  char *zBuf = 0;
147649 
147650  p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
147651  if( !p ) goto no_mem;
147652  memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
147653  p->eType = FTSQUERY_PHRASE;
147654  p->pPhrase = (Fts3Phrase *)&p[1];
147655  p->pPhrase->iColumn = pParse->iDefaultCol;
147656  p->pPhrase->nToken = nToken;
147657 
147658  zBuf = (char *)&p->pPhrase->aToken[nToken];
147659  if( zTemp ){
147660  memcpy(zBuf, zTemp, nTemp);
147661  sqlite3_free(zTemp);
147662  }else{
147663  assert( nTemp==0 );
147664  }
147665 
147666  for(jj=0; jj<p->pPhrase->nToken; jj++){
147667  p->pPhrase->aToken[jj].z = zBuf;
147668  zBuf += p->pPhrase->aToken[jj].n;
147669  }
147670  rc = SQLITE_OK;
147671  }
147672 
147673  *ppExpr = p;
147674  return rc;
147675 no_mem:
147676 
147677  if( pCursor ){
147678  pModule->xClose(pCursor);
147679  }
147680  sqlite3_free(zTemp);
147681  sqlite3_free(p);
147682  *ppExpr = 0;
147683  return SQLITE_NOMEM;
147684 }
147685 
147686 /*
147687 ** The output variable *ppExpr is populated with an allocated Fts3Expr
147688 ** structure, or set to 0 if the end of the input buffer is reached.
147689 **
147690 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
147691 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
147692 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
147693 */
147694 static int getNextNode(
147695  ParseContext *pParse, /* fts3 query parse context */
147696  const char *z, int n, /* Input string */
147697  Fts3Expr **ppExpr, /* OUT: expression */
147698  int *pnConsumed /* OUT: Number of bytes consumed */
147699 ){
147700  static const struct Fts3Keyword {
147701  char *z; /* Keyword text */
147702  unsigned char n; /* Length of the keyword */
147703  unsigned char parenOnly; /* Only valid in paren mode */
147704  unsigned char eType; /* Keyword code */
147705  } aKeyword[] = {
147706  { "OR" , 2, 0, FTSQUERY_OR },
147707  { "AND", 3, 1, FTSQUERY_AND },
147708  { "NOT", 3, 1, FTSQUERY_NOT },
147709  { "NEAR", 4, 0, FTSQUERY_NEAR }
147710  };
147711  int ii;
147712  int iCol;
147713  int iColLen;
147714  int rc;
147715  Fts3Expr *pRet = 0;
147716 
147717  const char *zInput = z;
147718  int nInput = n;
147719 
147720  pParse->isNot = 0;
147721 
147722  /* Skip over any whitespace before checking for a keyword, an open or
147723  ** close bracket, or a quoted string.
147724  */
147725  while( nInput>0 && fts3isspace(*zInput) ){
147726  nInput--;
147727  zInput++;
147728  }
147729  if( nInput==0 ){
147730  return SQLITE_DONE;
147731  }
147732 
147733  /* See if we are dealing with a keyword. */
147734  for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
147735  const struct Fts3Keyword *pKey = &aKeyword[ii];
147736 
147737  if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
147738  continue;
147739  }
147740 
147741  if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
147742  int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
147743  int nKey = pKey->n;
147744  char cNext;
147745 
147746  /* If this is a "NEAR" keyword, check for an explicit nearness. */
147747  if( pKey->eType==FTSQUERY_NEAR ){
147748  assert( nKey==4 );
147749  if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
147750  nNear = 0;
147751  for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
147752  nNear = nNear * 10 + (zInput[nKey] - '0');
147753  }
147754  }
147755  }
147756 
147757  /* At this point this is probably a keyword. But for that to be true,
147758  ** the next byte must contain either whitespace, an open or close
147759  ** parenthesis, a quote character, or EOF.
147760  */
147761  cNext = zInput[nKey];
147762  if( fts3isspace(cNext)
147763  || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
147764  ){
147765  pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
147766  if( !pRet ){
147767  return SQLITE_NOMEM;
147768  }
147769  pRet->eType = pKey->eType;
147770  pRet->nNear = nNear;
147771  *ppExpr = pRet;
147772  *pnConsumed = (int)((zInput - z) + nKey);
147773  return SQLITE_OK;
147774  }
147775 
147776  /* Turns out that wasn't a keyword after all. This happens if the
147777  ** user has supplied a token such as "ORacle". Continue.
147778  */
147779  }
147780  }
147781 
147782  /* See if we are dealing with a quoted phrase. If this is the case, then
147783  ** search for the closing quote and pass the whole string to getNextString()
147784  ** for processing. This is easy to do, as fts3 has no syntax for escaping
147785  ** a quote character embedded in a string.
147786  */
147787  if( *zInput=='"' ){
147788  for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
147789  *pnConsumed = (int)((zInput - z) + ii + 1);
147790  if( ii==nInput ){
147791  return SQLITE_ERROR;
147792  }
147793  return getNextString(pParse, &zInput[1], ii-1, ppExpr);
147794  }
147795 
147796  if( sqlite3_fts3_enable_parentheses ){
147797  if( *zInput=='(' ){
147798  int nConsumed = 0;
147799  pParse->nNest++;
147800  rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
147801  if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
147802  *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
147803  return rc;
147804  }else if( *zInput==')' ){
147805  pParse->nNest--;
147806  *pnConsumed = (int)((zInput - z) + 1);
147807  *ppExpr = 0;
147808  return SQLITE_DONE;
147809  }
147810  }
147811 
147812  /* If control flows to this point, this must be a regular token, or
147813  ** the end of the input. Read a regular token using the sqlite3_tokenizer
147814  ** interface. Before doing so, figure out if there is an explicit
147815  ** column specifier for the token.
147816  **
147817  ** TODO: Strangely, it is not possible to associate a column specifier
147818  ** with a quoted phrase, only with a single token. Not sure if this was
147819  ** an implementation artifact or an intentional decision when fts3 was
147820  ** first implemented. Whichever it was, this module duplicates the
147821  ** limitation.
147822  */
147823  iCol = pParse->iDefaultCol;
147824  iColLen = 0;
147825  for(ii=0; ii<pParse->nCol; ii++){
147826  const char *zStr = pParse->azCol[ii];
147827  int nStr = (int)strlen(zStr);
147828  if( nInput>nStr && zInput[nStr]==':'
147829  && sqlite3_strnicmp(zStr, zInput, nStr)==0
147830  ){
147831  iCol = ii;
147832  iColLen = (int)((zInput - z) + nStr + 1);
147833  break;
147834  }
147835  }
147836  rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
147837  *pnConsumed += iColLen;
147838  return rc;
147839 }
147840 
147841 /*
147842 ** The argument is an Fts3Expr structure for a binary operator (any type
147843 ** except an FTSQUERY_PHRASE). Return an integer value representing the
147844 ** precedence of the operator. Lower values have a higher precedence (i.e.
147845 ** group more tightly). For example, in the C language, the == operator
147846 ** groups more tightly than ||, and would therefore have a higher precedence.
147847 **
147848 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
147849 ** is defined), the order of the operators in precedence from highest to
147850 ** lowest is:
147851 **
147852 ** NEAR
147853 ** NOT
147854 ** AND (including implicit ANDs)
147855 ** OR
147856 **
147857 ** Note that when using the old query syntax, the OR operator has a higher
147858 ** precedence than the AND operator.
147859 */
147860 static int opPrecedence(Fts3Expr *p){
147861  assert( p->eType!=FTSQUERY_PHRASE );
147862  if( sqlite3_fts3_enable_parentheses ){
147863  return p->eType;
147864  }else if( p->eType==FTSQUERY_NEAR ){
147865  return 1;
147866  }else if( p->eType==FTSQUERY_OR ){
147867  return 2;
147868  }
147869  assert( p->eType==FTSQUERY_AND );
147870  return 3;
147871 }
147872 
147873 /*
147874 ** Argument ppHead contains a pointer to the current head of a query
147875 ** expression tree being parsed. pPrev is the expression node most recently
147876 ** inserted into the tree. This function adds pNew, which is always a binary
147877 ** operator node, into the expression tree based on the relative precedence
147878 ** of pNew and the existing nodes of the tree. This may result in the head
147879 ** of the tree changing, in which case *ppHead is set to the new root node.
147880 */
147881 static void insertBinaryOperator(
147882  Fts3Expr **ppHead, /* Pointer to the root node of a tree */
147883  Fts3Expr *pPrev, /* Node most recently inserted into the tree */
147884  Fts3Expr *pNew /* New binary node to insert into expression tree */
147885 ){
147886  Fts3Expr *pSplit = pPrev;
147887  while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
147888  pSplit = pSplit->pParent;
147889  }
147890 
147891  if( pSplit->pParent ){
147892  assert( pSplit->pParent->pRight==pSplit );
147893  pSplit->pParent->pRight = pNew;
147894  pNew->pParent = pSplit->pParent;
147895  }else{
147896  *ppHead = pNew;
147897  }
147898  pNew->pLeft = pSplit;
147899  pSplit->pParent = pNew;
147900 }
147901 
147902 /*
147903 ** Parse the fts3 query expression found in buffer z, length n. This function
147904 ** returns either when the end of the buffer is reached or an unmatched
147905 ** closing bracket - ')' - is encountered.
147906 **
147907 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
147908 ** parsed form of the expression and *pnConsumed is set to the number of
147909 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
147910 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
147911 */
147912 static int fts3ExprParse(
147913  ParseContext *pParse, /* fts3 query parse context */
147914  const char *z, int n, /* Text of MATCH query */
147915  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
147916  int *pnConsumed /* OUT: Number of bytes consumed */
147917 ){
147918  Fts3Expr *pRet = 0;
147919  Fts3Expr *pPrev = 0;
147920  Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
147921  int nIn = n;
147922  const char *zIn = z;
147923  int rc = SQLITE_OK;
147924  int isRequirePhrase = 1;
147925 
147926  while( rc==SQLITE_OK ){
147927  Fts3Expr *p = 0;
147928  int nByte = 0;
147929 
147930  rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
147931  assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
147932  if( rc==SQLITE_OK ){
147933  if( p ){
147934  int isPhrase;
147935 
147936  if( !sqlite3_fts3_enable_parentheses
147937  && p->eType==FTSQUERY_PHRASE && pParse->isNot
147938  ){
147939  /* Create an implicit NOT operator. */
147940  Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
147941  if( !pNot ){
147942  sqlite3Fts3ExprFree(p);
147943  rc = SQLITE_NOMEM;
147944  goto exprparse_out;
147945  }
147946  pNot->eType = FTSQUERY_NOT;
147947  pNot->pRight = p;
147948  p->pParent = pNot;
147949  if( pNotBranch ){
147950  pNot->pLeft = pNotBranch;
147951  pNotBranch->pParent = pNot;
147952  }
147953  pNotBranch = pNot;
147954  p = pPrev;
147955  }else{
147956  int eType = p->eType;
147957  isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
147958 
147959  /* The isRequirePhrase variable is set to true if a phrase or
147960  ** an expression contained in parenthesis is required. If a
147961  ** binary operator (AND, OR, NOT or NEAR) is encounted when
147962  ** isRequirePhrase is set, this is a syntax error.
147963  */
147964  if( !isPhrase && isRequirePhrase ){
147965  sqlite3Fts3ExprFree(p);
147966  rc = SQLITE_ERROR;
147967  goto exprparse_out;
147968  }
147969 
147970  if( isPhrase && !isRequirePhrase ){
147971  /* Insert an implicit AND operator. */
147972  Fts3Expr *pAnd;
147973  assert( pRet && pPrev );
147974  pAnd = fts3MallocZero(sizeof(Fts3Expr));
147975  if( !pAnd ){
147976  sqlite3Fts3ExprFree(p);
147977  rc = SQLITE_NOMEM;
147978  goto exprparse_out;
147979  }
147980  pAnd->eType = FTSQUERY_AND;
147981  insertBinaryOperator(&pRet, pPrev, pAnd);
147982  pPrev = pAnd;
147983  }
147984 
147985  /* This test catches attempts to make either operand of a NEAR
147986  ** operator something other than a phrase. For example, either of
147987  ** the following:
147988  **
147989  ** (bracketed expression) NEAR phrase
147990  ** phrase NEAR (bracketed expression)
147991  **
147992  ** Return an error in either case.
147993  */
147994  if( pPrev && (
147995  (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
147996  || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
147997  )){
147998  sqlite3Fts3ExprFree(p);
147999  rc = SQLITE_ERROR;
148000  goto exprparse_out;
148001  }
148002 
148003  if( isPhrase ){
148004  if( pRet ){
148005  assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
148006  pPrev->pRight = p;
148007  p->pParent = pPrev;
148008  }else{
148009  pRet = p;
148010  }
148011  }else{
148012  insertBinaryOperator(&pRet, pPrev, p);
148013  }
148014  isRequirePhrase = !isPhrase;
148015  }
148016  pPrev = p;
148017  }
148018  assert( nByte>0 );
148019  }
148020  assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
148021  nIn -= nByte;
148022  zIn += nByte;
148023  }
148024 
148025  if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
148026  rc = SQLITE_ERROR;
148027  }
148028 
148029  if( rc==SQLITE_DONE ){
148030  rc = SQLITE_OK;
148031  if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
148032  if( !pRet ){
148033  rc = SQLITE_ERROR;
148034  }else{
148035  Fts3Expr *pIter = pNotBranch;
148036  while( pIter->pLeft ){
148037  pIter = pIter->pLeft;
148038  }
148039  pIter->pLeft = pRet;
148040  pRet->pParent = pIter;
148041  pRet = pNotBranch;
148042  }
148043  }
148044  }
148045  *pnConsumed = n - nIn;
148046 
148047 exprparse_out:
148048  if( rc!=SQLITE_OK ){
148049  sqlite3Fts3ExprFree(pRet);
148050  sqlite3Fts3ExprFree(pNotBranch);
148051  pRet = 0;
148052  }
148053  *ppExpr = pRet;
148054  return rc;
148055 }
148056 
148057 /*
148058 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
148059 ** as the only argument is more than nMaxDepth.
148060 */
148061 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
148062  int rc = SQLITE_OK;
148063  if( p ){
148064  if( nMaxDepth<0 ){
148065  rc = SQLITE_TOOBIG;
148066  }else{
148067  rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
148068  if( rc==SQLITE_OK ){
148069  rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
148070  }
148071  }
148072  }
148073  return rc;
148074 }
148075 
148076 /*
148077 ** This function attempts to transform the expression tree at (*pp) to
148078 ** an equivalent but more balanced form. The tree is modified in place.
148079 ** If successful, SQLITE_OK is returned and (*pp) set to point to the
148080 ** new root expression node.
148081 **
148082 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
148083 **
148084 ** Otherwise, if an error occurs, an SQLite error code is returned and
148085 ** expression (*pp) freed.
148086 */
148087 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
148088  int rc = SQLITE_OK; /* Return code */
148089  Fts3Expr *pRoot = *pp; /* Initial root node */
148090  Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
148091  int eType = pRoot->eType; /* Type of node in this tree */
148092 
148093  if( nMaxDepth==0 ){
148094  rc = SQLITE_ERROR;
148095  }
148096 
148097  if( rc==SQLITE_OK ){
148098  if( (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
148099  Fts3Expr **apLeaf;
148100  apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
148101  if( 0==apLeaf ){
148102  rc = SQLITE_NOMEM;
148103  }else{
148104  memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
148105  }
148106 
148107  if( rc==SQLITE_OK ){
148108  int i;
148109  Fts3Expr *p;
148110 
148111  /* Set $p to point to the left-most leaf in the tree of eType nodes. */
148112  for(p=pRoot; p->eType==eType; p=p->pLeft){
148113  assert( p->pParent==0 || p->pParent->pLeft==p );
148114  assert( p->pLeft && p->pRight );
148115  }
148116 
148117  /* This loop runs once for each leaf in the tree of eType nodes. */
148118  while( 1 ){
148119  int iLvl;
148120  Fts3Expr *pParent = p->pParent; /* Current parent of p */
148121 
148122  assert( pParent==0 || pParent->pLeft==p );
148123  p->pParent = 0;
148124  if( pParent ){
148125  pParent->pLeft = 0;
148126  }else{
148127  pRoot = 0;
148128  }
148129  rc = fts3ExprBalance(&p, nMaxDepth-1);
148130  if( rc!=SQLITE_OK ) break;
148131 
148132  for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
148133  if( apLeaf[iLvl]==0 ){
148134  apLeaf[iLvl] = p;
148135  p = 0;
148136  }else{
148137  assert( pFree );
148138  pFree->pLeft = apLeaf[iLvl];
148139  pFree->pRight = p;
148140  pFree->pLeft->pParent = pFree;
148141  pFree->pRight->pParent = pFree;
148142 
148143  p = pFree;
148144  pFree = pFree->pParent;
148145  p->pParent = 0;
148146  apLeaf[iLvl] = 0;
148147  }
148148  }
148149  if( p ){
148150  sqlite3Fts3ExprFree(p);
148151  rc = SQLITE_TOOBIG;
148152  break;
148153  }
148154 
148155  /* If that was the last leaf node, break out of the loop */
148156  if( pParent==0 ) break;
148157 
148158  /* Set $p to point to the next leaf in the tree of eType nodes */
148159  for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
148160 
148161  /* Remove pParent from the original tree. */
148162  assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
148163  pParent->pRight->pParent = pParent->pParent;
148164  if( pParent->pParent ){
148165  pParent->pParent->pLeft = pParent->pRight;
148166  }else{
148167  assert( pParent==pRoot );
148168  pRoot = pParent->pRight;
148169  }
148170 
148171  /* Link pParent into the free node list. It will be used as an
148172  ** internal node of the new tree. */
148173  pParent->pParent = pFree;
148174  pFree = pParent;
148175  }
148176 
148177  if( rc==SQLITE_OK ){
148178  p = 0;
148179  for(i=0; i<nMaxDepth; i++){
148180  if( apLeaf[i] ){
148181  if( p==0 ){
148182  p = apLeaf[i];
148183  p->pParent = 0;
148184  }else{
148185  assert( pFree!=0 );
148186  pFree->pRight = p;
148187  pFree->pLeft = apLeaf[i];
148188  pFree->pLeft->pParent = pFree;
148189  pFree->pRight->pParent = pFree;
148190 
148191  p = pFree;
148192  pFree = pFree->pParent;
148193  p->pParent = 0;
148194  }
148195  }
148196  }
148197  pRoot = p;
148198  }else{
148199  /* An error occurred. Delete the contents of the apLeaf[] array
148200  ** and pFree list. Everything else is cleaned up by the call to
148201  ** sqlite3Fts3ExprFree(pRoot) below. */
148202  Fts3Expr *pDel;
148203  for(i=0; i<nMaxDepth; i++){
148204  sqlite3Fts3ExprFree(apLeaf[i]);
148205  }
148206  while( (pDel=pFree)!=0 ){
148207  pFree = pDel->pParent;
148208  sqlite3_free(pDel);
148209  }
148210  }
148211 
148212  assert( pFree==0 );
148213  sqlite3_free( apLeaf );
148214  }
148215  }else if( eType==FTSQUERY_NOT ){
148216  Fts3Expr *pLeft = pRoot->pLeft;
148217  Fts3Expr *pRight = pRoot->pRight;
148218 
148219  pRoot->pLeft = 0;
148220  pRoot->pRight = 0;
148221  pLeft->pParent = 0;
148222  pRight->pParent = 0;
148223 
148224  rc = fts3ExprBalance(&pLeft, nMaxDepth-1);
148225  if( rc==SQLITE_OK ){
148226  rc = fts3ExprBalance(&pRight, nMaxDepth-1);
148227  }
148228 
148229  if( rc!=SQLITE_OK ){
148230  sqlite3Fts3ExprFree(pRight);
148231  sqlite3Fts3ExprFree(pLeft);
148232  }else{
148233  assert( pLeft && pRight );
148234  pRoot->pLeft = pLeft;
148235  pLeft->pParent = pRoot;
148236  pRoot->pRight = pRight;
148237  pRight->pParent = pRoot;
148238  }
148239  }
148240  }
148241 
148242  if( rc!=SQLITE_OK ){
148243  sqlite3Fts3ExprFree(pRoot);
148244  pRoot = 0;
148245  }
148246  *pp = pRoot;
148247  return rc;
148248 }
148249 
148250 /*
148251 ** This function is similar to sqlite3Fts3ExprParse(), with the following
148252 ** differences:
148253 **
148254 ** 1. It does not do expression rebalancing.
148255 ** 2. It does not check that the expression does not exceed the
148256 ** maximum allowable depth.
148257 ** 3. Even if it fails, *ppExpr may still be set to point to an
148258 ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
148259 ** in this case.
148260 */
148261 static int fts3ExprParseUnbalanced(
148262  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
148263  int iLangid, /* Language id for tokenizer */
148264  char **azCol, /* Array of column names for fts3 table */
148265  int bFts4, /* True to allow FTS4-only syntax */
148266  int nCol, /* Number of entries in azCol[] */
148267  int iDefaultCol, /* Default column to query */
148268  const char *z, int n, /* Text of MATCH query */
148269  Fts3Expr **ppExpr /* OUT: Parsed query structure */
148270 ){
148271  int nParsed;
148272  int rc;
148273  ParseContext sParse;
148274 
148275  memset(&sParse, 0, sizeof(ParseContext));
148276  sParse.pTokenizer = pTokenizer;
148277  sParse.iLangid = iLangid;
148278  sParse.azCol = (const char **)azCol;
148279  sParse.nCol = nCol;
148280  sParse.iDefaultCol = iDefaultCol;
148281  sParse.bFts4 = bFts4;
148282  if( z==0 ){
148283  *ppExpr = 0;
148284  return SQLITE_OK;
148285  }
148286  if( n<0 ){
148287  n = (int)strlen(z);
148288  }
148289  rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
148290  assert( rc==SQLITE_OK || *ppExpr==0 );
148291 
148292  /* Check for mismatched parenthesis */
148293  if( rc==SQLITE_OK && sParse.nNest ){
148294  rc = SQLITE_ERROR;
148295  }
148296 
148297  return rc;
148298 }
148299 
148300 /*
148301 ** Parameters z and n contain a pointer to and length of a buffer containing
148302 ** an fts3 query expression, respectively. This function attempts to parse the
148303 ** query expression and create a tree of Fts3Expr structures representing the
148304 ** parsed expression. If successful, *ppExpr is set to point to the head
148305 ** of the parsed expression tree and SQLITE_OK is returned. If an error
148306 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
148307 ** error) is returned and *ppExpr is set to 0.
148308 **
148309 ** If parameter n is a negative number, then z is assumed to point to a
148310 ** nul-terminated string and the length is determined using strlen().
148311 **
148312 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
148313 ** use to normalize query tokens while parsing the expression. The azCol[]
148314 ** array, which is assumed to contain nCol entries, should contain the names
148315 ** of each column in the target fts3 table, in order from left to right.
148316 ** Column names must be nul-terminated strings.
148317 **
148318 ** The iDefaultCol parameter should be passed the index of the table column
148319 ** that appears on the left-hand-side of the MATCH operator (the default
148320 ** column to match against for tokens for which a column name is not explicitly
148321 ** specified as part of the query string), or -1 if tokens may by default
148322 ** match any table column.
148323 */
148324 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
148325  sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
148326  int iLangid, /* Language id for tokenizer */
148327  char **azCol, /* Array of column names for fts3 table */
148328  int bFts4, /* True to allow FTS4-only syntax */
148329  int nCol, /* Number of entries in azCol[] */
148330  int iDefaultCol, /* Default column to query */
148331  const char *z, int n, /* Text of MATCH query */
148332  Fts3Expr **ppExpr, /* OUT: Parsed query structure */
148333  char **pzErr /* OUT: Error message (sqlite3_malloc) */
148334 ){
148335  int rc = fts3ExprParseUnbalanced(
148336  pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
148337  );
148338 
148339  /* Rebalance the expression. And check that its depth does not exceed
148340  ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
148341  if( rc==SQLITE_OK && *ppExpr ){
148342  rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
148343  if( rc==SQLITE_OK ){
148344  rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
148345  }
148346  }
148347 
148348  if( rc!=SQLITE_OK ){
148349  sqlite3Fts3ExprFree(*ppExpr);
148350  *ppExpr = 0;
148351  if( rc==SQLITE_TOOBIG ){
148352  sqlite3Fts3ErrMsg(pzErr,
148353  "FTS expression tree is too large (maximum depth %d)",
148354  SQLITE_FTS3_MAX_EXPR_DEPTH
148355  );
148356  rc = SQLITE_ERROR;
148357  }else if( rc==SQLITE_ERROR ){
148358  sqlite3Fts3ErrMsg(pzErr, "malformed MATCH expression: [%s]", z);
148359  }
148360  }
148361 
148362  return rc;
148363 }
148364 
148365 /*
148366 ** Free a single node of an expression tree.
148367 */
148368 static void fts3FreeExprNode(Fts3Expr *p){
148369  assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
148370  sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
148371  sqlite3_free(p->aMI);
148372  sqlite3_free(p);
148373 }
148374 
148375 /*
148376 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
148377 **
148378 ** This function would be simpler if it recursively called itself. But
148379 ** that would mean passing a sufficiently large expression to ExprParse()
148380 ** could cause a stack overflow.
148381 */
148382 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
148383  Fts3Expr *p;
148384  assert( pDel==0 || pDel->pParent==0 );
148385  for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
148386  assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
148387  }
148388  while( p ){
148389  Fts3Expr *pParent = p->pParent;
148390  fts3FreeExprNode(p);
148391  if( pParent && p==pParent->pLeft && pParent->pRight ){
148392  p = pParent->pRight;
148393  while( p && (p->pLeft || p->pRight) ){
148394  assert( p==p->pParent->pRight || p==p->pParent->pLeft );
148395  p = (p->pLeft ? p->pLeft : p->pRight);
148396  }
148397  }else{
148398  p = pParent;
148399  }
148400  }
148401 }
148402 
148403 /****************************************************************************
148404 *****************************************************************************
148405 ** Everything after this point is just test code.
148406 */
148407 
148408 #ifdef SQLITE_TEST
148409 
148410 /* #include <stdio.h> */
148411 
148412 /*
148413 ** Function to query the hash-table of tokenizers (see README.tokenizers).
148414 */
148415 static int queryTestTokenizer(
148416  sqlite3 *db,
148417  const char *zName,
148418  const sqlite3_tokenizer_module **pp
148419 ){
148420  int rc;
148421  sqlite3_stmt *pStmt;
148422  const char zSql[] = "SELECT fts3_tokenizer(?)";
148423 
148424  *pp = 0;
148425  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
148426  if( rc!=SQLITE_OK ){
148427  return rc;
148428  }
148429 
148430  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
148431  if( SQLITE_ROW==sqlite3_step(pStmt) ){
148432  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
148433  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
148434  }
148435  }
148436 
148437  return sqlite3_finalize(pStmt);
148438 }
148439 
148440 /*
148441 ** Return a pointer to a buffer containing a text representation of the
148442 ** expression passed as the first argument. The buffer is obtained from
148443 ** sqlite3_malloc(). It is the responsibility of the caller to use
148444 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
148445 ** NULL is returned.
148446 **
148447 ** If the second argument is not NULL, then its contents are prepended to
148448 ** the returned expression text and then freed using sqlite3_free().
148449 */
148450 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
148451  if( pExpr==0 ){
148452  return sqlite3_mprintf("");
148453  }
148454  switch( pExpr->eType ){
148455  case FTSQUERY_PHRASE: {
148456  Fts3Phrase *pPhrase = pExpr->pPhrase;
148457  int i;
148458  zBuf = sqlite3_mprintf(
148459  "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
148460  for(i=0; zBuf && i<pPhrase->nToken; i++){
148461  zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
148462  pPhrase->aToken[i].n, pPhrase->aToken[i].z,
148463  (pPhrase->aToken[i].isPrefix?"+":"")
148464  );
148465  }
148466  return zBuf;
148467  }
148468 
148469  case FTSQUERY_NEAR:
148470  zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
148471  break;
148472  case FTSQUERY_NOT:
148473  zBuf = sqlite3_mprintf("%zNOT ", zBuf);
148474  break;
148475  case FTSQUERY_AND:
148476  zBuf = sqlite3_mprintf("%zAND ", zBuf);
148477  break;
148478  case FTSQUERY_OR:
148479  zBuf = sqlite3_mprintf("%zOR ", zBuf);
148480  break;
148481  }
148482 
148483  if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
148484  if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
148485  if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
148486 
148487  if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
148488  if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
148489 
148490  return zBuf;
148491 }
148492 
148493 /*
148494 ** This is the implementation of a scalar SQL function used to test the
148495 ** expression parser. It should be called as follows:
148496 **
148497 ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
148498 **
148499 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
148500 ** to parse the query expression (see README.tokenizers). The second argument
148501 ** is the query expression to parse. Each subsequent argument is the name
148502 ** of a column of the fts3 table that the query expression may refer to.
148503 ** For example:
148504 **
148505 ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
148506 */
148507 static void fts3ExprTest(
148508  sqlite3_context *context,
148509  int argc,
148510  sqlite3_value **argv
148511 ){
148512  sqlite3_tokenizer_module const *pModule = 0;
148513  sqlite3_tokenizer *pTokenizer = 0;
148514  int rc;
148515  char **azCol = 0;
148516  const char *zExpr;
148517  int nExpr;
148518  int nCol;
148519  int ii;
148520  Fts3Expr *pExpr;
148521  char *zBuf = 0;
148522  sqlite3 *db = sqlite3_context_db_handle(context);
148523 
148524  if( argc<3 ){
148525  sqlite3_result_error(context,
148526  "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
148527  );
148528  return;
148529  }
148530 
148531  rc = queryTestTokenizer(db,
148532  (const char *)sqlite3_value_text(argv[0]), &pModule);
148533  if( rc==SQLITE_NOMEM ){
148534  sqlite3_result_error_nomem(context);
148535  goto exprtest_out;
148536  }else if( !pModule ){
148537  sqlite3_result_error(context, "No such tokenizer module", -1);
148538  goto exprtest_out;
148539  }
148540 
148541  rc = pModule->xCreate(0, 0, &pTokenizer);
148542  assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
148543  if( rc==SQLITE_NOMEM ){
148544  sqlite3_result_error_nomem(context);
148545  goto exprtest_out;
148546  }
148547  pTokenizer->pModule = pModule;
148548 
148549  zExpr = (const char *)sqlite3_value_text(argv[1]);
148550  nExpr = sqlite3_value_bytes(argv[1]);
148551  nCol = argc-2;
148552  azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
148553  if( !azCol ){
148554  sqlite3_result_error_nomem(context);
148555  goto exprtest_out;
148556  }
148557  for(ii=0; ii<nCol; ii++){
148558  azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
148559  }
148560 
148561  if( sqlite3_user_data(context) ){
148562  char *zDummy = 0;
148563  rc = sqlite3Fts3ExprParse(
148564  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
148565  );
148566  assert( rc==SQLITE_OK || pExpr==0 );
148567  sqlite3_free(zDummy);
148568  }else{
148569  rc = fts3ExprParseUnbalanced(
148570  pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
148571  );
148572  }
148573 
148574  if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
148575  sqlite3Fts3ExprFree(pExpr);
148576  sqlite3_result_error(context, "Error parsing expression", -1);
148577  }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
148578  sqlite3_result_error_nomem(context);
148579  }else{
148580  sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
148581  sqlite3_free(zBuf);
148582  }
148583 
148584  sqlite3Fts3ExprFree(pExpr);
148585 
148586 exprtest_out:
148587  if( pModule && pTokenizer ){
148588  rc = pModule->xDestroy(pTokenizer);
148589  }
148590  sqlite3_free(azCol);
148591 }
148592 
148593 /*
148594 ** Register the query expression parser test function fts3_exprtest()
148595 ** with database connection db.
148596 */
148597 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
148598  int rc = sqlite3_create_function(
148599  db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
148600  );
148601  if( rc==SQLITE_OK ){
148602  rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
148603  -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
148604  );
148605  }
148606  return rc;
148607 }
148608 
148609 #endif
148610 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
148611 
148612 /************** End of fts3_expr.c *******************************************/
148613 /************** Begin file fts3_hash.c ***************************************/
148614 /*
148615 ** 2001 September 22
148616 **
148617 ** The author disclaims copyright to this source code. In place of
148618 ** a legal notice, here is a blessing:
148619 **
148620 ** May you do good and not evil.
148621 ** May you find forgiveness for yourself and forgive others.
148622 ** May you share freely, never taking more than you give.
148623 **
148624 *************************************************************************
148625 ** This is the implementation of generic hash-tables used in SQLite.
148626 ** We've modified it slightly to serve as a standalone hash table
148627 ** implementation for the full-text indexing module.
148628 */
148629 
148630 /*
148631 ** The code in this file is only compiled if:
148632 **
148633 ** * The FTS3 module is being built as an extension
148634 ** (in which case SQLITE_CORE is not defined), or
148635 **
148636 ** * The FTS3 module is being built into the core of
148637 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
148638 */
148639 /* #include "fts3Int.h" */
148640 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148641 
148642 /* #include <assert.h> */
148643 /* #include <stdlib.h> */
148644 /* #include <string.h> */
148645 
148646 /* #include "fts3_hash.h" */
148647 
148648 /*
148649 ** Malloc and Free functions
148650 */
148651 static void *fts3HashMalloc(int n){
148652  void *p = sqlite3_malloc(n);
148653  if( p ){
148654  memset(p, 0, n);
148655  }
148656  return p;
148657 }
148658 static void fts3HashFree(void *p){
148659  sqlite3_free(p);
148660 }
148661 
148662 /* Turn bulk memory into a hash table object by initializing the
148663 ** fields of the Hash structure.
148664 **
148665 ** "pNew" is a pointer to the hash table that is to be initialized.
148666 ** keyClass is one of the constants
148667 ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
148668 ** determines what kind of key the hash table will use. "copyKey" is
148669 ** true if the hash table should make its own private copy of keys and
148670 ** false if it should just use the supplied pointer.
148671 */
148672 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
148673  assert( pNew!=0 );
148674  assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
148675  pNew->keyClass = keyClass;
148676  pNew->copyKey = copyKey;
148677  pNew->first = 0;
148678  pNew->count = 0;
148679  pNew->htsize = 0;
148680  pNew->ht = 0;
148681 }
148682 
148683 /* Remove all entries from a hash table. Reclaim all memory.
148684 ** Call this routine to delete a hash table or to reset a hash table
148685 ** to the empty state.
148686 */
148687 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
148688  Fts3HashElem *elem; /* For looping over all elements of the table */
148689 
148690  assert( pH!=0 );
148691  elem = pH->first;
148692  pH->first = 0;
148693  fts3HashFree(pH->ht);
148694  pH->ht = 0;
148695  pH->htsize = 0;
148696  while( elem ){
148697  Fts3HashElem *next_elem = elem->next;
148698  if( pH->copyKey && elem->pKey ){
148699  fts3HashFree(elem->pKey);
148700  }
148701  fts3HashFree(elem);
148702  elem = next_elem;
148703  }
148704  pH->count = 0;
148705 }
148706 
148707 /*
148708 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
148709 */
148710 static int fts3StrHash(const void *pKey, int nKey){
148711  const char *z = (const char *)pKey;
148712  unsigned h = 0;
148713  if( nKey<=0 ) nKey = (int) strlen(z);
148714  while( nKey > 0 ){
148715  h = (h<<3) ^ h ^ *z++;
148716  nKey--;
148717  }
148718  return (int)(h & 0x7fffffff);
148719 }
148720 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
148721  if( n1!=n2 ) return 1;
148722  return strncmp((const char*)pKey1,(const char*)pKey2,n1);
148723 }
148724 
148725 /*
148726 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
148727 */
148728 static int fts3BinHash(const void *pKey, int nKey){
148729  int h = 0;
148730  const char *z = (const char *)pKey;
148731  while( nKey-- > 0 ){
148732  h = (h<<3) ^ h ^ *(z++);
148733  }
148734  return h & 0x7fffffff;
148735 }
148736 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
148737  if( n1!=n2 ) return 1;
148738  return memcmp(pKey1,pKey2,n1);
148739 }
148740 
148741 /*
148742 ** Return a pointer to the appropriate hash function given the key class.
148743 **
148744 ** The C syntax in this function definition may be unfamilar to some
148745 ** programmers, so we provide the following additional explanation:
148746 **
148747 ** The name of the function is "ftsHashFunction". The function takes a
148748 ** single parameter "keyClass". The return value of ftsHashFunction()
148749 ** is a pointer to another function. Specifically, the return value
148750 ** of ftsHashFunction() is a pointer to a function that takes two parameters
148751 ** with types "const void*" and "int" and returns an "int".
148752 */
148753 static int (*ftsHashFunction(int keyClass))(const void*,int){
148754  if( keyClass==FTS3_HASH_STRING ){
148755  return &fts3StrHash;
148756  }else{
148757  assert( keyClass==FTS3_HASH_BINARY );
148758  return &fts3BinHash;
148759  }
148760 }
148761 
148762 /*
148763 ** Return a pointer to the appropriate hash function given the key class.
148764 **
148765 ** For help in interpreted the obscure C code in the function definition,
148766 ** see the header comment on the previous function.
148767 */
148768 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
148769  if( keyClass==FTS3_HASH_STRING ){
148770  return &fts3StrCompare;
148771  }else{
148772  assert( keyClass==FTS3_HASH_BINARY );
148773  return &fts3BinCompare;
148774  }
148775 }
148776 
148777 /* Link an element into the hash table
148778 */
148779 static void fts3HashInsertElement(
148780  Fts3Hash *pH, /* The complete hash table */
148781  struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
148782  Fts3HashElem *pNew /* The element to be inserted */
148783 ){
148784  Fts3HashElem *pHead; /* First element already in pEntry */
148785  pHead = pEntry->chain;
148786  if( pHead ){
148787  pNew->next = pHead;
148788  pNew->prev = pHead->prev;
148789  if( pHead->prev ){ pHead->prev->next = pNew; }
148790  else { pH->first = pNew; }
148791  pHead->prev = pNew;
148792  }else{
148793  pNew->next = pH->first;
148794  if( pH->first ){ pH->first->prev = pNew; }
148795  pNew->prev = 0;
148796  pH->first = pNew;
148797  }
148798  pEntry->count++;
148799  pEntry->chain = pNew;
148800 }
148801 
148802 
148803 /* Resize the hash table so that it cantains "new_size" buckets.
148804 ** "new_size" must be a power of 2. The hash table might fail
148805 ** to resize if sqliteMalloc() fails.
148806 **
148807 ** Return non-zero if a memory allocation error occurs.
148808 */
148809 static int fts3Rehash(Fts3Hash *pH, int new_size){
148810  struct _fts3ht *new_ht; /* The new hash table */
148811  Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
148812  int (*xHash)(const void*,int); /* The hash function */
148813 
148814  assert( (new_size & (new_size-1))==0 );
148815  new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
148816  if( new_ht==0 ) return 1;
148817  fts3HashFree(pH->ht);
148818  pH->ht = new_ht;
148819  pH->htsize = new_size;
148820  xHash = ftsHashFunction(pH->keyClass);
148821  for(elem=pH->first, pH->first=0; elem; elem = next_elem){
148822  int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
148823  next_elem = elem->next;
148824  fts3HashInsertElement(pH, &new_ht[h], elem);
148825  }
148826  return 0;
148827 }
148828 
148829 /* This function (for internal use only) locates an element in an
148830 ** hash table that matches the given key. The hash for this key has
148831 ** already been computed and is passed as the 4th parameter.
148832 */
148833 static Fts3HashElem *fts3FindElementByHash(
148834  const Fts3Hash *pH, /* The pH to be searched */
148835  const void *pKey, /* The key we are searching for */
148836  int nKey,
148837  int h /* The hash for this key. */
148838 ){
148839  Fts3HashElem *elem; /* Used to loop thru the element list */
148840  int count; /* Number of elements left to test */
148841  int (*xCompare)(const void*,int,const void*,int); /* comparison function */
148842 
148843  if( pH->ht ){
148844  struct _fts3ht *pEntry = &pH->ht[h];
148845  elem = pEntry->chain;
148846  count = pEntry->count;
148847  xCompare = ftsCompareFunction(pH->keyClass);
148848  while( count-- && elem ){
148849  if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
148850  return elem;
148851  }
148852  elem = elem->next;
148853  }
148854  }
148855  return 0;
148856 }
148857 
148858 /* Remove a single entry from the hash table given a pointer to that
148859 ** element and a hash on the element's key.
148860 */
148861 static void fts3RemoveElementByHash(
148862  Fts3Hash *pH, /* The pH containing "elem" */
148863  Fts3HashElem* elem, /* The element to be removed from the pH */
148864  int h /* Hash value for the element */
148865 ){
148866  struct _fts3ht *pEntry;
148867  if( elem->prev ){
148868  elem->prev->next = elem->next;
148869  }else{
148870  pH->first = elem->next;
148871  }
148872  if( elem->next ){
148873  elem->next->prev = elem->prev;
148874  }
148875  pEntry = &pH->ht[h];
148876  if( pEntry->chain==elem ){
148877  pEntry->chain = elem->next;
148878  }
148879  pEntry->count--;
148880  if( pEntry->count<=0 ){
148881  pEntry->chain = 0;
148882  }
148883  if( pH->copyKey && elem->pKey ){
148884  fts3HashFree(elem->pKey);
148885  }
148886  fts3HashFree( elem );
148887  pH->count--;
148888  if( pH->count<=0 ){
148889  assert( pH->first==0 );
148890  assert( pH->count==0 );
148891  fts3HashClear(pH);
148892  }
148893 }
148894 
148895 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
148896  const Fts3Hash *pH,
148897  const void *pKey,
148898  int nKey
148899 ){
148900  int h; /* A hash on key */
148901  int (*xHash)(const void*,int); /* The hash function */
148902 
148903  if( pH==0 || pH->ht==0 ) return 0;
148904  xHash = ftsHashFunction(pH->keyClass);
148905  assert( xHash!=0 );
148906  h = (*xHash)(pKey,nKey);
148907  assert( (pH->htsize & (pH->htsize-1))==0 );
148908  return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
148909 }
148910 
148911 /*
148912 ** Attempt to locate an element of the hash table pH with a key
148913 ** that matches pKey,nKey. Return the data for this element if it is
148914 ** found, or NULL if there is no match.
148915 */
148916 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
148917  Fts3HashElem *pElem; /* The element that matches key (if any) */
148918 
148919  pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
148920  return pElem ? pElem->data : 0;
148921 }
148922 
148923 /* Insert an element into the hash table pH. The key is pKey,nKey
148924 ** and the data is "data".
148925 **
148926 ** If no element exists with a matching key, then a new
148927 ** element is created. A copy of the key is made if the copyKey
148928 ** flag is set. NULL is returned.
148929 **
148930 ** If another element already exists with the same key, then the
148931 ** new data replaces the old data and the old data is returned.
148932 ** The key is not copied in this instance. If a malloc fails, then
148933 ** the new data is returned and the hash table is unchanged.
148934 **
148935 ** If the "data" parameter to this function is NULL, then the
148936 ** element corresponding to "key" is removed from the hash table.
148937 */
148938 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
148939  Fts3Hash *pH, /* The hash table to insert into */
148940  const void *pKey, /* The key */
148941  int nKey, /* Number of bytes in the key */
148942  void *data /* The data */
148943 ){
148944  int hraw; /* Raw hash value of the key */
148945  int h; /* the hash of the key modulo hash table size */
148946  Fts3HashElem *elem; /* Used to loop thru the element list */
148947  Fts3HashElem *new_elem; /* New element added to the pH */
148948  int (*xHash)(const void*,int); /* The hash function */
148949 
148950  assert( pH!=0 );
148951  xHash = ftsHashFunction(pH->keyClass);
148952  assert( xHash!=0 );
148953  hraw = (*xHash)(pKey, nKey);
148954  assert( (pH->htsize & (pH->htsize-1))==0 );
148955  h = hraw & (pH->htsize-1);
148956  elem = fts3FindElementByHash(pH,pKey,nKey,h);
148957  if( elem ){
148958  void *old_data = elem->data;
148959  if( data==0 ){
148960  fts3RemoveElementByHash(pH,elem,h);
148961  }else{
148962  elem->data = data;
148963  }
148964  return old_data;
148965  }
148966  if( data==0 ) return 0;
148967  if( (pH->htsize==0 && fts3Rehash(pH,8))
148968  || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
148969  ){
148970  pH->count = 0;
148971  return data;
148972  }
148973  assert( pH->htsize>0 );
148974  new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
148975  if( new_elem==0 ) return data;
148976  if( pH->copyKey && pKey!=0 ){
148977  new_elem->pKey = fts3HashMalloc( nKey );
148978  if( new_elem->pKey==0 ){
148979  fts3HashFree(new_elem);
148980  return data;
148981  }
148982  memcpy((void*)new_elem->pKey, pKey, nKey);
148983  }else{
148984  new_elem->pKey = (void*)pKey;
148985  }
148986  new_elem->nKey = nKey;
148987  pH->count++;
148988  assert( pH->htsize>0 );
148989  assert( (pH->htsize & (pH->htsize-1))==0 );
148990  h = hraw & (pH->htsize-1);
148991  fts3HashInsertElement(pH, &pH->ht[h], new_elem);
148992  new_elem->data = data;
148993  return 0;
148994 }
148995 
148996 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
148997 
148998 /************** End of fts3_hash.c *******************************************/
148999 /************** Begin file fts3_porter.c *************************************/
149000 /*
149001 ** 2006 September 30
149002 **
149003 ** The author disclaims copyright to this source code. In place of
149004 ** a legal notice, here is a blessing:
149005 **
149006 ** May you do good and not evil.
149007 ** May you find forgiveness for yourself and forgive others.
149008 ** May you share freely, never taking more than you give.
149009 **
149010 *************************************************************************
149011 ** Implementation of the full-text-search tokenizer that implements
149012 ** a Porter stemmer.
149013 */
149014 
149015 /*
149016 ** The code in this file is only compiled if:
149017 **
149018 ** * The FTS3 module is being built as an extension
149019 ** (in which case SQLITE_CORE is not defined), or
149020 **
149021 ** * The FTS3 module is being built into the core of
149022 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149023 */
149024 /* #include "fts3Int.h" */
149025 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149026 
149027 /* #include <assert.h> */
149028 /* #include <stdlib.h> */
149029 /* #include <stdio.h> */
149030 /* #include <string.h> */
149031 
149032 /* #include "fts3_tokenizer.h" */
149033 
149034 /*
149035 ** Class derived from sqlite3_tokenizer
149036 */
149037 typedef struct porter_tokenizer {
149038  sqlite3_tokenizer base; /* Base class */
149039 } porter_tokenizer;
149040 
149041 /*
149042 ** Class derived from sqlite3_tokenizer_cursor
149043 */
149044 typedef struct porter_tokenizer_cursor {
149045  sqlite3_tokenizer_cursor base;
149046  const char *zInput; /* input we are tokenizing */
149047  int nInput; /* size of the input */
149048  int iOffset; /* current position in zInput */
149049  int iToken; /* index of next token to be returned */
149050  char *zToken; /* storage for current token */
149051  int nAllocated; /* space allocated to zToken buffer */
149052 } porter_tokenizer_cursor;
149053 
149054 
149055 /*
149056 ** Create a new tokenizer instance.
149057 */
149058 static int porterCreate(
149059  int argc, const char * const *argv,
149060  sqlite3_tokenizer **ppTokenizer
149061 ){
149062  porter_tokenizer *t;
149063 
149064  UNUSED_PARAMETER(argc);
149065  UNUSED_PARAMETER(argv);
149066 
149067  t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
149068  if( t==NULL ) return SQLITE_NOMEM;
149069  memset(t, 0, sizeof(*t));
149070  *ppTokenizer = &t->base;
149071  return SQLITE_OK;
149072 }
149073 
149074 /*
149075 ** Destroy a tokenizer
149076 */
149077 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
149078  sqlite3_free(pTokenizer);
149079  return SQLITE_OK;
149080 }
149081 
149082 /*
149083 ** Prepare to begin tokenizing a particular string. The input
149084 ** string to be tokenized is zInput[0..nInput-1]. A cursor
149085 ** used to incrementally tokenize this string is returned in
149086 ** *ppCursor.
149087 */
149088 static int porterOpen(
149089  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
149090  const char *zInput, int nInput, /* String to be tokenized */
149091  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
149092 ){
149093  porter_tokenizer_cursor *c;
149094 
149095  UNUSED_PARAMETER(pTokenizer);
149096 
149097  c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
149098  if( c==NULL ) return SQLITE_NOMEM;
149099 
149100  c->zInput = zInput;
149101  if( zInput==0 ){
149102  c->nInput = 0;
149103  }else if( nInput<0 ){
149104  c->nInput = (int)strlen(zInput);
149105  }else{
149106  c->nInput = nInput;
149107  }
149108  c->iOffset = 0; /* start tokenizing at the beginning */
149109  c->iToken = 0;
149110  c->zToken = NULL; /* no space allocated, yet. */
149111  c->nAllocated = 0;
149112 
149113  *ppCursor = &c->base;
149114  return SQLITE_OK;
149115 }
149116 
149117 /*
149118 ** Close a tokenization cursor previously opened by a call to
149119 ** porterOpen() above.
149120 */
149121 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
149122  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
149123  sqlite3_free(c->zToken);
149124  sqlite3_free(c);
149125  return SQLITE_OK;
149126 }
149127 /*
149128 ** Vowel or consonant
149129 */
149130 static const char cType[] = {
149131  0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
149132  1, 1, 1, 2, 1
149133 };
149134 
149135 /*
149136 ** isConsonant() and isVowel() determine if their first character in
149137 ** the string they point to is a consonant or a vowel, according
149138 ** to Porter ruls.
149139 **
149140 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
149141 ** 'Y' is a consonant unless it follows another consonant,
149142 ** in which case it is a vowel.
149143 **
149144 ** In these routine, the letters are in reverse order. So the 'y' rule
149145 ** is that 'y' is a consonant unless it is followed by another
149146 ** consonent.
149147 */
149148 static int isVowel(const char*);
149149 static int isConsonant(const char *z){
149150  int j;
149151  char x = *z;
149152  if( x==0 ) return 0;
149153  assert( x>='a' && x<='z' );
149154  j = cType[x-'a'];
149155  if( j<2 ) return j;
149156  return z[1]==0 || isVowel(z + 1);
149157 }
149158 static int isVowel(const char *z){
149159  int j;
149160  char x = *z;
149161  if( x==0 ) return 0;
149162  assert( x>='a' && x<='z' );
149163  j = cType[x-'a'];
149164  if( j<2 ) return 1-j;
149165  return isConsonant(z + 1);
149166 }
149167 
149168 /*
149169 ** Let any sequence of one or more vowels be represented by V and let
149170 ** C be sequence of one or more consonants. Then every word can be
149171 ** represented as:
149172 **
149173 ** [C] (VC){m} [V]
149174 **
149175 ** In prose: A word is an optional consonant followed by zero or
149176 ** vowel-consonant pairs followed by an optional vowel. "m" is the
149177 ** number of vowel consonant pairs. This routine computes the value
149178 ** of m for the first i bytes of a word.
149179 **
149180 ** Return true if the m-value for z is 1 or more. In other words,
149181 ** return true if z contains at least one vowel that is followed
149182 ** by a consonant.
149183 **
149184 ** In this routine z[] is in reverse order. So we are really looking
149185 ** for an instance of a consonant followed by a vowel.
149186 */
149187 static int m_gt_0(const char *z){
149188  while( isVowel(z) ){ z++; }
149189  if( *z==0 ) return 0;
149190  while( isConsonant(z) ){ z++; }
149191  return *z!=0;
149192 }
149193 
149194 /* Like mgt0 above except we are looking for a value of m which is
149195 ** exactly 1
149196 */
149197 static int m_eq_1(const char *z){
149198  while( isVowel(z) ){ z++; }
149199  if( *z==0 ) return 0;
149200  while( isConsonant(z) ){ z++; }
149201  if( *z==0 ) return 0;
149202  while( isVowel(z) ){ z++; }
149203  if( *z==0 ) return 1;
149204  while( isConsonant(z) ){ z++; }
149205  return *z==0;
149206 }
149207 
149208 /* Like mgt0 above except we are looking for a value of m>1 instead
149209 ** or m>0
149210 */
149211 static int m_gt_1(const char *z){
149212  while( isVowel(z) ){ z++; }
149213  if( *z==0 ) return 0;
149214  while( isConsonant(z) ){ z++; }
149215  if( *z==0 ) return 0;
149216  while( isVowel(z) ){ z++; }
149217  if( *z==0 ) return 0;
149218  while( isConsonant(z) ){ z++; }
149219  return *z!=0;
149220 }
149221 
149222 /*
149223 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
149224 */
149225 static int hasVowel(const char *z){
149226  while( isConsonant(z) ){ z++; }
149227  return *z!=0;
149228 }
149229 
149230 /*
149231 ** Return TRUE if the word ends in a double consonant.
149232 **
149233 ** The text is reversed here. So we are really looking at
149234 ** the first two characters of z[].
149235 */
149236 static int doubleConsonant(const char *z){
149237  return isConsonant(z) && z[0]==z[1];
149238 }
149239 
149240 /*
149241 ** Return TRUE if the word ends with three letters which
149242 ** are consonant-vowel-consonent and where the final consonant
149243 ** is not 'w', 'x', or 'y'.
149244 **
149245 ** The word is reversed here. So we are really checking the
149246 ** first three letters and the first one cannot be in [wxy].
149247 */
149248 static int star_oh(const char *z){
149249  return
149250  isConsonant(z) &&
149251  z[0]!='w' && z[0]!='x' && z[0]!='y' &&
149252  isVowel(z+1) &&
149253  isConsonant(z+2);
149254 }
149255 
149256 /*
149257 ** If the word ends with zFrom and xCond() is true for the stem
149258 ** of the word that preceeds the zFrom ending, then change the
149259 ** ending to zTo.
149260 **
149261 ** The input word *pz and zFrom are both in reverse order. zTo
149262 ** is in normal order.
149263 **
149264 ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
149265 ** match. Not that TRUE is returned even if xCond() fails and
149266 ** no substitution occurs.
149267 */
149268 static int stem(
149269  char **pz, /* The word being stemmed (Reversed) */
149270  const char *zFrom, /* If the ending matches this... (Reversed) */
149271  const char *zTo, /* ... change the ending to this (not reversed) */
149272  int (*xCond)(const char*) /* Condition that must be true */
149273 ){
149274  char *z = *pz;
149275  while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
149276  if( *zFrom!=0 ) return 0;
149277  if( xCond && !xCond(z) ) return 1;
149278  while( *zTo ){
149279  *(--z) = *(zTo++);
149280  }
149281  *pz = z;
149282  return 1;
149283 }
149284 
149285 /*
149286 ** This is the fallback stemmer used when the porter stemmer is
149287 ** inappropriate. The input word is copied into the output with
149288 ** US-ASCII case folding. If the input word is too long (more
149289 ** than 20 bytes if it contains no digits or more than 6 bytes if
149290 ** it contains digits) then word is truncated to 20 or 6 bytes
149291 ** by taking 10 or 3 bytes from the beginning and end.
149292 */
149293 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
149294  int i, mx, j;
149295  int hasDigit = 0;
149296  for(i=0; i<nIn; i++){
149297  char c = zIn[i];
149298  if( c>='A' && c<='Z' ){
149299  zOut[i] = c - 'A' + 'a';
149300  }else{
149301  if( c>='0' && c<='9' ) hasDigit = 1;
149302  zOut[i] = c;
149303  }
149304  }
149305  mx = hasDigit ? 3 : 10;
149306  if( nIn>mx*2 ){
149307  for(j=mx, i=nIn-mx; i<nIn; i++, j++){
149308  zOut[j] = zOut[i];
149309  }
149310  i = j;
149311  }
149312  zOut[i] = 0;
149313  *pnOut = i;
149314 }
149315 
149316 
149317 /*
149318 ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
149319 ** zOut is at least big enough to hold nIn bytes. Write the actual
149320 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
149321 **
149322 ** Any upper-case characters in the US-ASCII character set ([A-Z])
149323 ** are converted to lower case. Upper-case UTF characters are
149324 ** unchanged.
149325 **
149326 ** Words that are longer than about 20 bytes are stemmed by retaining
149327 ** a few bytes from the beginning and the end of the word. If the
149328 ** word contains digits, 3 bytes are taken from the beginning and
149329 ** 3 bytes from the end. For long words without digits, 10 bytes
149330 ** are taken from each end. US-ASCII case folding still applies.
149331 **
149332 ** If the input word contains not digits but does characters not
149333 ** in [a-zA-Z] then no stemming is attempted and this routine just
149334 ** copies the input into the input into the output with US-ASCII
149335 ** case folding.
149336 **
149337 ** Stemming never increases the length of the word. So there is
149338 ** no chance of overflowing the zOut buffer.
149339 */
149340 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
149341  int i, j;
149342  char zReverse[28];
149343  char *z, *z2;
149344  if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
149345  /* The word is too big or too small for the porter stemmer.
149346  ** Fallback to the copy stemmer */
149347  copy_stemmer(zIn, nIn, zOut, pnOut);
149348  return;
149349  }
149350  for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
149351  char c = zIn[i];
149352  if( c>='A' && c<='Z' ){
149353  zReverse[j] = c + 'a' - 'A';
149354  }else if( c>='a' && c<='z' ){
149355  zReverse[j] = c;
149356  }else{
149357  /* The use of a character not in [a-zA-Z] means that we fallback
149358  ** to the copy stemmer */
149359  copy_stemmer(zIn, nIn, zOut, pnOut);
149360  return;
149361  }
149362  }
149363  memset(&zReverse[sizeof(zReverse)-5], 0, 5);
149364  z = &zReverse[j+1];
149365 
149366 
149367  /* Step 1a */
149368  if( z[0]=='s' ){
149369  if(
149370  !stem(&z, "sess", "ss", 0) &&
149371  !stem(&z, "sei", "i", 0) &&
149372  !stem(&z, "ss", "ss", 0)
149373  ){
149374  z++;
149375  }
149376  }
149377 
149378  /* Step 1b */
149379  z2 = z;
149380  if( stem(&z, "dee", "ee", m_gt_0) ){
149381  /* Do nothing. The work was all in the test */
149382  }else if(
149383  (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
149384  && z!=z2
149385  ){
149386  if( stem(&z, "ta", "ate", 0) ||
149387  stem(&z, "lb", "ble", 0) ||
149388  stem(&z, "zi", "ize", 0) ){
149389  /* Do nothing. The work was all in the test */
149390  }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
149391  z++;
149392  }else if( m_eq_1(z) && star_oh(z) ){
149393  *(--z) = 'e';
149394  }
149395  }
149396 
149397  /* Step 1c */
149398  if( z[0]=='y' && hasVowel(z+1) ){
149399  z[0] = 'i';
149400  }
149401 
149402  /* Step 2 */
149403  switch( z[1] ){
149404  case 'a':
149405  if( !stem(&z, "lanoita", "ate", m_gt_0) ){
149406  stem(&z, "lanoit", "tion", m_gt_0);
149407  }
149408  break;
149409  case 'c':
149410  if( !stem(&z, "icne", "ence", m_gt_0) ){
149411  stem(&z, "icna", "ance", m_gt_0);
149412  }
149413  break;
149414  case 'e':
149415  stem(&z, "rezi", "ize", m_gt_0);
149416  break;
149417  case 'g':
149418  stem(&z, "igol", "log", m_gt_0);
149419  break;
149420  case 'l':
149421  if( !stem(&z, "ilb", "ble", m_gt_0)
149422  && !stem(&z, "illa", "al", m_gt_0)
149423  && !stem(&z, "iltne", "ent", m_gt_0)
149424  && !stem(&z, "ile", "e", m_gt_0)
149425  ){
149426  stem(&z, "ilsuo", "ous", m_gt_0);
149427  }
149428  break;
149429  case 'o':
149430  if( !stem(&z, "noitazi", "ize", m_gt_0)
149431  && !stem(&z, "noita", "ate", m_gt_0)
149432  ){
149433  stem(&z, "rota", "ate", m_gt_0);
149434  }
149435  break;
149436  case 's':
149437  if( !stem(&z, "msila", "al", m_gt_0)
149438  && !stem(&z, "ssenevi", "ive", m_gt_0)
149439  && !stem(&z, "ssenluf", "ful", m_gt_0)
149440  ){
149441  stem(&z, "ssensuo", "ous", m_gt_0);
149442  }
149443  break;
149444  case 't':
149445  if( !stem(&z, "itila", "al", m_gt_0)
149446  && !stem(&z, "itivi", "ive", m_gt_0)
149447  ){
149448  stem(&z, "itilib", "ble", m_gt_0);
149449  }
149450  break;
149451  }
149452 
149453  /* Step 3 */
149454  switch( z[0] ){
149455  case 'e':
149456  if( !stem(&z, "etaci", "ic", m_gt_0)
149457  && !stem(&z, "evita", "", m_gt_0)
149458  ){
149459  stem(&z, "ezila", "al", m_gt_0);
149460  }
149461  break;
149462  case 'i':
149463  stem(&z, "itici", "ic", m_gt_0);
149464  break;
149465  case 'l':
149466  if( !stem(&z, "laci", "ic", m_gt_0) ){
149467  stem(&z, "luf", "", m_gt_0);
149468  }
149469  break;
149470  case 's':
149471  stem(&z, "ssen", "", m_gt_0);
149472  break;
149473  }
149474 
149475  /* Step 4 */
149476  switch( z[1] ){
149477  case 'a':
149478  if( z[0]=='l' && m_gt_1(z+2) ){
149479  z += 2;
149480  }
149481  break;
149482  case 'c':
149483  if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
149484  z += 4;
149485  }
149486  break;
149487  case 'e':
149488  if( z[0]=='r' && m_gt_1(z+2) ){
149489  z += 2;
149490  }
149491  break;
149492  case 'i':
149493  if( z[0]=='c' && m_gt_1(z+2) ){
149494  z += 2;
149495  }
149496  break;
149497  case 'l':
149498  if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
149499  z += 4;
149500  }
149501  break;
149502  case 'n':
149503  if( z[0]=='t' ){
149504  if( z[2]=='a' ){
149505  if( m_gt_1(z+3) ){
149506  z += 3;
149507  }
149508  }else if( z[2]=='e' ){
149509  if( !stem(&z, "tneme", "", m_gt_1)
149510  && !stem(&z, "tnem", "", m_gt_1)
149511  ){
149512  stem(&z, "tne", "", m_gt_1);
149513  }
149514  }
149515  }
149516  break;
149517  case 'o':
149518  if( z[0]=='u' ){
149519  if( m_gt_1(z+2) ){
149520  z += 2;
149521  }
149522  }else if( z[3]=='s' || z[3]=='t' ){
149523  stem(&z, "noi", "", m_gt_1);
149524  }
149525  break;
149526  case 's':
149527  if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
149528  z += 3;
149529  }
149530  break;
149531  case 't':
149532  if( !stem(&z, "eta", "", m_gt_1) ){
149533  stem(&z, "iti", "", m_gt_1);
149534  }
149535  break;
149536  case 'u':
149537  if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
149538  z += 3;
149539  }
149540  break;
149541  case 'v':
149542  case 'z':
149543  if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
149544  z += 3;
149545  }
149546  break;
149547  }
149548 
149549  /* Step 5a */
149550  if( z[0]=='e' ){
149551  if( m_gt_1(z+1) ){
149552  z++;
149553  }else if( m_eq_1(z+1) && !star_oh(z+1) ){
149554  z++;
149555  }
149556  }
149557 
149558  /* Step 5b */
149559  if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
149560  z++;
149561  }
149562 
149563  /* z[] is now the stemmed word in reverse order. Flip it back
149564  ** around into forward order and return.
149565  */
149566  *pnOut = i = (int)strlen(z);
149567  zOut[i] = 0;
149568  while( *z ){
149569  zOut[--i] = *(z++);
149570  }
149571 }
149572 
149573 /*
149574 ** Characters that can be part of a token. We assume any character
149575 ** whose value is greater than 0x80 (any UTF character) can be
149576 ** part of a token. In other words, delimiters all must have
149577 ** values of 0x7f or lower.
149578 */
149579 static const char porterIdChar[] = {
149580 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
149581  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
149582  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
149583  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
149584  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
149585  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
149586 };
149587 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
149588 
149589 /*
149590 ** Extract the next token from a tokenization cursor. The cursor must
149591 ** have been opened by a prior call to porterOpen().
149592 */
149593 static int porterNext(
149594  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
149595  const char **pzToken, /* OUT: *pzToken is the token text */
149596  int *pnBytes, /* OUT: Number of bytes in token */
149597  int *piStartOffset, /* OUT: Starting offset of token */
149598  int *piEndOffset, /* OUT: Ending offset of token */
149599  int *piPosition /* OUT: Position integer of token */
149600 ){
149601  porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
149602  const char *z = c->zInput;
149603 
149604  while( c->iOffset<c->nInput ){
149605  int iStartOffset, ch;
149606 
149607  /* Scan past delimiter characters */
149608  while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
149609  c->iOffset++;
149610  }
149611 
149612  /* Count non-delimiter characters. */
149613  iStartOffset = c->iOffset;
149614  while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
149615  c->iOffset++;
149616  }
149617 
149618  if( c->iOffset>iStartOffset ){
149619  int n = c->iOffset-iStartOffset;
149620  if( n>c->nAllocated ){
149621  char *pNew;
149622  c->nAllocated = n+20;
149623  pNew = sqlite3_realloc(c->zToken, c->nAllocated);
149624  if( !pNew ) return SQLITE_NOMEM;
149625  c->zToken = pNew;
149626  }
149627  porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
149628  *pzToken = c->zToken;
149629  *piStartOffset = iStartOffset;
149630  *piEndOffset = c->iOffset;
149631  *piPosition = c->iToken++;
149632  return SQLITE_OK;
149633  }
149634  }
149635  return SQLITE_DONE;
149636 }
149637 
149638 /*
149639 ** The set of routines that implement the porter-stemmer tokenizer
149640 */
149641 static const sqlite3_tokenizer_module porterTokenizerModule = {
149642  0,
149643  porterCreate,
149644  porterDestroy,
149645  porterOpen,
149646  porterClose,
149647  porterNext,
149648  0
149649 };
149650 
149651 /*
149652 ** Allocate a new porter tokenizer. Return a pointer to the new
149653 ** tokenizer in *ppModule
149654 */
149655 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
149656  sqlite3_tokenizer_module const**ppModule
149657 ){
149658  *ppModule = &porterTokenizerModule;
149659 }
149660 
149661 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
149662 
149663 /************** End of fts3_porter.c *****************************************/
149664 /************** Begin file fts3_tokenizer.c **********************************/
149665 /*
149666 ** 2007 June 22
149667 **
149668 ** The author disclaims copyright to this source code. In place of
149669 ** a legal notice, here is a blessing:
149670 **
149671 ** May you do good and not evil.
149672 ** May you find forgiveness for yourself and forgive others.
149673 ** May you share freely, never taking more than you give.
149674 **
149675 ******************************************************************************
149676 **
149677 ** This is part of an SQLite module implementing full-text search.
149678 ** This particular file implements the generic tokenizer interface.
149679 */
149680 
149681 /*
149682 ** The code in this file is only compiled if:
149683 **
149684 ** * The FTS3 module is being built as an extension
149685 ** (in which case SQLITE_CORE is not defined), or
149686 **
149687 ** * The FTS3 module is being built into the core of
149688 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
149689 */
149690 /* #include "fts3Int.h" */
149691 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149692 
149693 /* #include <assert.h> */
149694 /* #include <string.h> */
149695 
149696 /*
149697 ** Return true if the two-argument version of fts3_tokenizer()
149698 ** has been activated via a prior call to sqlite3_db_config(db,
149699 ** SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER, 1, 0);
149700 */
149701 static int fts3TokenizerEnabled(sqlite3_context *context){
149702  sqlite3 *db = sqlite3_context_db_handle(context);
149703  int isEnabled = 0;
149705  return isEnabled;
149706 }
149707 
149708 /*
149709 ** Implementation of the SQL scalar function for accessing the underlying
149710 ** hash table. This function may be called as follows:
149711 **
149712 ** SELECT <function-name>(<key-name>);
149713 ** SELECT <function-name>(<key-name>, <pointer>);
149714 **
149715 ** where <function-name> is the name passed as the second argument
149716 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
149717 **
149718 ** If the <pointer> argument is specified, it must be a blob value
149719 ** containing a pointer to be stored as the hash data corresponding
149720 ** to the string <key-name>. If <pointer> is not specified, then
149721 ** the string <key-name> must already exist in the has table. Otherwise,
149722 ** an error is returned.
149723 **
149724 ** Whether or not the <pointer> argument is specified, the value returned
149725 ** is a blob containing the pointer stored as the hash data corresponding
149726 ** to string <key-name> (after the hash-table is updated, if applicable).
149727 */
149728 static void fts3TokenizerFunc(
149729  sqlite3_context *context,
149730  int argc,
149731  sqlite3_value **argv
149732 ){
149733  Fts3Hash *pHash;
149734  void *pPtr = 0;
149735  const unsigned char *zName;
149736  int nName;
149737 
149738  assert( argc==1 || argc==2 );
149739 
149740  pHash = (Fts3Hash *)sqlite3_user_data(context);
149741 
149742  zName = sqlite3_value_text(argv[0]);
149743  nName = sqlite3_value_bytes(argv[0])+1;
149744 
149745  if( argc==2 ){
149746  if( fts3TokenizerEnabled(context) ){
149747  void *pOld;
149748  int n = sqlite3_value_bytes(argv[1]);
149749  if( zName==0 || n!=sizeof(pPtr) ){
149750  sqlite3_result_error(context, "argument type mismatch", -1);
149751  return;
149752  }
149753  pPtr = *(void **)sqlite3_value_blob(argv[1]);
149754  pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
149755  if( pOld==pPtr ){
149756  sqlite3_result_error(context, "out of memory", -1);
149757  }
149758  }else{
149759  sqlite3_result_error(context, "fts3tokenize disabled", -1);
149760  return;
149761  }
149762  }else{
149763  if( zName ){
149764  pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
149765  }
149766  if( !pPtr ){
149767  char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
149768  sqlite3_result_error(context, zErr, -1);
149769  sqlite3_free(zErr);
149770  return;
149771  }
149772  }
149773  sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
149774 }
149775 
149776 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
149777  static const char isFtsIdChar[] = {
149778  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
149779  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
149780  0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
149781  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
149782  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
149783  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
149784  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
149785  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
149786  };
149787  return (c&0x80 || isFtsIdChar[(int)(c)]);
149788 }
149789 
149790 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
149791  const char *z1;
149792  const char *z2 = 0;
149793 
149794  /* Find the start of the next token. */
149795  z1 = zStr;
149796  while( z2==0 ){
149797  char c = *z1;
149798  switch( c ){
149799  case '\0': return 0; /* No more tokens here */
149800  case '\'':
149801  case '"':
149802  case '`': {
149803  z2 = z1;
149804  while( *++z2 && (*z2!=c || *++z2==c) );
149805  break;
149806  }
149807  case '[':
149808  z2 = &z1[1];
149809  while( *z2 && z2[0]!=']' ) z2++;
149810  if( *z2 ) z2++;
149811  break;
149812 
149813  default:
149814  if( sqlite3Fts3IsIdChar(*z1) ){
149815  z2 = &z1[1];
149816  while( sqlite3Fts3IsIdChar(*z2) ) z2++;
149817  }else{
149818  z1++;
149819  }
149820  }
149821  }
149822 
149823  *pn = (int)(z2-z1);
149824  return z1;
149825 }
149826 
149827 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
149828  Fts3Hash *pHash, /* Tokenizer hash table */
149829  const char *zArg, /* Tokenizer name */
149830  sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
149831  char **pzErr /* OUT: Set to malloced error message */
149832 ){
149833  int rc;
149834  char *z = (char *)zArg;
149835  int n = 0;
149836  char *zCopy;
149837  char *zEnd; /* Pointer to nul-term of zCopy */
149838  sqlite3_tokenizer_module *m;
149839 
149840  zCopy = sqlite3_mprintf("%s", zArg);
149841  if( !zCopy ) return SQLITE_NOMEM;
149842  zEnd = &zCopy[strlen(zCopy)];
149843 
149844  z = (char *)sqlite3Fts3NextToken(zCopy, &n);
149845  if( z==0 ){
149846  assert( n==0 );
149847  z = zCopy;
149848  }
149849  z[n] = '\0';
149850  sqlite3Fts3Dequote(z);
149851 
149852  m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
149853  if( !m ){
149854  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", z);
149855  rc = SQLITE_ERROR;
149856  }else{
149857  char const **aArg = 0;
149858  int iArg = 0;
149859  z = &z[n+1];
149860  while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
149861  int nNew = sizeof(char *)*(iArg+1);
149862  char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
149863  if( !aNew ){
149864  sqlite3_free(zCopy);
149865  sqlite3_free((void *)aArg);
149866  return SQLITE_NOMEM;
149867  }
149868  aArg = aNew;
149869  aArg[iArg++] = z;
149870  z[n] = '\0';
149871  sqlite3Fts3Dequote(z);
149872  z = &z[n+1];
149873  }
149874  rc = m->xCreate(iArg, aArg, ppTok);
149875  assert( rc!=SQLITE_OK || *ppTok );
149876  if( rc!=SQLITE_OK ){
149877  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer");
149878  }else{
149879  (*ppTok)->pModule = m;
149880  }
149881  sqlite3_free((void *)aArg);
149882  }
149883 
149884  sqlite3_free(zCopy);
149885  return rc;
149886 }
149887 
149888 
149889 #ifdef SQLITE_TEST
149890 
149891 #include <tcl.h>
149892 /* #include <string.h> */
149893 
149894 /*
149895 ** Implementation of a special SQL scalar function for testing tokenizers
149896 ** designed to be used in concert with the Tcl testing framework. This
149897 ** function must be called with two or more arguments:
149898 **
149899 ** SELECT <function-name>(<key-name>, ..., <input-string>);
149900 **
149901 ** where <function-name> is the name passed as the second argument
149902 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
149903 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
149904 **
149905 ** The return value is a string that may be interpreted as a Tcl
149906 ** list. For each token in the <input-string>, three elements are
149907 ** added to the returned list. The first is the token position, the
149908 ** second is the token text (folded, stemmed, etc.) and the third is the
149909 ** substring of <input-string> associated with the token. For example,
149910 ** using the built-in "simple" tokenizer:
149911 **
149912 ** SELECT fts_tokenizer_test('simple', 'I don't see how');
149913 **
149914 ** will return the string:
149915 **
149916 ** "{0 i I 1 dont don't 2 see see 3 how how}"
149917 **
149918 */
149919 static void testFunc(
149920  sqlite3_context *context,
149921  int argc,
149922  sqlite3_value **argv
149923 ){
149924  Fts3Hash *pHash;
149925  sqlite3_tokenizer_module *p;
149926  sqlite3_tokenizer *pTokenizer = 0;
149927  sqlite3_tokenizer_cursor *pCsr = 0;
149928 
149929  const char *zErr = 0;
149930 
149931  const char *zName;
149932  int nName;
149933  const char *zInput;
149934  int nInput;
149935 
149936  const char *azArg[64];
149937 
149938  const char *zToken;
149939  int nToken = 0;
149940  int iStart = 0;
149941  int iEnd = 0;
149942  int iPos = 0;
149943  int i;
149944 
149945  Tcl_Obj *pRet;
149946 
149947  if( argc<2 ){
149948  sqlite3_result_error(context, "insufficient arguments", -1);
149949  return;
149950  }
149951 
149952  nName = sqlite3_value_bytes(argv[0]);
149953  zName = (const char *)sqlite3_value_text(argv[0]);
149954  nInput = sqlite3_value_bytes(argv[argc-1]);
149955  zInput = (const char *)sqlite3_value_text(argv[argc-1]);
149956 
149957  pHash = (Fts3Hash *)sqlite3_user_data(context);
149958  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
149959 
149960  if( !p ){
149961  char *zErr2 = sqlite3_mprintf("unknown tokenizer: %s", zName);
149962  sqlite3_result_error(context, zErr2, -1);
149963  sqlite3_free(zErr2);
149964  return;
149965  }
149966 
149967  pRet = Tcl_NewObj();
149968  Tcl_IncrRefCount(pRet);
149969 
149970  for(i=1; i<argc-1; i++){
149971  azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
149972  }
149973 
149974  if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
149975  zErr = "error in xCreate()";
149976  goto finish;
149977  }
149978  pTokenizer->pModule = p;
149979  if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
149980  zErr = "error in xOpen()";
149981  goto finish;
149982  }
149983 
149984  while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
149985  Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
149986  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
149987  zToken = &zInput[iStart];
149988  nToken = iEnd-iStart;
149989  Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
149990  }
149991 
149992  if( SQLITE_OK!=p->xClose(pCsr) ){
149993  zErr = "error in xClose()";
149994  goto finish;
149995  }
149996  if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
149997  zErr = "error in xDestroy()";
149998  goto finish;
149999  }
150000 
150001 finish:
150002  if( zErr ){
150003  sqlite3_result_error(context, zErr, -1);
150004  }else{
150005  sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
150006  }
150007  Tcl_DecrRefCount(pRet);
150008 }
150009 
150010 static
150011 int registerTokenizer(
150012  sqlite3 *db,
150013  char *zName,
150014  const sqlite3_tokenizer_module *p
150015 ){
150016  int rc;
150017  sqlite3_stmt *pStmt;
150018  const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
150019 
150020  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150021  if( rc!=SQLITE_OK ){
150022  return rc;
150023  }
150024 
150025  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150026  sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
150027  sqlite3_step(pStmt);
150028 
150029  return sqlite3_finalize(pStmt);
150030 }
150031 
150032 
150033 static
150034 int queryTokenizer(
150035  sqlite3 *db,
150036  char *zName,
150037  const sqlite3_tokenizer_module **pp
150038 ){
150039  int rc;
150040  sqlite3_stmt *pStmt;
150041  const char zSql[] = "SELECT fts3_tokenizer(?)";
150042 
150043  *pp = 0;
150044  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
150045  if( rc!=SQLITE_OK ){
150046  return rc;
150047  }
150048 
150049  sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
150050  if( SQLITE_ROW==sqlite3_step(pStmt) ){
150051  if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
150052  memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
150053  }
150054  }
150055 
150056  return sqlite3_finalize(pStmt);
150057 }
150058 
150059 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
150060 
150061 /*
150062 ** Implementation of the scalar function fts3_tokenizer_internal_test().
150063 ** This function is used for testing only, it is not included in the
150064 ** build unless SQLITE_TEST is defined.
150065 **
150066 ** The purpose of this is to test that the fts3_tokenizer() function
150067 ** can be used as designed by the C-code in the queryTokenizer and
150068 ** registerTokenizer() functions above. These two functions are repeated
150069 ** in the README.tokenizer file as an example, so it is important to
150070 ** test them.
150071 **
150072 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
150073 ** function with no arguments. An assert() will fail if a problem is
150074 ** detected. i.e.:
150075 **
150076 ** SELECT fts3_tokenizer_internal_test();
150077 **
150078 */
150079 static void intTestFunc(
150080  sqlite3_context *context,
150081  int argc,
150082  sqlite3_value **argv
150083 ){
150084  int rc;
150085  const sqlite3_tokenizer_module *p1;
150086  const sqlite3_tokenizer_module *p2;
150087  sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
150088 
150089  UNUSED_PARAMETER(argc);
150090  UNUSED_PARAMETER(argv);
150091 
150092  /* Test the query function */
150093  sqlite3Fts3SimpleTokenizerModule(&p1);
150094  rc = queryTokenizer(db, "simple", &p2);
150095  assert( rc==SQLITE_OK );
150096  assert( p1==p2 );
150097  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
150098  assert( rc==SQLITE_ERROR );
150099  assert( p2==0 );
150100  assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
150101 
150102  /* Test the storage function */
150103  if( fts3TokenizerEnabled(context) ){
150104  rc = registerTokenizer(db, "nosuchtokenizer", p1);
150105  assert( rc==SQLITE_OK );
150106  rc = queryTokenizer(db, "nosuchtokenizer", &p2);
150107  assert( rc==SQLITE_OK );
150108  assert( p2==p1 );
150109  }
150110 
150111  sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
150112 }
150113 
150114 #endif
150115 
150116 /*
150117 ** Set up SQL objects in database db used to access the contents of
150118 ** the hash table pointed to by argument pHash. The hash table must
150119 ** been initialized to use string keys, and to take a private copy
150120 ** of the key when a value is inserted. i.e. by a call similar to:
150121 **
150122 ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
150123 **
150124 ** This function adds a scalar function (see header comment above
150125 ** fts3TokenizerFunc() in this file for details) and, if ENABLE_TABLE is
150126 ** defined at compilation time, a temporary virtual table (see header
150127 ** comment above struct HashTableVtab) to the database schema. Both
150128 ** provide read/write access to the contents of *pHash.
150129 **
150130 ** The third argument to this function, zName, is used as the name
150131 ** of both the scalar and, if created, the virtual table.
150132 */
150133 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
150134  sqlite3 *db,
150135  Fts3Hash *pHash,
150136  const char *zName
150137 ){
150138  int rc = SQLITE_OK;
150139  void *p = (void *)pHash;
150140  const int any = SQLITE_ANY;
150141 
150142 #ifdef SQLITE_TEST
150143  char *zTest = 0;
150144  char *zTest2 = 0;
150145  void *pdb = (void *)db;
150146  zTest = sqlite3_mprintf("%s_test", zName);
150147  zTest2 = sqlite3_mprintf("%s_internal_test", zName);
150148  if( !zTest || !zTest2 ){
150149  rc = SQLITE_NOMEM;
150150  }
150151 #endif
150152 
150153  if( SQLITE_OK==rc ){
150154  rc = sqlite3_create_function(db, zName, 1, any, p, fts3TokenizerFunc, 0, 0);
150155  }
150156  if( SQLITE_OK==rc ){
150157  rc = sqlite3_create_function(db, zName, 2, any, p, fts3TokenizerFunc, 0, 0);
150158  }
150159 #ifdef SQLITE_TEST
150160  if( SQLITE_OK==rc ){
150161  rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
150162  }
150163  if( SQLITE_OK==rc ){
150164  rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
150165  }
150166 #endif
150167 
150168 #ifdef SQLITE_TEST
150169  sqlite3_free(zTest);
150170  sqlite3_free(zTest2);
150171 #endif
150172 
150173  return rc;
150174 }
150175 
150176 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150177 
150178 /************** End of fts3_tokenizer.c **************************************/
150179 /************** Begin file fts3_tokenizer1.c *********************************/
150180 /*
150181 ** 2006 Oct 10
150182 **
150183 ** The author disclaims copyright to this source code. In place of
150184 ** a legal notice, here is a blessing:
150185 **
150186 ** May you do good and not evil.
150187 ** May you find forgiveness for yourself and forgive others.
150188 ** May you share freely, never taking more than you give.
150189 **
150190 ******************************************************************************
150191 **
150192 ** Implementation of the "simple" full-text-search tokenizer.
150193 */
150194 
150195 /*
150196 ** The code in this file is only compiled if:
150197 **
150198 ** * The FTS3 module is being built as an extension
150199 ** (in which case SQLITE_CORE is not defined), or
150200 **
150201 ** * The FTS3 module is being built into the core of
150202 ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
150203 */
150204 /* #include "fts3Int.h" */
150205 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150206 
150207 /* #include <assert.h> */
150208 /* #include <stdlib.h> */
150209 /* #include <stdio.h> */
150210 /* #include <string.h> */
150211 
150212 /* #include "fts3_tokenizer.h" */
150213 
150214 typedef struct simple_tokenizer {
150215  sqlite3_tokenizer base;
150216  char delim[128]; /* flag ASCII delimiters */
150217 } simple_tokenizer;
150218 
150219 typedef struct simple_tokenizer_cursor {
150220  sqlite3_tokenizer_cursor base;
150221  const char *pInput; /* input we are tokenizing */
150222  int nBytes; /* size of the input */
150223  int iOffset; /* current position in pInput */
150224  int iToken; /* index of next token to be returned */
150225  char *pToken; /* storage for current token */
150226  int nTokenAllocated; /* space allocated to zToken buffer */
150227 } simple_tokenizer_cursor;
150228 
150229 
150230 static int simpleDelim(simple_tokenizer *t, unsigned char c){
150231  return c<0x80 && t->delim[c];
150232 }
150233 static int fts3_isalnum(int x){
150234  return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
150235 }
150236 
150237 /*
150238 ** Create a new tokenizer instance.
150239 */
150240 static int simpleCreate(
150241  int argc, const char * const *argv,
150242  sqlite3_tokenizer **ppTokenizer
150243 ){
150244  simple_tokenizer *t;
150245 
150246  t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
150247  if( t==NULL ) return SQLITE_NOMEM;
150248  memset(t, 0, sizeof(*t));
150249 
150250  /* TODO(shess) Delimiters need to remain the same from run to run,
150251  ** else we need to reindex. One solution would be a meta-table to
150252  ** track such information in the database, then we'd only want this
150253  ** information on the initial create.
150254  */
150255  if( argc>1 ){
150256  int i, n = (int)strlen(argv[1]);
150257  for(i=0; i<n; i++){
150258  unsigned char ch = argv[1][i];
150259  /* We explicitly don't support UTF-8 delimiters for now. */
150260  if( ch>=0x80 ){
150261  sqlite3_free(t);
150262  return SQLITE_ERROR;
150263  }
150264  t->delim[ch] = 1;
150265  }
150266  } else {
150267  /* Mark non-alphanumeric ASCII characters as delimiters */
150268  int i;
150269  for(i=1; i<0x80; i++){
150270  t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
150271  }
150272  }
150273 
150274  *ppTokenizer = &t->base;
150275  return SQLITE_OK;
150276 }
150277 
150278 /*
150279 ** Destroy a tokenizer
150280 */
150281 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
150282  sqlite3_free(pTokenizer);
150283  return SQLITE_OK;
150284 }
150285 
150286 /*
150287 ** Prepare to begin tokenizing a particular string. The input
150288 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
150289 ** used to incrementally tokenize this string is returned in
150290 ** *ppCursor.
150291 */
150292 static int simpleOpen(
150293  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
150294  const char *pInput, int nBytes, /* String to be tokenized */
150295  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
150296 ){
150297  simple_tokenizer_cursor *c;
150298 
150299  UNUSED_PARAMETER(pTokenizer);
150300 
150301  c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
150302  if( c==NULL ) return SQLITE_NOMEM;
150303 
150304  c->pInput = pInput;
150305  if( pInput==0 ){
150306  c->nBytes = 0;
150307  }else if( nBytes<0 ){
150308  c->nBytes = (int)strlen(pInput);
150309  }else{
150310  c->nBytes = nBytes;
150311  }
150312  c->iOffset = 0; /* start tokenizing at the beginning */
150313  c->iToken = 0;
150314  c->pToken = NULL; /* no space allocated, yet. */
150315  c->nTokenAllocated = 0;
150316 
150317  *ppCursor = &c->base;
150318  return SQLITE_OK;
150319 }
150320 
150321 /*
150322 ** Close a tokenization cursor previously opened by a call to
150323 ** simpleOpen() above.
150324 */
150325 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
150326  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
150327  sqlite3_free(c->pToken);
150328  sqlite3_free(c);
150329  return SQLITE_OK;
150330 }
150331 
150332 /*
150333 ** Extract the next token from a tokenization cursor. The cursor must
150334 ** have been opened by a prior call to simpleOpen().
150335 */
150336 static int simpleNext(
150337  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
150338  const char **ppToken, /* OUT: *ppToken is the token text */
150339  int *pnBytes, /* OUT: Number of bytes in token */
150340  int *piStartOffset, /* OUT: Starting offset of token */
150341  int *piEndOffset, /* OUT: Ending offset of token */
150342  int *piPosition /* OUT: Position integer of token */
150343 ){
150344  simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
150345  simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
150346  unsigned char *p = (unsigned char *)c->pInput;
150347 
150348  while( c->iOffset<c->nBytes ){
150349  int iStartOffset;
150350 
150351  /* Scan past delimiter characters */
150352  while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
150353  c->iOffset++;
150354  }
150355 
150356  /* Count non-delimiter characters. */
150357  iStartOffset = c->iOffset;
150358  while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
150359  c->iOffset++;
150360  }
150361 
150362  if( c->iOffset>iStartOffset ){
150363  int i, n = c->iOffset-iStartOffset;
150364  if( n>c->nTokenAllocated ){
150365  char *pNew;
150366  c->nTokenAllocated = n+20;
150367  pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
150368  if( !pNew ) return SQLITE_NOMEM;
150369  c->pToken = pNew;
150370  }
150371  for(i=0; i<n; i++){
150372  /* TODO(shess) This needs expansion to handle UTF-8
150373  ** case-insensitivity.
150374  */
150375  unsigned char ch = p[iStartOffset+i];
150376  c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
150377  }
150378  *ppToken = c->pToken;
150379  *pnBytes = n;
150380  *piStartOffset = iStartOffset;
150381  *piEndOffset = c->iOffset;
150382  *piPosition = c->iToken++;
150383 
150384  return SQLITE_OK;
150385  }
150386  }
150387  return SQLITE_DONE;
150388 }
150389 
150390 /*
150391 ** The set of routines that implement the simple tokenizer
150392 */
150393 static const sqlite3_tokenizer_module simpleTokenizerModule = {
150394  0,
150395  simpleCreate,
150396  simpleDestroy,
150397  simpleOpen,
150398  simpleClose,
150399  simpleNext,
150400  0,
150401 };
150402 
150403 /*
150404 ** Allocate a new simple tokenizer. Return a pointer to the new
150405 ** tokenizer in *ppModule
150406 */
150407 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
150408  sqlite3_tokenizer_module const**ppModule
150409 ){
150410  *ppModule = &simpleTokenizerModule;
150411 }
150412 
150413 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150414 
150415 /************** End of fts3_tokenizer1.c *************************************/
150416 /************** Begin file fts3_tokenize_vtab.c ******************************/
150417 /*
150418 ** 2013 Apr 22
150419 **
150420 ** The author disclaims copyright to this source code. In place of
150421 ** a legal notice, here is a blessing:
150422 **
150423 ** May you do good and not evil.
150424 ** May you find forgiveness for yourself and forgive others.
150425 ** May you share freely, never taking more than you give.
150426 **
150427 ******************************************************************************
150428 **
150429 ** This file contains code for the "fts3tokenize" virtual table module.
150430 ** An fts3tokenize virtual table is created as follows:
150431 **
150432 ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
150433 ** <tokenizer-name>, <arg-1>, ...
150434 ** );
150435 **
150436 ** The table created has the following schema:
150437 **
150438 ** CREATE TABLE <tbl>(input, token, start, end, position)
150439 **
150440 ** When queried, the query must include a WHERE clause of type:
150441 **
150442 ** input = <string>
150443 **
150444 ** The virtual table module tokenizes this <string>, using the FTS3
150445 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
150446 ** statement and returns one row for each token in the result. With
150447 ** fields set as follows:
150448 **
150449 ** input: Always set to a copy of <string>
150450 ** token: A token from the input.
150451 ** start: Byte offset of the token within the input <string>.
150452 ** end: Byte offset of the byte immediately following the end of the
150453 ** token within the input string.
150454 ** pos: Token offset of token within input.
150455 **
150456 */
150457 /* #include "fts3Int.h" */
150458 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150459 
150460 /* #include <string.h> */
150461 /* #include <assert.h> */
150462 
150463 typedef struct Fts3tokTable Fts3tokTable;
150464 typedef struct Fts3tokCursor Fts3tokCursor;
150465 
150466 /*
150467 ** Virtual table structure.
150468 */
150469 struct Fts3tokTable {
150470  sqlite3_vtab base; /* Base class used by SQLite core */
150471  const sqlite3_tokenizer_module *pMod;
150472  sqlite3_tokenizer *pTok;
150473 };
150474 
150475 /*
150476 ** Virtual table cursor structure.
150477 */
150478 struct Fts3tokCursor {
150479  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
150480  char *zInput; /* Input string */
150481  sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
150482  int iRowid; /* Current 'rowid' value */
150483  const char *zToken; /* Current 'token' value */
150484  int nToken; /* Size of zToken in bytes */
150485  int iStart; /* Current 'start' value */
150486  int iEnd; /* Current 'end' value */
150487  int iPos; /* Current 'pos' value */
150488 };
150489 
150490 /*
150491 ** Query FTS for the tokenizer implementation named zName.
150492 */
150493 static int fts3tokQueryTokenizer(
150494  Fts3Hash *pHash,
150495  const char *zName,
150496  const sqlite3_tokenizer_module **pp,
150497  char **pzErr
150498 ){
150499  sqlite3_tokenizer_module *p;
150500  int nName = (int)strlen(zName);
150501 
150502  p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
150503  if( !p ){
150504  sqlite3Fts3ErrMsg(pzErr, "unknown tokenizer: %s", zName);
150505  return SQLITE_ERROR;
150506  }
150507 
150508  *pp = p;
150509  return SQLITE_OK;
150510 }
150511 
150512 /*
150513 ** The second argument, argv[], is an array of pointers to nul-terminated
150514 ** strings. This function makes a copy of the array and strings into a
150515 ** single block of memory. It then dequotes any of the strings that appear
150516 ** to be quoted.
150517 **
150518 ** If successful, output parameter *pazDequote is set to point at the
150519 ** array of dequoted strings and SQLITE_OK is returned. The caller is
150520 ** responsible for eventually calling sqlite3_free() to free the array
150521 ** in this case. Or, if an error occurs, an SQLite error code is returned.
150522 ** The final value of *pazDequote is undefined in this case.
150523 */
150524 static int fts3tokDequoteArray(
150525  int argc, /* Number of elements in argv[] */
150526  const char * const *argv, /* Input array */
150527  char ***pazDequote /* Output array */
150528 ){
150529  int rc = SQLITE_OK; /* Return code */
150530  if( argc==0 ){
150531  *pazDequote = 0;
150532  }else{
150533  int i;
150534  int nByte = 0;
150535  char **azDequote;
150536 
150537  for(i=0; i<argc; i++){
150538  nByte += (int)(strlen(argv[i]) + 1);
150539  }
150540 
150541  *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
150542  if( azDequote==0 ){
150543  rc = SQLITE_NOMEM;
150544  }else{
150545  char *pSpace = (char *)&azDequote[argc];
150546  for(i=0; i<argc; i++){
150547  int n = (int)strlen(argv[i]);
150548  azDequote[i] = pSpace;
150549  memcpy(pSpace, argv[i], n+1);
150550  sqlite3Fts3Dequote(pSpace);
150551  pSpace += (n+1);
150552  }
150553  }
150554  }
150555 
150556  return rc;
150557 }
150558 
150559 /*
150560 ** Schema of the tokenizer table.
150561 */
150562 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
150563 
150564 /*
150565 ** This function does all the work for both the xConnect and xCreate methods.
150566 ** These tables have no persistent representation of their own, so xConnect
150567 ** and xCreate are identical operations.
150568 **
150569 ** argv[0]: module name
150570 ** argv[1]: database name
150571 ** argv[2]: table name
150572 ** argv[3]: first argument (tokenizer name)
150573 */
150574 static int fts3tokConnectMethod(
150575  sqlite3 *db, /* Database connection */
150576  void *pHash, /* Hash table of tokenizers */
150577  int argc, /* Number of elements in argv array */
150578  const char * const *argv, /* xCreate/xConnect argument array */
150579  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
150580  char **pzErr /* OUT: sqlite3_malloc'd error message */
150581 ){
150582  Fts3tokTable *pTab = 0;
150583  const sqlite3_tokenizer_module *pMod = 0;
150584  sqlite3_tokenizer *pTok = 0;
150585  int rc;
150586  char **azDequote = 0;
150587  int nDequote;
150588 
150589  rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
150590  if( rc!=SQLITE_OK ) return rc;
150591 
150592  nDequote = argc-3;
150593  rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
150594 
150595  if( rc==SQLITE_OK ){
150596  const char *zModule;
150597  if( nDequote<1 ){
150598  zModule = "simple";
150599  }else{
150600  zModule = azDequote[0];
150601  }
150602  rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
150603  }
150604 
150605  assert( (rc==SQLITE_OK)==(pMod!=0) );
150606  if( rc==SQLITE_OK ){
150607  const char * const *azArg = (const char * const *)&azDequote[1];
150608  rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
150609  }
150610 
150611  if( rc==SQLITE_OK ){
150612  pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
150613  if( pTab==0 ){
150614  rc = SQLITE_NOMEM;
150615  }
150616  }
150617 
150618  if( rc==SQLITE_OK ){
150619  memset(pTab, 0, sizeof(Fts3tokTable));
150620  pTab->pMod = pMod;
150621  pTab->pTok = pTok;
150622  *ppVtab = &pTab->base;
150623  }else{
150624  if( pTok ){
150625  pMod->xDestroy(pTok);
150626  }
150627  }
150628 
150629  sqlite3_free(azDequote);
150630  return rc;
150631 }
150632 
150633 /*
150634 ** This function does the work for both the xDisconnect and xDestroy methods.
150635 ** These tables have no persistent representation of their own, so xDisconnect
150636 ** and xDestroy are identical operations.
150637 */
150638 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
150639  Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
150640 
150641  pTab->pMod->xDestroy(pTab->pTok);
150642  sqlite3_free(pTab);
150643  return SQLITE_OK;
150644 }
150645 
150646 /*
150647 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
150648 */
150649 static int fts3tokBestIndexMethod(
150650  sqlite3_vtab *pVTab,
150651  sqlite3_index_info *pInfo
150652 ){
150653  int i;
150654  UNUSED_PARAMETER(pVTab);
150655 
150656  for(i=0; i<pInfo->nConstraint; i++){
150657  if( pInfo->aConstraint[i].usable
150658  && pInfo->aConstraint[i].iColumn==0
150659  && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
150660  ){
150661  pInfo->idxNum = 1;
150662  pInfo->aConstraintUsage[i].argvIndex = 1;
150663  pInfo->aConstraintUsage[i].omit = 1;
150664  pInfo->estimatedCost = 1;
150665  return SQLITE_OK;
150666  }
150667  }
150668 
150669  pInfo->idxNum = 0;
150670  assert( pInfo->estimatedCost>1000000.0 );
150671 
150672  return SQLITE_OK;
150673 }
150674 
150675 /*
150676 ** xOpen - Open a cursor.
150677 */
150678 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
150679  Fts3tokCursor *pCsr;
150680  UNUSED_PARAMETER(pVTab);
150681 
150682  pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
150683  if( pCsr==0 ){
150684  return SQLITE_NOMEM;
150685  }
150686  memset(pCsr, 0, sizeof(Fts3tokCursor));
150687 
150688  *ppCsr = (sqlite3_vtab_cursor *)pCsr;
150689  return SQLITE_OK;
150690 }
150691 
150692 /*
150693 ** Reset the tokenizer cursor passed as the only argument. As if it had
150694 ** just been returned by fts3tokOpenMethod().
150695 */
150696 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
150697  if( pCsr->pCsr ){
150698  Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
150699  pTab->pMod->xClose(pCsr->pCsr);
150700  pCsr->pCsr = 0;
150701  }
150702  sqlite3_free(pCsr->zInput);
150703  pCsr->zInput = 0;
150704  pCsr->zToken = 0;
150705  pCsr->nToken = 0;
150706  pCsr->iStart = 0;
150707  pCsr->iEnd = 0;
150708  pCsr->iPos = 0;
150709  pCsr->iRowid = 0;
150710 }
150711 
150712 /*
150713 ** xClose - Close a cursor.
150714 */
150715 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
150716  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150717 
150718  fts3tokResetCursor(pCsr);
150719  sqlite3_free(pCsr);
150720  return SQLITE_OK;
150721 }
150722 
150723 /*
150724 ** xNext - Advance the cursor to the next row, if any.
150725 */
150726 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
150727  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150728  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
150729  int rc; /* Return code */
150730 
150731  pCsr->iRowid++;
150732  rc = pTab->pMod->xNext(pCsr->pCsr,
150733  &pCsr->zToken, &pCsr->nToken,
150734  &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
150735  );
150736 
150737  if( rc!=SQLITE_OK ){
150738  fts3tokResetCursor(pCsr);
150739  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
150740  }
150741 
150742  return rc;
150743 }
150744 
150745 /*
150746 ** xFilter - Initialize a cursor to point at the start of its data.
150747 */
150748 static int fts3tokFilterMethod(
150749  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
150750  int idxNum, /* Strategy index */
150751  const char *idxStr, /* Unused */
150752  int nVal, /* Number of elements in apVal */
150753  sqlite3_value **apVal /* Arguments for the indexing scheme */
150754 ){
150755  int rc = SQLITE_ERROR;
150756  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150757  Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
150758  UNUSED_PARAMETER(idxStr);
150759  UNUSED_PARAMETER(nVal);
150760 
150761  fts3tokResetCursor(pCsr);
150762  if( idxNum==1 ){
150763  const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
150764  int nByte = sqlite3_value_bytes(apVal[0]);
150765  pCsr->zInput = sqlite3_malloc(nByte+1);
150766  if( pCsr->zInput==0 ){
150767  rc = SQLITE_NOMEM;
150768  }else{
150769  memcpy(pCsr->zInput, zByte, nByte);
150770  pCsr->zInput[nByte] = 0;
150771  rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
150772  if( rc==SQLITE_OK ){
150773  pCsr->pCsr->pTokenizer = pTab->pTok;
150774  }
150775  }
150776  }
150777 
150778  if( rc!=SQLITE_OK ) return rc;
150779  return fts3tokNextMethod(pCursor);
150780 }
150781 
150782 /*
150783 ** xEof - Return true if the cursor is at EOF, or false otherwise.
150784 */
150785 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
150786  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150787  return (pCsr->zToken==0);
150788 }
150789 
150790 /*
150791 ** xColumn - Return a column value.
150792 */
150793 static int fts3tokColumnMethod(
150794  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
150795  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
150796  int iCol /* Index of column to read value from */
150797 ){
150798  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150799 
150800  /* CREATE TABLE x(input, token, start, end, position) */
150801  switch( iCol ){
150802  case 0:
150803  sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
150804  break;
150805  case 1:
150806  sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
150807  break;
150808  case 2:
150809  sqlite3_result_int(pCtx, pCsr->iStart);
150810  break;
150811  case 3:
150812  sqlite3_result_int(pCtx, pCsr->iEnd);
150813  break;
150814  default:
150815  assert( iCol==4 );
150816  sqlite3_result_int(pCtx, pCsr->iPos);
150817  break;
150818  }
150819  return SQLITE_OK;
150820 }
150821 
150822 /*
150823 ** xRowid - Return the current rowid for the cursor.
150824 */
150825 static int fts3tokRowidMethod(
150826  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
150827  sqlite_int64 *pRowid /* OUT: Rowid value */
150828 ){
150829  Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
150830  *pRowid = (sqlite3_int64)pCsr->iRowid;
150831  return SQLITE_OK;
150832 }
150833 
150834 /*
150835 ** Register the fts3tok module with database connection db. Return SQLITE_OK
150836 ** if successful or an error code if sqlite3_create_module() fails.
150837 */
150838 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
150839  static const sqlite3_module fts3tok_module = {
150840  0, /* iVersion */
150841  fts3tokConnectMethod, /* xCreate */
150842  fts3tokConnectMethod, /* xConnect */
150843  fts3tokBestIndexMethod, /* xBestIndex */
150844  fts3tokDisconnectMethod, /* xDisconnect */
150845  fts3tokDisconnectMethod, /* xDestroy */
150846  fts3tokOpenMethod, /* xOpen */
150847  fts3tokCloseMethod, /* xClose */
150848  fts3tokFilterMethod, /* xFilter */
150849  fts3tokNextMethod, /* xNext */
150850  fts3tokEofMethod, /* xEof */
150851  fts3tokColumnMethod, /* xColumn */
150852  fts3tokRowidMethod, /* xRowid */
150853  0, /* xUpdate */
150854  0, /* xBegin */
150855  0, /* xSync */
150856  0, /* xCommit */
150857  0, /* xRollback */
150858  0, /* xFindFunction */
150859  0, /* xRename */
150860  0, /* xSavepoint */
150861  0, /* xRelease */
150862  0 /* xRollbackTo */
150863  };
150864  int rc; /* Return code */
150865 
150866  rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
150867  return rc;
150868 }
150869 
150870 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150871 
150872 /************** End of fts3_tokenize_vtab.c **********************************/
150873 /************** Begin file fts3_write.c **************************************/
150874 /*
150875 ** 2009 Oct 23
150876 **
150877 ** The author disclaims copyright to this source code. In place of
150878 ** a legal notice, here is a blessing:
150879 **
150880 ** May you do good and not evil.
150881 ** May you find forgiveness for yourself and forgive others.
150882 ** May you share freely, never taking more than you give.
150883 **
150884 ******************************************************************************
150885 **
150886 ** This file is part of the SQLite FTS3 extension module. Specifically,
150887 ** this file contains code to insert, update and delete rows from FTS3
150888 ** tables. It also contains code to merge FTS3 b-tree segments. Some
150889 ** of the sub-routines used to merge segments are also used by the query
150890 ** code in fts3.c.
150891 */
150892 
150893 /* #include "fts3Int.h" */
150894 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
150895 
150896 /* #include <string.h> */
150897 /* #include <assert.h> */
150898 /* #include <stdlib.h> */
150899 
150900 
150901 #define FTS_MAX_APPENDABLE_HEIGHT 16
150902 
150903 /*
150904 ** When full-text index nodes are loaded from disk, the buffer that they
150905 ** are loaded into has the following number of bytes of padding at the end
150906 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
150907 ** of 920 bytes is allocated for it.
150908 **
150909 ** This means that if we have a pointer into a buffer containing node data,
150910 ** it is always safe to read up to two varints from it without risking an
150911 ** overread, even if the node data is corrupted.
150912 */
150913 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
150914 
150915 /*
150916 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
150917 ** memory incrementally instead of all at once. This can be a big performance
150918 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
150919 ** method before retrieving all query results (as may happen, for example,
150920 ** if a query has a LIMIT clause).
150921 **
150922 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
150923 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
150924 ** The code is written so that the hard lower-limit for each of these values
150925 ** is 1. Clearly such small values would be inefficient, but can be useful
150926 ** for testing purposes.
150927 **
150928 ** If this module is built with SQLITE_TEST defined, these constants may
150929 ** be overridden at runtime for testing purposes. File fts3_test.c contains
150930 ** a Tcl interface to read and write the values.
150931 */
150932 #ifdef SQLITE_TEST
150933 int test_fts3_node_chunksize = (4*1024);
150934 int test_fts3_node_chunk_threshold = (4*1024)*4;
150935 # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
150936 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
150937 #else
150938 # define FTS3_NODE_CHUNKSIZE (4*1024)
150939 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
150940 #endif
150941 
150942 /*
150943 ** The two values that may be meaningfully bound to the :1 parameter in
150944 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
150945 */
150946 #define FTS_STAT_DOCTOTAL 0
150947 #define FTS_STAT_INCRMERGEHINT 1
150948 #define FTS_STAT_AUTOINCRMERGE 2
150949 
150950 /*
150951 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
150952 ** and incremental merge operation that takes place. This is used for
150953 ** debugging FTS only, it should not usually be turned on in production
150954 ** systems.
150955 */
150956 #ifdef FTS3_LOG_MERGES
150957 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
150958  sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
150959 }
150960 #else
150961 #define fts3LogMerge(x, y)
150962 #endif
150963 
150964 
150965 typedef struct PendingList PendingList;
150966 typedef struct SegmentNode SegmentNode;
150967 typedef struct SegmentWriter SegmentWriter;
150968 
150969 /*
150970 ** An instance of the following data structure is used to build doclists
150971 ** incrementally. See function fts3PendingListAppend() for details.
150972 */
150973 struct PendingList {
150974  int nData;
150975  char *aData;
150976  int nSpace;
150977  sqlite3_int64 iLastDocid;
150978  sqlite3_int64 iLastCol;
150979  sqlite3_int64 iLastPos;
150980 };
150981 
150982 
150983 /*
150984 ** Each cursor has a (possibly empty) linked list of the following objects.
150985 */
150986 struct Fts3DeferredToken {
150987  Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
150988  int iCol; /* Column token must occur in */
150989  Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
150990  PendingList *pList; /* Doclist is assembled here */
150991 };
150992 
150993 /*
150994 ** An instance of this structure is used to iterate through the terms on
150995 ** a contiguous set of segment b-tree leaf nodes. Although the details of
150996 ** this structure are only manipulated by code in this file, opaque handles
150997 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
150998 ** terms when querying the full-text index. See functions:
150999 **
151000 ** sqlite3Fts3SegReaderNew()
151001 ** sqlite3Fts3SegReaderFree()
151002 ** sqlite3Fts3SegReaderIterate()
151003 **
151004 ** Methods used to manipulate Fts3SegReader structures:
151005 **
151006 ** fts3SegReaderNext()
151007 ** fts3SegReaderFirstDocid()
151008 ** fts3SegReaderNextDocid()
151009 */
151010 struct Fts3SegReader {
151011  int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
151012  u8 bLookup; /* True for a lookup only */
151013  u8 rootOnly; /* True for a root-only reader */
151014 
151015  sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
151016  sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
151017  sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
151018  sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
151019 
151020  char *aNode; /* Pointer to node data (or NULL) */
151021  int nNode; /* Size of buffer at aNode (or 0) */
151022  int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
151023  sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
151024 
151025  Fts3HashElem **ppNextElem;
151026 
151027  /* Variables set by fts3SegReaderNext(). These may be read directly
151028  ** by the caller. They are valid from the time SegmentReaderNew() returns
151029  ** until SegmentReaderNext() returns something other than SQLITE_OK
151030  ** (i.e. SQLITE_DONE).
151031  */
151032  int nTerm; /* Number of bytes in current term */
151033  char *zTerm; /* Pointer to current term */
151034  int nTermAlloc; /* Allocated size of zTerm buffer */
151035  char *aDoclist; /* Pointer to doclist of current entry */
151036  int nDoclist; /* Size of doclist in current entry */
151037 
151038  /* The following variables are used by fts3SegReaderNextDocid() to iterate
151039  ** through the current doclist (aDoclist/nDoclist).
151040  */
151041  char *pOffsetList;
151042  int nOffsetList; /* For descending pending seg-readers only */
151043  sqlite3_int64 iDocid;
151044 };
151045 
151046 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
151047 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
151048 
151049 /*
151050 ** An instance of this structure is used to create a segment b-tree in the
151051 ** database. The internal details of this type are only accessed by the
151052 ** following functions:
151053 **
151054 ** fts3SegWriterAdd()
151055 ** fts3SegWriterFlush()
151056 ** fts3SegWriterFree()
151057 */
151058 struct SegmentWriter {
151059  SegmentNode *pTree; /* Pointer to interior tree structure */
151060  sqlite3_int64 iFirst; /* First slot in %_segments written */
151061  sqlite3_int64 iFree; /* Next free slot in %_segments */
151062  char *zTerm; /* Pointer to previous term buffer */
151063  int nTerm; /* Number of bytes in zTerm */
151064  int nMalloc; /* Size of malloc'd buffer at zMalloc */
151065  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
151066  int nSize; /* Size of allocation at aData */
151067  int nData; /* Bytes of data in aData */
151068  char *aData; /* Pointer to block from malloc() */
151069  i64 nLeafData; /* Number of bytes of leaf data written */
151070 };
151071 
151072 /*
151073 ** Type SegmentNode is used by the following three functions to create
151074 ** the interior part of the segment b+-tree structures (everything except
151075 ** the leaf nodes). These functions and type are only ever used by code
151076 ** within the fts3SegWriterXXX() family of functions described above.
151077 **
151078 ** fts3NodeAddTerm()
151079 ** fts3NodeWrite()
151080 ** fts3NodeFree()
151081 **
151082 ** When a b+tree is written to the database (either as a result of a merge
151083 ** or the pending-terms table being flushed), leaves are written into the
151084 ** database file as soon as they are completely populated. The interior of
151085 ** the tree is assembled in memory and written out only once all leaves have
151086 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
151087 ** very large, meaning that the interior of the tree consumes relatively
151088 ** little memory.
151089 */
151090 struct SegmentNode {
151091  SegmentNode *pParent; /* Parent node (or NULL for root node) */
151092  SegmentNode *pRight; /* Pointer to right-sibling */
151093  SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
151094  int nEntry; /* Number of terms written to node so far */
151095  char *zTerm; /* Pointer to previous term buffer */
151096  int nTerm; /* Number of bytes in zTerm */
151097  int nMalloc; /* Size of malloc'd buffer at zMalloc */
151098  char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
151099  int nData; /* Bytes of valid data so far */
151100  char *aData; /* Node data */
151101 };
151102 
151103 /*
151104 ** Valid values for the second argument to fts3SqlStmt().
151105 */
151106 #define SQL_DELETE_CONTENT 0
151107 #define SQL_IS_EMPTY 1
151108 #define SQL_DELETE_ALL_CONTENT 2
151109 #define SQL_DELETE_ALL_SEGMENTS 3
151110 #define SQL_DELETE_ALL_SEGDIR 4
151111 #define SQL_DELETE_ALL_DOCSIZE 5
151112 #define SQL_DELETE_ALL_STAT 6
151113 #define SQL_SELECT_CONTENT_BY_ROWID 7
151114 #define SQL_NEXT_SEGMENT_INDEX 8
151115 #define SQL_INSERT_SEGMENTS 9
151116 #define SQL_NEXT_SEGMENTS_ID 10
151117 #define SQL_INSERT_SEGDIR 11
151118 #define SQL_SELECT_LEVEL 12
151119 #define SQL_SELECT_LEVEL_RANGE 13
151120 #define SQL_SELECT_LEVEL_COUNT 14
151121 #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
151122 #define SQL_DELETE_SEGDIR_LEVEL 16
151123 #define SQL_DELETE_SEGMENTS_RANGE 17
151124 #define SQL_CONTENT_INSERT 18
151125 #define SQL_DELETE_DOCSIZE 19
151126 #define SQL_REPLACE_DOCSIZE 20
151127 #define SQL_SELECT_DOCSIZE 21
151128 #define SQL_SELECT_STAT 22
151129 #define SQL_REPLACE_STAT 23
151130 
151131 #define SQL_SELECT_ALL_PREFIX_LEVEL 24
151132 #define SQL_DELETE_ALL_TERMS_SEGDIR 25
151133 #define SQL_DELETE_SEGDIR_RANGE 26
151134 #define SQL_SELECT_ALL_LANGID 27
151135 #define SQL_FIND_MERGE_LEVEL 28
151136 #define SQL_MAX_LEAF_NODE_ESTIMATE 29
151137 #define SQL_DELETE_SEGDIR_ENTRY 30
151138 #define SQL_SHIFT_SEGDIR_ENTRY 31
151139 #define SQL_SELECT_SEGDIR 32
151140 #define SQL_CHOMP_SEGDIR 33
151141 #define SQL_SEGMENT_IS_APPENDABLE 34
151142 #define SQL_SELECT_INDEXES 35
151143 #define SQL_SELECT_MXLEVEL 36
151144 
151145 #define SQL_SELECT_LEVEL_RANGE2 37
151146 #define SQL_UPDATE_LEVEL_IDX 38
151147 #define SQL_UPDATE_LEVEL 39
151148 
151149 /*
151150 ** This function is used to obtain an SQLite prepared statement handle
151151 ** for the statement identified by the second argument. If successful,
151152 ** *pp is set to the requested statement handle and SQLITE_OK returned.
151153 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
151154 **
151155 ** If argument apVal is not NULL, then it must point to an array with
151156 ** at least as many entries as the requested statement has bound
151157 ** parameters. The values are bound to the statements parameters before
151158 ** returning.
151159 */
151160 static int fts3SqlStmt(
151161  Fts3Table *p, /* Virtual table handle */
151162  int eStmt, /* One of the SQL_XXX constants above */
151163  sqlite3_stmt **pp, /* OUT: Statement handle */
151164  sqlite3_value **apVal /* Values to bind to statement */
151165 ){
151166  const char *azSql[] = {
151167 /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
151168 /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
151169 /* 2 */ "DELETE FROM %Q.'%q_content'",
151170 /* 3 */ "DELETE FROM %Q.'%q_segments'",
151171 /* 4 */ "DELETE FROM %Q.'%q_segdir'",
151172 /* 5 */ "DELETE FROM %Q.'%q_docsize'",
151173 /* 6 */ "DELETE FROM %Q.'%q_stat'",
151174 /* 7 */ "SELECT %s WHERE rowid=?",
151175 /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
151176 /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
151177 /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
151178 /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
151179 
151180  /* Return segments in order from oldest to newest.*/
151181 /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
151182  "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
151183 /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
151184  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
151185  "ORDER BY level DESC, idx ASC",
151186 
151187 /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
151188 /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
151189 
151190 /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
151191 /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
151192 /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
151193 /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
151194 /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
151195 /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
151196 /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
151197 /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
151198 /* 24 */ "",
151199 /* 25 */ "",
151200 
151201 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
151202 /* 27 */ "SELECT ? UNION SELECT level / (1024 * ?) FROM %Q.'%q_segdir'",
151203 
151204 /* This statement is used to determine which level to read the input from
151205 ** when performing an incremental merge. It returns the absolute level number
151206 ** of the oldest level in the db that contains at least ? segments. Or,
151207 ** if no level in the FTS index contains more than ? segments, the statement
151208 ** returns zero rows. */
151209 /* 28 */ "SELECT level, count(*) AS cnt FROM %Q.'%q_segdir' "
151210  " GROUP BY level HAVING cnt>=?"
151211  " ORDER BY (level %% 1024) ASC LIMIT 1",
151212 
151213 /* Estimate the upper limit on the number of leaf nodes in a new segment
151214 ** created by merging the oldest :2 segments from absolute level :1. See
151215 ** function sqlite3Fts3Incrmerge() for details. */
151216 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
151217  " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
151218 
151219 /* SQL_DELETE_SEGDIR_ENTRY
151220 ** Delete the %_segdir entry on absolute level :1 with index :2. */
151221 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
151222 
151223 /* SQL_SHIFT_SEGDIR_ENTRY
151224 ** Modify the idx value for the segment with idx=:3 on absolute level :2
151225 ** to :1. */
151226 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
151227 
151228 /* SQL_SELECT_SEGDIR
151229 ** Read a single entry from the %_segdir table. The entry from absolute
151230 ** level :1 with index value :2. */
151231 /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
151232  "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
151233 
151234 /* SQL_CHOMP_SEGDIR
151235 ** Update the start_block (:1) and root (:2) fields of the %_segdir
151236 ** entry located on absolute level :3 with index :4. */
151237 /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
151238  "WHERE level = ? AND idx = ?",
151239 
151240 /* SQL_SEGMENT_IS_APPENDABLE
151241 ** Return a single row if the segment with end_block=? is appendable. Or
151242 ** no rows otherwise. */
151243 /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
151244 
151245 /* SQL_SELECT_INDEXES
151246 ** Return the list of valid segment indexes for absolute level ? */
151247 /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
151248 
151249 /* SQL_SELECT_MXLEVEL
151250 ** Return the largest relative level in the FTS index or indexes. */
151251 /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
151252 
151253  /* Return segments in order from oldest to newest.*/
151254 /* 37 */ "SELECT level, idx, end_block "
151255  "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
151256  "ORDER BY level DESC, idx ASC",
151257 
151258  /* Update statements used while promoting segments */
151259 /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
151260  "WHERE level=? AND idx=?",
151261 /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
151262 
151263  };
151264  int rc = SQLITE_OK;
151265  sqlite3_stmt *pStmt;
151266 
151267  assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
151268  assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
151269 
151270  pStmt = p->aStmt[eStmt];
151271  if( !pStmt ){
151272  char *zSql;
151273  if( eStmt==SQL_CONTENT_INSERT ){
151274  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
151275  }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
151276  zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
151277  }else{
151278  zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
151279  }
151280  if( !zSql ){
151281  rc = SQLITE_NOMEM;
151282  }else{
151283  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
151284  sqlite3_free(zSql);
151285  assert( rc==SQLITE_OK || pStmt==0 );
151286  p->aStmt[eStmt] = pStmt;
151287  }
151288  }
151289  if( apVal ){
151290  int i;
151291  int nParam = sqlite3_bind_parameter_count(pStmt);
151292  for(i=0; rc==SQLITE_OK && i<nParam; i++){
151293  rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
151294  }
151295  }
151296  *pp = pStmt;
151297  return rc;
151298 }
151299 
151300 
151301 static int fts3SelectDocsize(
151302  Fts3Table *pTab, /* FTS3 table handle */
151303  sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
151304  sqlite3_stmt **ppStmt /* OUT: Statement handle */
151305 ){
151306  sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
151307  int rc; /* Return code */
151308 
151309  rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
151310  if( rc==SQLITE_OK ){
151311  sqlite3_bind_int64(pStmt, 1, iDocid);
151312  rc = sqlite3_step(pStmt);
151313  if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
151314  rc = sqlite3_reset(pStmt);
151315  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
151316  pStmt = 0;
151317  }else{
151318  rc = SQLITE_OK;
151319  }
151320  }
151321 
151322  *ppStmt = pStmt;
151323  return rc;
151324 }
151325 
151326 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
151327  Fts3Table *pTab, /* Fts3 table handle */
151328  sqlite3_stmt **ppStmt /* OUT: Statement handle */
151329 ){
151330  sqlite3_stmt *pStmt = 0;
151331  int rc;
151332  rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
151333  if( rc==SQLITE_OK ){
151334  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
151335  if( sqlite3_step(pStmt)!=SQLITE_ROW
151336  || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
151337  ){
151338  rc = sqlite3_reset(pStmt);
151339  if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
151340  pStmt = 0;
151341  }
151342  }
151343  *ppStmt = pStmt;
151344  return rc;
151345 }
151346 
151347 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
151348  Fts3Table *pTab, /* Fts3 table handle */
151349  sqlite3_int64 iDocid, /* Docid to read size data for */
151350  sqlite3_stmt **ppStmt /* OUT: Statement handle */
151351 ){
151352  return fts3SelectDocsize(pTab, iDocid, ppStmt);
151353 }
151354 
151355 /*
151356 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
151357 ** array apVal[] to the SQL statement identified by eStmt, the statement
151358 ** is executed.
151359 **
151360 ** Returns SQLITE_OK if the statement is successfully executed, or an
151361 ** SQLite error code otherwise.
151362 */
151363 static void fts3SqlExec(
151364  int *pRC, /* Result code */
151365  Fts3Table *p, /* The FTS3 table */
151366  int eStmt, /* Index of statement to evaluate */
151367  sqlite3_value **apVal /* Parameters to bind */
151368 ){
151369  sqlite3_stmt *pStmt;
151370  int rc;
151371  if( *pRC ) return;
151372  rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
151373  if( rc==SQLITE_OK ){
151374  sqlite3_step(pStmt);
151375  rc = sqlite3_reset(pStmt);
151376  }
151377  *pRC = rc;
151378 }
151379 
151380 
151381 /*
151382 ** This function ensures that the caller has obtained an exclusive
151383 ** shared-cache table-lock on the %_segdir table. This is required before
151384 ** writing data to the fts3 table. If this lock is not acquired first, then
151385 ** the caller may end up attempting to take this lock as part of committing
151386 ** a transaction, causing SQLite to return SQLITE_LOCKED or
151387 ** LOCKED_SHAREDCACHEto a COMMIT command.
151388 **
151389 ** It is best to avoid this because if FTS3 returns any error when
151390 ** committing a transaction, the whole transaction will be rolled back.
151391 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
151392 ** It can still happen if the user locks the underlying tables directly
151393 ** instead of accessing them via FTS.
151394 */
151395 static int fts3Writelock(Fts3Table *p){
151396  int rc = SQLITE_OK;
151397 
151398  if( p->nPendingData==0 ){
151399  sqlite3_stmt *pStmt;
151400  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
151401  if( rc==SQLITE_OK ){
151402  sqlite3_bind_null(pStmt, 1);
151403  sqlite3_step(pStmt);
151404  rc = sqlite3_reset(pStmt);
151405  }
151406  }
151407 
151408  return rc;
151409 }
151410 
151411 /*
151412 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
151413 ** Within each language id, a separate index is maintained to store the
151414 ** document terms, and each configured prefix size (configured the FTS
151415 ** "prefix=" option). And each index consists of multiple levels ("relative
151416 ** levels").
151417 **
151418 ** All three of these values (the language id, the specific index and the
151419 ** level within the index) are encoded in 64-bit integer values stored
151420 ** in the %_segdir table on disk. This function is used to convert three
151421 ** separate component values into the single 64-bit integer value that
151422 ** can be used to query the %_segdir table.
151423 **
151424 ** Specifically, each language-id/index combination is allocated 1024
151425 ** 64-bit integer level values ("absolute levels"). The main terms index
151426 ** for language-id 0 is allocate values 0-1023. The first prefix index
151427 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
151428 ** Language 1 indexes are allocated immediately following language 0.
151429 **
151430 ** So, for a system with nPrefix prefix indexes configured, the block of
151431 ** absolute levels that corresponds to language-id iLangid and index
151432 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
151433 */
151434 static sqlite3_int64 getAbsoluteLevel(
151435  Fts3Table *p, /* FTS3 table handle */
151436  int iLangid, /* Language id */
151437  int iIndex, /* Index in p->aIndex[] */
151438  int iLevel /* Level of segments */
151439 ){
151440  sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
151441  assert( iLangid>=0 );
151442  assert( p->nIndex>0 );
151443  assert( iIndex>=0 && iIndex<p->nIndex );
151444 
151445  iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
151446  return iBase + iLevel;
151447 }
151448 
151449 /*
151450 ** Set *ppStmt to a statement handle that may be used to iterate through
151451 ** all rows in the %_segdir table, from oldest to newest. If successful,
151452 ** return SQLITE_OK. If an error occurs while preparing the statement,
151453 ** return an SQLite error code.
151454 **
151455 ** There is only ever one instance of this SQL statement compiled for
151456 ** each FTS3 table.
151457 **
151458 ** The statement returns the following columns from the %_segdir table:
151459 **
151460 ** 0: idx
151461 ** 1: start_block
151462 ** 2: leaves_end_block
151463 ** 3: end_block
151464 ** 4: root
151465 */
151466 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
151467  Fts3Table *p, /* FTS3 table */
151468  int iLangid, /* Language being queried */
151469  int iIndex, /* Index for p->aIndex[] */
151470  int iLevel, /* Level to select (relative level) */
151471  sqlite3_stmt **ppStmt /* OUT: Compiled statement */
151472 ){
151473  int rc;
151474  sqlite3_stmt *pStmt = 0;
151475 
151476  assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
151477  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
151478  assert( iIndex>=0 && iIndex<p->nIndex );
151479 
151480  if( iLevel<0 ){
151481  /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
151482  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
151483  if( rc==SQLITE_OK ){
151484  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
151485  sqlite3_bind_int64(pStmt, 2,
151486  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
151487  );
151488  }
151489  }else{
151490  /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
151491  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
151492  if( rc==SQLITE_OK ){
151493  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
151494  }
151495  }
151496  *ppStmt = pStmt;
151497  return rc;
151498 }
151499 
151500 
151501 /*
151502 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
151503 ** if successful, or an SQLite error code otherwise.
151504 **
151505 ** This function also serves to allocate the PendingList structure itself.
151506 ** For example, to create a new PendingList structure containing two
151507 ** varints:
151508 **
151509 ** PendingList *p = 0;
151510 ** fts3PendingListAppendVarint(&p, 1);
151511 ** fts3PendingListAppendVarint(&p, 2);
151512 */
151513 static int fts3PendingListAppendVarint(
151514  PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
151515  sqlite3_int64 i /* Value to append to data */
151516 ){
151517  PendingList *p = *pp;
151518 
151519  /* Allocate or grow the PendingList as required. */
151520  if( !p ){
151521  p = sqlite3_malloc(sizeof(*p) + 100);
151522  if( !p ){
151523  return SQLITE_NOMEM;
151524  }
151525  p->nSpace = 100;
151526  p->aData = (char *)&p[1];
151527  p->nData = 0;
151528  }
151529  else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
151530  int nNew = p->nSpace * 2;
151531  p = sqlite3_realloc(p, sizeof(*p) + nNew);
151532  if( !p ){
151533  sqlite3_free(*pp);
151534  *pp = 0;
151535  return SQLITE_NOMEM;
151536  }
151537  p->nSpace = nNew;
151538  p->aData = (char *)&p[1];
151539  }
151540 
151541  /* Append the new serialized varint to the end of the list. */
151542  p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
151543  p->aData[p->nData] = '\0';
151544  *pp = p;
151545  return SQLITE_OK;
151546 }
151547 
151548 /*
151549 ** Add a docid/column/position entry to a PendingList structure. Non-zero
151550 ** is returned if the structure is sqlite3_realloced as part of adding
151551 ** the entry. Otherwise, zero.
151552 **
151553 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
151554 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
151555 ** it is set to SQLITE_OK.
151556 */
151557 static int fts3PendingListAppend(
151558  PendingList **pp, /* IN/OUT: PendingList structure */
151559  sqlite3_int64 iDocid, /* Docid for entry to add */
151560  sqlite3_int64 iCol, /* Column for entry to add */
151561  sqlite3_int64 iPos, /* Position of term for entry to add */
151562  int *pRc /* OUT: Return code */
151563 ){
151564  PendingList *p = *pp;
151565  int rc = SQLITE_OK;
151566 
151567  assert( !p || p->iLastDocid<=iDocid );
151568 
151569  if( !p || p->iLastDocid!=iDocid ){
151570  sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
151571  if( p ){
151572  assert( p->nData<p->nSpace );
151573  assert( p->aData[p->nData]==0 );
151574  p->nData++;
151575  }
151576  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
151577  goto pendinglistappend_out;
151578  }
151579  p->iLastCol = -1;
151580  p->iLastPos = 0;
151581  p->iLastDocid = iDocid;
151582  }
151583  if( iCol>0 && p->iLastCol!=iCol ){
151584  if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
151585  || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
151586  ){
151587  goto pendinglistappend_out;
151588  }
151589  p->iLastCol = iCol;
151590  p->iLastPos = 0;
151591  }
151592  if( iCol>=0 ){
151593  assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
151594  rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
151595  if( rc==SQLITE_OK ){
151596  p->iLastPos = iPos;
151597  }
151598  }
151599 
151600  pendinglistappend_out:
151601  *pRc = rc;
151602  if( p!=*pp ){
151603  *pp = p;
151604  return 1;
151605  }
151606  return 0;
151607 }
151608 
151609 /*
151610 ** Free a PendingList object allocated by fts3PendingListAppend().
151611 */
151612 static void fts3PendingListDelete(PendingList *pList){
151613  sqlite3_free(pList);
151614 }
151615 
151616 /*
151617 ** Add an entry to one of the pending-terms hash tables.
151618 */
151619 static int fts3PendingTermsAddOne(
151620  Fts3Table *p,
151621  int iCol,
151622  int iPos,
151623  Fts3Hash *pHash, /* Pending terms hash table to add entry to */
151624  const char *zToken,
151625  int nToken
151626 ){
151627  PendingList *pList;
151628  int rc = SQLITE_OK;
151629 
151630  pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
151631  if( pList ){
151632  p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
151633  }
151634  if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
151635  if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
151636  /* Malloc failed while inserting the new entry. This can only
151637  ** happen if there was no previous entry for this token.
151638  */
151639  assert( 0==fts3HashFind(pHash, zToken, nToken) );
151640  sqlite3_free(pList);
151641  rc = SQLITE_NOMEM;
151642  }
151643  }
151644  if( rc==SQLITE_OK ){
151645  p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
151646  }
151647  return rc;
151648 }
151649 
151650 /*
151651 ** Tokenize the nul-terminated string zText and add all tokens to the
151652 ** pending-terms hash-table. The docid used is that currently stored in
151653 ** p->iPrevDocid, and the column is specified by argument iCol.
151654 **
151655 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
151656 */
151657 static int fts3PendingTermsAdd(
151658  Fts3Table *p, /* Table into which text will be inserted */
151659  int iLangid, /* Language id to use */
151660  const char *zText, /* Text of document to be inserted */
151661  int iCol, /* Column into which text is being inserted */
151662  u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
151663 ){
151664  int rc;
151665  int iStart = 0;
151666  int iEnd = 0;
151667  int iPos = 0;
151668  int nWord = 0;
151669 
151670  char const *zToken;
151671  int nToken = 0;
151672 
151673  sqlite3_tokenizer *pTokenizer = p->pTokenizer;
151674  sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
151675  sqlite3_tokenizer_cursor *pCsr;
151676  int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
151677  const char**,int*,int*,int*,int*);
151678 
151679  assert( pTokenizer && pModule );
151680 
151681  /* If the user has inserted a NULL value, this function may be called with
151682  ** zText==0. In this case, add zero token entries to the hash table and
151683  ** return early. */
151684  if( zText==0 ){
151685  *pnWord = 0;
151686  return SQLITE_OK;
151687  }
151688 
151689  rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
151690  if( rc!=SQLITE_OK ){
151691  return rc;
151692  }
151693 
151694  xNext = pModule->xNext;
151695  while( SQLITE_OK==rc
151696  && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
151697  ){
151698  int i;
151699  if( iPos>=nWord ) nWord = iPos+1;
151700 
151701  /* Positions cannot be negative; we use -1 as a terminator internally.
151702  ** Tokens must have a non-zero length.
151703  */
151704  if( iPos<0 || !zToken || nToken<=0 ){
151705  rc = SQLITE_ERROR;
151706  break;
151707  }
151708 
151709  /* Add the term to the terms index */
151710  rc = fts3PendingTermsAddOne(
151711  p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
151712  );
151713 
151714  /* Add the term to each of the prefix indexes that it is not too
151715  ** short for. */
151716  for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
151717  struct Fts3Index *pIndex = &p->aIndex[i];
151718  if( nToken<pIndex->nPrefix ) continue;
151719  rc = fts3PendingTermsAddOne(
151720  p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
151721  );
151722  }
151723  }
151724 
151725  pModule->xClose(pCsr);
151726  *pnWord += nWord;
151727  return (rc==SQLITE_DONE ? SQLITE_OK : rc);
151728 }
151729 
151730 /*
151731 ** Calling this function indicates that subsequent calls to
151732 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
151733 ** contents of the document with docid iDocid.
151734 */
151735 static int fts3PendingTermsDocid(
151736  Fts3Table *p, /* Full-text table handle */
151737  int bDelete, /* True if this op is a delete */
151738  int iLangid, /* Language id of row being written */
151739  sqlite_int64 iDocid /* Docid of row being written */
151740 ){
151741  assert( iLangid>=0 );
151742  assert( bDelete==1 || bDelete==0 );
151743 
151744  /* TODO(shess) Explore whether partially flushing the buffer on
151745  ** forced-flush would provide better performance. I suspect that if
151746  ** we ordered the doclists by size and flushed the largest until the
151747  ** buffer was half empty, that would let the less frequent terms
151748  ** generate longer doclists.
151749  */
151750  if( iDocid<p->iPrevDocid
151751  || (iDocid==p->iPrevDocid && p->bPrevDelete==0)
151752  || p->iPrevLangid!=iLangid
151753  || p->nPendingData>p->nMaxPendingData
151754  ){
151755  int rc = sqlite3Fts3PendingTermsFlush(p);
151756  if( rc!=SQLITE_OK ) return rc;
151757  }
151758  p->iPrevDocid = iDocid;
151759  p->iPrevLangid = iLangid;
151760  p->bPrevDelete = bDelete;
151761  return SQLITE_OK;
151762 }
151763 
151764 /*
151765 ** Discard the contents of the pending-terms hash tables.
151766 */
151767 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
151768  int i;
151769  for(i=0; i<p->nIndex; i++){
151770  Fts3HashElem *pElem;
151771  Fts3Hash *pHash = &p->aIndex[i].hPending;
151772  for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
151773  PendingList *pList = (PendingList *)fts3HashData(pElem);
151774  fts3PendingListDelete(pList);
151775  }
151776  fts3HashClear(pHash);
151777  }
151778  p->nPendingData = 0;
151779 }
151780 
151781 /*
151782 ** This function is called by the xUpdate() method as part of an INSERT
151783 ** operation. It adds entries for each term in the new record to the
151784 ** pendingTerms hash table.
151785 **
151786 ** Argument apVal is the same as the similarly named argument passed to
151787 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
151788 */
151789 static int fts3InsertTerms(
151790  Fts3Table *p,
151791  int iLangid,
151792  sqlite3_value **apVal,
151793  u32 *aSz
151794 ){
151795  int i; /* Iterator variable */
151796  for(i=2; i<p->nColumn+2; i++){
151797  int iCol = i-2;
151798  if( p->abNotindexed[iCol]==0 ){
151799  const char *zText = (const char *)sqlite3_value_text(apVal[i]);
151800  int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
151801  if( rc!=SQLITE_OK ){
151802  return rc;
151803  }
151804  aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
151805  }
151806  }
151807  return SQLITE_OK;
151808 }
151809 
151810 /*
151811 ** This function is called by the xUpdate() method for an INSERT operation.
151812 ** The apVal parameter is passed a copy of the apVal argument passed by
151813 ** SQLite to the xUpdate() method. i.e:
151814 **
151815 ** apVal[0] Not used for INSERT.
151816 ** apVal[1] rowid
151817 ** apVal[2] Left-most user-defined column
151818 ** ...
151819 ** apVal[p->nColumn+1] Right-most user-defined column
151820 ** apVal[p->nColumn+2] Hidden column with same name as table
151821 ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
151822 ** apVal[p->nColumn+4] Hidden languageid column
151823 */
151824 static int fts3InsertData(
151825  Fts3Table *p, /* Full-text table */
151826  sqlite3_value **apVal, /* Array of values to insert */
151827  sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
151828 ){
151829  int rc; /* Return code */
151830  sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
151831 
151832  if( p->zContentTbl ){
151833  sqlite3_value *pRowid = apVal[p->nColumn+3];
151834  if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
151835  pRowid = apVal[1];
151836  }
151837  if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
151838  return SQLITE_CONSTRAINT;
151839  }
151840  *piDocid = sqlite3_value_int64(pRowid);
151841  return SQLITE_OK;
151842  }
151843 
151844  /* Locate the statement handle used to insert data into the %_content
151845  ** table. The SQL for this statement is:
151846  **
151847  ** INSERT INTO %_content VALUES(?, ?, ?, ...)
151848  **
151849  ** The statement features N '?' variables, where N is the number of user
151850  ** defined columns in the FTS3 table, plus one for the docid field.
151851  */
151852  rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
151853  if( rc==SQLITE_OK && p->zLanguageid ){
151854  rc = sqlite3_bind_int(
151855  pContentInsert, p->nColumn+2,
151856  sqlite3_value_int(apVal[p->nColumn+4])
151857  );
151858  }
151859  if( rc!=SQLITE_OK ) return rc;
151860 
151861  /* There is a quirk here. The users INSERT statement may have specified
151862  ** a value for the "rowid" field, for the "docid" field, or for both.
151863  ** Which is a problem, since "rowid" and "docid" are aliases for the
151864  ** same value. For example:
151865  **
151866  ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
151867  **
151868  ** In FTS3, this is an error. It is an error to specify non-NULL values
151869  ** for both docid and some other rowid alias.
151870  */
151871  if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
151872  if( SQLITE_NULL==sqlite3_value_type(apVal[0])
151873  && SQLITE_NULL!=sqlite3_value_type(apVal[1])
151874  ){
151875  /* A rowid/docid conflict. */
151876  return SQLITE_ERROR;
151877  }
151878  rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
151879  if( rc!=SQLITE_OK ) return rc;
151880  }
151881 
151882  /* Execute the statement to insert the record. Set *piDocid to the
151883  ** new docid value.
151884  */
151885  sqlite3_step(pContentInsert);
151886  rc = sqlite3_reset(pContentInsert);
151887 
151888  *piDocid = sqlite3_last_insert_rowid(p->db);
151889  return rc;
151890 }
151891 
151892 
151893 
151894 /*
151895 ** Remove all data from the FTS3 table. Clear the hash table containing
151896 ** pending terms.
151897 */
151898 static int fts3DeleteAll(Fts3Table *p, int bContent){
151899  int rc = SQLITE_OK; /* Return code */
151900 
151901  /* Discard the contents of the pending-terms hash table. */
151902  sqlite3Fts3PendingTermsClear(p);
151903 
151904  /* Delete everything from the shadow tables. Except, leave %_content as
151905  ** is if bContent is false. */
151906  assert( p->zContentTbl==0 || bContent==0 );
151907  if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
151908  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
151909  fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
151910  if( p->bHasDocsize ){
151911  fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
151912  }
151913  if( p->bHasStat ){
151914  fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
151915  }
151916  return rc;
151917 }
151918 
151919 /*
151920 **
151921 */
151922 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
151923  int iLangid = 0;
151924  if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
151925  return iLangid;
151926 }
151927 
151928 /*
151929 ** The first element in the apVal[] array is assumed to contain the docid
151930 ** (an integer) of a row about to be deleted. Remove all terms from the
151931 ** full-text index.
151932 */
151933 static void fts3DeleteTerms(
151934  int *pRC, /* Result code */
151935  Fts3Table *p, /* The FTS table to delete from */
151936  sqlite3_value *pRowid, /* The docid to be deleted */
151937  u32 *aSz, /* Sizes of deleted document written here */
151938  int *pbFound /* OUT: Set to true if row really does exist */
151939 ){
151940  int rc;
151941  sqlite3_stmt *pSelect;
151942 
151943  assert( *pbFound==0 );
151944  if( *pRC ) return;
151945  rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
151946  if( rc==SQLITE_OK ){
151947  if( SQLITE_ROW==sqlite3_step(pSelect) ){
151948  int i;
151949  int iLangid = langidFromSelect(p, pSelect);
151950  i64 iDocid = sqlite3_column_int64(pSelect, 0);
151951  rc = fts3PendingTermsDocid(p, 1, iLangid, iDocid);
151952  for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
151953  int iCol = i-1;
151954  if( p->abNotindexed[iCol]==0 ){
151955  const char *zText = (const char *)sqlite3_column_text(pSelect, i);
151956  rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
151957  aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
151958  }
151959  }
151960  if( rc!=SQLITE_OK ){
151961  sqlite3_reset(pSelect);
151962  *pRC = rc;
151963  return;
151964  }
151965  *pbFound = 1;
151966  }
151967  rc = sqlite3_reset(pSelect);
151968  }else{
151969  sqlite3_reset(pSelect);
151970  }
151971  *pRC = rc;
151972 }
151973 
151974 /*
151975 ** Forward declaration to account for the circular dependency between
151976 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
151977 */
151978 static int fts3SegmentMerge(Fts3Table *, int, int, int);
151979 
151980 /*
151981 ** This function allocates a new level iLevel index in the segdir table.
151982 ** Usually, indexes are allocated within a level sequentially starting
151983 ** with 0, so the allocated index is one greater than the value returned
151984 ** by:
151985 **
151986 ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
151987 **
151988 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
151989 ** level, they are merged into a single level (iLevel+1) segment and the
151990 ** allocated index is 0.
151991 **
151992 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
151993 ** returned. Otherwise, an SQLite error code is returned.
151994 */
151995 static int fts3AllocateSegdirIdx(
151996  Fts3Table *p,
151997  int iLangid, /* Language id */
151998  int iIndex, /* Index for p->aIndex */
151999  int iLevel,
152000  int *piIdx
152001 ){
152002  int rc; /* Return Code */
152003  sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
152004  int iNext = 0; /* Result of query pNextIdx */
152005 
152006  assert( iLangid>=0 );
152007  assert( p->nIndex>=1 );
152008 
152009  /* Set variable iNext to the next available segdir index at level iLevel. */
152010  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
152011  if( rc==SQLITE_OK ){
152013  pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
152014  );
152015  if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
152016  iNext = sqlite3_column_int(pNextIdx, 0);
152017  }
152018  rc = sqlite3_reset(pNextIdx);
152019  }
152020 
152021  if( rc==SQLITE_OK ){
152022  /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
152023  ** full, merge all segments in level iLevel into a single iLevel+1
152024  ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
152025  ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
152026  */
152027  if( iNext>=FTS3_MERGE_COUNT ){
152028  fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
152029  rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
152030  *piIdx = 0;
152031  }else{
152032  *piIdx = iNext;
152033  }
152034  }
152035 
152036  return rc;
152037 }
152038 
152039 /*
152040 ** The %_segments table is declared as follows:
152041 **
152042 ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
152043 **
152044 ** This function reads data from a single row of the %_segments table. The
152045 ** specific row is identified by the iBlockid parameter. If paBlob is not
152046 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
152047 ** with the contents of the blob stored in the "block" column of the
152048 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
152049 ** to the size of the blob in bytes before returning.
152050 **
152051 ** If an error occurs, or the table does not contain the specified row,
152052 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
152053 ** paBlob is non-NULL, then it is the responsibility of the caller to
152054 ** eventually free the returned buffer.
152055 **
152056 ** This function may leave an open sqlite3_blob* handle in the
152057 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
152058 ** to this function. The handle may be closed by calling the
152059 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
152060 ** performance improvement, but the blob handle should always be closed
152061 ** before control is returned to the user (to prevent a lock being held
152062 ** on the database file for longer than necessary). Thus, any virtual table
152063 ** method (xFilter etc.) that may directly or indirectly call this function
152064 ** must call sqlite3Fts3SegmentsClose() before returning.
152065 */
152066 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
152067  Fts3Table *p, /* FTS3 table handle */
152068  sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
152069  char **paBlob, /* OUT: Blob data in malloc'd buffer */
152070  int *pnBlob, /* OUT: Size of blob data */
152071  int *pnLoad /* OUT: Bytes actually loaded */
152072 ){
152073  int rc; /* Return code */
152074 
152075  /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
152076  assert( pnBlob );
152077 
152078  if( p->pSegments ){
152079  rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
152080  }else{
152081  if( 0==p->zSegmentsTbl ){
152082  p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
152083  if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
152084  }
152085  rc = sqlite3_blob_open(
152086  p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
152087  );
152088  }
152089 
152090  if( rc==SQLITE_OK ){
152091  int nByte = sqlite3_blob_bytes(p->pSegments);
152092  *pnBlob = nByte;
152093  if( paBlob ){
152094  char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
152095  if( !aByte ){
152096  rc = SQLITE_NOMEM;
152097  }else{
152098  if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
152099  nByte = FTS3_NODE_CHUNKSIZE;
152100  *pnLoad = nByte;
152101  }
152102  rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
152103  memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
152104  if( rc!=SQLITE_OK ){
152105  sqlite3_free(aByte);
152106  aByte = 0;
152107  }
152108  }
152109  *paBlob = aByte;
152110  }
152111  }
152112 
152113  return rc;
152114 }
152115 
152116 /*
152117 ** Close the blob handle at p->pSegments, if it is open. See comments above
152118 ** the sqlite3Fts3ReadBlock() function for details.
152119 */
152120 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
152121  sqlite3_blob_close(p->pSegments);
152122  p->pSegments = 0;
152123 }
152124 
152125 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
152126  int nRead; /* Number of bytes to read */
152127  int rc; /* Return code */
152128 
152129  nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
152130  rc = sqlite3_blob_read(
152131  pReader->pBlob,
152132  &pReader->aNode[pReader->nPopulate],
152133  nRead,
152134  pReader->nPopulate
152135  );
152136 
152137  if( rc==SQLITE_OK ){
152138  pReader->nPopulate += nRead;
152139  memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
152140  if( pReader->nPopulate==pReader->nNode ){
152141  sqlite3_blob_close(pReader->pBlob);
152142  pReader->pBlob = 0;
152143  pReader->nPopulate = 0;
152144  }
152145  }
152146  return rc;
152147 }
152148 
152149 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
152150  int rc = SQLITE_OK;
152151  assert( !pReader->pBlob
152152  || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
152153  );
152154  while( pReader->pBlob && rc==SQLITE_OK
152155  && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
152156  ){
152157  rc = fts3SegReaderIncrRead(pReader);
152158  }
152159  return rc;
152160 }
152161 
152162 /*
152163 ** Set an Fts3SegReader cursor to point at EOF.
152164 */
152165 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
152166  if( !fts3SegReaderIsRootOnly(pSeg) ){
152167  sqlite3_free(pSeg->aNode);
152168  sqlite3_blob_close(pSeg->pBlob);
152169  pSeg->pBlob = 0;
152170  }
152171  pSeg->aNode = 0;
152172 }
152173 
152174 /*
152175 ** Move the iterator passed as the first argument to the next term in the
152176 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
152177 ** SQLITE_DONE. Otherwise, an SQLite error code.
152178 */
152179 static int fts3SegReaderNext(
152180  Fts3Table *p,
152181  Fts3SegReader *pReader,
152182  int bIncr
152183 ){
152184  int rc; /* Return code of various sub-routines */
152185  char *pNext; /* Cursor variable */
152186  int nPrefix; /* Number of bytes in term prefix */
152187  int nSuffix; /* Number of bytes in term suffix */
152188 
152189  if( !pReader->aDoclist ){
152190  pNext = pReader->aNode;
152191  }else{
152192  pNext = &pReader->aDoclist[pReader->nDoclist];
152193  }
152194 
152195  if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
152196 
152197  if( fts3SegReaderIsPending(pReader) ){
152198  Fts3HashElem *pElem = *(pReader->ppNextElem);
152199  sqlite3_free(pReader->aNode);
152200  pReader->aNode = 0;
152201  if( pElem ){
152202  char *aCopy;
152203  PendingList *pList = (PendingList *)fts3HashData(pElem);
152204  int nCopy = pList->nData+1;
152205  pReader->zTerm = (char *)fts3HashKey(pElem);
152206  pReader->nTerm = fts3HashKeysize(pElem);
152207  aCopy = (char*)sqlite3_malloc(nCopy);
152208  if( !aCopy ) return SQLITE_NOMEM;
152209  memcpy(aCopy, pList->aData, nCopy);
152210  pReader->nNode = pReader->nDoclist = nCopy;
152211  pReader->aNode = pReader->aDoclist = aCopy;
152212  pReader->ppNextElem++;
152213  assert( pReader->aNode );
152214  }
152215  return SQLITE_OK;
152216  }
152217 
152218  fts3SegReaderSetEof(pReader);
152219 
152220  /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
152221  ** blocks have already been traversed. */
152222  assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
152223  if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
152224  return SQLITE_OK;
152225  }
152226 
152227  rc = sqlite3Fts3ReadBlock(
152228  p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
152229  (bIncr ? &pReader->nPopulate : 0)
152230  );
152231  if( rc!=SQLITE_OK ) return rc;
152232  assert( pReader->pBlob==0 );
152233  if( bIncr && pReader->nPopulate<pReader->nNode ){
152234  pReader->pBlob = p->pSegments;
152235  p->pSegments = 0;
152236  }
152237  pNext = pReader->aNode;
152238  }
152239 
152240  assert( !fts3SegReaderIsPending(pReader) );
152241 
152242  rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
152243  if( rc!=SQLITE_OK ) return rc;
152244 
152245  /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
152246  ** safe (no risk of overread) even if the node data is corrupted. */
152247  pNext += fts3GetVarint32(pNext, &nPrefix);
152248  pNext += fts3GetVarint32(pNext, &nSuffix);
152249  if( nPrefix<0 || nSuffix<=0
152250  || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
152251  ){
152252  return FTS_CORRUPT_VTAB;
152253  }
152254 
152255  if( nPrefix+nSuffix>pReader->nTermAlloc ){
152256  int nNew = (nPrefix+nSuffix)*2;
152257  char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
152258  if( !zNew ){
152259  return SQLITE_NOMEM;
152260  }
152261  pReader->zTerm = zNew;
152262  pReader->nTermAlloc = nNew;
152263  }
152264 
152265  rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
152266  if( rc!=SQLITE_OK ) return rc;
152267 
152268  memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
152269  pReader->nTerm = nPrefix+nSuffix;
152270  pNext += nSuffix;
152271  pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
152272  pReader->aDoclist = pNext;
152273  pReader->pOffsetList = 0;
152274 
152275  /* Check that the doclist does not appear to extend past the end of the
152276  ** b-tree node. And that the final byte of the doclist is 0x00. If either
152277  ** of these statements is untrue, then the data structure is corrupt.
152278  */
152279  if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
152280  || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
152281  ){
152282  return FTS_CORRUPT_VTAB;
152283  }
152284  return SQLITE_OK;
152285 }
152286 
152287 /*
152288 ** Set the SegReader to point to the first docid in the doclist associated
152289 ** with the current term.
152290 */
152291 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
152292  int rc = SQLITE_OK;
152293  assert( pReader->aDoclist );
152294  assert( !pReader->pOffsetList );
152295  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
152296  u8 bEof = 0;
152297  pReader->iDocid = 0;
152298  pReader->nOffsetList = 0;
152299  sqlite3Fts3DoclistPrev(0,
152300  pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
152301  &pReader->iDocid, &pReader->nOffsetList, &bEof
152302  );
152303  }else{
152304  rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
152305  if( rc==SQLITE_OK ){
152306  int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
152307  pReader->pOffsetList = &pReader->aDoclist[n];
152308  }
152309  }
152310  return rc;
152311 }
152312 
152313 /*
152314 ** Advance the SegReader to point to the next docid in the doclist
152315 ** associated with the current term.
152316 **
152317 ** If arguments ppOffsetList and pnOffsetList are not NULL, then
152318 ** *ppOffsetList is set to point to the first column-offset list
152319 ** in the doclist entry (i.e. immediately past the docid varint).
152320 ** *pnOffsetList is set to the length of the set of column-offset
152321 ** lists, not including the nul-terminator byte. For example:
152322 */
152323 static int fts3SegReaderNextDocid(
152324  Fts3Table *pTab,
152325  Fts3SegReader *pReader, /* Reader to advance to next docid */
152326  char **ppOffsetList, /* OUT: Pointer to current position-list */
152327  int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
152328 ){
152329  int rc = SQLITE_OK;
152330  char *p = pReader->pOffsetList;
152331  char c = 0;
152332 
152333  assert( p );
152334 
152335  if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
152336  /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
152337  ** Pending-terms doclists are always built up in ascending order, so
152338  ** we have to iterate through them backwards here. */
152339  u8 bEof = 0;
152340  if( ppOffsetList ){
152341  *ppOffsetList = pReader->pOffsetList;
152342  *pnOffsetList = pReader->nOffsetList - 1;
152343  }
152344  sqlite3Fts3DoclistPrev(0,
152345  pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
152346  &pReader->nOffsetList, &bEof
152347  );
152348  if( bEof ){
152349  pReader->pOffsetList = 0;
152350  }else{
152351  pReader->pOffsetList = p;
152352  }
152353  }else{
152354  char *pEnd = &pReader->aDoclist[pReader->nDoclist];
152355 
152356  /* Pointer p currently points at the first byte of an offset list. The
152357  ** following block advances it to point one byte past the end of
152358  ** the same offset list. */
152359  while( 1 ){
152360 
152361  /* The following line of code (and the "p++" below the while() loop) is
152362  ** normally all that is required to move pointer p to the desired
152363  ** position. The exception is if this node is being loaded from disk
152364  ** incrementally and pointer "p" now points to the first byte past
152365  ** the populated part of pReader->aNode[].
152366  */
152367  while( *p | c ) c = *p++ & 0x80;
152368  assert( *p==0 );
152369 
152370  if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
152371  rc = fts3SegReaderIncrRead(pReader);
152372  if( rc!=SQLITE_OK ) return rc;
152373  }
152374  p++;
152375 
152376  /* If required, populate the output variables with a pointer to and the
152377  ** size of the previous offset-list.
152378  */
152379  if( ppOffsetList ){
152380  *ppOffsetList = pReader->pOffsetList;
152381  *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
152382  }
152383 
152384  /* List may have been edited in place by fts3EvalNearTrim() */
152385  while( p<pEnd && *p==0 ) p++;
152386 
152387  /* If there are no more entries in the doclist, set pOffsetList to
152388  ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
152389  ** Fts3SegReader.pOffsetList to point to the next offset list before
152390  ** returning.
152391  */
152392  if( p>=pEnd ){
152393  pReader->pOffsetList = 0;
152394  }else{
152395  rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
152396  if( rc==SQLITE_OK ){
152397  sqlite3_int64 iDelta;
152398  pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
152399  if( pTab->bDescIdx ){
152400  pReader->iDocid -= iDelta;
152401  }else{
152402  pReader->iDocid += iDelta;
152403  }
152404  }
152405  }
152406  }
152407 
152408  return SQLITE_OK;
152409 }
152410 
152411 
152412 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
152413  Fts3Cursor *pCsr,
152414  Fts3MultiSegReader *pMsr,
152415  int *pnOvfl
152416 ){
152417  Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
152418  int nOvfl = 0;
152419  int ii;
152420  int rc = SQLITE_OK;
152421  int pgsz = p->nPgsz;
152422 
152423  assert( p->bFts4 );
152424  assert( pgsz>0 );
152425 
152426  for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
152427  Fts3SegReader *pReader = pMsr->apSegment[ii];
152428  if( !fts3SegReaderIsPending(pReader)
152429  && !fts3SegReaderIsRootOnly(pReader)
152430  ){
152431  sqlite3_int64 jj;
152432  for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
152433  int nBlob;
152434  rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
152435  if( rc!=SQLITE_OK ) break;
152436  if( (nBlob+35)>pgsz ){
152437  nOvfl += (nBlob + 34)/pgsz;
152438  }
152439  }
152440  }
152441  }
152442  *pnOvfl = nOvfl;
152443  return rc;
152444 }
152445 
152446 /*
152447 ** Free all allocations associated with the iterator passed as the
152448 ** second argument.
152449 */
152450 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
152451  if( pReader ){
152452  if( !fts3SegReaderIsPending(pReader) ){
152453  sqlite3_free(pReader->zTerm);
152454  }
152455  if( !fts3SegReaderIsRootOnly(pReader) ){
152456  sqlite3_free(pReader->aNode);
152457  }
152458  sqlite3_blob_close(pReader->pBlob);
152459  }
152460  sqlite3_free(pReader);
152461 }
152462 
152463 /*
152464 ** Allocate a new SegReader object.
152465 */
152466 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
152467  int iAge, /* Segment "age". */
152468  int bLookup, /* True for a lookup only */
152469  sqlite3_int64 iStartLeaf, /* First leaf to traverse */
152470  sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
152471  sqlite3_int64 iEndBlock, /* Final block of segment */
152472  const char *zRoot, /* Buffer containing root node */
152473  int nRoot, /* Size of buffer containing root node */
152474  Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
152475 ){
152476  Fts3SegReader *pReader; /* Newly allocated SegReader object */
152477  int nExtra = 0; /* Bytes to allocate segment root node */
152478 
152479  assert( iStartLeaf<=iEndLeaf );
152480  if( iStartLeaf==0 ){
152481  nExtra = nRoot + FTS3_NODE_PADDING;
152482  }
152483 
152484  pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
152485  if( !pReader ){
152486  return SQLITE_NOMEM;
152487  }
152488  memset(pReader, 0, sizeof(Fts3SegReader));
152489  pReader->iIdx = iAge;
152490  pReader->bLookup = bLookup!=0;
152491  pReader->iStartBlock = iStartLeaf;
152492  pReader->iLeafEndBlock = iEndLeaf;
152493  pReader->iEndBlock = iEndBlock;
152494 
152495  if( nExtra ){
152496  /* The entire segment is stored in the root node. */
152497  pReader->aNode = (char *)&pReader[1];
152498  pReader->rootOnly = 1;
152499  pReader->nNode = nRoot;
152500  memcpy(pReader->aNode, zRoot, nRoot);
152501  memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
152502  }else{
152503  pReader->iCurrentBlock = iStartLeaf-1;
152504  }
152505  *ppReader = pReader;
152506  return SQLITE_OK;
152507 }
152508 
152509 /*
152510 ** This is a comparison function used as a qsort() callback when sorting
152511 ** an array of pending terms by term. This occurs as part of flushing
152512 ** the contents of the pending-terms hash table to the database.
152513 */
152514 static int SQLITE_CDECL fts3CompareElemByTerm(
152515  const void *lhs,
152516  const void *rhs
152517 ){
152518  char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
152519  char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
152520  int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
152521  int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
152522 
152523  int n = (n1<n2 ? n1 : n2);
152524  int c = memcmp(z1, z2, n);
152525  if( c==0 ){
152526  c = n1 - n2;
152527  }
152528  return c;
152529 }
152530 
152531 /*
152532 ** This function is used to allocate an Fts3SegReader that iterates through
152533 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
152534 **
152535 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
152536 ** through each term in the pending-terms table. Or, if isPrefixIter is
152537 ** non-zero, it iterates through each term and its prefixes. For example, if
152538 ** the pending terms hash table contains the terms "sqlite", "mysql" and
152539 ** "firebird", then the iterator visits the following 'terms' (in the order
152540 ** shown):
152541 **
152542 ** f fi fir fire fireb firebi firebir firebird
152543 ** m my mys mysq mysql
152544 ** s sq sql sqli sqlit sqlite
152545 **
152546 ** Whereas if isPrefixIter is zero, the terms visited are:
152547 **
152548 ** firebird mysql sqlite
152549 */
152550 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
152551  Fts3Table *p, /* Virtual table handle */
152552  int iIndex, /* Index for p->aIndex */
152553  const char *zTerm, /* Term to search for */
152554  int nTerm, /* Size of buffer zTerm */
152555  int bPrefix, /* True for a prefix iterator */
152556  Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
152557 ){
152558  Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
152559  Fts3HashElem *pE; /* Iterator variable */
152560  Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
152561  int nElem = 0; /* Size of array at aElem */
152562  int rc = SQLITE_OK; /* Return Code */
152563  Fts3Hash *pHash;
152564 
152565  pHash = &p->aIndex[iIndex].hPending;
152566  if( bPrefix ){
152567  int nAlloc = 0; /* Size of allocated array at aElem */
152568 
152569  for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
152570  char *zKey = (char *)fts3HashKey(pE);
152571  int nKey = fts3HashKeysize(pE);
152572  if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
152573  if( nElem==nAlloc ){
152574  Fts3HashElem **aElem2;
152575  nAlloc += 16;
152576  aElem2 = (Fts3HashElem **)sqlite3_realloc(
152577  aElem, nAlloc*sizeof(Fts3HashElem *)
152578  );
152579  if( !aElem2 ){
152580  rc = SQLITE_NOMEM;
152581  nElem = 0;
152582  break;
152583  }
152584  aElem = aElem2;
152585  }
152586 
152587  aElem[nElem++] = pE;
152588  }
152589  }
152590 
152591  /* If more than one term matches the prefix, sort the Fts3HashElem
152592  ** objects in term order using qsort(). This uses the same comparison
152593  ** callback as is used when flushing terms to disk.
152594  */
152595  if( nElem>1 ){
152596  qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
152597  }
152598 
152599  }else{
152600  /* The query is a simple term lookup that matches at most one term in
152601  ** the index. All that is required is a straight hash-lookup.
152602  **
152603  ** Because the stack address of pE may be accessed via the aElem pointer
152604  ** below, the "Fts3HashElem *pE" must be declared so that it is valid
152605  ** within this entire function, not just this "else{...}" block.
152606  */
152607  pE = fts3HashFindElem(pHash, zTerm, nTerm);
152608  if( pE ){
152609  aElem = &pE;
152610  nElem = 1;
152611  }
152612  }
152613 
152614  if( nElem>0 ){
152615  int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
152616  pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
152617  if( !pReader ){
152618  rc = SQLITE_NOMEM;
152619  }else{
152620  memset(pReader, 0, nByte);
152621  pReader->iIdx = 0x7FFFFFFF;
152622  pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
152623  memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
152624  }
152625  }
152626 
152627  if( bPrefix ){
152628  sqlite3_free(aElem);
152629  }
152630  *ppReader = pReader;
152631  return rc;
152632 }
152633 
152634 /*
152635 ** Compare the entries pointed to by two Fts3SegReader structures.
152636 ** Comparison is as follows:
152637 **
152638 ** 1) EOF is greater than not EOF.
152639 **
152640 ** 2) The current terms (if any) are compared using memcmp(). If one
152641 ** term is a prefix of another, the longer term is considered the
152642 ** larger.
152643 **
152644 ** 3) By segment age. An older segment is considered larger.
152645 */
152646 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
152647  int rc;
152648  if( pLhs->aNode && pRhs->aNode ){
152649  int rc2 = pLhs->nTerm - pRhs->nTerm;
152650  if( rc2<0 ){
152651  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
152652  }else{
152653  rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
152654  }
152655  if( rc==0 ){
152656  rc = rc2;
152657  }
152658  }else{
152659  rc = (pLhs->aNode==0) - (pRhs->aNode==0);
152660  }
152661  if( rc==0 ){
152662  rc = pRhs->iIdx - pLhs->iIdx;
152663  }
152664  assert( rc!=0 );
152665  return rc;
152666 }
152667 
152668 /*
152669 ** A different comparison function for SegReader structures. In this
152670 ** version, it is assumed that each SegReader points to an entry in
152671 ** a doclist for identical terms. Comparison is made as follows:
152672 **
152673 ** 1) EOF (end of doclist in this case) is greater than not EOF.
152674 **
152675 ** 2) By current docid.
152676 **
152677 ** 3) By segment age. An older segment is considered larger.
152678 */
152679 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
152680  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
152681  if( rc==0 ){
152682  if( pLhs->iDocid==pRhs->iDocid ){
152683  rc = pRhs->iIdx - pLhs->iIdx;
152684  }else{
152685  rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
152686  }
152687  }
152688  assert( pLhs->aNode && pRhs->aNode );
152689  return rc;
152690 }
152691 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
152692  int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
152693  if( rc==0 ){
152694  if( pLhs->iDocid==pRhs->iDocid ){
152695  rc = pRhs->iIdx - pLhs->iIdx;
152696  }else{
152697  rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
152698  }
152699  }
152700  assert( pLhs->aNode && pRhs->aNode );
152701  return rc;
152702 }
152703 
152704 /*
152705 ** Compare the term that the Fts3SegReader object passed as the first argument
152706 ** points to with the term specified by arguments zTerm and nTerm.
152707 **
152708 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
152709 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
152710 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
152711 */
152712 static int fts3SegReaderTermCmp(
152713  Fts3SegReader *pSeg, /* Segment reader object */
152714  const char *zTerm, /* Term to compare to */
152715  int nTerm /* Size of term zTerm in bytes */
152716 ){
152717  int res = 0;
152718  if( pSeg->aNode ){
152719  if( pSeg->nTerm>nTerm ){
152720  res = memcmp(pSeg->zTerm, zTerm, nTerm);
152721  }else{
152722  res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
152723  }
152724  if( res==0 ){
152725  res = pSeg->nTerm-nTerm;
152726  }
152727  }
152728  return res;
152729 }
152730 
152731 /*
152732 ** Argument apSegment is an array of nSegment elements. It is known that
152733 ** the final (nSegment-nSuspect) members are already in sorted order
152734 ** (according to the comparison function provided). This function shuffles
152735 ** the array around until all entries are in sorted order.
152736 */
152737 static void fts3SegReaderSort(
152738  Fts3SegReader **apSegment, /* Array to sort entries of */
152739  int nSegment, /* Size of apSegment array */
152740  int nSuspect, /* Unsorted entry count */
152741  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
152742 ){
152743  int i; /* Iterator variable */
152744 
152745  assert( nSuspect<=nSegment );
152746 
152747  if( nSuspect==nSegment ) nSuspect--;
152748  for(i=nSuspect-1; i>=0; i--){
152749  int j;
152750  for(j=i; j<(nSegment-1); j++){
152751  Fts3SegReader *pTmp;
152752  if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
152753  pTmp = apSegment[j+1];
152754  apSegment[j+1] = apSegment[j];
152755  apSegment[j] = pTmp;
152756  }
152757  }
152758 
152759 #ifndef NDEBUG
152760  /* Check that the list really is sorted now. */
152761  for(i=0; i<(nSuspect-1); i++){
152762  assert( xCmp(apSegment[i], apSegment[i+1])<0 );
152763  }
152764 #endif
152765 }
152766 
152767 /*
152768 ** Insert a record into the %_segments table.
152769 */
152770 static int fts3WriteSegment(
152771  Fts3Table *p, /* Virtual table handle */
152772  sqlite3_int64 iBlock, /* Block id for new block */
152773  char *z, /* Pointer to buffer containing block data */
152774  int n /* Size of buffer z in bytes */
152775 ){
152776  sqlite3_stmt *pStmt;
152777  int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
152778  if( rc==SQLITE_OK ){
152779  sqlite3_bind_int64(pStmt, 1, iBlock);
152780  sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
152781  sqlite3_step(pStmt);
152782  rc = sqlite3_reset(pStmt);
152783  }
152784  return rc;
152785 }
152786 
152787 /*
152788 ** Find the largest relative level number in the table. If successful, set
152789 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
152790 ** set *pnMax to zero and return an SQLite error code.
152791 */
152792 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
152793  int rc;
152794  int mxLevel = 0;
152795  sqlite3_stmt *pStmt = 0;
152796 
152797  rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
152798  if( rc==SQLITE_OK ){
152799  if( SQLITE_ROW==sqlite3_step(pStmt) ){
152800  mxLevel = sqlite3_column_int(pStmt, 0);
152801  }
152802  rc = sqlite3_reset(pStmt);
152803  }
152804  *pnMax = mxLevel;
152805  return rc;
152806 }
152807 
152808 /*
152809 ** Insert a record into the %_segdir table.
152810 */
152811 static int fts3WriteSegdir(
152812  Fts3Table *p, /* Virtual table handle */
152813  sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
152814  int iIdx, /* Value for "idx" field */
152815  sqlite3_int64 iStartBlock, /* Value for "start_block" field */
152816  sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
152817  sqlite3_int64 iEndBlock, /* Value for "end_block" field */
152818  sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
152819  char *zRoot, /* Blob value for "root" field */
152820  int nRoot /* Number of bytes in buffer zRoot */
152821 ){
152822  sqlite3_stmt *pStmt;
152823  int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
152824  if( rc==SQLITE_OK ){
152825  sqlite3_bind_int64(pStmt, 1, iLevel);
152826  sqlite3_bind_int(pStmt, 2, iIdx);
152827  sqlite3_bind_int64(pStmt, 3, iStartBlock);
152828  sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
152829  if( nLeafData==0 ){
152830  sqlite3_bind_int64(pStmt, 5, iEndBlock);
152831  }else{
152832  char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
152833  if( !zEnd ) return SQLITE_NOMEM;
152834  sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
152835  }
152836  sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
152837  sqlite3_step(pStmt);
152838  rc = sqlite3_reset(pStmt);
152839  }
152840  return rc;
152841 }
152842 
152843 /*
152844 ** Return the size of the common prefix (if any) shared by zPrev and
152845 ** zNext, in bytes. For example,
152846 **
152847 ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
152848 ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
152849 ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
152850 */
152851 static int fts3PrefixCompress(
152852  const char *zPrev, /* Buffer containing previous term */
152853  int nPrev, /* Size of buffer zPrev in bytes */
152854  const char *zNext, /* Buffer containing next term */
152855  int nNext /* Size of buffer zNext in bytes */
152856 ){
152857  int n;
152858  UNUSED_PARAMETER(nNext);
152859  for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
152860  return n;
152861 }
152862 
152863 /*
152864 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
152865 ** (according to memcmp) than the previous term.
152866 */
152867 static int fts3NodeAddTerm(
152868  Fts3Table *p, /* Virtual table handle */
152869  SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
152870  int isCopyTerm, /* True if zTerm/nTerm is transient */
152871  const char *zTerm, /* Pointer to buffer containing term */
152872  int nTerm /* Size of term in bytes */
152873 ){
152874  SegmentNode *pTree = *ppTree;
152875  int rc;
152876  SegmentNode *pNew;
152877 
152878  /* First try to append the term to the current node. Return early if
152879  ** this is possible.
152880  */
152881  if( pTree ){
152882  int nData = pTree->nData; /* Current size of node in bytes */
152883  int nReq = nData; /* Required space after adding zTerm */
152884  int nPrefix; /* Number of bytes of prefix compression */
152885  int nSuffix; /* Suffix length */
152886 
152887  nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
152888  nSuffix = nTerm-nPrefix;
152889 
152890  nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
152891  if( nReq<=p->nNodeSize || !pTree->zTerm ){
152892 
152893  if( nReq>p->nNodeSize ){
152894  /* An unusual case: this is the first term to be added to the node
152895  ** and the static node buffer (p->nNodeSize bytes) is not large
152896  ** enough. Use a separately malloced buffer instead This wastes
152897  ** p->nNodeSize bytes, but since this scenario only comes about when
152898  ** the database contain two terms that share a prefix of almost 2KB,
152899  ** this is not expected to be a serious problem.
152900  */
152901  assert( pTree->aData==(char *)&pTree[1] );
152902  pTree->aData = (char *)sqlite3_malloc(nReq);
152903  if( !pTree->aData ){
152904  return SQLITE_NOMEM;
152905  }
152906  }
152907 
152908  if( pTree->zTerm ){
152909  /* There is no prefix-length field for first term in a node */
152910  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
152911  }
152912 
152913  nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
152914  memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
152915  pTree->nData = nData + nSuffix;
152916  pTree->nEntry++;
152917 
152918  if( isCopyTerm ){
152919  if( pTree->nMalloc<nTerm ){
152920  char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
152921  if( !zNew ){
152922  return SQLITE_NOMEM;
152923  }
152924  pTree->nMalloc = nTerm*2;
152925  pTree->zMalloc = zNew;
152926  }
152927  pTree->zTerm = pTree->zMalloc;
152928  memcpy(pTree->zTerm, zTerm, nTerm);
152929  pTree->nTerm = nTerm;
152930  }else{
152931  pTree->zTerm = (char *)zTerm;
152932  pTree->nTerm = nTerm;
152933  }
152934  return SQLITE_OK;
152935  }
152936  }
152937 
152938  /* If control flows to here, it was not possible to append zTerm to the
152939  ** current node. Create a new node (a right-sibling of the current node).
152940  ** If this is the first node in the tree, the term is added to it.
152941  **
152942  ** Otherwise, the term is not added to the new node, it is left empty for
152943  ** now. Instead, the term is inserted into the parent of pTree. If pTree
152944  ** has no parent, one is created here.
152945  */
152946  pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
152947  if( !pNew ){
152948  return SQLITE_NOMEM;
152949  }
152950  memset(pNew, 0, sizeof(SegmentNode));
152951  pNew->nData = 1 + FTS3_VARINT_MAX;
152952  pNew->aData = (char *)&pNew[1];
152953 
152954  if( pTree ){
152955  SegmentNode *pParent = pTree->pParent;
152956  rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
152957  if( pTree->pParent==0 ){
152958  pTree->pParent = pParent;
152959  }
152960  pTree->pRight = pNew;
152961  pNew->pLeftmost = pTree->pLeftmost;
152962  pNew->pParent = pParent;
152963  pNew->zMalloc = pTree->zMalloc;
152964  pNew->nMalloc = pTree->nMalloc;
152965  pTree->zMalloc = 0;
152966  }else{
152967  pNew->pLeftmost = pNew;
152968  rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
152969  }
152970 
152971  *ppTree = pNew;
152972  return rc;
152973 }
152974 
152975 /*
152976 ** Helper function for fts3NodeWrite().
152977 */
152978 static int fts3TreeFinishNode(
152979  SegmentNode *pTree,
152980  int iHeight,
152981  sqlite3_int64 iLeftChild
152982 ){
152983  int nStart;
152984  assert( iHeight>=1 && iHeight<128 );
152985  nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
152986  pTree->aData[nStart] = (char)iHeight;
152987  sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
152988  return nStart;
152989 }
152990 
152991 /*
152992 ** Write the buffer for the segment node pTree and all of its peers to the
152993 ** database. Then call this function recursively to write the parent of
152994 ** pTree and its peers to the database.
152995 **
152996 ** Except, if pTree is a root node, do not write it to the database. Instead,
152997 ** set output variables *paRoot and *pnRoot to contain the root node.
152998 **
152999 ** If successful, SQLITE_OK is returned and output variable *piLast is
153000 ** set to the largest blockid written to the database (or zero if no
153001 ** blocks were written to the db). Otherwise, an SQLite error code is
153002 ** returned.
153003 */
153004 static int fts3NodeWrite(
153005  Fts3Table *p, /* Virtual table handle */
153006  SegmentNode *pTree, /* SegmentNode handle */
153007  int iHeight, /* Height of this node in tree */
153008  sqlite3_int64 iLeaf, /* Block id of first leaf node */
153009  sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
153010  sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
153011  char **paRoot, /* OUT: Data for root node */
153012  int *pnRoot /* OUT: Size of root node in bytes */
153013 ){
153014  int rc = SQLITE_OK;
153015 
153016  if( !pTree->pParent ){
153017  /* Root node of the tree. */
153018  int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
153019  *piLast = iFree-1;
153020  *pnRoot = pTree->nData - nStart;
153021  *paRoot = &pTree->aData[nStart];
153022  }else{
153023  SegmentNode *pIter;
153024  sqlite3_int64 iNextFree = iFree;
153025  sqlite3_int64 iNextLeaf = iLeaf;
153026  for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
153027  int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
153028  int nWrite = pIter->nData - nStart;
153029 
153030  rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
153031  iNextFree++;
153032  iNextLeaf += (pIter->nEntry+1);
153033  }
153034  if( rc==SQLITE_OK ){
153035  assert( iNextLeaf==iFree );
153036  rc = fts3NodeWrite(
153037  p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
153038  );
153039  }
153040  }
153041 
153042  return rc;
153043 }
153044 
153045 /*
153046 ** Free all memory allocations associated with the tree pTree.
153047 */
153048 static void fts3NodeFree(SegmentNode *pTree){
153049  if( pTree ){
153050  SegmentNode *p = pTree->pLeftmost;
153051  fts3NodeFree(p->pParent);
153052  while( p ){
153053  SegmentNode *pRight = p->pRight;
153054  if( p->aData!=(char *)&p[1] ){
153055  sqlite3_free(p->aData);
153056  }
153057  assert( pRight==0 || p->zMalloc==0 );
153058  sqlite3_free(p->zMalloc);
153059  sqlite3_free(p);
153060  p = pRight;
153061  }
153062  }
153063 }
153064 
153065 /*
153066 ** Add a term to the segment being constructed by the SegmentWriter object
153067 ** *ppWriter. When adding the first term to a segment, *ppWriter should
153068 ** be passed NULL. This function will allocate a new SegmentWriter object
153069 ** and return it via the input/output variable *ppWriter in this case.
153070 **
153071 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
153072 */
153073 static int fts3SegWriterAdd(
153074  Fts3Table *p, /* Virtual table handle */
153075  SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
153076  int isCopyTerm, /* True if buffer zTerm must be copied */
153077  const char *zTerm, /* Pointer to buffer containing term */
153078  int nTerm, /* Size of term in bytes */
153079  const char *aDoclist, /* Pointer to buffer containing doclist */
153080  int nDoclist /* Size of doclist in bytes */
153081 ){
153082  int nPrefix; /* Size of term prefix in bytes */
153083  int nSuffix; /* Size of term suffix in bytes */
153084  int nReq; /* Number of bytes required on leaf page */
153085  int nData;
153086  SegmentWriter *pWriter = *ppWriter;
153087 
153088  if( !pWriter ){
153089  int rc;
153090  sqlite3_stmt *pStmt;
153091 
153092  /* Allocate the SegmentWriter structure */
153093  pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
153094  if( !pWriter ) return SQLITE_NOMEM;
153095  memset(pWriter, 0, sizeof(SegmentWriter));
153096  *ppWriter = pWriter;
153097 
153098  /* Allocate a buffer in which to accumulate data */
153099  pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
153100  if( !pWriter->aData ) return SQLITE_NOMEM;
153101  pWriter->nSize = p->nNodeSize;
153102 
153103  /* Find the next free blockid in the %_segments table */
153104  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
153105  if( rc!=SQLITE_OK ) return rc;
153106  if( SQLITE_ROW==sqlite3_step(pStmt) ){
153107  pWriter->iFree = sqlite3_column_int64(pStmt, 0);
153108  pWriter->iFirst = pWriter->iFree;
153109  }
153110  rc = sqlite3_reset(pStmt);
153111  if( rc!=SQLITE_OK ) return rc;
153112  }
153113  nData = pWriter->nData;
153114 
153115  nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
153116  nSuffix = nTerm-nPrefix;
153117 
153118  /* Figure out how many bytes are required by this new entry */
153119  nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
153120  sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
153121  nSuffix + /* Term suffix */
153122  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
153123  nDoclist; /* Doclist data */
153124 
153125  if( nData>0 && nData+nReq>p->nNodeSize ){
153126  int rc;
153127 
153128  /* The current leaf node is full. Write it out to the database. */
153129  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
153130  if( rc!=SQLITE_OK ) return rc;
153131  p->nLeafAdd++;
153132 
153133  /* Add the current term to the interior node tree. The term added to
153134  ** the interior tree must:
153135  **
153136  ** a) be greater than the largest term on the leaf node just written
153137  ** to the database (still available in pWriter->zTerm), and
153138  **
153139  ** b) be less than or equal to the term about to be added to the new
153140  ** leaf node (zTerm/nTerm).
153141  **
153142  ** In other words, it must be the prefix of zTerm 1 byte longer than
153143  ** the common prefix (if any) of zTerm and pWriter->zTerm.
153144  */
153145  assert( nPrefix<nTerm );
153146  rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
153147  if( rc!=SQLITE_OK ) return rc;
153148 
153149  nData = 0;
153150  pWriter->nTerm = 0;
153151 
153152  nPrefix = 0;
153153  nSuffix = nTerm;
153154  nReq = 1 + /* varint containing prefix size */
153155  sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
153156  nTerm + /* Term suffix */
153157  sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
153158  nDoclist; /* Doclist data */
153159  }
153160 
153161  /* Increase the total number of bytes written to account for the new entry. */
153162  pWriter->nLeafData += nReq;
153163 
153164  /* If the buffer currently allocated is too small for this entry, realloc
153165  ** the buffer to make it large enough.
153166  */
153167  if( nReq>pWriter->nSize ){
153168  char *aNew = sqlite3_realloc(pWriter->aData, nReq);
153169  if( !aNew ) return SQLITE_NOMEM;
153170  pWriter->aData = aNew;
153171  pWriter->nSize = nReq;
153172  }
153173  assert( nData+nReq<=pWriter->nSize );
153174 
153175  /* Append the prefix-compressed term and doclist to the buffer. */
153176  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
153177  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
153178  memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
153179  nData += nSuffix;
153180  nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
153181  memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
153182  pWriter->nData = nData + nDoclist;
153183 
153184  /* Save the current term so that it can be used to prefix-compress the next.
153185  ** If the isCopyTerm parameter is true, then the buffer pointed to by
153186  ** zTerm is transient, so take a copy of the term data. Otherwise, just
153187  ** store a copy of the pointer.
153188  */
153189  if( isCopyTerm ){
153190  if( nTerm>pWriter->nMalloc ){
153191  char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
153192  if( !zNew ){
153193  return SQLITE_NOMEM;
153194  }
153195  pWriter->nMalloc = nTerm*2;
153196  pWriter->zMalloc = zNew;
153197  pWriter->zTerm = zNew;
153198  }
153199  assert( pWriter->zTerm==pWriter->zMalloc );
153200  memcpy(pWriter->zTerm, zTerm, nTerm);
153201  }else{
153202  pWriter->zTerm = (char *)zTerm;
153203  }
153204  pWriter->nTerm = nTerm;
153205 
153206  return SQLITE_OK;
153207 }
153208 
153209 /*
153210 ** Flush all data associated with the SegmentWriter object pWriter to the
153211 ** database. This function must be called after all terms have been added
153212 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
153213 ** returned. Otherwise, an SQLite error code.
153214 */
153215 static int fts3SegWriterFlush(
153216  Fts3Table *p, /* Virtual table handle */
153217  SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
153218  sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
153219  int iIdx /* Value for 'idx' column of %_segdir */
153220 ){
153221  int rc; /* Return code */
153222  if( pWriter->pTree ){
153223  sqlite3_int64 iLast = 0; /* Largest block id written to database */
153224  sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
153225  char *zRoot = NULL; /* Pointer to buffer containing root node */
153226  int nRoot = 0; /* Size of buffer zRoot */
153227 
153228  iLastLeaf = pWriter->iFree;
153229  rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
153230  if( rc==SQLITE_OK ){
153231  rc = fts3NodeWrite(p, pWriter->pTree, 1,
153232  pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
153233  }
153234  if( rc==SQLITE_OK ){
153235  rc = fts3WriteSegdir(p, iLevel, iIdx,
153236  pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
153237  }
153238  }else{
153239  /* The entire tree fits on the root node. Write it to the segdir table. */
153240  rc = fts3WriteSegdir(p, iLevel, iIdx,
153241  0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
153242  }
153243  p->nLeafAdd++;
153244  return rc;
153245 }
153246 
153247 /*
153248 ** Release all memory held by the SegmentWriter object passed as the
153249 ** first argument.
153250 */
153251 static void fts3SegWriterFree(SegmentWriter *pWriter){
153252  if( pWriter ){
153253  sqlite3_free(pWriter->aData);
153254  sqlite3_free(pWriter->zMalloc);
153255  fts3NodeFree(pWriter->pTree);
153256  sqlite3_free(pWriter);
153257  }
153258 }
153259 
153260 /*
153261 ** The first value in the apVal[] array is assumed to contain an integer.
153262 ** This function tests if there exist any documents with docid values that
153263 ** are different from that integer. i.e. if deleting the document with docid
153264 ** pRowid would mean the FTS3 table were empty.
153265 **
153266 ** If successful, *pisEmpty is set to true if the table is empty except for
153267 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
153268 ** error occurs, an SQLite error code is returned.
153269 */
153270 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
153271  sqlite3_stmt *pStmt;
153272  int rc;
153273  if( p->zContentTbl ){
153274  /* If using the content=xxx option, assume the table is never empty */
153275  *pisEmpty = 0;
153276  rc = SQLITE_OK;
153277  }else{
153278  rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
153279  if( rc==SQLITE_OK ){
153280  if( SQLITE_ROW==sqlite3_step(pStmt) ){
153281  *pisEmpty = sqlite3_column_int(pStmt, 0);
153282  }
153283  rc = sqlite3_reset(pStmt);
153284  }
153285  }
153286  return rc;
153287 }
153288 
153289 /*
153290 ** Set *pnMax to the largest segment level in the database for the index
153291 ** iIndex.
153292 **
153293 ** Segment levels are stored in the 'level' column of the %_segdir table.
153294 **
153295 ** Return SQLITE_OK if successful, or an SQLite error code if not.
153296 */
153297 static int fts3SegmentMaxLevel(
153298  Fts3Table *p,
153299  int iLangid,
153300  int iIndex,
153301  sqlite3_int64 *pnMax
153302 ){
153303  sqlite3_stmt *pStmt;
153304  int rc;
153305  assert( iIndex>=0 && iIndex<p->nIndex );
153306 
153307  /* Set pStmt to the compiled version of:
153308  **
153309  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
153310  **
153311  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
153312  */
153313  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
153314  if( rc!=SQLITE_OK ) return rc;
153315  sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
153316  sqlite3_bind_int64(pStmt, 2,
153317  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
153318  );
153319  if( SQLITE_ROW==sqlite3_step(pStmt) ){
153320  *pnMax = sqlite3_column_int64(pStmt, 0);
153321  }
153322  return sqlite3_reset(pStmt);
153323 }
153324 
153325 /*
153326 ** iAbsLevel is an absolute level that may be assumed to exist within
153327 ** the database. This function checks if it is the largest level number
153328 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
153329 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
153330 ** is returned. If an error occurs, an error code is returned and the
153331 ** final value of *pbMax is undefined.
153332 */
153333 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
153334 
153335  /* Set pStmt to the compiled version of:
153336  **
153337  ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
153338  **
153339  ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
153340  */
153341  sqlite3_stmt *pStmt;
153342  int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
153343  if( rc!=SQLITE_OK ) return rc;
153344  sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
153345  sqlite3_bind_int64(pStmt, 2,
153346  ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
153347  );
153348 
153349  *pbMax = 0;
153350  if( SQLITE_ROW==sqlite3_step(pStmt) ){
153351  *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
153352  }
153353  return sqlite3_reset(pStmt);
153354 }
153355 
153356 /*
153357 ** Delete all entries in the %_segments table associated with the segment
153358 ** opened with seg-reader pSeg. This function does not affect the contents
153359 ** of the %_segdir table.
153360 */
153361 static int fts3DeleteSegment(
153362  Fts3Table *p, /* FTS table handle */
153363  Fts3SegReader *pSeg /* Segment to delete */
153364 ){
153365  int rc = SQLITE_OK; /* Return code */
153366  if( pSeg->iStartBlock ){
153367  sqlite3_stmt *pDelete; /* SQL statement to delete rows */
153368  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
153369  if( rc==SQLITE_OK ){
153370  sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
153371  sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
153372  sqlite3_step(pDelete);
153373  rc = sqlite3_reset(pDelete);
153374  }
153375  }
153376  return rc;
153377 }
153378 
153379 /*
153380 ** This function is used after merging multiple segments into a single large
153381 ** segment to delete the old, now redundant, segment b-trees. Specifically,
153382 ** it:
153383 **
153384 ** 1) Deletes all %_segments entries for the segments associated with
153385 ** each of the SegReader objects in the array passed as the third
153386 ** argument, and
153387 **
153388 ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
153389 ** entries regardless of level if (iLevel<0).
153390 **
153391 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
153392 */
153393 static int fts3DeleteSegdir(
153394  Fts3Table *p, /* Virtual table handle */
153395  int iLangid, /* Language id */
153396  int iIndex, /* Index for p->aIndex */
153397  int iLevel, /* Level of %_segdir entries to delete */
153398  Fts3SegReader **apSegment, /* Array of SegReader objects */
153399  int nReader /* Size of array apSegment */
153400 ){
153401  int rc = SQLITE_OK; /* Return Code */
153402  int i; /* Iterator variable */
153403  sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
153404 
153405  for(i=0; rc==SQLITE_OK && i<nReader; i++){
153406  rc = fts3DeleteSegment(p, apSegment[i]);
153407  }
153408  if( rc!=SQLITE_OK ){
153409  return rc;
153410  }
153411 
153412  assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
153413  if( iLevel==FTS3_SEGCURSOR_ALL ){
153414  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
153415  if( rc==SQLITE_OK ){
153416  sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
153417  sqlite3_bind_int64(pDelete, 2,
153418  getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
153419  );
153420  }
153421  }else{
153422  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
153423  if( rc==SQLITE_OK ){
153425  pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
153426  );
153427  }
153428  }
153429 
153430  if( rc==SQLITE_OK ){
153431  sqlite3_step(pDelete);
153432  rc = sqlite3_reset(pDelete);
153433  }
153434 
153435  return rc;
153436 }
153437 
153438 /*
153439 ** When this function is called, buffer *ppList (size *pnList bytes) contains
153440 ** a position list that may (or may not) feature multiple columns. This
153441 ** function adjusts the pointer *ppList and the length *pnList so that they
153442 ** identify the subset of the position list that corresponds to column iCol.
153443 **
153444 ** If there are no entries in the input position list for column iCol, then
153445 ** *pnList is set to zero before returning.
153446 **
153447 ** If parameter bZero is non-zero, then any part of the input list following
153448 ** the end of the output list is zeroed before returning.
153449 */
153450 static void fts3ColumnFilter(
153451  int iCol, /* Column to filter on */
153452  int bZero, /* Zero out anything following *ppList */
153453  char **ppList, /* IN/OUT: Pointer to position list */
153454  int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
153455 ){
153456  char *pList = *ppList;
153457  int nList = *pnList;
153458  char *pEnd = &pList[nList];
153459  int iCurrent = 0;
153460  char *p = pList;
153461 
153462  assert( iCol>=0 );
153463  while( 1 ){
153464  char c = 0;
153465  while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
153466 
153467  if( iCol==iCurrent ){
153468  nList = (int)(p - pList);
153469  break;
153470  }
153471 
153472  nList -= (int)(p - pList);
153473  pList = p;
153474  if( nList==0 ){
153475  break;
153476  }
153477  p = &pList[1];
153478  p += fts3GetVarint32(p, &iCurrent);
153479  }
153480 
153481  if( bZero && &pList[nList]!=pEnd ){
153482  memset(&pList[nList], 0, pEnd - &pList[nList]);
153483  }
153484  *ppList = pList;
153485  *pnList = nList;
153486 }
153487 
153488 /*
153489 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
153490 ** existing data). Grow the buffer if required.
153491 **
153492 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
153493 ** trying to resize the buffer, return SQLITE_NOMEM.
153494 */
153495 static int fts3MsrBufferData(
153496  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
153497  char *pList,
153498  int nList
153499 ){
153500  if( nList>pMsr->nBuffer ){
153501  char *pNew;
153502  pMsr->nBuffer = nList*2;
153503  pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
153504  if( !pNew ) return SQLITE_NOMEM;
153505  pMsr->aBuffer = pNew;
153506  }
153507 
153508  memcpy(pMsr->aBuffer, pList, nList);
153509  return SQLITE_OK;
153510 }
153511 
153512 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
153513  Fts3Table *p, /* Virtual table handle */
153514  Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
153515  sqlite3_int64 *piDocid, /* OUT: Docid value */
153516  char **paPoslist, /* OUT: Pointer to position list */
153517  int *pnPoslist /* OUT: Size of position list in bytes */
153518 ){
153519  int nMerge = pMsr->nAdvance;
153520  Fts3SegReader **apSegment = pMsr->apSegment;
153521  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
153522  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
153523  );
153524 
153525  if( nMerge==0 ){
153526  *paPoslist = 0;
153527  return SQLITE_OK;
153528  }
153529 
153530  while( 1 ){
153531  Fts3SegReader *pSeg;
153532  pSeg = pMsr->apSegment[0];
153533 
153534  if( pSeg->pOffsetList==0 ){
153535  *paPoslist = 0;
153536  break;
153537  }else{
153538  int rc;
153539  char *pList;
153540  int nList;
153541  int j;
153542  sqlite3_int64 iDocid = apSegment[0]->iDocid;
153543 
153544  rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
153545  j = 1;
153546  while( rc==SQLITE_OK
153547  && j<nMerge
153548  && apSegment[j]->pOffsetList
153549  && apSegment[j]->iDocid==iDocid
153550  ){
153551  rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
153552  j++;
153553  }
153554  if( rc!=SQLITE_OK ) return rc;
153555  fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
153556 
153557  if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
153558  rc = fts3MsrBufferData(pMsr, pList, nList+1);
153559  if( rc!=SQLITE_OK ) return rc;
153560  assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
153561  pList = pMsr->aBuffer;
153562  }
153563 
153564  if( pMsr->iColFilter>=0 ){
153565  fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
153566  }
153567 
153568  if( nList>0 ){
153569  *paPoslist = pList;
153570  *piDocid = iDocid;
153571  *pnPoslist = nList;
153572  break;
153573  }
153574  }
153575  }
153576 
153577  return SQLITE_OK;
153578 }
153579 
153580 static int fts3SegReaderStart(
153581  Fts3Table *p, /* Virtual table handle */
153582  Fts3MultiSegReader *pCsr, /* Cursor object */
153583  const char *zTerm, /* Term searched for (or NULL) */
153584  int nTerm /* Length of zTerm in bytes */
153585 ){
153586  int i;
153587  int nSeg = pCsr->nSegment;
153588 
153589  /* If the Fts3SegFilter defines a specific term (or term prefix) to search
153590  ** for, then advance each segment iterator until it points to a term of
153591  ** equal or greater value than the specified term. This prevents many
153592  ** unnecessary merge/sort operations for the case where single segment
153593  ** b-tree leaf nodes contain more than one term.
153594  */
153595  for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
153596  int res = 0;
153597  Fts3SegReader *pSeg = pCsr->apSegment[i];
153598  do {
153599  int rc = fts3SegReaderNext(p, pSeg, 0);
153600  if( rc!=SQLITE_OK ) return rc;
153601  }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
153602 
153603  if( pSeg->bLookup && res!=0 ){
153604  fts3SegReaderSetEof(pSeg);
153605  }
153606  }
153607  fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
153608 
153609  return SQLITE_OK;
153610 }
153611 
153612 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
153613  Fts3Table *p, /* Virtual table handle */
153614  Fts3MultiSegReader *pCsr, /* Cursor object */
153615  Fts3SegFilter *pFilter /* Restrictions on range of iteration */
153616 ){
153617  pCsr->pFilter = pFilter;
153618  return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
153619 }
153620 
153621 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
153622  Fts3Table *p, /* Virtual table handle */
153623  Fts3MultiSegReader *pCsr, /* Cursor object */
153624  int iCol, /* Column to match on. */
153625  const char *zTerm, /* Term to iterate through a doclist for */
153626  int nTerm /* Number of bytes in zTerm */
153627 ){
153628  int i;
153629  int rc;
153630  int nSegment = pCsr->nSegment;
153631  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
153632  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
153633  );
153634 
153635  assert( pCsr->pFilter==0 );
153636  assert( zTerm && nTerm>0 );
153637 
153638  /* Advance each segment iterator until it points to the term zTerm/nTerm. */
153639  rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
153640  if( rc!=SQLITE_OK ) return rc;
153641 
153642  /* Determine how many of the segments actually point to zTerm/nTerm. */
153643  for(i=0; i<nSegment; i++){
153644  Fts3SegReader *pSeg = pCsr->apSegment[i];
153645  if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
153646  break;
153647  }
153648  }
153649  pCsr->nAdvance = i;
153650 
153651  /* Advance each of the segments to point to the first docid. */
153652  for(i=0; i<pCsr->nAdvance; i++){
153653  rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
153654  if( rc!=SQLITE_OK ) return rc;
153655  }
153656  fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
153657 
153658  assert( iCol<0 || iCol<p->nColumn );
153659  pCsr->iColFilter = iCol;
153660 
153661  return SQLITE_OK;
153662 }
153663 
153664 /*
153665 ** This function is called on a MultiSegReader that has been started using
153666 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
153667 ** have been made. Calling this function puts the MultiSegReader in such
153668 ** a state that if the next two calls are:
153669 **
153670 ** sqlite3Fts3SegReaderStart()
153671 ** sqlite3Fts3SegReaderStep()
153672 **
153673 ** then the entire doclist for the term is available in
153674 ** MultiSegReader.aDoclist/nDoclist.
153675 */
153676 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
153677  int i; /* Used to iterate through segment-readers */
153678 
153679  assert( pCsr->zTerm==0 );
153680  assert( pCsr->nTerm==0 );
153681  assert( pCsr->aDoclist==0 );
153682  assert( pCsr->nDoclist==0 );
153683 
153684  pCsr->nAdvance = 0;
153685  pCsr->bRestart = 1;
153686  for(i=0; i<pCsr->nSegment; i++){
153687  pCsr->apSegment[i]->pOffsetList = 0;
153688  pCsr->apSegment[i]->nOffsetList = 0;
153689  pCsr->apSegment[i]->iDocid = 0;
153690  }
153691 
153692  return SQLITE_OK;
153693 }
153694 
153695 
153696 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
153697  Fts3Table *p, /* Virtual table handle */
153698  Fts3MultiSegReader *pCsr /* Cursor object */
153699 ){
153700  int rc = SQLITE_OK;
153701 
153702  int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
153703  int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
153704  int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
153705  int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
153706  int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
153707  int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
153708 
153709  Fts3SegReader **apSegment = pCsr->apSegment;
153710  int nSegment = pCsr->nSegment;
153711  Fts3SegFilter *pFilter = pCsr->pFilter;
153712  int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
153713  p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
153714  );
153715 
153716  if( pCsr->nSegment==0 ) return SQLITE_OK;
153717 
153718  do {
153719  int nMerge;
153720  int i;
153721 
153722  /* Advance the first pCsr->nAdvance entries in the apSegment[] array
153723  ** forward. Then sort the list in order of current term again.
153724  */
153725  for(i=0; i<pCsr->nAdvance; i++){
153726  Fts3SegReader *pSeg = apSegment[i];
153727  if( pSeg->bLookup ){
153728  fts3SegReaderSetEof(pSeg);
153729  }else{
153730  rc = fts3SegReaderNext(p, pSeg, 0);
153731  }
153732  if( rc!=SQLITE_OK ) return rc;
153733  }
153734  fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
153735  pCsr->nAdvance = 0;
153736 
153737  /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
153738  assert( rc==SQLITE_OK );
153739  if( apSegment[0]->aNode==0 ) break;
153740 
153741  pCsr->nTerm = apSegment[0]->nTerm;
153742  pCsr->zTerm = apSegment[0]->zTerm;
153743 
153744  /* If this is a prefix-search, and if the term that apSegment[0] points
153745  ** to does not share a suffix with pFilter->zTerm/nTerm, then all
153746  ** required callbacks have been made. In this case exit early.
153747  **
153748  ** Similarly, if this is a search for an exact match, and the first term
153749  ** of segment apSegment[0] is not a match, exit early.
153750  */
153751  if( pFilter->zTerm && !isScan ){
153752  if( pCsr->nTerm<pFilter->nTerm
153753  || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
153754  || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
153755  ){
153756  break;
153757  }
153758  }
153759 
153760  nMerge = 1;
153761  while( nMerge<nSegment
153762  && apSegment[nMerge]->aNode
153763  && apSegment[nMerge]->nTerm==pCsr->nTerm
153764  && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
153765  ){
153766  nMerge++;
153767  }
153768 
153769  assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
153770  if( nMerge==1
153771  && !isIgnoreEmpty
153772  && !isFirst
153773  && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
153774  ){
153775  pCsr->nDoclist = apSegment[0]->nDoclist;
153776  if( fts3SegReaderIsPending(apSegment[0]) ){
153777  rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
153778  pCsr->aDoclist = pCsr->aBuffer;
153779  }else{
153780  pCsr->aDoclist = apSegment[0]->aDoclist;
153781  }
153782  if( rc==SQLITE_OK ) rc = SQLITE_ROW;
153783  }else{
153784  int nDoclist = 0; /* Size of doclist */
153785  sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
153786 
153787  /* The current term of the first nMerge entries in the array
153788  ** of Fts3SegReader objects is the same. The doclists must be merged
153789  ** and a single term returned with the merged doclist.
153790  */
153791  for(i=0; i<nMerge; i++){
153792  fts3SegReaderFirstDocid(p, apSegment[i]);
153793  }
153794  fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
153795  while( apSegment[0]->pOffsetList ){
153796  int j; /* Number of segments that share a docid */
153797  char *pList = 0;
153798  int nList = 0;
153799  int nByte;
153800  sqlite3_int64 iDocid = apSegment[0]->iDocid;
153801  fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
153802  j = 1;
153803  while( j<nMerge
153804  && apSegment[j]->pOffsetList
153805  && apSegment[j]->iDocid==iDocid
153806  ){
153807  fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
153808  j++;
153809  }
153810 
153811  if( isColFilter ){
153812  fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
153813  }
153814 
153815  if( !isIgnoreEmpty || nList>0 ){
153816 
153817  /* Calculate the 'docid' delta value to write into the merged
153818  ** doclist. */
153819  sqlite3_int64 iDelta;
153820  if( p->bDescIdx && nDoclist>0 ){
153821  iDelta = iPrev - iDocid;
153822  }else{
153823  iDelta = iDocid - iPrev;
153824  }
153825  assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
153826  assert( nDoclist>0 || iDelta==iDocid );
153827 
153828  nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
153829  if( nDoclist+nByte>pCsr->nBuffer ){
153830  char *aNew;
153831  pCsr->nBuffer = (nDoclist+nByte)*2;
153832  aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
153833  if( !aNew ){
153834  return SQLITE_NOMEM;
153835  }
153836  pCsr->aBuffer = aNew;
153837  }
153838 
153839  if( isFirst ){
153840  char *a = &pCsr->aBuffer[nDoclist];
153841  int nWrite;
153842 
153843  nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
153844  if( nWrite ){
153845  iPrev = iDocid;
153846  nDoclist += nWrite;
153847  }
153848  }else{
153849  nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
153850  iPrev = iDocid;
153851  if( isRequirePos ){
153852  memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
153853  nDoclist += nList;
153854  pCsr->aBuffer[nDoclist++] = '\0';
153855  }
153856  }
153857  }
153858 
153859  fts3SegReaderSort(apSegment, nMerge, j, xCmp);
153860  }
153861  if( nDoclist>0 ){
153862  pCsr->aDoclist = pCsr->aBuffer;
153863  pCsr->nDoclist = nDoclist;
153864  rc = SQLITE_ROW;
153865  }
153866  }
153867  pCsr->nAdvance = nMerge;
153868  }while( rc==SQLITE_OK );
153869 
153870  return rc;
153871 }
153872 
153873 
153874 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
153875  Fts3MultiSegReader *pCsr /* Cursor object */
153876 ){
153877  if( pCsr ){
153878  int i;
153879  for(i=0; i<pCsr->nSegment; i++){
153880  sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
153881  }
153882  sqlite3_free(pCsr->apSegment);
153883  sqlite3_free(pCsr->aBuffer);
153884 
153885  pCsr->nSegment = 0;
153886  pCsr->apSegment = 0;
153887  pCsr->aBuffer = 0;
153888  }
153889 }
153890 
153891 /*
153892 ** Decode the "end_block" field, selected by column iCol of the SELECT
153893 ** statement passed as the first argument.
153894 **
153895 ** The "end_block" field may contain either an integer, or a text field
153896 ** containing the text representation of two non-negative integers separated
153897 ** by one or more space (0x20) characters. In the first case, set *piEndBlock
153898 ** to the integer value and *pnByte to zero before returning. In the second,
153899 ** set *piEndBlock to the first value and *pnByte to the second.
153900 */
153901 static void fts3ReadEndBlockField(
153902  sqlite3_stmt *pStmt,
153903  int iCol,
153904  i64 *piEndBlock,
153905  i64 *pnByte
153906 ){
153907  const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
153908  if( zText ){
153909  int i;
153910  int iMul = 1;
153911  i64 iVal = 0;
153912  for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
153913  iVal = iVal*10 + (zText[i] - '0');
153914  }
153915  *piEndBlock = iVal;
153916  while( zText[i]==' ' ) i++;
153917  iVal = 0;
153918  if( zText[i]=='-' ){
153919  i++;
153920  iMul = -1;
153921  }
153922  for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
153923  iVal = iVal*10 + (zText[i] - '0');
153924  }
153925  *pnByte = (iVal * (i64)iMul);
153926  }
153927 }
153928 
153929 
153930 /*
153931 ** A segment of size nByte bytes has just been written to absolute level
153932 ** iAbsLevel. Promote any segments that should be promoted as a result.
153933 */
153934 static int fts3PromoteSegments(
153935  Fts3Table *p, /* FTS table handle */
153936  sqlite3_int64 iAbsLevel, /* Absolute level just updated */
153937  sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
153938 ){
153939  int rc = SQLITE_OK;
153940  sqlite3_stmt *pRange;
153941 
153942  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
153943 
153944  if( rc==SQLITE_OK ){
153945  int bOk = 0;
153946  i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
153947  i64 nLimit = (nByte*3)/2;
153948 
153949  /* Loop through all entries in the %_segdir table corresponding to
153950  ** segments in this index on levels greater than iAbsLevel. If there is
153951  ** at least one such segment, and it is possible to determine that all
153952  ** such segments are smaller than nLimit bytes in size, they will be
153953  ** promoted to level iAbsLevel. */
153954  sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
153955  sqlite3_bind_int64(pRange, 2, iLast);
153956  while( SQLITE_ROW==sqlite3_step(pRange) ){
153957  i64 nSize = 0, dummy;
153958  fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
153959  if( nSize<=0 || nSize>nLimit ){
153960  /* If nSize==0, then the %_segdir.end_block field does not not
153961  ** contain a size value. This happens if it was written by an
153962  ** old version of FTS. In this case it is not possible to determine
153963  ** the size of the segment, and so segment promotion does not
153964  ** take place. */
153965  bOk = 0;
153966  break;
153967  }
153968  bOk = 1;
153969  }
153970  rc = sqlite3_reset(pRange);
153971 
153972  if( bOk ){
153973  int iIdx = 0;
153974  sqlite3_stmt *pUpdate1 = 0;
153975  sqlite3_stmt *pUpdate2 = 0;
153976 
153977  if( rc==SQLITE_OK ){
153978  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
153979  }
153980  if( rc==SQLITE_OK ){
153981  rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
153982  }
153983 
153984  if( rc==SQLITE_OK ){
153985 
153986  /* Loop through all %_segdir entries for segments in this index with
153987  ** levels equal to or greater than iAbsLevel. As each entry is visited,
153988  ** updated it to set (level = -1) and (idx = N), where N is 0 for the
153989  ** oldest segment in the range, 1 for the next oldest, and so on.
153990  **
153991  ** In other words, move all segments being promoted to level -1,
153992  ** setting the "idx" fields as appropriate to keep them in the same
153993  ** order. The contents of level -1 (which is never used, except
153994  ** transiently here), will be moved back to level iAbsLevel below. */
153995  sqlite3_bind_int64(pRange, 1, iAbsLevel);
153996  while( SQLITE_ROW==sqlite3_step(pRange) ){
153997  sqlite3_bind_int(pUpdate1, 1, iIdx++);
153998  sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
153999  sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
154000  sqlite3_step(pUpdate1);
154001  rc = sqlite3_reset(pUpdate1);
154002  if( rc!=SQLITE_OK ){
154003  sqlite3_reset(pRange);
154004  break;
154005  }
154006  }
154007  }
154008  if( rc==SQLITE_OK ){
154009  rc = sqlite3_reset(pRange);
154010  }
154011 
154012  /* Move level -1 to level iAbsLevel */
154013  if( rc==SQLITE_OK ){
154014  sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
154015  sqlite3_step(pUpdate2);
154016  rc = sqlite3_reset(pUpdate2);
154017  }
154018  }
154019  }
154020 
154021 
154022  return rc;
154023 }
154024 
154025 /*
154026 ** Merge all level iLevel segments in the database into a single
154027 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
154028 ** single segment with a level equal to the numerically largest level
154029 ** currently present in the database.
154030 **
154031 ** If this function is called with iLevel<0, but there is only one
154032 ** segment in the database, SQLITE_DONE is returned immediately.
154033 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
154034 ** an SQLite error code is returned.
154035 */
154036 static int fts3SegmentMerge(
154037  Fts3Table *p,
154038  int iLangid, /* Language id to merge */
154039  int iIndex, /* Index in p->aIndex[] to merge */
154040  int iLevel /* Level to merge */
154041 ){
154042  int rc; /* Return code */
154043  int iIdx = 0; /* Index of new segment */
154044  sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
154045  SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
154046  Fts3SegFilter filter; /* Segment term filter condition */
154047  Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
154048  int bIgnoreEmpty = 0; /* True to ignore empty segments */
154049  i64 iMaxLevel = 0; /* Max level number for this index/langid */
154050 
154051  assert( iLevel==FTS3_SEGCURSOR_ALL
154052  || iLevel==FTS3_SEGCURSOR_PENDING
154053  || iLevel>=0
154054  );
154055  assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
154056  assert( iIndex>=0 && iIndex<p->nIndex );
154057 
154058  rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
154059  if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
154060 
154061  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
154062  rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
154063  if( rc!=SQLITE_OK ) goto finished;
154064  }
154065 
154066  if( iLevel==FTS3_SEGCURSOR_ALL ){
154067  /* This call is to merge all segments in the database to a single
154068  ** segment. The level of the new segment is equal to the numerically
154069  ** greatest segment level currently present in the database for this
154070  ** index. The idx of the new segment is always 0. */
154071  if( csr.nSegment==1 && 0==fts3SegReaderIsPending(csr.apSegment[0]) ){
154072  rc = SQLITE_DONE;
154073  goto finished;
154074  }
154075  iNewLevel = iMaxLevel;
154076  bIgnoreEmpty = 1;
154077 
154078  }else{
154079  /* This call is to merge all segments at level iLevel. find the next
154080  ** available segment index at level iLevel+1. The call to
154081  ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
154082  ** a single iLevel+2 segment if necessary. */
154083  assert( FTS3_SEGCURSOR_PENDING==-1 );
154084  iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
154085  rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
154086  bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
154087  }
154088  if( rc!=SQLITE_OK ) goto finished;
154089 
154090  assert( csr.nSegment>0 );
154091  assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
154092  assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
154093 
154094  memset(&filter, 0, sizeof(Fts3SegFilter));
154095  filter.flags = FTS3_SEGMENT_REQUIRE_POS;
154096  filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
154097 
154098  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
154099  while( SQLITE_OK==rc ){
154100  rc = sqlite3Fts3SegReaderStep(p, &csr);
154101  if( rc!=SQLITE_ROW ) break;
154102  rc = fts3SegWriterAdd(p, &pWriter, 1,
154103  csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
154104  }
154105  if( rc!=SQLITE_OK ) goto finished;
154106  assert( pWriter || bIgnoreEmpty );
154107 
154108  if( iLevel!=FTS3_SEGCURSOR_PENDING ){
154109  rc = fts3DeleteSegdir(
154110  p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
154111  );
154112  if( rc!=SQLITE_OK ) goto finished;
154113  }
154114  if( pWriter ){
154115  rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
154116  if( rc==SQLITE_OK ){
154117  if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
154118  rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
154119  }
154120  }
154121  }
154122 
154123  finished:
154124  fts3SegWriterFree(pWriter);
154125  sqlite3Fts3SegReaderFinish(&csr);
154126  return rc;
154127 }
154128 
154129 
154130 /*
154131 ** Flush the contents of pendingTerms to level 0 segments.
154132 */
154133 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
154134  int rc = SQLITE_OK;
154135  int i;
154136 
154137  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
154138  rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
154139  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
154140  }
154141  sqlite3Fts3PendingTermsClear(p);
154142 
154143  /* Determine the auto-incr-merge setting if unknown. If enabled,
154144  ** estimate the number of leaf blocks of content to be written
154145  */
154146  if( rc==SQLITE_OK && p->bHasStat
154147  && p->nAutoincrmerge==0xff && p->nLeafAdd>0
154148  ){
154149  sqlite3_stmt *pStmt = 0;
154150  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
154151  if( rc==SQLITE_OK ){
154152  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
154153  rc = sqlite3_step(pStmt);
154154  if( rc==SQLITE_ROW ){
154155  p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
154156  if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
154157  }else if( rc==SQLITE_DONE ){
154158  p->nAutoincrmerge = 0;
154159  }
154160  rc = sqlite3_reset(pStmt);
154161  }
154162  }
154163  return rc;
154164 }
154165 
154166 /*
154167 ** Encode N integers as varints into a blob.
154168 */
154169 static void fts3EncodeIntArray(
154170  int N, /* The number of integers to encode */
154171  u32 *a, /* The integer values */
154172  char *zBuf, /* Write the BLOB here */
154173  int *pNBuf /* Write number of bytes if zBuf[] used here */
154174 ){
154175  int i, j;
154176  for(i=j=0; i<N; i++){
154177  j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
154178  }
154179  *pNBuf = j;
154180 }
154181 
154182 /*
154183 ** Decode a blob of varints into N integers
154184 */
154185 static void fts3DecodeIntArray(
154186  int N, /* The number of integers to decode */
154187  u32 *a, /* Write the integer values */
154188  const char *zBuf, /* The BLOB containing the varints */
154189  int nBuf /* size of the BLOB */
154190 ){
154191  int i, j;
154192  UNUSED_PARAMETER(nBuf);
154193  for(i=j=0; i<N; i++){
154194  sqlite3_int64 x;
154195  j += sqlite3Fts3GetVarint(&zBuf[j], &x);
154196  assert(j<=nBuf);
154197  a[i] = (u32)(x & 0xffffffff);
154198  }
154199 }
154200 
154201 /*
154202 ** Insert the sizes (in tokens) for each column of the document
154203 ** with docid equal to p->iPrevDocid. The sizes are encoded as
154204 ** a blob of varints.
154205 */
154206 static void fts3InsertDocsize(
154207  int *pRC, /* Result code */
154208  Fts3Table *p, /* Table into which to insert */
154209  u32 *aSz /* Sizes of each column, in tokens */
154210 ){
154211  char *pBlob; /* The BLOB encoding of the document size */
154212  int nBlob; /* Number of bytes in the BLOB */
154213  sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
154214  int rc; /* Result code from subfunctions */
154215 
154216  if( *pRC ) return;
154217  pBlob = sqlite3_malloc( 10*p->nColumn );
154218  if( pBlob==0 ){
154219  *pRC = SQLITE_NOMEM;
154220  return;
154221  }
154222  fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
154223  rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
154224  if( rc ){
154225  sqlite3_free(pBlob);
154226  *pRC = rc;
154227  return;
154228  }
154229  sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
154230  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
154231  sqlite3_step(pStmt);
154232  *pRC = sqlite3_reset(pStmt);
154233 }
154234 
154235 /*
154236 ** Record 0 of the %_stat table contains a blob consisting of N varints,
154237 ** where N is the number of user defined columns in the fts3 table plus
154238 ** two. If nCol is the number of user defined columns, then values of the
154239 ** varints are set as follows:
154240 **
154241 ** Varint 0: Total number of rows in the table.
154242 **
154243 ** Varint 1..nCol: For each column, the total number of tokens stored in
154244 ** the column for all rows of the table.
154245 **
154246 ** Varint 1+nCol: The total size, in bytes, of all text values in all
154247 ** columns of all rows of the table.
154248 **
154249 */
154250 static void fts3UpdateDocTotals(
154251  int *pRC, /* The result code */
154252  Fts3Table *p, /* Table being updated */
154253  u32 *aSzIns, /* Size increases */
154254  u32 *aSzDel, /* Size decreases */
154255  int nChng /* Change in the number of documents */
154256 ){
154257  char *pBlob; /* Storage for BLOB written into %_stat */
154258  int nBlob; /* Size of BLOB written into %_stat */
154259  u32 *a; /* Array of integers that becomes the BLOB */
154260  sqlite3_stmt *pStmt; /* Statement for reading and writing */
154261  int i; /* Loop counter */
154262  int rc; /* Result code from subfunctions */
154263 
154264  const int nStat = p->nColumn+2;
154265 
154266  if( *pRC ) return;
154267  a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
154268  if( a==0 ){
154269  *pRC = SQLITE_NOMEM;
154270  return;
154271  }
154272  pBlob = (char*)&a[nStat];
154273  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
154274  if( rc ){
154275  sqlite3_free(a);
154276  *pRC = rc;
154277  return;
154278  }
154279  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
154280  if( sqlite3_step(pStmt)==SQLITE_ROW ){
154281  fts3DecodeIntArray(nStat, a,
154282  sqlite3_column_blob(pStmt, 0),
154283  sqlite3_column_bytes(pStmt, 0));
154284  }else{
154285  memset(a, 0, sizeof(u32)*(nStat) );
154286  }
154287  rc = sqlite3_reset(pStmt);
154288  if( rc!=SQLITE_OK ){
154289  sqlite3_free(a);
154290  *pRC = rc;
154291  return;
154292  }
154293  if( nChng<0 && a[0]<(u32)(-nChng) ){
154294  a[0] = 0;
154295  }else{
154296  a[0] += nChng;
154297  }
154298  for(i=0; i<p->nColumn+1; i++){
154299  u32 x = a[i+1];
154300  if( x+aSzIns[i] < aSzDel[i] ){
154301  x = 0;
154302  }else{
154303  x = x + aSzIns[i] - aSzDel[i];
154304  }
154305  a[i+1] = x;
154306  }
154307  fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
154308  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
154309  if( rc ){
154310  sqlite3_free(a);
154311  *pRC = rc;
154312  return;
154313  }
154314  sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
154315  sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
154316  sqlite3_step(pStmt);
154317  *pRC = sqlite3_reset(pStmt);
154318  sqlite3_free(a);
154319 }
154320 
154321 /*
154322 ** Merge the entire database so that there is one segment for each
154323 ** iIndex/iLangid combination.
154324 */
154325 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
154326  int bSeenDone = 0;
154327  int rc;
154328  sqlite3_stmt *pAllLangid = 0;
154329 
154330  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
154331  if( rc==SQLITE_OK ){
154332  int rc2;
154333  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
154334  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
154335  while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
154336  int i;
154337  int iLangid = sqlite3_column_int(pAllLangid, 0);
154338  for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
154339  rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
154340  if( rc==SQLITE_DONE ){
154341  bSeenDone = 1;
154342  rc = SQLITE_OK;
154343  }
154344  }
154345  }
154346  rc2 = sqlite3_reset(pAllLangid);
154347  if( rc==SQLITE_OK ) rc = rc2;
154348  }
154349 
154350  sqlite3Fts3SegmentsClose(p);
154351  sqlite3Fts3PendingTermsClear(p);
154352 
154353  return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
154354 }
154355 
154356 /*
154357 ** This function is called when the user executes the following statement:
154358 **
154359 ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
154360 **
154361 ** The entire FTS index is discarded and rebuilt. If the table is one
154362 ** created using the content=xxx option, then the new index is based on
154363 ** the current contents of the xxx table. Otherwise, it is rebuilt based
154364 ** on the contents of the %_content table.
154365 */
154366 static int fts3DoRebuild(Fts3Table *p){
154367  int rc; /* Return Code */
154368 
154369  rc = fts3DeleteAll(p, 0);
154370  if( rc==SQLITE_OK ){
154371  u32 *aSz = 0;
154372  u32 *aSzIns = 0;
154373  u32 *aSzDel = 0;
154374  sqlite3_stmt *pStmt = 0;
154375  int nEntry = 0;
154376 
154377  /* Compose and prepare an SQL statement to loop through the content table */
154378  char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
154379  if( !zSql ){
154380  rc = SQLITE_NOMEM;
154381  }else{
154382  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
154383  sqlite3_free(zSql);
154384  }
154385 
154386  if( rc==SQLITE_OK ){
154387  int nByte = sizeof(u32) * (p->nColumn+1)*3;
154388  aSz = (u32 *)sqlite3_malloc(nByte);
154389  if( aSz==0 ){
154390  rc = SQLITE_NOMEM;
154391  }else{
154392  memset(aSz, 0, nByte);
154393  aSzIns = &aSz[p->nColumn+1];
154394  aSzDel = &aSzIns[p->nColumn+1];
154395  }
154396  }
154397 
154398  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
154399  int iCol;
154400  int iLangid = langidFromSelect(p, pStmt);
154401  rc = fts3PendingTermsDocid(p, 0, iLangid, sqlite3_column_int64(pStmt, 0));
154402  memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
154403  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
154404  if( p->abNotindexed[iCol]==0 ){
154405  const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
154406  rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
154407  aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
154408  }
154409  }
154410  if( p->bHasDocsize ){
154411  fts3InsertDocsize(&rc, p, aSz);
154412  }
154413  if( rc!=SQLITE_OK ){
154414  sqlite3_finalize(pStmt);
154415  pStmt = 0;
154416  }else{
154417  nEntry++;
154418  for(iCol=0; iCol<=p->nColumn; iCol++){
154419  aSzIns[iCol] += aSz[iCol];
154420  }
154421  }
154422  }
154423  if( p->bFts4 ){
154424  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
154425  }
154426  sqlite3_free(aSz);
154427 
154428  if( pStmt ){
154429  int rc2 = sqlite3_finalize(pStmt);
154430  if( rc==SQLITE_OK ){
154431  rc = rc2;
154432  }
154433  }
154434  }
154435 
154436  return rc;
154437 }
154438 
154439 
154440 /*
154441 ** This function opens a cursor used to read the input data for an
154442 ** incremental merge operation. Specifically, it opens a cursor to scan
154443 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
154444 ** level iAbsLevel.
154445 */
154446 static int fts3IncrmergeCsr(
154447  Fts3Table *p, /* FTS3 table handle */
154448  sqlite3_int64 iAbsLevel, /* Absolute level to open */
154449  int nSeg, /* Number of segments to merge */
154450  Fts3MultiSegReader *pCsr /* Cursor object to populate */
154451 ){
154452  int rc; /* Return Code */
154453  sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
154454  int nByte; /* Bytes allocated at pCsr->apSegment[] */
154455 
154456  /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
154457  memset(pCsr, 0, sizeof(*pCsr));
154458  nByte = sizeof(Fts3SegReader *) * nSeg;
154459  pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
154460 
154461  if( pCsr->apSegment==0 ){
154462  rc = SQLITE_NOMEM;
154463  }else{
154464  memset(pCsr->apSegment, 0, nByte);
154465  rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
154466  }
154467  if( rc==SQLITE_OK ){
154468  int i;
154469  int rc2;
154470  sqlite3_bind_int64(pStmt, 1, iAbsLevel);
154471  assert( pCsr->nSegment==0 );
154472  for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
154473  rc = sqlite3Fts3SegReaderNew(i, 0,
154474  sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
154475  sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
154476  sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
154477  sqlite3_column_blob(pStmt, 4), /* segdir.root */
154478  sqlite3_column_bytes(pStmt, 4), /* segdir.root */
154479  &pCsr->apSegment[i]
154480  );
154481  pCsr->nSegment++;
154482  }
154483  rc2 = sqlite3_reset(pStmt);
154484  if( rc==SQLITE_OK ) rc = rc2;
154485  }
154486 
154487  return rc;
154488 }
154489 
154490 typedef struct IncrmergeWriter IncrmergeWriter;
154491 typedef struct NodeWriter NodeWriter;
154492 typedef struct Blob Blob;
154493 typedef struct NodeReader NodeReader;
154494 
154495 /*
154496 ** An instance of the following structure is used as a dynamic buffer
154497 ** to build up nodes or other blobs of data in.
154498 **
154499 ** The function blobGrowBuffer() is used to extend the allocation.
154500 */
154501 struct Blob {
154502  char *a; /* Pointer to allocation */
154503  int n; /* Number of valid bytes of data in a[] */
154504  int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
154505 };
154506 
154507 /*
154508 ** This structure is used to build up buffers containing segment b-tree
154509 ** nodes (blocks).
154510 */
154511 struct NodeWriter {
154512  sqlite3_int64 iBlock; /* Current block id */
154513  Blob key; /* Last key written to the current block */
154514  Blob block; /* Current block image */
154515 };
154516 
154517 /*
154518 ** An object of this type contains the state required to create or append
154519 ** to an appendable b-tree segment.
154520 */
154521 struct IncrmergeWriter {
154522  int nLeafEst; /* Space allocated for leaf blocks */
154523  int nWork; /* Number of leaf pages flushed */
154524  sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
154525  int iIdx; /* Index of *output* segment in iAbsLevel+1 */
154526  sqlite3_int64 iStart; /* Block number of first allocated block */
154527  sqlite3_int64 iEnd; /* Block number of last allocated block */
154528  sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
154529  u8 bNoLeafData; /* If true, store 0 for segment size */
154530  NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
154531 };
154532 
154533 /*
154534 ** An object of the following type is used to read data from a single
154535 ** FTS segment node. See the following functions:
154536 **
154537 ** nodeReaderInit()
154538 ** nodeReaderNext()
154539 ** nodeReaderRelease()
154540 */
154541 struct NodeReader {
154542  const char *aNode;
154543  int nNode;
154544  int iOff; /* Current offset within aNode[] */
154545 
154546  /* Output variables. Containing the current node entry. */
154547  sqlite3_int64 iChild; /* Pointer to child node */
154548  Blob term; /* Current term */
154549  const char *aDoclist; /* Pointer to doclist */
154550  int nDoclist; /* Size of doclist in bytes */
154551 };
154552 
154553 /*
154554 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
154555 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
154556 ** bytes in size, extend (realloc) it to be so.
154557 **
154558 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
154559 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
154560 ** to reflect the new size of the pBlob->a[] buffer.
154561 */
154562 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
154563  if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
154564  int nAlloc = nMin;
154565  char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
154566  if( a ){
154567  pBlob->nAlloc = nAlloc;
154568  pBlob->a = a;
154569  }else{
154570  *pRc = SQLITE_NOMEM;
154571  }
154572  }
154573 }
154574 
154575 /*
154576 ** Attempt to advance the node-reader object passed as the first argument to
154577 ** the next entry on the node.
154578 **
154579 ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
154580 ** Otherwise return SQLITE_OK. If there is no next entry on the node
154581 ** (e.g. because the current entry is the last) set NodeReader->aNode to
154582 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
154583 ** variables for the new entry.
154584 */
154585 static int nodeReaderNext(NodeReader *p){
154586  int bFirst = (p->term.n==0); /* True for first term on the node */
154587  int nPrefix = 0; /* Bytes to copy from previous term */
154588  int nSuffix = 0; /* Bytes to append to the prefix */
154589  int rc = SQLITE_OK; /* Return code */
154590 
154591  assert( p->aNode );
154592  if( p->iChild && bFirst==0 ) p->iChild++;
154593  if( p->iOff>=p->nNode ){
154594  /* EOF */
154595  p->aNode = 0;
154596  }else{
154597  if( bFirst==0 ){
154598  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
154599  }
154600  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
154601 
154602  blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
154603  if( rc==SQLITE_OK ){
154604  memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
154605  p->term.n = nPrefix+nSuffix;
154606  p->iOff += nSuffix;
154607  if( p->iChild==0 ){
154608  p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
154609  p->aDoclist = &p->aNode[p->iOff];
154610  p->iOff += p->nDoclist;
154611  }
154612  }
154613  }
154614 
154615  assert( p->iOff<=p->nNode );
154616 
154617  return rc;
154618 }
154619 
154620 /*
154621 ** Release all dynamic resources held by node-reader object *p.
154622 */
154623 static void nodeReaderRelease(NodeReader *p){
154624  sqlite3_free(p->term.a);
154625 }
154626 
154627 /*
154628 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
154629 **
154630 ** If successful, SQLITE_OK is returned and the NodeReader object set to
154631 ** point to the first entry on the node (if any). Otherwise, an SQLite
154632 ** error code is returned.
154633 */
154634 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
154635  memset(p, 0, sizeof(NodeReader));
154636  p->aNode = aNode;
154637  p->nNode = nNode;
154638 
154639  /* Figure out if this is a leaf or an internal node. */
154640  if( p->aNode[0] ){
154641  /* An internal node. */
154642  p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
154643  }else{
154644  p->iOff = 1;
154645  }
154646 
154647  return nodeReaderNext(p);
154648 }
154649 
154650 /*
154651 ** This function is called while writing an FTS segment each time a leaf o
154652 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
154653 ** to be greater than the largest key on the node just written, but smaller
154654 ** than or equal to the first key that will be written to the next leaf
154655 ** node.
154656 **
154657 ** The block id of the leaf node just written to disk may be found in
154658 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
154659 */
154660 static int fts3IncrmergePush(
154661  Fts3Table *p, /* Fts3 table handle */
154662  IncrmergeWriter *pWriter, /* Writer object */
154663  const char *zTerm, /* Term to write to internal node */
154664  int nTerm /* Bytes at zTerm */
154665 ){
154666  sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
154667  int iLayer;
154668 
154669  assert( nTerm>0 );
154670  for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
154671  sqlite3_int64 iNextPtr = 0;
154672  NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
154673  int rc = SQLITE_OK;
154674  int nPrefix;
154675  int nSuffix;
154676  int nSpace;
154677 
154678  /* Figure out how much space the key will consume if it is written to
154679  ** the current node of layer iLayer. Due to the prefix compression,
154680  ** the space required changes depending on which node the key is to
154681  ** be added to. */
154682  nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
154683  nSuffix = nTerm - nPrefix;
154684  nSpace = sqlite3Fts3VarintLen(nPrefix);
154685  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
154686 
154687  if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
154688  /* If the current node of layer iLayer contains zero keys, or if adding
154689  ** the key to it will not cause it to grow to larger than nNodeSize
154690  ** bytes in size, write the key here. */
154691 
154692  Blob *pBlk = &pNode->block;
154693  if( pBlk->n==0 ){
154694  blobGrowBuffer(pBlk, p->nNodeSize, &rc);
154695  if( rc==SQLITE_OK ){
154696  pBlk->a[0] = (char)iLayer;
154697  pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
154698  }
154699  }
154700  blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
154701  blobGrowBuffer(&pNode->key, nTerm, &rc);
154702 
154703  if( rc==SQLITE_OK ){
154704  if( pNode->key.n ){
154705  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
154706  }
154707  pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
154708  memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
154709  pBlk->n += nSuffix;
154710 
154711  memcpy(pNode->key.a, zTerm, nTerm);
154712  pNode->key.n = nTerm;
154713  }
154714  }else{
154715  /* Otherwise, flush the current node of layer iLayer to disk.
154716  ** Then allocate a new, empty sibling node. The key will be written
154717  ** into the parent of this node. */
154718  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
154719 
154720  assert( pNode->block.nAlloc>=p->nNodeSize );
154721  pNode->block.a[0] = (char)iLayer;
154722  pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
154723 
154724  iNextPtr = pNode->iBlock;
154725  pNode->iBlock++;
154726  pNode->key.n = 0;
154727  }
154728 
154729  if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
154730  iPtr = iNextPtr;
154731  }
154732 
154733  assert( 0 );
154734  return 0;
154735 }
154736 
154737 /*
154738 ** Append a term and (optionally) doclist to the FTS segment node currently
154739 ** stored in blob *pNode. The node need not contain any terms, but the
154740 ** header must be written before this function is called.
154741 **
154742 ** A node header is a single 0x00 byte for a leaf node, or a height varint
154743 ** followed by the left-hand-child varint for an internal node.
154744 **
154745 ** The term to be appended is passed via arguments zTerm/nTerm. For a
154746 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
154747 ** node, both aDoclist and nDoclist must be passed 0.
154748 **
154749 ** If the size of the value in blob pPrev is zero, then this is the first
154750 ** term written to the node. Otherwise, pPrev contains a copy of the
154751 ** previous term. Before this function returns, it is updated to contain a
154752 ** copy of zTerm/nTerm.
154753 **
154754 ** It is assumed that the buffer associated with pNode is already large
154755 ** enough to accommodate the new entry. The buffer associated with pPrev
154756 ** is extended by this function if requrired.
154757 **
154758 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
154759 ** returned. Otherwise, SQLITE_OK.
154760 */
154761 static int fts3AppendToNode(
154762  Blob *pNode, /* Current node image to append to */
154763  Blob *pPrev, /* Buffer containing previous term written */
154764  const char *zTerm, /* New term to write */
154765  int nTerm, /* Size of zTerm in bytes */
154766  const char *aDoclist, /* Doclist (or NULL) to write */
154767  int nDoclist /* Size of aDoclist in bytes */
154768 ){
154769  int rc = SQLITE_OK; /* Return code */
154770  int bFirst = (pPrev->n==0); /* True if this is the first term written */
154771  int nPrefix; /* Size of term prefix in bytes */
154772  int nSuffix; /* Size of term suffix in bytes */
154773 
154774  /* Node must have already been started. There must be a doclist for a
154775  ** leaf node, and there must not be a doclist for an internal node. */
154776  assert( pNode->n>0 );
154777  assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
154778 
154779  blobGrowBuffer(pPrev, nTerm, &rc);
154780  if( rc!=SQLITE_OK ) return rc;
154781 
154782  nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
154783  nSuffix = nTerm - nPrefix;
154784  memcpy(pPrev->a, zTerm, nTerm);
154785  pPrev->n = nTerm;
154786 
154787  if( bFirst==0 ){
154788  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
154789  }
154790  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
154791  memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
154792  pNode->n += nSuffix;
154793 
154794  if( aDoclist ){
154795  pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
154796  memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
154797  pNode->n += nDoclist;
154798  }
154799 
154800  assert( pNode->n<=pNode->nAlloc );
154801 
154802  return SQLITE_OK;
154803 }
154804 
154805 /*
154806 ** Append the current term and doclist pointed to by cursor pCsr to the
154807 ** appendable b-tree segment opened for writing by pWriter.
154808 **
154809 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
154810 */
154811 static int fts3IncrmergeAppend(
154812  Fts3Table *p, /* Fts3 table handle */
154813  IncrmergeWriter *pWriter, /* Writer object */
154814  Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
154815 ){
154816  const char *zTerm = pCsr->zTerm;
154817  int nTerm = pCsr->nTerm;
154818  const char *aDoclist = pCsr->aDoclist;
154819  int nDoclist = pCsr->nDoclist;
154820  int rc = SQLITE_OK; /* Return code */
154821  int nSpace; /* Total space in bytes required on leaf */
154822  int nPrefix; /* Size of prefix shared with previous term */
154823  int nSuffix; /* Size of suffix (nTerm - nPrefix) */
154824  NodeWriter *pLeaf; /* Object used to write leaf nodes */
154825 
154826  pLeaf = &pWriter->aNodeWriter[0];
154827  nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
154828  nSuffix = nTerm - nPrefix;
154829 
154830  nSpace = sqlite3Fts3VarintLen(nPrefix);
154831  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
154832  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
154833 
154834  /* If the current block is not empty, and if adding this term/doclist
154835  ** to the current block would make it larger than Fts3Table.nNodeSize
154836  ** bytes, write this block out to the database. */
154837  if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
154838  rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
154839  pWriter->nWork++;
154840 
154841  /* Add the current term to the parent node. The term added to the
154842  ** parent must:
154843  **
154844  ** a) be greater than the largest term on the leaf node just written
154845  ** to the database (still available in pLeaf->key), and
154846  **
154847  ** b) be less than or equal to the term about to be added to the new
154848  ** leaf node (zTerm/nTerm).
154849  **
154850  ** In other words, it must be the prefix of zTerm 1 byte longer than
154851  ** the common prefix (if any) of zTerm and pWriter->zTerm.
154852  */
154853  if( rc==SQLITE_OK ){
154854  rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
154855  }
154856 
154857  /* Advance to the next output block */
154858  pLeaf->iBlock++;
154859  pLeaf->key.n = 0;
154860  pLeaf->block.n = 0;
154861 
154862  nSuffix = nTerm;
154863  nSpace = 1;
154864  nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
154865  nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
154866  }
154867 
154868  pWriter->nLeafData += nSpace;
154869  blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
154870  if( rc==SQLITE_OK ){
154871  if( pLeaf->block.n==0 ){
154872  pLeaf->block.n = 1;
154873  pLeaf->block.a[0] = '\0';
154874  }
154875  rc = fts3AppendToNode(
154876  &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
154877  );
154878  }
154879 
154880  return rc;
154881 }
154882 
154883 /*
154884 ** This function is called to release all dynamic resources held by the
154885 ** merge-writer object pWriter, and if no error has occurred, to flush
154886 ** all outstanding node buffers held by pWriter to disk.
154887 **
154888 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
154889 ** is made to write any data to disk. Instead, this function serves only
154890 ** to release outstanding resources.
154891 **
154892 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
154893 ** flushing buffers to disk, *pRc is set to an SQLite error code before
154894 ** returning.
154895 */
154896 static void fts3IncrmergeRelease(
154897  Fts3Table *p, /* FTS3 table handle */
154898  IncrmergeWriter *pWriter, /* Merge-writer object */
154899  int *pRc /* IN/OUT: Error code */
154900 ){
154901  int i; /* Used to iterate through non-root layers */
154902  int iRoot; /* Index of root in pWriter->aNodeWriter */
154903  NodeWriter *pRoot; /* NodeWriter for root node */
154904  int rc = *pRc; /* Error code */
154905 
154906  /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
154907  ** root node. If the segment fits entirely on a single leaf node, iRoot
154908  ** will be set to 0. If the root node is the parent of the leaves, iRoot
154909  ** will be 1. And so on. */
154910  for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
154911  NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
154912  if( pNode->block.n>0 ) break;
154913  assert( *pRc || pNode->block.nAlloc==0 );
154914  assert( *pRc || pNode->key.nAlloc==0 );
154915  sqlite3_free(pNode->block.a);
154916  sqlite3_free(pNode->key.a);
154917  }
154918 
154919  /* Empty output segment. This is a no-op. */
154920  if( iRoot<0 ) return;
154921 
154922  /* The entire output segment fits on a single node. Normally, this means
154923  ** the node would be stored as a blob in the "root" column of the %_segdir
154924  ** table. However, this is not permitted in this case. The problem is that
154925  ** space has already been reserved in the %_segments table, and so the
154926  ** start_block and end_block fields of the %_segdir table must be populated.
154927  ** And, by design or by accident, released versions of FTS cannot handle
154928  ** segments that fit entirely on the root node with start_block!=0.
154929  **
154930  ** Instead, create a synthetic root node that contains nothing but a
154931  ** pointer to the single content node. So that the segment consists of a
154932  ** single leaf and a single interior (root) node.
154933  **
154934  ** Todo: Better might be to defer allocating space in the %_segments
154935  ** table until we are sure it is needed.
154936  */
154937  if( iRoot==0 ){
154938  Blob *pBlock = &pWriter->aNodeWriter[1].block;
154939  blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
154940  if( rc==SQLITE_OK ){
154941  pBlock->a[0] = 0x01;
154942  pBlock->n = 1 + sqlite3Fts3PutVarint(
154943  &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
154944  );
154945  }
154946  iRoot = 1;
154947  }
154948  pRoot = &pWriter->aNodeWriter[iRoot];
154949 
154950  /* Flush all currently outstanding nodes to disk. */
154951  for(i=0; i<iRoot; i++){
154952  NodeWriter *pNode = &pWriter->aNodeWriter[i];
154953  if( pNode->block.n>0 && rc==SQLITE_OK ){
154954  rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
154955  }
154956  sqlite3_free(pNode->block.a);
154957  sqlite3_free(pNode->key.a);
154958  }
154959 
154960  /* Write the %_segdir record. */
154961  if( rc==SQLITE_OK ){
154962  rc = fts3WriteSegdir(p,
154963  pWriter->iAbsLevel+1, /* level */
154964  pWriter->iIdx, /* idx */
154965  pWriter->iStart, /* start_block */
154966  pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
154967  pWriter->iEnd, /* end_block */
154968  (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
154969  pRoot->block.a, pRoot->block.n /* root */
154970  );
154971  }
154972  sqlite3_free(pRoot->block.a);
154973  sqlite3_free(pRoot->key.a);
154974 
154975  *pRc = rc;
154976 }
154977 
154978 /*
154979 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
154980 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
154981 ** the other, it is considered to be smaller than the other.
154982 **
154983 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
154984 ** if it is greater.
154985 */
154986 static int fts3TermCmp(
154987  const char *zLhs, int nLhs, /* LHS of comparison */
154988  const char *zRhs, int nRhs /* RHS of comparison */
154989 ){
154990  int nCmp = MIN(nLhs, nRhs);
154991  int res;
154992 
154993  res = memcmp(zLhs, zRhs, nCmp);
154994  if( res==0 ) res = nLhs - nRhs;
154995 
154996  return res;
154997 }
154998 
154999 
155000 /*
155001 ** Query to see if the entry in the %_segments table with blockid iEnd is
155002 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
155003 ** returning. Otherwise, set *pbRes to 0.
155004 **
155005 ** Or, if an error occurs while querying the database, return an SQLite
155006 ** error code. The final value of *pbRes is undefined in this case.
155007 **
155008 ** This is used to test if a segment is an "appendable" segment. If it
155009 ** is, then a NULL entry has been inserted into the %_segments table
155010 ** with blockid %_segdir.end_block.
155011 */
155012 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
155013  int bRes = 0; /* Result to set *pbRes to */
155014  sqlite3_stmt *pCheck = 0; /* Statement to query database with */
155015  int rc; /* Return code */
155016 
155017  rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
155018  if( rc==SQLITE_OK ){
155019  sqlite3_bind_int64(pCheck, 1, iEnd);
155020  if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
155021  rc = sqlite3_reset(pCheck);
155022  }
155023 
155024  *pbRes = bRes;
155025  return rc;
155026 }
155027 
155028 /*
155029 ** This function is called when initializing an incremental-merge operation.
155030 ** It checks if the existing segment with index value iIdx at absolute level
155031 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
155032 ** merge-writer object *pWriter is initialized to write to it.
155033 **
155034 ** An existing segment can be appended to by an incremental merge if:
155035 **
155036 ** * It was initially created as an appendable segment (with all required
155037 ** space pre-allocated), and
155038 **
155039 ** * The first key read from the input (arguments zKey and nKey) is
155040 ** greater than the largest key currently stored in the potential
155041 ** output segment.
155042 */
155043 static int fts3IncrmergeLoad(
155044  Fts3Table *p, /* Fts3 table handle */
155045  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
155046  int iIdx, /* Index of candidate output segment */
155047  const char *zKey, /* First key to write */
155048  int nKey, /* Number of bytes in nKey */
155049  IncrmergeWriter *pWriter /* Populate this object */
155050 ){
155051  int rc; /* Return code */
155052  sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
155053 
155054  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
155055  if( rc==SQLITE_OK ){
155056  sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
155057  sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
155058  sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
155059  const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
155060  int nRoot = 0; /* Size of aRoot[] in bytes */
155061  int rc2; /* Return code from sqlite3_reset() */
155062  int bAppendable = 0; /* Set to true if segment is appendable */
155063 
155064  /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
155065  sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
155066  sqlite3_bind_int(pSelect, 2, iIdx);
155067  if( sqlite3_step(pSelect)==SQLITE_ROW ){
155068  iStart = sqlite3_column_int64(pSelect, 1);
155069  iLeafEnd = sqlite3_column_int64(pSelect, 2);
155070  fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
155071  if( pWriter->nLeafData<0 ){
155072  pWriter->nLeafData = pWriter->nLeafData * -1;
155073  }
155074  pWriter->bNoLeafData = (pWriter->nLeafData==0);
155075  nRoot = sqlite3_column_bytes(pSelect, 4);
155076  aRoot = sqlite3_column_blob(pSelect, 4);
155077  }else{
155078  return sqlite3_reset(pSelect);
155079  }
155080 
155081  /* Check for the zero-length marker in the %_segments table */
155082  rc = fts3IsAppendable(p, iEnd, &bAppendable);
155083 
155084  /* Check that zKey/nKey is larger than the largest key the candidate */
155085  if( rc==SQLITE_OK && bAppendable ){
155086  char *aLeaf = 0;
155087  int nLeaf = 0;
155088 
155089  rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
155090  if( rc==SQLITE_OK ){
155091  NodeReader reader;
155092  for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
155093  rc==SQLITE_OK && reader.aNode;
155094  rc = nodeReaderNext(&reader)
155095  ){
155096  assert( reader.aNode );
155097  }
155098  if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
155099  bAppendable = 0;
155100  }
155101  nodeReaderRelease(&reader);
155102  }
155103  sqlite3_free(aLeaf);
155104  }
155105 
155106  if( rc==SQLITE_OK && bAppendable ){
155107  /* It is possible to append to this segment. Set up the IncrmergeWriter
155108  ** object to do so. */
155109  int i;
155110  int nHeight = (int)aRoot[0];
155111  NodeWriter *pNode;
155112 
155113  pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
155114  pWriter->iStart = iStart;
155115  pWriter->iEnd = iEnd;
155116  pWriter->iAbsLevel = iAbsLevel;
155117  pWriter->iIdx = iIdx;
155118 
155119  for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
155120  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
155121  }
155122 
155123  pNode = &pWriter->aNodeWriter[nHeight];
155124  pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
155125  blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
155126  if( rc==SQLITE_OK ){
155127  memcpy(pNode->block.a, aRoot, nRoot);
155128  pNode->block.n = nRoot;
155129  }
155130 
155131  for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
155132  NodeReader reader;
155133  pNode = &pWriter->aNodeWriter[i];
155134 
155135  rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
155136  while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
155137  blobGrowBuffer(&pNode->key, reader.term.n, &rc);
155138  if( rc==SQLITE_OK ){
155139  memcpy(pNode->key.a, reader.term.a, reader.term.n);
155140  pNode->key.n = reader.term.n;
155141  if( i>0 ){
155142  char *aBlock = 0;
155143  int nBlock = 0;
155144  pNode = &pWriter->aNodeWriter[i-1];
155145  pNode->iBlock = reader.iChild;
155146  rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
155147  blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
155148  if( rc==SQLITE_OK ){
155149  memcpy(pNode->block.a, aBlock, nBlock);
155150  pNode->block.n = nBlock;
155151  }
155152  sqlite3_free(aBlock);
155153  }
155154  }
155155  nodeReaderRelease(&reader);
155156  }
155157  }
155158 
155159  rc2 = sqlite3_reset(pSelect);
155160  if( rc==SQLITE_OK ) rc = rc2;
155161  }
155162 
155163  return rc;
155164 }
155165 
155166 /*
155167 ** Determine the largest segment index value that exists within absolute
155168 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
155169 ** one before returning SQLITE_OK. Or, if there are no segments at all
155170 ** within level iAbsLevel, set *piIdx to zero.
155171 **
155172 ** If an error occurs, return an SQLite error code. The final value of
155173 ** *piIdx is undefined in this case.
155174 */
155175 static int fts3IncrmergeOutputIdx(
155176  Fts3Table *p, /* FTS Table handle */
155177  sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
155178  int *piIdx /* OUT: Next free index at iAbsLevel+1 */
155179 ){
155180  int rc;
155181  sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
155182 
155183  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
155184  if( rc==SQLITE_OK ){
155185  sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
155186  sqlite3_step(pOutputIdx);
155187  *piIdx = sqlite3_column_int(pOutputIdx, 0);
155188  rc = sqlite3_reset(pOutputIdx);
155189  }
155190 
155191  return rc;
155192 }
155193 
155194 /*
155195 ** Allocate an appendable output segment on absolute level iAbsLevel+1
155196 ** with idx value iIdx.
155197 **
155198 ** In the %_segdir table, a segment is defined by the values in three
155199 ** columns:
155200 **
155201 ** start_block
155202 ** leaves_end_block
155203 ** end_block
155204 **
155205 ** When an appendable segment is allocated, it is estimated that the
155206 ** maximum number of leaf blocks that may be required is the sum of the
155207 ** number of leaf blocks consumed by the input segments, plus the number
155208 ** of input segments, multiplied by two. This value is stored in stack
155209 ** variable nLeafEst.
155210 **
155211 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
155212 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
155213 ** array of leaf nodes starts at the first block allocated. The array
155214 ** of interior nodes that are parents of the leaf nodes start at block
155215 ** (start_block + (1 + end_block - start_block) / 16). And so on.
155216 **
155217 ** In the actual code below, the value "16" is replaced with the
155218 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
155219 */
155220 static int fts3IncrmergeWriter(
155221  Fts3Table *p, /* Fts3 table handle */
155222  sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
155223  int iIdx, /* Index of new output segment */
155224  Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
155225  IncrmergeWriter *pWriter /* Populate this object */
155226 ){
155227  int rc; /* Return Code */
155228  int i; /* Iterator variable */
155229  int nLeafEst = 0; /* Blocks allocated for leaf nodes */
155230  sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
155231  sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
155232 
155233  /* Calculate nLeafEst. */
155234  rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
155235  if( rc==SQLITE_OK ){
155236  sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
155237  sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
155238  if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
155239  nLeafEst = sqlite3_column_int(pLeafEst, 0);
155240  }
155241  rc = sqlite3_reset(pLeafEst);
155242  }
155243  if( rc!=SQLITE_OK ) return rc;
155244 
155245  /* Calculate the first block to use in the output segment */
155246  rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
155247  if( rc==SQLITE_OK ){
155248  if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
155249  pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
155250  pWriter->iEnd = pWriter->iStart - 1;
155251  pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
155252  }
155253  rc = sqlite3_reset(pFirstBlock);
155254  }
155255  if( rc!=SQLITE_OK ) return rc;
155256 
155257  /* Insert the marker in the %_segments table to make sure nobody tries
155258  ** to steal the space just allocated. This is also used to identify
155259  ** appendable segments. */
155260  rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
155261  if( rc!=SQLITE_OK ) return rc;
155262 
155263  pWriter->iAbsLevel = iAbsLevel;
155264  pWriter->nLeafEst = nLeafEst;
155265  pWriter->iIdx = iIdx;
155266 
155267  /* Set up the array of NodeWriter objects */
155268  for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
155269  pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
155270  }
155271  return SQLITE_OK;
155272 }
155273 
155274 /*
155275 ** Remove an entry from the %_segdir table. This involves running the
155276 ** following two statements:
155277 **
155278 ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
155279 ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
155280 **
155281 ** The DELETE statement removes the specific %_segdir level. The UPDATE
155282 ** statement ensures that the remaining segments have contiguously allocated
155283 ** idx values.
155284 */
155285 static int fts3RemoveSegdirEntry(
155286  Fts3Table *p, /* FTS3 table handle */
155287  sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
155288  int iIdx /* Index of %_segdir entry to delete */
155289 ){
155290  int rc; /* Return code */
155291  sqlite3_stmt *pDelete = 0; /* DELETE statement */
155292 
155293  rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
155294  if( rc==SQLITE_OK ){
155295  sqlite3_bind_int64(pDelete, 1, iAbsLevel);
155296  sqlite3_bind_int(pDelete, 2, iIdx);
155297  sqlite3_step(pDelete);
155298  rc = sqlite3_reset(pDelete);
155299  }
155300 
155301  return rc;
155302 }
155303 
155304 /*
155305 ** One or more segments have just been removed from absolute level iAbsLevel.
155306 ** Update the 'idx' values of the remaining segments in the level so that
155307 ** the idx values are a contiguous sequence starting from 0.
155308 */
155309 static int fts3RepackSegdirLevel(
155310  Fts3Table *p, /* FTS3 table handle */
155311  sqlite3_int64 iAbsLevel /* Absolute level to repack */
155312 ){
155313  int rc; /* Return code */
155314  int *aIdx = 0; /* Array of remaining idx values */
155315  int nIdx = 0; /* Valid entries in aIdx[] */
155316  int nAlloc = 0; /* Allocated size of aIdx[] */
155317  int i; /* Iterator variable */
155318  sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
155319  sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
155320 
155321  rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
155322  if( rc==SQLITE_OK ){
155323  int rc2;
155324  sqlite3_bind_int64(pSelect, 1, iAbsLevel);
155325  while( SQLITE_ROW==sqlite3_step(pSelect) ){
155326  if( nIdx>=nAlloc ){
155327  int *aNew;
155328  nAlloc += 16;
155329  aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
155330  if( !aNew ){
155331  rc = SQLITE_NOMEM;
155332  break;
155333  }
155334  aIdx = aNew;
155335  }
155336  aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
155337  }
155338  rc2 = sqlite3_reset(pSelect);
155339  if( rc==SQLITE_OK ) rc = rc2;
155340  }
155341 
155342  if( rc==SQLITE_OK ){
155343  rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
155344  }
155345  if( rc==SQLITE_OK ){
155346  sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
155347  }
155348 
155349  assert( p->bIgnoreSavepoint==0 );
155350  p->bIgnoreSavepoint = 1;
155351  for(i=0; rc==SQLITE_OK && i<nIdx; i++){
155352  if( aIdx[i]!=i ){
155353  sqlite3_bind_int(pUpdate, 3, aIdx[i]);
155354  sqlite3_bind_int(pUpdate, 1, i);
155355  sqlite3_step(pUpdate);
155356  rc = sqlite3_reset(pUpdate);
155357  }
155358  }
155359  p->bIgnoreSavepoint = 0;
155360 
155361  sqlite3_free(aIdx);
155362  return rc;
155363 }
155364 
155365 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
155366  pNode->a[0] = (char)iHeight;
155367  if( iChild ){
155368  assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
155369  pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
155370  }else{
155371  assert( pNode->nAlloc>=1 );
155372  pNode->n = 1;
155373  }
155374 }
155375 
155376 /*
155377 ** The first two arguments are a pointer to and the size of a segment b-tree
155378 ** node. The node may be a leaf or an internal node.
155379 **
155380 ** This function creates a new node image in blob object *pNew by copying
155381 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
155382 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
155383 */
155384 static int fts3TruncateNode(
155385  const char *aNode, /* Current node image */
155386  int nNode, /* Size of aNode in bytes */
155387  Blob *pNew, /* OUT: Write new node image here */
155388  const char *zTerm, /* Omit all terms smaller than this */
155389  int nTerm, /* Size of zTerm in bytes */
155390  sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
155391 ){
155392  NodeReader reader; /* Reader object */
155393  Blob prev = {0, 0, 0}; /* Previous term written to new node */
155394  int rc = SQLITE_OK; /* Return code */
155395  int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
155396 
155397  /* Allocate required output space */
155398  blobGrowBuffer(pNew, nNode, &rc);
155399  if( rc!=SQLITE_OK ) return rc;
155400  pNew->n = 0;
155401 
155402  /* Populate new node buffer */
155403  for(rc = nodeReaderInit(&reader, aNode, nNode);
155404  rc==SQLITE_OK && reader.aNode;
155405  rc = nodeReaderNext(&reader)
155406  ){
155407  if( pNew->n==0 ){
155408  int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
155409  if( res<0 || (bLeaf==0 && res==0) ) continue;
155410  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
155411  *piBlock = reader.iChild;
155412  }
155413  rc = fts3AppendToNode(
155414  pNew, &prev, reader.term.a, reader.term.n,
155415  reader.aDoclist, reader.nDoclist
155416  );
155417  if( rc!=SQLITE_OK ) break;
155418  }
155419  if( pNew->n==0 ){
155420  fts3StartNode(pNew, (int)aNode[0], reader.iChild);
155421  *piBlock = reader.iChild;
155422  }
155423  assert( pNew->n<=pNew->nAlloc );
155424 
155425  nodeReaderRelease(&reader);
155426  sqlite3_free(prev.a);
155427  return rc;
155428 }
155429 
155430 /*
155431 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
155432 ** level iAbsLevel. This may involve deleting entries from the %_segments
155433 ** table, and modifying existing entries in both the %_segments and %_segdir
155434 ** tables.
155435 **
155436 ** SQLITE_OK is returned if the segment is updated successfully. Or an
155437 ** SQLite error code otherwise.
155438 */
155439 static int fts3TruncateSegment(
155440  Fts3Table *p, /* FTS3 table handle */
155441  sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
155442  int iIdx, /* Index within level of segment to modify */
155443  const char *zTerm, /* Remove terms smaller than this */
155444  int nTerm /* Number of bytes in buffer zTerm */
155445 ){
155446  int rc = SQLITE_OK; /* Return code */
155447  Blob root = {0,0,0}; /* New root page image */
155448  Blob block = {0,0,0}; /* Buffer used for any other block */
155449  sqlite3_int64 iBlock = 0; /* Block id */
155450  sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
155451  sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
155452  sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
155453 
155454  rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
155455  if( rc==SQLITE_OK ){
155456  int rc2; /* sqlite3_reset() return code */
155457  sqlite3_bind_int64(pFetch, 1, iAbsLevel);
155458  sqlite3_bind_int(pFetch, 2, iIdx);
155459  if( SQLITE_ROW==sqlite3_step(pFetch) ){
155460  const char *aRoot = sqlite3_column_blob(pFetch, 4);
155461  int nRoot = sqlite3_column_bytes(pFetch, 4);
155462  iOldStart = sqlite3_column_int64(pFetch, 1);
155463  rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
155464  }
155465  rc2 = sqlite3_reset(pFetch);
155466  if( rc==SQLITE_OK ) rc = rc2;
155467  }
155468 
155469  while( rc==SQLITE_OK && iBlock ){
155470  char *aBlock = 0;
155471  int nBlock = 0;
155472  iNewStart = iBlock;
155473 
155474  rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
155475  if( rc==SQLITE_OK ){
155476  rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
155477  }
155478  if( rc==SQLITE_OK ){
155479  rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
155480  }
155481  sqlite3_free(aBlock);
155482  }
155483 
155484  /* Variable iNewStart now contains the first valid leaf node. */
155485  if( rc==SQLITE_OK && iNewStart ){
155486  sqlite3_stmt *pDel = 0;
155487  rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
155488  if( rc==SQLITE_OK ){
155489  sqlite3_bind_int64(pDel, 1, iOldStart);
155490  sqlite3_bind_int64(pDel, 2, iNewStart-1);
155491  sqlite3_step(pDel);
155492  rc = sqlite3_reset(pDel);
155493  }
155494  }
155495 
155496  if( rc==SQLITE_OK ){
155497  sqlite3_stmt *pChomp = 0;
155498  rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
155499  if( rc==SQLITE_OK ){
155500  sqlite3_bind_int64(pChomp, 1, iNewStart);
155501  sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
155502  sqlite3_bind_int64(pChomp, 3, iAbsLevel);
155503  sqlite3_bind_int(pChomp, 4, iIdx);
155504  sqlite3_step(pChomp);
155505  rc = sqlite3_reset(pChomp);
155506  }
155507  }
155508 
155509  sqlite3_free(root.a);
155510  sqlite3_free(block.a);
155511  return rc;
155512 }
155513 
155514 /*
155515 ** This function is called after an incrmental-merge operation has run to
155516 ** merge (or partially merge) two or more segments from absolute level
155517 ** iAbsLevel.
155518 **
155519 ** Each input segment is either removed from the db completely (if all of
155520 ** its data was copied to the output segment by the incrmerge operation)
155521 ** or modified in place so that it no longer contains those entries that
155522 ** have been duplicated in the output segment.
155523 */
155524 static int fts3IncrmergeChomp(
155525  Fts3Table *p, /* FTS table handle */
155526  sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
155527  Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
155528  int *pnRem /* Number of segments not deleted */
155529 ){
155530  int i;
155531  int nRem = 0;
155532  int rc = SQLITE_OK;
155533 
155534  for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
155535  Fts3SegReader *pSeg = 0;
155536  int j;
155537 
155538  /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
155539  ** somewhere in the pCsr->apSegment[] array. */
155540  for(j=0; ALWAYS(j<pCsr->nSegment); j++){
155541  pSeg = pCsr->apSegment[j];
155542  if( pSeg->iIdx==i ) break;
155543  }
155544  assert( j<pCsr->nSegment && pSeg->iIdx==i );
155545 
155546  if( pSeg->aNode==0 ){
155547  /* Seg-reader is at EOF. Remove the entire input segment. */
155548  rc = fts3DeleteSegment(p, pSeg);
155549  if( rc==SQLITE_OK ){
155550  rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
155551  }
155552  *pnRem = 0;
155553  }else{
155554  /* The incremental merge did not copy all the data from this
155555  ** segment to the upper level. The segment is modified in place
155556  ** so that it contains no keys smaller than zTerm/nTerm. */
155557  const char *zTerm = pSeg->zTerm;
155558  int nTerm = pSeg->nTerm;
155559  rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
155560  nRem++;
155561  }
155562  }
155563 
155564  if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
155565  rc = fts3RepackSegdirLevel(p, iAbsLevel);
155566  }
155567 
155568  *pnRem = nRem;
155569  return rc;
155570 }
155571 
155572 /*
155573 ** Store an incr-merge hint in the database.
155574 */
155575 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
155576  sqlite3_stmt *pReplace = 0;
155577  int rc; /* Return code */
155578 
155579  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
155580  if( rc==SQLITE_OK ){
155581  sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
155582  sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
155583  sqlite3_step(pReplace);
155584  rc = sqlite3_reset(pReplace);
155585  }
155586 
155587  return rc;
155588 }
155589 
155590 /*
155591 ** Load an incr-merge hint from the database. The incr-merge hint, if one
155592 ** exists, is stored in the rowid==1 row of the %_stat table.
155593 **
155594 ** If successful, populate blob *pHint with the value read from the %_stat
155595 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
155596 ** SQLite error code.
155597 */
155598 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
155599  sqlite3_stmt *pSelect = 0;
155600  int rc;
155601 
155602  pHint->n = 0;
155603  rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
155604  if( rc==SQLITE_OK ){
155605  int rc2;
155606  sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
155607  if( SQLITE_ROW==sqlite3_step(pSelect) ){
155608  const char *aHint = sqlite3_column_blob(pSelect, 0);
155609  int nHint = sqlite3_column_bytes(pSelect, 0);
155610  if( aHint ){
155611  blobGrowBuffer(pHint, nHint, &rc);
155612  if( rc==SQLITE_OK ){
155613  memcpy(pHint->a, aHint, nHint);
155614  pHint->n = nHint;
155615  }
155616  }
155617  }
155618  rc2 = sqlite3_reset(pSelect);
155619  if( rc==SQLITE_OK ) rc = rc2;
155620  }
155621 
155622  return rc;
155623 }
155624 
155625 /*
155626 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
155627 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
155628 ** consists of two varints, the absolute level number of the input segments
155629 ** and the number of input segments.
155630 **
155631 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
155632 ** set *pRc to an SQLite error code before returning.
155633 */
155634 static void fts3IncrmergeHintPush(
155635  Blob *pHint, /* Hint blob to append to */
155636  i64 iAbsLevel, /* First varint to store in hint */
155637  int nInput, /* Second varint to store in hint */
155638  int *pRc /* IN/OUT: Error code */
155639 ){
155640  blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
155641  if( *pRc==SQLITE_OK ){
155642  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
155643  pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
155644  }
155645 }
155646 
155647 /*
155648 ** Read the last entry (most recently pushed) from the hint blob *pHint
155649 ** and then remove the entry. Write the two values read to *piAbsLevel and
155650 ** *pnInput before returning.
155651 **
155652 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
155653 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
155654 */
155655 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
155656  const int nHint = pHint->n;
155657  int i;
155658 
155659  i = pHint->n-2;
155660  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
155661  while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
155662 
155663  pHint->n = i;
155664  i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
155665  i += fts3GetVarint32(&pHint->a[i], pnInput);
155666  if( i!=nHint ) return FTS_CORRUPT_VTAB;
155667 
155668  return SQLITE_OK;
155669 }
155670 
155671 
155672 /*
155673 ** Attempt an incremental merge that writes nMerge leaf blocks.
155674 **
155675 ** Incremental merges happen nMin segments at a time. The segments
155676 ** to be merged are the nMin oldest segments (the ones with the smallest
155677 ** values for the _segdir.idx field) in the highest level that contains
155678 ** at least nMin segments. Multiple merges might occur in an attempt to
155679 ** write the quota of nMerge leaf blocks.
155680 */
155681 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
155682  int rc; /* Return code */
155683  int nRem = nMerge; /* Number of leaf pages yet to be written */
155684  Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
155685  Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
155686  IncrmergeWriter *pWriter; /* Writer object */
155687  int nSeg = 0; /* Number of input segments */
155688  sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
155689  Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
155690  int bDirtyHint = 0; /* True if blob 'hint' has been modified */
155691 
155692  /* Allocate space for the cursor, filter and writer objects */
155693  const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
155694  pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
155695  if( !pWriter ) return SQLITE_NOMEM;
155696  pFilter = (Fts3SegFilter *)&pWriter[1];
155697  pCsr = (Fts3MultiSegReader *)&pFilter[1];
155698 
155699  rc = fts3IncrmergeHintLoad(p, &hint);
155700  while( rc==SQLITE_OK && nRem>0 ){
155701  const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
155702  sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
155703  int bUseHint = 0; /* True if attempting to append */
155704  int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
155705 
155706  /* Search the %_segdir table for the absolute level with the smallest
155707  ** relative level number that contains at least nMin segments, if any.
155708  ** If one is found, set iAbsLevel to the absolute level number and
155709  ** nSeg to nMin. If no level with at least nMin segments can be found,
155710  ** set nSeg to -1.
155711  */
155712  rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
155713  sqlite3_bind_int(pFindLevel, 1, MAX(2, nMin));
155714  if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
155715  iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
155716  nSeg = sqlite3_column_int(pFindLevel, 1);
155717  assert( nSeg>=2 );
155718  }else{
155719  nSeg = -1;
155720  }
155721  rc = sqlite3_reset(pFindLevel);
155722 
155723  /* If the hint read from the %_stat table is not empty, check if the
155724  ** last entry in it specifies a relative level smaller than or equal
155725  ** to the level identified by the block above (if any). If so, this
155726  ** iteration of the loop will work on merging at the hinted level.
155727  */
155728  if( rc==SQLITE_OK && hint.n ){
155729  int nHint = hint.n;
155730  sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
155731  int nHintSeg = 0; /* Hint number of segments */
155732 
155733  rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
155734  if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
155735  iAbsLevel = iHintAbsLevel;
155736  nSeg = nHintSeg;
155737  bUseHint = 1;
155738  bDirtyHint = 1;
155739  }else{
155740  /* This undoes the effect of the HintPop() above - so that no entry
155741  ** is removed from the hint blob. */
155742  hint.n = nHint;
155743  }
155744  }
155745 
155746  /* If nSeg is less that zero, then there is no level with at least
155747  ** nMin segments and no hint in the %_stat table. No work to do.
155748  ** Exit early in this case. */
155749  if( nSeg<0 ) break;
155750 
155751  /* Open a cursor to iterate through the contents of the oldest nSeg
155752  ** indexes of absolute level iAbsLevel. If this cursor is opened using
155753  ** the 'hint' parameters, it is possible that there are less than nSeg
155754  ** segments available in level iAbsLevel. In this case, no work is
155755  ** done on iAbsLevel - fall through to the next iteration of the loop
155756  ** to start work on some other level. */
155757  memset(pWriter, 0, nAlloc);
155758  pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
155759 
155760  if( rc==SQLITE_OK ){
155761  rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
155762  assert( bUseHint==1 || bUseHint==0 );
155763  if( iIdx==0 || (bUseHint && iIdx==1) ){
155764  int bIgnore = 0;
155765  rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
155766  if( bIgnore ){
155767  pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
155768  }
155769  }
155770  }
155771 
155772  if( rc==SQLITE_OK ){
155773  rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
155774  }
155775  if( SQLITE_OK==rc && pCsr->nSegment==nSeg
155776  && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
155777  && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
155778  ){
155779  if( bUseHint && iIdx>0 ){
155780  const char *zKey = pCsr->zTerm;
155781  int nKey = pCsr->nTerm;
155782  rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
155783  }else{
155784  rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
155785  }
155786 
155787  if( rc==SQLITE_OK && pWriter->nLeafEst ){
155788  fts3LogMerge(nSeg, iAbsLevel);
155789  do {
155790  rc = fts3IncrmergeAppend(p, pWriter, pCsr);
155791  if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
155792  if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
155793  }while( rc==SQLITE_ROW );
155794 
155795  /* Update or delete the input segments */
155796  if( rc==SQLITE_OK ){
155797  nRem -= (1 + pWriter->nWork);
155798  rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
155799  if( nSeg!=0 ){
155800  bDirtyHint = 1;
155801  fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
155802  }
155803  }
155804  }
155805 
155806  if( nSeg!=0 ){
155807  pWriter->nLeafData = pWriter->nLeafData * -1;
155808  }
155809  fts3IncrmergeRelease(p, pWriter, &rc);
155810  if( nSeg==0 && pWriter->bNoLeafData==0 ){
155811  fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
155812  }
155813  }
155814 
155815  sqlite3Fts3SegReaderFinish(pCsr);
155816  }
155817 
155818  /* Write the hint values into the %_stat table for the next incr-merger */
155819  if( bDirtyHint && rc==SQLITE_OK ){
155820  rc = fts3IncrmergeHintStore(p, &hint);
155821  }
155822 
155823  sqlite3_free(pWriter);
155824  sqlite3_free(hint.a);
155825  return rc;
155826 }
155827 
155828 /*
155829 ** Convert the text beginning at *pz into an integer and return
155830 ** its value. Advance *pz to point to the first character past
155831 ** the integer.
155832 */
155833 static int fts3Getint(const char **pz){
155834  const char *z = *pz;
155835  int i = 0;
155836  while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
155837  *pz = z;
155838  return i;
155839 }
155840 
155841 /*
155842 ** Process statements of the form:
155843 **
155844 ** INSERT INTO table(table) VALUES('merge=A,B');
155845 **
155846 ** A and B are integers that decode to be the number of leaf pages
155847 ** written for the merge, and the minimum number of segments on a level
155848 ** before it will be selected for a merge, respectively.
155849 */
155850 static int fts3DoIncrmerge(
155851  Fts3Table *p, /* FTS3 table handle */
155852  const char *zParam /* Nul-terminated string containing "A,B" */
155853 ){
155854  int rc;
155855  int nMin = (FTS3_MERGE_COUNT / 2);
155856  int nMerge = 0;
155857  const char *z = zParam;
155858 
155859  /* Read the first integer value */
155860  nMerge = fts3Getint(&z);
155861 
155862  /* If the first integer value is followed by a ',', read the second
155863  ** integer value. */
155864  if( z[0]==',' && z[1]!='\0' ){
155865  z++;
155866  nMin = fts3Getint(&z);
155867  }
155868 
155869  if( z[0]!='\0' || nMin<2 ){
155870  rc = SQLITE_ERROR;
155871  }else{
155872  rc = SQLITE_OK;
155873  if( !p->bHasStat ){
155874  assert( p->bFts4==0 );
155875  sqlite3Fts3CreateStatTable(&rc, p);
155876  }
155877  if( rc==SQLITE_OK ){
155878  rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
155879  }
155880  sqlite3Fts3SegmentsClose(p);
155881  }
155882  return rc;
155883 }
155884 
155885 /*
155886 ** Process statements of the form:
155887 **
155888 ** INSERT INTO table(table) VALUES('automerge=X');
155889 **
155890 ** where X is an integer. X==0 means to turn automerge off. X!=0 means
155891 ** turn it on. The setting is persistent.
155892 */
155893 static int fts3DoAutoincrmerge(
155894  Fts3Table *p, /* FTS3 table handle */
155895  const char *zParam /* Nul-terminated string containing boolean */
155896 ){
155897  int rc = SQLITE_OK;
155898  sqlite3_stmt *pStmt = 0;
155899  p->nAutoincrmerge = fts3Getint(&zParam);
155900  if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
155901  p->nAutoincrmerge = 8;
155902  }
155903  if( !p->bHasStat ){
155904  assert( p->bFts4==0 );
155905  sqlite3Fts3CreateStatTable(&rc, p);
155906  if( rc ) return rc;
155907  }
155908  rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
155909  if( rc ) return rc;
155910  sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
155911  sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
155912  sqlite3_step(pStmt);
155913  rc = sqlite3_reset(pStmt);
155914  return rc;
155915 }
155916 
155917 /*
155918 ** Return a 64-bit checksum for the FTS index entry specified by the
155919 ** arguments to this function.
155920 */
155921 static u64 fts3ChecksumEntry(
155922  const char *zTerm, /* Pointer to buffer containing term */
155923  int nTerm, /* Size of zTerm in bytes */
155924  int iLangid, /* Language id for current row */
155925  int iIndex, /* Index (0..Fts3Table.nIndex-1) */
155926  i64 iDocid, /* Docid for current row. */
155927  int iCol, /* Column number */
155928  int iPos /* Position */
155929 ){
155930  int i;
155931  u64 ret = (u64)iDocid;
155932 
155933  ret += (ret<<3) + iLangid;
155934  ret += (ret<<3) + iIndex;
155935  ret += (ret<<3) + iCol;
155936  ret += (ret<<3) + iPos;
155937  for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
155938 
155939  return ret;
155940 }
155941 
155942 /*
155943 ** Return a checksum of all entries in the FTS index that correspond to
155944 ** language id iLangid. The checksum is calculated by XORing the checksums
155945 ** of each individual entry (see fts3ChecksumEntry()) together.
155946 **
155947 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
155948 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
155949 ** return value is undefined in this case.
155950 */
155951 static u64 fts3ChecksumIndex(
155952  Fts3Table *p, /* FTS3 table handle */
155953  int iLangid, /* Language id to return cksum for */
155954  int iIndex, /* Index to cksum (0..p->nIndex-1) */
155955  int *pRc /* OUT: Return code */
155956 ){
155957  Fts3SegFilter filter;
155958  Fts3MultiSegReader csr;
155959  int rc;
155960  u64 cksum = 0;
155961 
155962  assert( *pRc==SQLITE_OK );
155963 
155964  memset(&filter, 0, sizeof(filter));
155965  memset(&csr, 0, sizeof(csr));
155966  filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
155967  filter.flags |= FTS3_SEGMENT_SCAN;
155968 
155969  rc = sqlite3Fts3SegReaderCursor(
155970  p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
155971  );
155972  if( rc==SQLITE_OK ){
155973  rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
155974  }
155975 
155976  if( rc==SQLITE_OK ){
155977  while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
155978  char *pCsr = csr.aDoclist;
155979  char *pEnd = &pCsr[csr.nDoclist];
155980 
155981  i64 iDocid = 0;
155982  i64 iCol = 0;
155983  i64 iPos = 0;
155984 
155985  pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
155986  while( pCsr<pEnd ){
155987  i64 iVal = 0;
155988  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
155989  if( pCsr<pEnd ){
155990  if( iVal==0 || iVal==1 ){
155991  iCol = 0;
155992  iPos = 0;
155993  if( iVal ){
155994  pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
155995  }else{
155996  pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
155997  iDocid += iVal;
155998  }
155999  }else{
156000  iPos += (iVal - 2);
156001  cksum = cksum ^ fts3ChecksumEntry(
156002  csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
156003  (int)iCol, (int)iPos
156004  );
156005  }
156006  }
156007  }
156008  }
156009  }
156010  sqlite3Fts3SegReaderFinish(&csr);
156011 
156012  *pRc = rc;
156013  return cksum;
156014 }
156015 
156016 /*
156017 ** Check if the contents of the FTS index match the current contents of the
156018 ** content table. If no error occurs and the contents do match, set *pbOk
156019 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
156020 ** to false before returning.
156021 **
156022 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
156023 ** code. The final value of *pbOk is undefined in this case.
156024 */
156025 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
156026  int rc = SQLITE_OK; /* Return code */
156027  u64 cksum1 = 0; /* Checksum based on FTS index contents */
156028  u64 cksum2 = 0; /* Checksum based on %_content contents */
156029  sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
156030 
156031  /* This block calculates the checksum according to the FTS index. */
156032  rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
156033  if( rc==SQLITE_OK ){
156034  int rc2;
156035  sqlite3_bind_int(pAllLangid, 1, p->iPrevLangid);
156036  sqlite3_bind_int(pAllLangid, 2, p->nIndex);
156037  while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
156038  int iLangid = sqlite3_column_int(pAllLangid, 0);
156039  int i;
156040  for(i=0; i<p->nIndex; i++){
156041  cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
156042  }
156043  }
156044  rc2 = sqlite3_reset(pAllLangid);
156045  if( rc==SQLITE_OK ) rc = rc2;
156046  }
156047 
156048  /* This block calculates the checksum according to the %_content table */
156049  if( rc==SQLITE_OK ){
156050  sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
156051  sqlite3_stmt *pStmt = 0;
156052  char *zSql;
156053 
156054  zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
156055  if( !zSql ){
156056  rc = SQLITE_NOMEM;
156057  }else{
156058  rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
156059  sqlite3_free(zSql);
156060  }
156061 
156062  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
156063  i64 iDocid = sqlite3_column_int64(pStmt, 0);
156064  int iLang = langidFromSelect(p, pStmt);
156065  int iCol;
156066 
156067  for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
156068  if( p->abNotindexed[iCol]==0 ){
156069  const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
156070  int nText = sqlite3_column_bytes(pStmt, iCol+1);
156071  sqlite3_tokenizer_cursor *pT = 0;
156072 
156073  rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
156074  while( rc==SQLITE_OK ){
156075  char const *zToken; /* Buffer containing token */
156076  int nToken = 0; /* Number of bytes in token */
156077  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
156078  int iPos = 0; /* Position of token in zText */
156079 
156080  rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
156081  if( rc==SQLITE_OK ){
156082  int i;
156083  cksum2 = cksum2 ^ fts3ChecksumEntry(
156084  zToken, nToken, iLang, 0, iDocid, iCol, iPos
156085  );
156086  for(i=1; i<p->nIndex; i++){
156087  if( p->aIndex[i].nPrefix<=nToken ){
156088  cksum2 = cksum2 ^ fts3ChecksumEntry(
156089  zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
156090  );
156091  }
156092  }
156093  }
156094  }
156095  if( pT ) pModule->xClose(pT);
156096  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
156097  }
156098  }
156099  }
156100 
156101  sqlite3_finalize(pStmt);
156102  }
156103 
156104  *pbOk = (cksum1==cksum2);
156105  return rc;
156106 }
156107 
156108 /*
156109 ** Run the integrity-check. If no error occurs and the current contents of
156110 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
156111 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
156112 **
156113 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
156114 ** error code.
156115 **
156116 ** The integrity-check works as follows. For each token and indexed token
156117 ** prefix in the document set, a 64-bit checksum is calculated (by code
156118 ** in fts3ChecksumEntry()) based on the following:
156119 **
156120 ** + The index number (0 for the main index, 1 for the first prefix
156121 ** index etc.),
156122 ** + The token (or token prefix) text itself,
156123 ** + The language-id of the row it appears in,
156124 ** + The docid of the row it appears in,
156125 ** + The column it appears in, and
156126 ** + The tokens position within that column.
156127 **
156128 ** The checksums for all entries in the index are XORed together to create
156129 ** a single checksum for the entire index.
156130 **
156131 ** The integrity-check code calculates the same checksum in two ways:
156132 **
156133 ** 1. By scanning the contents of the FTS index, and
156134 ** 2. By scanning and tokenizing the content table.
156135 **
156136 ** If the two checksums are identical, the integrity-check is deemed to have
156137 ** passed.
156138 */
156139 static int fts3DoIntegrityCheck(
156140  Fts3Table *p /* FTS3 table handle */
156141 ){
156142  int rc;
156143  int bOk = 0;
156144  rc = fts3IntegrityCheck(p, &bOk);
156145  if( rc==SQLITE_OK && bOk==0 ) rc = FTS_CORRUPT_VTAB;
156146  return rc;
156147 }
156148 
156149 /*
156150 ** Handle a 'special' INSERT of the form:
156151 **
156152 ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
156153 **
156154 ** Argument pVal contains the result of <expr>. Currently the only
156155 ** meaningful value to insert is the text 'optimize'.
156156 */
156157 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
156158  int rc; /* Return Code */
156159  const char *zVal = (const char *)sqlite3_value_text(pVal);
156160  int nVal = sqlite3_value_bytes(pVal);
156161 
156162  if( !zVal ){
156163  return SQLITE_NOMEM;
156164  }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
156165  rc = fts3DoOptimize(p, 0);
156166  }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
156167  rc = fts3DoRebuild(p);
156168  }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
156169  rc = fts3DoIntegrityCheck(p);
156170  }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
156171  rc = fts3DoIncrmerge(p, &zVal[6]);
156172  }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
156173  rc = fts3DoAutoincrmerge(p, &zVal[10]);
156174 #ifdef SQLITE_TEST
156175  }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
156176  p->nNodeSize = atoi(&zVal[9]);
156177  rc = SQLITE_OK;
156178  }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
156179  p->nMaxPendingData = atoi(&zVal[11]);
156180  rc = SQLITE_OK;
156181  }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
156182  p->bNoIncrDoclist = atoi(&zVal[21]);
156183  rc = SQLITE_OK;
156184 #endif
156185  }else{
156186  rc = SQLITE_ERROR;
156187  }
156188 
156189  return rc;
156190 }
156191 
156192 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
156193 /*
156194 ** Delete all cached deferred doclists. Deferred doclists are cached
156195 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
156196 */
156197 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
156198  Fts3DeferredToken *pDef;
156199  for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
156200  fts3PendingListDelete(pDef->pList);
156201  pDef->pList = 0;
156202  }
156203 }
156204 
156205 /*
156206 ** Free all entries in the pCsr->pDeffered list. Entries are added to
156207 ** this list using sqlite3Fts3DeferToken().
156208 */
156209 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
156210  Fts3DeferredToken *pDef;
156211  Fts3DeferredToken *pNext;
156212  for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
156213  pNext = pDef->pNext;
156214  fts3PendingListDelete(pDef->pList);
156215  sqlite3_free(pDef);
156216  }
156217  pCsr->pDeferred = 0;
156218 }
156219 
156220 /*
156221 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
156222 ** based on the row that pCsr currently points to.
156223 **
156224 ** A deferred-doclist is like any other doclist with position information
156225 ** included, except that it only contains entries for a single row of the
156226 ** table, not for all rows.
156227 */
156228 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
156229  int rc = SQLITE_OK; /* Return code */
156230  if( pCsr->pDeferred ){
156231  int i; /* Used to iterate through table columns */
156232  sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
156233  Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
156234 
156235  Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
156236  sqlite3_tokenizer *pT = p->pTokenizer;
156237  sqlite3_tokenizer_module const *pModule = pT->pModule;
156238 
156239  assert( pCsr->isRequireSeek==0 );
156240  iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
156241 
156242  for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
156243  if( p->abNotindexed[i]==0 ){
156244  const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
156245  sqlite3_tokenizer_cursor *pTC = 0;
156246 
156247  rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
156248  while( rc==SQLITE_OK ){
156249  char const *zToken; /* Buffer containing token */
156250  int nToken = 0; /* Number of bytes in token */
156251  int iDum1 = 0, iDum2 = 0; /* Dummy variables */
156252  int iPos = 0; /* Position of token in zText */
156253 
156254  rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
156255  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
156256  Fts3PhraseToken *pPT = pDef->pToken;
156257  if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
156258  && (pPT->bFirst==0 || iPos==0)
156259  && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
156260  && (0==memcmp(zToken, pPT->z, pPT->n))
156261  ){
156262  fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
156263  }
156264  }
156265  }
156266  if( pTC ) pModule->xClose(pTC);
156267  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
156268  }
156269  }
156270 
156271  for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
156272  if( pDef->pList ){
156273  rc = fts3PendingListAppendVarint(&pDef->pList, 0);
156274  }
156275  }
156276  }
156277 
156278  return rc;
156279 }
156280 
156281 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
156282  Fts3DeferredToken *p,
156283  char **ppData,
156284  int *pnData
156285 ){
156286  char *pRet;
156287  int nSkip;
156288  sqlite3_int64 dummy;
156289 
156290  *ppData = 0;
156291  *pnData = 0;
156292 
156293  if( p->pList==0 ){
156294  return SQLITE_OK;
156295  }
156296 
156297  pRet = (char *)sqlite3_malloc(p->pList->nData);
156298  if( !pRet ) return SQLITE_NOMEM;
156299 
156300  nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
156301  *pnData = p->pList->nData - nSkip;
156302  *ppData = pRet;
156303 
156304  memcpy(pRet, &p->pList->aData[nSkip], *pnData);
156305  return SQLITE_OK;
156306 }
156307 
156308 /*
156309 ** Add an entry for token pToken to the pCsr->pDeferred list.
156310 */
156311 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
156312  Fts3Cursor *pCsr, /* Fts3 table cursor */
156313  Fts3PhraseToken *pToken, /* Token to defer */
156314  int iCol /* Column that token must appear in (or -1) */
156315 ){
156316  Fts3DeferredToken *pDeferred;
156317  pDeferred = sqlite3_malloc(sizeof(*pDeferred));
156318  if( !pDeferred ){
156319  return SQLITE_NOMEM;
156320  }
156321  memset(pDeferred, 0, sizeof(*pDeferred));
156322  pDeferred->pToken = pToken;
156323  pDeferred->pNext = pCsr->pDeferred;
156324  pDeferred->iCol = iCol;
156325  pCsr->pDeferred = pDeferred;
156326 
156327  assert( pToken->pDeferred==0 );
156328  pToken->pDeferred = pDeferred;
156329 
156330  return SQLITE_OK;
156331 }
156332 #endif
156333 
156334 /*
156335 ** SQLite value pRowid contains the rowid of a row that may or may not be
156336 ** present in the FTS3 table. If it is, delete it and adjust the contents
156337 ** of subsiduary data structures accordingly.
156338 */
156339 static int fts3DeleteByRowid(
156340  Fts3Table *p,
156341  sqlite3_value *pRowid,
156342  int *pnChng, /* IN/OUT: Decrement if row is deleted */
156343  u32 *aSzDel
156344 ){
156345  int rc = SQLITE_OK; /* Return code */
156346  int bFound = 0; /* True if *pRowid really is in the table */
156347 
156348  fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
156349  if( bFound && rc==SQLITE_OK ){
156350  int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
156351  rc = fts3IsEmpty(p, pRowid, &isEmpty);
156352  if( rc==SQLITE_OK ){
156353  if( isEmpty ){
156354  /* Deleting this row means the whole table is empty. In this case
156355  ** delete the contents of all three tables and throw away any
156356  ** data in the pendingTerms hash table. */
156357  rc = fts3DeleteAll(p, 1);
156358  *pnChng = 0;
156359  memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
156360  }else{
156361  *pnChng = *pnChng - 1;
156362  if( p->zContentTbl==0 ){
156363  fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
156364  }
156365  if( p->bHasDocsize ){
156366  fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
156367  }
156368  }
156369  }
156370  }
156371 
156372  return rc;
156373 }
156374 
156375 /*
156376 ** This function does the work for the xUpdate method of FTS3 virtual
156377 ** tables. The schema of the virtual table being:
156378 **
156379 ** CREATE TABLE <table name>(
156380 ** <user columns>,
156381 ** <table name> HIDDEN,
156382 ** docid HIDDEN,
156383 ** <langid> HIDDEN
156384 ** );
156385 **
156386 **
156387 */
156388 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
156389  sqlite3_vtab *pVtab, /* FTS3 vtab object */
156390  int nArg, /* Size of argument array */
156391  sqlite3_value **apVal, /* Array of arguments */
156392  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
156393 ){
156394  Fts3Table *p = (Fts3Table *)pVtab;
156395  int rc = SQLITE_OK; /* Return Code */
156396  int isRemove = 0; /* True for an UPDATE or DELETE */
156397  u32 *aSzIns = 0; /* Sizes of inserted documents */
156398  u32 *aSzDel = 0; /* Sizes of deleted documents */
156399  int nChng = 0; /* Net change in number of documents */
156400  int bInsertDone = 0;
156401 
156402  /* At this point it must be known if the %_stat table exists or not.
156403  ** So bHasStat may not be 2. */
156404  assert( p->bHasStat==0 || p->bHasStat==1 );
156405 
156406  assert( p->pSegments==0 );
156407  assert(
156408  nArg==1 /* DELETE operations */
156409  || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
156410  );
156411 
156412  /* Check for a "special" INSERT operation. One of the form:
156413  **
156414  ** INSERT INTO xyz(xyz) VALUES('command');
156415  */
156416  if( nArg>1
156417  && sqlite3_value_type(apVal[0])==SQLITE_NULL
156418  && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
156419  ){
156420  rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
156421  goto update_out;
156422  }
156423 
156424  if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
156425  rc = SQLITE_CONSTRAINT;
156426  goto update_out;
156427  }
156428 
156429  /* Allocate space to hold the change in document sizes */
156430  aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
156431  if( aSzDel==0 ){
156432  rc = SQLITE_NOMEM;
156433  goto update_out;
156434  }
156435  aSzIns = &aSzDel[p->nColumn+1];
156436  memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
156437 
156438  rc = fts3Writelock(p);
156439  if( rc!=SQLITE_OK ) goto update_out;
156440 
156441  /* If this is an INSERT operation, or an UPDATE that modifies the rowid
156442  ** value, then this operation requires constraint handling.
156443  **
156444  ** If the on-conflict mode is REPLACE, this means that the existing row
156445  ** should be deleted from the database before inserting the new row. Or,
156446  ** if the on-conflict mode is other than REPLACE, then this method must
156447  ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
156448  ** modify the database file.
156449  */
156450  if( nArg>1 && p->zContentTbl==0 ){
156451  /* Find the value object that holds the new rowid value. */
156452  sqlite3_value *pNewRowid = apVal[3+p->nColumn];
156453  if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
156454  pNewRowid = apVal[1];
156455  }
156456 
156457  if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
156458  sqlite3_value_type(apVal[0])==SQLITE_NULL
156459  || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
156460  )){
156461  /* The new rowid is not NULL (in this case the rowid will be
156462  ** automatically assigned and there is no chance of a conflict), and
156463  ** the statement is either an INSERT or an UPDATE that modifies the
156464  ** rowid column. So if the conflict mode is REPLACE, then delete any
156465  ** existing row with rowid=pNewRowid.
156466  **
156467  ** Or, if the conflict mode is not REPLACE, insert the new record into
156468  ** the %_content table. If we hit the duplicate rowid constraint (or any
156469  ** other error) while doing so, return immediately.
156470  **
156471  ** This branch may also run if pNewRowid contains a value that cannot
156472  ** be losslessly converted to an integer. In this case, the eventual
156473  ** call to fts3InsertData() (either just below or further on in this
156474  ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
156475  ** invoked, it will delete zero rows (since no row will have
156476  ** docid=$pNewRowid if $pNewRowid is not an integer value).
156477  */
156479  rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
156480  }else{
156481  rc = fts3InsertData(p, apVal, pRowid);
156482  bInsertDone = 1;
156483  }
156484  }
156485  }
156486  if( rc!=SQLITE_OK ){
156487  goto update_out;
156488  }
156489 
156490  /* If this is a DELETE or UPDATE operation, remove the old record. */
156491  if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
156492  assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
156493  rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
156494  isRemove = 1;
156495  }
156496 
156497  /* If this is an INSERT or UPDATE operation, insert the new record. */
156498  if( nArg>1 && rc==SQLITE_OK ){
156499  int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
156500  if( bInsertDone==0 ){
156501  rc = fts3InsertData(p, apVal, pRowid);
156502  if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
156503  rc = FTS_CORRUPT_VTAB;
156504  }
156505  }
156506  if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
156507  rc = fts3PendingTermsDocid(p, 0, iLangid, *pRowid);
156508  }
156509  if( rc==SQLITE_OK ){
156510  assert( p->iPrevDocid==*pRowid );
156511  rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
156512  }
156513  if( p->bHasDocsize ){
156514  fts3InsertDocsize(&rc, p, aSzIns);
156515  }
156516  nChng++;
156517  }
156518 
156519  if( p->bFts4 ){
156520  fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
156521  }
156522 
156523  update_out:
156524  sqlite3_free(aSzDel);
156525  sqlite3Fts3SegmentsClose(p);
156526  return rc;
156527 }
156528 
156529 /*
156530 ** Flush any data in the pending-terms hash table to disk. If successful,
156531 ** merge all segments in the database (including the new segment, if
156532 ** there was any data to flush) into a single segment.
156533 */
156534 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
156535  int rc;
156536  rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
156537  if( rc==SQLITE_OK ){
156538  rc = fts3DoOptimize(p, 1);
156539  if( rc==SQLITE_OK || rc==SQLITE_DONE ){
156540  int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
156541  if( rc2!=SQLITE_OK ) rc = rc2;
156542  }else{
156543  sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
156544  sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
156545  }
156546  }
156547  sqlite3Fts3SegmentsClose(p);
156548  return rc;
156549 }
156550 
156551 #endif
156552 
156553 /************** End of fts3_write.c ******************************************/
156554 /************** Begin file fts3_snippet.c ************************************/
156555 /*
156556 ** 2009 Oct 23
156557 **
156558 ** The author disclaims copyright to this source code. In place of
156559 ** a legal notice, here is a blessing:
156560 **
156561 ** May you do good and not evil.
156562 ** May you find forgiveness for yourself and forgive others.
156563 ** May you share freely, never taking more than you give.
156564 **
156565 ******************************************************************************
156566 */
156567 
156568 /* #include "fts3Int.h" */
156569 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
156570 
156571 /* #include <string.h> */
156572 /* #include <assert.h> */
156573 
156574 /*
156575 ** Characters that may appear in the second argument to matchinfo().
156576 */
156577 #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
156578 #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
156579 #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
156580 #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
156581 #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
156582 #define FTS3_MATCHINFO_LCS 's' /* nCol values */
156583 #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
156584 #define FTS3_MATCHINFO_LHITS 'y' /* nCol*nPhrase values */
156585 #define FTS3_MATCHINFO_LHITS_BM 'b' /* nCol*nPhrase values */
156586 
156587 /*
156588 ** The default value for the second argument to matchinfo().
156589 */
156590 #define FTS3_MATCHINFO_DEFAULT "pcx"
156591 
156592 
156593 /*
156594 ** Used as an fts3ExprIterate() context when loading phrase doclists to
156595 ** Fts3Expr.aDoclist[]/nDoclist.
156596 */
156597 typedef struct LoadDoclistCtx LoadDoclistCtx;
156598 struct LoadDoclistCtx {
156599  Fts3Cursor *pCsr; /* FTS3 Cursor */
156600  int nPhrase; /* Number of phrases seen so far */
156601  int nToken; /* Number of tokens seen so far */
156602 };
156603 
156604 /*
156605 ** The following types are used as part of the implementation of the
156606 ** fts3BestSnippet() routine.
156607 */
156608 typedef struct SnippetIter SnippetIter;
156609 typedef struct SnippetPhrase SnippetPhrase;
156610 typedef struct SnippetFragment SnippetFragment;
156611 
156612 struct SnippetIter {
156613  Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
156614  int iCol; /* Extract snippet from this column */
156615  int nSnippet; /* Requested snippet length (in tokens) */
156616  int nPhrase; /* Number of phrases in query */
156617  SnippetPhrase *aPhrase; /* Array of size nPhrase */
156618  int iCurrent; /* First token of current snippet */
156619 };
156620 
156621 struct SnippetPhrase {
156622  int nToken; /* Number of tokens in phrase */
156623  char *pList; /* Pointer to start of phrase position list */
156624  int iHead; /* Next value in position list */
156625  char *pHead; /* Position list data following iHead */
156626  int iTail; /* Next value in trailing position list */
156627  char *pTail; /* Position list data following iTail */
156628 };
156629 
156630 struct SnippetFragment {
156631  int iCol; /* Column snippet is extracted from */
156632  int iPos; /* Index of first token in snippet */
156633  u64 covered; /* Mask of query phrases covered */
156634  u64 hlmask; /* Mask of snippet terms to highlight */
156635 };
156636 
156637 /*
156638 ** This type is used as an fts3ExprIterate() context object while
156639 ** accumulating the data returned by the matchinfo() function.
156640 */
156641 typedef struct MatchInfo MatchInfo;
156642 struct MatchInfo {
156643  Fts3Cursor *pCursor; /* FTS3 Cursor */
156644  int nCol; /* Number of columns in table */
156645  int nPhrase; /* Number of matchable phrases in query */
156646  sqlite3_int64 nDoc; /* Number of docs in database */
156647  char flag;
156648  u32 *aMatchinfo; /* Pre-allocated buffer */
156649 };
156650 
156651 /*
156652 ** An instance of this structure is used to manage a pair of buffers, each
156653 ** (nElem * sizeof(u32)) bytes in size. See the MatchinfoBuffer code below
156654 ** for details.
156655 */
156656 struct MatchinfoBuffer {
156657  u8 aRef[3];
156658  int nElem;
156659  int bGlobal; /* Set if global data is loaded */
156660  char *zMatchinfo;
156661  u32 aMatchinfo[1];
156662 };
156663 
156664 
156665 /*
156666 ** The snippet() and offsets() functions both return text values. An instance
156667 ** of the following structure is used to accumulate those values while the
156668 ** functions are running. See fts3StringAppend() for details.
156669 */
156670 typedef struct StrBuffer StrBuffer;
156671 struct StrBuffer {
156672  char *z; /* Pointer to buffer containing string */
156673  int n; /* Length of z in bytes (excl. nul-term) */
156674  int nAlloc; /* Allocated size of buffer z in bytes */
156675 };
156676 
156677 
156678 /*************************************************************************
156679 ** Start of MatchinfoBuffer code.
156680 */
156681 
156682 /*
156683 ** Allocate a two-slot MatchinfoBuffer object.
156684 */
156685 static MatchinfoBuffer *fts3MIBufferNew(int nElem, const char *zMatchinfo){
156686  MatchinfoBuffer *pRet;
156687  int nByte = sizeof(u32) * (2*nElem + 1) + sizeof(MatchinfoBuffer);
156688  int nStr = (int)strlen(zMatchinfo);
156689 
156690  pRet = sqlite3_malloc(nByte + nStr+1);
156691  if( pRet ){
156692  memset(pRet, 0, nByte);
156693  pRet->aMatchinfo[0] = (u8*)(&pRet->aMatchinfo[1]) - (u8*)pRet;
156694  pRet->aMatchinfo[1+nElem] = pRet->aMatchinfo[0] + sizeof(u32)*(nElem+1);
156695  pRet->nElem = nElem;
156696  pRet->zMatchinfo = ((char*)pRet) + nByte;
156697  memcpy(pRet->zMatchinfo, zMatchinfo, nStr+1);
156698  pRet->aRef[0] = 1;
156699  }
156700 
156701  return pRet;
156702 }
156703 
156704 static void fts3MIBufferFree(void *p){
156705  MatchinfoBuffer *pBuf = (MatchinfoBuffer*)((u8*)p - ((u32*)p)[-1]);
156706 
156707  assert( (u32*)p==&pBuf->aMatchinfo[1]
156708  || (u32*)p==&pBuf->aMatchinfo[pBuf->nElem+2]
156709  );
156710  if( (u32*)p==&pBuf->aMatchinfo[1] ){
156711  pBuf->aRef[1] = 0;
156712  }else{
156713  pBuf->aRef[2] = 0;
156714  }
156715 
156716  if( pBuf->aRef[0]==0 && pBuf->aRef[1]==0 && pBuf->aRef[2]==0 ){
156717  sqlite3_free(pBuf);
156718  }
156719 }
156720 
156721 static void (*fts3MIBufferAlloc(MatchinfoBuffer *p, u32 **paOut))(void*){
156722  void (*xRet)(void*) = 0;
156723  u32 *aOut = 0;
156724 
156725  if( p->aRef[1]==0 ){
156726  p->aRef[1] = 1;
156727  aOut = &p->aMatchinfo[1];
156728  xRet = fts3MIBufferFree;
156729  }
156730  else if( p->aRef[2]==0 ){
156731  p->aRef[2] = 1;
156732  aOut = &p->aMatchinfo[p->nElem+2];
156733  xRet = fts3MIBufferFree;
156734  }else{
156735  aOut = (u32*)sqlite3_malloc(p->nElem * sizeof(u32));
156736  if( aOut ){
156737  xRet = sqlite3_free;
156738  if( p->bGlobal ) memcpy(aOut, &p->aMatchinfo[1], p->nElem*sizeof(u32));
156739  }
156740  }
156741 
156742  *paOut = aOut;
156743  return xRet;
156744 }
156745 
156746 static void fts3MIBufferSetGlobal(MatchinfoBuffer *p){
156747  p->bGlobal = 1;
156748  memcpy(&p->aMatchinfo[2+p->nElem], &p->aMatchinfo[1], p->nElem*sizeof(u32));
156749 }
156750 
156751 /*
156752 ** Free a MatchinfoBuffer object allocated using fts3MIBufferNew()
156753 */
156754 SQLITE_PRIVATE void sqlite3Fts3MIBufferFree(MatchinfoBuffer *p){
156755  if( p ){
156756  assert( p->aRef[0]==1 );
156757  p->aRef[0] = 0;
156758  if( p->aRef[0]==0 && p->aRef[1]==0 && p->aRef[2]==0 ){
156759  sqlite3_free(p);
156760  }
156761  }
156762 }
156763 
156764 /*
156765 ** End of MatchinfoBuffer code.
156766 *************************************************************************/
156767 
156768 
156769 /*
156770 ** This function is used to help iterate through a position-list. A position
156771 ** list is a list of unique integers, sorted from smallest to largest. Each
156772 ** element of the list is represented by an FTS3 varint that takes the value
156773 ** of the difference between the current element and the previous one plus
156774 ** two. For example, to store the position-list:
156775 **
156776 ** 4 9 113
156777 **
156778 ** the three varints:
156779 **
156780 ** 6 7 106
156781 **
156782 ** are encoded.
156783 **
156784 ** When this function is called, *pp points to the start of an element of
156785 ** the list. *piPos contains the value of the previous entry in the list.
156786 ** After it returns, *piPos contains the value of the next element of the
156787 ** list and *pp is advanced to the following varint.
156788 */
156789 static void fts3GetDeltaPosition(char **pp, int *piPos){
156790  int iVal;
156791  *pp += fts3GetVarint32(*pp, &iVal);
156792  *piPos += (iVal-2);
156793 }
156794 
156795 /*
156796 ** Helper function for fts3ExprIterate() (see below).
156797 */
156798 static int fts3ExprIterate2(
156799  Fts3Expr *pExpr, /* Expression to iterate phrases of */
156800  int *piPhrase, /* Pointer to phrase counter */
156801  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
156802  void *pCtx /* Second argument to pass to callback */
156803 ){
156804  int rc; /* Return code */
156805  int eType = pExpr->eType; /* Type of expression node pExpr */
156806 
156807  if( eType!=FTSQUERY_PHRASE ){
156808  assert( pExpr->pLeft && pExpr->pRight );
156809  rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
156810  if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
156811  rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
156812  }
156813  }else{
156814  rc = x(pExpr, *piPhrase, pCtx);
156815  (*piPhrase)++;
156816  }
156817  return rc;
156818 }
156819 
156820 /*
156821 ** Iterate through all phrase nodes in an FTS3 query, except those that
156822 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
156823 ** For each phrase node found, the supplied callback function is invoked.
156824 **
156825 ** If the callback function returns anything other than SQLITE_OK,
156826 ** the iteration is abandoned and the error code returned immediately.
156827 ** Otherwise, SQLITE_OK is returned after a callback has been made for
156828 ** all eligible phrase nodes.
156829 */
156830 static int fts3ExprIterate(
156831  Fts3Expr *pExpr, /* Expression to iterate phrases of */
156832  int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
156833  void *pCtx /* Second argument to pass to callback */
156834 ){
156835  int iPhrase = 0; /* Variable used as the phrase counter */
156836  return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
156837 }
156838 
156839 
156840 /*
156841 ** This is an fts3ExprIterate() callback used while loading the doclists
156842 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
156843 ** fts3ExprLoadDoclists().
156844 */
156845 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
156846  int rc = SQLITE_OK;
156847  Fts3Phrase *pPhrase = pExpr->pPhrase;
156848  LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
156849 
156850  UNUSED_PARAMETER(iPhrase);
156851 
156852  p->nPhrase++;
156853  p->nToken += pPhrase->nToken;
156854 
156855  return rc;
156856 }
156857 
156858 /*
156859 ** Load the doclists for each phrase in the query associated with FTS3 cursor
156860 ** pCsr.
156861 **
156862 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
156863 ** phrases in the expression (all phrases except those directly or
156864 ** indirectly descended from the right-hand-side of a NOT operator). If
156865 ** pnToken is not NULL, then it is set to the number of tokens in all
156866 ** matchable phrases of the expression.
156867 */
156868 static int fts3ExprLoadDoclists(
156869  Fts3Cursor *pCsr, /* Fts3 cursor for current query */
156870  int *pnPhrase, /* OUT: Number of phrases in query */
156871  int *pnToken /* OUT: Number of tokens in query */
156872 ){
156873  int rc; /* Return Code */
156874  LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
156875  sCtx.pCsr = pCsr;
156876  rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
156877  if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
156878  if( pnToken ) *pnToken = sCtx.nToken;
156879  return rc;
156880 }
156881 
156882 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
156883  (*(int *)ctx)++;
156884  pExpr->iPhrase = iPhrase;
156885  return SQLITE_OK;
156886 }
156887 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
156888  int nPhrase = 0;
156889  (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
156890  return nPhrase;
156891 }
156892 
156893 /*
156894 ** Advance the position list iterator specified by the first two
156895 ** arguments so that it points to the first element with a value greater
156896 ** than or equal to parameter iNext.
156897 */
156898 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
156899  char *pIter = *ppIter;
156900  if( pIter ){
156901  int iIter = *piIter;
156902 
156903  while( iIter<iNext ){
156904  if( 0==(*pIter & 0xFE) ){
156905  iIter = -1;
156906  pIter = 0;
156907  break;
156908  }
156909  fts3GetDeltaPosition(&pIter, &iIter);
156910  }
156911 
156912  *piIter = iIter;
156913  *ppIter = pIter;
156914  }
156915 }
156916 
156917 /*
156918 ** Advance the snippet iterator to the next candidate snippet.
156919 */
156920 static int fts3SnippetNextCandidate(SnippetIter *pIter){
156921  int i; /* Loop counter */
156922 
156923  if( pIter->iCurrent<0 ){
156924  /* The SnippetIter object has just been initialized. The first snippet
156925  ** candidate always starts at offset 0 (even if this candidate has a
156926  ** score of 0.0).
156927  */
156928  pIter->iCurrent = 0;
156929 
156930  /* Advance the 'head' iterator of each phrase to the first offset that
156931  ** is greater than or equal to (iNext+nSnippet).
156932  */
156933  for(i=0; i<pIter->nPhrase; i++){
156934  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
156935  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
156936  }
156937  }else{
156938  int iStart;
156939  int iEnd = 0x7FFFFFFF;
156940 
156941  for(i=0; i<pIter->nPhrase; i++){
156942  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
156943  if( pPhrase->pHead && pPhrase->iHead<iEnd ){
156944  iEnd = pPhrase->iHead;
156945  }
156946  }
156947  if( iEnd==0x7FFFFFFF ){
156948  return 1;
156949  }
156950 
156951  pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
156952  for(i=0; i<pIter->nPhrase; i++){
156953  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
156954  fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
156955  fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
156956  }
156957  }
156958 
156959  return 0;
156960 }
156961 
156962 /*
156963 ** Retrieve information about the current candidate snippet of snippet
156964 ** iterator pIter.
156965 */
156966 static void fts3SnippetDetails(
156967  SnippetIter *pIter, /* Snippet iterator */
156968  u64 mCovered, /* Bitmask of phrases already covered */
156969  int *piToken, /* OUT: First token of proposed snippet */
156970  int *piScore, /* OUT: "Score" for this snippet */
156971  u64 *pmCover, /* OUT: Bitmask of phrases covered */
156972  u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
156973 ){
156974  int iStart = pIter->iCurrent; /* First token of snippet */
156975  int iScore = 0; /* Score of this snippet */
156976  int i; /* Loop counter */
156977  u64 mCover = 0; /* Mask of phrases covered by this snippet */
156978  u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
156979 
156980  for(i=0; i<pIter->nPhrase; i++){
156981  SnippetPhrase *pPhrase = &pIter->aPhrase[i];
156982  if( pPhrase->pTail ){
156983  char *pCsr = pPhrase->pTail;
156984  int iCsr = pPhrase->iTail;
156985 
156986  while( iCsr<(iStart+pIter->nSnippet) ){
156987  int j;
156988  u64 mPhrase = (u64)1 << i;
156989  u64 mPos = (u64)1 << (iCsr - iStart);
156990  assert( iCsr>=iStart );
156991  if( (mCover|mCovered)&mPhrase ){
156992  iScore++;
156993  }else{
156994  iScore += 1000;
156995  }
156996  mCover |= mPhrase;
156997 
156998  for(j=0; j<pPhrase->nToken; j++){
156999  mHighlight |= (mPos>>j);
157000  }
157001 
157002  if( 0==(*pCsr & 0x0FE) ) break;
157003  fts3GetDeltaPosition(&pCsr, &iCsr);
157004  }
157005  }
157006  }
157007 
157008  /* Set the output variables before returning. */
157009  *piToken = iStart;
157010  *piScore = iScore;
157011  *pmCover = mCover;
157012  *pmHighlight = mHighlight;
157013 }
157014 
157015 /*
157016 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
157017 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
157018 */
157019 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
157020  SnippetIter *p = (SnippetIter *)ctx;
157021  SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
157022  char *pCsr;
157023  int rc;
157024 
157025  pPhrase->nToken = pExpr->pPhrase->nToken;
157026  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
157027  assert( rc==SQLITE_OK || pCsr==0 );
157028  if( pCsr ){
157029  int iFirst = 0;
157030  pPhrase->pList = pCsr;
157031  fts3GetDeltaPosition(&pCsr, &iFirst);
157032  assert( iFirst>=0 );
157033  pPhrase->pHead = pCsr;
157034  pPhrase->pTail = pCsr;
157035  pPhrase->iHead = iFirst;
157036  pPhrase->iTail = iFirst;
157037  }else{
157038  assert( rc!=SQLITE_OK || (
157039  pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
157040  ));
157041  }
157042 
157043  return rc;
157044 }
157045 
157046 /*
157047 ** Select the fragment of text consisting of nFragment contiguous tokens
157048 ** from column iCol that represent the "best" snippet. The best snippet
157049 ** is the snippet with the highest score, where scores are calculated
157050 ** by adding:
157051 **
157052 ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
157053 **
157054 ** (b) +1000 points for the first occurrence of each matchable phrase in
157055 ** the snippet for which the corresponding mCovered bit is not set.
157056 **
157057 ** The selected snippet parameters are stored in structure *pFragment before
157058 ** returning. The score of the selected snippet is stored in *piScore
157059 ** before returning.
157060 */
157061 static int fts3BestSnippet(
157062  int nSnippet, /* Desired snippet length */
157063  Fts3Cursor *pCsr, /* Cursor to create snippet for */
157064  int iCol, /* Index of column to create snippet from */
157065  u64 mCovered, /* Mask of phrases already covered */
157066  u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
157067  SnippetFragment *pFragment, /* OUT: Best snippet found */
157068  int *piScore /* OUT: Score of snippet pFragment */
157069 ){
157070  int rc; /* Return Code */
157071  int nList; /* Number of phrases in expression */
157072  SnippetIter sIter; /* Iterates through snippet candidates */
157073  int nByte; /* Number of bytes of space to allocate */
157074  int iBestScore = -1; /* Best snippet score found so far */
157075  int i; /* Loop counter */
157076 
157077  memset(&sIter, 0, sizeof(sIter));
157078 
157079  /* Iterate through the phrases in the expression to count them. The same
157080  ** callback makes sure the doclists are loaded for each phrase.
157081  */
157082  rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
157083  if( rc!=SQLITE_OK ){
157084  return rc;
157085  }
157086 
157087  /* Now that it is known how many phrases there are, allocate and zero
157088  ** the required space using malloc().
157089  */
157090  nByte = sizeof(SnippetPhrase) * nList;
157091  sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
157092  if( !sIter.aPhrase ){
157093  return SQLITE_NOMEM;
157094  }
157095  memset(sIter.aPhrase, 0, nByte);
157096 
157097  /* Initialize the contents of the SnippetIter object. Then iterate through
157098  ** the set of phrases in the expression to populate the aPhrase[] array.
157099  */
157100  sIter.pCsr = pCsr;
157101  sIter.iCol = iCol;
157102  sIter.nSnippet = nSnippet;
157103  sIter.nPhrase = nList;
157104  sIter.iCurrent = -1;
157105  rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void*)&sIter);
157106  if( rc==SQLITE_OK ){
157107 
157108  /* Set the *pmSeen output variable. */
157109  for(i=0; i<nList; i++){
157110  if( sIter.aPhrase[i].pHead ){
157111  *pmSeen |= (u64)1 << i;
157112  }
157113  }
157114 
157115  /* Loop through all candidate snippets. Store the best snippet in
157116  ** *pFragment. Store its associated 'score' in iBestScore.
157117  */
157118  pFragment->iCol = iCol;
157119  while( !fts3SnippetNextCandidate(&sIter) ){
157120  int iPos;
157121  int iScore;
157122  u64 mCover;
157123  u64 mHighlite;
157124  fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
157125  assert( iScore>=0 );
157126  if( iScore>iBestScore ){
157127  pFragment->iPos = iPos;
157128  pFragment->hlmask = mHighlite;
157129  pFragment->covered = mCover;
157130  iBestScore = iScore;
157131  }
157132  }
157133 
157134  *piScore = iBestScore;
157135  }
157136  sqlite3_free(sIter.aPhrase);
157137  return rc;
157138 }
157139 
157140 
157141 /*
157142 ** Append a string to the string-buffer passed as the first argument.
157143 **
157144 ** If nAppend is negative, then the length of the string zAppend is
157145 ** determined using strlen().
157146 */
157147 static int fts3StringAppend(
157148  StrBuffer *pStr, /* Buffer to append to */
157149  const char *zAppend, /* Pointer to data to append to buffer */
157150  int nAppend /* Size of zAppend in bytes (or -1) */
157151 ){
157152  if( nAppend<0 ){
157153  nAppend = (int)strlen(zAppend);
157154  }
157155 
157156  /* If there is insufficient space allocated at StrBuffer.z, use realloc()
157157  ** to grow the buffer until so that it is big enough to accomadate the
157158  ** appended data.
157159  */
157160  if( pStr->n+nAppend+1>=pStr->nAlloc ){
157161  int nAlloc = pStr->nAlloc+nAppend+100;
157162  char *zNew = sqlite3_realloc(pStr->z, nAlloc);
157163  if( !zNew ){
157164  return SQLITE_NOMEM;
157165  }
157166  pStr->z = zNew;
157167  pStr->nAlloc = nAlloc;
157168  }
157169  assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
157170 
157171  /* Append the data to the string buffer. */
157172  memcpy(&pStr->z[pStr->n], zAppend, nAppend);
157173  pStr->n += nAppend;
157174  pStr->z[pStr->n] = '\0';
157175 
157176  return SQLITE_OK;
157177 }
157178 
157179 /*
157180 ** The fts3BestSnippet() function often selects snippets that end with a
157181 ** query term. That is, the final term of the snippet is always a term
157182 ** that requires highlighting. For example, if 'X' is a highlighted term
157183 ** and '.' is a non-highlighted term, BestSnippet() may select:
157184 **
157185 ** ........X.....X
157186 **
157187 ** This function "shifts" the beginning of the snippet forward in the
157188 ** document so that there are approximately the same number of
157189 ** non-highlighted terms to the right of the final highlighted term as there
157190 ** are to the left of the first highlighted term. For example, to this:
157191 **
157192 ** ....X.....X....
157193 **
157194 ** This is done as part of extracting the snippet text, not when selecting
157195 ** the snippet. Snippet selection is done based on doclists only, so there
157196 ** is no way for fts3BestSnippet() to know whether or not the document
157197 ** actually contains terms that follow the final highlighted term.
157198 */
157199 static int fts3SnippetShift(
157200  Fts3Table *pTab, /* FTS3 table snippet comes from */
157201  int iLangid, /* Language id to use in tokenizing */
157202  int nSnippet, /* Number of tokens desired for snippet */
157203  const char *zDoc, /* Document text to extract snippet from */
157204  int nDoc, /* Size of buffer zDoc in bytes */
157205  int *piPos, /* IN/OUT: First token of snippet */
157206  u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
157207 ){
157208  u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
157209 
157210  if( hlmask ){
157211  int nLeft; /* Tokens to the left of first highlight */
157212  int nRight; /* Tokens to the right of last highlight */
157213  int nDesired; /* Ideal number of tokens to shift forward */
157214 
157215  for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
157216  for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
157217  nDesired = (nLeft-nRight)/2;
157218 
157219  /* Ideally, the start of the snippet should be pushed forward in the
157220  ** document nDesired tokens. This block checks if there are actually
157221  ** nDesired tokens to the right of the snippet. If so, *piPos and
157222  ** *pHlMask are updated to shift the snippet nDesired tokens to the
157223  ** right. Otherwise, the snippet is shifted by the number of tokens
157224  ** available.
157225  */
157226  if( nDesired>0 ){
157227  int nShift; /* Number of tokens to shift snippet by */
157228  int iCurrent = 0; /* Token counter */
157229  int rc; /* Return Code */
157230  sqlite3_tokenizer_module *pMod;
157231  sqlite3_tokenizer_cursor *pC;
157232  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
157233 
157234  /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
157235  ** or more tokens in zDoc/nDoc.
157236  */
157237  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
157238  if( rc!=SQLITE_OK ){
157239  return rc;
157240  }
157241  while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
157242  const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
157243  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
157244  }
157245  pMod->xClose(pC);
157246  if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
157247 
157248  nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
157249  assert( nShift<=nDesired );
157250  if( nShift>0 ){
157251  *piPos += nShift;
157252  *pHlmask = hlmask >> nShift;
157253  }
157254  }
157255  }
157256  return SQLITE_OK;
157257 }
157258 
157259 /*
157260 ** Extract the snippet text for fragment pFragment from cursor pCsr and
157261 ** append it to string buffer pOut.
157262 */
157263 static int fts3SnippetText(
157264  Fts3Cursor *pCsr, /* FTS3 Cursor */
157265  SnippetFragment *pFragment, /* Snippet to extract */
157266  int iFragment, /* Fragment number */
157267  int isLast, /* True for final fragment in snippet */
157268  int nSnippet, /* Number of tokens in extracted snippet */
157269  const char *zOpen, /* String inserted before highlighted term */
157270  const char *zClose, /* String inserted after highlighted term */
157271  const char *zEllipsis, /* String inserted between snippets */
157272  StrBuffer *pOut /* Write output here */
157273 ){
157274  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
157275  int rc; /* Return code */
157276  const char *zDoc; /* Document text to extract snippet from */
157277  int nDoc; /* Size of zDoc in bytes */
157278  int iCurrent = 0; /* Current token number of document */
157279  int iEnd = 0; /* Byte offset of end of current token */
157280  int isShiftDone = 0; /* True after snippet is shifted */
157281  int iPos = pFragment->iPos; /* First token of snippet */
157282  u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
157283  int iCol = pFragment->iCol+1; /* Query column to extract text from */
157284  sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
157285  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
157286 
157287  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
157288  if( zDoc==0 ){
157289  if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
157290  return SQLITE_NOMEM;
157291  }
157292  return SQLITE_OK;
157293  }
157294  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
157295 
157296  /* Open a token cursor on the document. */
157297  pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
157298  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
157299  if( rc!=SQLITE_OK ){
157300  return rc;
157301  }
157302 
157303  while( rc==SQLITE_OK ){
157304  const char *ZDUMMY; /* Dummy argument used with tokenizer */
157305  int DUMMY1 = -1; /* Dummy argument used with tokenizer */
157306  int iBegin = 0; /* Offset in zDoc of start of token */
157307  int iFin = 0; /* Offset in zDoc of end of token */
157308  int isHighlight = 0; /* True for highlighted terms */
157309 
157310  /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
157311  ** in the FTS code the variable that the third argument to xNext points to
157312  ** is initialized to zero before the first (*but not necessarily
157313  ** subsequent*) call to xNext(). This is done for a particular application
157314  ** that needs to know whether or not the tokenizer is being used for
157315  ** snippet generation or for some other purpose.
157316  **
157317  ** Extreme care is required when writing code to depend on this
157318  ** initialization. It is not a documented part of the tokenizer interface.
157319  ** If a tokenizer is used directly by any code outside of FTS, this
157320  ** convention might not be respected. */
157321  rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
157322  if( rc!=SQLITE_OK ){
157323  if( rc==SQLITE_DONE ){
157324  /* Special case - the last token of the snippet is also the last token
157325  ** of the column. Append any punctuation that occurred between the end
157326  ** of the previous token and the end of the document to the output.
157327  ** Then break out of the loop. */
157328  rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
157329  }
157330  break;
157331  }
157332  if( iCurrent<iPos ){ continue; }
157333 
157334  if( !isShiftDone ){
157335  int n = nDoc - iBegin;
157336  rc = fts3SnippetShift(
157337  pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
157338  );
157339  isShiftDone = 1;
157340 
157341  /* Now that the shift has been done, check if the initial "..." are
157342  ** required. They are required if (a) this is not the first fragment,
157343  ** or (b) this fragment does not begin at position 0 of its column.
157344  */
157345  if( rc==SQLITE_OK ){
157346  if( iPos>0 || iFragment>0 ){
157347  rc = fts3StringAppend(pOut, zEllipsis, -1);
157348  }else if( iBegin ){
157349  rc = fts3StringAppend(pOut, zDoc, iBegin);
157350  }
157351  }
157352  if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
157353  }
157354 
157355  if( iCurrent>=(iPos+nSnippet) ){
157356  if( isLast ){
157357  rc = fts3StringAppend(pOut, zEllipsis, -1);
157358  }
157359  break;
157360  }
157361 
157362  /* Set isHighlight to true if this term should be highlighted. */
157363  isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
157364 
157365  if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
157366  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
157367  if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
157368  if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
157369 
157370  iEnd = iFin;
157371  }
157372 
157373  pMod->xClose(pC);
157374  return rc;
157375 }
157376 
157377 
157378 /*
157379 ** This function is used to count the entries in a column-list (a
157380 ** delta-encoded list of term offsets within a single column of a single
157381 ** row). When this function is called, *ppCollist should point to the
157382 ** beginning of the first varint in the column-list (the varint that
157383 ** contains the position of the first matching term in the column data).
157384 ** Before returning, *ppCollist is set to point to the first byte after
157385 ** the last varint in the column-list (either the 0x00 signifying the end
157386 ** of the position-list, or the 0x01 that precedes the column number of
157387 ** the next column in the position-list).
157388 **
157389 ** The number of elements in the column-list is returned.
157390 */
157391 static int fts3ColumnlistCount(char **ppCollist){
157392  char *pEnd = *ppCollist;
157393  char c = 0;
157394  int nEntry = 0;
157395 
157396  /* A column-list is terminated by either a 0x01 or 0x00. */
157397  while( 0xFE & (*pEnd | c) ){
157398  c = *pEnd++ & 0x80;
157399  if( !c ) nEntry++;
157400  }
157401 
157402  *ppCollist = pEnd;
157403  return nEntry;
157404 }
157405 
157406 /*
157407 ** This function gathers 'y' or 'b' data for a single phrase.
157408 */
157409 static void fts3ExprLHits(
157410  Fts3Expr *pExpr, /* Phrase expression node */
157411  MatchInfo *p /* Matchinfo context */
157412 ){
157413  Fts3Table *pTab = (Fts3Table *)p->pCursor->base.pVtab;
157414  int iStart;
157415  Fts3Phrase *pPhrase = pExpr->pPhrase;
157416  char *pIter = pPhrase->doclist.pList;
157417  int iCol = 0;
157418 
157419  assert( p->flag==FTS3_MATCHINFO_LHITS_BM || p->flag==FTS3_MATCHINFO_LHITS );
157420  if( p->flag==FTS3_MATCHINFO_LHITS ){
157421  iStart = pExpr->iPhrase * p->nCol;
157422  }else{
157423  iStart = pExpr->iPhrase * ((p->nCol + 31) / 32);
157424  }
157425 
157426  while( 1 ){
157427  int nHit = fts3ColumnlistCount(&pIter);
157428  if( (pPhrase->iColumn>=pTab->nColumn || pPhrase->iColumn==iCol) ){
157429  if( p->flag==FTS3_MATCHINFO_LHITS ){
157430  p->aMatchinfo[iStart + iCol] = (u32)nHit;
157431  }else if( nHit ){
157432  p->aMatchinfo[iStart + (iCol+1)/32] |= (1 << (iCol&0x1F));
157433  }
157434  }
157435  assert( *pIter==0x00 || *pIter==0x01 );
157436  if( *pIter!=0x01 ) break;
157437  pIter++;
157438  pIter += fts3GetVarint32(pIter, &iCol);
157439  }
157440 }
157441 
157442 /*
157443 ** Gather the results for matchinfo directives 'y' and 'b'.
157444 */
157445 static void fts3ExprLHitGather(
157446  Fts3Expr *pExpr,
157447  MatchInfo *p
157448 ){
157449  assert( (pExpr->pLeft==0)==(pExpr->pRight==0) );
157450  if( pExpr->bEof==0 && pExpr->iDocid==p->pCursor->iPrevId ){
157451  if( pExpr->pLeft ){
157452  fts3ExprLHitGather(pExpr->pLeft, p);
157453  fts3ExprLHitGather(pExpr->pRight, p);
157454  }else{
157455  fts3ExprLHits(pExpr, p);
157456  }
157457  }
157458 }
157459 
157460 /*
157461 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
157462 ** for a single query.
157463 **
157464 ** fts3ExprIterate() callback to load the 'global' elements of a
157465 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
157466 ** of the matchinfo array that are constant for all rows returned by the
157467 ** current query.
157468 **
157469 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
157470 ** function populates Matchinfo.aMatchinfo[] as follows:
157471 **
157472 ** for(iCol=0; iCol<nCol; iCol++){
157473 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
157474 ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
157475 ** }
157476 **
157477 ** where X is the number of matches for phrase iPhrase is column iCol of all
157478 ** rows of the table. Y is the number of rows for which column iCol contains
157479 ** at least one instance of phrase iPhrase.
157480 **
157481 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
157482 ** Y values are set to nDoc, where nDoc is the number of documents in the
157483 ** file system. This is done because the full-text index doclist is required
157484 ** to calculate these values properly, and the full-text index doclist is
157485 ** not available for deferred tokens.
157486 */
157487 static int fts3ExprGlobalHitsCb(
157488  Fts3Expr *pExpr, /* Phrase expression node */
157489  int iPhrase, /* Phrase number (numbered from zero) */
157490  void *pCtx /* Pointer to MatchInfo structure */
157491 ){
157492  MatchInfo *p = (MatchInfo *)pCtx;
157493  return sqlite3Fts3EvalPhraseStats(
157494  p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
157495  );
157496 }
157497 
157498 /*
157499 ** fts3ExprIterate() callback used to collect the "local" part of the
157500 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
157501 ** array that are different for each row returned by the query.
157502 */
157503 static int fts3ExprLocalHitsCb(
157504  Fts3Expr *pExpr, /* Phrase expression node */
157505  int iPhrase, /* Phrase number */
157506  void *pCtx /* Pointer to MatchInfo structure */
157507 ){
157508  int rc = SQLITE_OK;
157509  MatchInfo *p = (MatchInfo *)pCtx;
157510  int iStart = iPhrase * p->nCol * 3;
157511  int i;
157512 
157513  for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
157514  char *pCsr;
157515  rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
157516  if( pCsr ){
157517  p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
157518  }else{
157519  p->aMatchinfo[iStart+i*3] = 0;
157520  }
157521  }
157522 
157523  return rc;
157524 }
157525 
157526 static int fts3MatchinfoCheck(
157527  Fts3Table *pTab,
157528  char cArg,
157529  char **pzErr
157530 ){
157531  if( (cArg==FTS3_MATCHINFO_NPHRASE)
157532  || (cArg==FTS3_MATCHINFO_NCOL)
157533  || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
157534  || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
157535  || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
157536  || (cArg==FTS3_MATCHINFO_LCS)
157537  || (cArg==FTS3_MATCHINFO_HITS)
157538  || (cArg==FTS3_MATCHINFO_LHITS)
157539  || (cArg==FTS3_MATCHINFO_LHITS_BM)
157540  ){
157541  return SQLITE_OK;
157542  }
157543  sqlite3Fts3ErrMsg(pzErr, "unrecognized matchinfo request: %c", cArg);
157544  return SQLITE_ERROR;
157545 }
157546 
157547 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
157548  int nVal; /* Number of integers output by cArg */
157549 
157550  switch( cArg ){
157551  case FTS3_MATCHINFO_NDOC:
157552  case FTS3_MATCHINFO_NPHRASE:
157553  case FTS3_MATCHINFO_NCOL:
157554  nVal = 1;
157555  break;
157556 
157557  case FTS3_MATCHINFO_AVGLENGTH:
157558  case FTS3_MATCHINFO_LENGTH:
157559  case FTS3_MATCHINFO_LCS:
157560  nVal = pInfo->nCol;
157561  break;
157562 
157563  case FTS3_MATCHINFO_LHITS:
157564  nVal = pInfo->nCol * pInfo->nPhrase;
157565  break;
157566 
157567  case FTS3_MATCHINFO_LHITS_BM:
157568  nVal = pInfo->nPhrase * ((pInfo->nCol + 31) / 32);
157569  break;
157570 
157571  default:
157572  assert( cArg==FTS3_MATCHINFO_HITS );
157573  nVal = pInfo->nCol * pInfo->nPhrase * 3;
157574  break;
157575  }
157576 
157577  return nVal;
157578 }
157579 
157580 static int fts3MatchinfoSelectDoctotal(
157581  Fts3Table *pTab,
157582  sqlite3_stmt **ppStmt,
157583  sqlite3_int64 *pnDoc,
157584  const char **paLen
157585 ){
157586  sqlite3_stmt *pStmt;
157587  const char *a;
157588  sqlite3_int64 nDoc;
157589 
157590  if( !*ppStmt ){
157591  int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
157592  if( rc!=SQLITE_OK ) return rc;
157593  }
157594  pStmt = *ppStmt;
157595  assert( sqlite3_data_count(pStmt)==1 );
157596 
157597  a = sqlite3_column_blob(pStmt, 0);
157598  a += sqlite3Fts3GetVarint(a, &nDoc);
157599  if( nDoc==0 ) return FTS_CORRUPT_VTAB;
157600  *pnDoc = (u32)nDoc;
157601 
157602  if( paLen ) *paLen = a;
157603  return SQLITE_OK;
157604 }
157605 
157606 /*
157607 ** An instance of the following structure is used to store state while
157608 ** iterating through a multi-column position-list corresponding to the
157609 ** hits for a single phrase on a single row in order to calculate the
157610 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
157611 */
157612 typedef struct LcsIterator LcsIterator;
157613 struct LcsIterator {
157614  Fts3Expr *pExpr; /* Pointer to phrase expression */
157615  int iPosOffset; /* Tokens count up to end of this phrase */
157616  char *pRead; /* Cursor used to iterate through aDoclist */
157617  int iPos; /* Current position */
157618 };
157619 
157620 /*
157621 ** If LcsIterator.iCol is set to the following value, the iterator has
157622 ** finished iterating through all offsets for all columns.
157623 */
157624 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
157625 
157626 static int fts3MatchinfoLcsCb(
157627  Fts3Expr *pExpr, /* Phrase expression node */
157628  int iPhrase, /* Phrase number (numbered from zero) */
157629  void *pCtx /* Pointer to MatchInfo structure */
157630 ){
157631  LcsIterator *aIter = (LcsIterator *)pCtx;
157632  aIter[iPhrase].pExpr = pExpr;
157633  return SQLITE_OK;
157634 }
157635 
157636 /*
157637 ** Advance the iterator passed as an argument to the next position. Return
157638 ** 1 if the iterator is at EOF or if it now points to the start of the
157639 ** position list for the next column.
157640 */
157641 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
157642  char *pRead = pIter->pRead;
157643  sqlite3_int64 iRead;
157644  int rc = 0;
157645 
157646  pRead += sqlite3Fts3GetVarint(pRead, &iRead);
157647  if( iRead==0 || iRead==1 ){
157648  pRead = 0;
157649  rc = 1;
157650  }else{
157651  pIter->iPos += (int)(iRead-2);
157652  }
157653 
157654  pIter->pRead = pRead;
157655  return rc;
157656 }
157657 
157658 /*
157659 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
157660 **
157661 ** If the call is successful, the longest-common-substring lengths for each
157662 ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
157663 ** array before returning. SQLITE_OK is returned in this case.
157664 **
157665 ** Otherwise, if an error occurs, an SQLite error code is returned and the
157666 ** data written to the first nCol elements of pInfo->aMatchinfo[] is
157667 ** undefined.
157668 */
157669 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
157670  LcsIterator *aIter;
157671  int i;
157672  int iCol;
157673  int nToken = 0;
157674 
157675  /* Allocate and populate the array of LcsIterator objects. The array
157676  ** contains one element for each matchable phrase in the query.
157677  **/
157678  aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
157679  if( !aIter ) return SQLITE_NOMEM;
157680  memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
157681  (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
157682 
157683  for(i=0; i<pInfo->nPhrase; i++){
157684  LcsIterator *pIter = &aIter[i];
157685  nToken -= pIter->pExpr->pPhrase->nToken;
157686  pIter->iPosOffset = nToken;
157687  }
157688 
157689  for(iCol=0; iCol<pInfo->nCol; iCol++){
157690  int nLcs = 0; /* LCS value for this column */
157691  int nLive = 0; /* Number of iterators in aIter not at EOF */
157692 
157693  for(i=0; i<pInfo->nPhrase; i++){
157694  int rc;
157695  LcsIterator *pIt = &aIter[i];
157696  rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
157697  if( rc!=SQLITE_OK ) return rc;
157698  if( pIt->pRead ){
157699  pIt->iPos = pIt->iPosOffset;
157700  fts3LcsIteratorAdvance(&aIter[i]);
157701  nLive++;
157702  }
157703  }
157704 
157705  while( nLive>0 ){
157706  LcsIterator *pAdv = 0; /* The iterator to advance by one position */
157707  int nThisLcs = 0; /* LCS for the current iterator positions */
157708 
157709  for(i=0; i<pInfo->nPhrase; i++){
157710  LcsIterator *pIter = &aIter[i];
157711  if( pIter->pRead==0 ){
157712  /* This iterator is already at EOF for this column. */
157713  nThisLcs = 0;
157714  }else{
157715  if( pAdv==0 || pIter->iPos<pAdv->iPos ){
157716  pAdv = pIter;
157717  }
157718  if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
157719  nThisLcs++;
157720  }else{
157721  nThisLcs = 1;
157722  }
157723  if( nThisLcs>nLcs ) nLcs = nThisLcs;
157724  }
157725  }
157726  if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
157727  }
157728 
157729  pInfo->aMatchinfo[iCol] = nLcs;
157730  }
157731 
157732  sqlite3_free(aIter);
157733  return SQLITE_OK;
157734 }
157735 
157736 /*
157737 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
157738 ** be returned by the matchinfo() function. Argument zArg contains the
157739 ** format string passed as the second argument to matchinfo (or the
157740 ** default value "pcx" if no second argument was specified). The format
157741 ** string has already been validated and the pInfo->aMatchinfo[] array
157742 ** is guaranteed to be large enough for the output.
157743 **
157744 ** If bGlobal is true, then populate all fields of the matchinfo() output.
157745 ** If it is false, then assume that those fields that do not change between
157746 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
157747 ** have already been populated.
157748 **
157749 ** Return SQLITE_OK if successful, or an SQLite error code if an error
157750 ** occurs. If a value other than SQLITE_OK is returned, the state the
157751 ** pInfo->aMatchinfo[] buffer is left in is undefined.
157752 */
157753 static int fts3MatchinfoValues(
157754  Fts3Cursor *pCsr, /* FTS3 cursor object */
157755  int bGlobal, /* True to grab the global stats */
157756  MatchInfo *pInfo, /* Matchinfo context object */
157757  const char *zArg /* Matchinfo format string */
157758 ){
157759  int rc = SQLITE_OK;
157760  int i;
157761  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
157762  sqlite3_stmt *pSelect = 0;
157763 
157764  for(i=0; rc==SQLITE_OK && zArg[i]; i++){
157765  pInfo->flag = zArg[i];
157766  switch( zArg[i] ){
157767  case FTS3_MATCHINFO_NPHRASE:
157768  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
157769  break;
157770 
157771  case FTS3_MATCHINFO_NCOL:
157772  if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
157773  break;
157774 
157775  case FTS3_MATCHINFO_NDOC:
157776  if( bGlobal ){
157777  sqlite3_int64 nDoc = 0;
157778  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
157779  pInfo->aMatchinfo[0] = (u32)nDoc;
157780  }
157781  break;
157782 
157783  case FTS3_MATCHINFO_AVGLENGTH:
157784  if( bGlobal ){
157785  sqlite3_int64 nDoc; /* Number of rows in table */
157786  const char *a; /* Aggregate column length array */
157787 
157788  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
157789  if( rc==SQLITE_OK ){
157790  int iCol;
157791  for(iCol=0; iCol<pInfo->nCol; iCol++){
157792  u32 iVal;
157793  sqlite3_int64 nToken;
157794  a += sqlite3Fts3GetVarint(a, &nToken);
157795  iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
157796  pInfo->aMatchinfo[iCol] = iVal;
157797  }
157798  }
157799  }
157800  break;
157801 
157802  case FTS3_MATCHINFO_LENGTH: {
157803  sqlite3_stmt *pSelectDocsize = 0;
157804  rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
157805  if( rc==SQLITE_OK ){
157806  int iCol;
157807  const char *a = sqlite3_column_blob(pSelectDocsize, 0);
157808  for(iCol=0; iCol<pInfo->nCol; iCol++){
157809  sqlite3_int64 nToken;
157810  a += sqlite3Fts3GetVarint(a, &nToken);
157811  pInfo->aMatchinfo[iCol] = (u32)nToken;
157812  }
157813  }
157814  sqlite3_reset(pSelectDocsize);
157815  break;
157816  }
157817 
157818  case FTS3_MATCHINFO_LCS:
157819  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
157820  if( rc==SQLITE_OK ){
157821  rc = fts3MatchinfoLcs(pCsr, pInfo);
157822  }
157823  break;
157824 
157825  case FTS3_MATCHINFO_LHITS_BM:
157826  case FTS3_MATCHINFO_LHITS: {
157827  int nZero = fts3MatchinfoSize(pInfo, zArg[i]) * sizeof(u32);
157828  memset(pInfo->aMatchinfo, 0, nZero);
157829  fts3ExprLHitGather(pCsr->pExpr, pInfo);
157830  break;
157831  }
157832 
157833  default: {
157834  Fts3Expr *pExpr;
157835  assert( zArg[i]==FTS3_MATCHINFO_HITS );
157836  pExpr = pCsr->pExpr;
157837  rc = fts3ExprLoadDoclists(pCsr, 0, 0);
157838  if( rc!=SQLITE_OK ) break;
157839  if( bGlobal ){
157840  if( pCsr->pDeferred ){
157841  rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
157842  if( rc!=SQLITE_OK ) break;
157843  }
157844  rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
157845  sqlite3Fts3EvalTestDeferred(pCsr, &rc);
157846  if( rc!=SQLITE_OK ) break;
157847  }
157848  (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
157849  break;
157850  }
157851  }
157852 
157853  pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
157854  }
157855 
157856  sqlite3_reset(pSelect);
157857  return rc;
157858 }
157859 
157860 
157861 /*
157862 ** Populate pCsr->aMatchinfo[] with data for the current row. The
157863 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
157864 */
157865 static void fts3GetMatchinfo(
157866  sqlite3_context *pCtx, /* Return results here */
157867  Fts3Cursor *pCsr, /* FTS3 Cursor object */
157868  const char *zArg /* Second argument to matchinfo() function */
157869 ){
157870  MatchInfo sInfo;
157871  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
157872  int rc = SQLITE_OK;
157873  int bGlobal = 0; /* Collect 'global' stats as well as local */
157874 
157875  u32 *aOut = 0;
157876  void (*xDestroyOut)(void*) = 0;
157877 
157878  memset(&sInfo, 0, sizeof(MatchInfo));
157879  sInfo.pCursor = pCsr;
157880  sInfo.nCol = pTab->nColumn;
157881 
157882  /* If there is cached matchinfo() data, but the format string for the
157883  ** cache does not match the format string for this request, discard
157884  ** the cached data. */
157885  if( pCsr->pMIBuffer && strcmp(pCsr->pMIBuffer->zMatchinfo, zArg) ){
157886  sqlite3Fts3MIBufferFree(pCsr->pMIBuffer);
157887  pCsr->pMIBuffer = 0;
157888  }
157889 
157890  /* If Fts3Cursor.pMIBuffer is NULL, then this is the first time the
157891  ** matchinfo function has been called for this query. In this case
157892  ** allocate the array used to accumulate the matchinfo data and
157893  ** initialize those elements that are constant for every row.
157894  */
157895  if( pCsr->pMIBuffer==0 ){
157896  int nMatchinfo = 0; /* Number of u32 elements in match-info */
157897  int i; /* Used to iterate through zArg */
157898 
157899  /* Determine the number of phrases in the query */
157900  pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
157901  sInfo.nPhrase = pCsr->nPhrase;
157902 
157903  /* Determine the number of integers in the buffer returned by this call. */
157904  for(i=0; zArg[i]; i++){
157905  char *zErr = 0;
157906  if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
157907  sqlite3_result_error(pCtx, zErr, -1);
157908  sqlite3_free(zErr);
157909  return;
157910  }
157911  nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
157912  }
157913 
157914  /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
157915  pCsr->pMIBuffer = fts3MIBufferNew(nMatchinfo, zArg);
157916  if( !pCsr->pMIBuffer ) rc = SQLITE_NOMEM;
157917 
157918  pCsr->isMatchinfoNeeded = 1;
157919  bGlobal = 1;
157920  }
157921 
157922  if( rc==SQLITE_OK ){
157923  xDestroyOut = fts3MIBufferAlloc(pCsr->pMIBuffer, &aOut);
157924  if( xDestroyOut==0 ){
157925  rc = SQLITE_NOMEM;
157926  }
157927  }
157928 
157929  if( rc==SQLITE_OK ){
157930  sInfo.aMatchinfo = aOut;
157931  sInfo.nPhrase = pCsr->nPhrase;
157932  rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
157933  if( bGlobal ){
157934  fts3MIBufferSetGlobal(pCsr->pMIBuffer);
157935  }
157936  }
157937 
157938  if( rc!=SQLITE_OK ){
157939  sqlite3_result_error_code(pCtx, rc);
157940  if( xDestroyOut ) xDestroyOut(aOut);
157941  }else{
157942  int n = pCsr->pMIBuffer->nElem * sizeof(u32);
157943  sqlite3_result_blob(pCtx, aOut, n, xDestroyOut);
157944  }
157945 }
157946 
157947 /*
157948 ** Implementation of snippet() function.
157949 */
157950 SQLITE_PRIVATE void sqlite3Fts3Snippet(
157951  sqlite3_context *pCtx, /* SQLite function call context */
157952  Fts3Cursor *pCsr, /* Cursor object */
157953  const char *zStart, /* Snippet start text - "<b>" */
157954  const char *zEnd, /* Snippet end text - "</b>" */
157955  const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
157956  int iCol, /* Extract snippet from this column */
157957  int nToken /* Approximate number of tokens in snippet */
157958 ){
157959  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
157960  int rc = SQLITE_OK;
157961  int i;
157962  StrBuffer res = {0, 0, 0};
157963 
157964  /* The returned text includes up to four fragments of text extracted from
157965  ** the data in the current row. The first iteration of the for(...) loop
157966  ** below attempts to locate a single fragment of text nToken tokens in
157967  ** size that contains at least one instance of all phrases in the query
157968  ** expression that appear in the current row. If such a fragment of text
157969  ** cannot be found, the second iteration of the loop attempts to locate
157970  ** a pair of fragments, and so on.
157971  */
157972  int nSnippet = 0; /* Number of fragments in this snippet */
157973  SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
157974  int nFToken = -1; /* Number of tokens in each fragment */
157975 
157976  if( !pCsr->pExpr ){
157977  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
157978  return;
157979  }
157980 
157981  for(nSnippet=1; 1; nSnippet++){
157982 
157983  int iSnip; /* Loop counter 0..nSnippet-1 */
157984  u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
157985  u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
157986 
157987  if( nToken>=0 ){
157988  nFToken = (nToken+nSnippet-1) / nSnippet;
157989  }else{
157990  nFToken = -1 * nToken;
157991  }
157992 
157993  for(iSnip=0; iSnip<nSnippet; iSnip++){
157994  int iBestScore = -1; /* Best score of columns checked so far */
157995  int iRead; /* Used to iterate through columns */
157996  SnippetFragment *pFragment = &aSnippet[iSnip];
157997 
157998  memset(pFragment, 0, sizeof(*pFragment));
157999 
158000  /* Loop through all columns of the table being considered for snippets.
158001  ** If the iCol argument to this function was negative, this means all
158002  ** columns of the FTS3 table. Otherwise, only column iCol is considered.
158003  */
158004  for(iRead=0; iRead<pTab->nColumn; iRead++){
158005  SnippetFragment sF = {0, 0, 0, 0};
158006  int iS = 0;
158007  if( iCol>=0 && iRead!=iCol ) continue;
158008 
158009  /* Find the best snippet of nFToken tokens in column iRead. */
158010  rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
158011  if( rc!=SQLITE_OK ){
158012  goto snippet_out;
158013  }
158014  if( iS>iBestScore ){
158015  *pFragment = sF;
158016  iBestScore = iS;
158017  }
158018  }
158019 
158020  mCovered |= pFragment->covered;
158021  }
158022 
158023  /* If all query phrases seen by fts3BestSnippet() are present in at least
158024  ** one of the nSnippet snippet fragments, break out of the loop.
158025  */
158026  assert( (mCovered&mSeen)==mCovered );
158027  if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
158028  }
158029 
158030  assert( nFToken>0 );
158031 
158032  for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
158033  rc = fts3SnippetText(pCsr, &aSnippet[i],
158034  i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
158035  );
158036  }
158037 
158038  snippet_out:
158039  sqlite3Fts3SegmentsClose(pTab);
158040  if( rc!=SQLITE_OK ){
158041  sqlite3_result_error_code(pCtx, rc);
158042  sqlite3_free(res.z);
158043  }else{
158044  sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
158045  }
158046 }
158047 
158048 
158049 typedef struct TermOffset TermOffset;
158050 typedef struct TermOffsetCtx TermOffsetCtx;
158051 
158052 struct TermOffset {
158053  char *pList; /* Position-list */
158054  int iPos; /* Position just read from pList */
158055  int iOff; /* Offset of this term from read positions */
158056 };
158057 
158058 struct TermOffsetCtx {
158059  Fts3Cursor *pCsr;
158060  int iCol; /* Column of table to populate aTerm for */
158061  int iTerm;
158062  sqlite3_int64 iDocid;
158063  TermOffset *aTerm;
158064 };
158065 
158066 /*
158067 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
158068 */
158069 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
158070  TermOffsetCtx *p = (TermOffsetCtx *)ctx;
158071  int nTerm; /* Number of tokens in phrase */
158072  int iTerm; /* For looping through nTerm phrase terms */
158073  char *pList; /* Pointer to position list for phrase */
158074  int iPos = 0; /* First position in position-list */
158075  int rc;
158076 
158077  UNUSED_PARAMETER(iPhrase);
158078  rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
158079  nTerm = pExpr->pPhrase->nToken;
158080  if( pList ){
158081  fts3GetDeltaPosition(&pList, &iPos);
158082  assert( iPos>=0 );
158083  }
158084 
158085  for(iTerm=0; iTerm<nTerm; iTerm++){
158086  TermOffset *pT = &p->aTerm[p->iTerm++];
158087  pT->iOff = nTerm-iTerm-1;
158088  pT->pList = pList;
158089  pT->iPos = iPos;
158090  }
158091 
158092  return rc;
158093 }
158094 
158095 /*
158096 ** Implementation of offsets() function.
158097 */
158098 SQLITE_PRIVATE void sqlite3Fts3Offsets(
158099  sqlite3_context *pCtx, /* SQLite function call context */
158100  Fts3Cursor *pCsr /* Cursor object */
158101 ){
158102  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158103  sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
158104  int rc; /* Return Code */
158105  int nToken; /* Number of tokens in query */
158106  int iCol; /* Column currently being processed */
158107  StrBuffer res = {0, 0, 0}; /* Result string */
158108  TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
158109 
158110  if( !pCsr->pExpr ){
158111  sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
158112  return;
158113  }
158114 
158115  memset(&sCtx, 0, sizeof(sCtx));
158116  assert( pCsr->isRequireSeek==0 );
158117 
158118  /* Count the number of terms in the query */
158119  rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
158120  if( rc!=SQLITE_OK ) goto offsets_out;
158121 
158122  /* Allocate the array of TermOffset iterators. */
158123  sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
158124  if( 0==sCtx.aTerm ){
158125  rc = SQLITE_NOMEM;
158126  goto offsets_out;
158127  }
158128  sCtx.iDocid = pCsr->iPrevId;
158129  sCtx.pCsr = pCsr;
158130 
158131  /* Loop through the table columns, appending offset information to
158132  ** string-buffer res for each column.
158133  */
158134  for(iCol=0; iCol<pTab->nColumn; iCol++){
158135  sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
158136  const char *ZDUMMY; /* Dummy argument used with xNext() */
158137  int NDUMMY = 0; /* Dummy argument used with xNext() */
158138  int iStart = 0;
158139  int iEnd = 0;
158140  int iCurrent = 0;
158141  const char *zDoc;
158142  int nDoc;
158143 
158144  /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
158145  ** no way that this operation can fail, so the return code from
158146  ** fts3ExprIterate() can be discarded.
158147  */
158148  sCtx.iCol = iCol;
158149  sCtx.iTerm = 0;
158150  (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void*)&sCtx);
158151 
158152  /* Retreive the text stored in column iCol. If an SQL NULL is stored
158153  ** in column iCol, jump immediately to the next iteration of the loop.
158154  ** If an OOM occurs while retrieving the data (this can happen if SQLite
158155  ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
158156  ** to the caller.
158157  */
158158  zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
158159  nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
158160  if( zDoc==0 ){
158161  if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
158162  continue;
158163  }
158164  rc = SQLITE_NOMEM;
158165  goto offsets_out;
158166  }
158167 
158168  /* Initialize a tokenizer iterator to iterate through column iCol. */
158169  rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
158170  zDoc, nDoc, &pC
158171  );
158172  if( rc!=SQLITE_OK ) goto offsets_out;
158173 
158174  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
158175  while( rc==SQLITE_OK ){
158176  int i; /* Used to loop through terms */
158177  int iMinPos = 0x7FFFFFFF; /* Position of next token */
158178  TermOffset *pTerm = 0; /* TermOffset associated with next token */
158179 
158180  for(i=0; i<nToken; i++){
158181  TermOffset *pT = &sCtx.aTerm[i];
158182  if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
158183  iMinPos = pT->iPos-pT->iOff;
158184  pTerm = pT;
158185  }
158186  }
158187 
158188  if( !pTerm ){
158189  /* All offsets for this column have been gathered. */
158190  rc = SQLITE_DONE;
158191  }else{
158192  assert( iCurrent<=iMinPos );
158193  if( 0==(0xFE&*pTerm->pList) ){
158194  pTerm->pList = 0;
158195  }else{
158196  fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
158197  }
158198  while( rc==SQLITE_OK && iCurrent<iMinPos ){
158199  rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
158200  }
158201  if( rc==SQLITE_OK ){
158202  char aBuffer[64];
158203  sqlite3_snprintf(sizeof(aBuffer), aBuffer,
158204  "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
158205  );
158206  rc = fts3StringAppend(&res, aBuffer, -1);
158207  }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
158208  rc = FTS_CORRUPT_VTAB;
158209  }
158210  }
158211  }
158212  if( rc==SQLITE_DONE ){
158213  rc = SQLITE_OK;
158214  }
158215 
158216  pMod->xClose(pC);
158217  if( rc!=SQLITE_OK ) goto offsets_out;
158218  }
158219 
158220  offsets_out:
158221  sqlite3_free(sCtx.aTerm);
158222  assert( rc!=SQLITE_DONE );
158223  sqlite3Fts3SegmentsClose(pTab);
158224  if( rc!=SQLITE_OK ){
158225  sqlite3_result_error_code(pCtx, rc);
158226  sqlite3_free(res.z);
158227  }else{
158228  sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
158229  }
158230  return;
158231 }
158232 
158233 /*
158234 ** Implementation of matchinfo() function.
158235 */
158236 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
158237  sqlite3_context *pContext, /* Function call context */
158238  Fts3Cursor *pCsr, /* FTS3 table cursor */
158239  const char *zArg /* Second arg to matchinfo() function */
158240 ){
158241  Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
158242  const char *zFormat;
158243 
158244  if( zArg ){
158245  zFormat = zArg;
158246  }else{
158247  zFormat = FTS3_MATCHINFO_DEFAULT;
158248  }
158249 
158250  if( !pCsr->pExpr ){
158251  sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
158252  return;
158253  }else{
158254  /* Retrieve matchinfo() data. */
158255  fts3GetMatchinfo(pContext, pCsr, zFormat);
158256  sqlite3Fts3SegmentsClose(pTab);
158257  }
158258 }
158259 
158260 #endif
158261 
158262 /************** End of fts3_snippet.c ****************************************/
158263 /************** Begin file fts3_unicode.c ************************************/
158264 /*
158265 ** 2012 May 24
158266 **
158267 ** The author disclaims copyright to this source code. In place of
158268 ** a legal notice, here is a blessing:
158269 **
158270 ** May you do good and not evil.
158271 ** May you find forgiveness for yourself and forgive others.
158272 ** May you share freely, never taking more than you give.
158273 **
158274 ******************************************************************************
158275 **
158276 ** Implementation of the "unicode" full-text-search tokenizer.
158277 */
158278 
158279 #ifndef SQLITE_DISABLE_FTS3_UNICODE
158280 
158281 /* #include "fts3Int.h" */
158282 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
158283 
158284 /* #include <assert.h> */
158285 /* #include <stdlib.h> */
158286 /* #include <stdio.h> */
158287 /* #include <string.h> */
158288 
158289 /* #include "fts3_tokenizer.h" */
158290 
158291 /*
158292 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
158293 ** from the sqlite3 source file utf.c. If this file is compiled as part
158294 ** of the amalgamation, they are not required.
158295 */
158296 #ifndef SQLITE_AMALGAMATION
158297 
158298 static const unsigned char sqlite3Utf8Trans1[] = {
158299  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
158300  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
158301  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
158302  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
158303  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
158304  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
158305  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
158306  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
158307 };
158308 
158309 #define READ_UTF8(zIn, zTerm, c) \
158310  c = *(zIn++); \
158311  if( c>=0xc0 ){ \
158312  c = sqlite3Utf8Trans1[c-0xc0]; \
158313  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
158314  c = (c<<6) + (0x3f & *(zIn++)); \
158315  } \
158316  if( c<0x80 \
158317  || (c&0xFFFFF800)==0xD800 \
158318  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
158319  }
158320 
158321 #define WRITE_UTF8(zOut, c) { \
158322  if( c<0x00080 ){ \
158323  *zOut++ = (u8)(c&0xFF); \
158324  } \
158325  else if( c<0x00800 ){ \
158326  *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
158327  *zOut++ = 0x80 + (u8)(c & 0x3F); \
158328  } \
158329  else if( c<0x10000 ){ \
158330  *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
158331  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
158332  *zOut++ = 0x80 + (u8)(c & 0x3F); \
158333  }else{ \
158334  *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
158335  *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
158336  *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
158337  *zOut++ = 0x80 + (u8)(c & 0x3F); \
158338  } \
158339 }
158340 
158341 #endif /* ifndef SQLITE_AMALGAMATION */
158342 
158343 typedef struct unicode_tokenizer unicode_tokenizer;
158344 typedef struct unicode_cursor unicode_cursor;
158345 
158346 struct unicode_tokenizer {
158347  sqlite3_tokenizer base;
158348  int bRemoveDiacritic;
158349  int nException;
158350  int *aiException;
158351 };
158352 
158353 struct unicode_cursor {
158354  sqlite3_tokenizer_cursor base;
158355  const unsigned char *aInput; /* Input text being tokenized */
158356  int nInput; /* Size of aInput[] in bytes */
158357  int iOff; /* Current offset within aInput[] */
158358  int iToken; /* Index of next token to be returned */
158359  char *zToken; /* storage for current token */
158360  int nAlloc; /* space allocated at zToken */
158361 };
158362 
158363 
158364 /*
158365 ** Destroy a tokenizer allocated by unicodeCreate().
158366 */
158367 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
158368  if( pTokenizer ){
158369  unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
158370  sqlite3_free(p->aiException);
158371  sqlite3_free(p);
158372  }
158373  return SQLITE_OK;
158374 }
158375 
158376 /*
158377 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
158378 ** statement has specified that the tokenizer for this table shall consider
158379 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
158380 ** token characters (if bAlnum==1).
158381 **
158382 ** For each codepoint in the zIn/nIn string, this function checks if the
158383 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
158384 ** If so, no action is taken. Otherwise, the codepoint is added to the
158385 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
158386 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
158387 ** codepoints in the aiException[] array.
158388 **
158389 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
158390 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
158391 ** It is not possible to change the behavior of the tokenizer with respect
158392 ** to these codepoints.
158393 */
158394 static int unicodeAddExceptions(
158395  unicode_tokenizer *p, /* Tokenizer to add exceptions to */
158396  int bAlnum, /* Replace Isalnum() return value with this */
158397  const char *zIn, /* Array of characters to make exceptions */
158398  int nIn /* Length of z in bytes */
158399 ){
158400  const unsigned char *z = (const unsigned char *)zIn;
158401  const unsigned char *zTerm = &z[nIn];
158402  int iCode;
158403  int nEntry = 0;
158404 
158405  assert( bAlnum==0 || bAlnum==1 );
158406 
158407  while( z<zTerm ){
158408  READ_UTF8(z, zTerm, iCode);
158409  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
158410  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
158411  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
158412  ){
158413  nEntry++;
158414  }
158415  }
158416 
158417  if( nEntry ){
158418  int *aNew; /* New aiException[] array */
158419  int nNew; /* Number of valid entries in array aNew[] */
158420 
158421  aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
158422  if( aNew==0 ) return SQLITE_NOMEM;
158423  nNew = p->nException;
158424 
158425  z = (const unsigned char *)zIn;
158426  while( z<zTerm ){
158427  READ_UTF8(z, zTerm, iCode);
158428  if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
158429  && sqlite3FtsUnicodeIsdiacritic(iCode)==0
158430  ){
158431  int i, j;
158432  for(i=0; i<nNew && aNew[i]<iCode; i++);
158433  for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
158434  aNew[i] = iCode;
158435  nNew++;
158436  }
158437  }
158438  p->aiException = aNew;
158439  p->nException = nNew;
158440  }
158441 
158442  return SQLITE_OK;
158443 }
158444 
158445 /*
158446 ** Return true if the p->aiException[] array contains the value iCode.
158447 */
158448 static int unicodeIsException(unicode_tokenizer *p, int iCode){
158449  if( p->nException>0 ){
158450  int *a = p->aiException;
158451  int iLo = 0;
158452  int iHi = p->nException-1;
158453 
158454  while( iHi>=iLo ){
158455  int iTest = (iHi + iLo) / 2;
158456  if( iCode==a[iTest] ){
158457  return 1;
158458  }else if( iCode>a[iTest] ){
158459  iLo = iTest+1;
158460  }else{
158461  iHi = iTest-1;
158462  }
158463  }
158464  }
158465 
158466  return 0;
158467 }
158468 
158469 /*
158470 ** Return true if, for the purposes of tokenization, codepoint iCode is
158471 ** considered a token character (not a separator).
158472 */
158473 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
158474  assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
158475  return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
158476 }
158477 
158478 /*
158479 ** Create a new tokenizer instance.
158480 */
158481 static int unicodeCreate(
158482  int nArg, /* Size of array argv[] */
158483  const char * const *azArg, /* Tokenizer creation arguments */
158484  sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
158485 ){
158486  unicode_tokenizer *pNew; /* New tokenizer object */
158487  int i;
158488  int rc = SQLITE_OK;
158489 
158490  pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
158491  if( pNew==NULL ) return SQLITE_NOMEM;
158492  memset(pNew, 0, sizeof(unicode_tokenizer));
158493  pNew->bRemoveDiacritic = 1;
158494 
158495  for(i=0; rc==SQLITE_OK && i<nArg; i++){
158496  const char *z = azArg[i];
158497  int n = (int)strlen(z);
158498 
158499  if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
158500  pNew->bRemoveDiacritic = 1;
158501  }
158502  else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
158503  pNew->bRemoveDiacritic = 0;
158504  }
158505  else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
158506  rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
158507  }
158508  else if( n>=11 && memcmp("separators=", z, 11)==0 ){
158509  rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
158510  }
158511  else{
158512  /* Unrecognized argument */
158513  rc = SQLITE_ERROR;
158514  }
158515  }
158516 
158517  if( rc!=SQLITE_OK ){
158518  unicodeDestroy((sqlite3_tokenizer *)pNew);
158519  pNew = 0;
158520  }
158521  *pp = (sqlite3_tokenizer *)pNew;
158522  return rc;
158523 }
158524 
158525 /*
158526 ** Prepare to begin tokenizing a particular string. The input
158527 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
158528 ** used to incrementally tokenize this string is returned in
158529 ** *ppCursor.
158530 */
158531 static int unicodeOpen(
158532  sqlite3_tokenizer *p, /* The tokenizer */
158533  const char *aInput, /* Input string */
158534  int nInput, /* Size of string aInput in bytes */
158535  sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
158536 ){
158537  unicode_cursor *pCsr;
158538 
158539  pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
158540  if( pCsr==0 ){
158541  return SQLITE_NOMEM;
158542  }
158543  memset(pCsr, 0, sizeof(unicode_cursor));
158544 
158545  pCsr->aInput = (const unsigned char *)aInput;
158546  if( aInput==0 ){
158547  pCsr->nInput = 0;
158548  }else if( nInput<0 ){
158549  pCsr->nInput = (int)strlen(aInput);
158550  }else{
158551  pCsr->nInput = nInput;
158552  }
158553 
158554  *pp = &pCsr->base;
158555  UNUSED_PARAMETER(p);
158556  return SQLITE_OK;
158557 }
158558 
158559 /*
158560 ** Close a tokenization cursor previously opened by a call to
158561 ** simpleOpen() above.
158562 */
158563 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
158564  unicode_cursor *pCsr = (unicode_cursor *) pCursor;
158565  sqlite3_free(pCsr->zToken);
158566  sqlite3_free(pCsr);
158567  return SQLITE_OK;
158568 }
158569 
158570 /*
158571 ** Extract the next token from a tokenization cursor. The cursor must
158572 ** have been opened by a prior call to simpleOpen().
158573 */
158574 static int unicodeNext(
158575  sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
158576  const char **paToken, /* OUT: Token text */
158577  int *pnToken, /* OUT: Number of bytes at *paToken */
158578  int *piStart, /* OUT: Starting offset of token */
158579  int *piEnd, /* OUT: Ending offset of token */
158580  int *piPos /* OUT: Position integer of token */
158581 ){
158582  unicode_cursor *pCsr = (unicode_cursor *)pC;
158583  unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
158584  int iCode = 0;
158585  char *zOut;
158586  const unsigned char *z = &pCsr->aInput[pCsr->iOff];
158587  const unsigned char *zStart = z;
158588  const unsigned char *zEnd;
158589  const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
158590 
158591  /* Scan past any delimiter characters before the start of the next token.
158592  ** Return SQLITE_DONE early if this takes us all the way to the end of
158593  ** the input. */
158594  while( z<zTerm ){
158595  READ_UTF8(z, zTerm, iCode);
158596  if( unicodeIsAlnum(p, iCode) ) break;
158597  zStart = z;
158598  }
158599  if( zStart>=zTerm ) return SQLITE_DONE;
158600 
158601  zOut = pCsr->zToken;
158602  do {
158603  int iOut;
158604 
158605  /* Grow the output buffer if required. */
158606  if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
158607  char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
158608  if( !zNew ) return SQLITE_NOMEM;
158609  zOut = &zNew[zOut - pCsr->zToken];
158610  pCsr->zToken = zNew;
158611  pCsr->nAlloc += 64;
158612  }
158613 
158614  /* Write the folded case of the last character read to the output */
158615  zEnd = z;
158616  iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
158617  if( iOut ){
158618  WRITE_UTF8(zOut, iOut);
158619  }
158620 
158621  /* If the cursor is not at EOF, read the next character */
158622  if( z>=zTerm ) break;
158623  READ_UTF8(z, zTerm, iCode);
158624  }while( unicodeIsAlnum(p, iCode)
158625  || sqlite3FtsUnicodeIsdiacritic(iCode)
158626  );
158627 
158628  /* Set the output variables and return. */
158629  pCsr->iOff = (int)(z - pCsr->aInput);
158630  *paToken = pCsr->zToken;
158631  *pnToken = (int)(zOut - pCsr->zToken);
158632  *piStart = (int)(zStart - pCsr->aInput);
158633  *piEnd = (int)(zEnd - pCsr->aInput);
158634  *piPos = pCsr->iToken++;
158635  return SQLITE_OK;
158636 }
158637 
158638 /*
158639 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
158640 ** structure for the unicode tokenizer.
158641 */
158642 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
158643  static const sqlite3_tokenizer_module module = {
158644  0,
158645  unicodeCreate,
158646  unicodeDestroy,
158647  unicodeOpen,
158648  unicodeClose,
158649  unicodeNext,
158650  0,
158651  };
158652  *ppModule = &module;
158653 }
158654 
158655 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
158656 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
158657 
158658 /************** End of fts3_unicode.c ****************************************/
158659 /************** Begin file fts3_unicode2.c ***********************************/
158660 /*
158661 ** 2012 May 25
158662 **
158663 ** The author disclaims copyright to this source code. In place of
158664 ** a legal notice, here is a blessing:
158665 **
158666 ** May you do good and not evil.
158667 ** May you find forgiveness for yourself and forgive others.
158668 ** May you share freely, never taking more than you give.
158669 **
158670 ******************************************************************************
158671 */
158672 
158673 /*
158674 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
158675 */
158676 
158677 #ifndef SQLITE_DISABLE_FTS3_UNICODE
158678 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
158679 
158680 /* #include <assert.h> */
158681 
158682 /*
158683 ** Return true if the argument corresponds to a unicode codepoint
158684 ** classified as either a letter or a number. Otherwise false.
158685 **
158686 ** The results are undefined if the value passed to this function
158687 ** is less than zero.
158688 */
158689 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
158690  /* Each unsigned integer in the following array corresponds to a contiguous
158691  ** range of unicode codepoints that are not either letters or numbers (i.e.
158692  ** codepoints for which this function should return 0).
158693  **
158694  ** The most significant 22 bits in each 32-bit value contain the first
158695  ** codepoint in the range. The least significant 10 bits are used to store
158696  ** the size of the range (always at least 1). In other words, the value
158697  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
158698  ** C. It is not possible to represent a range larger than 1023 codepoints
158699  ** using this format.
158700  */
158701  static const unsigned int aEntry[] = {
158702  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
158703  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
158704  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
158705  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
158706  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
158707  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
158708  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
158709  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
158710  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
158711  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
158712  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
158713  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
158714  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
158715  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
158716  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
158717  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
158718  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
158719  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
158720  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
158721  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
158722  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
158723  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
158724  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
158725  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
158726  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
158727  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
158728  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
158729  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
158730  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
158731  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
158732  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
158733  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
158734  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
158735  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
158736  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
158737  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
158738  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
158739  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
158740  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
158741  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
158742  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
158743  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
158744  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
158745  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
158746  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
158747  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
158748  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
158749  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
158750  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
158751  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
158752  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
158753  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
158754  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
158755  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
158756  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
158757  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
158758  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
158759  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
158760  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
158761  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
158762  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
158763  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
158764  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
158765  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
158766  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
158767  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
158768  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
158769  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
158770  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
158771  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
158772  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
158773  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
158774  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
158775  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
158776  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
158777  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
158778  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
158779  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
158780  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
158781  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
158782  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
158783  0x380400F0,
158784  };
158785  static const unsigned int aAscii[4] = {
158786  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
158787  };
158788 
158789  if( c<128 ){
158790  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
158791  }else if( c<(1<<22) ){
158792  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
158793  int iRes = 0;
158794  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
158795  int iLo = 0;
158796  while( iHi>=iLo ){
158797  int iTest = (iHi + iLo) / 2;
158798  if( key >= aEntry[iTest] ){
158799  iRes = iTest;
158800  iLo = iTest+1;
158801  }else{
158802  iHi = iTest-1;
158803  }
158804  }
158805  assert( aEntry[0]<key );
158806  assert( key>=aEntry[iRes] );
158807  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
158808  }
158809  return 1;
158810 }
158811 
158812 
158813 /*
158814 ** If the argument is a codepoint corresponding to a lowercase letter
158815 ** in the ASCII range with a diacritic added, return the codepoint
158816 ** of the ASCII letter only. For example, if passed 235 - "LATIN
158817 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
158818 ** E"). The resuls of passing a codepoint that corresponds to an
158819 ** uppercase letter are undefined.
158820 */
158821 static int remove_diacritic(int c){
158822  unsigned short aDia[] = {
158823  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
158824  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
158825  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
158826  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
158827  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
158828  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
158829  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
158830  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
158831  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
158832  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
158833  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
158834  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
158835  62924, 63050, 63082, 63274, 63390,
158836  };
158837  char aChar[] = {
158838  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
158839  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
158840  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
158841  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
158842  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
158843  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
158844  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
158845  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
158846  'e', 'i', 'o', 'u', 'y',
158847  };
158848 
158849  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
158850  int iRes = 0;
158851  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
158852  int iLo = 0;
158853  while( iHi>=iLo ){
158854  int iTest = (iHi + iLo) / 2;
158855  if( key >= aDia[iTest] ){
158856  iRes = iTest;
158857  iLo = iTest+1;
158858  }else{
158859  iHi = iTest-1;
158860  }
158861  }
158862  assert( key>=aDia[iRes] );
158863  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
158864 }
158865 
158866 
158867 /*
158868 ** Return true if the argument interpreted as a unicode codepoint
158869 ** is a diacritical modifier character.
158870 */
158871 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
158872  unsigned int mask0 = 0x08029FDF;
158873  unsigned int mask1 = 0x000361F8;
158874  if( c<768 || c>817 ) return 0;
158875  return (c < 768+32) ?
158876  (mask0 & (1 << (c-768))) :
158877  (mask1 & (1 << (c-768-32)));
158878 }
158879 
158880 
158881 /*
158882 ** Interpret the argument as a unicode codepoint. If the codepoint
158883 ** is an upper case character that has a lower case equivalent,
158884 ** return the codepoint corresponding to the lower case version.
158885 ** Otherwise, return a copy of the argument.
158886 **
158887 ** The results are undefined if the value passed to this function
158888 ** is less than zero.
158889 */
158890 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
158891  /* Each entry in the following array defines a rule for folding a range
158892  ** of codepoints to lower case. The rule applies to a range of nRange
158893  ** codepoints starting at codepoint iCode.
158894  **
158895  ** If the least significant bit in flags is clear, then the rule applies
158896  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
158897  ** need to be folded). Or, if it is set, then the rule only applies to
158898  ** every second codepoint in the range, starting with codepoint C.
158899  **
158900  ** The 7 most significant bits in flags are an index into the aiOff[]
158901  ** array. If a specific codepoint C does require folding, then its lower
158902  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
158903  **
158904  ** The contents of this array are generated by parsing the CaseFolding.txt
158905  ** file distributed as part of the "Unicode Character Database". See
158906  ** http://www.unicode.org for details.
158907  */
158908  static const struct TableEntry {
158909  unsigned short iCode;
158910  unsigned char flags;
158911  unsigned char nRange;
158912  } aEntry[] = {
158913  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
158914  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
158915  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
158916  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
158917  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
158918  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
158919  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
158920  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
158921  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
158922  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
158923  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
158924  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
158925  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
158926  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
158927  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
158928  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
158929  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
158930  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
158931  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
158932  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
158933  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
158934  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
158935  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
158936  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
158937  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
158938  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
158939  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
158940  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
158941  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
158942  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
158943  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
158944  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
158945  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
158946  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
158947  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
158948  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
158949  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
158950  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
158951  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
158952  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
158953  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
158954  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
158955  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
158956  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
158957  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
158958  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
158959  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
158960  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
158961  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
158962  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
158963  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
158964  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
158965  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
158966  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
158967  {65313, 14, 26},
158968  };
158969  static const unsigned short aiOff[] = {
158970  1, 2, 8, 15, 16, 26, 28, 32,
158971  37, 38, 40, 48, 63, 64, 69, 71,
158972  79, 80, 116, 202, 203, 205, 206, 207,
158973  209, 210, 211, 213, 214, 217, 218, 219,
158974  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
158975  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
158976  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
158977  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
158978  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
158979  65514, 65521, 65527, 65528, 65529,
158980  };
158981 
158982  int ret = c;
158983 
158984  assert( c>=0 );
158985  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
158986 
158987  if( c<128 ){
158988  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
158989  }else if( c<65536 ){
158990  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
158991  int iLo = 0;
158992  int iRes = -1;
158993 
158994  while( iHi>=iLo ){
158995  int iTest = (iHi + iLo) / 2;
158996  int cmp = (c - aEntry[iTest].iCode);
158997  if( cmp>=0 ){
158998  iRes = iTest;
158999  iLo = iTest+1;
159000  }else{
159001  iHi = iTest-1;
159002  }
159003  }
159004  assert( iRes<0 || c>=aEntry[iRes].iCode );
159005 
159006  if( iRes>=0 ){
159007  const struct TableEntry *p = &aEntry[iRes];
159008  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
159009  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
159010  assert( ret>0 );
159011  }
159012  }
159013 
159014  if( bRemoveDiacritic ) ret = remove_diacritic(ret);
159015  }
159016 
159017  else if( c>=66560 && c<66600 ){
159018  ret = c + 40;
159019  }
159020 
159021  return ret;
159022 }
159023 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
159024 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
159025 
159026 /************** End of fts3_unicode2.c ***************************************/
159027 /************** Begin file rtree.c *******************************************/
159028 /*
159029 ** 2001 September 15
159030 **
159031 ** The author disclaims copyright to this source code. In place of
159032 ** a legal notice, here is a blessing:
159033 **
159034 ** May you do good and not evil.
159035 ** May you find forgiveness for yourself and forgive others.
159036 ** May you share freely, never taking more than you give.
159037 **
159038 *************************************************************************
159039 ** This file contains code for implementations of the r-tree and r*-tree
159040 ** algorithms packaged as an SQLite virtual table module.
159041 */
159042 
159043 /*
159044 ** Database Format of R-Tree Tables
159045 ** --------------------------------
159046 **
159047 ** The data structure for a single virtual r-tree table is stored in three
159048 ** native SQLite tables declared as follows. In each case, the '%' character
159049 ** in the table name is replaced with the user-supplied name of the r-tree
159050 ** table.
159051 **
159052 ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
159053 ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
159054 ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
159055 **
159056 ** The data for each node of the r-tree structure is stored in the %_node
159057 ** table. For each node that is not the root node of the r-tree, there is
159058 ** an entry in the %_parent table associating the node with its parent.
159059 ** And for each row of data in the table, there is an entry in the %_rowid
159060 ** table that maps from the entries rowid to the id of the node that it
159061 ** is stored on.
159062 **
159063 ** The root node of an r-tree always exists, even if the r-tree table is
159064 ** empty. The nodeno of the root node is always 1. All other nodes in the
159065 ** table must be the same size as the root node. The content of each node
159066 ** is formatted as follows:
159067 **
159068 ** 1. If the node is the root node (node 1), then the first 2 bytes
159069 ** of the node contain the tree depth as a big-endian integer.
159070 ** For non-root nodes, the first 2 bytes are left unused.
159071 **
159072 ** 2. The next 2 bytes contain the number of entries currently
159073 ** stored in the node.
159074 **
159075 ** 3. The remainder of the node contains the node entries. Each entry
159076 ** consists of a single 8-byte integer followed by an even number
159077 ** of 4-byte coordinates. For leaf nodes the integer is the rowid
159078 ** of a record. For internal nodes it is the node number of a
159079 ** child page.
159080 */
159081 
159082 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
159083 
159084 #ifndef SQLITE_CORE
159085 /* #include "sqlite3ext.h" */
159087 #else
159088 /* #include "sqlite3.h" */
159089 #endif
159090 
159091 /* #include <string.h> */
159092 /* #include <assert.h> */
159093 /* #include <stdio.h> */
159094 
159095 #ifndef SQLITE_AMALGAMATION
159096 #include "sqlite3rtree.h"
159097 typedef sqlite3_int64 i64;
159098 typedef unsigned char u8;
159099 typedef unsigned short u16;
159100 typedef unsigned int u32;
159101 #endif
159102 
159103 /* The following macro is used to suppress compiler warnings.
159104 */
159105 #ifndef UNUSED_PARAMETER
159106 # define UNUSED_PARAMETER(x) (void)(x)
159107 #endif
159108 
159109 typedef struct Rtree Rtree;
159110 typedef struct RtreeCursor RtreeCursor;
159111 typedef struct RtreeNode RtreeNode;
159112 typedef struct RtreeCell RtreeCell;
159113 typedef struct RtreeConstraint RtreeConstraint;
159114 typedef struct RtreeMatchArg RtreeMatchArg;
159115 typedef struct RtreeGeomCallback RtreeGeomCallback;
159116 typedef union RtreeCoord RtreeCoord;
159117 typedef struct RtreeSearchPoint RtreeSearchPoint;
159118 
159119 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
159120 #define RTREE_MAX_DIMENSIONS 5
159121 
159122 /* Size of hash table Rtree.aHash. This hash table is not expected to
159123 ** ever contain very many entries, so a fixed number of buckets is
159124 ** used.
159125 */
159126 #define HASHSIZE 97
159127 
159128 /* The xBestIndex method of this virtual table requires an estimate of
159129 ** the number of rows in the virtual table to calculate the costs of
159130 ** various strategies. If possible, this estimate is loaded from the
159131 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
159132 ** Otherwise, if no sqlite_stat1 entry is available, use
159133 ** RTREE_DEFAULT_ROWEST.
159134 */
159135 #define RTREE_DEFAULT_ROWEST 1048576
159136 #define RTREE_MIN_ROWEST 100
159137 
159138 /*
159139 ** An rtree virtual-table object.
159140 */
159141 struct Rtree {
159142  sqlite3_vtab base; /* Base class. Must be first */
159143  sqlite3 *db; /* Host database connection */
159144  int iNodeSize; /* Size in bytes of each node in the node table */
159145  u8 nDim; /* Number of dimensions */
159146  u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
159147  u8 nBytesPerCell; /* Bytes consumed per cell */
159148  int iDepth; /* Current depth of the r-tree structure */
159149  char *zDb; /* Name of database containing r-tree table */
159150  char *zName; /* Name of r-tree table */
159151  int nBusy; /* Current number of users of this structure */
159152  i64 nRowEst; /* Estimated number of rows in this table */
159153 
159154  /* List of nodes removed during a CondenseTree operation. List is
159155  ** linked together via the pointer normally used for hash chains -
159156  ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
159157  ** headed by the node (leaf nodes have RtreeNode.iNode==0).
159158  */
159159  RtreeNode *pDeleted;
159160  int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
159161 
159162  /* Statements to read/write/delete a record from xxx_node */
159163  sqlite3_stmt *pReadNode;
159164  sqlite3_stmt *pWriteNode;
159165  sqlite3_stmt *pDeleteNode;
159166 
159167  /* Statements to read/write/delete a record from xxx_rowid */
159168  sqlite3_stmt *pReadRowid;
159169  sqlite3_stmt *pWriteRowid;
159170  sqlite3_stmt *pDeleteRowid;
159171 
159172  /* Statements to read/write/delete a record from xxx_parent */
159173  sqlite3_stmt *pReadParent;
159174  sqlite3_stmt *pWriteParent;
159175  sqlite3_stmt *pDeleteParent;
159176 
159177  RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
159178 };
159179 
159180 /* Possible values for Rtree.eCoordType: */
159181 #define RTREE_COORD_REAL32 0
159182 #define RTREE_COORD_INT32 1
159183 
159184 /*
159185 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
159186 ** only deal with integer coordinates. No floating point operations
159187 ** will be done.
159188 */
159189 #ifdef SQLITE_RTREE_INT_ONLY
159190  typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
159191  typedef int RtreeValue; /* Low accuracy coordinate */
159192 # define RTREE_ZERO 0
159193 #else
159194  typedef double RtreeDValue; /* High accuracy coordinate */
159195  typedef float RtreeValue; /* Low accuracy coordinate */
159196 # define RTREE_ZERO 0.0
159197 #endif
159198 
159199 /*
159200 ** When doing a search of an r-tree, instances of the following structure
159201 ** record intermediate results from the tree walk.
159202 **
159203 ** The id is always a node-id. For iLevel>=1 the id is the node-id of
159204 ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
159205 ** the id is of the parent node and the cell that RtreeSearchPoint
159206 ** represents is the iCell-th entry in the parent node.
159207 */
159208 struct RtreeSearchPoint {
159209  RtreeDValue rScore; /* The score for this node. Smallest goes first. */
159210  sqlite3_int64 id; /* Node ID */
159211  u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
159212  u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
159213  u8 iCell; /* Cell index within the node */
159214 };
159215 
159216 /*
159217 ** The minimum number of cells allowed for a node is a third of the
159218 ** maximum. In Gutman's notation:
159219 **
159220 ** m = M/3
159221 **
159222 ** If an R*-tree "Reinsert" operation is required, the same number of
159223 ** cells are removed from the overfull node and reinserted into the tree.
159224 */
159225 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
159226 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
159227 #define RTREE_MAXCELLS 51
159228 
159229 /*
159230 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
159231 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
159232 ** Therefore all non-root nodes must contain at least 3 entries. Since
159233 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
159234 ** 40 or less.
159235 */
159236 #define RTREE_MAX_DEPTH 40
159237 
159238 
159239 /*
159240 ** Number of entries in the cursor RtreeNode cache. The first entry is
159241 ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
159242 ** entries cache the RtreeNode for the first elements of the priority queue.
159243 */
159244 #define RTREE_CACHE_SZ 5
159245 
159246 /*
159247 ** An rtree cursor object.
159248 */
159249 struct RtreeCursor {
159250  sqlite3_vtab_cursor base; /* Base class. Must be first */
159251  u8 atEOF; /* True if at end of search */
159252  u8 bPoint; /* True if sPoint is valid */
159253  int iStrategy; /* Copy of idxNum search parameter */
159254  int nConstraint; /* Number of entries in aConstraint */
159255  RtreeConstraint *aConstraint; /* Search constraints. */
159256  int nPointAlloc; /* Number of slots allocated for aPoint[] */
159257  int nPoint; /* Number of slots used in aPoint[] */
159258  int mxLevel; /* iLevel value for root of the tree */
159259  RtreeSearchPoint *aPoint; /* Priority queue for search points */
159260  RtreeSearchPoint sPoint; /* Cached next search point */
159261  RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
159262  u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
159263 };
159264 
159265 /* Return the Rtree of a RtreeCursor */
159266 #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
159267 
159268 /*
159269 ** A coordinate can be either a floating point number or a integer. All
159270 ** coordinates within a single R-Tree are always of the same time.
159271 */
159272 union RtreeCoord {
159273  RtreeValue f; /* Floating point value */
159274  int i; /* Integer value */
159275  u32 u; /* Unsigned for byte-order conversions */
159276 };
159277 
159278 /*
159279 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
159280 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
159281 ** variable pRtree points to the Rtree structure associated with the
159282 ** RtreeCoord.
159283 */
159284 #ifdef SQLITE_RTREE_INT_ONLY
159285 # define DCOORD(coord) ((RtreeDValue)coord.i)
159286 #else
159287 # define DCOORD(coord) ( \
159288  (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
159289  ((double)coord.f) : \
159290  ((double)coord.i) \
159291  )
159292 #endif
159293 
159294 /*
159295 ** A search constraint.
159296 */
159297 struct RtreeConstraint {
159298  int iCoord; /* Index of constrained coordinate */
159299  int op; /* Constraining operation */
159300  union {
159301  RtreeDValue rValue; /* Constraint value. */
159302  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
159303  int (*xQueryFunc)(sqlite3_rtree_query_info*);
159304  } u;
159305  sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
159306 };
159307 
159308 /* Possible values for RtreeConstraint.op */
159309 #define RTREE_EQ 0x41 /* A */
159310 #define RTREE_LE 0x42 /* B */
159311 #define RTREE_LT 0x43 /* C */
159312 #define RTREE_GE 0x44 /* D */
159313 #define RTREE_GT 0x45 /* E */
159314 #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
159315 #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
159316 
159317 
159318 /*
159319 ** An rtree structure node.
159320 */
159321 struct RtreeNode {
159322  RtreeNode *pParent; /* Parent node */
159323  i64 iNode; /* The node number */
159324  int nRef; /* Number of references to this node */
159325  int isDirty; /* True if the node needs to be written to disk */
159326  u8 *zData; /* Content of the node, as should be on disk */
159327  RtreeNode *pNext; /* Next node in this hash collision chain */
159328 };
159329 
159330 /* Return the number of cells in a node */
159331 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
159332 
159333 /*
159334 ** A single cell from a node, deserialized
159335 */
159336 struct RtreeCell {
159337  i64 iRowid; /* Node or entry ID */
159338  RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
159339 };
159340 
159341 
159342 /*
159343 ** This object becomes the sqlite3_user_data() for the SQL functions
159344 ** that are created by sqlite3_rtree_geometry_callback() and
159345 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
159346 ** operators in order to constrain a search.
159347 **
159348 ** xGeom and xQueryFunc are the callback functions. Exactly one of
159349 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
159350 ** SQL function was created using sqlite3_rtree_geometry_callback() or
159351 ** sqlite3_rtree_query_callback().
159352 **
159353 ** This object is deleted automatically by the destructor mechanism in
159354 ** sqlite3_create_function_v2().
159355 */
159356 struct RtreeGeomCallback {
159357  int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
159358  int (*xQueryFunc)(sqlite3_rtree_query_info*);
159359  void (*xDestructor)(void*);
159360  void *pContext;
159361 };
159362 
159363 
159364 /*
159365 ** Value for the first field of every RtreeMatchArg object. The MATCH
159366 ** operator tests that the first field of a blob operand matches this
159367 ** value to avoid operating on invalid blobs (which could cause a segfault).
159368 */
159369 #define RTREE_GEOMETRY_MAGIC 0x891245AB
159370 
159371 /*
159372 ** An instance of this structure (in the form of a BLOB) is returned by
159373 ** the SQL functions that sqlite3_rtree_geometry_callback() and
159374 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
159375 ** operand to the MATCH operator of an R-Tree.
159376 */
159377 struct RtreeMatchArg {
159378  u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
159379  RtreeGeomCallback cb; /* Info about the callback functions */
159380  int nParam; /* Number of parameters to the SQL function */
159381  sqlite3_value **apSqlParam; /* Original SQL parameter values */
159382  RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
159383 };
159384 
159385 #ifndef MAX
159386 # define MAX(x,y) ((x) < (y) ? (y) : (x))
159387 #endif
159388 #ifndef MIN
159389 # define MIN(x,y) ((x) > (y) ? (y) : (x))
159390 #endif
159391 
159392 /*
159393 ** Functions to deserialize a 16 bit integer, 32 bit real number and
159394 ** 64 bit integer. The deserialized value is returned.
159395 */
159396 static int readInt16(u8 *p){
159397  return (p[0]<<8) + p[1];
159398 }
159399 static void readCoord(u8 *p, RtreeCoord *pCoord){
159400  pCoord->u = (
159401  (((u32)p[0]) << 24) +
159402  (((u32)p[1]) << 16) +
159403  (((u32)p[2]) << 8) +
159404  (((u32)p[3]) << 0)
159405  );
159406 }
159407 static i64 readInt64(u8 *p){
159408  return (
159409  (((i64)p[0]) << 56) +
159410  (((i64)p[1]) << 48) +
159411  (((i64)p[2]) << 40) +
159412  (((i64)p[3]) << 32) +
159413  (((i64)p[4]) << 24) +
159414  (((i64)p[5]) << 16) +
159415  (((i64)p[6]) << 8) +
159416  (((i64)p[7]) << 0)
159417  );
159418 }
159419 
159420 /*
159421 ** Functions to serialize a 16 bit integer, 32 bit real number and
159422 ** 64 bit integer. The value returned is the number of bytes written
159423 ** to the argument buffer (always 2, 4 and 8 respectively).
159424 */
159425 static int writeInt16(u8 *p, int i){
159426  p[0] = (i>> 8)&0xFF;
159427  p[1] = (i>> 0)&0xFF;
159428  return 2;
159429 }
159430 static int writeCoord(u8 *p, RtreeCoord *pCoord){
159431  u32 i;
159432  assert( sizeof(RtreeCoord)==4 );
159433  assert( sizeof(u32)==4 );
159434  i = pCoord->u;
159435  p[0] = (i>>24)&0xFF;
159436  p[1] = (i>>16)&0xFF;
159437  p[2] = (i>> 8)&0xFF;
159438  p[3] = (i>> 0)&0xFF;
159439  return 4;
159440 }
159441 static int writeInt64(u8 *p, i64 i){
159442  p[0] = (i>>56)&0xFF;
159443  p[1] = (i>>48)&0xFF;
159444  p[2] = (i>>40)&0xFF;
159445  p[3] = (i>>32)&0xFF;
159446  p[4] = (i>>24)&0xFF;
159447  p[5] = (i>>16)&0xFF;
159448  p[6] = (i>> 8)&0xFF;
159449  p[7] = (i>> 0)&0xFF;
159450  return 8;
159451 }
159452 
159453 /*
159454 ** Increment the reference count of node p.
159455 */
159456 static void nodeReference(RtreeNode *p){
159457  if( p ){
159458  p->nRef++;
159459  }
159460 }
159461 
159462 /*
159463 ** Clear the content of node p (set all bytes to 0x00).
159464 */
159465 static void nodeZero(Rtree *pRtree, RtreeNode *p){
159466  memset(&p->zData[2], 0, pRtree->iNodeSize-2);
159467  p->isDirty = 1;
159468 }
159469 
159470 /*
159471 ** Given a node number iNode, return the corresponding key to use
159472 ** in the Rtree.aHash table.
159473 */
159474 static int nodeHash(i64 iNode){
159475  return iNode % HASHSIZE;
159476 }
159477 
159478 /*
159479 ** Search the node hash table for node iNode. If found, return a pointer
159480 ** to it. Otherwise, return 0.
159481 */
159482 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
159483  RtreeNode *p;
159484  for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
159485  return p;
159486 }
159487 
159488 /*
159489 ** Add node pNode to the node hash table.
159490 */
159491 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
159492  int iHash;
159493  assert( pNode->pNext==0 );
159494  iHash = nodeHash(pNode->iNode);
159495  pNode->pNext = pRtree->aHash[iHash];
159496  pRtree->aHash[iHash] = pNode;
159497 }
159498 
159499 /*
159500 ** Remove node pNode from the node hash table.
159501 */
159502 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
159503  RtreeNode **pp;
159504  if( pNode->iNode!=0 ){
159505  pp = &pRtree->aHash[nodeHash(pNode->iNode)];
159506  for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
159507  *pp = pNode->pNext;
159508  pNode->pNext = 0;
159509  }
159510 }
159511 
159512 /*
159513 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
159514 ** indicating that node has not yet been assigned a node number. It is
159515 ** assigned a node number when nodeWrite() is called to write the
159516 ** node contents out to the database.
159517 */
159518 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
159519  RtreeNode *pNode;
159520  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
159521  if( pNode ){
159522  memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
159523  pNode->zData = (u8 *)&pNode[1];
159524  pNode->nRef = 1;
159525  pNode->pParent = pParent;
159526  pNode->isDirty = 1;
159527  nodeReference(pParent);
159528  }
159529  return pNode;
159530 }
159531 
159532 /*
159533 ** Obtain a reference to an r-tree node.
159534 */
159535 static int nodeAcquire(
159536  Rtree *pRtree, /* R-tree structure */
159537  i64 iNode, /* Node number to load */
159538  RtreeNode *pParent, /* Either the parent node or NULL */
159539  RtreeNode **ppNode /* OUT: Acquired node */
159540 ){
159541  int rc;
159542  int rc2 = SQLITE_OK;
159543  RtreeNode *pNode;
159544 
159545  /* Check if the requested node is already in the hash table. If so,
159546  ** increase its reference count and return it.
159547  */
159548  if( (pNode = nodeHashLookup(pRtree, iNode)) ){
159549  assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
159550  if( pParent && !pNode->pParent ){
159551  nodeReference(pParent);
159552  pNode->pParent = pParent;
159553  }
159554  pNode->nRef++;
159555  *ppNode = pNode;
159556  return SQLITE_OK;
159557  }
159558 
159559  sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
159560  rc = sqlite3_step(pRtree->pReadNode);
159561  if( rc==SQLITE_ROW ){
159562  const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
159563  if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
159564  pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
159565  if( !pNode ){
159566  rc2 = SQLITE_NOMEM;
159567  }else{
159568  pNode->pParent = pParent;
159569  pNode->zData = (u8 *)&pNode[1];
159570  pNode->nRef = 1;
159571  pNode->iNode = iNode;
159572  pNode->isDirty = 0;
159573  pNode->pNext = 0;
159574  memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
159575  nodeReference(pParent);
159576  }
159577  }
159578  }
159579  rc = sqlite3_reset(pRtree->pReadNode);
159580  if( rc==SQLITE_OK ) rc = rc2;
159581 
159582  /* If the root node was just loaded, set pRtree->iDepth to the height
159583  ** of the r-tree structure. A height of zero means all data is stored on
159584  ** the root node. A height of one means the children of the root node
159585  ** are the leaves, and so on. If the depth as specified on the root node
159586  ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
159587  */
159588  if( pNode && iNode==1 ){
159589  pRtree->iDepth = readInt16(pNode->zData);
159590  if( pRtree->iDepth>RTREE_MAX_DEPTH ){
159591  rc = SQLITE_CORRUPT_VTAB;
159592  }
159593  }
159594 
159595  /* If no error has occurred so far, check if the "number of entries"
159596  ** field on the node is too large. If so, set the return code to
159597  ** SQLITE_CORRUPT_VTAB.
159598  */
159599  if( pNode && rc==SQLITE_OK ){
159600  if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
159601  rc = SQLITE_CORRUPT_VTAB;
159602  }
159603  }
159604 
159605  if( rc==SQLITE_OK ){
159606  if( pNode!=0 ){
159607  nodeHashInsert(pRtree, pNode);
159608  }else{
159609  rc = SQLITE_CORRUPT_VTAB;
159610  }
159611  *ppNode = pNode;
159612  }else{
159613  sqlite3_free(pNode);
159614  *ppNode = 0;
159615  }
159616 
159617  return rc;
159618 }
159619 
159620 /*
159621 ** Overwrite cell iCell of node pNode with the contents of pCell.
159622 */
159623 static void nodeOverwriteCell(
159624  Rtree *pRtree, /* The overall R-Tree */
159625  RtreeNode *pNode, /* The node into which the cell is to be written */
159626  RtreeCell *pCell, /* The cell to write */
159627  int iCell /* Index into pNode into which pCell is written */
159628 ){
159629  int ii;
159630  u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
159631  p += writeInt64(p, pCell->iRowid);
159632  for(ii=0; ii<(pRtree->nDim*2); ii++){
159633  p += writeCoord(p, &pCell->aCoord[ii]);
159634  }
159635  pNode->isDirty = 1;
159636 }
159637 
159638 /*
159639 ** Remove the cell with index iCell from node pNode.
159640 */
159641 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
159642  u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
159643  u8 *pSrc = &pDst[pRtree->nBytesPerCell];
159644  int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
159645  memmove(pDst, pSrc, nByte);
159646  writeInt16(&pNode->zData[2], NCELL(pNode)-1);
159647  pNode->isDirty = 1;
159648 }
159649 
159650 /*
159651 ** Insert the contents of cell pCell into node pNode. If the insert
159652 ** is successful, return SQLITE_OK.
159653 **
159654 ** If there is not enough free space in pNode, return SQLITE_FULL.
159655 */
159656 static int nodeInsertCell(
159657  Rtree *pRtree, /* The overall R-Tree */
159658  RtreeNode *pNode, /* Write new cell into this node */
159659  RtreeCell *pCell /* The cell to be inserted */
159660 ){
159661  int nCell; /* Current number of cells in pNode */
159662  int nMaxCell; /* Maximum number of cells for pNode */
159663 
159664  nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
159665  nCell = NCELL(pNode);
159666 
159667  assert( nCell<=nMaxCell );
159668  if( nCell<nMaxCell ){
159669  nodeOverwriteCell(pRtree, pNode, pCell, nCell);
159670  writeInt16(&pNode->zData[2], nCell+1);
159671  pNode->isDirty = 1;
159672  }
159673 
159674  return (nCell==nMaxCell);
159675 }
159676 
159677 /*
159678 ** If the node is dirty, write it out to the database.
159679 */
159680 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
159681  int rc = SQLITE_OK;
159682  if( pNode->isDirty ){
159683  sqlite3_stmt *p = pRtree->pWriteNode;
159684  if( pNode->iNode ){
159685  sqlite3_bind_int64(p, 1, pNode->iNode);
159686  }else{
159687  sqlite3_bind_null(p, 1);
159688  }
159689  sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
159690  sqlite3_step(p);
159691  pNode->isDirty = 0;
159692  rc = sqlite3_reset(p);
159693  if( pNode->iNode==0 && rc==SQLITE_OK ){
159694  pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
159695  nodeHashInsert(pRtree, pNode);
159696  }
159697  }
159698  return rc;
159699 }
159700 
159701 /*
159702 ** Release a reference to a node. If the node is dirty and the reference
159703 ** count drops to zero, the node data is written to the database.
159704 */
159705 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
159706  int rc = SQLITE_OK;
159707  if( pNode ){
159708  assert( pNode->nRef>0 );
159709  pNode->nRef--;
159710  if( pNode->nRef==0 ){
159711  if( pNode->iNode==1 ){
159712  pRtree->iDepth = -1;
159713  }
159714  if( pNode->pParent ){
159715  rc = nodeRelease(pRtree, pNode->pParent);
159716  }
159717  if( rc==SQLITE_OK ){
159718  rc = nodeWrite(pRtree, pNode);
159719  }
159720  nodeHashDelete(pRtree, pNode);
159721  sqlite3_free(pNode);
159722  }
159723  }
159724  return rc;
159725 }
159726 
159727 /*
159728 ** Return the 64-bit integer value associated with cell iCell of
159729 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
159730 ** an internal node, then the 64-bit integer is a child page number.
159731 */
159732 static i64 nodeGetRowid(
159733  Rtree *pRtree, /* The overall R-Tree */
159734  RtreeNode *pNode, /* The node from which to extract the ID */
159735  int iCell /* The cell index from which to extract the ID */
159736 ){
159737  assert( iCell<NCELL(pNode) );
159738  return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
159739 }
159740 
159741 /*
159742 ** Return coordinate iCoord from cell iCell in node pNode.
159743 */
159744 static void nodeGetCoord(
159745  Rtree *pRtree, /* The overall R-Tree */
159746  RtreeNode *pNode, /* The node from which to extract a coordinate */
159747  int iCell, /* The index of the cell within the node */
159748  int iCoord, /* Which coordinate to extract */
159749  RtreeCoord *pCoord /* OUT: Space to write result to */
159750 ){
159751  readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
159752 }
159753 
159754 /*
159755 ** Deserialize cell iCell of node pNode. Populate the structure pointed
159756 ** to by pCell with the results.
159757 */
159758 static void nodeGetCell(
159759  Rtree *pRtree, /* The overall R-Tree */
159760  RtreeNode *pNode, /* The node containing the cell to be read */
159761  int iCell, /* Index of the cell within the node */
159762  RtreeCell *pCell /* OUT: Write the cell contents here */
159763 ){
159764  u8 *pData;
159765  RtreeCoord *pCoord;
159766  int ii;
159767  pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
159768  pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
159769  pCoord = pCell->aCoord;
159770  for(ii=0; ii<pRtree->nDim*2; ii++){
159771  readCoord(&pData[ii*4], &pCoord[ii]);
159772  }
159773 }
159774 
159775 
159776 /* Forward declaration for the function that does the work of
159777 ** the virtual table module xCreate() and xConnect() methods.
159778 */
159779 static int rtreeInit(
159780  sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
159781 );
159782 
159783 /*
159784 ** Rtree virtual table module xCreate method.
159785 */
159786 static int rtreeCreate(
159787  sqlite3 *db,
159788  void *pAux,
159789  int argc, const char *const*argv,
159790  sqlite3_vtab **ppVtab,
159791  char **pzErr
159792 ){
159793  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
159794 }
159795 
159796 /*
159797 ** Rtree virtual table module xConnect method.
159798 */
159799 static int rtreeConnect(
159800  sqlite3 *db,
159801  void *pAux,
159802  int argc, const char *const*argv,
159803  sqlite3_vtab **ppVtab,
159804  char **pzErr
159805 ){
159806  return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
159807 }
159808 
159809 /*
159810 ** Increment the r-tree reference count.
159811 */
159812 static void rtreeReference(Rtree *pRtree){
159813  pRtree->nBusy++;
159814 }
159815 
159816 /*
159817 ** Decrement the r-tree reference count. When the reference count reaches
159818 ** zero the structure is deleted.
159819 */
159820 static void rtreeRelease(Rtree *pRtree){
159821  pRtree->nBusy--;
159822  if( pRtree->nBusy==0 ){
159823  sqlite3_finalize(pRtree->pReadNode);
159824  sqlite3_finalize(pRtree->pWriteNode);
159825  sqlite3_finalize(pRtree->pDeleteNode);
159826  sqlite3_finalize(pRtree->pReadRowid);
159827  sqlite3_finalize(pRtree->pWriteRowid);
159828  sqlite3_finalize(pRtree->pDeleteRowid);
159829  sqlite3_finalize(pRtree->pReadParent);
159830  sqlite3_finalize(pRtree->pWriteParent);
159831  sqlite3_finalize(pRtree->pDeleteParent);
159832  sqlite3_free(pRtree);
159833  }
159834 }
159835 
159836 /*
159837 ** Rtree virtual table module xDisconnect method.
159838 */
159839 static int rtreeDisconnect(sqlite3_vtab *pVtab){
159840  rtreeRelease((Rtree *)pVtab);
159841  return SQLITE_OK;
159842 }
159843 
159844 /*
159845 ** Rtree virtual table module xDestroy method.
159846 */
159847 static int rtreeDestroy(sqlite3_vtab *pVtab){
159848  Rtree *pRtree = (Rtree *)pVtab;
159849  int rc;
159850  char *zCreate = sqlite3_mprintf(
159851  "DROP TABLE '%q'.'%q_node';"
159852  "DROP TABLE '%q'.'%q_rowid';"
159853  "DROP TABLE '%q'.'%q_parent';",
159854  pRtree->zDb, pRtree->zName,
159855  pRtree->zDb, pRtree->zName,
159856  pRtree->zDb, pRtree->zName
159857  );
159858  if( !zCreate ){
159859  rc = SQLITE_NOMEM;
159860  }else{
159861  rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
159862  sqlite3_free(zCreate);
159863  }
159864  if( rc==SQLITE_OK ){
159865  rtreeRelease(pRtree);
159866  }
159867 
159868  return rc;
159869 }
159870 
159871 /*
159872 ** Rtree virtual table module xOpen method.
159873 */
159874 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
159875  int rc = SQLITE_NOMEM;
159876  RtreeCursor *pCsr;
159877 
159878  pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
159879  if( pCsr ){
159880  memset(pCsr, 0, sizeof(RtreeCursor));
159881  pCsr->base.pVtab = pVTab;
159882  rc = SQLITE_OK;
159883  }
159884  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
159885 
159886  return rc;
159887 }
159888 
159889 
159890 /*
159891 ** Free the RtreeCursor.aConstraint[] array and its contents.
159892 */
159893 static void freeCursorConstraints(RtreeCursor *pCsr){
159894  if( pCsr->aConstraint ){
159895  int i; /* Used to iterate through constraint array */
159896  for(i=0; i<pCsr->nConstraint; i++){
159897  sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
159898  if( pInfo ){
159899  if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
159900  sqlite3_free(pInfo);
159901  }
159902  }
159903  sqlite3_free(pCsr->aConstraint);
159904  pCsr->aConstraint = 0;
159905  }
159906 }
159907 
159908 /*
159909 ** Rtree virtual table module xClose method.
159910 */
159911 static int rtreeClose(sqlite3_vtab_cursor *cur){
159912  Rtree *pRtree = (Rtree *)(cur->pVtab);
159913  int ii;
159914  RtreeCursor *pCsr = (RtreeCursor *)cur;
159915  freeCursorConstraints(pCsr);
159916  sqlite3_free(pCsr->aPoint);
159917  for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
159918  sqlite3_free(pCsr);
159919  return SQLITE_OK;
159920 }
159921 
159922 /*
159923 ** Rtree virtual table module xEof method.
159924 **
159925 ** Return non-zero if the cursor does not currently point to a valid
159926 ** record (i.e if the scan has finished), or zero otherwise.
159927 */
159928 static int rtreeEof(sqlite3_vtab_cursor *cur){
159929  RtreeCursor *pCsr = (RtreeCursor *)cur;
159930  return pCsr->atEOF;
159931 }
159932 
159933 /*
159934 ** Convert raw bits from the on-disk RTree record into a coordinate value.
159935 ** The on-disk format is big-endian and needs to be converted for little-
159936 ** endian platforms. The on-disk record stores integer coordinates if
159937 ** eInt is true and it stores 32-bit floating point records if eInt is
159938 ** false. a[] is the four bytes of the on-disk record to be decoded.
159939 ** Store the results in "r".
159940 **
159941 ** There are three versions of this macro, one each for little-endian and
159942 ** big-endian processors and a third generic implementation. The endian-
159943 ** specific implementations are much faster and are preferred if the
159944 ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
159945 ** macro is part of sqliteInt.h and hence the endian-specific
159946 ** implementation will only be used if this module is compiled as part
159947 ** of the amalgamation.
159948 */
159949 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
159950 #define RTREE_DECODE_COORD(eInt, a, r) { \
159951  RtreeCoord c; /* Coordinate decoded */ \
159952  memcpy(&c.u,a,4); \
159953  c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
159954  ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
159955  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
159956 }
159957 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
159958 #define RTREE_DECODE_COORD(eInt, a, r) { \
159959  RtreeCoord c; /* Coordinate decoded */ \
159960  memcpy(&c.u,a,4); \
159961  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
159962 }
159963 #else
159964 #define RTREE_DECODE_COORD(eInt, a, r) { \
159965  RtreeCoord c; /* Coordinate decoded */ \
159966  c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
159967  +((u32)a[2]<<8) + a[3]; \
159968  r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
159969 }
159970 #endif
159971 
159972 /*
159973 ** Check the RTree node or entry given by pCellData and p against the MATCH
159974 ** constraint pConstraint.
159975 */
159976 static int rtreeCallbackConstraint(
159977  RtreeConstraint *pConstraint, /* The constraint to test */
159978  int eInt, /* True if RTree holding integer coordinates */
159979  u8 *pCellData, /* Raw cell content */
159980  RtreeSearchPoint *pSearch, /* Container of this cell */
159981  sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
159982  int *peWithin /* OUT: visibility of the cell */
159983 ){
159984  int i; /* Loop counter */
159985  sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
159986  int nCoord = pInfo->nCoord; /* No. of coordinates */
159987  int rc; /* Callback return code */
159988  sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
159989 
159990  assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
159991  assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
159992 
159993  if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
159994  pInfo->iRowid = readInt64(pCellData);
159995  }
159996  pCellData += 8;
159997  for(i=0; i<nCoord; i++, pCellData += 4){
159998  RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
159999  }
160000  if( pConstraint->op==RTREE_MATCH ){
160001  rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
160002  nCoord, aCoord, &i);
160003  if( i==0 ) *peWithin = NOT_WITHIN;
160004  *prScore = RTREE_ZERO;
160005  }else{
160006  pInfo->aCoord = aCoord;
160007  pInfo->iLevel = pSearch->iLevel - 1;
160008  pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
160009  pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
160010  rc = pConstraint->u.xQueryFunc(pInfo);
160011  if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
160012  if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
160013  *prScore = pInfo->rScore;
160014  }
160015  }
160016  return rc;
160017 }
160018 
160019 /*
160020 ** Check the internal RTree node given by pCellData against constraint p.
160021 ** If this constraint cannot be satisfied by any child within the node,
160022 ** set *peWithin to NOT_WITHIN.
160023 */
160024 static void rtreeNonleafConstraint(
160025  RtreeConstraint *p, /* The constraint to test */
160026  int eInt, /* True if RTree holds integer coordinates */
160027  u8 *pCellData, /* Raw cell content as appears on disk */
160028  int *peWithin /* Adjust downward, as appropriate */
160029 ){
160030  sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
160031 
160032  /* p->iCoord might point to either a lower or upper bound coordinate
160033  ** in a coordinate pair. But make pCellData point to the lower bound.
160034  */
160035  pCellData += 8 + 4*(p->iCoord&0xfe);
160036 
160037  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
160038  || p->op==RTREE_GT || p->op==RTREE_EQ );
160039  switch( p->op ){
160040  case RTREE_LE:
160041  case RTREE_LT:
160042  case RTREE_EQ:
160043  RTREE_DECODE_COORD(eInt, pCellData, val);
160044  /* val now holds the lower bound of the coordinate pair */
160045  if( p->u.rValue>=val ) return;
160046  if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
160047  /* Fall through for the RTREE_EQ case */
160048 
160049  default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
160050  pCellData += 4;
160051  RTREE_DECODE_COORD(eInt, pCellData, val);
160052  /* val now holds the upper bound of the coordinate pair */
160053  if( p->u.rValue<=val ) return;
160054  }
160055  *peWithin = NOT_WITHIN;
160056 }
160057 
160058 /*
160059 ** Check the leaf RTree cell given by pCellData against constraint p.
160060 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
160061 ** If the constraint is satisfied, leave *peWithin unchanged.
160062 **
160063 ** The constraint is of the form: xN op $val
160064 **
160065 ** The op is given by p->op. The xN is p->iCoord-th coordinate in
160066 ** pCellData. $val is given by p->u.rValue.
160067 */
160068 static void rtreeLeafConstraint(
160069  RtreeConstraint *p, /* The constraint to test */
160070  int eInt, /* True if RTree holds integer coordinates */
160071  u8 *pCellData, /* Raw cell content as appears on disk */
160072  int *peWithin /* Adjust downward, as appropriate */
160073 ){
160074  RtreeDValue xN; /* Coordinate value converted to a double */
160075 
160076  assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
160077  || p->op==RTREE_GT || p->op==RTREE_EQ );
160078  pCellData += 8 + p->iCoord*4;
160079  RTREE_DECODE_COORD(eInt, pCellData, xN);
160080  switch( p->op ){
160081  case RTREE_LE: if( xN <= p->u.rValue ) return; break;
160082  case RTREE_LT: if( xN < p->u.rValue ) return; break;
160083  case RTREE_GE: if( xN >= p->u.rValue ) return; break;
160084  case RTREE_GT: if( xN > p->u.rValue ) return; break;
160085  default: if( xN == p->u.rValue ) return; break;
160086  }
160087  *peWithin = NOT_WITHIN;
160088 }
160089 
160090 /*
160091 ** One of the cells in node pNode is guaranteed to have a 64-bit
160092 ** integer value equal to iRowid. Return the index of this cell.
160093 */
160094 static int nodeRowidIndex(
160095  Rtree *pRtree,
160096  RtreeNode *pNode,
160097  i64 iRowid,
160098  int *piIndex
160099 ){
160100  int ii;
160101  int nCell = NCELL(pNode);
160102  assert( nCell<200 );
160103  for(ii=0; ii<nCell; ii++){
160104  if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
160105  *piIndex = ii;
160106  return SQLITE_OK;
160107  }
160108  }
160109  return SQLITE_CORRUPT_VTAB;
160110 }
160111 
160112 /*
160113 ** Return the index of the cell containing a pointer to node pNode
160114 ** in its parent. If pNode is the root node, return -1.
160115 */
160116 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
160117  RtreeNode *pParent = pNode->pParent;
160118  if( pParent ){
160119  return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
160120  }
160121  *piIndex = -1;
160122  return SQLITE_OK;
160123 }
160124 
160125 /*
160126 ** Compare two search points. Return negative, zero, or positive if the first
160127 ** is less than, equal to, or greater than the second.
160128 **
160129 ** The rScore is the primary key. Smaller rScore values come first.
160130 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
160131 ** iLevel values coming first. In this way, if rScore is the same for all
160132 ** SearchPoints, then iLevel becomes the deciding factor and the result
160133 ** is a depth-first search, which is the desired default behavior.
160134 */
160135 static int rtreeSearchPointCompare(
160136  const RtreeSearchPoint *pA,
160137  const RtreeSearchPoint *pB
160138 ){
160139  if( pA->rScore<pB->rScore ) return -1;
160140  if( pA->rScore>pB->rScore ) return +1;
160141  if( pA->iLevel<pB->iLevel ) return -1;
160142  if( pA->iLevel>pB->iLevel ) return +1;
160143  return 0;
160144 }
160145 
160146 /*
160147 ** Interchange to search points in a cursor.
160148 */
160149 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
160150  RtreeSearchPoint t = p->aPoint[i];
160151  assert( i<j );
160152  p->aPoint[i] = p->aPoint[j];
160153  p->aPoint[j] = t;
160154  i++; j++;
160155  if( i<RTREE_CACHE_SZ ){
160156  if( j>=RTREE_CACHE_SZ ){
160157  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
160158  p->aNode[i] = 0;
160159  }else{
160160  RtreeNode *pTemp = p->aNode[i];
160161  p->aNode[i] = p->aNode[j];
160162  p->aNode[j] = pTemp;
160163  }
160164  }
160165 }
160166 
160167 /*
160168 ** Return the search point with the lowest current score.
160169 */
160170 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
160171  return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
160172 }
160173 
160174 /*
160175 ** Get the RtreeNode for the search point with the lowest score.
160176 */
160177 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
160178  sqlite3_int64 id;
160179  int ii = 1 - pCur->bPoint;
160180  assert( ii==0 || ii==1 );
160181  assert( pCur->bPoint || pCur->nPoint );
160182  if( pCur->aNode[ii]==0 ){
160183  assert( pRC!=0 );
160184  id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
160185  *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
160186  }
160187  return pCur->aNode[ii];
160188 }
160189 
160190 /*
160191 ** Push a new element onto the priority queue
160192 */
160193 static RtreeSearchPoint *rtreeEnqueue(
160194  RtreeCursor *pCur, /* The cursor */
160195  RtreeDValue rScore, /* Score for the new search point */
160196  u8 iLevel /* Level for the new search point */
160197 ){
160198  int i, j;
160199  RtreeSearchPoint *pNew;
160200  if( pCur->nPoint>=pCur->nPointAlloc ){
160201  int nNew = pCur->nPointAlloc*2 + 8;
160202  pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
160203  if( pNew==0 ) return 0;
160204  pCur->aPoint = pNew;
160205  pCur->nPointAlloc = nNew;
160206  }
160207  i = pCur->nPoint++;
160208  pNew = pCur->aPoint + i;
160209  pNew->rScore = rScore;
160210  pNew->iLevel = iLevel;
160211  assert( iLevel<=RTREE_MAX_DEPTH );
160212  while( i>0 ){
160213  RtreeSearchPoint *pParent;
160214  j = (i-1)/2;
160215  pParent = pCur->aPoint + j;
160216  if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
160217  rtreeSearchPointSwap(pCur, j, i);
160218  i = j;
160219  pNew = pParent;
160220  }
160221  return pNew;
160222 }
160223 
160224 /*
160225 ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
160226 ** NULL if malloc fails.
160227 */
160228 static RtreeSearchPoint *rtreeSearchPointNew(
160229  RtreeCursor *pCur, /* The cursor */
160230  RtreeDValue rScore, /* Score for the new search point */
160231  u8 iLevel /* Level for the new search point */
160232 ){
160233  RtreeSearchPoint *pNew, *pFirst;
160234  pFirst = rtreeSearchPointFirst(pCur);
160235  pCur->anQueue[iLevel]++;
160236  if( pFirst==0
160237  || pFirst->rScore>rScore
160238  || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
160239  ){
160240  if( pCur->bPoint ){
160241  int ii;
160242  pNew = rtreeEnqueue(pCur, rScore, iLevel);
160243  if( pNew==0 ) return 0;
160244  ii = (int)(pNew - pCur->aPoint) + 1;
160245  if( ii<RTREE_CACHE_SZ ){
160246  assert( pCur->aNode[ii]==0 );
160247  pCur->aNode[ii] = pCur->aNode[0];
160248  }else{
160249  nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
160250  }
160251  pCur->aNode[0] = 0;
160252  *pNew = pCur->sPoint;
160253  }
160254  pCur->sPoint.rScore = rScore;
160255  pCur->sPoint.iLevel = iLevel;
160256  pCur->bPoint = 1;
160257  return &pCur->sPoint;
160258  }else{
160259  return rtreeEnqueue(pCur, rScore, iLevel);
160260  }
160261 }
160262 
160263 #if 0
160264 /* Tracing routines for the RtreeSearchPoint queue */
160265 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
160266  if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
160267  printf(" %d.%05lld.%02d %g %d",
160268  p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
160269  );
160270  idx++;
160271  if( idx<RTREE_CACHE_SZ ){
160272  printf(" %p\n", pCur->aNode[idx]);
160273  }else{
160274  printf("\n");
160275  }
160276 }
160277 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
160278  int ii;
160279  printf("=== %9s ", zPrefix);
160280  if( pCur->bPoint ){
160281  tracePoint(&pCur->sPoint, -1, pCur);
160282  }
160283  for(ii=0; ii<pCur->nPoint; ii++){
160284  if( ii>0 || pCur->bPoint ) printf(" ");
160285  tracePoint(&pCur->aPoint[ii], ii, pCur);
160286  }
160287 }
160288 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
160289 #else
160290 # define RTREE_QUEUE_TRACE(A,B) /* no-op */
160291 #endif
160292 
160293 /* Remove the search point with the lowest current score.
160294 */
160295 static void rtreeSearchPointPop(RtreeCursor *p){
160296  int i, j, k, n;
160297  i = 1 - p->bPoint;
160298  assert( i==0 || i==1 );
160299  if( p->aNode[i] ){
160300  nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
160301  p->aNode[i] = 0;
160302  }
160303  if( p->bPoint ){
160304  p->anQueue[p->sPoint.iLevel]--;
160305  p->bPoint = 0;
160306  }else if( p->nPoint ){
160307  p->anQueue[p->aPoint[0].iLevel]--;
160308  n = --p->nPoint;
160309  p->aPoint[0] = p->aPoint[n];
160310  if( n<RTREE_CACHE_SZ-1 ){
160311  p->aNode[1] = p->aNode[n+1];
160312  p->aNode[n+1] = 0;
160313  }
160314  i = 0;
160315  while( (j = i*2+1)<n ){
160316  k = j+1;
160317  if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
160318  if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
160319  rtreeSearchPointSwap(p, i, k);
160320  i = k;
160321  }else{
160322  break;
160323  }
160324  }else{
160325  if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
160326  rtreeSearchPointSwap(p, i, j);
160327  i = j;
160328  }else{
160329  break;
160330  }
160331  }
160332  }
160333  }
160334 }
160335 
160336 
160337 /*
160338 ** Continue the search on cursor pCur until the front of the queue
160339 ** contains an entry suitable for returning as a result-set row,
160340 ** or until the RtreeSearchPoint queue is empty, indicating that the
160341 ** query has completed.
160342 */
160343 static int rtreeStepToLeaf(RtreeCursor *pCur){
160344  RtreeSearchPoint *p;
160345  Rtree *pRtree = RTREE_OF_CURSOR(pCur);
160346  RtreeNode *pNode;
160347  int eWithin;
160348  int rc = SQLITE_OK;
160349  int nCell;
160350  int nConstraint = pCur->nConstraint;
160351  int ii;
160352  int eInt;
160353  RtreeSearchPoint x;
160354 
160355  eInt = pRtree->eCoordType==RTREE_COORD_INT32;
160356  while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
160357  pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
160358  if( rc ) return rc;
160359  nCell = NCELL(pNode);
160360  assert( nCell<200 );
160361  while( p->iCell<nCell ){
160362  sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
160363  u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
160364  eWithin = FULLY_WITHIN;
160365  for(ii=0; ii<nConstraint; ii++){
160366  RtreeConstraint *pConstraint = pCur->aConstraint + ii;
160367  if( pConstraint->op>=RTREE_MATCH ){
160368  rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
160369  &rScore, &eWithin);
160370  if( rc ) return rc;
160371  }else if( p->iLevel==1 ){
160372  rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
160373  }else{
160374  rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
160375  }
160376  if( eWithin==NOT_WITHIN ) break;
160377  }
160378  p->iCell++;
160379  if( eWithin==NOT_WITHIN ) continue;
160380  x.iLevel = p->iLevel - 1;
160381  if( x.iLevel ){
160382  x.id = readInt64(pCellData);
160383  x.iCell = 0;
160384  }else{
160385  x.id = p->id;
160386  x.iCell = p->iCell - 1;
160387  }
160388  if( p->iCell>=nCell ){
160389  RTREE_QUEUE_TRACE(pCur, "POP-S:");
160390  rtreeSearchPointPop(pCur);
160391  }
160392  if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
160393  p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
160394  if( p==0 ) return SQLITE_NOMEM;
160395  p->eWithin = eWithin;
160396  p->id = x.id;
160397  p->iCell = x.iCell;
160398  RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
160399  break;
160400  }
160401  if( p->iCell>=nCell ){
160402  RTREE_QUEUE_TRACE(pCur, "POP-Se:");
160403  rtreeSearchPointPop(pCur);
160404  }
160405  }
160406  pCur->atEOF = p==0;
160407  return SQLITE_OK;
160408 }
160409 
160410 /*
160411 ** Rtree virtual table module xNext method.
160412 */
160413 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
160414  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
160415  int rc = SQLITE_OK;
160416 
160417  /* Move to the next entry that matches the configured constraints. */
160418  RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
160419  rtreeSearchPointPop(pCsr);
160420  rc = rtreeStepToLeaf(pCsr);
160421  return rc;
160422 }
160423 
160424 /*
160425 ** Rtree virtual table module xRowid method.
160426 */
160427 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
160428  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
160429  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
160430  int rc = SQLITE_OK;
160431  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
160432  if( rc==SQLITE_OK && p ){
160433  *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
160434  }
160435  return rc;
160436 }
160437 
160438 /*
160439 ** Rtree virtual table module xColumn method.
160440 */
160441 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
160442  Rtree *pRtree = (Rtree *)cur->pVtab;
160443  RtreeCursor *pCsr = (RtreeCursor *)cur;
160444  RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
160445  RtreeCoord c;
160446  int rc = SQLITE_OK;
160447  RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
160448 
160449  if( rc ) return rc;
160450  if( p==0 ) return SQLITE_OK;
160451  if( i==0 ){
160452  sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
160453  }else{
160454  if( rc ) return rc;
160455  nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
160456 #ifndef SQLITE_RTREE_INT_ONLY
160457  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
160458  sqlite3_result_double(ctx, c.f);
160459  }else
160460 #endif
160461  {
160462  assert( pRtree->eCoordType==RTREE_COORD_INT32 );
160463  sqlite3_result_int(ctx, c.i);
160464  }
160465  }
160466  return SQLITE_OK;
160467 }
160468 
160469 /*
160470 ** Use nodeAcquire() to obtain the leaf node containing the record with
160471 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
160472 ** return SQLITE_OK. If there is no such record in the table, set
160473 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
160474 ** to zero and return an SQLite error code.
160475 */
160476 static int findLeafNode(
160477  Rtree *pRtree, /* RTree to search */
160478  i64 iRowid, /* The rowid searching for */
160479  RtreeNode **ppLeaf, /* Write the node here */
160480  sqlite3_int64 *piNode /* Write the node-id here */
160481 ){
160482  int rc;
160483  *ppLeaf = 0;
160484  sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
160485  if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
160486  i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
160487  if( piNode ) *piNode = iNode;
160488  rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
160489  sqlite3_reset(pRtree->pReadRowid);
160490  }else{
160491  rc = sqlite3_reset(pRtree->pReadRowid);
160492  }
160493  return rc;
160494 }
160495 
160496 /*
160497 ** This function is called to configure the RtreeConstraint object passed
160498 ** as the second argument for a MATCH constraint. The value passed as the
160499 ** first argument to this function is the right-hand operand to the MATCH
160500 ** operator.
160501 */
160502 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
160503  RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
160504  sqlite3_rtree_query_info *pInfo; /* Callback information */
160505  int nBlob; /* Size of the geometry function blob */
160506  int nExpected; /* Expected size of the BLOB */
160507 
160508  /* Check that value is actually a blob. */
160509  if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
160510 
160511  /* Check that the blob is roughly the right size. */
160512  nBlob = sqlite3_value_bytes(pValue);
160513  if( nBlob<(int)sizeof(RtreeMatchArg) ){
160514  return SQLITE_ERROR;
160515  }
160516 
160517  pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
160518  if( !pInfo ) return SQLITE_NOMEM;
160519  memset(pInfo, 0, sizeof(*pInfo));
160520  pBlob = (RtreeMatchArg*)&pInfo[1];
160521 
160522  memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
160523  nExpected = (int)(sizeof(RtreeMatchArg) +
160524  pBlob->nParam*sizeof(sqlite3_value*) +
160525  (pBlob->nParam-1)*sizeof(RtreeDValue));
160526  if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
160527  sqlite3_free(pInfo);
160528  return SQLITE_ERROR;
160529  }
160530  pInfo->pContext = pBlob->cb.pContext;
160531  pInfo->nParam = pBlob->nParam;
160532  pInfo->aParam = pBlob->aParam;
160533  pInfo->apSqlParam = pBlob->apSqlParam;
160534 
160535  if( pBlob->cb.xGeom ){
160536  pCons->u.xGeom = pBlob->cb.xGeom;
160537  }else{
160538  pCons->op = RTREE_QUERY;
160539  pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
160540  }
160541  pCons->pInfo = pInfo;
160542  return SQLITE_OK;
160543 }
160544 
160545 /*
160546 ** Rtree virtual table module xFilter method.
160547 */
160548 static int rtreeFilter(
160549  sqlite3_vtab_cursor *pVtabCursor,
160550  int idxNum, const char *idxStr,
160551  int argc, sqlite3_value **argv
160552 ){
160553  Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
160554  RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
160555  RtreeNode *pRoot = 0;
160556  int ii;
160557  int rc = SQLITE_OK;
160558  int iCell = 0;
160559 
160560  rtreeReference(pRtree);
160561 
160562  /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
160563  freeCursorConstraints(pCsr);
160564  sqlite3_free(pCsr->aPoint);
160565  memset(pCsr, 0, sizeof(RtreeCursor));
160566  pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
160567 
160568  pCsr->iStrategy = idxNum;
160569  if( idxNum==1 ){
160570  /* Special case - lookup by rowid. */
160571  RtreeNode *pLeaf; /* Leaf on which the required cell resides */
160572  RtreeSearchPoint *p; /* Search point for the the leaf */
160573  i64 iRowid = sqlite3_value_int64(argv[0]);
160574  i64 iNode = 0;
160575  rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
160576  if( rc==SQLITE_OK && pLeaf!=0 ){
160577  p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
160578  assert( p!=0 ); /* Always returns pCsr->sPoint */
160579  pCsr->aNode[0] = pLeaf;
160580  p->id = iNode;
160581  p->eWithin = PARTLY_WITHIN;
160582  rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
160583  p->iCell = iCell;
160584  RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
160585  }else{
160586  pCsr->atEOF = 1;
160587  }
160588  }else{
160589  /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
160590  ** with the configured constraints.
160591  */
160592  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
160593  if( rc==SQLITE_OK && argc>0 ){
160594  pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
160595  pCsr->nConstraint = argc;
160596  if( !pCsr->aConstraint ){
160597  rc = SQLITE_NOMEM;
160598  }else{
160599  memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
160600  memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
160601  assert( (idxStr==0 && argc==0)
160602  || (idxStr && (int)strlen(idxStr)==argc*2) );
160603  for(ii=0; ii<argc; ii++){
160604  RtreeConstraint *p = &pCsr->aConstraint[ii];
160605  p->op = idxStr[ii*2];
160606  p->iCoord = idxStr[ii*2+1]-'0';
160607  if( p->op>=RTREE_MATCH ){
160608  /* A MATCH operator. The right-hand-side must be a blob that
160609  ** can be cast into an RtreeMatchArg object. One created using
160610  ** an sqlite3_rtree_geometry_callback() SQL user function.
160611  */
160612  rc = deserializeGeometry(argv[ii], p);
160613  if( rc!=SQLITE_OK ){
160614  break;
160615  }
160616  p->pInfo->nCoord = pRtree->nDim*2;
160617  p->pInfo->anQueue = pCsr->anQueue;
160618  p->pInfo->mxLevel = pRtree->iDepth + 1;
160619  }else{
160620 #ifdef SQLITE_RTREE_INT_ONLY
160621  p->u.rValue = sqlite3_value_int64(argv[ii]);
160622 #else
160623  p->u.rValue = sqlite3_value_double(argv[ii]);
160624 #endif
160625  }
160626  }
160627  }
160628  }
160629  if( rc==SQLITE_OK ){
160630  RtreeSearchPoint *pNew;
160631  pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
160632  if( pNew==0 ) return SQLITE_NOMEM;
160633  pNew->id = 1;
160634  pNew->iCell = 0;
160635  pNew->eWithin = PARTLY_WITHIN;
160636  assert( pCsr->bPoint==1 );
160637  pCsr->aNode[0] = pRoot;
160638  pRoot = 0;
160639  RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
160640  rc = rtreeStepToLeaf(pCsr);
160641  }
160642  }
160643 
160644  nodeRelease(pRtree, pRoot);
160645  rtreeRelease(pRtree);
160646  return rc;
160647 }
160648 
160649 /*
160650 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
160651 ** extension is currently being used by a version of SQLite too old to
160652 ** support estimatedRows. In that case this function is a no-op.
160653 */
160654 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
160655 #if SQLITE_VERSION_NUMBER>=3008002
160656  if( sqlite3_libversion_number()>=3008002 ){
160657  pIdxInfo->estimatedRows = nRow;
160658  }
160659 #endif
160660 }
160661 
160662 /*
160663 ** Rtree virtual table module xBestIndex method. There are three
160664 ** table scan strategies to choose from (in order from most to
160665 ** least desirable):
160666 **
160667 ** idxNum idxStr Strategy
160668 ** ------------------------------------------------
160669 ** 1 Unused Direct lookup by rowid.
160670 ** 2 See below R-tree query or full-table scan.
160671 ** ------------------------------------------------
160672 **
160673 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
160674 ** 2 is used, idxStr is formatted to contain 2 bytes for each
160675 ** constraint used. The first two bytes of idxStr correspond to
160676 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
160677 ** (argvIndex==1) etc.
160678 **
160679 ** The first of each pair of bytes in idxStr identifies the constraint
160680 ** operator as follows:
160681 **
160682 ** Operator Byte Value
160683 ** ----------------------
160684 ** = 0x41 ('A')
160685 ** <= 0x42 ('B')
160686 ** < 0x43 ('C')
160687 ** >= 0x44 ('D')
160688 ** > 0x45 ('E')
160689 ** MATCH 0x46 ('F')
160690 ** ----------------------
160691 **
160692 ** The second of each pair of bytes identifies the coordinate column
160693 ** to which the constraint applies. The leftmost coordinate column
160694 ** is 'a', the second from the left 'b' etc.
160695 */
160696 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
160697  Rtree *pRtree = (Rtree*)tab;
160698  int rc = SQLITE_OK;
160699  int ii;
160700  int bMatch = 0; /* True if there exists a MATCH constraint */
160701  i64 nRow; /* Estimated rows returned by this scan */
160702 
160703  int iIdx = 0;
160704  char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
160705  memset(zIdxStr, 0, sizeof(zIdxStr));
160706 
160707  /* Check if there exists a MATCH constraint - even an unusable one. If there
160708  ** is, do not consider the lookup-by-rowid plan as using such a plan would
160709  ** require the VDBE to evaluate the MATCH constraint, which is not currently
160710  ** possible. */
160711  for(ii=0; ii<pIdxInfo->nConstraint; ii++){
160712  if( pIdxInfo->aConstraint[ii].op==SQLITE_INDEX_CONSTRAINT_MATCH ){
160713  bMatch = 1;
160714  }
160715  }
160716 
160717  assert( pIdxInfo->idxStr==0 );
160718  for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
160719  struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
160720 
160721  if( bMatch==0 && p->usable
160722  && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ
160723  ){
160724  /* We have an equality constraint on the rowid. Use strategy 1. */
160725  int jj;
160726  for(jj=0; jj<ii; jj++){
160727  pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
160728  pIdxInfo->aConstraintUsage[jj].omit = 0;
160729  }
160730  pIdxInfo->idxNum = 1;
160731  pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
160732  pIdxInfo->aConstraintUsage[jj].omit = 1;
160733 
160734  /* This strategy involves a two rowid lookups on an B-Tree structures
160735  ** and then a linear search of an R-Tree node. This should be
160736  ** considered almost as quick as a direct rowid lookup (for which
160737  ** sqlite uses an internal cost of 0.0). It is expected to return
160738  ** a single row.
160739  */
160740  pIdxInfo->estimatedCost = 30.0;
160741  setEstimatedRows(pIdxInfo, 1);
160742  return SQLITE_OK;
160743  }
160744 
160745  if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
160746  u8 op;
160747  switch( p->op ){
160748  case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
160749  case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
160750  case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
160751  case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
160752  case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
160753  default:
160755  op = RTREE_MATCH;
160756  break;
160757  }
160758  zIdxStr[iIdx++] = op;
160759  zIdxStr[iIdx++] = p->iColumn - 1 + '0';
160760  pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
160761  pIdxInfo->aConstraintUsage[ii].omit = 1;
160762  }
160763  }
160764 
160765  pIdxInfo->idxNum = 2;
160766  pIdxInfo->needToFreeIdxStr = 1;
160767  if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
160768  return SQLITE_NOMEM;
160769  }
160770 
160771  nRow = pRtree->nRowEst >> (iIdx/2);
160772  pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
160773  setEstimatedRows(pIdxInfo, nRow);
160774 
160775  return rc;
160776 }
160777 
160778 /*
160779 ** Return the N-dimensional volumn of the cell stored in *p.
160780 */
160781 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
160782  RtreeDValue area = (RtreeDValue)1;
160783  int ii;
160784  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
160785  area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
160786  }
160787  return area;
160788 }
160789 
160790 /*
160791 ** Return the margin length of cell p. The margin length is the sum
160792 ** of the objects size in each dimension.
160793 */
160794 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
160795  RtreeDValue margin = (RtreeDValue)0;
160796  int ii;
160797  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
160798  margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
160799  }
160800  return margin;
160801 }
160802 
160803 /*
160804 ** Store the union of cells p1 and p2 in p1.
160805 */
160806 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
160807  int ii;
160808  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
160809  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
160810  p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
160811  p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
160812  }
160813  }else{
160814  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
160815  p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
160816  p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
160817  }
160818  }
160819 }
160820 
160821 /*
160822 ** Return true if the area covered by p2 is a subset of the area covered
160823 ** by p1. False otherwise.
160824 */
160825 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
160826  int ii;
160827  int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
160828  for(ii=0; ii<(pRtree->nDim*2); ii+=2){
160829  RtreeCoord *a1 = &p1->aCoord[ii];
160830  RtreeCoord *a2 = &p2->aCoord[ii];
160831  if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
160832  || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
160833  ){
160834  return 0;
160835  }
160836  }
160837  return 1;
160838 }
160839 
160840 /*
160841 ** Return the amount cell p would grow by if it were unioned with pCell.
160842 */
160843 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
160844  RtreeDValue area;
160845  RtreeCell cell;
160846  memcpy(&cell, p, sizeof(RtreeCell));
160847  area = cellArea(pRtree, &cell);
160848  cellUnion(pRtree, &cell, pCell);
160849  return (cellArea(pRtree, &cell)-area);
160850 }
160851 
160852 static RtreeDValue cellOverlap(
160853  Rtree *pRtree,
160854  RtreeCell *p,
160855  RtreeCell *aCell,
160856  int nCell
160857 ){
160858  int ii;
160859  RtreeDValue overlap = RTREE_ZERO;
160860  for(ii=0; ii<nCell; ii++){
160861  int jj;
160862  RtreeDValue o = (RtreeDValue)1;
160863  for(jj=0; jj<(pRtree->nDim*2); jj+=2){
160864  RtreeDValue x1, x2;
160865  x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
160866  x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
160867  if( x2<x1 ){
160868  o = (RtreeDValue)0;
160869  break;
160870  }else{
160871  o = o * (x2-x1);
160872  }
160873  }
160874  overlap += o;
160875  }
160876  return overlap;
160877 }
160878 
160879 
160880 /*
160881 ** This function implements the ChooseLeaf algorithm from Gutman[84].
160882 ** ChooseSubTree in r*tree terminology.
160883 */
160884 static int ChooseLeaf(
160885  Rtree *pRtree, /* Rtree table */
160886  RtreeCell *pCell, /* Cell to insert into rtree */
160887  int iHeight, /* Height of sub-tree rooted at pCell */
160888  RtreeNode **ppLeaf /* OUT: Selected leaf page */
160889 ){
160890  int rc;
160891  int ii;
160892  RtreeNode *pNode;
160893  rc = nodeAcquire(pRtree, 1, 0, &pNode);
160894 
160895  for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
160896  int iCell;
160897  sqlite3_int64 iBest = 0;
160898 
160899  RtreeDValue fMinGrowth = RTREE_ZERO;
160900  RtreeDValue fMinArea = RTREE_ZERO;
160901 
160902  int nCell = NCELL(pNode);
160903  RtreeCell cell;
160904  RtreeNode *pChild;
160905 
160906  RtreeCell *aCell = 0;
160907 
160908  /* Select the child node which will be enlarged the least if pCell
160909  ** is inserted into it. Resolve ties by choosing the entry with
160910  ** the smallest area.
160911  */
160912  for(iCell=0; iCell<nCell; iCell++){
160913  int bBest = 0;
160914  RtreeDValue growth;
160915  RtreeDValue area;
160916  nodeGetCell(pRtree, pNode, iCell, &cell);
160917  growth = cellGrowth(pRtree, &cell, pCell);
160918  area = cellArea(pRtree, &cell);
160919  if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
160920  bBest = 1;
160921  }
160922  if( bBest ){
160923  fMinGrowth = growth;
160924  fMinArea = area;
160925  iBest = cell.iRowid;
160926  }
160927  }
160928 
160929  sqlite3_free(aCell);
160930  rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
160931  nodeRelease(pRtree, pNode);
160932  pNode = pChild;
160933  }
160934 
160935  *ppLeaf = pNode;
160936  return rc;
160937 }
160938 
160939 /*
160940 ** A cell with the same content as pCell has just been inserted into
160941 ** the node pNode. This function updates the bounding box cells in
160942 ** all ancestor elements.
160943 */
160944 static int AdjustTree(
160945  Rtree *pRtree, /* Rtree table */
160946  RtreeNode *pNode, /* Adjust ancestry of this node. */
160947  RtreeCell *pCell /* This cell was just inserted */
160948 ){
160949  RtreeNode *p = pNode;
160950  while( p->pParent ){
160951  RtreeNode *pParent = p->pParent;
160952  RtreeCell cell;
160953  int iCell;
160954 
160955  if( nodeParentIndex(pRtree, p, &iCell) ){
160956  return SQLITE_CORRUPT_VTAB;
160957  }
160958 
160959  nodeGetCell(pRtree, pParent, iCell, &cell);
160960  if( !cellContains(pRtree, &cell, pCell) ){
160961  cellUnion(pRtree, &cell, pCell);
160962  nodeOverwriteCell(pRtree, pParent, &cell, iCell);
160963  }
160964 
160965  p = pParent;
160966  }
160967  return SQLITE_OK;
160968 }
160969 
160970 /*
160971 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
160972 */
160973 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
160974  sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
160975  sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
160976  sqlite3_step(pRtree->pWriteRowid);
160977  return sqlite3_reset(pRtree->pWriteRowid);
160978 }
160979 
160980 /*
160981 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
160982 */
160983 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
160984  sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
160985  sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
160986  sqlite3_step(pRtree->pWriteParent);
160987  return sqlite3_reset(pRtree->pWriteParent);
160988 }
160989 
160990 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
160991 
160992 
160993 /*
160994 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
160995 ** nIdx. The aIdx array contains the set of integers from 0 to
160996 ** (nIdx-1) in no particular order. This function sorts the values
160997 ** in aIdx according to the indexed values in aDistance. For
160998 ** example, assuming the inputs:
160999 **
161000 ** aIdx = { 0, 1, 2, 3 }
161001 ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
161002 **
161003 ** this function sets the aIdx array to contain:
161004 **
161005 ** aIdx = { 0, 1, 2, 3 }
161006 **
161007 ** The aSpare array is used as temporary working space by the
161008 ** sorting algorithm.
161009 */
161010 static void SortByDistance(
161011  int *aIdx,
161012  int nIdx,
161013  RtreeDValue *aDistance,
161014  int *aSpare
161015 ){
161016  if( nIdx>1 ){
161017  int iLeft = 0;
161018  int iRight = 0;
161019 
161020  int nLeft = nIdx/2;
161021  int nRight = nIdx-nLeft;
161022  int *aLeft = aIdx;
161023  int *aRight = &aIdx[nLeft];
161024 
161025  SortByDistance(aLeft, nLeft, aDistance, aSpare);
161026  SortByDistance(aRight, nRight, aDistance, aSpare);
161027 
161028  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
161029  aLeft = aSpare;
161030 
161031  while( iLeft<nLeft || iRight<nRight ){
161032  if( iLeft==nLeft ){
161033  aIdx[iLeft+iRight] = aRight[iRight];
161034  iRight++;
161035  }else if( iRight==nRight ){
161036  aIdx[iLeft+iRight] = aLeft[iLeft];
161037  iLeft++;
161038  }else{
161039  RtreeDValue fLeft = aDistance[aLeft[iLeft]];
161040  RtreeDValue fRight = aDistance[aRight[iRight]];
161041  if( fLeft<fRight ){
161042  aIdx[iLeft+iRight] = aLeft[iLeft];
161043  iLeft++;
161044  }else{
161045  aIdx[iLeft+iRight] = aRight[iRight];
161046  iRight++;
161047  }
161048  }
161049  }
161050 
161051 #if 0
161052  /* Check that the sort worked */
161053  {
161054  int jj;
161055  for(jj=1; jj<nIdx; jj++){
161056  RtreeDValue left = aDistance[aIdx[jj-1]];
161057  RtreeDValue right = aDistance[aIdx[jj]];
161058  assert( left<=right );
161059  }
161060  }
161061 #endif
161062  }
161063 }
161064 
161065 /*
161066 ** Arguments aIdx, aCell and aSpare all point to arrays of size
161067 ** nIdx. The aIdx array contains the set of integers from 0 to
161068 ** (nIdx-1) in no particular order. This function sorts the values
161069 ** in aIdx according to dimension iDim of the cells in aCell. The
161070 ** minimum value of dimension iDim is considered first, the
161071 ** maximum used to break ties.
161072 **
161073 ** The aSpare array is used as temporary working space by the
161074 ** sorting algorithm.
161075 */
161076 static void SortByDimension(
161077  Rtree *pRtree,
161078  int *aIdx,
161079  int nIdx,
161080  int iDim,
161081  RtreeCell *aCell,
161082  int *aSpare
161083 ){
161084  if( nIdx>1 ){
161085 
161086  int iLeft = 0;
161087  int iRight = 0;
161088 
161089  int nLeft = nIdx/2;
161090  int nRight = nIdx-nLeft;
161091  int *aLeft = aIdx;
161092  int *aRight = &aIdx[nLeft];
161093 
161094  SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
161095  SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
161096 
161097  memcpy(aSpare, aLeft, sizeof(int)*nLeft);
161098  aLeft = aSpare;
161099  while( iLeft<nLeft || iRight<nRight ){
161100  RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
161101  RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
161102  RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
161103  RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
161104  if( (iLeft!=nLeft) && ((iRight==nRight)
161105  || (xleft1<xright1)
161106  || (xleft1==xright1 && xleft2<xright2)
161107  )){
161108  aIdx[iLeft+iRight] = aLeft[iLeft];
161109  iLeft++;
161110  }else{
161111  aIdx[iLeft+iRight] = aRight[iRight];
161112  iRight++;
161113  }
161114  }
161115 
161116 #if 0
161117  /* Check that the sort worked */
161118  {
161119  int jj;
161120  for(jj=1; jj<nIdx; jj++){
161121  RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
161122  RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
161123  RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
161124  RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
161125  assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
161126  }
161127  }
161128 #endif
161129  }
161130 }
161131 
161132 /*
161133 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
161134 */
161135 static int splitNodeStartree(
161136  Rtree *pRtree,
161137  RtreeCell *aCell,
161138  int nCell,
161139  RtreeNode *pLeft,
161140  RtreeNode *pRight,
161141  RtreeCell *pBboxLeft,
161142  RtreeCell *pBboxRight
161143 ){
161144  int **aaSorted;
161145  int *aSpare;
161146  int ii;
161147 
161148  int iBestDim = 0;
161149  int iBestSplit = 0;
161150  RtreeDValue fBestMargin = RTREE_ZERO;
161151 
161152  int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
161153 
161154  aaSorted = (int **)sqlite3_malloc(nByte);
161155  if( !aaSorted ){
161156  return SQLITE_NOMEM;
161157  }
161158 
161159  aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
161160  memset(aaSorted, 0, nByte);
161161  for(ii=0; ii<pRtree->nDim; ii++){
161162  int jj;
161163  aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
161164  for(jj=0; jj<nCell; jj++){
161165  aaSorted[ii][jj] = jj;
161166  }
161167  SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
161168  }
161169 
161170  for(ii=0; ii<pRtree->nDim; ii++){
161171  RtreeDValue margin = RTREE_ZERO;
161172  RtreeDValue fBestOverlap = RTREE_ZERO;
161173  RtreeDValue fBestArea = RTREE_ZERO;
161174  int iBestLeft = 0;
161175  int nLeft;
161176 
161177  for(
161178  nLeft=RTREE_MINCELLS(pRtree);
161179  nLeft<=(nCell-RTREE_MINCELLS(pRtree));
161180  nLeft++
161181  ){
161182  RtreeCell left;
161183  RtreeCell right;
161184  int kk;
161185  RtreeDValue overlap;
161186  RtreeDValue area;
161187 
161188  memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
161189  memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
161190  for(kk=1; kk<(nCell-1); kk++){
161191  if( kk<nLeft ){
161192  cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
161193  }else{
161194  cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
161195  }
161196  }
161197  margin += cellMargin(pRtree, &left);
161198  margin += cellMargin(pRtree, &right);
161199  overlap = cellOverlap(pRtree, &left, &right, 1);
161200  area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
161201  if( (nLeft==RTREE_MINCELLS(pRtree))
161202  || (overlap<fBestOverlap)
161203  || (overlap==fBestOverlap && area<fBestArea)
161204  ){
161205  iBestLeft = nLeft;
161206  fBestOverlap = overlap;
161207  fBestArea = area;
161208  }
161209  }
161210 
161211  if( ii==0 || margin<fBestMargin ){
161212  iBestDim = ii;
161213  fBestMargin = margin;
161214  iBestSplit = iBestLeft;
161215  }
161216  }
161217 
161218  memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
161219  memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
161220  for(ii=0; ii<nCell; ii++){
161221  RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
161222  RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
161223  RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
161224  nodeInsertCell(pRtree, pTarget, pCell);
161225  cellUnion(pRtree, pBbox, pCell);
161226  }
161227 
161228  sqlite3_free(aaSorted);
161229  return SQLITE_OK;
161230 }
161231 
161232 
161233 static int updateMapping(
161234  Rtree *pRtree,
161235  i64 iRowid,
161236  RtreeNode *pNode,
161237  int iHeight
161238 ){
161239  int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
161240  xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
161241  if( iHeight>0 ){
161242  RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
161243  if( pChild ){
161244  nodeRelease(pRtree, pChild->pParent);
161245  nodeReference(pNode);
161246  pChild->pParent = pNode;
161247  }
161248  }
161249  return xSetMapping(pRtree, iRowid, pNode->iNode);
161250 }
161251 
161252 static int SplitNode(
161253  Rtree *pRtree,
161254  RtreeNode *pNode,
161255  RtreeCell *pCell,
161256  int iHeight
161257 ){
161258  int i;
161259  int newCellIsRight = 0;
161260 
161261  int rc = SQLITE_OK;
161262  int nCell = NCELL(pNode);
161263  RtreeCell *aCell;
161264  int *aiUsed;
161265 
161266  RtreeNode *pLeft = 0;
161267  RtreeNode *pRight = 0;
161268 
161269  RtreeCell leftbbox;
161270  RtreeCell rightbbox;
161271 
161272  /* Allocate an array and populate it with a copy of pCell and
161273  ** all cells from node pLeft. Then zero the original node.
161274  */
161275  aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
161276  if( !aCell ){
161277  rc = SQLITE_NOMEM;
161278  goto splitnode_out;
161279  }
161280  aiUsed = (int *)&aCell[nCell+1];
161281  memset(aiUsed, 0, sizeof(int)*(nCell+1));
161282  for(i=0; i<nCell; i++){
161283  nodeGetCell(pRtree, pNode, i, &aCell[i]);
161284  }
161285  nodeZero(pRtree, pNode);
161286  memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
161287  nCell++;
161288 
161289  if( pNode->iNode==1 ){
161290  pRight = nodeNew(pRtree, pNode);
161291  pLeft = nodeNew(pRtree, pNode);
161292  pRtree->iDepth++;
161293  pNode->isDirty = 1;
161294  writeInt16(pNode->zData, pRtree->iDepth);
161295  }else{
161296  pLeft = pNode;
161297  pRight = nodeNew(pRtree, pLeft->pParent);
161298  nodeReference(pLeft);
161299  }
161300 
161301  if( !pLeft || !pRight ){
161302  rc = SQLITE_NOMEM;
161303  goto splitnode_out;
161304  }
161305 
161306  memset(pLeft->zData, 0, pRtree->iNodeSize);
161307  memset(pRight->zData, 0, pRtree->iNodeSize);
161308 
161309  rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
161310  &leftbbox, &rightbbox);
161311  if( rc!=SQLITE_OK ){
161312  goto splitnode_out;
161313  }
161314 
161315  /* Ensure both child nodes have node numbers assigned to them by calling
161316  ** nodeWrite(). Node pRight always needs a node number, as it was created
161317  ** by nodeNew() above. But node pLeft sometimes already has a node number.
161318  ** In this case avoid the all to nodeWrite().
161319  */
161320  if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
161321  || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
161322  ){
161323  goto splitnode_out;
161324  }
161325 
161326  rightbbox.iRowid = pRight->iNode;
161327  leftbbox.iRowid = pLeft->iNode;
161328 
161329  if( pNode->iNode==1 ){
161330  rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
161331  if( rc!=SQLITE_OK ){
161332  goto splitnode_out;
161333  }
161334  }else{
161335  RtreeNode *pParent = pLeft->pParent;
161336  int iCell;
161337  rc = nodeParentIndex(pRtree, pLeft, &iCell);
161338  if( rc==SQLITE_OK ){
161339  nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
161340  rc = AdjustTree(pRtree, pParent, &leftbbox);
161341  }
161342  if( rc!=SQLITE_OK ){
161343  goto splitnode_out;
161344  }
161345  }
161346  if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
161347  goto splitnode_out;
161348  }
161349 
161350  for(i=0; i<NCELL(pRight); i++){
161351  i64 iRowid = nodeGetRowid(pRtree, pRight, i);
161352  rc = updateMapping(pRtree, iRowid, pRight, iHeight);
161353  if( iRowid==pCell->iRowid ){
161354  newCellIsRight = 1;
161355  }
161356  if( rc!=SQLITE_OK ){
161357  goto splitnode_out;
161358  }
161359  }
161360  if( pNode->iNode==1 ){
161361  for(i=0; i<NCELL(pLeft); i++){
161362  i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
161363  rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
161364  if( rc!=SQLITE_OK ){
161365  goto splitnode_out;
161366  }
161367  }
161368  }else if( newCellIsRight==0 ){
161369  rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
161370  }
161371 
161372  if( rc==SQLITE_OK ){
161373  rc = nodeRelease(pRtree, pRight);
161374  pRight = 0;
161375  }
161376  if( rc==SQLITE_OK ){
161377  rc = nodeRelease(pRtree, pLeft);
161378  pLeft = 0;
161379  }
161380 
161381 splitnode_out:
161382  nodeRelease(pRtree, pRight);
161383  nodeRelease(pRtree, pLeft);
161384  sqlite3_free(aCell);
161385  return rc;
161386 }
161387 
161388 /*
161389 ** If node pLeaf is not the root of the r-tree and its pParent pointer is
161390 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
161391 ** the pLeaf->pParent chain all the way up to the root node.
161392 **
161393 ** This operation is required when a row is deleted (or updated - an update
161394 ** is implemented as a delete followed by an insert). SQLite provides the
161395 ** rowid of the row to delete, which can be used to find the leaf on which
161396 ** the entry resides (argument pLeaf). Once the leaf is located, this
161397 ** function is called to determine its ancestry.
161398 */
161399 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
161400  int rc = SQLITE_OK;
161401  RtreeNode *pChild = pLeaf;
161402  while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
161403  int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
161404  sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
161405  rc = sqlite3_step(pRtree->pReadParent);
161406  if( rc==SQLITE_ROW ){
161407  RtreeNode *pTest; /* Used to test for reference loops */
161408  i64 iNode; /* Node number of parent node */
161409 
161410  /* Before setting pChild->pParent, test that we are not creating a
161411  ** loop of references (as we would if, say, pChild==pParent). We don't
161412  ** want to do this as it leads to a memory leak when trying to delete
161413  ** the referenced counted node structures.
161414  */
161415  iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
161416  for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
161417  if( !pTest ){
161418  rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
161419  }
161420  }
161421  rc = sqlite3_reset(pRtree->pReadParent);
161422  if( rc==SQLITE_OK ) rc = rc2;
161423  if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
161424  pChild = pChild->pParent;
161425  }
161426  return rc;
161427 }
161428 
161429 static int deleteCell(Rtree *, RtreeNode *, int, int);
161430 
161431 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
161432  int rc;
161433  int rc2;
161434  RtreeNode *pParent = 0;
161435  int iCell;
161436 
161437  assert( pNode->nRef==1 );
161438 
161439  /* Remove the entry in the parent cell. */
161440  rc = nodeParentIndex(pRtree, pNode, &iCell);
161441  if( rc==SQLITE_OK ){
161442  pParent = pNode->pParent;
161443  pNode->pParent = 0;
161444  rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
161445  }
161446  rc2 = nodeRelease(pRtree, pParent);
161447  if( rc==SQLITE_OK ){
161448  rc = rc2;
161449  }
161450  if( rc!=SQLITE_OK ){
161451  return rc;
161452  }
161453 
161454  /* Remove the xxx_node entry. */
161455  sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
161456  sqlite3_step(pRtree->pDeleteNode);
161457  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
161458  return rc;
161459  }
161460 
161461  /* Remove the xxx_parent entry. */
161462  sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
161463  sqlite3_step(pRtree->pDeleteParent);
161464  if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
161465  return rc;
161466  }
161467 
161468  /* Remove the node from the in-memory hash table and link it into
161469  ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
161470  */
161471  nodeHashDelete(pRtree, pNode);
161472  pNode->iNode = iHeight;
161473  pNode->pNext = pRtree->pDeleted;
161474  pNode->nRef++;
161475  pRtree->pDeleted = pNode;
161476 
161477  return SQLITE_OK;
161478 }
161479 
161480 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
161481  RtreeNode *pParent = pNode->pParent;
161482  int rc = SQLITE_OK;
161483  if( pParent ){
161484  int ii;
161485  int nCell = NCELL(pNode);
161486  RtreeCell box; /* Bounding box for pNode */
161487  nodeGetCell(pRtree, pNode, 0, &box);
161488  for(ii=1; ii<nCell; ii++){
161489  RtreeCell cell;
161490  nodeGetCell(pRtree, pNode, ii, &cell);
161491  cellUnion(pRtree, &box, &cell);
161492  }
161493  box.iRowid = pNode->iNode;
161494  rc = nodeParentIndex(pRtree, pNode, &ii);
161495  if( rc==SQLITE_OK ){
161496  nodeOverwriteCell(pRtree, pParent, &box, ii);
161497  rc = fixBoundingBox(pRtree, pParent);
161498  }
161499  }
161500  return rc;
161501 }
161502 
161503 /*
161504 ** Delete the cell at index iCell of node pNode. After removing the
161505 ** cell, adjust the r-tree data structure if required.
161506 */
161507 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
161508  RtreeNode *pParent;
161509  int rc;
161510 
161511  if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
161512  return rc;
161513  }
161514 
161515  /* Remove the cell from the node. This call just moves bytes around
161516  ** the in-memory node image, so it cannot fail.
161517  */
161518  nodeDeleteCell(pRtree, pNode, iCell);
161519 
161520  /* If the node is not the tree root and now has less than the minimum
161521  ** number of cells, remove it from the tree. Otherwise, update the
161522  ** cell in the parent node so that it tightly contains the updated
161523  ** node.
161524  */
161525  pParent = pNode->pParent;
161526  assert( pParent || pNode->iNode==1 );
161527  if( pParent ){
161528  if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
161529  rc = removeNode(pRtree, pNode, iHeight);
161530  }else{
161531  rc = fixBoundingBox(pRtree, pNode);
161532  }
161533  }
161534 
161535  return rc;
161536 }
161537 
161538 static int Reinsert(
161539  Rtree *pRtree,
161540  RtreeNode *pNode,
161541  RtreeCell *pCell,
161542  int iHeight
161543 ){
161544  int *aOrder;
161545  int *aSpare;
161546  RtreeCell *aCell;
161547  RtreeDValue *aDistance;
161548  int nCell;
161549  RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
161550  int iDim;
161551  int ii;
161552  int rc = SQLITE_OK;
161553  int n;
161554 
161555  memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
161556 
161557  nCell = NCELL(pNode)+1;
161558  n = (nCell+1)&(~1);
161559 
161560  /* Allocate the buffers used by this operation. The allocation is
161561  ** relinquished before this function returns.
161562  */
161563  aCell = (RtreeCell *)sqlite3_malloc(n * (
161564  sizeof(RtreeCell) + /* aCell array */
161565  sizeof(int) + /* aOrder array */
161566  sizeof(int) + /* aSpare array */
161567  sizeof(RtreeDValue) /* aDistance array */
161568  ));
161569  if( !aCell ){
161570  return SQLITE_NOMEM;
161571  }
161572  aOrder = (int *)&aCell[n];
161573  aSpare = (int *)&aOrder[n];
161574  aDistance = (RtreeDValue *)&aSpare[n];
161575 
161576  for(ii=0; ii<nCell; ii++){
161577  if( ii==(nCell-1) ){
161578  memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
161579  }else{
161580  nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
161581  }
161582  aOrder[ii] = ii;
161583  for(iDim=0; iDim<pRtree->nDim; iDim++){
161584  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
161585  aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
161586  }
161587  }
161588  for(iDim=0; iDim<pRtree->nDim; iDim++){
161589  aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
161590  }
161591 
161592  for(ii=0; ii<nCell; ii++){
161593  aDistance[ii] = RTREE_ZERO;
161594  for(iDim=0; iDim<pRtree->nDim; iDim++){
161595  RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
161596  DCOORD(aCell[ii].aCoord[iDim*2]));
161597  aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
161598  }
161599  }
161600 
161601  SortByDistance(aOrder, nCell, aDistance, aSpare);
161602  nodeZero(pRtree, pNode);
161603 
161604  for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
161605  RtreeCell *p = &aCell[aOrder[ii]];
161606  nodeInsertCell(pRtree, pNode, p);
161607  if( p->iRowid==pCell->iRowid ){
161608  if( iHeight==0 ){
161609  rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
161610  }else{
161611  rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
161612  }
161613  }
161614  }
161615  if( rc==SQLITE_OK ){
161616  rc = fixBoundingBox(pRtree, pNode);
161617  }
161618  for(; rc==SQLITE_OK && ii<nCell; ii++){
161619  /* Find a node to store this cell in. pNode->iNode currently contains
161620  ** the height of the sub-tree headed by the cell.
161621  */
161622  RtreeNode *pInsert;
161623  RtreeCell *p = &aCell[aOrder[ii]];
161624  rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
161625  if( rc==SQLITE_OK ){
161626  int rc2;
161627  rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
161628  rc2 = nodeRelease(pRtree, pInsert);
161629  if( rc==SQLITE_OK ){
161630  rc = rc2;
161631  }
161632  }
161633  }
161634 
161635  sqlite3_free(aCell);
161636  return rc;
161637 }
161638 
161639 /*
161640 ** Insert cell pCell into node pNode. Node pNode is the head of a
161641 ** subtree iHeight high (leaf nodes have iHeight==0).
161642 */
161643 static int rtreeInsertCell(
161644  Rtree *pRtree,
161645  RtreeNode *pNode,
161646  RtreeCell *pCell,
161647  int iHeight
161648 ){
161649  int rc = SQLITE_OK;
161650  if( iHeight>0 ){
161651  RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
161652  if( pChild ){
161653  nodeRelease(pRtree, pChild->pParent);
161654  nodeReference(pNode);
161655  pChild->pParent = pNode;
161656  }
161657  }
161658  if( nodeInsertCell(pRtree, pNode, pCell) ){
161659  if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
161660  rc = SplitNode(pRtree, pNode, pCell, iHeight);
161661  }else{
161662  pRtree->iReinsertHeight = iHeight;
161663  rc = Reinsert(pRtree, pNode, pCell, iHeight);
161664  }
161665  }else{
161666  rc = AdjustTree(pRtree, pNode, pCell);
161667  if( rc==SQLITE_OK ){
161668  if( iHeight==0 ){
161669  rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
161670  }else{
161671  rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
161672  }
161673  }
161674  }
161675  return rc;
161676 }
161677 
161678 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
161679  int ii;
161680  int rc = SQLITE_OK;
161681  int nCell = NCELL(pNode);
161682 
161683  for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
161684  RtreeNode *pInsert;
161685  RtreeCell cell;
161686  nodeGetCell(pRtree, pNode, ii, &cell);
161687 
161688  /* Find a node to store this cell in. pNode->iNode currently contains
161689  ** the height of the sub-tree headed by the cell.
161690  */
161691  rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
161692  if( rc==SQLITE_OK ){
161693  int rc2;
161694  rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
161695  rc2 = nodeRelease(pRtree, pInsert);
161696  if( rc==SQLITE_OK ){
161697  rc = rc2;
161698  }
161699  }
161700  }
161701  return rc;
161702 }
161703 
161704 /*
161705 ** Select a currently unused rowid for a new r-tree record.
161706 */
161707 static int newRowid(Rtree *pRtree, i64 *piRowid){
161708  int rc;
161709  sqlite3_bind_null(pRtree->pWriteRowid, 1);
161710  sqlite3_bind_null(pRtree->pWriteRowid, 2);
161711  sqlite3_step(pRtree->pWriteRowid);
161712  rc = sqlite3_reset(pRtree->pWriteRowid);
161713  *piRowid = sqlite3_last_insert_rowid(pRtree->db);
161714  return rc;
161715 }
161716 
161717 /*
161718 ** Remove the entry with rowid=iDelete from the r-tree structure.
161719 */
161720 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
161721  int rc; /* Return code */
161722  RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
161723  int iCell; /* Index of iDelete cell in pLeaf */
161724  RtreeNode *pRoot; /* Root node of rtree structure */
161725 
161726 
161727  /* Obtain a reference to the root node to initialize Rtree.iDepth */
161728  rc = nodeAcquire(pRtree, 1, 0, &pRoot);
161729 
161730  /* Obtain a reference to the leaf node that contains the entry
161731  ** about to be deleted.
161732  */
161733  if( rc==SQLITE_OK ){
161734  rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
161735  }
161736 
161737  /* Delete the cell in question from the leaf node. */
161738  if( rc==SQLITE_OK ){
161739  int rc2;
161740  rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
161741  if( rc==SQLITE_OK ){
161742  rc = deleteCell(pRtree, pLeaf, iCell, 0);
161743  }
161744  rc2 = nodeRelease(pRtree, pLeaf);
161745  if( rc==SQLITE_OK ){
161746  rc = rc2;
161747  }
161748  }
161749 
161750  /* Delete the corresponding entry in the <rtree>_rowid table. */
161751  if( rc==SQLITE_OK ){
161752  sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
161753  sqlite3_step(pRtree->pDeleteRowid);
161754  rc = sqlite3_reset(pRtree->pDeleteRowid);
161755  }
161756 
161757  /* Check if the root node now has exactly one child. If so, remove
161758  ** it, schedule the contents of the child for reinsertion and
161759  ** reduce the tree height by one.
161760  **
161761  ** This is equivalent to copying the contents of the child into
161762  ** the root node (the operation that Gutman's paper says to perform
161763  ** in this scenario).
161764  */
161765  if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
161766  int rc2;
161767  RtreeNode *pChild;
161768  i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
161769  rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
161770  if( rc==SQLITE_OK ){
161771  rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
161772  }
161773  rc2 = nodeRelease(pRtree, pChild);
161774  if( rc==SQLITE_OK ) rc = rc2;
161775  if( rc==SQLITE_OK ){
161776  pRtree->iDepth--;
161777  writeInt16(pRoot->zData, pRtree->iDepth);
161778  pRoot->isDirty = 1;
161779  }
161780  }
161781 
161782  /* Re-insert the contents of any underfull nodes removed from the tree. */
161783  for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
161784  if( rc==SQLITE_OK ){
161785  rc = reinsertNodeContent(pRtree, pLeaf);
161786  }
161787  pRtree->pDeleted = pLeaf->pNext;
161788  sqlite3_free(pLeaf);
161789  }
161790 
161791  /* Release the reference to the root node. */
161792  if( rc==SQLITE_OK ){
161793  rc = nodeRelease(pRtree, pRoot);
161794  }else{
161795  nodeRelease(pRtree, pRoot);
161796  }
161797 
161798  return rc;
161799 }
161800 
161801 /*
161802 ** Rounding constants for float->double conversion.
161803 */
161804 #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
161805 #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
161806 
161807 #if !defined(SQLITE_RTREE_INT_ONLY)
161808 /*
161809 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
161810 ** while taking care to round toward negative or positive, respectively.
161811 */
161812 static RtreeValue rtreeValueDown(sqlite3_value *v){
161813  double d = sqlite3_value_double(v);
161814  float f = (float)d;
161815  if( f>d ){
161816  f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
161817  }
161818  return f;
161819 }
161820 static RtreeValue rtreeValueUp(sqlite3_value *v){
161821  double d = sqlite3_value_double(v);
161822  float f = (float)d;
161823  if( f<d ){
161824  f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
161825  }
161826  return f;
161827 }
161828 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
161829 
161830 
161831 /*
161832 ** The xUpdate method for rtree module virtual tables.
161833 */
161834 static int rtreeUpdate(
161835  sqlite3_vtab *pVtab,
161836  int nData,
161837  sqlite3_value **azData,
161838  sqlite_int64 *pRowid
161839 ){
161840  Rtree *pRtree = (Rtree *)pVtab;
161841  int rc = SQLITE_OK;
161842  RtreeCell cell; /* New cell to insert if nData>1 */
161843  int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
161844 
161845  rtreeReference(pRtree);
161846  assert(nData>=1);
161847 
161848  cell.iRowid = 0; /* Used only to suppress a compiler warning */
161849 
161850  /* Constraint handling. A write operation on an r-tree table may return
161851  ** SQLITE_CONSTRAINT for two reasons:
161852  **
161853  ** 1. A duplicate rowid value, or
161854  ** 2. The supplied data violates the "x2>=x1" constraint.
161855  **
161856  ** In the first case, if the conflict-handling mode is REPLACE, then
161857  ** the conflicting row can be removed before proceeding. In the second
161858  ** case, SQLITE_CONSTRAINT must be returned regardless of the
161859  ** conflict-handling mode specified by the user.
161860  */
161861  if( nData>1 ){
161862  int ii;
161863 
161864  /* Populate the cell.aCoord[] array. The first coordinate is azData[3].
161865  **
161866  ** NB: nData can only be less than nDim*2+3 if the rtree is mis-declared
161867  ** with "column" that are interpreted as table constraints.
161868  ** Example: CREATE VIRTUAL TABLE bad USING rtree(x,y,CHECK(y>5));
161869  ** This problem was discovered after years of use, so we silently ignore
161870  ** these kinds of misdeclared tables to avoid breaking any legacy.
161871  */
161872  assert( nData<=(pRtree->nDim*2 + 3) );
161873 
161874 #ifndef SQLITE_RTREE_INT_ONLY
161875  if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
161876  for(ii=0; ii<nData-4; ii+=2){
161877  cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
161878  cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
161879  if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
161880  rc = SQLITE_CONSTRAINT;
161881  goto constraint;
161882  }
161883  }
161884  }else
161885 #endif
161886  {
161887  for(ii=0; ii<nData-4; ii+=2){
161888  cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
161889  cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
161890  if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
161891  rc = SQLITE_CONSTRAINT;
161892  goto constraint;
161893  }
161894  }
161895  }
161896 
161897  /* If a rowid value was supplied, check if it is already present in
161898  ** the table. If so, the constraint has failed. */
161899  if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
161900  cell.iRowid = sqlite3_value_int64(azData[2]);
161901  if( sqlite3_value_type(azData[0])==SQLITE_NULL
161902  || sqlite3_value_int64(azData[0])!=cell.iRowid
161903  ){
161904  int steprc;
161905  sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
161906  steprc = sqlite3_step(pRtree->pReadRowid);
161907  rc = sqlite3_reset(pRtree->pReadRowid);
161908  if( SQLITE_ROW==steprc ){
161909  if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
161910  rc = rtreeDeleteRowid(pRtree, cell.iRowid);
161911  }else{
161912  rc = SQLITE_CONSTRAINT;
161913  goto constraint;
161914  }
161915  }
161916  }
161917  bHaveRowid = 1;
161918  }
161919  }
161920 
161921  /* If azData[0] is not an SQL NULL value, it is the rowid of a
161922  ** record to delete from the r-tree table. The following block does
161923  ** just that.
161924  */
161925  if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
161926  rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
161927  }
161928 
161929  /* If the azData[] array contains more than one element, elements
161930  ** (azData[2]..azData[argc-1]) contain a new record to insert into
161931  ** the r-tree structure.
161932  */
161933  if( rc==SQLITE_OK && nData>1 ){
161934  /* Insert the new record into the r-tree */
161935  RtreeNode *pLeaf = 0;
161936 
161937  /* Figure out the rowid of the new row. */
161938  if( bHaveRowid==0 ){
161939  rc = newRowid(pRtree, &cell.iRowid);
161940  }
161941  *pRowid = cell.iRowid;
161942 
161943  if( rc==SQLITE_OK ){
161944  rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
161945  }
161946  if( rc==SQLITE_OK ){
161947  int rc2;
161948  pRtree->iReinsertHeight = -1;
161949  rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
161950  rc2 = nodeRelease(pRtree, pLeaf);
161951  if( rc==SQLITE_OK ){
161952  rc = rc2;
161953  }
161954  }
161955  }
161956 
161957 constraint:
161958  rtreeRelease(pRtree);
161959  return rc;
161960 }
161961 
161962 /*
161963 ** The xRename method for rtree module virtual tables.
161964 */
161965 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
161966  Rtree *pRtree = (Rtree *)pVtab;
161967  int rc = SQLITE_NOMEM;
161968  char *zSql = sqlite3_mprintf(
161969  "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
161970  "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
161971  "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
161972  , pRtree->zDb, pRtree->zName, zNewName
161973  , pRtree->zDb, pRtree->zName, zNewName
161974  , pRtree->zDb, pRtree->zName, zNewName
161975  );
161976  if( zSql ){
161977  rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
161978  sqlite3_free(zSql);
161979  }
161980  return rc;
161981 }
161982 
161983 /*
161984 ** This function populates the pRtree->nRowEst variable with an estimate
161985 ** of the number of rows in the virtual table. If possible, this is based
161986 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
161987 */
161988 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
161989  const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
161990  char *zSql;
161991  sqlite3_stmt *p;
161992  int rc;
161993  i64 nRow = 0;
161994 
161995  zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
161996  if( zSql==0 ){
161997  rc = SQLITE_NOMEM;
161998  }else{
161999  rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
162000  if( rc==SQLITE_OK ){
162001  if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
162002  rc = sqlite3_finalize(p);
162003  }else if( rc!=SQLITE_NOMEM ){
162004  rc = SQLITE_OK;
162005  }
162006 
162007  if( rc==SQLITE_OK ){
162008  if( nRow==0 ){
162009  pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
162010  }else{
162011  pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
162012  }
162013  }
162014  sqlite3_free(zSql);
162015  }
162016 
162017  return rc;
162018 }
162019 
162020 static sqlite3_module rtreeModule = {
162021  0, /* iVersion */
162022  rtreeCreate, /* xCreate - create a table */
162023  rtreeConnect, /* xConnect - connect to an existing table */
162024  rtreeBestIndex, /* xBestIndex - Determine search strategy */
162025  rtreeDisconnect, /* xDisconnect - Disconnect from a table */
162026  rtreeDestroy, /* xDestroy - Drop a table */
162027  rtreeOpen, /* xOpen - open a cursor */
162028  rtreeClose, /* xClose - close a cursor */
162029  rtreeFilter, /* xFilter - configure scan constraints */
162030  rtreeNext, /* xNext - advance a cursor */
162031  rtreeEof, /* xEof */
162032  rtreeColumn, /* xColumn - read data */
162033  rtreeRowid, /* xRowid - read data */
162034  rtreeUpdate, /* xUpdate - write data */
162035  0, /* xBegin - begin transaction */
162036  0, /* xSync - sync transaction */
162037  0, /* xCommit - commit transaction */
162038  0, /* xRollback - rollback transaction */
162039  0, /* xFindFunction - function overloading */
162040  rtreeRename, /* xRename - rename the table */
162041  0, /* xSavepoint */
162042  0, /* xRelease */
162043  0 /* xRollbackTo */
162044 };
162045 
162046 static int rtreeSqlInit(
162047  Rtree *pRtree,
162048  sqlite3 *db,
162049  const char *zDb,
162050  const char *zPrefix,
162051  int isCreate
162052 ){
162053  int rc = SQLITE_OK;
162054 
162055  #define N_STATEMENT 9
162056  static const char *azSql[N_STATEMENT] = {
162057  /* Read and write the xxx_node table */
162058  "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
162059  "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
162060  "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
162061 
162062  /* Read and write the xxx_rowid table */
162063  "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
162064  "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
162065  "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
162066 
162067  /* Read and write the xxx_parent table */
162068  "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
162069  "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
162070  "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
162071  };
162072  sqlite3_stmt **appStmt[N_STATEMENT];
162073  int i;
162074 
162075  pRtree->db = db;
162076 
162077  if( isCreate ){
162078  char *zCreate = sqlite3_mprintf(
162079 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
162080 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
162081 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
162082  " parentnode INTEGER);"
162083 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
162084  zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
162085  );
162086  if( !zCreate ){
162087  return SQLITE_NOMEM;
162088  }
162089  rc = sqlite3_exec(db, zCreate, 0, 0, 0);
162090  sqlite3_free(zCreate);
162091  if( rc!=SQLITE_OK ){
162092  return rc;
162093  }
162094  }
162095 
162096  appStmt[0] = &pRtree->pReadNode;
162097  appStmt[1] = &pRtree->pWriteNode;
162098  appStmt[2] = &pRtree->pDeleteNode;
162099  appStmt[3] = &pRtree->pReadRowid;
162100  appStmt[4] = &pRtree->pWriteRowid;
162101  appStmt[5] = &pRtree->pDeleteRowid;
162102  appStmt[6] = &pRtree->pReadParent;
162103  appStmt[7] = &pRtree->pWriteParent;
162104  appStmt[8] = &pRtree->pDeleteParent;
162105 
162106  rc = rtreeQueryStat1(db, pRtree);
162107  for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
162108  char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
162109  if( zSql ){
162110  rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
162111  }else{
162112  rc = SQLITE_NOMEM;
162113  }
162114  sqlite3_free(zSql);
162115  }
162116 
162117  return rc;
162118 }
162119 
162120 /*
162121 ** The second argument to this function contains the text of an SQL statement
162122 ** that returns a single integer value. The statement is compiled and executed
162123 ** using database connection db. If successful, the integer value returned
162124 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
162125 ** code is returned and the value of *piVal after returning is not defined.
162126 */
162127 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
162128  int rc = SQLITE_NOMEM;
162129  if( zSql ){
162130  sqlite3_stmt *pStmt = 0;
162131  rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
162132  if( rc==SQLITE_OK ){
162133  if( SQLITE_ROW==sqlite3_step(pStmt) ){
162134  *piVal = sqlite3_column_int(pStmt, 0);
162135  }
162136  rc = sqlite3_finalize(pStmt);
162137  }
162138  }
162139  return rc;
162140 }
162141 
162142 /*
162143 ** This function is called from within the xConnect() or xCreate() method to
162144 ** determine the node-size used by the rtree table being created or connected
162145 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
162146 ** Otherwise, an SQLite error code is returned.
162147 **
162148 ** If this function is being called as part of an xConnect(), then the rtree
162149 ** table already exists. In this case the node-size is determined by inspecting
162150 ** the root node of the tree.
162151 **
162152 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
162153 ** This ensures that each node is stored on a single database page. If the
162154 ** database page-size is so large that more than RTREE_MAXCELLS entries
162155 ** would fit in a single node, use a smaller node-size.
162156 */
162157 static int getNodeSize(
162158  sqlite3 *db, /* Database handle */
162159  Rtree *pRtree, /* Rtree handle */
162160  int isCreate, /* True for xCreate, false for xConnect */
162161  char **pzErr /* OUT: Error message, if any */
162162 ){
162163  int rc;
162164  char *zSql;
162165  if( isCreate ){
162166  int iPageSize = 0;
162167  zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
162168  rc = getIntFromStmt(db, zSql, &iPageSize);
162169  if( rc==SQLITE_OK ){
162170  pRtree->iNodeSize = iPageSize-64;
162171  if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
162172  pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
162173  }
162174  }else{
162175  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
162176  }
162177  }else{
162178  zSql = sqlite3_mprintf(
162179  "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
162180  pRtree->zDb, pRtree->zName
162181  );
162182  rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
162183  if( rc!=SQLITE_OK ){
162184  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
162185  }
162186  }
162187 
162188  sqlite3_free(zSql);
162189  return rc;
162190 }
162191 
162192 /*
162193 ** This function is the implementation of both the xConnect and xCreate
162194 ** methods of the r-tree virtual table.
162195 **
162196 ** argv[0] -> module name
162197 ** argv[1] -> database name
162198 ** argv[2] -> table name
162199 ** argv[...] -> column names...
162200 */
162201 static int rtreeInit(
162202  sqlite3 *db, /* Database connection */
162203  void *pAux, /* One of the RTREE_COORD_* constants */
162204  int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
162205  sqlite3_vtab **ppVtab, /* OUT: New virtual table */
162206  char **pzErr, /* OUT: Error message, if any */
162207  int isCreate /* True for xCreate, false for xConnect */
162208 ){
162209  int rc = SQLITE_OK;
162210  Rtree *pRtree;
162211  int nDb; /* Length of string argv[1] */
162212  int nName; /* Length of string argv[2] */
162213  int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
162214 
162215  const char *aErrMsg[] = {
162216  0, /* 0 */
162217  "Wrong number of columns for an rtree table", /* 1 */
162218  "Too few columns for an rtree table", /* 2 */
162219  "Too many columns for an rtree table" /* 3 */
162220  };
162221 
162222  int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
162223  if( aErrMsg[iErr] ){
162224  *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
162225  return SQLITE_ERROR;
162226  }
162227 
162229 
162230  /* Allocate the sqlite3_vtab structure */
162231  nDb = (int)strlen(argv[1]);
162232  nName = (int)strlen(argv[2]);
162233  pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
162234  if( !pRtree ){
162235  return SQLITE_NOMEM;
162236  }
162237  memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
162238  pRtree->nBusy = 1;
162239  pRtree->base.pModule = &rtreeModule;
162240  pRtree->zDb = (char *)&pRtree[1];
162241  pRtree->zName = &pRtree->zDb[nDb+1];
162242  pRtree->nDim = (argc-4)/2;
162243  pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
162244  pRtree->eCoordType = eCoordType;
162245  memcpy(pRtree->zDb, argv[1], nDb);
162246  memcpy(pRtree->zName, argv[2], nName);
162247 
162248  /* Figure out the node size to use. */
162249  rc = getNodeSize(db, pRtree, isCreate, pzErr);
162250 
162251  /* Create/Connect to the underlying relational database schema. If
162252  ** that is successful, call sqlite3_declare_vtab() to configure
162253  ** the r-tree table schema.
162254  */
162255  if( rc==SQLITE_OK ){
162256  if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
162257  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
162258  }else{
162259  char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
162260  char *zTmp;
162261  int ii;
162262  for(ii=4; zSql && ii<argc; ii++){
162263  zTmp = zSql;
162264  zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
162265  sqlite3_free(zTmp);
162266  }
162267  if( zSql ){
162268  zTmp = zSql;
162269  zSql = sqlite3_mprintf("%s);", zTmp);
162270  sqlite3_free(zTmp);
162271  }
162272  if( !zSql ){
162273  rc = SQLITE_NOMEM;
162274  }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
162275  *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
162276  }
162277  sqlite3_free(zSql);
162278  }
162279  }
162280 
162281  if( rc==SQLITE_OK ){
162282  *ppVtab = (sqlite3_vtab *)pRtree;
162283  }else{
162284  assert( *ppVtab==0 );
162285  assert( pRtree->nBusy==1 );
162286  rtreeRelease(pRtree);
162287  }
162288  return rc;
162289 }
162290 
162291 
162292 /*
162293 ** Implementation of a scalar function that decodes r-tree nodes to
162294 ** human readable strings. This can be used for debugging and analysis.
162295 **
162296 ** The scalar function takes two arguments: (1) the number of dimensions
162297 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
162298 ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
162299 ** deserialize all nodes, a statement like:
162300 **
162301 ** SELECT rtreenode(2, data) FROM rt_node;
162302 **
162303 ** The human readable string takes the form of a Tcl list with one
162304 ** entry for each cell in the r-tree node. Each entry is itself a
162305 ** list, containing the 8-byte rowid/pageno followed by the
162306 ** <num-dimension>*2 coordinates.
162307 */
162308 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
162309  char *zText = 0;
162310  RtreeNode node;
162311  Rtree tree;
162312  int ii;
162313 
162314  UNUSED_PARAMETER(nArg);
162315  memset(&node, 0, sizeof(RtreeNode));
162316  memset(&tree, 0, sizeof(Rtree));
162317  tree.nDim = sqlite3_value_int(apArg[0]);
162318  tree.nBytesPerCell = 8 + 8 * tree.nDim;
162319  node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
162320 
162321  for(ii=0; ii<NCELL(&node); ii++){
162322  char zCell[512];
162323  int nCell = 0;
162324  RtreeCell cell;
162325  int jj;
162326 
162327  nodeGetCell(&tree, &node, ii, &cell);
162328  sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
162329  nCell = (int)strlen(zCell);
162330  for(jj=0; jj<tree.nDim*2; jj++){
162331 #ifndef SQLITE_RTREE_INT_ONLY
162332  sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
162333  (double)cell.aCoord[jj].f);
162334 #else
162335  sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
162336  cell.aCoord[jj].i);
162337 #endif
162338  nCell = (int)strlen(zCell);
162339  }
162340 
162341  if( zText ){
162342  char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
162343  sqlite3_free(zText);
162344  zText = zTextNew;
162345  }else{
162346  zText = sqlite3_mprintf("{%s}", zCell);
162347  }
162348  }
162349 
162350  sqlite3_result_text(ctx, zText, -1, sqlite3_free);
162351 }
162352 
162353 /* This routine implements an SQL function that returns the "depth" parameter
162354 ** from the front of a blob that is an r-tree node. For example:
162355 **
162356 ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
162357 **
162358 ** The depth value is 0 for all nodes other than the root node, and the root
162359 ** node always has nodeno=1, so the example above is the primary use for this
162360 ** routine. This routine is intended for testing and analysis only.
162361 */
162362 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
162363  UNUSED_PARAMETER(nArg);
162364  if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
162365  || sqlite3_value_bytes(apArg[0])<2
162366  ){
162367  sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
162368  }else{
162369  u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
162370  sqlite3_result_int(ctx, readInt16(zBlob));
162371  }
162372 }
162373 
162374 /*
162375 ** Register the r-tree module with database handle db. This creates the
162376 ** virtual table module "rtree" and the debugging/analysis scalar
162377 ** function "rtreenode".
162378 */
162379 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
162380  const int utf8 = SQLITE_UTF8;
162381  int rc;
162382 
162383  rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
162384  if( rc==SQLITE_OK ){
162385  rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
162386  }
162387  if( rc==SQLITE_OK ){
162388 #ifdef SQLITE_RTREE_INT_ONLY
162389  void *c = (void *)RTREE_COORD_INT32;
162390 #else
162391  void *c = (void *)RTREE_COORD_REAL32;
162392 #endif
162393  rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
162394  }
162395  if( rc==SQLITE_OK ){
162396  void *c = (void *)RTREE_COORD_INT32;
162397  rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
162398  }
162399 
162400  return rc;
162401 }
162402 
162403 /*
162404 ** This routine deletes the RtreeGeomCallback object that was attached
162405 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
162406 ** or sqlite3_rtree_query_callback(). In other words, this routine is the
162407 ** destructor for an RtreeGeomCallback objecct. This routine is called when
162408 ** the corresponding SQL function is deleted.
162409 */
162410 static void rtreeFreeCallback(void *p){
162411  RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
162412  if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
162413  sqlite3_free(p);
162414 }
162415 
162416 /*
162417 ** This routine frees the BLOB that is returned by geomCallback().
162418 */
162419 static void rtreeMatchArgFree(void *pArg){
162420  int i;
162421  RtreeMatchArg *p = (RtreeMatchArg*)pArg;
162422  for(i=0; i<p->nParam; i++){
162423  sqlite3_value_free(p->apSqlParam[i]);
162424  }
162425  sqlite3_free(p);
162426 }
162427 
162428 /*
162429 ** Each call to sqlite3_rtree_geometry_callback() or
162430 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
162431 ** scalar function that is implemented by this routine.
162432 **
162433 ** All this function does is construct an RtreeMatchArg object that
162434 ** contains the geometry-checking callback routines and a list of
162435 ** parameters to this function, then return that RtreeMatchArg object
162436 ** as a BLOB.
162437 **
162438 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
162439 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
162440 ** out which elements of the R-Tree should be returned by the query.
162441 */
162442 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
162443  RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
162444  RtreeMatchArg *pBlob;
162445  int nBlob;
162446  int memErr = 0;
162447 
162448  nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue)
162449  + nArg*sizeof(sqlite3_value*);
162450  pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
162451  if( !pBlob ){
162453  }else{
162454  int i;
162455  pBlob->magic = RTREE_GEOMETRY_MAGIC;
162456  pBlob->cb = pGeomCtx[0];
162457  pBlob->apSqlParam = (sqlite3_value**)&pBlob->aParam[nArg];
162458  pBlob->nParam = nArg;
162459  for(i=0; i<nArg; i++){
162460  pBlob->apSqlParam[i] = sqlite3_value_dup(aArg[i]);
162461  if( pBlob->apSqlParam[i]==0 ) memErr = 1;
162462 #ifdef SQLITE_RTREE_INT_ONLY
162463  pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
162464 #else
162465  pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
162466 #endif
162467  }
162468  if( memErr ){
162470  rtreeMatchArgFree(pBlob);
162471  }else{
162472  sqlite3_result_blob(ctx, pBlob, nBlob, rtreeMatchArgFree);
162473  }
162474  }
162475 }
162476 
162477 /*
162478 ** Register a new geometry function for use with the r-tree MATCH operator.
162479 */
162481  sqlite3 *db, /* Register SQL function on this connection */
162482  const char *zGeom, /* Name of the new SQL function */
162483  int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
162484  void *pContext /* Extra data associated with the callback */
162485 ){
162486  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
162487 
162488  /* Allocate and populate the context object. */
162489  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
162490  if( !pGeomCtx ) return SQLITE_NOMEM;
162491  pGeomCtx->xGeom = xGeom;
162492  pGeomCtx->xQueryFunc = 0;
162493  pGeomCtx->xDestructor = 0;
162494  pGeomCtx->pContext = pContext;
162495  return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
162496  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
162497  );
162498 }
162499 
162500 /*
162501 ** Register a new 2nd-generation geometry function for use with the
162502 ** r-tree MATCH operator.
162503 */
162505  sqlite3 *db, /* Register SQL function on this connection */
162506  const char *zQueryFunc, /* Name of new SQL function */
162507  int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
162508  void *pContext, /* Extra data passed into the callback */
162509  void (*xDestructor)(void*) /* Destructor for the extra data */
162510 ){
162511  RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
162512 
162513  /* Allocate and populate the context object. */
162514  pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
162515  if( !pGeomCtx ) return SQLITE_NOMEM;
162516  pGeomCtx->xGeom = 0;
162517  pGeomCtx->xQueryFunc = xQueryFunc;
162518  pGeomCtx->xDestructor = xDestructor;
162519  pGeomCtx->pContext = pContext;
162520  return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
162521  (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
162522  );
162523 }
162524 
162525 #if !SQLITE_CORE
162526 #ifdef _WIN32
162527 __declspec(dllexport)
162528 #endif
162529 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
162530  sqlite3 *db,
162531  char **pzErrMsg,
162532  const sqlite3_api_routines *pApi
162533 ){
162534  SQLITE_EXTENSION_INIT2(pApi)
162535  return sqlite3RtreeInit(db);
162536 }
162537 #endif
162538 
162539 #endif
162540 
162541 /************** End of rtree.c ***********************************************/
162542 /************** Begin file icu.c *********************************************/
162543 /*
162544 ** 2007 May 6
162545 **
162546 ** The author disclaims copyright to this source code. In place of
162547 ** a legal notice, here is a blessing:
162548 **
162549 ** May you do good and not evil.
162550 ** May you find forgiveness for yourself and forgive others.
162551 ** May you share freely, never taking more than you give.
162552 **
162553 *************************************************************************
162554 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
162555 **
162556 ** This file implements an integration between the ICU library
162557 ** ("International Components for Unicode", an open-source library
162558 ** for handling unicode data) and SQLite. The integration uses
162559 ** ICU to provide the following to SQLite:
162560 **
162561 ** * An implementation of the SQL regexp() function (and hence REGEXP
162562 ** operator) using the ICU uregex_XX() APIs.
162563 **
162564 ** * Implementations of the SQL scalar upper() and lower() functions
162565 ** for case mapping.
162566 **
162567 ** * Integration of ICU and SQLite collation sequences.
162568 **
162569 ** * An implementation of the LIKE operator that uses ICU to
162570 ** provide case-independent matching.
162571 */
162572 
162573 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
162574 
162575 /* Include ICU headers */
162576 #include <unicode/utypes.h>
162577 #include <unicode/uregex.h>
162578 #include <unicode/ustring.h>
162579 #include <unicode/ucol.h>
162580 
162581 /* #include <assert.h> */
162582 
162583 #ifndef SQLITE_CORE
162584 /* #include "sqlite3ext.h" */
162586 #else
162587 /* #include "sqlite3.h" */
162588 #endif
162589 
162590 /*
162591 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
162592 ** operator.
162593 */
162594 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
162595 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
162596 #endif
162597 
162598 /*
162599 ** Version of sqlite3_free() that is always a function, never a macro.
162600 */
162601 static void xFree(void *p){
162602  sqlite3_free(p);
162603 }
162604 
162605 /*
162606 ** This lookup table is used to help decode the first byte of
162607 ** a multi-byte UTF8 character. It is copied here from SQLite source
162608 ** code file utf8.c.
162609 */
162610 static const unsigned char icuUtf8Trans1[] = {
162611  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162612  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
162613  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
162614  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
162615  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162616  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
162617  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
162618  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
162619 };
162620 
162621 #define SQLITE_ICU_READ_UTF8(zIn, c) \
162622  c = *(zIn++); \
162623  if( c>=0xc0 ){ \
162624  c = icuUtf8Trans1[c-0xc0]; \
162625  while( (*zIn & 0xc0)==0x80 ){ \
162626  c = (c<<6) + (0x3f & *(zIn++)); \
162627  } \
162628  }
162629 
162630 #define SQLITE_ICU_SKIP_UTF8(zIn) \
162631  assert( *zIn ); \
162632  if( *(zIn++)>=0xc0 ){ \
162633  while( (*zIn & 0xc0)==0x80 ){zIn++;} \
162634  }
162635 
162636 
162637 /*
162638 ** Compare two UTF-8 strings for equality where the first string is
162639 ** a "LIKE" expression. Return true (1) if they are the same and
162640 ** false (0) if they are different.
162641 */
162642 static int icuLikeCompare(
162643  const uint8_t *zPattern, /* LIKE pattern */
162644  const uint8_t *zString, /* The UTF-8 string to compare against */
162645  const UChar32 uEsc /* The escape character */
162646 ){
162647  static const int MATCH_ONE = (UChar32)'_';
162648  static const int MATCH_ALL = (UChar32)'%';
162649 
162650  int prevEscape = 0; /* True if the previous character was uEsc */
162651 
162652  while( 1 ){
162653 
162654  /* Read (and consume) the next character from the input pattern. */
162655  UChar32 uPattern;
162656  SQLITE_ICU_READ_UTF8(zPattern, uPattern);
162657  if( uPattern==0 ) break;
162658 
162659  /* There are now 4 possibilities:
162660  **
162661  ** 1. uPattern is an unescaped match-all character "%",
162662  ** 2. uPattern is an unescaped match-one character "_",
162663  ** 3. uPattern is an unescaped escape character, or
162664  ** 4. uPattern is to be handled as an ordinary character
162665  */
162666  if( !prevEscape && uPattern==MATCH_ALL ){
162667  /* Case 1. */
162668  uint8_t c;
162669 
162670  /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
162671  ** MATCH_ALL. For each MATCH_ONE, skip one character in the
162672  ** test string.
162673  */
162674  while( (c=*zPattern) == MATCH_ALL || c == MATCH_ONE ){
162675  if( c==MATCH_ONE ){
162676  if( *zString==0 ) return 0;
162677  SQLITE_ICU_SKIP_UTF8(zString);
162678  }
162679  zPattern++;
162680  }
162681 
162682  if( *zPattern==0 ) return 1;
162683 
162684  while( *zString ){
162685  if( icuLikeCompare(zPattern, zString, uEsc) ){
162686  return 1;
162687  }
162688  SQLITE_ICU_SKIP_UTF8(zString);
162689  }
162690  return 0;
162691 
162692  }else if( !prevEscape && uPattern==MATCH_ONE ){
162693  /* Case 2. */
162694  if( *zString==0 ) return 0;
162695  SQLITE_ICU_SKIP_UTF8(zString);
162696 
162697  }else if( !prevEscape && uPattern==uEsc){
162698  /* Case 3. */
162699  prevEscape = 1;
162700 
162701  }else{
162702  /* Case 4. */
162703  UChar32 uString;
162704  SQLITE_ICU_READ_UTF8(zString, uString);
162705  uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
162706  uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
162707  if( uString!=uPattern ){
162708  return 0;
162709  }
162710  prevEscape = 0;
162711  }
162712  }
162713 
162714  return *zString==0;
162715 }
162716 
162717 /*
162718 ** Implementation of the like() SQL function. This function implements
162719 ** the build-in LIKE operator. The first argument to the function is the
162720 ** pattern and the second argument is the string. So, the SQL statements:
162721 **
162722 ** A LIKE B
162723 **
162724 ** is implemented as like(B, A). If there is an escape character E,
162725 **
162726 ** A LIKE B ESCAPE E
162727 **
162728 ** is mapped to like(B, A, E).
162729 */
162730 static void icuLikeFunc(
162731  sqlite3_context *context,
162732  int argc,
162733  sqlite3_value **argv
162734 ){
162735  const unsigned char *zA = sqlite3_value_text(argv[0]);
162736  const unsigned char *zB = sqlite3_value_text(argv[1]);
162737  UChar32 uEsc = 0;
162738 
162739  /* Limit the length of the LIKE or GLOB pattern to avoid problems
162740  ** of deep recursion and N*N behavior in patternCompare().
162741  */
162743  sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
162744  return;
162745  }
162746 
162747 
162748  if( argc==3 ){
162749  /* The escape character string must consist of a single UTF-8 character.
162750  ** Otherwise, return an error.
162751  */
162752  int nE= sqlite3_value_bytes(argv[2]);
162753  const unsigned char *zE = sqlite3_value_text(argv[2]);
162754  int i = 0;
162755  if( zE==0 ) return;
162756  U8_NEXT(zE, i, nE, uEsc);
162757  if( i!=nE){
162758  sqlite3_result_error(context,
162759  "ESCAPE expression must be a single character", -1);
162760  return;
162761  }
162762  }
162763 
162764  if( zA && zB ){
162765  sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
162766  }
162767 }
162768 
162769 /*
162770 ** This function is called when an ICU function called from within
162771 ** the implementation of an SQL scalar function returns an error.
162772 **
162773 ** The scalar function context passed as the first argument is
162774 ** loaded with an error message based on the following two args.
162775 */
162776 static void icuFunctionError(
162777  sqlite3_context *pCtx, /* SQLite scalar function context */
162778  const char *zName, /* Name of ICU function that failed */
162779  UErrorCode e /* Error code returned by ICU function */
162780 ){
162781  char zBuf[128];
162782  sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
162783  zBuf[127] = '\0';
162784  sqlite3_result_error(pCtx, zBuf, -1);
162785 }
162786 
162787 /*
162788 ** Function to delete compiled regexp objects. Registered as
162789 ** a destructor function with sqlite3_set_auxdata().
162790 */
162791 static void icuRegexpDelete(void *p){
162792  URegularExpression *pExpr = (URegularExpression *)p;
162793  uregex_close(pExpr);
162794 }
162795 
162796 /*
162797 ** Implementation of SQLite REGEXP operator. This scalar function takes
162798 ** two arguments. The first is a regular expression pattern to compile
162799 ** the second is a string to match against that pattern. If either
162800 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
162801 ** is 1 if the string matches the pattern, or 0 otherwise.
162802 **
162803 ** SQLite maps the regexp() function to the regexp() operator such
162804 ** that the following two are equivalent:
162805 **
162806 ** zString REGEXP zPattern
162807 ** regexp(zPattern, zString)
162808 **
162809 ** Uses the following ICU regexp APIs:
162810 **
162811 ** uregex_open()
162812 ** uregex_matches()
162813 ** uregex_close()
162814 */
162815 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
162816  UErrorCode status = U_ZERO_ERROR;
162817  URegularExpression *pExpr;
162818  UBool res;
162819  const UChar *zString = sqlite3_value_text16(apArg[1]);
162820 
162821  (void)nArg; /* Unused parameter */
162822 
162823  /* If the left hand side of the regexp operator is NULL,
162824  ** then the result is also NULL.
162825  */
162826  if( !zString ){
162827  return;
162828  }
162829 
162830  pExpr = sqlite3_get_auxdata(p, 0);
162831  if( !pExpr ){
162832  const UChar *zPattern = sqlite3_value_text16(apArg[0]);
162833  if( !zPattern ){
162834  return;
162835  }
162836  pExpr = uregex_open(zPattern, -1, 0, 0, &status);
162837 
162838  if( U_SUCCESS(status) ){
162839  sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
162840  }else{
162841  assert(!pExpr);
162842  icuFunctionError(p, "uregex_open", status);
162843  return;
162844  }
162845  }
162846 
162847  /* Configure the text that the regular expression operates on. */
162848  uregex_setText(pExpr, zString, -1, &status);
162849  if( !U_SUCCESS(status) ){
162850  icuFunctionError(p, "uregex_setText", status);
162851  return;
162852  }
162853 
162854  /* Attempt the match */
162855  res = uregex_matches(pExpr, 0, &status);
162856  if( !U_SUCCESS(status) ){
162857  icuFunctionError(p, "uregex_matches", status);
162858  return;
162859  }
162860 
162861  /* Set the text that the regular expression operates on to a NULL
162862  ** pointer. This is not really necessary, but it is tidier than
162863  ** leaving the regular expression object configured with an invalid
162864  ** pointer after this function returns.
162865  */
162866  uregex_setText(pExpr, 0, 0, &status);
162867 
162868  /* Return 1 or 0. */
162869  sqlite3_result_int(p, res ? 1 : 0);
162870 }
162871 
162872 /*
162873 ** Implementations of scalar functions for case mapping - upper() and
162874 ** lower(). Function upper() converts its input to upper-case (ABC).
162875 ** Function lower() converts to lower-case (abc).
162876 **
162877 ** ICU provides two types of case mapping, "general" case mapping and
162878 ** "language specific". Refer to ICU documentation for the differences
162879 ** between the two.
162880 **
162881 ** To utilise "general" case mapping, the upper() or lower() scalar
162882 ** functions are invoked with one argument:
162883 **
162884 ** upper('ABC') -> 'abc'
162885 ** lower('abc') -> 'ABC'
162886 **
162887 ** To access ICU "language specific" case mapping, upper() or lower()
162888 ** should be invoked with two arguments. The second argument is the name
162889 ** of the locale to use. Passing an empty string ("") or SQL NULL value
162890 ** as the second argument is the same as invoking the 1 argument version
162891 ** of upper() or lower().
162892 **
162893 ** lower('I', 'en_us') -> 'i'
162894 ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
162895 **
162896 ** http://www.icu-project.org/userguide/posix.html#case_mappings
162897 */
162898 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
162899  const UChar *zInput; /* Pointer to input string */
162900  UChar *zOutput = 0; /* Pointer to output buffer */
162901  int nInput; /* Size of utf-16 input string in bytes */
162902  int nOut; /* Size of output buffer in bytes */
162903  int cnt;
162904  int bToUpper; /* True for toupper(), false for tolower() */
162905  UErrorCode status;
162906  const char *zLocale = 0;
162907 
162908  assert(nArg==1 || nArg==2);
162909  bToUpper = (sqlite3_user_data(p)!=0);
162910  if( nArg==2 ){
162911  zLocale = (const char *)sqlite3_value_text(apArg[1]);
162912  }
162913 
162914  zInput = sqlite3_value_text16(apArg[0]);
162915  if( !zInput ){
162916  return;
162917  }
162918  nOut = nInput = sqlite3_value_bytes16(apArg[0]);
162919  if( nOut==0 ){
162921  return;
162922  }
162923 
162924  for(cnt=0; cnt<2; cnt++){
162925  UChar *zNew = sqlite3_realloc(zOutput, nOut);
162926  if( zNew==0 ){
162927  sqlite3_free(zOutput);
162929  return;
162930  }
162931  zOutput = zNew;
162932  status = U_ZERO_ERROR;
162933  if( bToUpper ){
162934  nOut = 2*u_strToUpper(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
162935  }else{
162936  nOut = 2*u_strToLower(zOutput,nOut/2,zInput,nInput/2,zLocale,&status);
162937  }
162938 
162939  if( U_SUCCESS(status) ){
162940  sqlite3_result_text16(p, zOutput, nOut, xFree);
162941  }else if( status==U_BUFFER_OVERFLOW_ERROR ){
162942  assert( cnt==0 );
162943  continue;
162944  }else{
162945  icuFunctionError(p, bToUpper ? "u_strToUpper" : "u_strToLower", status);
162946  }
162947  return;
162948  }
162949  assert( 0 ); /* Unreachable */
162950 }
162951 
162952 /*
162953 ** Collation sequence destructor function. The pCtx argument points to
162954 ** a UCollator structure previously allocated using ucol_open().
162955 */
162956 static void icuCollationDel(void *pCtx){
162957  UCollator *p = (UCollator *)pCtx;
162958  ucol_close(p);
162959 }
162960 
162961 /*
162962 ** Collation sequence comparison function. The pCtx argument points to
162963 ** a UCollator structure previously allocated using ucol_open().
162964 */
162965 static int icuCollationColl(
162966  void *pCtx,
162967  int nLeft,
162968  const void *zLeft,
162969  int nRight,
162970  const void *zRight
162971 ){
162972  UCollationResult res;
162973  UCollator *p = (UCollator *)pCtx;
162974  res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
162975  switch( res ){
162976  case UCOL_LESS: return -1;
162977  case UCOL_GREATER: return +1;
162978  case UCOL_EQUAL: return 0;
162979  }
162980  assert(!"Unexpected return value from ucol_strcoll()");
162981  return 0;
162982 }
162983 
162984 /*
162985 ** Implementation of the scalar function icu_load_collation().
162986 **
162987 ** This scalar function is used to add ICU collation based collation
162988 ** types to an SQLite database connection. It is intended to be called
162989 ** as follows:
162990 **
162991 ** SELECT icu_load_collation(<locale>, <collation-name>);
162992 **
162993 ** Where <locale> is a string containing an ICU locale identifier (i.e.
162994 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
162995 ** collation sequence to create.
162996 */
162997 static void icuLoadCollation(
162998  sqlite3_context *p,
162999  int nArg,
163000  sqlite3_value **apArg
163001 ){
163002  sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
163003  UErrorCode status = U_ZERO_ERROR;
163004  const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
163005  const char *zName; /* SQL Collation sequence name (eg. "japanese") */
163006  UCollator *pUCollator; /* ICU library collation object */
163007  int rc; /* Return code from sqlite3_create_collation_x() */
163008 
163009  assert(nArg==2);
163010  (void)nArg; /* Unused parameter */
163011  zLocale = (const char *)sqlite3_value_text(apArg[0]);
163012  zName = (const char *)sqlite3_value_text(apArg[1]);
163013 
163014  if( !zLocale || !zName ){
163015  return;
163016  }
163017 
163018  pUCollator = ucol_open(zLocale, &status);
163019  if( !U_SUCCESS(status) ){
163020  icuFunctionError(p, "ucol_open", status);
163021  return;
163022  }
163023  assert(p);
163024 
163025  rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
163026  icuCollationColl, icuCollationDel
163027  );
163028  if( rc!=SQLITE_OK ){
163029  ucol_close(pUCollator);
163030  sqlite3_result_error(p, "Error registering collation function", -1);
163031  }
163032 }
163033 
163034 /*
163035 ** Register the ICU extension functions with database db.
163036 */
163037 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
163038  struct IcuScalar {
163039  const char *zName; /* Function name */
163040  int nArg; /* Number of arguments */
163041  int enc; /* Optimal text encoding */
163042  void *pContext; /* sqlite3_user_data() context */
163043  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
163044  } scalars[] = {
163045  {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
163046 
163047  {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
163048  {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
163049  {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
163050  {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
163051 
163052  {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
163053  {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
163054  {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
163055  {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
163056 
163057  {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
163058  {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
163059 
163060  {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
163061  };
163062 
163063  int rc = SQLITE_OK;
163064  int i;
163065 
163066  for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
163067  struct IcuScalar *p = &scalars[i];
163069  db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
163070  );
163071  }
163072 
163073  return rc;
163074 }
163075 
163076 #if !SQLITE_CORE
163077 #ifdef _WIN32
163078 __declspec(dllexport)
163079 #endif
163080 SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
163081  sqlite3 *db,
163082  char **pzErrMsg,
163083  const sqlite3_api_routines *pApi
163084 ){
163085  SQLITE_EXTENSION_INIT2(pApi)
163086  return sqlite3IcuInit(db);
163087 }
163088 #endif
163089 
163090 #endif
163091 
163092 /************** End of icu.c *************************************************/
163093 /************** Begin file fts3_icu.c ****************************************/
163094 /*
163095 ** 2007 June 22
163096 **
163097 ** The author disclaims copyright to this source code. In place of
163098 ** a legal notice, here is a blessing:
163099 **
163100 ** May you do good and not evil.
163101 ** May you find forgiveness for yourself and forgive others.
163102 ** May you share freely, never taking more than you give.
163103 **
163104 *************************************************************************
163105 ** This file implements a tokenizer for fts3 based on the ICU library.
163106 */
163107 /* #include "fts3Int.h" */
163108 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
163109 #ifdef SQLITE_ENABLE_ICU
163110 
163111 /* #include <assert.h> */
163112 /* #include <string.h> */
163113 /* #include "fts3_tokenizer.h" */
163114 
163115 #include <unicode/ubrk.h>
163116 /* #include <unicode/ucol.h> */
163117 /* #include <unicode/ustring.h> */
163118 #include <unicode/utf16.h>
163119 
163120 typedef struct IcuTokenizer IcuTokenizer;
163121 typedef struct IcuCursor IcuCursor;
163122 
163123 struct IcuTokenizer {
163124  sqlite3_tokenizer base;
163125  char *zLocale;
163126 };
163127 
163128 struct IcuCursor {
163129  sqlite3_tokenizer_cursor base;
163130 
163131  UBreakIterator *pIter; /* ICU break-iterator object */
163132  int nChar; /* Number of UChar elements in pInput */
163133  UChar *aChar; /* Copy of input using utf-16 encoding */
163134  int *aOffset; /* Offsets of each character in utf-8 input */
163135 
163136  int nBuffer;
163137  char *zBuffer;
163138 
163139  int iToken;
163140 };
163141 
163142 /*
163143 ** Create a new tokenizer instance.
163144 */
163145 static int icuCreate(
163146  int argc, /* Number of entries in argv[] */
163147  const char * const *argv, /* Tokenizer creation arguments */
163148  sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
163149 ){
163150  IcuTokenizer *p;
163151  int n = 0;
163152 
163153  if( argc>0 ){
163154  n = strlen(argv[0])+1;
163155  }
163156  p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
163157  if( !p ){
163158  return SQLITE_NOMEM;
163159  }
163160  memset(p, 0, sizeof(IcuTokenizer));
163161 
163162  if( n ){
163163  p->zLocale = (char *)&p[1];
163164  memcpy(p->zLocale, argv[0], n);
163165  }
163166 
163167  *ppTokenizer = (sqlite3_tokenizer *)p;
163168 
163169  return SQLITE_OK;
163170 }
163171 
163172 /*
163173 ** Destroy a tokenizer
163174 */
163175 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
163176  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
163177  sqlite3_free(p);
163178  return SQLITE_OK;
163179 }
163180 
163181 /*
163182 ** Prepare to begin tokenizing a particular string. The input
163183 ** string to be tokenized is pInput[0..nBytes-1]. A cursor
163184 ** used to incrementally tokenize this string is returned in
163185 ** *ppCursor.
163186 */
163187 static int icuOpen(
163188  sqlite3_tokenizer *pTokenizer, /* The tokenizer */
163189  const char *zInput, /* Input string */
163190  int nInput, /* Length of zInput in bytes */
163191  sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
163192 ){
163193  IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
163194  IcuCursor *pCsr;
163195 
163196  const int32_t opt = U_FOLD_CASE_DEFAULT;
163197  UErrorCode status = U_ZERO_ERROR;
163198  int nChar;
163199 
163200  UChar32 c;
163201  int iInput = 0;
163202  int iOut = 0;
163203 
163204  *ppCursor = 0;
163205 
163206  if( zInput==0 ){
163207  nInput = 0;
163208  zInput = "";
163209  }else if( nInput<0 ){
163210  nInput = strlen(zInput);
163211  }
163212  nChar = nInput+1;
163213  pCsr = (IcuCursor *)sqlite3_malloc(
163214  sizeof(IcuCursor) + /* IcuCursor */
163215  ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
163216  (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
163217  );
163218  if( !pCsr ){
163219  return SQLITE_NOMEM;
163220  }
163221  memset(pCsr, 0, sizeof(IcuCursor));
163222  pCsr->aChar = (UChar *)&pCsr[1];
163223  pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
163224 
163225  pCsr->aOffset[iOut] = iInput;
163226  U8_NEXT(zInput, iInput, nInput, c);
163227  while( c>0 ){
163228  int isError = 0;
163229  c = u_foldCase(c, opt);
163230  U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
163231  if( isError ){
163232  sqlite3_free(pCsr);
163233  return SQLITE_ERROR;
163234  }
163235  pCsr->aOffset[iOut] = iInput;
163236 
163237  if( iInput<nInput ){
163238  U8_NEXT(zInput, iInput, nInput, c);
163239  }else{
163240  c = 0;
163241  }
163242  }
163243 
163244  pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
163245  if( !U_SUCCESS(status) ){
163246  sqlite3_free(pCsr);
163247  return SQLITE_ERROR;
163248  }
163249  pCsr->nChar = iOut;
163250 
163251  ubrk_first(pCsr->pIter);
163252  *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
163253  return SQLITE_OK;
163254 }
163255 
163256 /*
163257 ** Close a tokenization cursor previously opened by a call to icuOpen().
163258 */
163259 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
163260  IcuCursor *pCsr = (IcuCursor *)pCursor;
163261  ubrk_close(pCsr->pIter);
163262  sqlite3_free(pCsr->zBuffer);
163263  sqlite3_free(pCsr);
163264  return SQLITE_OK;
163265 }
163266 
163267 /*
163268 ** Extract the next token from a tokenization cursor.
163269 */
163270 static int icuNext(
163271  sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
163272  const char **ppToken, /* OUT: *ppToken is the token text */
163273  int *pnBytes, /* OUT: Number of bytes in token */
163274  int *piStartOffset, /* OUT: Starting offset of token */
163275  int *piEndOffset, /* OUT: Ending offset of token */
163276  int *piPosition /* OUT: Position integer of token */
163277 ){
163278  IcuCursor *pCsr = (IcuCursor *)pCursor;
163279 
163280  int iStart = 0;
163281  int iEnd = 0;
163282  int nByte = 0;
163283 
163284  while( iStart==iEnd ){
163285  UChar32 c;
163286 
163287  iStart = ubrk_current(pCsr->pIter);
163288  iEnd = ubrk_next(pCsr->pIter);
163289  if( iEnd==UBRK_DONE ){
163290  return SQLITE_DONE;
163291  }
163292 
163293  while( iStart<iEnd ){
163294  int iWhite = iStart;
163295  U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
163296  if( u_isspace(c) ){
163297  iStart = iWhite;
163298  }else{
163299  break;
163300  }
163301  }
163302  assert(iStart<=iEnd);
163303  }
163304 
163305  do {
163306  UErrorCode status = U_ZERO_ERROR;
163307  if( nByte ){
163308  char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
163309  if( !zNew ){
163310  return SQLITE_NOMEM;
163311  }
163312  pCsr->zBuffer = zNew;
163313  pCsr->nBuffer = nByte;
163314  }
163315 
163316  u_strToUTF8(
163317  pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
163318  &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
163319  &status /* Output success/failure */
163320  );
163321  } while( nByte>pCsr->nBuffer );
163322 
163323  *ppToken = pCsr->zBuffer;
163324  *pnBytes = nByte;
163325  *piStartOffset = pCsr->aOffset[iStart];
163326  *piEndOffset = pCsr->aOffset[iEnd];
163327  *piPosition = pCsr->iToken++;
163328 
163329  return SQLITE_OK;
163330 }
163331 
163332 /*
163333 ** The set of routines that implement the simple tokenizer
163334 */
163335 static const sqlite3_tokenizer_module icuTokenizerModule = {
163336  0, /* iVersion */
163337  icuCreate, /* xCreate */
163338  icuDestroy, /* xCreate */
163339  icuOpen, /* xOpen */
163340  icuClose, /* xClose */
163341  icuNext, /* xNext */
163342  0, /* xLanguageid */
163343 };
163344 
163345 /*
163346 ** Set *ppModule to point at the implementation of the ICU tokenizer.
163347 */
163348 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
163349  sqlite3_tokenizer_module const**ppModule
163350 ){
163351  *ppModule = &icuTokenizerModule;
163352 }
163353 
163354 #endif /* defined(SQLITE_ENABLE_ICU) */
163355 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
163356 
163357 /************** End of fts3_icu.c ********************************************/
163358 /************** Begin file sqlite3rbu.c **************************************/
163359 /*
163360 ** 2014 August 30
163361 **
163362 ** The author disclaims copyright to this source code. In place of
163363 ** a legal notice, here is a blessing:
163364 **
163365 ** May you do good and not evil.
163366 ** May you find forgiveness for yourself and forgive others.
163367 ** May you share freely, never taking more than you give.
163368 **
163369 *************************************************************************
163370 **
163371 **
163372 ** OVERVIEW
163373 **
163374 ** The RBU extension requires that the RBU update be packaged as an
163375 ** SQLite database. The tables it expects to find are described in
163376 ** sqlite3rbu.h. Essentially, for each table xyz in the target database
163377 ** that the user wishes to write to, a corresponding data_xyz table is
163378 ** created in the RBU database and populated with one row for each row to
163379 ** update, insert or delete from the target table.
163380 **
163381 ** The update proceeds in three stages:
163382 **
163383 ** 1) The database is updated. The modified database pages are written
163384 ** to a *-oal file. A *-oal file is just like a *-wal file, except
163385 ** that it is named "<database>-oal" instead of "<database>-wal".
163386 ** Because regular SQLite clients do not look for file named
163387 ** "<database>-oal", they go on using the original database in
163388 ** rollback mode while the *-oal file is being generated.
163389 **
163390 ** During this stage RBU does not update the database by writing
163391 ** directly to the target tables. Instead it creates "imposter"
163392 ** tables using the SQLITE_TESTCTRL_IMPOSTER interface that it uses
163393 ** to update each b-tree individually. All updates required by each
163394 ** b-tree are completed before moving on to the next, and all
163395 ** updates are done in sorted key order.
163396 **
163397 ** 2) The "<database>-oal" file is moved to the equivalent "<database>-wal"
163398 ** location using a call to rename(2). Before doing this the RBU
163399 ** module takes an EXCLUSIVE lock on the database file, ensuring
163400 ** that there are no other active readers.
163401 **
163402 ** Once the EXCLUSIVE lock is released, any other database readers
163403 ** detect the new *-wal file and read the database in wal mode. At
163404 ** this point they see the new version of the database - including
163405 ** the updates made as part of the RBU update.
163406 **
163407 ** 3) The new *-wal file is checkpointed. This proceeds in the same way
163408 ** as a regular database checkpoint, except that a single frame is
163409 ** checkpointed each time sqlite3rbu_step() is called. If the RBU
163410 ** handle is closed before the entire *-wal file is checkpointed,
163411 ** the checkpoint progress is saved in the RBU database and the
163412 ** checkpoint can be resumed by another RBU client at some point in
163413 ** the future.
163414 **
163415 ** POTENTIAL PROBLEMS
163416 **
163417 ** The rename() call might not be portable. And RBU is not currently
163418 ** syncing the directory after renaming the file.
163419 **
163420 ** When state is saved, any commit to the *-oal file and the commit to
163421 ** the RBU update database are not atomic. So if the power fails at the
163422 ** wrong moment they might get out of sync. As the main database will be
163423 ** committed before the RBU update database this will likely either just
163424 ** pass unnoticed, or result in SQLITE_CONSTRAINT errors (due to UNIQUE
163425 ** constraint violations).
163426 **
163427 ** If some client does modify the target database mid RBU update, or some
163428 ** other error occurs, the RBU extension will keep throwing errors. It's
163429 ** not really clear how to get out of this state. The system could just
163430 ** by delete the RBU update database and *-oal file and have the device
163431 ** download the update again and start over.
163432 **
163433 ** At present, for an UPDATE, both the new.* and old.* records are
163434 ** collected in the rbu_xyz table. And for both UPDATEs and DELETEs all
163435 ** fields are collected. This means we're probably writing a lot more
163436 ** data to disk when saving the state of an ongoing update to the RBU
163437 ** update database than is strictly necessary.
163438 **
163439 */
163440 
163441 /* #include <assert.h> */
163442 /* #include <string.h> */
163443 /* #include <stdio.h> */
163444 
163445 /* #include "sqlite3.h" */
163446 
163447 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU)
163448 /************** Include sqlite3rbu.h in the middle of sqlite3rbu.c ***********/
163449 /************** Begin file sqlite3rbu.h **************************************/
163450 /*
163451 ** 2014 August 30
163452 **
163453 ** The author disclaims copyright to this source code. In place of
163454 ** a legal notice, here is a blessing:
163455 **
163456 ** May you do good and not evil.
163457 ** May you find forgiveness for yourself and forgive others.
163458 ** May you share freely, never taking more than you give.
163459 **
163460 *************************************************************************
163461 **
163462 ** This file contains the public interface for the RBU extension.
163463 */
163464 
163465 /*
163466 ** SUMMARY
163467 **
163468 ** Writing a transaction containing a large number of operations on
163469 ** b-tree indexes that are collectively larger than the available cache
163470 ** memory can be very inefficient.
163471 **
163472 ** The problem is that in order to update a b-tree, the leaf page (at least)
163473 ** containing the entry being inserted or deleted must be modified. If the
163474 ** working set of leaves is larger than the available cache memory, then a
163475 ** single leaf that is modified more than once as part of the transaction
163476 ** may be loaded from or written to the persistent media multiple times.
163477 ** Additionally, because the index updates are likely to be applied in
163478 ** random order, access to pages within the database is also likely to be in
163479 ** random order, which is itself quite inefficient.
163480 **
163481 ** One way to improve the situation is to sort the operations on each index
163482 ** by index key before applying them to the b-tree. This leads to an IO
163483 ** pattern that resembles a single linear scan through the index b-tree,
163484 ** and all but guarantees each modified leaf page is loaded and stored
163485 ** exactly once. SQLite uses this trick to improve the performance of
163486 ** CREATE INDEX commands. This extension allows it to be used to improve
163487 ** the performance of large transactions on existing databases.
163488 **
163489 ** Additionally, this extension allows the work involved in writing the
163490 ** large transaction to be broken down into sub-transactions performed
163491 ** sequentially by separate processes. This is useful if the system cannot
163492 ** guarantee that a single update process will run for long enough to apply
163493 ** the entire update, for example because the update is being applied on a
163494 ** mobile device that is frequently rebooted. Even after the writer process
163495 ** has committed one or more sub-transactions, other database clients continue
163496 ** to read from the original database snapshot. In other words, partially
163497 ** applied transactions are not visible to other clients.
163498 **
163499 ** "RBU" stands for "Resumable Bulk Update". As in a large database update
163500 ** transmitted via a wireless network to a mobile device. A transaction
163501 ** applied using this extension is hence refered to as an "RBU update".
163502 **
163503 **
163504 ** LIMITATIONS
163505 **
163506 ** An "RBU update" transaction is subject to the following limitations:
163507 **
163508 ** * The transaction must consist of INSERT, UPDATE and DELETE operations
163509 ** only.
163510 **
163511 ** * INSERT statements may not use any default values.
163512 **
163513 ** * UPDATE and DELETE statements must identify their target rows by
163514 ** non-NULL PRIMARY KEY values. Rows with NULL values stored in PRIMARY
163515 ** KEY fields may not be updated or deleted. If the table being written
163516 ** has no PRIMARY KEY, affected rows must be identified by rowid.
163517 **
163518 ** * UPDATE statements may not modify PRIMARY KEY columns.
163519 **
163520 ** * No triggers will be fired.
163521 **
163522 ** * No foreign key violations are detected or reported.
163523 **
163524 ** * CHECK constraints are not enforced.
163525 **
163526 ** * No constraint handling mode except for "OR ROLLBACK" is supported.
163527 **
163528 **
163529 ** PREPARATION
163530 **
163531 ** An "RBU update" is stored as a separate SQLite database. A database
163532 ** containing an RBU update is an "RBU database". For each table in the
163533 ** target database to be updated, the RBU database should contain a table
163534 ** named "data_<target name>" containing the same set of columns as the
163535 ** target table, and one more - "rbu_control". The data_% table should
163536 ** have no PRIMARY KEY or UNIQUE constraints, but each column should have
163537 ** the same type as the corresponding column in the target database.
163538 ** The "rbu_control" column should have no type at all. For example, if
163539 ** the target database contains:
163540 **
163541 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b TEXT, c UNIQUE);
163542 **
163543 ** Then the RBU database should contain:
163544 **
163545 ** CREATE TABLE data_t1(a INTEGER, b TEXT, c, rbu_control);
163546 **
163547 ** The order of the columns in the data_% table does not matter.
163548 **
163549 ** Instead of a regular table, the RBU database may also contain virtual
163550 ** tables or view named using the data_<target> naming scheme.
163551 **
163552 ** Instead of the plain data_<target> naming scheme, RBU database tables
163553 ** may also be named data<integer>_<target>, where <integer> is any sequence
163554 ** of zero or more numeric characters (0-9). This can be significant because
163555 ** tables within the RBU database are always processed in order sorted by
163556 ** name. By judicious selection of the the <integer> portion of the names
163557 ** of the RBU tables the user can therefore control the order in which they
163558 ** are processed. This can be useful, for example, to ensure that "external
163559 ** content" FTS4 tables are updated before their underlying content tables.
163560 **
163561 ** If the target database table is a virtual table or a table that has no
163562 ** PRIMARY KEY declaration, the data_% table must also contain a column
163563 ** named "rbu_rowid". This column is mapped to the tables implicit primary
163564 ** key column - "rowid". Virtual tables for which the "rowid" column does
163565 ** not function like a primary key value cannot be updated using RBU. For
163566 ** example, if the target db contains either of the following:
163567 **
163568 ** CREATE VIRTUAL TABLE x1 USING fts3(a, b);
163569 ** CREATE TABLE x1(a, b)
163570 **
163571 ** then the RBU database should contain:
163572 **
163573 ** CREATE TABLE data_x1(a, b, rbu_rowid, rbu_control);
163574 **
163575 ** All non-hidden columns (i.e. all columns matched by "SELECT *") of the
163576 ** target table must be present in the input table. For virtual tables,
163577 ** hidden columns are optional - they are updated by RBU if present in
163578 ** the input table, or not otherwise. For example, to write to an fts4
163579 ** table with a hidden languageid column such as:
163580 **
163581 ** CREATE VIRTUAL TABLE ft1 USING fts4(a, b, languageid='langid');
163582 **
163583 ** Either of the following input table schemas may be used:
163584 **
163585 ** CREATE TABLE data_ft1(a, b, langid, rbu_rowid, rbu_control);
163586 ** CREATE TABLE data_ft1(a, b, rbu_rowid, rbu_control);
163587 **
163588 ** For each row to INSERT into the target database as part of the RBU
163589 ** update, the corresponding data_% table should contain a single record
163590 ** with the "rbu_control" column set to contain integer value 0. The
163591 ** other columns should be set to the values that make up the new record
163592 ** to insert.
163593 **
163594 ** If the target database table has an INTEGER PRIMARY KEY, it is not
163595 ** possible to insert a NULL value into the IPK column. Attempting to
163596 ** do so results in an SQLITE_MISMATCH error.
163597 **
163598 ** For each row to DELETE from the target database as part of the RBU
163599 ** update, the corresponding data_% table should contain a single record
163600 ** with the "rbu_control" column set to contain integer value 1. The
163601 ** real primary key values of the row to delete should be stored in the
163602 ** corresponding columns of the data_% table. The values stored in the
163603 ** other columns are not used.
163604 **
163605 ** For each row to UPDATE from the target database as part of the RBU
163606 ** update, the corresponding data_% table should contain a single record
163607 ** with the "rbu_control" column set to contain a value of type text.
163608 ** The real primary key values identifying the row to update should be
163609 ** stored in the corresponding columns of the data_% table row, as should
163610 ** the new values of all columns being update. The text value in the
163611 ** "rbu_control" column must contain the same number of characters as
163612 ** there are columns in the target database table, and must consist entirely
163613 ** of 'x' and '.' characters (or in some special cases 'd' - see below). For
163614 ** each column that is being updated, the corresponding character is set to
163615 ** 'x'. For those that remain as they are, the corresponding character of the
163616 ** rbu_control value should be set to '.'. For example, given the tables
163617 ** above, the update statement:
163618 **
163619 ** UPDATE t1 SET c = 'usa' WHERE a = 4;
163620 **
163621 ** is represented by the data_t1 row created by:
163622 **
163623 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..x');
163624 **
163625 ** Instead of an 'x' character, characters of the rbu_control value specified
163626 ** for UPDATEs may also be set to 'd'. In this case, instead of updating the
163627 ** target table with the value stored in the corresponding data_% column, the
163628 ** user-defined SQL function "rbu_delta()" is invoked and the result stored in
163629 ** the target table column. rbu_delta() is invoked with two arguments - the
163630 ** original value currently stored in the target table column and the
163631 ** value specified in the data_xxx table.
163632 **
163633 ** For example, this row:
163634 **
163635 ** INSERT INTO data_t1(a, b, c, rbu_control) VALUES(4, NULL, 'usa', '..d');
163636 **
163637 ** is similar to an UPDATE statement such as:
163638 **
163639 ** UPDATE t1 SET c = rbu_delta(c, 'usa') WHERE a = 4;
163640 **
163641 ** Finally, if an 'f' character appears in place of a 'd' or 's' in an
163642 ** ota_control string, the contents of the data_xxx table column is assumed
163643 ** to be a "fossil delta" - a patch to be applied to a blob value in the
163644 ** format used by the fossil source-code management system. In this case
163645 ** the existing value within the target database table must be of type BLOB.
163646 ** It is replaced by the result of applying the specified fossil delta to
163647 ** itself.
163648 **
163649 ** If the target database table is a virtual table or a table with no PRIMARY
163650 ** KEY, the rbu_control value should not include a character corresponding
163651 ** to the rbu_rowid value. For example, this:
163652 **
163653 ** INSERT INTO data_ft1(a, b, rbu_rowid, rbu_control)
163654 ** VALUES(NULL, 'usa', 12, '.x');
163655 **
163656 ** causes a result similar to:
163657 **
163658 ** UPDATE ft1 SET b = 'usa' WHERE rowid = 12;
163659 **
163660 ** The data_xxx tables themselves should have no PRIMARY KEY declarations.
163661 ** However, RBU is more efficient if reading the rows in from each data_xxx
163662 ** table in "rowid" order is roughly the same as reading them sorted by
163663 ** the PRIMARY KEY of the corresponding target database table. In other
163664 ** words, rows should be sorted using the destination table PRIMARY KEY
163665 ** fields before they are inserted into the data_xxx tables.
163666 **
163667 ** USAGE
163668 **
163669 ** The API declared below allows an application to apply an RBU update
163670 ** stored on disk to an existing target database. Essentially, the
163671 ** application:
163672 **
163673 ** 1) Opens an RBU handle using the sqlite3rbu_open() function.
163674 **
163675 ** 2) Registers any required virtual table modules with the database
163676 ** handle returned by sqlite3rbu_db(). Also, if required, register
163677 ** the rbu_delta() implementation.
163678 **
163679 ** 3) Calls the sqlite3rbu_step() function one or more times on
163680 ** the new handle. Each call to sqlite3rbu_step() performs a single
163681 ** b-tree operation, so thousands of calls may be required to apply
163682 ** a complete update.
163683 **
163684 ** 4) Calls sqlite3rbu_close() to close the RBU update handle. If
163685 ** sqlite3rbu_step() has been called enough times to completely
163686 ** apply the update to the target database, then the RBU database
163687 ** is marked as fully applied. Otherwise, the state of the RBU
163688 ** update application is saved in the RBU database for later
163689 ** resumption.
163690 **
163691 ** See comments below for more detail on APIs.
163692 **
163693 ** If an update is only partially applied to the target database by the
163694 ** time sqlite3rbu_close() is called, various state information is saved
163695 ** within the RBU database. This allows subsequent processes to automatically
163696 ** resume the RBU update from where it left off.
163697 **
163698 ** To remove all RBU extension state information, returning an RBU database
163699 ** to its original contents, it is sufficient to drop all tables that begin
163700 ** with the prefix "rbu_"
163701 **
163702 ** DATABASE LOCKING
163703 **
163704 ** An RBU update may not be applied to a database in WAL mode. Attempting
163705 ** to do so is an error (SQLITE_ERROR).
163706 **
163707 ** While an RBU handle is open, a SHARED lock may be held on the target
163708 ** database file. This means it is possible for other clients to read the
163709 ** database, but not to write it.
163710 **
163711 ** If an RBU update is started and then suspended before it is completed,
163712 ** then an external client writes to the database, then attempting to resume
163713 ** the suspended RBU update is also an error (SQLITE_BUSY).
163714 */
163715 
163716 #ifndef _SQLITE3RBU_H
163717 #define _SQLITE3RBU_H
163718 
163719 /* #include "sqlite3.h" ** Required for error code definitions ** */
163720 
163721 #if 0
163722 extern "C" {
163723 #endif
163724 
163725 typedef struct sqlite3rbu sqlite3rbu;
163726 
163727 /*
163728 ** Open an RBU handle.
163729 **
163730 ** Argument zTarget is the path to the target database. Argument zRbu is
163731 ** the path to the RBU database. Each call to this function must be matched
163732 ** by a call to sqlite3rbu_close(). When opening the databases, RBU passes
163733 ** the SQLITE_CONFIG_URI flag to sqlite3_open_v2(). So if either zTarget
163734 ** or zRbu begin with "file:", it will be interpreted as an SQLite
163735 ** database URI, not a regular file name.
163736 **
163737 ** If the zState argument is passed a NULL value, the RBU extension stores
163738 ** the current state of the update (how many rows have been updated, which
163739 ** indexes are yet to be updated etc.) within the RBU database itself. This
163740 ** can be convenient, as it means that the RBU application does not need to
163741 ** organize removing a separate state file after the update is concluded.
163742 ** Or, if zState is non-NULL, it must be a path to a database file in which
163743 ** the RBU extension can store the state of the update.
163744 **
163745 ** When resuming an RBU update, the zState argument must be passed the same
163746 ** value as when the RBU update was started.
163747 **
163748 ** Once the RBU update is finished, the RBU extension does not
163749 ** automatically remove any zState database file, even if it created it.
163750 **
163751 ** By default, RBU uses the default VFS to access the files on disk. To
163752 ** use a VFS other than the default, an SQLite "file:" URI containing a
163753 ** "vfs=..." option may be passed as the zTarget option.
163754 **
163755 ** IMPORTANT NOTE FOR ZIPVFS USERS: The RBU extension works with all of
163756 ** SQLite's built-in VFSs, including the multiplexor VFS. However it does
163757 ** not work out of the box with zipvfs. Refer to the comment describing
163758 ** the zipvfs_create_vfs() API below for details on using RBU with zipvfs.
163759 */
163760 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
163761  const char *zTarget,
163762  const char *zRbu,
163763  const char *zState
163764 );
163765 
163766 /*
163767 ** Open an RBU handle to perform an RBU vacuum on database file zTarget.
163768 ** An RBU vacuum is similar to SQLite's built-in VACUUM command, except
163769 ** that it can be suspended and resumed like an RBU update.
163770 **
163771 ** The second argument to this function, which may not be NULL, identifies
163772 ** a database in which to store the state of the RBU vacuum operation if
163773 ** it is suspended. The first time sqlite3rbu_vacuum() is called, to start
163774 ** an RBU vacuum operation, the state database should either not exist or
163775 ** be empty (contain no tables). If an RBU vacuum is suspended by calling
163776 ** sqlite3rbu_close() on the RBU handle before sqlite3rbu_step() has
163777 ** returned SQLITE_DONE, the vacuum state is stored in the state database.
163778 ** The vacuum can be resumed by calling this function to open a new RBU
163779 ** handle specifying the same target and state databases.
163780 **
163781 ** This function does not delete the state database after an RBU vacuum
163782 ** is completed, even if it created it. However, if the call to
163783 ** sqlite3rbu_close() returns any value other than SQLITE_OK, the contents
163784 ** of the state tables within the state database are zeroed. This way,
163785 ** the next call to sqlite3rbu_vacuum() opens a handle that starts a
163786 ** new RBU vacuum operation.
163787 **
163788 ** As with sqlite3rbu_open(), Zipvfs users should rever to the comment
163789 ** describing the sqlite3rbu_create_vfs() API function below for
163790 ** a description of the complications associated with using RBU with
163791 ** zipvfs databases.
163792 */
163793 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
163794  const char *zTarget,
163795  const char *zState
163796 );
163797 
163798 /*
163799 ** Internally, each RBU connection uses a separate SQLite database
163800 ** connection to access the target and rbu update databases. This
163801 ** API allows the application direct access to these database handles.
163802 **
163803 ** The first argument passed to this function must be a valid, open, RBU
163804 ** handle. The second argument should be passed zero to access the target
163805 ** database handle, or non-zero to access the rbu update database handle.
163806 ** Accessing the underlying database handles may be useful in the
163807 ** following scenarios:
163808 **
163809 ** * If any target tables are virtual tables, it may be necessary to
163810 ** call sqlite3_create_module() on the target database handle to
163811 ** register the required virtual table implementations.
163812 **
163813 ** * If the data_xxx tables in the RBU source database are virtual
163814 ** tables, the application may need to call sqlite3_create_module() on
163815 ** the rbu update db handle to any required virtual table
163816 ** implementations.
163817 **
163818 ** * If the application uses the "rbu_delta()" feature described above,
163819 ** it must use sqlite3_create_function() or similar to register the
163820 ** rbu_delta() implementation with the target database handle.
163821 **
163822 ** If an error has occurred, either while opening or stepping the RBU object,
163823 ** this function may return NULL. The error code and message may be collected
163824 ** when sqlite3rbu_close() is called.
163825 **
163826 ** Database handles returned by this function remain valid until the next
163827 ** call to any sqlite3rbu_xxx() function other than sqlite3rbu_db().
163828 */
163829 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu*, int bRbu);
163830 
163831 /*
163832 ** Do some work towards applying the RBU update to the target db.
163833 **
163834 ** Return SQLITE_DONE if the update has been completely applied, or
163835 ** SQLITE_OK if no error occurs but there remains work to do to apply
163836 ** the RBU update. If an error does occur, some other error code is
163837 ** returned.
163838 **
163839 ** Once a call to sqlite3rbu_step() has returned a value other than
163840 ** SQLITE_OK, all subsequent calls on the same RBU handle are no-ops
163841 ** that immediately return the same value.
163842 */
163843 SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *pRbu);
163844 
163845 /*
163846 ** Force RBU to save its state to disk.
163847 **
163848 ** If a power failure or application crash occurs during an update, following
163849 ** system recovery RBU may resume the update from the point at which the state
163850 ** was last saved. In other words, from the most recent successful call to
163851 ** sqlite3rbu_close() or this function.
163852 **
163853 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
163854 */
163855 SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *pRbu);
163856 
163857 /*
163858 ** Close an RBU handle.
163859 **
163860 ** If the RBU update has been completely applied, mark the RBU database
163861 ** as fully applied. Otherwise, assuming no error has occurred, save the
163862 ** current state of the RBU update appliation to the RBU database.
163863 **
163864 ** If an error has already occurred as part of an sqlite3rbu_step()
163865 ** or sqlite3rbu_open() call, or if one occurs within this function, an
163866 ** SQLite error code is returned. Additionally, *pzErrmsg may be set to
163867 ** point to a buffer containing a utf-8 formatted English language error
163868 ** message. It is the responsibility of the caller to eventually free any
163869 ** such buffer using sqlite3_free().
163870 **
163871 ** Otherwise, if no error occurs, this function returns SQLITE_OK if the
163872 ** update has been partially applied, or SQLITE_DONE if it has been
163873 ** completely applied.
163874 */
163875 SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *pRbu, char **pzErrmsg);
163876 
163877 /*
163878 ** Return the total number of key-value operations (inserts, deletes or
163879 ** updates) that have been performed on the target database since the
163880 ** current RBU update was started.
163881 */
163882 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu);
163883 
163884 /*
163885 ** Obtain permyriadage (permyriadage is to 10000 as percentage is to 100)
163886 ** progress indications for the two stages of an RBU update. This API may
163887 ** be useful for driving GUI progress indicators and similar.
163888 **
163889 ** An RBU update is divided into two stages:
163890 **
163891 ** * Stage 1, in which changes are accumulated in an oal/wal file, and
163892 ** * Stage 2, in which the contents of the wal file are copied into the
163893 ** main database.
163894 **
163895 ** The update is visible to non-RBU clients during stage 2. During stage 1
163896 ** non-RBU reader clients may see the original database.
163897 **
163898 ** If this API is called during stage 2 of the update, output variable
163899 ** (*pnOne) is set to 10000 to indicate that stage 1 has finished and (*pnTwo)
163900 ** to a value between 0 and 10000 to indicate the permyriadage progress of
163901 ** stage 2. A value of 5000 indicates that stage 2 is half finished,
163902 ** 9000 indicates that it is 90% finished, and so on.
163903 **
163904 ** If this API is called during stage 1 of the update, output variable
163905 ** (*pnTwo) is set to 0 to indicate that stage 2 has not yet started. The
163906 ** value to which (*pnOne) is set depends on whether or not the RBU
163907 ** database contains an "rbu_count" table. The rbu_count table, if it
163908 ** exists, must contain the same columns as the following:
163909 **
163910 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
163911 **
163912 ** There must be one row in the table for each source (data_xxx) table within
163913 ** the RBU database. The 'tbl' column should contain the name of the source
163914 ** table. The 'cnt' column should contain the number of rows within the
163915 ** source table.
163916 **
163917 ** If the rbu_count table is present and populated correctly and this
163918 ** API is called during stage 1, the *pnOne output variable is set to the
163919 ** permyriadage progress of the same stage. If the rbu_count table does
163920 ** not exist, then (*pnOne) is set to -1 during stage 1. If the rbu_count
163921 ** table exists but is not correctly populated, the value of the *pnOne
163922 ** output variable during stage 1 is undefined.
163923 */
163924 SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *pRbu, int *pnOne, int *pnTwo);
163925 
163926 /*
163927 ** Create an RBU VFS named zName that accesses the underlying file-system
163928 ** via existing VFS zParent. Or, if the zParent parameter is passed NULL,
163929 ** then the new RBU VFS uses the default system VFS to access the file-system.
163930 ** The new object is registered as a non-default VFS with SQLite before
163931 ** returning.
163932 **
163933 ** Part of the RBU implementation uses a custom VFS object. Usually, this
163934 ** object is created and deleted automatically by RBU.
163935 **
163936 ** The exception is for applications that also use zipvfs. In this case,
163937 ** the custom VFS must be explicitly created by the user before the RBU
163938 ** handle is opened. The RBU VFS should be installed so that the zipvfs
163939 ** VFS uses the RBU VFS, which in turn uses any other VFS layers in use
163940 ** (for example multiplexor) to access the file-system. For example,
163941 ** to assemble an RBU enabled VFS stack that uses both zipvfs and
163942 ** multiplexor (error checking omitted):
163943 **
163944 ** // Create a VFS named "multiplex" (not the default).
163945 ** sqlite3_multiplex_initialize(0, 0);
163946 **
163947 ** // Create an rbu VFS named "rbu" that uses multiplexor. If the
163948 ** // second argument were replaced with NULL, the "rbu" VFS would
163949 ** // access the file-system via the system default VFS, bypassing the
163950 ** // multiplexor.
163951 ** sqlite3rbu_create_vfs("rbu", "multiplex");
163952 **
163953 ** // Create a zipvfs VFS named "zipvfs" that uses rbu.
163954 ** zipvfs_create_vfs_v3("zipvfs", "rbu", 0, xCompressorAlgorithmDetector);
163955 **
163956 ** // Make zipvfs the default VFS.
163957 ** sqlite3_vfs_register(sqlite3_vfs_find("zipvfs"), 1);
163958 **
163959 ** Because the default VFS created above includes a RBU functionality, it
163960 ** may be used by RBU clients. Attempting to use RBU with a zipvfs VFS stack
163961 ** that does not include the RBU layer results in an error.
163962 **
163963 ** The overhead of adding the "rbu" VFS to the system is negligible for
163964 ** non-RBU users. There is no harm in an application accessing the
163965 ** file-system via "rbu" all the time, even if it only uses RBU functionality
163966 ** occasionally.
163967 */
163968 SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent);
163969 
163970 /*
163971 ** Deregister and destroy an RBU vfs created by an earlier call to
163972 ** sqlite3rbu_create_vfs().
163973 **
163974 ** VFS objects are not reference counted. If a VFS object is destroyed
163975 ** before all database handles that use it have been closed, the results
163976 ** are undefined.
163977 */
163978 SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName);
163979 
163980 #if 0
163981 } /* end of the 'extern "C"' block */
163982 #endif
163983 
163984 #endif /* _SQLITE3RBU_H */
163985 
163986 /************** End of sqlite3rbu.h ******************************************/
163987 /************** Continuing where we left off in sqlite3rbu.c *****************/
163988 
163989 #if defined(_WIN32_WCE)
163990 /* #include "windows.h" */
163991 #endif
163992 
163993 /* Maximum number of prepared UPDATE statements held by this module */
163994 #define SQLITE_RBU_UPDATE_CACHESIZE 16
163995 
163996 /*
163997 ** Swap two objects of type TYPE.
163998 */
163999 #if !defined(SQLITE_AMALGAMATION)
164000 # define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
164001 #endif
164002 
164003 /*
164004 ** The rbu_state table is used to save the state of a partially applied
164005 ** update so that it can be resumed later. The table consists of integer
164006 ** keys mapped to values as follows:
164007 **
164008 ** RBU_STATE_STAGE:
164009 ** May be set to integer values 1, 2, 4 or 5. As follows:
164010 ** 1: the *-rbu file is currently under construction.
164011 ** 2: the *-rbu file has been constructed, but not yet moved
164012 ** to the *-wal path.
164013 ** 4: the checkpoint is underway.
164014 ** 5: the rbu update has been checkpointed.
164015 **
164016 ** RBU_STATE_TBL:
164017 ** Only valid if STAGE==1. The target database name of the table
164018 ** currently being written.
164019 **
164020 ** RBU_STATE_IDX:
164021 ** Only valid if STAGE==1. The target database name of the index
164022 ** currently being written, or NULL if the main table is currently being
164023 ** updated.
164024 **
164025 ** RBU_STATE_ROW:
164026 ** Only valid if STAGE==1. Number of rows already processed for the current
164027 ** table/index.
164028 **
164029 ** RBU_STATE_PROGRESS:
164030 ** Trbul number of sqlite3rbu_step() calls made so far as part of this
164031 ** rbu update.
164032 **
164033 ** RBU_STATE_CKPT:
164034 ** Valid if STAGE==4. The 64-bit checksum associated with the wal-index
164035 ** header created by recovering the *-wal file. This is used to detect
164036 ** cases when another client appends frames to the *-wal file in the
164037 ** middle of an incremental checkpoint (an incremental checkpoint cannot
164038 ** be continued if this happens).
164039 **
164040 ** RBU_STATE_COOKIE:
164041 ** Valid if STAGE==1. The current change-counter cookie value in the
164042 ** target db file.
164043 **
164044 ** RBU_STATE_OALSZ:
164045 ** Valid if STAGE==1. The size in bytes of the *-oal file.
164046 */
164047 #define RBU_STATE_STAGE 1
164048 #define RBU_STATE_TBL 2
164049 #define RBU_STATE_IDX 3
164050 #define RBU_STATE_ROW 4
164051 #define RBU_STATE_PROGRESS 5
164052 #define RBU_STATE_CKPT 6
164053 #define RBU_STATE_COOKIE 7
164054 #define RBU_STATE_OALSZ 8
164055 #define RBU_STATE_PHASEONESTEP 9
164056 
164057 #define RBU_STAGE_OAL 1
164058 #define RBU_STAGE_MOVE 2
164059 #define RBU_STAGE_CAPTURE 3
164060 #define RBU_STAGE_CKPT 4
164061 #define RBU_STAGE_DONE 5
164062 
164063 
164064 #define RBU_CREATE_STATE \
164065  "CREATE TABLE IF NOT EXISTS %s.rbu_state(k INTEGER PRIMARY KEY, v)"
164066 
164067 typedef struct RbuFrame RbuFrame;
164068 typedef struct RbuObjIter RbuObjIter;
164069 typedef struct RbuState RbuState;
164070 typedef struct rbu_vfs rbu_vfs;
164071 typedef struct rbu_file rbu_file;
164072 typedef struct RbuUpdateStmt RbuUpdateStmt;
164073 
164074 #if !defined(SQLITE_AMALGAMATION)
164075 typedef unsigned int u32;
164076 typedef unsigned short u16;
164077 typedef unsigned char u8;
164078 typedef sqlite3_int64 i64;
164079 #endif
164080 
164081 /*
164082 ** These values must match the values defined in wal.c for the equivalent
164083 ** locks. These are not magic numbers as they are part of the SQLite file
164084 ** format.
164085 */
164086 #define WAL_LOCK_WRITE 0
164087 #define WAL_LOCK_CKPT 1
164088 #define WAL_LOCK_READ0 3
164089 
164090 #define SQLITE_FCNTL_RBUCNT 5149216
164091 
164092 /*
164093 ** A structure to store values read from the rbu_state table in memory.
164094 */
164095 struct RbuState {
164096  int eStage;
164097  char *zTbl;
164098  char *zIdx;
164099  i64 iWalCksum;
164100  int nRow;
164101  i64 nProgress;
164102  u32 iCookie;
164103  i64 iOalSz;
164104  i64 nPhaseOneStep;
164105 };
164106 
164107 struct RbuUpdateStmt {
164108  char *zMask; /* Copy of update mask used with pUpdate */
164109  sqlite3_stmt *pUpdate; /* Last update statement (or NULL) */
164110  RbuUpdateStmt *pNext;
164111 };
164112 
164113 /*
164114 ** An iterator of this type is used to iterate through all objects in
164115 ** the target database that require updating. For each such table, the
164116 ** iterator visits, in order:
164117 **
164118 ** * the table itself,
164119 ** * each index of the table (zero or more points to visit), and
164120 ** * a special "cleanup table" state.
164121 **
164122 ** abIndexed:
164123 ** If the table has no indexes on it, abIndexed is set to NULL. Otherwise,
164124 ** it points to an array of flags nTblCol elements in size. The flag is
164125 ** set for each column that is either a part of the PK or a part of an
164126 ** index. Or clear otherwise.
164127 **
164128 */
164129 struct RbuObjIter {
164130  sqlite3_stmt *pTblIter; /* Iterate through tables */
164131  sqlite3_stmt *pIdxIter; /* Index iterator */
164132  int nTblCol; /* Size of azTblCol[] array */
164133  char **azTblCol; /* Array of unquoted target column names */
164134  char **azTblType; /* Array of target column types */
164135  int *aiSrcOrder; /* src table col -> target table col */
164136  u8 *abTblPk; /* Array of flags, set on target PK columns */
164137  u8 *abNotNull; /* Array of flags, set on NOT NULL columns */
164138  u8 *abIndexed; /* Array of flags, set on indexed & PK cols */
164139  int eType; /* Table type - an RBU_PK_XXX value */
164140 
164141  /* Output variables. zTbl==0 implies EOF. */
164142  int bCleanup; /* True in "cleanup" state */
164143  const char *zTbl; /* Name of target db table */
164144  const char *zDataTbl; /* Name of rbu db table (or null) */
164145  const char *zIdx; /* Name of target db index (or null) */
164146  int iTnum; /* Root page of current object */
164147  int iPkTnum; /* If eType==EXTERNAL, root of PK index */
164148  int bUnique; /* Current index is unique */
164149  int nIndex; /* Number of aux. indexes on table zTbl */
164150 
164151  /* Statements created by rbuObjIterPrepareAll() */
164152  int nCol; /* Number of columns in current object */
164153  sqlite3_stmt *pSelect; /* Source data */
164154  sqlite3_stmt *pInsert; /* Statement for INSERT operations */
164155  sqlite3_stmt *pDelete; /* Statement for DELETE ops */
164156  sqlite3_stmt *pTmpInsert; /* Insert into rbu_tmp_$zDataTbl */
164157 
164158  /* Last UPDATE used (for PK b-tree updates only), or NULL. */
164159  RbuUpdateStmt *pRbuUpdate;
164160 };
164161 
164162 /*
164163 ** Values for RbuObjIter.eType
164164 **
164165 ** 0: Table does not exist (error)
164166 ** 1: Table has an implicit rowid.
164167 ** 2: Table has an explicit IPK column.
164168 ** 3: Table has an external PK index.
164169 ** 4: Table is WITHOUT ROWID.
164170 ** 5: Table is a virtual table.
164171 */
164172 #define RBU_PK_NOTABLE 0
164173 #define RBU_PK_NONE 1
164174 #define RBU_PK_IPK 2
164175 #define RBU_PK_EXTERNAL 3
164176 #define RBU_PK_WITHOUT_ROWID 4
164177 #define RBU_PK_VTAB 5
164178 
164179 
164180 /*
164181 ** Within the RBU_STAGE_OAL stage, each call to sqlite3rbu_step() performs
164182 ** one of the following operations.
164183 */
164184 #define RBU_INSERT 1 /* Insert on a main table b-tree */
164185 #define RBU_DELETE 2 /* Delete a row from a main table b-tree */
164186 #define RBU_REPLACE 3 /* Delete and then insert a row */
164187 #define RBU_IDX_DELETE 4 /* Delete a row from an aux. index b-tree */
164188 #define RBU_IDX_INSERT 5 /* Insert on an aux. index b-tree */
164189 
164190 #define RBU_UPDATE 6 /* Update a row in a main table b-tree */
164191 
164192 /*
164193 ** A single step of an incremental checkpoint - frame iWalFrame of the wal
164194 ** file should be copied to page iDbPage of the database file.
164195 */
164196 struct RbuFrame {
164197  u32 iDbPage;
164198  u32 iWalFrame;
164199 };
164200 
164201 /*
164202 ** RBU handle.
164203 **
164204 ** nPhaseOneStep:
164205 ** If the RBU database contains an rbu_count table, this value is set to
164206 ** a running estimate of the number of b-tree operations required to
164207 ** finish populating the *-oal file. This allows the sqlite3_bp_progress()
164208 ** API to calculate the permyriadage progress of populating the *-oal file
164209 ** using the formula:
164210 **
164211 ** permyriadage = (10000 * nProgress) / nPhaseOneStep
164212 **
164213 ** nPhaseOneStep is initialized to the sum of:
164214 **
164215 ** nRow * (nIndex + 1)
164216 **
164217 ** for all source tables in the RBU database, where nRow is the number
164218 ** of rows in the source table and nIndex the number of indexes on the
164219 ** corresponding target database table.
164220 **
164221 ** This estimate is accurate if the RBU update consists entirely of
164222 ** INSERT operations. However, it is inaccurate if:
164223 **
164224 ** * the RBU update contains any UPDATE operations. If the PK specified
164225 ** for an UPDATE operation does not exist in the target table, then
164226 ** no b-tree operations are required on index b-trees. Or if the
164227 ** specified PK does exist, then (nIndex*2) such operations are
164228 ** required (one delete and one insert on each index b-tree).
164229 **
164230 ** * the RBU update contains any DELETE operations for which the specified
164231 ** PK does not exist. In this case no operations are required on index
164232 ** b-trees.
164233 **
164234 ** * the RBU update contains REPLACE operations. These are similar to
164235 ** UPDATE operations.
164236 **
164237 ** nPhaseOneStep is updated to account for the conditions above during the
164238 ** first pass of each source table. The updated nPhaseOneStep value is
164239 ** stored in the rbu_state table if the RBU update is suspended.
164240 */
164241 struct sqlite3rbu {
164242  int eStage; /* Value of RBU_STATE_STAGE field */
164243  sqlite3 *dbMain; /* target database handle */
164244  sqlite3 *dbRbu; /* rbu database handle */
164245  char *zTarget; /* Path to target db */
164246  char *zRbu; /* Path to rbu db */
164247  char *zState; /* Path to state db (or NULL if zRbu) */
164248  char zStateDb[5]; /* Db name for state ("stat" or "main") */
164249  int rc; /* Value returned by last rbu_step() call */
164250  char *zErrmsg; /* Error message if rc!=SQLITE_OK */
164251  int nStep; /* Rows processed for current object */
164252  int nProgress; /* Rows processed for all objects */
164253  RbuObjIter objiter; /* Iterator for skipping through tbl/idx */
164254  const char *zVfsName; /* Name of automatically created rbu vfs */
164255  rbu_file *pTargetFd; /* File handle open on target db */
164256  i64 iOalSz;
164257  i64 nPhaseOneStep;
164258 
164259  /* The following state variables are used as part of the incremental
164260  ** checkpoint stage (eStage==RBU_STAGE_CKPT). See comments surrounding
164261  ** function rbuSetupCheckpoint() for details. */
164262  u32 iMaxFrame; /* Largest iWalFrame value in aFrame[] */
164263  u32 mLock;
164264  int nFrame; /* Entries in aFrame[] array */
164265  int nFrameAlloc; /* Allocated size of aFrame[] array */
164266  RbuFrame *aFrame;
164267  int pgsz;
164268  u8 *aBuf;
164269  i64 iWalCksum;
164270 
164271  /* Used in RBU vacuum mode only */
164272  int nRbu; /* Number of RBU VFS in the stack */
164273  rbu_file *pRbuFd; /* Fd for main db of dbRbu */
164274 };
164275 
164276 /*
164277 ** An rbu VFS is implemented using an instance of this structure.
164278 */
164279 struct rbu_vfs {
164280  sqlite3_vfs base; /* rbu VFS shim methods */
164281  sqlite3_vfs *pRealVfs; /* Underlying VFS */
164282  sqlite3_mutex *mutex; /* Mutex to protect pMain */
164283  rbu_file *pMain; /* Linked list of main db files */
164284 };
164285 
164286 /*
164287 ** Each file opened by an rbu VFS is represented by an instance of
164288 ** the following structure.
164289 */
164290 struct rbu_file {
164291  sqlite3_file base; /* sqlite3_file methods */
164292  sqlite3_file *pReal; /* Underlying file handle */
164293  rbu_vfs *pRbuVfs; /* Pointer to the rbu_vfs object */
164294  sqlite3rbu *pRbu; /* Pointer to rbu object (rbu target only) */
164295 
164296  int openFlags; /* Flags this file was opened with */
164297  u32 iCookie; /* Cookie value for main db files */
164298  u8 iWriteVer; /* "write-version" value for main db files */
164299  u8 bNolock; /* True to fail EXCLUSIVE locks */
164300 
164301  int nShm; /* Number of entries in apShm[] array */
164302  char **apShm; /* Array of mmap'd *-shm regions */
164303  char *zDel; /* Delete this when closing file */
164304 
164305  const char *zWal; /* Wal filename for this main db file */
164306  rbu_file *pWalFd; /* Wal file descriptor for this main db */
164307  rbu_file *pMainNext; /* Next MAIN_DB file */
164308 };
164309 
164310 /*
164311 ** True for an RBU vacuum handle, or false otherwise.
164312 */
164313 #define rbuIsVacuum(p) ((p)->zTarget==0)
164314 
164315 
164316 /*************************************************************************
164317 ** The following three functions, found below:
164318 **
164319 ** rbuDeltaGetInt()
164320 ** rbuDeltaChecksum()
164321 ** rbuDeltaApply()
164322 **
164323 ** are lifted from the fossil source code (http://fossil-scm.org). They
164324 ** are used to implement the scalar SQL function rbu_fossil_delta().
164325 */
164326 
164327 /*
164328 ** Read bytes from *pz and convert them into a positive integer. When
164329 ** finished, leave *pz pointing to the first character past the end of
164330 ** the integer. The *pLen parameter holds the length of the string
164331 ** in *pz and is decremented once for each character in the integer.
164332 */
164333 static unsigned int rbuDeltaGetInt(const char **pz, int *pLen){
164334  static const signed char zValue[] = {
164335  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
164336  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
164337  -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
164338  0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1,
164339  -1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
164340  25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, 36,
164341  -1, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
164342  52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, -1, -1, -1, 63, -1,
164343  };
164344  unsigned int v = 0;
164345  int c;
164346  unsigned char *z = (unsigned char*)*pz;
164347  unsigned char *zStart = z;
164348  while( (c = zValue[0x7f&*(z++)])>=0 ){
164349  v = (v<<6) + c;
164350  }
164351  z--;
164352  *pLen -= z - zStart;
164353  *pz = (char*)z;
164354  return v;
164355 }
164356 
164357 /*
164358 ** Compute a 32-bit checksum on the N-byte buffer. Return the result.
164359 */
164360 static unsigned int rbuDeltaChecksum(const char *zIn, size_t N){
164361  const unsigned char *z = (const unsigned char *)zIn;
164362  unsigned sum0 = 0;
164363  unsigned sum1 = 0;
164364  unsigned sum2 = 0;
164365  unsigned sum3 = 0;
164366  while(N >= 16){
164367  sum0 += ((unsigned)z[0] + z[4] + z[8] + z[12]);
164368  sum1 += ((unsigned)z[1] + z[5] + z[9] + z[13]);
164369  sum2 += ((unsigned)z[2] + z[6] + z[10]+ z[14]);
164370  sum3 += ((unsigned)z[3] + z[7] + z[11]+ z[15]);
164371  z += 16;
164372  N -= 16;
164373  }
164374  while(N >= 4){
164375  sum0 += z[0];
164376  sum1 += z[1];
164377  sum2 += z[2];
164378  sum3 += z[3];
164379  z += 4;
164380  N -= 4;
164381  }
164382  sum3 += (sum2 << 8) + (sum1 << 16) + (sum0 << 24);
164383  switch(N){
164384  case 3: sum3 += (z[2] << 8);
164385  case 2: sum3 += (z[1] << 16);
164386  case 1: sum3 += (z[0] << 24);
164387  default: ;
164388  }
164389  return sum3;
164390 }
164391 
164392 /*
164393 ** Apply a delta.
164394 **
164395 ** The output buffer should be big enough to hold the whole output
164396 ** file and a NUL terminator at the end. The delta_output_size()
164397 ** routine will determine this size for you.
164398 **
164399 ** The delta string should be null-terminated. But the delta string
164400 ** may contain embedded NUL characters (if the input and output are
164401 ** binary files) so we also have to pass in the length of the delta in
164402 ** the lenDelta parameter.
164403 **
164404 ** This function returns the size of the output file in bytes (excluding
164405 ** the final NUL terminator character). Except, if the delta string is
164406 ** malformed or intended for use with a source file other than zSrc,
164407 ** then this routine returns -1.
164408 **
164409 ** Refer to the delta_create() documentation above for a description
164410 ** of the delta file format.
164411 */
164412 static int rbuDeltaApply(
164413  const char *zSrc, /* The source or pattern file */
164414  int lenSrc, /* Length of the source file */
164415  const char *zDelta, /* Delta to apply to the pattern */
164416  int lenDelta, /* Length of the delta */
164417  char *zOut /* Write the output into this preallocated buffer */
164418 ){
164419  unsigned int limit;
164420  unsigned int total = 0;
164421 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
164422  char *zOrigOut = zOut;
164423 #endif
164424 
164425  limit = rbuDeltaGetInt(&zDelta, &lenDelta);
164426  if( *zDelta!='\n' ){
164427  /* ERROR: size integer not terminated by "\n" */
164428  return -1;
164429  }
164430  zDelta++; lenDelta--;
164431  while( *zDelta && lenDelta>0 ){
164432  unsigned int cnt, ofst;
164433  cnt = rbuDeltaGetInt(&zDelta, &lenDelta);
164434  switch( zDelta[0] ){
164435  case '@': {
164436  zDelta++; lenDelta--;
164437  ofst = rbuDeltaGetInt(&zDelta, &lenDelta);
164438  if( lenDelta>0 && zDelta[0]!=',' ){
164439  /* ERROR: copy command not terminated by ',' */
164440  return -1;
164441  }
164442  zDelta++; lenDelta--;
164443  total += cnt;
164444  if( total>limit ){
164445  /* ERROR: copy exceeds output file size */
164446  return -1;
164447  }
164448  if( (int)(ofst+cnt) > lenSrc ){
164449  /* ERROR: copy extends past end of input */
164450  return -1;
164451  }
164452  memcpy(zOut, &zSrc[ofst], cnt);
164453  zOut += cnt;
164454  break;
164455  }
164456  case ':': {
164457  zDelta++; lenDelta--;
164458  total += cnt;
164459  if( total>limit ){
164460  /* ERROR: insert command gives an output larger than predicted */
164461  return -1;
164462  }
164463  if( (int)cnt>lenDelta ){
164464  /* ERROR: insert count exceeds size of delta */
164465  return -1;
164466  }
164467  memcpy(zOut, zDelta, cnt);
164468  zOut += cnt;
164469  zDelta += cnt;
164470  lenDelta -= cnt;
164471  break;
164472  }
164473  case ';': {
164474  zDelta++; lenDelta--;
164475  zOut[0] = 0;
164476 #ifndef FOSSIL_OMIT_DELTA_CKSUM_TEST
164477  if( cnt!=rbuDeltaChecksum(zOrigOut, total) ){
164478  /* ERROR: bad checksum */
164479  return -1;
164480  }
164481 #endif
164482  if( total!=limit ){
164483  /* ERROR: generated size does not match predicted size */
164484  return -1;
164485  }
164486  return total;
164487  }
164488  default: {
164489  /* ERROR: unknown delta operator */
164490  return -1;
164491  }
164492  }
164493  }
164494  /* ERROR: unterminated delta */
164495  return -1;
164496 }
164497 
164498 static int rbuDeltaOutputSize(const char *zDelta, int lenDelta){
164499  int size;
164500  size = rbuDeltaGetInt(&zDelta, &lenDelta);
164501  if( *zDelta!='\n' ){
164502  /* ERROR: size integer not terminated by "\n" */
164503  return -1;
164504  }
164505  return size;
164506 }
164507 
164508 /*
164509 ** End of code taken from fossil.
164510 *************************************************************************/
164511 
164512 /*
164513 ** Implementation of SQL scalar function rbu_fossil_delta().
164514 **
164515 ** This function applies a fossil delta patch to a blob. Exactly two
164516 ** arguments must be passed to this function. The first is the blob to
164517 ** patch and the second the patch to apply. If no error occurs, this
164518 ** function returns the patched blob.
164519 */
164520 static void rbuFossilDeltaFunc(
164521  sqlite3_context *context,
164522  int argc,
164523  sqlite3_value **argv
164524 ){
164525  const char *aDelta;
164526  int nDelta;
164527  const char *aOrig;
164528  int nOrig;
164529 
164530  int nOut;
164531  int nOut2;
164532  char *aOut;
164533 
164534  assert( argc==2 );
164535 
164536  nOrig = sqlite3_value_bytes(argv[0]);
164537  aOrig = (const char*)sqlite3_value_blob(argv[0]);
164538  nDelta = sqlite3_value_bytes(argv[1]);
164539  aDelta = (const char*)sqlite3_value_blob(argv[1]);
164540 
164541  /* Figure out the size of the output */
164542  nOut = rbuDeltaOutputSize(aDelta, nDelta);
164543  if( nOut<0 ){
164544  sqlite3_result_error(context, "corrupt fossil delta", -1);
164545  return;
164546  }
164547 
164548  aOut = sqlite3_malloc(nOut+1);
164549  if( aOut==0 ){
164550  sqlite3_result_error_nomem(context);
164551  }else{
164552  nOut2 = rbuDeltaApply(aOrig, nOrig, aDelta, nDelta, aOut);
164553  if( nOut2!=nOut ){
164554  sqlite3_result_error(context, "corrupt fossil delta", -1);
164555  }else{
164556  sqlite3_result_blob(context, aOut, nOut, sqlite3_free);
164557  }
164558  }
164559 }
164560 
164561 
164562 /*
164563 ** Prepare the SQL statement in buffer zSql against database handle db.
164564 ** If successful, set *ppStmt to point to the new statement and return
164565 ** SQLITE_OK.
164566 **
164567 ** Otherwise, if an error does occur, set *ppStmt to NULL and return
164568 ** an SQLite error code. Additionally, set output variable *pzErrmsg to
164569 ** point to a buffer containing an error message. It is the responsibility
164570 ** of the caller to (eventually) free this buffer using sqlite3_free().
164571 */
164572 static int prepareAndCollectError(
164573  sqlite3 *db,
164574  sqlite3_stmt **ppStmt,
164575  char **pzErrmsg,
164576  const char *zSql
164577 ){
164578  int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
164579  if( rc!=SQLITE_OK ){
164580  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164581  *ppStmt = 0;
164582  }
164583  return rc;
164584 }
164585 
164586 /*
164587 ** Reset the SQL statement passed as the first argument. Return a copy
164588 ** of the value returned by sqlite3_reset().
164589 **
164590 ** If an error has occurred, then set *pzErrmsg to point to a buffer
164591 ** containing an error message. It is the responsibility of the caller
164592 ** to eventually free this buffer using sqlite3_free().
164593 */
164594 static int resetAndCollectError(sqlite3_stmt *pStmt, char **pzErrmsg){
164595  int rc = sqlite3_reset(pStmt);
164596  if( rc!=SQLITE_OK ){
164597  *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(sqlite3_db_handle(pStmt)));
164598  }
164599  return rc;
164600 }
164601 
164602 /*
164603 ** Unless it is NULL, argument zSql points to a buffer allocated using
164604 ** sqlite3_malloc containing an SQL statement. This function prepares the SQL
164605 ** statement against database db and frees the buffer. If statement
164606 ** compilation is successful, *ppStmt is set to point to the new statement
164607 ** handle and SQLITE_OK is returned.
164608 **
164609 ** Otherwise, if an error occurs, *ppStmt is set to NULL and an error code
164610 ** returned. In this case, *pzErrmsg may also be set to point to an error
164611 ** message. It is the responsibility of the caller to free this error message
164612 ** buffer using sqlite3_free().
164613 **
164614 ** If argument zSql is NULL, this function assumes that an OOM has occurred.
164615 ** In this case SQLITE_NOMEM is returned and *ppStmt set to NULL.
164616 */
164617 static int prepareFreeAndCollectError(
164618  sqlite3 *db,
164619  sqlite3_stmt **ppStmt,
164620  char **pzErrmsg,
164621  char *zSql
164622 ){
164623  int rc;
164624  assert( *pzErrmsg==0 );
164625  if( zSql==0 ){
164626  rc = SQLITE_NOMEM;
164627  *ppStmt = 0;
164628  }else{
164629  rc = prepareAndCollectError(db, ppStmt, pzErrmsg, zSql);
164630  sqlite3_free(zSql);
164631  }
164632  return rc;
164633 }
164634 
164635 /*
164636 ** Free the RbuObjIter.azTblCol[] and RbuObjIter.abTblPk[] arrays allocated
164637 ** by an earlier call to rbuObjIterCacheTableInfo().
164638 */
164639 static void rbuObjIterFreeCols(RbuObjIter *pIter){
164640  int i;
164641  for(i=0; i<pIter->nTblCol; i++){
164642  sqlite3_free(pIter->azTblCol[i]);
164643  sqlite3_free(pIter->azTblType[i]);
164644  }
164645  sqlite3_free(pIter->azTblCol);
164646  pIter->azTblCol = 0;
164647  pIter->azTblType = 0;
164648  pIter->aiSrcOrder = 0;
164649  pIter->abTblPk = 0;
164650  pIter->abNotNull = 0;
164651  pIter->nTblCol = 0;
164652  pIter->eType = 0; /* Invalid value */
164653 }
164654 
164655 /*
164656 ** Finalize all statements and free all allocations that are specific to
164657 ** the current object (table/index pair).
164658 */
164659 static void rbuObjIterClearStatements(RbuObjIter *pIter){
164660  RbuUpdateStmt *pUp;
164661 
164662  sqlite3_finalize(pIter->pSelect);
164663  sqlite3_finalize(pIter->pInsert);
164664  sqlite3_finalize(pIter->pDelete);
164665  sqlite3_finalize(pIter->pTmpInsert);
164666  pUp = pIter->pRbuUpdate;
164667  while( pUp ){
164668  RbuUpdateStmt *pTmp = pUp->pNext;
164669  sqlite3_finalize(pUp->pUpdate);
164670  sqlite3_free(pUp);
164671  pUp = pTmp;
164672  }
164673 
164674  pIter->pSelect = 0;
164675  pIter->pInsert = 0;
164676  pIter->pDelete = 0;
164677  pIter->pRbuUpdate = 0;
164678  pIter->pTmpInsert = 0;
164679  pIter->nCol = 0;
164680 }
164681 
164682 /*
164683 ** Clean up any resources allocated as part of the iterator object passed
164684 ** as the only argument.
164685 */
164686 static void rbuObjIterFinalize(RbuObjIter *pIter){
164687  rbuObjIterClearStatements(pIter);
164688  sqlite3_finalize(pIter->pTblIter);
164689  sqlite3_finalize(pIter->pIdxIter);
164690  rbuObjIterFreeCols(pIter);
164691  memset(pIter, 0, sizeof(RbuObjIter));
164692 }
164693 
164694 /*
164695 ** Advance the iterator to the next position.
164696 **
164697 ** If no error occurs, SQLITE_OK is returned and the iterator is left
164698 ** pointing to the next entry. Otherwise, an error code and message is
164699 ** left in the RBU handle passed as the first argument. A copy of the
164700 ** error code is returned.
164701 */
164702 static int rbuObjIterNext(sqlite3rbu *p, RbuObjIter *pIter){
164703  int rc = p->rc;
164704  if( rc==SQLITE_OK ){
164705 
164706  /* Free any SQLite statements used while processing the previous object */
164707  rbuObjIterClearStatements(pIter);
164708  if( pIter->zIdx==0 ){
164709  rc = sqlite3_exec(p->dbMain,
164710  "DROP TRIGGER IF EXISTS temp.rbu_insert_tr;"
164711  "DROP TRIGGER IF EXISTS temp.rbu_update1_tr;"
164712  "DROP TRIGGER IF EXISTS temp.rbu_update2_tr;"
164713  "DROP TRIGGER IF EXISTS temp.rbu_delete_tr;"
164714  , 0, 0, &p->zErrmsg
164715  );
164716  }
164717 
164718  if( rc==SQLITE_OK ){
164719  if( pIter->bCleanup ){
164720  rbuObjIterFreeCols(pIter);
164721  pIter->bCleanup = 0;
164722  rc = sqlite3_step(pIter->pTblIter);
164723  if( rc!=SQLITE_ROW ){
164724  rc = resetAndCollectError(pIter->pTblIter, &p->zErrmsg);
164725  pIter->zTbl = 0;
164726  }else{
164727  pIter->zTbl = (const char*)sqlite3_column_text(pIter->pTblIter, 0);
164728  pIter->zDataTbl = (const char*)sqlite3_column_text(pIter->pTblIter,1);
164729  rc = (pIter->zDataTbl && pIter->zTbl) ? SQLITE_OK : SQLITE_NOMEM;
164730  }
164731  }else{
164732  if( pIter->zIdx==0 ){
164733  sqlite3_stmt *pIdx = pIter->pIdxIter;
164734  rc = sqlite3_bind_text(pIdx, 1, pIter->zTbl, -1, SQLITE_STATIC);
164735  }
164736  if( rc==SQLITE_OK ){
164737  rc = sqlite3_step(pIter->pIdxIter);
164738  if( rc!=SQLITE_ROW ){
164739  rc = resetAndCollectError(pIter->pIdxIter, &p->zErrmsg);
164740  pIter->bCleanup = 1;
164741  pIter->zIdx = 0;
164742  }else{
164743  pIter->zIdx = (const char*)sqlite3_column_text(pIter->pIdxIter, 0);
164744  pIter->iTnum = sqlite3_column_int(pIter->pIdxIter, 1);
164745  pIter->bUnique = sqlite3_column_int(pIter->pIdxIter, 2);
164746  rc = pIter->zIdx ? SQLITE_OK : SQLITE_NOMEM;
164747  }
164748  }
164749  }
164750  }
164751  }
164752 
164753  if( rc!=SQLITE_OK ){
164754  rbuObjIterFinalize(pIter);
164755  p->rc = rc;
164756  }
164757  return rc;
164758 }
164759 
164760 
164761 /*
164762 ** The implementation of the rbu_target_name() SQL function. This function
164763 ** accepts one or two arguments. The first argument is the name of a table -
164764 ** the name of a table in the RBU database. The second, if it is present, is 1
164765 ** for a view or 0 for a table.
164766 **
164767 ** For a non-vacuum RBU handle, if the table name matches the pattern:
164768 **
164769 ** data[0-9]_<name>
164770 **
164771 ** where <name> is any sequence of 1 or more characters, <name> is returned.
164772 ** Otherwise, if the only argument does not match the above pattern, an SQL
164773 ** NULL is returned.
164774 **
164775 ** "data_t1" -> "t1"
164776 ** "data0123_t2" -> "t2"
164777 ** "dataAB_t3" -> NULL
164778 **
164779 ** For an rbu vacuum handle, a copy of the first argument is returned if
164780 ** the second argument is either missing or 0 (not a view).
164781 */
164782 static void rbuTargetNameFunc(
164783  sqlite3_context *pCtx,
164784  int argc,
164785  sqlite3_value **argv
164786 ){
164787  sqlite3rbu *p = sqlite3_user_data(pCtx);
164788  const char *zIn;
164789  assert( argc==1 || argc==2 );
164790 
164791  zIn = (const char*)sqlite3_value_text(argv[0]);
164792  if( zIn ){
164793  if( rbuIsVacuum(p) ){
164794  if( argc==1 || 0==sqlite3_value_int(argv[1]) ){
164795  sqlite3_result_text(pCtx, zIn, -1, SQLITE_STATIC);
164796  }
164797  }else{
164798  if( strlen(zIn)>4 && memcmp("data", zIn, 4)==0 ){
164799  int i;
164800  for(i=4; zIn[i]>='0' && zIn[i]<='9'; i++);
164801  if( zIn[i]=='_' && zIn[i+1] ){
164802  sqlite3_result_text(pCtx, &zIn[i+1], -1, SQLITE_STATIC);
164803  }
164804  }
164805  }
164806  }
164807 }
164808 
164809 /*
164810 ** Initialize the iterator structure passed as the second argument.
164811 **
164812 ** If no error occurs, SQLITE_OK is returned and the iterator is left
164813 ** pointing to the first entry. Otherwise, an error code and message is
164814 ** left in the RBU handle passed as the first argument. A copy of the
164815 ** error code is returned.
164816 */
164817 static int rbuObjIterFirst(sqlite3rbu *p, RbuObjIter *pIter){
164818  int rc;
164819  memset(pIter, 0, sizeof(RbuObjIter));
164820 
164821  rc = prepareAndCollectError(p->dbRbu, &pIter->pTblIter, &p->zErrmsg,
164822  "SELECT rbu_target_name(name, type='view') AS target, name "
164823  "FROM sqlite_master "
164824  "WHERE type IN ('table', 'view') AND target IS NOT NULL "
164825  "ORDER BY name"
164826  );
164827 
164828  if( rc==SQLITE_OK ){
164829  rc = prepareAndCollectError(p->dbMain, &pIter->pIdxIter, &p->zErrmsg,
164830  "SELECT name, rootpage, sql IS NULL OR substr(8, 6)=='UNIQUE' "
164831  " FROM main.sqlite_master "
164832  " WHERE type='index' AND tbl_name = ?"
164833  );
164834  }
164835 
164836  pIter->bCleanup = 1;
164837  p->rc = rc;
164838  return rbuObjIterNext(p, pIter);
164839 }
164840 
164841 /*
164842 ** This is a wrapper around "sqlite3_mprintf(zFmt, ...)". If an OOM occurs,
164843 ** an error code is stored in the RBU handle passed as the first argument.
164844 **
164845 ** If an error has already occurred (p->rc is already set to something other
164846 ** than SQLITE_OK), then this function returns NULL without modifying the
164847 ** stored error code. In this case it still calls sqlite3_free() on any
164848 ** printf() parameters associated with %z conversions.
164849 */
164850 static char *rbuMPrintf(sqlite3rbu *p, const char *zFmt, ...){
164851  char *zSql = 0;
164852  va_list ap;
164853  va_start(ap, zFmt);
164854  zSql = sqlite3_vmprintf(zFmt, ap);
164855  if( p->rc==SQLITE_OK ){
164856  if( zSql==0 ) p->rc = SQLITE_NOMEM;
164857  }else{
164858  sqlite3_free(zSql);
164859  zSql = 0;
164860  }
164861  va_end(ap);
164862  return zSql;
164863 }
164864 
164865 /*
164866 ** Argument zFmt is a sqlite3_mprintf() style format string. The trailing
164867 ** arguments are the usual subsitution values. This function performs
164868 ** the printf() style substitutions and executes the result as an SQL
164869 ** statement on the RBU handles database.
164870 **
164871 ** If an error occurs, an error code and error message is stored in the
164872 ** RBU handle. If an error has already occurred when this function is
164873 ** called, it is a no-op.
164874 */
164875 static int rbuMPrintfExec(sqlite3rbu *p, sqlite3 *db, const char *zFmt, ...){
164876  va_list ap;
164877  char *zSql;
164878  va_start(ap, zFmt);
164879  zSql = sqlite3_vmprintf(zFmt, ap);
164880  if( p->rc==SQLITE_OK ){
164881  if( zSql==0 ){
164882  p->rc = SQLITE_NOMEM;
164883  }else{
164884  p->rc = sqlite3_exec(db, zSql, 0, 0, &p->zErrmsg);
164885  }
164886  }
164887  sqlite3_free(zSql);
164888  va_end(ap);
164889  return p->rc;
164890 }
164891 
164892 /*
164893 ** Attempt to allocate and return a pointer to a zeroed block of nByte
164894 ** bytes.
164895 **
164896 ** If an error (i.e. an OOM condition) occurs, return NULL and leave an
164897 ** error code in the rbu handle passed as the first argument. Or, if an
164898 ** error has already occurred when this function is called, return NULL
164899 ** immediately without attempting the allocation or modifying the stored
164900 ** error code.
164901 */
164902 static void *rbuMalloc(sqlite3rbu *p, int nByte){
164903  void *pRet = 0;
164904  if( p->rc==SQLITE_OK ){
164905  assert( nByte>0 );
164906  pRet = sqlite3_malloc64(nByte);
164907  if( pRet==0 ){
164908  p->rc = SQLITE_NOMEM;
164909  }else{
164910  memset(pRet, 0, nByte);
164911  }
164912  }
164913  return pRet;
164914 }
164915 
164916 
164917 /*
164918 ** Allocate and zero the pIter->azTblCol[] and abTblPk[] arrays so that
164919 ** there is room for at least nCol elements. If an OOM occurs, store an
164920 ** error code in the RBU handle passed as the first argument.
164921 */
164922 static void rbuAllocateIterArrays(sqlite3rbu *p, RbuObjIter *pIter, int nCol){
164923  int nByte = (2*sizeof(char*) + sizeof(int) + 3*sizeof(u8)) * nCol;
164924  char **azNew;
164925 
164926  azNew = (char**)rbuMalloc(p, nByte);
164927  if( azNew ){
164928  pIter->azTblCol = azNew;
164929  pIter->azTblType = &azNew[nCol];
164930  pIter->aiSrcOrder = (int*)&pIter->azTblType[nCol];
164931  pIter->abTblPk = (u8*)&pIter->aiSrcOrder[nCol];
164932  pIter->abNotNull = (u8*)&pIter->abTblPk[nCol];
164933  pIter->abIndexed = (u8*)&pIter->abNotNull[nCol];
164934  }
164935 }
164936 
164937 /*
164938 ** The first argument must be a nul-terminated string. This function
164939 ** returns a copy of the string in memory obtained from sqlite3_malloc().
164940 ** It is the responsibility of the caller to eventually free this memory
164941 ** using sqlite3_free().
164942 **
164943 ** If an OOM condition is encountered when attempting to allocate memory,
164944 ** output variable (*pRc) is set to SQLITE_NOMEM before returning. Otherwise,
164945 ** if the allocation succeeds, (*pRc) is left unchanged.
164946 */
164947 static char *rbuStrndup(const char *zStr, int *pRc){
164948  char *zRet = 0;
164949 
164950  assert( *pRc==SQLITE_OK );
164951  if( zStr ){
164952  size_t nCopy = strlen(zStr) + 1;
164953  zRet = (char*)sqlite3_malloc64(nCopy);
164954  if( zRet ){
164955  memcpy(zRet, zStr, nCopy);
164956  }else{
164957  *pRc = SQLITE_NOMEM;
164958  }
164959  }
164960 
164961  return zRet;
164962 }
164963 
164964 /*
164965 ** Finalize the statement passed as the second argument.
164966 **
164967 ** If the sqlite3_finalize() call indicates that an error occurs, and the
164968 ** rbu handle error code is not already set, set the error code and error
164969 ** message accordingly.
164970 */
164971 static void rbuFinalize(sqlite3rbu *p, sqlite3_stmt *pStmt){
164972  sqlite3 *db = sqlite3_db_handle(pStmt);
164973  int rc = sqlite3_finalize(pStmt);
164974  if( p->rc==SQLITE_OK && rc!=SQLITE_OK ){
164975  p->rc = rc;
164976  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
164977  }
164978 }
164979 
164980 /* Determine the type of a table.
164981 **
164982 ** peType is of type (int*), a pointer to an output parameter of type
164983 ** (int). This call sets the output parameter as follows, depending
164984 ** on the type of the table specified by parameters dbName and zTbl.
164985 **
164986 ** RBU_PK_NOTABLE: No such table.
164987 ** RBU_PK_NONE: Table has an implicit rowid.
164988 ** RBU_PK_IPK: Table has an explicit IPK column.
164989 ** RBU_PK_EXTERNAL: Table has an external PK index.
164990 ** RBU_PK_WITHOUT_ROWID: Table is WITHOUT ROWID.
164991 ** RBU_PK_VTAB: Table is a virtual table.
164992 **
164993 ** Argument *piPk is also of type (int*), and also points to an output
164994 ** parameter. Unless the table has an external primary key index
164995 ** (i.e. unless *peType is set to 3), then *piPk is set to zero. Or,
164996 ** if the table does have an external primary key index, then *piPk
164997 ** is set to the root page number of the primary key index before
164998 ** returning.
164999 **
165000 ** ALGORITHM:
165001 **
165002 ** if( no entry exists in sqlite_master ){
165003 ** return RBU_PK_NOTABLE
165004 ** }else if( sql for the entry starts with "CREATE VIRTUAL" ){
165005 ** return RBU_PK_VTAB
165006 ** }else if( "PRAGMA index_list()" for the table contains a "pk" index ){
165007 ** if( the index that is the pk exists in sqlite_master ){
165008 ** *piPK = rootpage of that index.
165009 ** return RBU_PK_EXTERNAL
165010 ** }else{
165011 ** return RBU_PK_WITHOUT_ROWID
165012 ** }
165013 ** }else if( "PRAGMA table_info()" lists one or more "pk" columns ){
165014 ** return RBU_PK_IPK
165015 ** }else{
165016 ** return RBU_PK_NONE
165017 ** }
165018 */
165019 static void rbuTableType(
165020  sqlite3rbu *p,
165021  const char *zTab,
165022  int *peType,
165023  int *piTnum,
165024  int *piPk
165025 ){
165026  /*
165027  ** 0) SELECT count(*) FROM sqlite_master where name=%Q AND IsVirtual(%Q)
165028  ** 1) PRAGMA index_list = ?
165029  ** 2) SELECT count(*) FROM sqlite_master where name=%Q
165030  ** 3) PRAGMA table_info = ?
165031  */
165032  sqlite3_stmt *aStmt[4] = {0, 0, 0, 0};
165033 
165034  *peType = RBU_PK_NOTABLE;
165035  *piPk = 0;
165036 
165037  assert( p->rc==SQLITE_OK );
165038  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[0], &p->zErrmsg,
165039  sqlite3_mprintf(
165040  "SELECT (sql LIKE 'create virtual%%'), rootpage"
165041  " FROM sqlite_master"
165042  " WHERE name=%Q", zTab
165043  ));
165044  if( p->rc!=SQLITE_OK || sqlite3_step(aStmt[0])!=SQLITE_ROW ){
165045  /* Either an error, or no such table. */
165046  goto rbuTableType_end;
165047  }
165048  if( sqlite3_column_int(aStmt[0], 0) ){
165049  *peType = RBU_PK_VTAB; /* virtual table */
165050  goto rbuTableType_end;
165051  }
165052  *piTnum = sqlite3_column_int(aStmt[0], 1);
165053 
165054  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[1], &p->zErrmsg,
165055  sqlite3_mprintf("PRAGMA index_list=%Q",zTab)
165056  );
165057  if( p->rc ) goto rbuTableType_end;
165058  while( sqlite3_step(aStmt[1])==SQLITE_ROW ){
165059  const u8 *zOrig = sqlite3_column_text(aStmt[1], 3);
165060  const u8 *zIdx = sqlite3_column_text(aStmt[1], 1);
165061  if( zOrig && zIdx && zOrig[0]=='p' ){
165062  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[2], &p->zErrmsg,
165063  sqlite3_mprintf(
165064  "SELECT rootpage FROM sqlite_master WHERE name = %Q", zIdx
165065  ));
165066  if( p->rc==SQLITE_OK ){
165067  if( sqlite3_step(aStmt[2])==SQLITE_ROW ){
165068  *piPk = sqlite3_column_int(aStmt[2], 0);
165069  *peType = RBU_PK_EXTERNAL;
165070  }else{
165071  *peType = RBU_PK_WITHOUT_ROWID;
165072  }
165073  }
165074  goto rbuTableType_end;
165075  }
165076  }
165077 
165078  p->rc = prepareFreeAndCollectError(p->dbMain, &aStmt[3], &p->zErrmsg,
165079  sqlite3_mprintf("PRAGMA table_info=%Q",zTab)
165080  );
165081  if( p->rc==SQLITE_OK ){
165082  while( sqlite3_step(aStmt[3])==SQLITE_ROW ){
165083  if( sqlite3_column_int(aStmt[3],5)>0 ){
165084  *peType = RBU_PK_IPK; /* explicit IPK column */
165085  goto rbuTableType_end;
165086  }
165087  }
165088  *peType = RBU_PK_NONE;
165089  }
165090 
165091 rbuTableType_end: {
165092  unsigned int i;
165093  for(i=0; i<sizeof(aStmt)/sizeof(aStmt[0]); i++){
165094  rbuFinalize(p, aStmt[i]);
165095  }
165096  }
165097 }
165098 
165099 /*
165100 ** This is a helper function for rbuObjIterCacheTableInfo(). It populates
165101 ** the pIter->abIndexed[] array.
165102 */
165103 static void rbuObjIterCacheIndexedCols(sqlite3rbu *p, RbuObjIter *pIter){
165104  sqlite3_stmt *pList = 0;
165105  int bIndex = 0;
165106 
165107  if( p->rc==SQLITE_OK ){
165108  memcpy(pIter->abIndexed, pIter->abTblPk, sizeof(u8)*pIter->nTblCol);
165109  p->rc = prepareFreeAndCollectError(p->dbMain, &pList, &p->zErrmsg,
165110  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
165111  );
165112  }
165113 
165114  pIter->nIndex = 0;
165115  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pList) ){
165116  const char *zIdx = (const char*)sqlite3_column_text(pList, 1);
165117  sqlite3_stmt *pXInfo = 0;
165118  if( zIdx==0 ) break;
165119  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
165120  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
165121  );
165122  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
165123  int iCid = sqlite3_column_int(pXInfo, 1);
165124  if( iCid>=0 ) pIter->abIndexed[iCid] = 1;
165125  }
165126  rbuFinalize(p, pXInfo);
165127  bIndex = 1;
165128  pIter->nIndex++;
165129  }
165130 
165131  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
165132  /* "PRAGMA index_list" includes the main PK b-tree */
165133  pIter->nIndex--;
165134  }
165135 
165136  rbuFinalize(p, pList);
165137  if( bIndex==0 ) pIter->abIndexed = 0;
165138 }
165139 
165140 
165141 /*
165142 ** If they are not already populated, populate the pIter->azTblCol[],
165143 ** pIter->abTblPk[], pIter->nTblCol and pIter->bRowid variables according to
165144 ** the table (not index) that the iterator currently points to.
165145 **
165146 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. If
165147 ** an error does occur, an error code and error message are also left in
165148 ** the RBU handle.
165149 */
165150 static int rbuObjIterCacheTableInfo(sqlite3rbu *p, RbuObjIter *pIter){
165151  if( pIter->azTblCol==0 ){
165152  sqlite3_stmt *pStmt = 0;
165153  int nCol = 0;
165154  int i; /* for() loop iterator variable */
165155  int bRbuRowid = 0; /* If input table has column "rbu_rowid" */
165156  int iOrder = 0;
165157  int iTnum = 0;
165158 
165159  /* Figure out the type of table this step will deal with. */
165160  assert( pIter->eType==0 );
165161  rbuTableType(p, pIter->zTbl, &pIter->eType, &iTnum, &pIter->iPkTnum);
165162  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_NOTABLE ){
165163  p->rc = SQLITE_ERROR;
165164  p->zErrmsg = sqlite3_mprintf("no such table: %s", pIter->zTbl);
165165  }
165166  if( p->rc ) return p->rc;
165167  if( pIter->zIdx==0 ) pIter->iTnum = iTnum;
165168 
165169  assert( pIter->eType==RBU_PK_NONE || pIter->eType==RBU_PK_IPK
165170  || pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_WITHOUT_ROWID
165171  || pIter->eType==RBU_PK_VTAB
165172  );
165173 
165174  /* Populate the azTblCol[] and nTblCol variables based on the columns
165175  ** of the input table. Ignore any input table columns that begin with
165176  ** "rbu_". */
165177  p->rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
165178  sqlite3_mprintf("SELECT * FROM '%q'", pIter->zDataTbl)
165179  );
165180  if( p->rc==SQLITE_OK ){
165181  nCol = sqlite3_column_count(pStmt);
165182  rbuAllocateIterArrays(p, pIter, nCol);
165183  }
165184  for(i=0; p->rc==SQLITE_OK && i<nCol; i++){
165185  const char *zName = (const char*)sqlite3_column_name(pStmt, i);
165186  if( sqlite3_strnicmp("rbu_", zName, 4) ){
165187  char *zCopy = rbuStrndup(zName, &p->rc);
165188  pIter->aiSrcOrder[pIter->nTblCol] = pIter->nTblCol;
165189  pIter->azTblCol[pIter->nTblCol++] = zCopy;
165190  }
165191  else if( 0==sqlite3_stricmp("rbu_rowid", zName) ){
165192  bRbuRowid = 1;
165193  }
165194  }
165195  sqlite3_finalize(pStmt);
165196  pStmt = 0;
165197 
165198  if( p->rc==SQLITE_OK
165199  && rbuIsVacuum(p)==0
165200  && bRbuRowid!=(pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
165201  ){
165202  p->rc = SQLITE_ERROR;
165203  p->zErrmsg = sqlite3_mprintf(
165204  "table %q %s rbu_rowid column", pIter->zDataTbl,
165205  (bRbuRowid ? "may not have" : "requires")
165206  );
165207  }
165208 
165209  /* Check that all non-HIDDEN columns in the destination table are also
165210  ** present in the input table. Populate the abTblPk[], azTblType[] and
165211  ** aiTblOrder[] arrays at the same time. */
165212  if( p->rc==SQLITE_OK ){
165213  p->rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &p->zErrmsg,
165214  sqlite3_mprintf("PRAGMA table_info(%Q)", pIter->zTbl)
165215  );
165216  }
165217  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
165218  const char *zName = (const char*)sqlite3_column_text(pStmt, 1);
165219  if( zName==0 ) break; /* An OOM - finalize() below returns S_NOMEM */
165220  for(i=iOrder; i<pIter->nTblCol; i++){
165221  if( 0==strcmp(zName, pIter->azTblCol[i]) ) break;
165222  }
165223  if( i==pIter->nTblCol ){
165224  p->rc = SQLITE_ERROR;
165225  p->zErrmsg = sqlite3_mprintf("column missing from %q: %s",
165226  pIter->zDataTbl, zName
165227  );
165228  }else{
165229  int iPk = sqlite3_column_int(pStmt, 5);
165230  int bNotNull = sqlite3_column_int(pStmt, 3);
165231  const char *zType = (const char*)sqlite3_column_text(pStmt, 2);
165232 
165233  if( i!=iOrder ){
165234  SWAP(int, pIter->aiSrcOrder[i], pIter->aiSrcOrder[iOrder]);
165235  SWAP(char*, pIter->azTblCol[i], pIter->azTblCol[iOrder]);
165236  }
165237 
165238  pIter->azTblType[iOrder] = rbuStrndup(zType, &p->rc);
165239  pIter->abTblPk[iOrder] = (iPk!=0);
165240  pIter->abNotNull[iOrder] = (u8)bNotNull || (iPk!=0);
165241  iOrder++;
165242  }
165243  }
165244 
165245  rbuFinalize(p, pStmt);
165246  rbuObjIterCacheIndexedCols(p, pIter);
165247  assert( pIter->eType!=RBU_PK_VTAB || pIter->abIndexed==0 );
165248  assert( pIter->eType!=RBU_PK_VTAB || pIter->nIndex==0 );
165249  }
165250 
165251  return p->rc;
165252 }
165253 
165254 /*
165255 ** This function constructs and returns a pointer to a nul-terminated
165256 ** string containing some SQL clause or list based on one or more of the
165257 ** column names currently stored in the pIter->azTblCol[] array.
165258 */
165259 static char *rbuObjIterGetCollist(
165260  sqlite3rbu *p, /* RBU object */
165261  RbuObjIter *pIter /* Object iterator for column names */
165262 ){
165263  char *zList = 0;
165264  const char *zSep = "";
165265  int i;
165266  for(i=0; i<pIter->nTblCol; i++){
165267  const char *z = pIter->azTblCol[i];
165268  zList = rbuMPrintf(p, "%z%s\"%w\"", zList, zSep, z);
165269  zSep = ", ";
165270  }
165271  return zList;
165272 }
165273 
165274 /*
165275 ** This function is used to create a SELECT list (the list of SQL
165276 ** expressions that follows a SELECT keyword) for a SELECT statement
165277 ** used to read from an data_xxx or rbu_tmp_xxx table while updating the
165278 ** index object currently indicated by the iterator object passed as the
165279 ** second argument. A "PRAGMA index_xinfo = <idxname>" statement is used
165280 ** to obtain the required information.
165281 **
165282 ** If the index is of the following form:
165283 **
165284 ** CREATE INDEX i1 ON t1(c, b COLLATE nocase);
165285 **
165286 ** and "t1" is a table with an explicit INTEGER PRIMARY KEY column
165287 ** "ipk", the returned string is:
165288 **
165289 ** "`c` COLLATE 'BINARY', `b` COLLATE 'NOCASE', `ipk` COLLATE 'BINARY'"
165290 **
165291 ** As well as the returned string, three other malloc'd strings are
165292 ** returned via output parameters. As follows:
165293 **
165294 ** pzImposterCols: ...
165295 ** pzImposterPk: ...
165296 ** pzWhere: ...
165297 */
165298 static char *rbuObjIterGetIndexCols(
165299  sqlite3rbu *p, /* RBU object */
165300  RbuObjIter *pIter, /* Object iterator for column names */
165301  char **pzImposterCols, /* OUT: Columns for imposter table */
165302  char **pzImposterPk, /* OUT: Imposter PK clause */
165303  char **pzWhere, /* OUT: WHERE clause */
165304  int *pnBind /* OUT: Trbul number of columns */
165305 ){
165306  int rc = p->rc; /* Error code */
165307  int rc2; /* sqlite3_finalize() return code */
165308  char *zRet = 0; /* String to return */
165309  char *zImpCols = 0; /* String to return via *pzImposterCols */
165310  char *zImpPK = 0; /* String to return via *pzImposterPK */
165311  char *zWhere = 0; /* String to return via *pzWhere */
165312  int nBind = 0; /* Value to return via *pnBind */
165313  const char *zCom = ""; /* Set to ", " later on */
165314  const char *zAnd = ""; /* Set to " AND " later on */
165315  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = ? */
165316 
165317  if( rc==SQLITE_OK ){
165318  assert( p->zErrmsg==0 );
165319  rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
165320  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", pIter->zIdx)
165321  );
165322  }
165323 
165324  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
165325  int iCid = sqlite3_column_int(pXInfo, 1);
165326  int bDesc = sqlite3_column_int(pXInfo, 3);
165327  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
165328  const char *zCol;
165329  const char *zType;
165330 
165331  if( iCid<0 ){
165332  /* An integer primary key. If the table has an explicit IPK, use
165333  ** its name. Otherwise, use "rbu_rowid". */
165334  if( pIter->eType==RBU_PK_IPK ){
165335  int i;
165336  for(i=0; pIter->abTblPk[i]==0; i++);
165337  assert( i<pIter->nTblCol );
165338  zCol = pIter->azTblCol[i];
165339  }else if( rbuIsVacuum(p) ){
165340  zCol = "_rowid_";
165341  }else{
165342  zCol = "rbu_rowid";
165343  }
165344  zType = "INTEGER";
165345  }else{
165346  zCol = pIter->azTblCol[iCid];
165347  zType = pIter->azTblType[iCid];
165348  }
165349 
165350  zRet = sqlite3_mprintf("%z%s\"%w\" COLLATE %Q", zRet, zCom, zCol, zCollate);
165351  if( pIter->bUnique==0 || sqlite3_column_int(pXInfo, 5) ){
165352  const char *zOrder = (bDesc ? " DESC" : "");
165353  zImpPK = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\"%s",
165354  zImpPK, zCom, nBind, zCol, zOrder
165355  );
165356  }
165357  zImpCols = sqlite3_mprintf("%z%s\"rbu_imp_%d%w\" %s COLLATE %Q",
165358  zImpCols, zCom, nBind, zCol, zType, zCollate
165359  );
165360  zWhere = sqlite3_mprintf(
165361  "%z%s\"rbu_imp_%d%w\" IS ?", zWhere, zAnd, nBind, zCol
165362  );
165363  if( zRet==0 || zImpPK==0 || zImpCols==0 || zWhere==0 ) rc = SQLITE_NOMEM;
165364  zCom = ", ";
165365  zAnd = " AND ";
165366  nBind++;
165367  }
165368 
165369  rc2 = sqlite3_finalize(pXInfo);
165370  if( rc==SQLITE_OK ) rc = rc2;
165371 
165372  if( rc!=SQLITE_OK ){
165373  sqlite3_free(zRet);
165374  sqlite3_free(zImpCols);
165375  sqlite3_free(zImpPK);
165376  sqlite3_free(zWhere);
165377  zRet = 0;
165378  zImpCols = 0;
165379  zImpPK = 0;
165380  zWhere = 0;
165381  p->rc = rc;
165382  }
165383 
165384  *pzImposterCols = zImpCols;
165385  *pzImposterPk = zImpPK;
165386  *pzWhere = zWhere;
165387  *pnBind = nBind;
165388  return zRet;
165389 }
165390 
165391 /*
165392 ** Assuming the current table columns are "a", "b" and "c", and the zObj
165393 ** paramter is passed "old", return a string of the form:
165394 **
165395 ** "old.a, old.b, old.b"
165396 **
165397 ** With the column names escaped.
165398 **
165399 ** For tables with implicit rowids - RBU_PK_EXTERNAL and RBU_PK_NONE, append
165400 ** the text ", old._rowid_" to the returned value.
165401 */
165402 static char *rbuObjIterGetOldlist(
165403  sqlite3rbu *p,
165404  RbuObjIter *pIter,
165405  const char *zObj
165406 ){
165407  char *zList = 0;
165408  if( p->rc==SQLITE_OK && pIter->abIndexed ){
165409  const char *zS = "";
165410  int i;
165411  for(i=0; i<pIter->nTblCol; i++){
165412  if( pIter->abIndexed[i] ){
165413  const char *zCol = pIter->azTblCol[i];
165414  zList = sqlite3_mprintf("%z%s%s.\"%w\"", zList, zS, zObj, zCol);
165415  }else{
165416  zList = sqlite3_mprintf("%z%sNULL", zList, zS);
165417  }
165418  zS = ", ";
165419  if( zList==0 ){
165420  p->rc = SQLITE_NOMEM;
165421  break;
165422  }
165423  }
165424 
165425  /* For a table with implicit rowids, append "old._rowid_" to the list. */
165426  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
165427  zList = rbuMPrintf(p, "%z, %s._rowid_", zList, zObj);
165428  }
165429  }
165430  return zList;
165431 }
165432 
165433 /*
165434 ** Return an expression that can be used in a WHERE clause to match the
165435 ** primary key of the current table. For example, if the table is:
165436 **
165437 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, c));
165438 **
165439 ** Return the string:
165440 **
165441 ** "b = ?1 AND c = ?2"
165442 */
165443 static char *rbuObjIterGetWhere(
165444  sqlite3rbu *p,
165445  RbuObjIter *pIter
165446 ){
165447  char *zList = 0;
165448  if( pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE ){
165449  zList = rbuMPrintf(p, "_rowid_ = ?%d", pIter->nTblCol+1);
165450  }else if( pIter->eType==RBU_PK_EXTERNAL ){
165451  const char *zSep = "";
165452  int i;
165453  for(i=0; i<pIter->nTblCol; i++){
165454  if( pIter->abTblPk[i] ){
165455  zList = rbuMPrintf(p, "%z%sc%d=?%d", zList, zSep, i, i+1);
165456  zSep = " AND ";
165457  }
165458  }
165459  zList = rbuMPrintf(p,
165460  "_rowid_ = (SELECT id FROM rbu_imposter2 WHERE %z)", zList
165461  );
165462 
165463  }else{
165464  const char *zSep = "";
165465  int i;
165466  for(i=0; i<pIter->nTblCol; i++){
165467  if( pIter->abTblPk[i] ){
165468  const char *zCol = pIter->azTblCol[i];
165469  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d", zList, zSep, zCol, i+1);
165470  zSep = " AND ";
165471  }
165472  }
165473  }
165474  return zList;
165475 }
165476 
165477 /*
165478 ** The SELECT statement iterating through the keys for the current object
165479 ** (p->objiter.pSelect) currently points to a valid row. However, there
165480 ** is something wrong with the rbu_control value in the rbu_control value
165481 ** stored in the (p->nCol+1)'th column. Set the error code and error message
165482 ** of the RBU handle to something reflecting this.
165483 */
165484 static void rbuBadControlError(sqlite3rbu *p){
165485  p->rc = SQLITE_ERROR;
165486  p->zErrmsg = sqlite3_mprintf("invalid rbu_control value");
165487 }
165488 
165489 
165490 /*
165491 ** Return a nul-terminated string containing the comma separated list of
165492 ** assignments that should be included following the "SET" keyword of
165493 ** an UPDATE statement used to update the table object that the iterator
165494 ** passed as the second argument currently points to if the rbu_control
165495 ** column of the data_xxx table entry is set to zMask.
165496 **
165497 ** The memory for the returned string is obtained from sqlite3_malloc().
165498 ** It is the responsibility of the caller to eventually free it using
165499 ** sqlite3_free().
165500 **
165501 ** If an OOM error is encountered when allocating space for the new
165502 ** string, an error code is left in the rbu handle passed as the first
165503 ** argument and NULL is returned. Or, if an error has already occurred
165504 ** when this function is called, NULL is returned immediately, without
165505 ** attempting the allocation or modifying the stored error code.
165506 */
165507 static char *rbuObjIterGetSetlist(
165508  sqlite3rbu *p,
165509  RbuObjIter *pIter,
165510  const char *zMask
165511 ){
165512  char *zList = 0;
165513  if( p->rc==SQLITE_OK ){
165514  int i;
165515 
165516  if( (int)strlen(zMask)!=pIter->nTblCol ){
165517  rbuBadControlError(p);
165518  }else{
165519  const char *zSep = "";
165520  for(i=0; i<pIter->nTblCol; i++){
165521  char c = zMask[pIter->aiSrcOrder[i]];
165522  if( c=='x' ){
165523  zList = rbuMPrintf(p, "%z%s\"%w\"=?%d",
165524  zList, zSep, pIter->azTblCol[i], i+1
165525  );
165526  zSep = ", ";
165527  }
165528  else if( c=='d' ){
165529  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_delta(\"%w\", ?%d)",
165530  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
165531  );
165532  zSep = ", ";
165533  }
165534  else if( c=='f' ){
165535  zList = rbuMPrintf(p, "%z%s\"%w\"=rbu_fossil_delta(\"%w\", ?%d)",
165536  zList, zSep, pIter->azTblCol[i], pIter->azTblCol[i], i+1
165537  );
165538  zSep = ", ";
165539  }
165540  }
165541  }
165542  }
165543  return zList;
165544 }
165545 
165546 /*
165547 ** Return a nul-terminated string consisting of nByte comma separated
165548 ** "?" expressions. For example, if nByte is 3, return a pointer to
165549 ** a buffer containing the string "?,?,?".
165550 **
165551 ** The memory for the returned string is obtained from sqlite3_malloc().
165552 ** It is the responsibility of the caller to eventually free it using
165553 ** sqlite3_free().
165554 **
165555 ** If an OOM error is encountered when allocating space for the new
165556 ** string, an error code is left in the rbu handle passed as the first
165557 ** argument and NULL is returned. Or, if an error has already occurred
165558 ** when this function is called, NULL is returned immediately, without
165559 ** attempting the allocation or modifying the stored error code.
165560 */
165561 static char *rbuObjIterGetBindlist(sqlite3rbu *p, int nBind){
165562  char *zRet = 0;
165563  int nByte = nBind*2 + 1;
165564 
165565  zRet = (char*)rbuMalloc(p, nByte);
165566  if( zRet ){
165567  int i;
165568  for(i=0; i<nBind; i++){
165569  zRet[i*2] = '?';
165570  zRet[i*2+1] = (i+1==nBind) ? '\0' : ',';
165571  }
165572  }
165573  return zRet;
165574 }
165575 
165576 /*
165577 ** The iterator currently points to a table (not index) of type
165578 ** RBU_PK_WITHOUT_ROWID. This function creates the PRIMARY KEY
165579 ** declaration for the corresponding imposter table. For example,
165580 ** if the iterator points to a table created as:
165581 **
165582 ** CREATE TABLE t1(a, b, c, PRIMARY KEY(b, a DESC)) WITHOUT ROWID
165583 **
165584 ** this function returns:
165585 **
165586 ** PRIMARY KEY("b", "a" DESC)
165587 */
165588 static char *rbuWithoutRowidPK(sqlite3rbu *p, RbuObjIter *pIter){
165589  char *z = 0;
165590  assert( pIter->zIdx==0 );
165591  if( p->rc==SQLITE_OK ){
165592  const char *zSep = "PRIMARY KEY(";
165593  sqlite3_stmt *pXList = 0; /* PRAGMA index_list = (pIter->zTbl) */
165594  sqlite3_stmt *pXInfo = 0; /* PRAGMA index_xinfo = <pk-index> */
165595 
165596  p->rc = prepareFreeAndCollectError(p->dbMain, &pXList, &p->zErrmsg,
165597  sqlite3_mprintf("PRAGMA main.index_list = %Q", pIter->zTbl)
165598  );
165599  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXList) ){
165600  const char *zOrig = (const char*)sqlite3_column_text(pXList,3);
165601  if( zOrig && strcmp(zOrig, "pk")==0 ){
165602  const char *zIdx = (const char*)sqlite3_column_text(pXList,1);
165603  if( zIdx ){
165604  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
165605  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
165606  );
165607  }
165608  break;
165609  }
165610  }
165611  rbuFinalize(p, pXList);
165612 
165613  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
165614  if( sqlite3_column_int(pXInfo, 5) ){
165615  /* int iCid = sqlite3_column_int(pXInfo, 0); */
165616  const char *zCol = (const char*)sqlite3_column_text(pXInfo, 2);
165617  const char *zDesc = sqlite3_column_int(pXInfo, 3) ? " DESC" : "";
165618  z = rbuMPrintf(p, "%z%s\"%w\"%s", z, zSep, zCol, zDesc);
165619  zSep = ", ";
165620  }
165621  }
165622  z = rbuMPrintf(p, "%z)", z);
165623  rbuFinalize(p, pXInfo);
165624  }
165625  return z;
165626 }
165627 
165628 /*
165629 ** This function creates the second imposter table used when writing to
165630 ** a table b-tree where the table has an external primary key. If the
165631 ** iterator passed as the second argument does not currently point to
165632 ** a table (not index) with an external primary key, this function is a
165633 ** no-op.
165634 **
165635 ** Assuming the iterator does point to a table with an external PK, this
165636 ** function creates a WITHOUT ROWID imposter table named "rbu_imposter2"
165637 ** used to access that PK index. For example, if the target table is
165638 ** declared as follows:
165639 **
165640 ** CREATE TABLE t1(a, b TEXT, c REAL, PRIMARY KEY(b, c));
165641 **
165642 ** then the imposter table schema is:
165643 **
165644 ** CREATE TABLE rbu_imposter2(c1 TEXT, c2 REAL, id INTEGER) WITHOUT ROWID;
165645 **
165646 */
165647 static void rbuCreateImposterTable2(sqlite3rbu *p, RbuObjIter *pIter){
165648  if( p->rc==SQLITE_OK && pIter->eType==RBU_PK_EXTERNAL ){
165649  int tnum = pIter->iPkTnum; /* Root page of PK index */
165650  sqlite3_stmt *pQuery = 0; /* SELECT name ... WHERE rootpage = $tnum */
165651  const char *zIdx = 0; /* Name of PK index */
165652  sqlite3_stmt *pXInfo = 0; /* PRAGMA main.index_xinfo = $zIdx */
165653  const char *zComma = "";
165654  char *zCols = 0; /* Used to build up list of table cols */
165655  char *zPk = 0; /* Used to build up table PK declaration */
165656 
165657  /* Figure out the name of the primary key index for the current table.
165658  ** This is needed for the argument to "PRAGMA index_xinfo". Set
165659  ** zIdx to point to a nul-terminated string containing this name. */
165660  p->rc = prepareAndCollectError(p->dbMain, &pQuery, &p->zErrmsg,
165661  "SELECT name FROM sqlite_master WHERE rootpage = ?"
165662  );
165663  if( p->rc==SQLITE_OK ){
165664  sqlite3_bind_int(pQuery, 1, tnum);
165665  if( SQLITE_ROW==sqlite3_step(pQuery) ){
165666  zIdx = (const char*)sqlite3_column_text(pQuery, 0);
165667  }
165668  }
165669  if( zIdx ){
165670  p->rc = prepareFreeAndCollectError(p->dbMain, &pXInfo, &p->zErrmsg,
165671  sqlite3_mprintf("PRAGMA main.index_xinfo = %Q", zIdx)
165672  );
165673  }
165674  rbuFinalize(p, pQuery);
165675 
165676  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pXInfo) ){
165677  int bKey = sqlite3_column_int(pXInfo, 5);
165678  if( bKey ){
165679  int iCid = sqlite3_column_int(pXInfo, 1);
165680  int bDesc = sqlite3_column_int(pXInfo, 3);
165681  const char *zCollate = (const char*)sqlite3_column_text(pXInfo, 4);
165682  zCols = rbuMPrintf(p, "%z%sc%d %s COLLATE %s", zCols, zComma,
165683  iCid, pIter->azTblType[iCid], zCollate
165684  );
165685  zPk = rbuMPrintf(p, "%z%sc%d%s", zPk, zComma, iCid, bDesc?" DESC":"");
165686  zComma = ", ";
165687  }
165688  }
165689  zCols = rbuMPrintf(p, "%z, id INTEGER", zCols);
165690  rbuFinalize(p, pXInfo);
165691 
165692  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
165693  rbuMPrintfExec(p, p->dbMain,
165694  "CREATE TABLE rbu_imposter2(%z, PRIMARY KEY(%z)) WITHOUT ROWID",
165695  zCols, zPk
165696  );
165697  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
165698  }
165699 }
165700 
165701 /*
165702 ** If an error has already occurred when this function is called, it
165703 ** immediately returns zero (without doing any work). Or, if an error
165704 ** occurs during the execution of this function, it sets the error code
165705 ** in the sqlite3rbu object indicated by the first argument and returns
165706 ** zero.
165707 **
165708 ** The iterator passed as the second argument is guaranteed to point to
165709 ** a table (not an index) when this function is called. This function
165710 ** attempts to create any imposter table required to write to the main
165711 ** table b-tree of the table before returning. Non-zero is returned if
165712 ** an imposter table are created, or zero otherwise.
165713 **
165714 ** An imposter table is required in all cases except RBU_PK_VTAB. Only
165715 ** virtual tables are written to directly. The imposter table has the
165716 ** same schema as the actual target table (less any UNIQUE constraints).
165717 ** More precisely, the "same schema" means the same columns, types,
165718 ** collation sequences. For tables that do not have an external PRIMARY
165719 ** KEY, it also means the same PRIMARY KEY declaration.
165720 */
165721 static void rbuCreateImposterTable(sqlite3rbu *p, RbuObjIter *pIter){
165722  if( p->rc==SQLITE_OK && pIter->eType!=RBU_PK_VTAB ){
165723  int tnum = pIter->iTnum;
165724  const char *zComma = "";
165725  char *zSql = 0;
165726  int iCol;
165727  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
165728 
165729  for(iCol=0; p->rc==SQLITE_OK && iCol<pIter->nTblCol; iCol++){
165730  const char *zPk = "";
165731  const char *zCol = pIter->azTblCol[iCol];
165732  const char *zColl = 0;
165733 
165735  p->dbMain, "main", pIter->zTbl, zCol, 0, &zColl, 0, 0, 0
165736  );
165737 
165738  if( pIter->eType==RBU_PK_IPK && pIter->abTblPk[iCol] ){
165739  /* If the target table column is an "INTEGER PRIMARY KEY", add
165740  ** "PRIMARY KEY" to the imposter table column declaration. */
165741  zPk = "PRIMARY KEY ";
165742  }
165743  zSql = rbuMPrintf(p, "%z%s\"%w\" %s %sCOLLATE %s%s",
165744  zSql, zComma, zCol, pIter->azTblType[iCol], zPk, zColl,
165745  (pIter->abNotNull[iCol] ? " NOT NULL" : "")
165746  );
165747  zComma = ", ";
165748  }
165749 
165750  if( pIter->eType==RBU_PK_WITHOUT_ROWID ){
165751  char *zPk = rbuWithoutRowidPK(p, pIter);
165752  if( zPk ){
165753  zSql = rbuMPrintf(p, "%z, %z", zSql, zPk);
165754  }
165755  }
165756 
165757  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1, tnum);
165758  rbuMPrintfExec(p, p->dbMain, "CREATE TABLE \"rbu_imp_%w\"(%z)%s",
165759  pIter->zTbl, zSql,
165760  (pIter->eType==RBU_PK_WITHOUT_ROWID ? " WITHOUT ROWID" : "")
165761  );
165762  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
165763  }
165764 }
165765 
165766 /*
165767 ** Prepare a statement used to insert rows into the "rbu_tmp_xxx" table.
165768 ** Specifically a statement of the form:
165769 **
165770 ** INSERT INTO rbu_tmp_xxx VALUES(?, ?, ? ...);
165771 **
165772 ** The number of bound variables is equal to the number of columns in
165773 ** the target table, plus one (for the rbu_control column), plus one more
165774 ** (for the rbu_rowid column) if the target table is an implicit IPK or
165775 ** virtual table.
165776 */
165777 static void rbuObjIterPrepareTmpInsert(
165778  sqlite3rbu *p,
165779  RbuObjIter *pIter,
165780  const char *zCollist,
165781  const char *zRbuRowid
165782 ){
165783  int bRbuRowid = (pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE);
165784  char *zBind = rbuObjIterGetBindlist(p, pIter->nTblCol + 1 + bRbuRowid);
165785  if( zBind ){
165786  assert( pIter->pTmpInsert==0 );
165787  p->rc = prepareFreeAndCollectError(
165788  p->dbRbu, &pIter->pTmpInsert, &p->zErrmsg, sqlite3_mprintf(
165789  "INSERT INTO %s.'rbu_tmp_%q'(rbu_control,%s%s) VALUES(%z)",
165790  p->zStateDb, pIter->zDataTbl, zCollist, zRbuRowid, zBind
165791  ));
165792  }
165793 }
165794 
165795 static void rbuTmpInsertFunc(
165796  sqlite3_context *pCtx,
165797  int nVal,
165798  sqlite3_value **apVal
165799 ){
165800  sqlite3rbu *p = sqlite3_user_data(pCtx);
165801  int rc = SQLITE_OK;
165802  int i;
165803 
165804  assert( sqlite3_value_int(apVal[0])!=0
165805  || p->objiter.eType==RBU_PK_EXTERNAL
165806  || p->objiter.eType==RBU_PK_NONE
165807  );
165808  if( sqlite3_value_int(apVal[0])!=0 ){
165809  p->nPhaseOneStep += p->objiter.nIndex;
165810  }
165811 
165812  for(i=0; rc==SQLITE_OK && i<nVal; i++){
165813  rc = sqlite3_bind_value(p->objiter.pTmpInsert, i+1, apVal[i]);
165814  }
165815  if( rc==SQLITE_OK ){
165816  sqlite3_step(p->objiter.pTmpInsert);
165817  rc = sqlite3_reset(p->objiter.pTmpInsert);
165818  }
165819 
165820  if( rc!=SQLITE_OK ){
165821  sqlite3_result_error_code(pCtx, rc);
165822  }
165823 }
165824 
165825 /*
165826 ** Ensure that the SQLite statement handles required to update the
165827 ** target database object currently indicated by the iterator passed
165828 ** as the second argument are available.
165829 */
165830 static int rbuObjIterPrepareAll(
165831  sqlite3rbu *p,
165832  RbuObjIter *pIter,
165833  int nOffset /* Add "LIMIT -1 OFFSET $nOffset" to SELECT */
165834 ){
165835  assert( pIter->bCleanup==0 );
165836  if( pIter->pSelect==0 && rbuObjIterCacheTableInfo(p, pIter)==SQLITE_OK ){
165837  const int tnum = pIter->iTnum;
165838  char *zCollist = 0; /* List of indexed columns */
165839  char **pz = &p->zErrmsg;
165840  const char *zIdx = pIter->zIdx;
165841  char *zLimit = 0;
165842 
165843  if( nOffset ){
165844  zLimit = sqlite3_mprintf(" LIMIT -1 OFFSET %d", nOffset);
165845  if( !zLimit ) p->rc = SQLITE_NOMEM;
165846  }
165847 
165848  if( zIdx ){
165849  const char *zTbl = pIter->zTbl;
165850  char *zImposterCols = 0; /* Columns for imposter table */
165851  char *zImposterPK = 0; /* Primary key declaration for imposter */
165852  char *zWhere = 0; /* WHERE clause on PK columns */
165853  char *zBind = 0;
165854  int nBind = 0;
165855 
165856  assert( pIter->eType!=RBU_PK_VTAB );
165857  zCollist = rbuObjIterGetIndexCols(
165858  p, pIter, &zImposterCols, &zImposterPK, &zWhere, &nBind
165859  );
165860  zBind = rbuObjIterGetBindlist(p, nBind);
165861 
165862  /* Create the imposter table used to write to this index. */
165863  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 1);
165864  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 1,tnum);
165865  rbuMPrintfExec(p, p->dbMain,
165866  "CREATE TABLE \"rbu_imp_%w\"( %s, PRIMARY KEY( %s ) ) WITHOUT ROWID",
165867  zTbl, zImposterCols, zImposterPK
165868  );
165869  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, p->dbMain, "main", 0, 0);
165870 
165871  /* Create the statement to insert index entries */
165872  pIter->nCol = nBind;
165873  if( p->rc==SQLITE_OK ){
165874  p->rc = prepareFreeAndCollectError(
165875  p->dbMain, &pIter->pInsert, &p->zErrmsg,
165876  sqlite3_mprintf("INSERT INTO \"rbu_imp_%w\" VALUES(%s)", zTbl, zBind)
165877  );
165878  }
165879 
165880  /* And to delete index entries */
165881  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
165882  p->rc = prepareFreeAndCollectError(
165883  p->dbMain, &pIter->pDelete, &p->zErrmsg,
165884  sqlite3_mprintf("DELETE FROM \"rbu_imp_%w\" WHERE %s", zTbl, zWhere)
165885  );
165886  }
165887 
165888  /* Create the SELECT statement to read keys in sorted order */
165889  if( p->rc==SQLITE_OK ){
165890  char *zSql;
165891  if( rbuIsVacuum(p) ){
165892  zSql = sqlite3_mprintf(
165893  "SELECT %s, 0 AS rbu_control FROM '%q' ORDER BY %s%s",
165894  zCollist,
165895  pIter->zDataTbl,
165896  zCollist, zLimit
165897  );
165898  }else
165899 
165900  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
165901  zSql = sqlite3_mprintf(
165902  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' ORDER BY %s%s",
165903  zCollist, p->zStateDb, pIter->zDataTbl,
165904  zCollist, zLimit
165905  );
165906  }else{
165907  zSql = sqlite3_mprintf(
165908  "SELECT %s, rbu_control FROM %s.'rbu_tmp_%q' "
165909  "UNION ALL "
165910  "SELECT %s, rbu_control FROM '%q' "
165911  "WHERE typeof(rbu_control)='integer' AND rbu_control!=1 "
165912  "ORDER BY %s%s",
165913  zCollist, p->zStateDb, pIter->zDataTbl,
165914  zCollist, pIter->zDataTbl,
165915  zCollist, zLimit
165916  );
165917  }
165918  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz, zSql);
165919  }
165920 
165921  sqlite3_free(zImposterCols);
165922  sqlite3_free(zImposterPK);
165923  sqlite3_free(zWhere);
165924  sqlite3_free(zBind);
165925  }else{
165926  int bRbuRowid = (pIter->eType==RBU_PK_VTAB)
165927  ||(pIter->eType==RBU_PK_NONE)
165928  ||(pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p));
165929  const char *zTbl = pIter->zTbl; /* Table this step applies to */
165930  const char *zWrite; /* Imposter table name */
165931 
165932  char *zBindings = rbuObjIterGetBindlist(p, pIter->nTblCol + bRbuRowid);
165933  char *zWhere = rbuObjIterGetWhere(p, pIter);
165934  char *zOldlist = rbuObjIterGetOldlist(p, pIter, "old");
165935  char *zNewlist = rbuObjIterGetOldlist(p, pIter, "new");
165936 
165937  zCollist = rbuObjIterGetCollist(p, pIter);
165938  pIter->nCol = pIter->nTblCol;
165939 
165940  /* Create the imposter table or tables (if required). */
165941  rbuCreateImposterTable(p, pIter);
165942  rbuCreateImposterTable2(p, pIter);
165943  zWrite = (pIter->eType==RBU_PK_VTAB ? "" : "rbu_imp_");
165944 
165945  /* Create the INSERT statement to write to the target PK b-tree */
165946  if( p->rc==SQLITE_OK ){
165947  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pInsert, pz,
165948  sqlite3_mprintf(
165949  "INSERT INTO \"%s%w\"(%s%s) VALUES(%s)",
165950  zWrite, zTbl, zCollist, (bRbuRowid ? ", _rowid_" : ""), zBindings
165951  )
165952  );
165953  }
165954 
165955  /* Create the DELETE statement to write to the target PK b-tree.
165956  ** Because it only performs INSERT operations, this is not required for
165957  ** an rbu vacuum handle. */
165958  if( rbuIsVacuum(p)==0 && p->rc==SQLITE_OK ){
165959  p->rc = prepareFreeAndCollectError(p->dbMain, &pIter->pDelete, pz,
165960  sqlite3_mprintf(
165961  "DELETE FROM \"%s%w\" WHERE %s", zWrite, zTbl, zWhere
165962  )
165963  );
165964  }
165965 
165966  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
165967  const char *zRbuRowid = "";
165968  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
165969  zRbuRowid = ", rbu_rowid";
165970  }
165971 
165972  /* Create the rbu_tmp_xxx table and the triggers to populate it. */
165973  rbuMPrintfExec(p, p->dbRbu,
165974  "CREATE TABLE IF NOT EXISTS %s.'rbu_tmp_%q' AS "
165975  "SELECT *%s FROM '%q' WHERE 0;"
165976  , p->zStateDb, pIter->zDataTbl
165977  , (pIter->eType==RBU_PK_EXTERNAL ? ", 0 AS rbu_rowid" : "")
165978  , pIter->zDataTbl
165979  );
165980 
165981  rbuMPrintfExec(p, p->dbMain,
165982  "CREATE TEMP TRIGGER rbu_delete_tr BEFORE DELETE ON \"%s%w\" "
165983  "BEGIN "
165984  " SELECT rbu_tmp_insert(3, %s);"
165985  "END;"
165986 
165987  "CREATE TEMP TRIGGER rbu_update1_tr BEFORE UPDATE ON \"%s%w\" "
165988  "BEGIN "
165989  " SELECT rbu_tmp_insert(3, %s);"
165990  "END;"
165991 
165992  "CREATE TEMP TRIGGER rbu_update2_tr AFTER UPDATE ON \"%s%w\" "
165993  "BEGIN "
165994  " SELECT rbu_tmp_insert(4, %s);"
165995  "END;",
165996  zWrite, zTbl, zOldlist,
165997  zWrite, zTbl, zOldlist,
165998  zWrite, zTbl, zNewlist
165999  );
166000 
166001  if( pIter->eType==RBU_PK_EXTERNAL || pIter->eType==RBU_PK_NONE ){
166002  rbuMPrintfExec(p, p->dbMain,
166003  "CREATE TEMP TRIGGER rbu_insert_tr AFTER INSERT ON \"%s%w\" "
166004  "BEGIN "
166005  " SELECT rbu_tmp_insert(0, %s);"
166006  "END;",
166007  zWrite, zTbl, zNewlist
166008  );
166009  }
166010 
166011  rbuObjIterPrepareTmpInsert(p, pIter, zCollist, zRbuRowid);
166012  }
166013 
166014  /* Create the SELECT statement to read keys from data_xxx */
166015  if( p->rc==SQLITE_OK ){
166016  const char *zRbuRowid = "";
166017  if( bRbuRowid ){
166018  zRbuRowid = rbuIsVacuum(p) ? ",_rowid_ " : ",rbu_rowid";
166019  }
166020  p->rc = prepareFreeAndCollectError(p->dbRbu, &pIter->pSelect, pz,
166021  sqlite3_mprintf(
166022  "SELECT %s,%s rbu_control%s FROM '%q'%s",
166023  zCollist,
166024  (rbuIsVacuum(p) ? "0 AS " : ""),
166025  zRbuRowid,
166026  pIter->zDataTbl, zLimit
166027  )
166028  );
166029  }
166030 
166031  sqlite3_free(zWhere);
166032  sqlite3_free(zOldlist);
166033  sqlite3_free(zNewlist);
166034  sqlite3_free(zBindings);
166035  }
166036  sqlite3_free(zCollist);
166037  sqlite3_free(zLimit);
166038  }
166039 
166040  return p->rc;
166041 }
166042 
166043 /*
166044 ** Set output variable *ppStmt to point to an UPDATE statement that may
166045 ** be used to update the imposter table for the main table b-tree of the
166046 ** table object that pIter currently points to, assuming that the
166047 ** rbu_control column of the data_xyz table contains zMask.
166048 **
166049 ** If the zMask string does not specify any columns to update, then this
166050 ** is not an error. Output variable *ppStmt is set to NULL in this case.
166051 */
166052 static int rbuGetUpdateStmt(
166053  sqlite3rbu *p, /* RBU handle */
166054  RbuObjIter *pIter, /* Object iterator */
166055  const char *zMask, /* rbu_control value ('x.x.') */
166056  sqlite3_stmt **ppStmt /* OUT: UPDATE statement handle */
166057 ){
166058  RbuUpdateStmt **pp;
166059  RbuUpdateStmt *pUp = 0;
166060  int nUp = 0;
166061 
166062  /* In case an error occurs */
166063  *ppStmt = 0;
166064 
166065  /* Search for an existing statement. If one is found, shift it to the front
166066  ** of the LRU queue and return immediately. Otherwise, leave nUp pointing
166067  ** to the number of statements currently in the cache and pUp to the
166068  ** last object in the list. */
166069  for(pp=&pIter->pRbuUpdate; *pp; pp=&((*pp)->pNext)){
166070  pUp = *pp;
166071  if( strcmp(pUp->zMask, zMask)==0 ){
166072  *pp = pUp->pNext;
166073  pUp->pNext = pIter->pRbuUpdate;
166074  pIter->pRbuUpdate = pUp;
166075  *ppStmt = pUp->pUpdate;
166076  return SQLITE_OK;
166077  }
166078  nUp++;
166079  }
166080  assert( pUp==0 || pUp->pNext==0 );
166081 
166082  if( nUp>=SQLITE_RBU_UPDATE_CACHESIZE ){
166083  for(pp=&pIter->pRbuUpdate; *pp!=pUp; pp=&((*pp)->pNext));
166084  *pp = 0;
166085  sqlite3_finalize(pUp->pUpdate);
166086  pUp->pUpdate = 0;
166087  }else{
166088  pUp = (RbuUpdateStmt*)rbuMalloc(p, sizeof(RbuUpdateStmt)+pIter->nTblCol+1);
166089  }
166090 
166091  if( pUp ){
166092  char *zWhere = rbuObjIterGetWhere(p, pIter);
166093  char *zSet = rbuObjIterGetSetlist(p, pIter, zMask);
166094  char *zUpdate = 0;
166095 
166096  pUp->zMask = (char*)&pUp[1];
166097  memcpy(pUp->zMask, zMask, pIter->nTblCol);
166098  pUp->pNext = pIter->pRbuUpdate;
166099  pIter->pRbuUpdate = pUp;
166100 
166101  if( zSet ){
166102  const char *zPrefix = "";
166103 
166104  if( pIter->eType!=RBU_PK_VTAB ) zPrefix = "rbu_imp_";
166105  zUpdate = sqlite3_mprintf("UPDATE \"%s%w\" SET %s WHERE %s",
166106  zPrefix, pIter->zTbl, zSet, zWhere
166107  );
166108  p->rc = prepareFreeAndCollectError(
166109  p->dbMain, &pUp->pUpdate, &p->zErrmsg, zUpdate
166110  );
166111  *ppStmt = pUp->pUpdate;
166112  }
166113  sqlite3_free(zWhere);
166114  sqlite3_free(zSet);
166115  }
166116 
166117  return p->rc;
166118 }
166119 
166120 static sqlite3 *rbuOpenDbhandle(
166121  sqlite3rbu *p,
166122  const char *zName,
166123  int bUseVfs
166124 ){
166125  sqlite3 *db = 0;
166126  if( p->rc==SQLITE_OK ){
166128  p->rc = sqlite3_open_v2(zName, &db, flags, bUseVfs ? p->zVfsName : 0);
166129  if( p->rc ){
166130  p->zErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
166131  sqlite3_close(db);
166132  db = 0;
166133  }
166134  }
166135  return db;
166136 }
166137 
166138 /*
166139 ** Free an RbuState object allocated by rbuLoadState().
166140 */
166141 static void rbuFreeState(RbuState *p){
166142  if( p ){
166143  sqlite3_free(p->zTbl);
166144  sqlite3_free(p->zIdx);
166145  sqlite3_free(p);
166146  }
166147 }
166148 
166149 /*
166150 ** Allocate an RbuState object and load the contents of the rbu_state
166151 ** table into it. Return a pointer to the new object. It is the
166152 ** responsibility of the caller to eventually free the object using
166153 ** sqlite3_free().
166154 **
166155 ** If an error occurs, leave an error code and message in the rbu handle
166156 ** and return NULL.
166157 */
166158 static RbuState *rbuLoadState(sqlite3rbu *p){
166159  RbuState *pRet = 0;
166160  sqlite3_stmt *pStmt = 0;
166161  int rc;
166162  int rc2;
166163 
166164  pRet = (RbuState*)rbuMalloc(p, sizeof(RbuState));
166165  if( pRet==0 ) return 0;
166166 
166167  rc = prepareFreeAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
166168  sqlite3_mprintf("SELECT k, v FROM %s.rbu_state", p->zStateDb)
166169  );
166170  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
166171  switch( sqlite3_column_int(pStmt, 0) ){
166172  case RBU_STATE_STAGE:
166173  pRet->eStage = sqlite3_column_int(pStmt, 1);
166174  if( pRet->eStage!=RBU_STAGE_OAL
166175  && pRet->eStage!=RBU_STAGE_MOVE
166176  && pRet->eStage!=RBU_STAGE_CKPT
166177  ){
166178  p->rc = SQLITE_CORRUPT;
166179  }
166180  break;
166181 
166182  case RBU_STATE_TBL:
166183  pRet->zTbl = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166184  break;
166185 
166186  case RBU_STATE_IDX:
166187  pRet->zIdx = rbuStrndup((char*)sqlite3_column_text(pStmt, 1), &rc);
166188  break;
166189 
166190  case RBU_STATE_ROW:
166191  pRet->nRow = sqlite3_column_int(pStmt, 1);
166192  break;
166193 
166194  case RBU_STATE_PROGRESS:
166195  pRet->nProgress = sqlite3_column_int64(pStmt, 1);
166196  break;
166197 
166198  case RBU_STATE_CKPT:
166199  pRet->iWalCksum = sqlite3_column_int64(pStmt, 1);
166200  break;
166201 
166202  case RBU_STATE_COOKIE:
166203  pRet->iCookie = (u32)sqlite3_column_int64(pStmt, 1);
166204  break;
166205 
166206  case RBU_STATE_OALSZ:
166207  pRet->iOalSz = (u32)sqlite3_column_int64(pStmt, 1);
166208  break;
166209 
166210  case RBU_STATE_PHASEONESTEP:
166211  pRet->nPhaseOneStep = sqlite3_column_int64(pStmt, 1);
166212  break;
166213 
166214  default:
166215  rc = SQLITE_CORRUPT;
166216  break;
166217  }
166218  }
166219  rc2 = sqlite3_finalize(pStmt);
166220  if( rc==SQLITE_OK ) rc = rc2;
166221 
166222  p->rc = rc;
166223  return pRet;
166224 }
166225 
166226 
166227 /*
166228 ** Open the database handle and attach the RBU database as "rbu". If an
166229 ** error occurs, leave an error code and message in the RBU handle.
166230 */
166231 static void rbuOpenDatabase(sqlite3rbu *p){
166232  assert( p->rc==SQLITE_OK );
166233  assert( p->dbMain==0 && p->dbRbu==0 );
166234  assert( rbuIsVacuum(p) || p->zTarget!=0 );
166235 
166236  /* Open the RBU database */
166237  p->dbRbu = rbuOpenDbhandle(p, p->zRbu, 1);
166238 
166239  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166240  sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166241  }
166242 
166243  /* If using separate RBU and state databases, attach the state database to
166244  ** the RBU db handle now. */
166245  if( p->zState ){
166246  rbuMPrintfExec(p, p->dbRbu, "ATTACH %Q AS stat", p->zState);
166247  memcpy(p->zStateDb, "stat", 4);
166248  }else{
166249  memcpy(p->zStateDb, "main", 4);
166250  }
166251 
166252 #if 0
166253  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166254  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, 0);
166255  }
166256 #endif
166257 
166258  /* If it has not already been created, create the rbu_state table */
166259  rbuMPrintfExec(p, p->dbRbu, RBU_CREATE_STATE, p->zStateDb);
166260 
166261 #if 0
166262  if( rbuIsVacuum(p) ){
166263  if( p->rc==SQLITE_OK ){
166264  int rc2;
166265  int bOk = 0;
166266  sqlite3_stmt *pCnt = 0;
166267  p->rc = prepareAndCollectError(p->dbRbu, &pCnt, &p->zErrmsg,
166268  "SELECT count(*) FROM stat.sqlite_master"
166269  );
166270  if( p->rc==SQLITE_OK
166271  && sqlite3_step(pCnt)==SQLITE_ROW
166272  && 1==sqlite3_column_int(pCnt, 0)
166273  ){
166274  bOk = 1;
166275  }
166276  rc2 = sqlite3_finalize(pCnt);
166277  if( p->rc==SQLITE_OK ) p->rc = rc2;
166278 
166279  if( p->rc==SQLITE_OK && bOk==0 ){
166280  p->rc = SQLITE_ERROR;
166281  p->zErrmsg = sqlite3_mprintf("invalid state database");
166282  }
166283 
166284  if( p->rc==SQLITE_OK ){
166285  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
166286  }
166287  }
166288  }
166289 #endif
166290 
166291  if( p->rc==SQLITE_OK && rbuIsVacuum(p) ){
166292  int bOpen = 0;
166293  int rc;
166294  p->nRbu = 0;
166295  p->pRbuFd = 0;
166296  rc = sqlite3_file_control(p->dbRbu, "main", SQLITE_FCNTL_RBUCNT, (void*)p);
166297  if( rc!=SQLITE_NOTFOUND ) p->rc = rc;
166298  if( p->eStage>=RBU_STAGE_MOVE ){
166299  bOpen = 1;
166300  }else{
166301  RbuState *pState = rbuLoadState(p);
166302  if( pState ){
166303  bOpen = (pState->eStage>RBU_STAGE_MOVE);
166304  rbuFreeState(pState);
166305  }
166306  }
166307  if( bOpen ) p->dbMain = rbuOpenDbhandle(p, p->zRbu, p->nRbu<=1);
166308  }
166309 
166310  p->eStage = 0;
166311  if( p->rc==SQLITE_OK && p->dbMain==0 ){
166312  if( !rbuIsVacuum(p) ){
166313  p->dbMain = rbuOpenDbhandle(p, p->zTarget, 1);
166314  }else if( p->pRbuFd->pWalFd ){
166315  p->rc = SQLITE_ERROR;
166316  p->zErrmsg = sqlite3_mprintf("cannot vacuum wal mode database");
166317  }else{
166318  char *zTarget;
166319  char *zExtra = 0;
166320  if( strlen(p->zRbu)>=5 && 0==memcmp("file:", p->zRbu, 5) ){
166321  zExtra = &p->zRbu[5];
166322  while( *zExtra ){
166323  if( *zExtra++=='?' ) break;
166324  }
166325  if( *zExtra=='\0' ) zExtra = 0;
166326  }
166327 
166328  zTarget = sqlite3_mprintf("file:%s-vacuum?rbu_memory=1%s%s",
166329  sqlite3_db_filename(p->dbRbu, "main"),
166330  (zExtra==0 ? "" : "&"), (zExtra==0 ? "" : zExtra)
166331  );
166332 
166333  if( zTarget==0 ){
166334  p->rc = SQLITE_NOMEM;
166335  return;
166336  }
166337  p->dbMain = rbuOpenDbhandle(p, zTarget, p->nRbu<=1);
166338  sqlite3_free(zTarget);
166339  }
166340  }
166341 
166342  if( p->rc==SQLITE_OK ){
166343  p->rc = sqlite3_create_function(p->dbMain,
166344  "rbu_tmp_insert", -1, SQLITE_UTF8, (void*)p, rbuTmpInsertFunc, 0, 0
166345  );
166346  }
166347 
166348  if( p->rc==SQLITE_OK ){
166349  p->rc = sqlite3_create_function(p->dbMain,
166350  "rbu_fossil_delta", 2, SQLITE_UTF8, 0, rbuFossilDeltaFunc, 0, 0
166351  );
166352  }
166353 
166354  if( p->rc==SQLITE_OK ){
166355  p->rc = sqlite3_create_function(p->dbRbu,
166356  "rbu_target_name", -1, SQLITE_UTF8, (void*)p, rbuTargetNameFunc, 0, 0
166357  );
166358  }
166359 
166360  if( p->rc==SQLITE_OK ){
166361  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
166362  }
166363  rbuMPrintfExec(p, p->dbMain, "SELECT * FROM sqlite_master");
166364 
166365  /* Mark the database file just opened as an RBU target database. If
166366  ** this call returns SQLITE_NOTFOUND, then the RBU vfs is not in use.
166367  ** This is an error. */
166368  if( p->rc==SQLITE_OK ){
166369  p->rc = sqlite3_file_control(p->dbMain, "main", SQLITE_FCNTL_RBU, (void*)p);
166370  }
166371 
166372  if( p->rc==SQLITE_NOTFOUND ){
166373  p->rc = SQLITE_ERROR;
166374  p->zErrmsg = sqlite3_mprintf("rbu vfs not found");
166375  }
166376 }
166377 
166378 /*
166379 ** This routine is a copy of the sqlite3FileSuffix3() routine from the core.
166380 ** It is a no-op unless SQLITE_ENABLE_8_3_NAMES is defined.
166381 **
166382 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
166383 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
166384 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
166385 ** three characters, then shorten the suffix on z[] to be the last three
166386 ** characters of the original suffix.
166387 **
166388 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
166389 ** do the suffix shortening regardless of URI parameter.
166390 **
166391 ** Examples:
166392 **
166393 ** test.db-journal => test.nal
166394 ** test.db-wal => test.wal
166395 ** test.db-shm => test.shm
166396 ** test.db-mj7f3319fa => test.9fa
166397 */
166398 static void rbuFileSuffix3(const char *zBase, char *z){
166399 #ifdef SQLITE_ENABLE_8_3_NAMES
166400 #if SQLITE_ENABLE_8_3_NAMES<2
166401  if( sqlite3_uri_boolean(zBase, "8_3_names", 0) )
166402 #endif
166403  {
166404  int i, sz;
166405  sz = sqlite3Strlen30(z);
166406  for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
166407  if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
166408  }
166409 #endif
166410 }
166411 
166412 /*
166413 ** Return the current wal-index header checksum for the target database
166414 ** as a 64-bit integer.
166415 **
166416 ** The checksum is store in the first page of xShmMap memory as an 8-byte
166417 ** blob starting at byte offset 40.
166418 */
166419 static i64 rbuShmChecksum(sqlite3rbu *p){
166420  i64 iRet = 0;
166421  if( p->rc==SQLITE_OK ){
166422  sqlite3_file *pDb = p->pTargetFd->pReal;
166423  u32 volatile *ptr;
166424  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, (void volatile**)&ptr);
166425  if( p->rc==SQLITE_OK ){
166426  iRet = ((i64)ptr[10] << 32) + ptr[11];
166427  }
166428  }
166429  return iRet;
166430 }
166431 
166432 /*
166433 ** This function is called as part of initializing or reinitializing an
166434 ** incremental checkpoint.
166435 **
166436 ** It populates the sqlite3rbu.aFrame[] array with the set of
166437 ** (wal frame -> db page) copy operations required to checkpoint the
166438 ** current wal file, and obtains the set of shm locks required to safely
166439 ** perform the copy operations directly on the file-system.
166440 **
166441 ** If argument pState is not NULL, then the incremental checkpoint is
166442 ** being resumed. In this case, if the checksum of the wal-index-header
166443 ** following recovery is not the same as the checksum saved in the RbuState
166444 ** object, then the rbu handle is set to DONE state. This occurs if some
166445 ** other client appends a transaction to the wal file in the middle of
166446 ** an incremental checkpoint.
166447 */
166448 static void rbuSetupCheckpoint(sqlite3rbu *p, RbuState *pState){
166449 
166450  /* If pState is NULL, then the wal file may not have been opened and
166451  ** recovered. Running a read-statement here to ensure that doing so
166452  ** does not interfere with the "capture" process below. */
166453  if( pState==0 ){
166454  p->eStage = 0;
166455  if( p->rc==SQLITE_OK ){
166456  p->rc = sqlite3_exec(p->dbMain, "SELECT * FROM sqlite_master", 0, 0, 0);
166457  }
166458  }
166459 
166460  /* Assuming no error has occurred, run a "restart" checkpoint with the
166461  ** sqlite3rbu.eStage variable set to CAPTURE. This turns on the following
166462  ** special behaviour in the rbu VFS:
166463  **
166464  ** * If the exclusive shm WRITER or READ0 lock cannot be obtained,
166465  ** the checkpoint fails with SQLITE_BUSY (normally SQLite would
166466  ** proceed with running a passive checkpoint instead of failing).
166467  **
166468  ** * Attempts to read from the *-wal file or write to the database file
166469  ** do not perform any IO. Instead, the frame/page combinations that
166470  ** would be read/written are recorded in the sqlite3rbu.aFrame[]
166471  ** array.
166472  **
166473  ** * Calls to xShmLock(UNLOCK) to release the exclusive shm WRITER,
166474  ** READ0 and CHECKPOINT locks taken as part of the checkpoint are
166475  ** no-ops. These locks will not be released until the connection
166476  ** is closed.
166477  **
166478  ** * Attempting to xSync() the database file causes an SQLITE_INTERNAL
166479  ** error.
166480  **
166481  ** As a result, unless an error (i.e. OOM or SQLITE_BUSY) occurs, the
166482  ** checkpoint below fails with SQLITE_INTERNAL, and leaves the aFrame[]
166483  ** array populated with a set of (frame -> page) mappings. Because the
166484  ** WRITER, CHECKPOINT and READ0 locks are still held, it is safe to copy
166485  ** data from the wal file into the database file according to the
166486  ** contents of aFrame[].
166487  */
166488  if( p->rc==SQLITE_OK ){
166489  int rc2;
166490  p->eStage = RBU_STAGE_CAPTURE;
166491  rc2 = sqlite3_exec(p->dbMain, "PRAGMA main.wal_checkpoint=restart", 0, 0,0);
166492  if( rc2!=SQLITE_INTERNAL ) p->rc = rc2;
166493  }
166494 
166495  if( p->rc==SQLITE_OK ){
166496  p->eStage = RBU_STAGE_CKPT;
166497  p->nStep = (pState ? pState->nRow : 0);
166498  p->aBuf = rbuMalloc(p, p->pgsz);
166499  p->iWalCksum = rbuShmChecksum(p);
166500  }
166501 
166502  if( p->rc==SQLITE_OK && pState && pState->iWalCksum!=p->iWalCksum ){
166503  p->rc = SQLITE_DONE;
166504  p->eStage = RBU_STAGE_DONE;
166505  }
166506 }
166507 
166508 /*
166509 ** Called when iAmt bytes are read from offset iOff of the wal file while
166510 ** the rbu object is in capture mode. Record the frame number of the frame
166511 ** being read in the aFrame[] array.
166512 */
166513 static int rbuCaptureWalRead(sqlite3rbu *pRbu, i64 iOff, int iAmt){
166514  const u32 mReq = (1<<WAL_LOCK_WRITE)|(1<<WAL_LOCK_CKPT)|(1<<WAL_LOCK_READ0);
166515  u32 iFrame;
166516 
166517  if( pRbu->mLock!=mReq ){
166518  pRbu->rc = SQLITE_BUSY;
166519  return SQLITE_INTERNAL;
166520  }
166521 
166522  pRbu->pgsz = iAmt;
166523  if( pRbu->nFrame==pRbu->nFrameAlloc ){
166524  int nNew = (pRbu->nFrameAlloc ? pRbu->nFrameAlloc : 64) * 2;
166525  RbuFrame *aNew;
166526  aNew = (RbuFrame*)sqlite3_realloc64(pRbu->aFrame, nNew * sizeof(RbuFrame));
166527  if( aNew==0 ) return SQLITE_NOMEM;
166528  pRbu->aFrame = aNew;
166529  pRbu->nFrameAlloc = nNew;
166530  }
166531 
166532  iFrame = (u32)((iOff-32) / (i64)(iAmt+24)) + 1;
166533  if( pRbu->iMaxFrame<iFrame ) pRbu->iMaxFrame = iFrame;
166534  pRbu->aFrame[pRbu->nFrame].iWalFrame = iFrame;
166535  pRbu->aFrame[pRbu->nFrame].iDbPage = 0;
166536  pRbu->nFrame++;
166537  return SQLITE_OK;
166538 }
166539 
166540 /*
166541 ** Called when a page of data is written to offset iOff of the database
166542 ** file while the rbu handle is in capture mode. Record the page number
166543 ** of the page being written in the aFrame[] array.
166544 */
166545 static int rbuCaptureDbWrite(sqlite3rbu *pRbu, i64 iOff){
166546  pRbu->aFrame[pRbu->nFrame-1].iDbPage = (u32)(iOff / pRbu->pgsz) + 1;
166547  return SQLITE_OK;
166548 }
166549 
166550 /*
166551 ** This is called as part of an incremental checkpoint operation. Copy
166552 ** a single frame of data from the wal file into the database file, as
166553 ** indicated by the RbuFrame object.
166554 */
166555 static void rbuCheckpointFrame(sqlite3rbu *p, RbuFrame *pFrame){
166556  sqlite3_file *pWal = p->pTargetFd->pWalFd->pReal;
166557  sqlite3_file *pDb = p->pTargetFd->pReal;
166558  i64 iOff;
166559 
166560  assert( p->rc==SQLITE_OK );
166561  iOff = (i64)(pFrame->iWalFrame-1) * (p->pgsz + 24) + 32 + 24;
166562  p->rc = pWal->pMethods->xRead(pWal, p->aBuf, p->pgsz, iOff);
166563  if( p->rc ) return;
166564 
166565  iOff = (i64)(pFrame->iDbPage-1) * p->pgsz;
166566  p->rc = pDb->pMethods->xWrite(pDb, p->aBuf, p->pgsz, iOff);
166567 }
166568 
166569 
166570 /*
166571 ** Take an EXCLUSIVE lock on the database file.
166572 */
166573 static void rbuLockDatabase(sqlite3rbu *p){
166574  sqlite3_file *pReal = p->pTargetFd->pReal;
166575  assert( p->rc==SQLITE_OK );
166576  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_SHARED);
166577  if( p->rc==SQLITE_OK ){
166578  p->rc = pReal->pMethods->xLock(pReal, SQLITE_LOCK_EXCLUSIVE);
166579  }
166580 }
166581 
166582 #if defined(_WIN32_WCE)
166583 static LPWSTR rbuWinUtf8ToUnicode(const char *zFilename){
166584  int nChar;
166585  LPWSTR zWideFilename;
166586 
166587  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
166588  if( nChar==0 ){
166589  return 0;
166590  }
166591  zWideFilename = sqlite3_malloc64( nChar*sizeof(zWideFilename[0]) );
166592  if( zWideFilename==0 ){
166593  return 0;
166594  }
166595  memset(zWideFilename, 0, nChar*sizeof(zWideFilename[0]));
166596  nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
166597  nChar);
166598  if( nChar==0 ){
166599  sqlite3_free(zWideFilename);
166600  zWideFilename = 0;
166601  }
166602  return zWideFilename;
166603 }
166604 #endif
166605 
166606 /*
166607 ** The RBU handle is currently in RBU_STAGE_OAL state, with a SHARED lock
166608 ** on the database file. This proc moves the *-oal file to the *-wal path,
166609 ** then reopens the database file (this time in vanilla, non-oal, WAL mode).
166610 ** If an error occurs, leave an error code and error message in the rbu
166611 ** handle.
166612 */
166613 static void rbuMoveOalFile(sqlite3rbu *p){
166614  const char *zBase = sqlite3_db_filename(p->dbMain, "main");
166615  const char *zMove = zBase;
166616  char *zOal;
166617  char *zWal;
166618 
166619  if( rbuIsVacuum(p) ){
166620  zMove = sqlite3_db_filename(p->dbRbu, "main");
166621  }
166622  zOal = sqlite3_mprintf("%s-oal", zMove);
166623  zWal = sqlite3_mprintf("%s-wal", zMove);
166624 
166625  assert( p->eStage==RBU_STAGE_MOVE );
166626  assert( p->rc==SQLITE_OK && p->zErrmsg==0 );
166627  if( zWal==0 || zOal==0 ){
166628  p->rc = SQLITE_NOMEM;
166629  }else{
166630  /* Move the *-oal file to *-wal. At this point connection p->db is
166631  ** holding a SHARED lock on the target database file (because it is
166632  ** in WAL mode). So no other connection may be writing the db.
166633  **
166634  ** In order to ensure that there are no database readers, an EXCLUSIVE
166635  ** lock is obtained here before the *-oal is moved to *-wal.
166636  */
166637  rbuLockDatabase(p);
166638  if( p->rc==SQLITE_OK ){
166639  rbuFileSuffix3(zBase, zWal);
166640  rbuFileSuffix3(zBase, zOal);
166641 
166642  /* Re-open the databases. */
166643  rbuObjIterFinalize(&p->objiter);
166644  sqlite3_close(p->dbRbu);
166645  sqlite3_close(p->dbMain);
166646  p->dbMain = 0;
166647  p->dbRbu = 0;
166648 
166649 #if defined(_WIN32_WCE)
166650  {
166651  LPWSTR zWideOal;
166652  LPWSTR zWideWal;
166653 
166654  zWideOal = rbuWinUtf8ToUnicode(zOal);
166655  if( zWideOal ){
166656  zWideWal = rbuWinUtf8ToUnicode(zWal);
166657  if( zWideWal ){
166658  if( MoveFileW(zWideOal, zWideWal) ){
166659  p->rc = SQLITE_OK;
166660  }else{
166661  p->rc = SQLITE_IOERR;
166662  }
166663  sqlite3_free(zWideWal);
166664  }else{
166665  p->rc = SQLITE_IOERR_NOMEM;
166666  }
166667  sqlite3_free(zWideOal);
166668  }else{
166669  p->rc = SQLITE_IOERR_NOMEM;
166670  }
166671  }
166672 #else
166673  p->rc = rename(zOal, zWal) ? SQLITE_IOERR : SQLITE_OK;
166674 #endif
166675 
166676  if( p->rc==SQLITE_OK ){
166677  rbuOpenDatabase(p);
166678  rbuSetupCheckpoint(p, 0);
166679  }
166680  }
166681  }
166682 
166683  sqlite3_free(zWal);
166684  sqlite3_free(zOal);
166685 }
166686 
166687 /*
166688 ** The SELECT statement iterating through the keys for the current object
166689 ** (p->objiter.pSelect) currently points to a valid row. This function
166690 ** determines the type of operation requested by this row and returns
166691 ** one of the following values to indicate the result:
166692 **
166693 ** * RBU_INSERT
166694 ** * RBU_DELETE
166695 ** * RBU_IDX_DELETE
166696 ** * RBU_UPDATE
166697 **
166698 ** If RBU_UPDATE is returned, then output variable *pzMask is set to
166699 ** point to the text value indicating the columns to update.
166700 **
166701 ** If the rbu_control field contains an invalid value, an error code and
166702 ** message are left in the RBU handle and zero returned.
166703 */
166704 static int rbuStepType(sqlite3rbu *p, const char **pzMask){
166705  int iCol = p->objiter.nCol; /* Index of rbu_control column */
166706  int res = 0; /* Return value */
166707 
166708  switch( sqlite3_column_type(p->objiter.pSelect, iCol) ){
166709  case SQLITE_INTEGER: {
166710  int iVal = sqlite3_column_int(p->objiter.pSelect, iCol);
166711  switch( iVal ){
166712  case 0: res = RBU_INSERT; break;
166713  case 1: res = RBU_DELETE; break;
166714  case 2: res = RBU_REPLACE; break;
166715  case 3: res = RBU_IDX_DELETE; break;
166716  case 4: res = RBU_IDX_INSERT; break;
166717  }
166718  break;
166719  }
166720 
166721  case SQLITE_TEXT: {
166722  const unsigned char *z = sqlite3_column_text(p->objiter.pSelect, iCol);
166723  if( z==0 ){
166724  p->rc = SQLITE_NOMEM;
166725  }else{
166726  *pzMask = (const char*)z;
166727  }
166728  res = RBU_UPDATE;
166729 
166730  break;
166731  }
166732 
166733  default:
166734  break;
166735  }
166736 
166737  if( res==0 ){
166738  rbuBadControlError(p);
166739  }
166740  return res;
166741 }
166742 
166743 #ifdef SQLITE_DEBUG
166744 /*
166745 ** Assert that column iCol of statement pStmt is named zName.
166746 */
166747 static void assertColumnName(sqlite3_stmt *pStmt, int iCol, const char *zName){
166748  const char *zCol = sqlite3_column_name(pStmt, iCol);
166749  assert( 0==sqlite3_stricmp(zName, zCol) );
166750 }
166751 #else
166752 # define assertColumnName(x,y,z)
166753 #endif
166754 
166755 /*
166756 ** Argument eType must be one of RBU_INSERT, RBU_DELETE, RBU_IDX_INSERT or
166757 ** RBU_IDX_DELETE. This function performs the work of a single
166758 ** sqlite3rbu_step() call for the type of operation specified by eType.
166759 */
166760 static void rbuStepOneOp(sqlite3rbu *p, int eType){
166761  RbuObjIter *pIter = &p->objiter;
166762  sqlite3_value *pVal;
166763  sqlite3_stmt *pWriter;
166764  int i;
166765 
166766  assert( p->rc==SQLITE_OK );
166767  assert( eType!=RBU_DELETE || pIter->zIdx==0 );
166768  assert( eType==RBU_DELETE || eType==RBU_IDX_DELETE
166769  || eType==RBU_INSERT || eType==RBU_IDX_INSERT
166770  );
166771 
166772  /* If this is a delete, decrement nPhaseOneStep by nIndex. If the DELETE
166773  ** statement below does actually delete a row, nPhaseOneStep will be
166774  ** incremented by the same amount when SQL function rbu_tmp_insert()
166775  ** is invoked by the trigger. */
166776  if( eType==RBU_DELETE ){
166777  p->nPhaseOneStep -= p->objiter.nIndex;
166778  }
166779 
166780  if( eType==RBU_IDX_DELETE || eType==RBU_DELETE ){
166781  pWriter = pIter->pDelete;
166782  }else{
166783  pWriter = pIter->pInsert;
166784  }
166785 
166786  for(i=0; i<pIter->nCol; i++){
166787  /* If this is an INSERT into a table b-tree and the table has an
166788  ** explicit INTEGER PRIMARY KEY, check that this is not an attempt
166789  ** to write a NULL into the IPK column. That is not permitted. */
166790  if( eType==RBU_INSERT
166791  && pIter->zIdx==0 && pIter->eType==RBU_PK_IPK && pIter->abTblPk[i]
166792  && sqlite3_column_type(pIter->pSelect, i)==SQLITE_NULL
166793  ){
166794  p->rc = SQLITE_MISMATCH;
166795  p->zErrmsg = sqlite3_mprintf("datatype mismatch");
166796  return;
166797  }
166798 
166799  if( eType==RBU_DELETE && pIter->abTblPk[i]==0 ){
166800  continue;
166801  }
166802 
166803  pVal = sqlite3_column_value(pIter->pSelect, i);
166804  p->rc = sqlite3_bind_value(pWriter, i+1, pVal);
166805  if( p->rc ) return;
166806  }
166807  if( pIter->zIdx==0 ){
166808  if( pIter->eType==RBU_PK_VTAB
166809  || pIter->eType==RBU_PK_NONE
166810  || (pIter->eType==RBU_PK_EXTERNAL && rbuIsVacuum(p))
166811  ){
166812  /* For a virtual table, or a table with no primary key, the
166813  ** SELECT statement is:
166814  **
166815  ** SELECT <cols>, rbu_control, rbu_rowid FROM ....
166816  **
166817  ** Hence column_value(pIter->nCol+1).
166818  */
166819  assertColumnName(pIter->pSelect, pIter->nCol+1,
166820  rbuIsVacuum(p) ? "rowid" : "rbu_rowid"
166821  );
166822  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
166823  p->rc = sqlite3_bind_value(pWriter, pIter->nCol+1, pVal);
166824  }
166825  }
166826  if( p->rc==SQLITE_OK ){
166827  sqlite3_step(pWriter);
166828  p->rc = resetAndCollectError(pWriter, &p->zErrmsg);
166829  }
166830 }
166831 
166832 /*
166833 ** This function does the work for an sqlite3rbu_step() call.
166834 **
166835 ** The object-iterator (p->objiter) currently points to a valid object,
166836 ** and the input cursor (p->objiter.pSelect) currently points to a valid
166837 ** input row. Perform whatever processing is required and return.
166838 **
166839 ** If no error occurs, SQLITE_OK is returned. Otherwise, an error code
166840 ** and message is left in the RBU handle and a copy of the error code
166841 ** returned.
166842 */
166843 static int rbuStep(sqlite3rbu *p){
166844  RbuObjIter *pIter = &p->objiter;
166845  const char *zMask = 0;
166846  int eType = rbuStepType(p, &zMask);
166847 
166848  if( eType ){
166849  assert( eType==RBU_INSERT || eType==RBU_DELETE
166850  || eType==RBU_REPLACE || eType==RBU_IDX_DELETE
166851  || eType==RBU_IDX_INSERT || eType==RBU_UPDATE
166852  );
166853  assert( eType!=RBU_UPDATE || pIter->zIdx==0 );
166854 
166855  if( pIter->zIdx==0 && (eType==RBU_IDX_DELETE || eType==RBU_IDX_INSERT) ){
166856  rbuBadControlError(p);
166857  }
166858  else if( eType==RBU_REPLACE ){
166859  if( pIter->zIdx==0 ){
166860  p->nPhaseOneStep += p->objiter.nIndex;
166861  rbuStepOneOp(p, RBU_DELETE);
166862  }
166863  if( p->rc==SQLITE_OK ) rbuStepOneOp(p, RBU_INSERT);
166864  }
166865  else if( eType!=RBU_UPDATE ){
166866  rbuStepOneOp(p, eType);
166867  }
166868  else{
166869  sqlite3_value *pVal;
166870  sqlite3_stmt *pUpdate = 0;
166871  assert( eType==RBU_UPDATE );
166872  p->nPhaseOneStep -= p->objiter.nIndex;
166873  rbuGetUpdateStmt(p, pIter, zMask, &pUpdate);
166874  if( pUpdate ){
166875  int i;
166876  for(i=0; p->rc==SQLITE_OK && i<pIter->nCol; i++){
166877  char c = zMask[pIter->aiSrcOrder[i]];
166878  pVal = sqlite3_column_value(pIter->pSelect, i);
166879  if( pIter->abTblPk[i] || c!='.' ){
166880  p->rc = sqlite3_bind_value(pUpdate, i+1, pVal);
166881  }
166882  }
166883  if( p->rc==SQLITE_OK
166884  && (pIter->eType==RBU_PK_VTAB || pIter->eType==RBU_PK_NONE)
166885  ){
166886  /* Bind the rbu_rowid value to column _rowid_ */
166887  assertColumnName(pIter->pSelect, pIter->nCol+1, "rbu_rowid");
166888  pVal = sqlite3_column_value(pIter->pSelect, pIter->nCol+1);
166889  p->rc = sqlite3_bind_value(pUpdate, pIter->nCol+1, pVal);
166890  }
166891  if( p->rc==SQLITE_OK ){
166892  sqlite3_step(pUpdate);
166893  p->rc = resetAndCollectError(pUpdate, &p->zErrmsg);
166894  }
166895  }
166896  }
166897  }
166898  return p->rc;
166899 }
166900 
166901 /*
166902 ** Increment the schema cookie of the main database opened by p->dbMain.
166903 **
166904 ** Or, if this is an RBU vacuum, set the schema cookie of the main db
166905 ** opened by p->dbMain to one more than the schema cookie of the main
166906 ** db opened by p->dbRbu.
166907 */
166908 static void rbuIncrSchemaCookie(sqlite3rbu *p){
166909  if( p->rc==SQLITE_OK ){
166910  sqlite3 *dbread = (rbuIsVacuum(p) ? p->dbRbu : p->dbMain);
166911  int iCookie = 1000000;
166912  sqlite3_stmt *pStmt;
166913 
166914  p->rc = prepareAndCollectError(dbread, &pStmt, &p->zErrmsg,
166915  "PRAGMA schema_version"
166916  );
166917  if( p->rc==SQLITE_OK ){
166918  /* Coverage: it may be that this sqlite3_step() cannot fail. There
166919  ** is already a transaction open, so the prepared statement cannot
166920  ** throw an SQLITE_SCHEMA exception. The only database page the
166921  ** statement reads is page 1, which is guaranteed to be in the cache.
166922  ** And no memory allocations are required. */
166923  if( SQLITE_ROW==sqlite3_step(pStmt) ){
166924  iCookie = sqlite3_column_int(pStmt, 0);
166925  }
166926  rbuFinalize(p, pStmt);
166927  }
166928  if( p->rc==SQLITE_OK ){
166929  rbuMPrintfExec(p, p->dbMain, "PRAGMA schema_version = %d", iCookie+1);
166930  }
166931  }
166932 }
166933 
166934 /*
166935 ** Update the contents of the rbu_state table within the rbu database. The
166936 ** value stored in the RBU_STATE_STAGE column is eStage. All other values
166937 ** are determined by inspecting the rbu handle passed as the first argument.
166938 */
166939 static void rbuSaveState(sqlite3rbu *p, int eStage){
166940  if( p->rc==SQLITE_OK || p->rc==SQLITE_DONE ){
166941  sqlite3_stmt *pInsert = 0;
166942  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
166943  int rc;
166944 
166945  assert( p->zErrmsg==0 );
166946  rc = prepareFreeAndCollectError(p->dbRbu, &pInsert, &p->zErrmsg,
166947  sqlite3_mprintf(
166948  "INSERT OR REPLACE INTO %s.rbu_state(k, v) VALUES "
166949  "(%d, %d), "
166950  "(%d, %Q), "
166951  "(%d, %Q), "
166952  "(%d, %d), "
166953  "(%d, %d), "
166954  "(%d, %lld), "
166955  "(%d, %lld), "
166956  "(%d, %lld), "
166957  "(%d, %lld) ",
166958  p->zStateDb,
166959  RBU_STATE_STAGE, eStage,
166960  RBU_STATE_TBL, p->objiter.zTbl,
166961  RBU_STATE_IDX, p->objiter.zIdx,
166962  RBU_STATE_ROW, p->nStep,
166963  RBU_STATE_PROGRESS, p->nProgress,
166964  RBU_STATE_CKPT, p->iWalCksum,
166965  RBU_STATE_COOKIE, (i64)pFd->iCookie,
166966  RBU_STATE_OALSZ, p->iOalSz,
166967  RBU_STATE_PHASEONESTEP, p->nPhaseOneStep
166968  )
166969  );
166970  assert( pInsert==0 || rc==SQLITE_OK );
166971 
166972  if( rc==SQLITE_OK ){
166973  sqlite3_step(pInsert);
166974  rc = sqlite3_finalize(pInsert);
166975  }
166976  if( rc!=SQLITE_OK ) p->rc = rc;
166977  }
166978 }
166979 
166980 
166981 /*
166982 ** The second argument passed to this function is the name of a PRAGMA
166983 ** setting - "page_size", "auto_vacuum", "user_version" or "application_id".
166984 ** This function executes the following on sqlite3rbu.dbRbu:
166985 **
166986 ** "PRAGMA main.$zPragma"
166987 **
166988 ** where $zPragma is the string passed as the second argument, then
166989 ** on sqlite3rbu.dbMain:
166990 **
166991 ** "PRAGMA main.$zPragma = $val"
166992 **
166993 ** where $val is the value returned by the first PRAGMA invocation.
166994 **
166995 ** In short, it copies the value of the specified PRAGMA setting from
166996 ** dbRbu to dbMain.
166997 */
166998 static void rbuCopyPragma(sqlite3rbu *p, const char *zPragma){
166999  if( p->rc==SQLITE_OK ){
167000  sqlite3_stmt *pPragma = 0;
167001  p->rc = prepareFreeAndCollectError(p->dbRbu, &pPragma, &p->zErrmsg,
167002  sqlite3_mprintf("PRAGMA main.%s", zPragma)
167003  );
167004  if( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pPragma) ){
167005  p->rc = rbuMPrintfExec(p, p->dbMain, "PRAGMA main.%s = %d",
167006  zPragma, sqlite3_column_int(pPragma, 0)
167007  );
167008  }
167009  rbuFinalize(p, pPragma);
167010  }
167011 }
167012 
167013 /*
167014 ** The RBU handle passed as the only argument has just been opened and
167015 ** the state database is empty. If this RBU handle was opened for an
167016 ** RBU vacuum operation, create the schema in the target db.
167017 */
167018 static void rbuCreateTargetSchema(sqlite3rbu *p){
167019  sqlite3_stmt *pSql = 0;
167020  sqlite3_stmt *pInsert = 0;
167021 
167022  assert( rbuIsVacuum(p) );
167023  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=1", 0,0, &p->zErrmsg);
167024  if( p->rc==SQLITE_OK ){
167025  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167026  "SELECT sql FROM sqlite_master WHERE sql!='' AND rootpage!=0"
167027  " AND name!='sqlite_sequence' "
167028  " ORDER BY type DESC"
167029  );
167030  }
167031 
167032  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167033  const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
167034  p->rc = sqlite3_exec(p->dbMain, zSql, 0, 0, &p->zErrmsg);
167035  }
167036  rbuFinalize(p, pSql);
167037  if( p->rc!=SQLITE_OK ) return;
167038 
167039  if( p->rc==SQLITE_OK ){
167040  p->rc = prepareAndCollectError(p->dbRbu, &pSql, &p->zErrmsg,
167041  "SELECT * FROM sqlite_master WHERE rootpage=0 OR rootpage IS NULL"
167042  );
167043  }
167044 
167045  if( p->rc==SQLITE_OK ){
167046  p->rc = prepareAndCollectError(p->dbMain, &pInsert, &p->zErrmsg,
167047  "INSERT INTO sqlite_master VALUES(?,?,?,?,?)"
167048  );
167049  }
167050 
167051  while( p->rc==SQLITE_OK && sqlite3_step(pSql)==SQLITE_ROW ){
167052  int i;
167053  for(i=0; i<5; i++){
167054  sqlite3_bind_value(pInsert, i+1, sqlite3_column_value(pSql, i));
167055  }
167056  sqlite3_step(pInsert);
167057  p->rc = sqlite3_reset(pInsert);
167058  }
167059  if( p->rc==SQLITE_OK ){
167060  p->rc = sqlite3_exec(p->dbMain, "PRAGMA writable_schema=0",0,0,&p->zErrmsg);
167061  }
167062 
167063  rbuFinalize(p, pSql);
167064  rbuFinalize(p, pInsert);
167065 }
167066 
167067 /*
167068 ** Step the RBU object.
167069 */
167070 SQLITE_API int SQLITE_STDCALL sqlite3rbu_step(sqlite3rbu *p){
167071  if( p ){
167072  switch( p->eStage ){
167073  case RBU_STAGE_OAL: {
167074  RbuObjIter *pIter = &p->objiter;
167075 
167076  /* If this is an RBU vacuum operation and the state table was empty
167077  ** when this handle was opened, create the target database schema. */
167078  if( rbuIsVacuum(p) && p->nProgress==0 && p->rc==SQLITE_OK ){
167079  rbuCreateTargetSchema(p);
167080  rbuCopyPragma(p, "user_version");
167081  rbuCopyPragma(p, "application_id");
167082  }
167083 
167084  while( p->rc==SQLITE_OK && pIter->zTbl ){
167085 
167086  if( pIter->bCleanup ){
167087  /* Clean up the rbu_tmp_xxx table for the previous table. It
167088  ** cannot be dropped as there are currently active SQL statements.
167089  ** But the contents can be deleted. */
167090  if( rbuIsVacuum(p)==0 && pIter->abIndexed ){
167091  rbuMPrintfExec(p, p->dbRbu,
167092  "DELETE FROM %s.'rbu_tmp_%q'", p->zStateDb, pIter->zDataTbl
167093  );
167094  }
167095  }else{
167096  rbuObjIterPrepareAll(p, pIter, 0);
167097 
167098  /* Advance to the next row to process. */
167099  if( p->rc==SQLITE_OK ){
167100  int rc = sqlite3_step(pIter->pSelect);
167101  if( rc==SQLITE_ROW ){
167102  p->nProgress++;
167103  p->nStep++;
167104  return rbuStep(p);
167105  }
167106  p->rc = sqlite3_reset(pIter->pSelect);
167107  p->nStep = 0;
167108  }
167109  }
167110 
167111  rbuObjIterNext(p, pIter);
167112  }
167113 
167114  if( p->rc==SQLITE_OK ){
167115  assert( pIter->zTbl==0 );
167116  rbuSaveState(p, RBU_STAGE_MOVE);
167117  rbuIncrSchemaCookie(p);
167118  if( p->rc==SQLITE_OK ){
167119  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
167120  }
167121  if( p->rc==SQLITE_OK ){
167122  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
167123  }
167124  p->eStage = RBU_STAGE_MOVE;
167125  }
167126  break;
167127  }
167128 
167129  case RBU_STAGE_MOVE: {
167130  if( p->rc==SQLITE_OK ){
167131  rbuMoveOalFile(p);
167132  p->nProgress++;
167133  }
167134  break;
167135  }
167136 
167137  case RBU_STAGE_CKPT: {
167138  if( p->rc==SQLITE_OK ){
167139  if( p->nStep>=p->nFrame ){
167140  sqlite3_file *pDb = p->pTargetFd->pReal;
167141 
167142  /* Sync the db file */
167143  p->rc = pDb->pMethods->xSync(pDb, SQLITE_SYNC_NORMAL);
167144 
167145  /* Update nBackfill */
167146  if( p->rc==SQLITE_OK ){
167147  void volatile *ptr;
167148  p->rc = pDb->pMethods->xShmMap(pDb, 0, 32*1024, 0, &ptr);
167149  if( p->rc==SQLITE_OK ){
167150  ((u32 volatile*)ptr)[24] = p->iMaxFrame;
167151  }
167152  }
167153 
167154  if( p->rc==SQLITE_OK ){
167155  p->eStage = RBU_STAGE_DONE;
167156  p->rc = SQLITE_DONE;
167157  }
167158  }else{
167159  RbuFrame *pFrame = &p->aFrame[p->nStep];
167160  rbuCheckpointFrame(p, pFrame);
167161  p->nStep++;
167162  }
167163  p->nProgress++;
167164  }
167165  break;
167166  }
167167 
167168  default:
167169  break;
167170  }
167171  return p->rc;
167172  }else{
167173  return SQLITE_NOMEM;
167174  }
167175 }
167176 
167177 /*
167178 ** Compare strings z1 and z2, returning 0 if they are identical, or non-zero
167179 ** otherwise. Either or both argument may be NULL. Two NULL values are
167180 ** considered equal, and NULL is considered distinct from all other values.
167181 */
167182 static int rbuStrCompare(const char *z1, const char *z2){
167183  if( z1==0 && z2==0 ) return 0;
167184  if( z1==0 || z2==0 ) return 1;
167185  return (sqlite3_stricmp(z1, z2)!=0);
167186 }
167187 
167188 /*
167189 ** This function is called as part of sqlite3rbu_open() when initializing
167190 ** an rbu handle in OAL stage. If the rbu update has not started (i.e.
167191 ** the rbu_state table was empty) it is a no-op. Otherwise, it arranges
167192 ** things so that the next call to sqlite3rbu_step() continues on from
167193 ** where the previous rbu handle left off.
167194 **
167195 ** If an error occurs, an error code and error message are left in the
167196 ** rbu handle passed as the first argument.
167197 */
167198 static void rbuSetupOal(sqlite3rbu *p, RbuState *pState){
167199  assert( p->rc==SQLITE_OK );
167200  if( pState->zTbl ){
167201  RbuObjIter *pIter = &p->objiter;
167202  int rc = SQLITE_OK;
167203 
167204  while( rc==SQLITE_OK && pIter->zTbl && (pIter->bCleanup
167205  || rbuStrCompare(pIter->zIdx, pState->zIdx)
167206  || rbuStrCompare(pIter->zTbl, pState->zTbl)
167207  )){
167208  rc = rbuObjIterNext(p, pIter);
167209  }
167210 
167211  if( rc==SQLITE_OK && !pIter->zTbl ){
167212  rc = SQLITE_ERROR;
167213  p->zErrmsg = sqlite3_mprintf("rbu_state mismatch error");
167214  }
167215 
167216  if( rc==SQLITE_OK ){
167217  p->nStep = pState->nRow;
167218  rc = rbuObjIterPrepareAll(p, &p->objiter, p->nStep);
167219  }
167220 
167221  p->rc = rc;
167222  }
167223 }
167224 
167225 /*
167226 ** If there is a "*-oal" file in the file-system corresponding to the
167227 ** target database in the file-system, delete it. If an error occurs,
167228 ** leave an error code and error message in the rbu handle.
167229 */
167230 static void rbuDeleteOalFile(sqlite3rbu *p){
167231  char *zOal = rbuMPrintf(p, "%s-oal", p->zTarget);
167232  if( zOal ){
167233  sqlite3_vfs *pVfs = sqlite3_vfs_find(0);
167234  assert( pVfs && p->rc==SQLITE_OK && p->zErrmsg==0 );
167235  pVfs->xDelete(pVfs, zOal, 0);
167236  sqlite3_free(zOal);
167237  }
167238 }
167239 
167240 /*
167241 ** Allocate a private rbu VFS for the rbu handle passed as the only
167242 ** argument. This VFS will be used unless the call to sqlite3rbu_open()
167243 ** specified a URI with a vfs=? option in place of a target database
167244 ** file name.
167245 */
167246 static void rbuCreateVfs(sqlite3rbu *p){
167247  int rnd;
167248  char zRnd[64];
167249 
167250  assert( p->rc==SQLITE_OK );
167251  sqlite3_randomness(sizeof(int), (void*)&rnd);
167252  sqlite3_snprintf(sizeof(zRnd), zRnd, "rbu_vfs_%d", rnd);
167253  p->rc = sqlite3rbu_create_vfs(zRnd, 0);
167254  if( p->rc==SQLITE_OK ){
167255  sqlite3_vfs *pVfs = sqlite3_vfs_find(zRnd);
167256  assert( pVfs );
167257  p->zVfsName = pVfs->zName;
167258  }
167259 }
167260 
167261 /*
167262 ** Destroy the private VFS created for the rbu handle passed as the only
167263 ** argument by an earlier call to rbuCreateVfs().
167264 */
167265 static void rbuDeleteVfs(sqlite3rbu *p){
167266  if( p->zVfsName ){
167267  sqlite3rbu_destroy_vfs(p->zVfsName);
167268  p->zVfsName = 0;
167269  }
167270 }
167271 
167272 /*
167273 ** This user-defined SQL function is invoked with a single argument - the
167274 ** name of a table expected to appear in the target database. It returns
167275 ** the number of auxilliary indexes on the table.
167276 */
167277 static void rbuIndexCntFunc(
167278  sqlite3_context *pCtx,
167279  int nVal,
167280  sqlite3_value **apVal
167281 ){
167282  sqlite3rbu *p = (sqlite3rbu*)sqlite3_user_data(pCtx);
167283  sqlite3_stmt *pStmt = 0;
167284  char *zErrmsg = 0;
167285  int rc;
167286 
167287  assert( nVal==1 );
167288 
167289  rc = prepareFreeAndCollectError(p->dbMain, &pStmt, &zErrmsg,
167290  sqlite3_mprintf("SELECT count(*) FROM sqlite_master "
167291  "WHERE type='index' AND tbl_name = %Q", sqlite3_value_text(apVal[0]))
167292  );
167293  if( rc!=SQLITE_OK ){
167294  sqlite3_result_error(pCtx, zErrmsg, -1);
167295  }else{
167296  int nIndex = 0;
167297  if( SQLITE_ROW==sqlite3_step(pStmt) ){
167298  nIndex = sqlite3_column_int(pStmt, 0);
167299  }
167300  rc = sqlite3_finalize(pStmt);
167301  if( rc==SQLITE_OK ){
167302  sqlite3_result_int(pCtx, nIndex);
167303  }else{
167304  sqlite3_result_error(pCtx, sqlite3_errmsg(p->dbMain), -1);
167305  }
167306  }
167307 
167308  sqlite3_free(zErrmsg);
167309 }
167310 
167311 /*
167312 ** If the RBU database contains the rbu_count table, use it to initialize
167313 ** the sqlite3rbu.nPhaseOneStep variable. The schema of the rbu_count table
167314 ** is assumed to contain the same columns as:
167315 **
167316 ** CREATE TABLE rbu_count(tbl TEXT PRIMARY KEY, cnt INTEGER) WITHOUT ROWID;
167317 **
167318 ** There should be one row in the table for each data_xxx table in the
167319 ** database. The 'tbl' column should contain the name of a data_xxx table,
167320 ** and the cnt column the number of rows it contains.
167321 **
167322 ** sqlite3rbu.nPhaseOneStep is initialized to the sum of (1 + nIndex) * cnt
167323 ** for all rows in the rbu_count table, where nIndex is the number of
167324 ** indexes on the corresponding target database table.
167325 */
167326 static void rbuInitPhaseOneSteps(sqlite3rbu *p){
167327  if( p->rc==SQLITE_OK ){
167328  sqlite3_stmt *pStmt = 0;
167329  int bExists = 0; /* True if rbu_count exists */
167330 
167331  p->nPhaseOneStep = -1;
167332 
167333  p->rc = sqlite3_create_function(p->dbRbu,
167334  "rbu_index_cnt", 1, SQLITE_UTF8, (void*)p, rbuIndexCntFunc, 0, 0
167335  );
167336 
167337  /* Check for the rbu_count table. If it does not exist, or if an error
167338  ** occurs, nPhaseOneStep will be left set to -1. */
167339  if( p->rc==SQLITE_OK ){
167340  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167341  "SELECT 1 FROM sqlite_master WHERE tbl_name = 'rbu_count'"
167342  );
167343  }
167344  if( p->rc==SQLITE_OK ){
167345  if( SQLITE_ROW==sqlite3_step(pStmt) ){
167346  bExists = 1;
167347  }
167348  p->rc = sqlite3_finalize(pStmt);
167349  }
167350 
167351  if( p->rc==SQLITE_OK && bExists ){
167352  p->rc = prepareAndCollectError(p->dbRbu, &pStmt, &p->zErrmsg,
167353  "SELECT sum(cnt * (1 + rbu_index_cnt(rbu_target_name(tbl))))"
167354  "FROM rbu_count"
167355  );
167356  if( p->rc==SQLITE_OK ){
167357  if( SQLITE_ROW==sqlite3_step(pStmt) ){
167358  p->nPhaseOneStep = sqlite3_column_int64(pStmt, 0);
167359  }
167360  p->rc = sqlite3_finalize(pStmt);
167361  }
167362  }
167363  }
167364 }
167365 
167366 
167367 static sqlite3rbu *openRbuHandle(
167368  const char *zTarget,
167369  const char *zRbu,
167370  const char *zState
167371 ){
167372  sqlite3rbu *p;
167373  size_t nTarget = zTarget ? strlen(zTarget) : 0;
167374  size_t nRbu = strlen(zRbu);
167375  size_t nState = zState ? strlen(zState) : 0;
167376  size_t nByte = sizeof(sqlite3rbu) + nTarget+1 + nRbu+1+ nState+1;
167377 
167378  p = (sqlite3rbu*)sqlite3_malloc64(nByte);
167379  if( p ){
167380  RbuState *pState = 0;
167381 
167382  /* Create the custom VFS. */
167383  memset(p, 0, sizeof(sqlite3rbu));
167384  rbuCreateVfs(p);
167385 
167386  /* Open the target, RBU and state databases */
167387  if( p->rc==SQLITE_OK ){
167388  char *pCsr = (char*)&p[1];
167389  if( zTarget ){
167390  p->zTarget = pCsr;
167391  memcpy(p->zTarget, zTarget, nTarget+1);
167392  pCsr += nTarget+1;
167393  }
167394  p->zRbu = pCsr;
167395  memcpy(p->zRbu, zRbu, nRbu+1);
167396  pCsr += nRbu+1;
167397  if( zState ){
167398  p->zState = pCsr;
167399  memcpy(p->zState, zState, nState+1);
167400  }
167401  rbuOpenDatabase(p);
167402  }
167403 
167404  if( p->rc==SQLITE_OK ){
167405  pState = rbuLoadState(p);
167406  assert( pState || p->rc!=SQLITE_OK );
167407  if( p->rc==SQLITE_OK ){
167408 
167409  if( pState->eStage==0 ){
167410  rbuDeleteOalFile(p);
167411  rbuInitPhaseOneSteps(p);
167412  p->eStage = RBU_STAGE_OAL;
167413  }else{
167414  p->eStage = pState->eStage;
167415  p->nPhaseOneStep = pState->nPhaseOneStep;
167416  }
167417  p->nProgress = pState->nProgress;
167418  p->iOalSz = pState->iOalSz;
167419  }
167420  }
167421  assert( p->rc!=SQLITE_OK || p->eStage!=0 );
167422 
167423  if( p->rc==SQLITE_OK && p->pTargetFd->pWalFd ){
167424  if( p->eStage==RBU_STAGE_OAL ){
167425  p->rc = SQLITE_ERROR;
167426  p->zErrmsg = sqlite3_mprintf("cannot update wal mode database");
167427  }else if( p->eStage==RBU_STAGE_MOVE ){
167428  p->eStage = RBU_STAGE_CKPT;
167429  p->nStep = 0;
167430  }
167431  }
167432 
167433  if( p->rc==SQLITE_OK
167434  && (p->eStage==RBU_STAGE_OAL || p->eStage==RBU_STAGE_MOVE)
167435  && pState->eStage!=0
167436  ){
167437  rbu_file *pFd = (rbuIsVacuum(p) ? p->pRbuFd : p->pTargetFd);
167438  if( pFd->iCookie!=pState->iCookie ){
167439  /* At this point (pTargetFd->iCookie) contains the value of the
167440  ** change-counter cookie (the thing that gets incremented when a
167441  ** transaction is committed in rollback mode) currently stored on
167442  ** page 1 of the database file. */
167443  p->rc = SQLITE_BUSY;
167444  p->zErrmsg = sqlite3_mprintf("database modified during rbu %s",
167445  (rbuIsVacuum(p) ? "vacuum" : "update")
167446  );
167447  }
167448  }
167449 
167450  if( p->rc==SQLITE_OK ){
167451  if( p->eStage==RBU_STAGE_OAL ){
167452  sqlite3 *db = p->dbMain;
167453 
167454  if( pState->eStage==0 && rbuIsVacuum(p) ){
167455  rbuCopyPragma(p, "page_size");
167456  rbuCopyPragma(p, "auto_vacuum");
167457  }
167458 
167459  /* Open transactions both databases. The *-oal file is opened or
167460  ** created at this point. */
167461  if( p->rc==SQLITE_OK ){
167462  p->rc = sqlite3_exec(db, "BEGIN IMMEDIATE", 0, 0, &p->zErrmsg);
167463  }
167464  if( p->rc==SQLITE_OK ){
167465  p->rc = sqlite3_exec(p->dbRbu, "BEGIN", 0, 0, &p->zErrmsg);
167466  }
167467 
167468  /* Check if the main database is a zipvfs db. If it is, set the upper
167469  ** level pager to use "journal_mode=off". This prevents it from
167470  ** generating a large journal using a temp file. */
167471  if( p->rc==SQLITE_OK ){
167472  int frc = sqlite3_file_control(db, "main", SQLITE_FCNTL_ZIPVFS, 0);
167473  if( frc==SQLITE_OK ){
167474  p->rc = sqlite3_exec(db, "PRAGMA journal_mode=off",0,0,&p->zErrmsg);
167475  }
167476  }
167477 
167478  /* Point the object iterator at the first object */
167479  if( p->rc==SQLITE_OK ){
167480  p->rc = rbuObjIterFirst(p, &p->objiter);
167481  }
167482 
167483  /* If the RBU database contains no data_xxx tables, declare the RBU
167484  ** update finished. */
167485  if( p->rc==SQLITE_OK && p->objiter.zTbl==0 ){
167486  p->rc = SQLITE_DONE;
167487  }
167488 
167489  if( p->rc==SQLITE_OK ){
167490  rbuSetupOal(p, pState);
167491  }
167492 
167493  }else if( p->eStage==RBU_STAGE_MOVE ){
167494  /* no-op */
167495  }else if( p->eStage==RBU_STAGE_CKPT ){
167496  rbuSetupCheckpoint(p, pState);
167497  }else if( p->eStage==RBU_STAGE_DONE ){
167498  p->rc = SQLITE_DONE;
167499  }else{
167500  p->rc = SQLITE_CORRUPT;
167501  }
167502  }
167503 
167504  rbuFreeState(pState);
167505  }
167506 
167507  return p;
167508 }
167509 
167510 /*
167511 ** Open and return a new RBU handle.
167512 */
167513 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_open(
167514  const char *zTarget,
167515  const char *zRbu,
167516  const char *zState
167517 ){
167518  /* TODO: Check that zTarget and zRbu are non-NULL */
167519  return openRbuHandle(zTarget, zRbu, zState);
167520 }
167521 
167522 /*
167523 ** Open a handle to begin or resume an RBU VACUUM operation.
167524 */
167525 SQLITE_API sqlite3rbu *SQLITE_STDCALL sqlite3rbu_vacuum(
167526  const char *zTarget,
167527  const char *zState
167528 ){
167529  /* TODO: Check that both arguments are non-NULL */
167530  return openRbuHandle(0, zTarget, zState);
167531 }
167532 
167533 /*
167534 ** Return the database handle used by pRbu.
167535 */
167536 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3rbu_db(sqlite3rbu *pRbu, int bRbu){
167537  sqlite3 *db = 0;
167538  if( pRbu ){
167539  db = (bRbu ? pRbu->dbRbu : pRbu->dbMain);
167540  }
167541  return db;
167542 }
167543 
167544 
167545 /*
167546 ** If the error code currently stored in the RBU handle is SQLITE_CONSTRAINT,
167547 ** then edit any error message string so as to remove all occurrences of
167548 ** the pattern "rbu_imp_[0-9]*".
167549 */
167550 static void rbuEditErrmsg(sqlite3rbu *p){
167551  if( p->rc==SQLITE_CONSTRAINT && p->zErrmsg ){
167552  unsigned int i;
167553  size_t nErrmsg = strlen(p->zErrmsg);
167554  for(i=0; i<(nErrmsg-8); i++){
167555  if( memcmp(&p->zErrmsg[i], "rbu_imp_", 8)==0 ){
167556  int nDel = 8;
167557  while( p->zErrmsg[i+nDel]>='0' && p->zErrmsg[i+nDel]<='9' ) nDel++;
167558  memmove(&p->zErrmsg[i], &p->zErrmsg[i+nDel], nErrmsg + 1 - i - nDel);
167559  nErrmsg -= nDel;
167560  }
167561  }
167562  }
167563 }
167564 
167565 /*
167566 ** Close the RBU handle.
167567 */
167568 SQLITE_API int SQLITE_STDCALL sqlite3rbu_close(sqlite3rbu *p, char **pzErrmsg){
167569  int rc;
167570  if( p ){
167571 
167572  /* Commit the transaction to the *-oal file. */
167573  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
167574  p->rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, &p->zErrmsg);
167575  }
167576 
167577  rbuSaveState(p, p->eStage);
167578 
167579  if( p->rc==SQLITE_OK && p->eStage==RBU_STAGE_OAL ){
167580  p->rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, &p->zErrmsg);
167581  }
167582 
167583  /* Close any open statement handles. */
167584  rbuObjIterFinalize(&p->objiter);
167585 
167586  /* If this is an RBU vacuum handle and the vacuum has either finished
167587  ** successfully or encountered an error, delete the contents of the
167588  ** state table. This causes the next call to sqlite3rbu_vacuum()
167589  ** specifying the current target and state databases to start a new
167590  ** vacuum from scratch. */
167591  if( rbuIsVacuum(p) && p->rc!=SQLITE_OK && p->dbRbu ){
167592  int rc2 = sqlite3_exec(p->dbRbu, "DELETE FROM stat.rbu_state", 0, 0, 0);
167593  if( p->rc==SQLITE_DONE && rc2!=SQLITE_OK ) p->rc = rc2;
167594  }
167595 
167596  /* Close the open database handle and VFS object. */
167597  sqlite3_close(p->dbRbu);
167598  sqlite3_close(p->dbMain);
167599  rbuDeleteVfs(p);
167600  sqlite3_free(p->aBuf);
167601  sqlite3_free(p->aFrame);
167602 
167603  rbuEditErrmsg(p);
167604  rc = p->rc;
167605  *pzErrmsg = p->zErrmsg;
167606  sqlite3_free(p);
167607  }else{
167608  rc = SQLITE_NOMEM;
167609  *pzErrmsg = 0;
167610  }
167611  return rc;
167612 }
167613 
167614 /*
167615 ** Return the total number of key-value operations (inserts, deletes or
167616 ** updates) that have been performed on the target database since the
167617 ** current RBU update was started.
167618 */
167619 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3rbu_progress(sqlite3rbu *pRbu){
167620  return pRbu->nProgress;
167621 }
167622 
167623 /*
167624 ** Return permyriadage progress indications for the two main stages of
167625 ** an RBU update.
167626 */
167627 SQLITE_API void SQLITE_STDCALL sqlite3rbu_bp_progress(sqlite3rbu *p, int *pnOne, int *pnTwo){
167628  const int MAX_PROGRESS = 10000;
167629  switch( p->eStage ){
167630  case RBU_STAGE_OAL:
167631  if( p->nPhaseOneStep>0 ){
167632  *pnOne = (int)(MAX_PROGRESS * (i64)p->nProgress/(i64)p->nPhaseOneStep);
167633  }else{
167634  *pnOne = -1;
167635  }
167636  *pnTwo = 0;
167637  break;
167638 
167639  case RBU_STAGE_MOVE:
167640  *pnOne = MAX_PROGRESS;
167641  *pnTwo = 0;
167642  break;
167643 
167644  case RBU_STAGE_CKPT:
167645  *pnOne = MAX_PROGRESS;
167646  *pnTwo = (int)(MAX_PROGRESS * (i64)p->nStep / (i64)p->nFrame);
167647  break;
167648 
167649  case RBU_STAGE_DONE:
167650  *pnOne = MAX_PROGRESS;
167651  *pnTwo = MAX_PROGRESS;
167652  break;
167653 
167654  default:
167655  assert( 0 );
167656  }
167657 }
167658 
167659 SQLITE_API int SQLITE_STDCALL sqlite3rbu_savestate(sqlite3rbu *p){
167660  int rc = p->rc;
167661 
167662  if( rc==SQLITE_DONE ) return SQLITE_OK;
167663 
167664  assert( p->eStage>=RBU_STAGE_OAL && p->eStage<=RBU_STAGE_DONE );
167665  if( p->eStage==RBU_STAGE_OAL ){
167666  assert( rc!=SQLITE_DONE );
167667  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "COMMIT", 0, 0, 0);
167668  }
167669 
167670  p->rc = rc;
167671  rbuSaveState(p, p->eStage);
167672  rc = p->rc;
167673 
167674  if( p->eStage==RBU_STAGE_OAL ){
167675  assert( rc!=SQLITE_DONE );
167676  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "COMMIT", 0, 0, 0);
167677  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbRbu, "BEGIN IMMEDIATE", 0, 0, 0);
167678  if( rc==SQLITE_OK ) rc = sqlite3_exec(p->dbMain, "BEGIN IMMEDIATE", 0, 0,0);
167679  }
167680 
167681  p->rc = rc;
167682  return rc;
167683 }
167684 
167685 /**************************************************************************
167686 ** Beginning of RBU VFS shim methods. The VFS shim modifies the behaviour
167687 ** of a standard VFS in the following ways:
167688 **
167689 ** 1. Whenever the first page of a main database file is read or
167690 ** written, the value of the change-counter cookie is stored in
167691 ** rbu_file.iCookie. Similarly, the value of the "write-version"
167692 ** database header field is stored in rbu_file.iWriteVer. This ensures
167693 ** that the values are always trustworthy within an open transaction.
167694 **
167695 ** 2. Whenever an SQLITE_OPEN_WAL file is opened, the (rbu_file.pWalFd)
167696 ** member variable of the associated database file descriptor is set
167697 ** to point to the new file. A mutex protected linked list of all main
167698 ** db fds opened using a particular RBU VFS is maintained at
167699 ** rbu_vfs.pMain to facilitate this.
167700 **
167701 ** 3. Using a new file-control "SQLITE_FCNTL_RBU", a main db rbu_file
167702 ** object can be marked as the target database of an RBU update. This
167703 ** turns on the following extra special behaviour:
167704 **
167705 ** 3a. If xAccess() is called to check if there exists a *-wal file
167706 ** associated with an RBU target database currently in RBU_STAGE_OAL
167707 ** stage (preparing the *-oal file), the following special handling
167708 ** applies:
167709 **
167710 ** * if the *-wal file does exist, return SQLITE_CANTOPEN. An RBU
167711 ** target database may not be in wal mode already.
167712 **
167713 ** * if the *-wal file does not exist, set the output parameter to
167714 ** non-zero (to tell SQLite that it does exist) anyway.
167715 **
167716 ** Then, when xOpen() is called to open the *-wal file associated with
167717 ** the RBU target in RBU_STAGE_OAL stage, instead of opening the *-wal
167718 ** file, the rbu vfs opens the corresponding *-oal file instead.
167719 **
167720 ** 3b. The *-shm pages returned by xShmMap() for a target db file in
167721 ** RBU_STAGE_OAL mode are actually stored in heap memory. This is to
167722 ** avoid creating a *-shm file on disk. Additionally, xShmLock() calls
167723 ** are no-ops on target database files in RBU_STAGE_OAL mode. This is
167724 ** because assert() statements in some VFS implementations fail if
167725 ** xShmLock() is called before xShmMap().
167726 **
167727 ** 3c. If an EXCLUSIVE lock is attempted on a target database file in any
167728 ** mode except RBU_STAGE_DONE (all work completed and checkpointed), it
167729 ** fails with an SQLITE_BUSY error. This is to stop RBU connections
167730 ** from automatically checkpointing a *-wal (or *-oal) file from within
167731 ** sqlite3_close().
167732 **
167733 ** 3d. In RBU_STAGE_CAPTURE mode, all xRead() calls on the wal file, and
167734 ** all xWrite() calls on the target database file perform no IO.
167735 ** Instead the frame and page numbers that would be read and written
167736 ** are recorded. Additionally, successful attempts to obtain exclusive
167737 ** xShmLock() WRITER, CHECKPOINTER and READ0 locks on the target
167738 ** database file are recorded. xShmLock() calls to unlock the same
167739 ** locks are no-ops (so that once obtained, these locks are never
167740 ** relinquished). Finally, calls to xSync() on the target database
167741 ** file fail with SQLITE_INTERNAL errors.
167742 */
167743 
167744 static void rbuUnlockShm(rbu_file *p){
167745  if( p->pRbu ){
167746  int (*xShmLock)(sqlite3_file*,int,int,int) = p->pReal->pMethods->xShmLock;
167747  int i;
167748  for(i=0; i<SQLITE_SHM_NLOCK;i++){
167749  if( (1<<i) & p->pRbu->mLock ){
167750  xShmLock(p->pReal, i, 1, SQLITE_SHM_UNLOCK|SQLITE_SHM_EXCLUSIVE);
167751  }
167752  }
167753  p->pRbu->mLock = 0;
167754  }
167755 }
167756 
167757 /*
167758 ** Close an rbu file.
167759 */
167760 static int rbuVfsClose(sqlite3_file *pFile){
167761  rbu_file *p = (rbu_file*)pFile;
167762  int rc;
167763  int i;
167764 
167765  /* Free the contents of the apShm[] array. And the array itself. */
167766  for(i=0; i<p->nShm; i++){
167767  sqlite3_free(p->apShm[i]);
167768  }
167769  sqlite3_free(p->apShm);
167770  p->apShm = 0;
167771  sqlite3_free(p->zDel);
167772 
167773  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
167774  rbu_file **pp;
167775  sqlite3_mutex_enter(p->pRbuVfs->mutex);
167776  for(pp=&p->pRbuVfs->pMain; *pp!=p; pp=&((*pp)->pMainNext));
167777  *pp = p->pMainNext;
167778  sqlite3_mutex_leave(p->pRbuVfs->mutex);
167779  rbuUnlockShm(p);
167780  p->pReal->pMethods->xShmUnmap(p->pReal, 0);
167781  }
167782 
167783  /* Close the underlying file handle */
167784  rc = p->pReal->pMethods->xClose(p->pReal);
167785  return rc;
167786 }
167787 
167788 
167789 /*
167790 ** Read and return an unsigned 32-bit big-endian integer from the buffer
167791 ** passed as the only argument.
167792 */
167793 static u32 rbuGetU32(u8 *aBuf){
167794  return ((u32)aBuf[0] << 24)
167795  + ((u32)aBuf[1] << 16)
167796  + ((u32)aBuf[2] << 8)
167797  + ((u32)aBuf[3]);
167798 }
167799 
167800 /*
167801 ** Write an unsigned 32-bit value in big-endian format to the supplied
167802 ** buffer.
167803 */
167804 static void rbuPutU32(u8 *aBuf, u32 iVal){
167805  aBuf[0] = (iVal >> 24) & 0xFF;
167806  aBuf[1] = (iVal >> 16) & 0xFF;
167807  aBuf[2] = (iVal >> 8) & 0xFF;
167808  aBuf[3] = (iVal >> 0) & 0xFF;
167809 }
167810 
167811 static void rbuPutU16(u8 *aBuf, u16 iVal){
167812  aBuf[0] = (iVal >> 8) & 0xFF;
167813  aBuf[1] = (iVal >> 0) & 0xFF;
167814 }
167815 
167816 /*
167817 ** Read data from an rbuVfs-file.
167818 */
167819 static int rbuVfsRead(
167820  sqlite3_file *pFile,
167821  void *zBuf,
167822  int iAmt,
167823  sqlite_int64 iOfst
167824 ){
167825  rbu_file *p = (rbu_file*)pFile;
167826  sqlite3rbu *pRbu = p->pRbu;
167827  int rc;
167828 
167829  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
167830  assert( p->openFlags & SQLITE_OPEN_WAL );
167831  rc = rbuCaptureWalRead(p->pRbu, iOfst, iAmt);
167832  }else{
167833  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
167834  && (p->openFlags & SQLITE_OPEN_WAL)
167835  && iOfst>=pRbu->iOalSz
167836  ){
167837  rc = SQLITE_OK;
167838  memset(zBuf, 0, iAmt);
167839  }else{
167840  rc = p->pReal->pMethods->xRead(p->pReal, zBuf, iAmt, iOfst);
167841 #if 1
167842  /* If this is being called to read the first page of the target
167843  ** database as part of an rbu vacuum operation, synthesize the
167844  ** contents of the first page if it does not yet exist. Otherwise,
167845  ** SQLite will not check for a *-wal file. */
167846  if( pRbu && rbuIsVacuum(pRbu)
167847  && rc==SQLITE_IOERR_SHORT_READ && iOfst==0
167848  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
167849  && pRbu->rc==SQLITE_OK
167850  ){
167851  sqlite3_file *pFd = (sqlite3_file*)pRbu->pRbuFd;
167852  rc = pFd->pMethods->xRead(pFd, zBuf, iAmt, iOfst);
167853  if( rc==SQLITE_OK ){
167854  u8 *aBuf = (u8*)zBuf;
167855  u32 iRoot = rbuGetU32(&aBuf[52]) ? 1 : 0;
167856  rbuPutU32(&aBuf[52], iRoot); /* largest root page number */
167857  rbuPutU32(&aBuf[36], 0); /* number of free pages */
167858  rbuPutU32(&aBuf[32], 0); /* first page on free list trunk */
167859  rbuPutU32(&aBuf[28], 1); /* size of db file in pages */
167860  rbuPutU32(&aBuf[24], pRbu->pRbuFd->iCookie+1); /* Change counter */
167861 
167862  if( iAmt>100 ){
167863  memset(&aBuf[100], 0, iAmt-100);
167864  rbuPutU16(&aBuf[105], iAmt & 0xFFFF);
167865  aBuf[100] = 0x0D;
167866  }
167867  }
167868  }
167869 #endif
167870  }
167871  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
167872  /* These look like magic numbers. But they are stable, as they are part
167873  ** of the definition of the SQLite file format, which may not change. */
167874  u8 *pBuf = (u8*)zBuf;
167875  p->iCookie = rbuGetU32(&pBuf[24]);
167876  p->iWriteVer = pBuf[19];
167877  }
167878  }
167879  return rc;
167880 }
167881 
167882 /*
167883 ** Write data to an rbuVfs-file.
167884 */
167885 static int rbuVfsWrite(
167886  sqlite3_file *pFile,
167887  const void *zBuf,
167888  int iAmt,
167889  sqlite_int64 iOfst
167890 ){
167891  rbu_file *p = (rbu_file*)pFile;
167892  sqlite3rbu *pRbu = p->pRbu;
167893  int rc;
167894 
167895  if( pRbu && pRbu->eStage==RBU_STAGE_CAPTURE ){
167896  assert( p->openFlags & SQLITE_OPEN_MAIN_DB );
167897  rc = rbuCaptureDbWrite(p->pRbu, iOfst);
167898  }else{
167899  if( pRbu && pRbu->eStage==RBU_STAGE_OAL
167900  && (p->openFlags & SQLITE_OPEN_WAL)
167901  && iOfst>=pRbu->iOalSz
167902  ){
167903  pRbu->iOalSz = iAmt + iOfst;
167904  }
167905  rc = p->pReal->pMethods->xWrite(p->pReal, zBuf, iAmt, iOfst);
167906  if( rc==SQLITE_OK && iOfst==0 && (p->openFlags & SQLITE_OPEN_MAIN_DB) ){
167907  /* These look like magic numbers. But they are stable, as they are part
167908  ** of the definition of the SQLite file format, which may not change. */
167909  u8 *pBuf = (u8*)zBuf;
167910  p->iCookie = rbuGetU32(&pBuf[24]);
167911  p->iWriteVer = pBuf[19];
167912  }
167913  }
167914  return rc;
167915 }
167916 
167917 /*
167918 ** Truncate an rbuVfs-file.
167919 */
167920 static int rbuVfsTruncate(sqlite3_file *pFile, sqlite_int64 size){
167921  rbu_file *p = (rbu_file*)pFile;
167922  return p->pReal->pMethods->xTruncate(p->pReal, size);
167923 }
167924 
167925 /*
167926 ** Sync an rbuVfs-file.
167927 */
167928 static int rbuVfsSync(sqlite3_file *pFile, int flags){
167929  rbu_file *p = (rbu_file *)pFile;
167930  if( p->pRbu && p->pRbu->eStage==RBU_STAGE_CAPTURE ){
167931  if( p->openFlags & SQLITE_OPEN_MAIN_DB ){
167932  return SQLITE_INTERNAL;
167933  }
167934  return SQLITE_OK;
167935  }
167936  return p->pReal->pMethods->xSync(p->pReal, flags);
167937 }
167938 
167939 /*
167940 ** Return the current file-size of an rbuVfs-file.
167941 */
167942 static int rbuVfsFileSize(sqlite3_file *pFile, sqlite_int64 *pSize){
167943  rbu_file *p = (rbu_file *)pFile;
167944  int rc;
167945  rc = p->pReal->pMethods->xFileSize(p->pReal, pSize);
167946 
167947  /* If this is an RBU vacuum operation and this is the target database,
167948  ** pretend that it has at least one page. Otherwise, SQLite will not
167949  ** check for the existance of a *-wal file. rbuVfsRead() contains
167950  ** similar logic. */
167951  if( rc==SQLITE_OK && *pSize==0
167952  && p->pRbu && rbuIsVacuum(p->pRbu)
167953  && (p->openFlags & SQLITE_OPEN_MAIN_DB)
167954  ){
167955  *pSize = 1024;
167956  }
167957  return rc;
167958 }
167959 
167960 /*
167961 ** Lock an rbuVfs-file.
167962 */
167963 static int rbuVfsLock(sqlite3_file *pFile, int eLock){
167964  rbu_file *p = (rbu_file*)pFile;
167965  sqlite3rbu *pRbu = p->pRbu;
167966  int rc = SQLITE_OK;
167967 
167968  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
167969  if( eLock==SQLITE_LOCK_EXCLUSIVE
167970  && (p->bNolock || (pRbu && pRbu->eStage!=RBU_STAGE_DONE))
167971  ){
167972  /* Do not allow EXCLUSIVE locks. Preventing SQLite from taking this
167973  ** prevents it from checkpointing the database from sqlite3_close(). */
167974  rc = SQLITE_BUSY;
167975  }else{
167976  rc = p->pReal->pMethods->xLock(p->pReal, eLock);
167977  }
167978 
167979  return rc;
167980 }
167981 
167982 /*
167983 ** Unlock an rbuVfs-file.
167984 */
167985 static int rbuVfsUnlock(sqlite3_file *pFile, int eLock){
167986  rbu_file *p = (rbu_file *)pFile;
167987  return p->pReal->pMethods->xUnlock(p->pReal, eLock);
167988 }
167989 
167990 /*
167991 ** Check if another file-handle holds a RESERVED lock on an rbuVfs-file.
167992 */
167993 static int rbuVfsCheckReservedLock(sqlite3_file *pFile, int *pResOut){
167994  rbu_file *p = (rbu_file *)pFile;
167995  return p->pReal->pMethods->xCheckReservedLock(p->pReal, pResOut);
167996 }
167997 
167998 /*
167999 ** File control method. For custom operations on an rbuVfs-file.
168000 */
168001 static int rbuVfsFileControl(sqlite3_file *pFile, int op, void *pArg){
168002  rbu_file *p = (rbu_file *)pFile;
168003  int (*xControl)(sqlite3_file*,int,void*) = p->pReal->pMethods->xFileControl;
168004  int rc;
168005 
168008  );
168009  if( op==SQLITE_FCNTL_RBU ){
168010  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
168011 
168012  /* First try to find another RBU vfs lower down in the vfs stack. If
168013  ** one is found, this vfs will operate in pass-through mode. The lower
168014  ** level vfs will do the special RBU handling. */
168015  rc = xControl(p->pReal, op, pArg);
168016 
168017  if( rc==SQLITE_NOTFOUND ){
168018  /* Now search for a zipvfs instance lower down in the VFS stack. If
168019  ** one is found, this is an error. */
168020  void *dummy = 0;
168021  rc = xControl(p->pReal, SQLITE_FCNTL_ZIPVFS, &dummy);
168022  if( rc==SQLITE_OK ){
168023  rc = SQLITE_ERROR;
168024  pRbu->zErrmsg = sqlite3_mprintf("rbu/zipvfs setup error");
168025  }else if( rc==SQLITE_NOTFOUND ){
168026  pRbu->pTargetFd = p;
168027  p->pRbu = pRbu;
168028  if( p->pWalFd ) p->pWalFd->pRbu = pRbu;
168029  rc = SQLITE_OK;
168030  }
168031  }
168032  return rc;
168033  }
168034  else if( op==SQLITE_FCNTL_RBUCNT ){
168035  sqlite3rbu *pRbu = (sqlite3rbu*)pArg;
168036  pRbu->nRbu++;
168037  pRbu->pRbuFd = p;
168038  p->bNolock = 1;
168039  }
168040 
168041  rc = xControl(p->pReal, op, pArg);
168042  if( rc==SQLITE_OK && op==SQLITE_FCNTL_VFSNAME ){
168043  rbu_vfs *pRbuVfs = p->pRbuVfs;
168044  char *zIn = *(char**)pArg;
168045  char *zOut = sqlite3_mprintf("rbu(%s)/%z", pRbuVfs->base.zName, zIn);
168046  *(char**)pArg = zOut;
168047  if( zOut==0 ) rc = SQLITE_NOMEM;
168048  }
168049 
168050  return rc;
168051 }
168052 
168053 /*
168054 ** Return the sector-size in bytes for an rbuVfs-file.
168055 */
168056 static int rbuVfsSectorSize(sqlite3_file *pFile){
168057  rbu_file *p = (rbu_file *)pFile;
168058  return p->pReal->pMethods->xSectorSize(p->pReal);
168059 }
168060 
168061 /*
168062 ** Return the device characteristic flags supported by an rbuVfs-file.
168063 */
168064 static int rbuVfsDeviceCharacteristics(sqlite3_file *pFile){
168065  rbu_file *p = (rbu_file *)pFile;
168066  return p->pReal->pMethods->xDeviceCharacteristics(p->pReal);
168067 }
168068 
168069 /*
168070 ** Take or release a shared-memory lock.
168071 */
168072 static int rbuVfsShmLock(sqlite3_file *pFile, int ofst, int n, int flags){
168073  rbu_file *p = (rbu_file*)pFile;
168074  sqlite3rbu *pRbu = p->pRbu;
168075  int rc = SQLITE_OK;
168076 
168077 #ifdef SQLITE_AMALGAMATION
168078  assert( WAL_CKPT_LOCK==1 );
168079 #endif
168080 
168081  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
168082  if( pRbu && (pRbu->eStage==RBU_STAGE_OAL || pRbu->eStage==RBU_STAGE_MOVE) ){
168083  /* Magic number 1 is the WAL_CKPT_LOCK lock. Preventing SQLite from
168084  ** taking this lock also prevents any checkpoints from occurring.
168085  ** todo: really, it's not clear why this might occur, as
168086  ** wal_autocheckpoint ought to be turned off. */
168087  if( ofst==WAL_LOCK_CKPT && n==1 ) rc = SQLITE_BUSY;
168088  }else{
168089  int bCapture = 0;
168090  if( n==1 && (flags & SQLITE_SHM_EXCLUSIVE)
168091  && pRbu && pRbu->eStage==RBU_STAGE_CAPTURE
168092  && (ofst==WAL_LOCK_WRITE || ofst==WAL_LOCK_CKPT || ofst==WAL_LOCK_READ0)
168093  ){
168094  bCapture = 1;
168095  }
168096 
168097  if( bCapture==0 || 0==(flags & SQLITE_SHM_UNLOCK) ){
168098  rc = p->pReal->pMethods->xShmLock(p->pReal, ofst, n, flags);
168099  if( bCapture && rc==SQLITE_OK ){
168100  pRbu->mLock |= (1 << ofst);
168101  }
168102  }
168103  }
168104 
168105  return rc;
168106 }
168107 
168108 /*
168109 ** Obtain a pointer to a mapping of a single 32KiB page of the *-shm file.
168110 */
168111 static int rbuVfsShmMap(
168112  sqlite3_file *pFile,
168113  int iRegion,
168114  int szRegion,
168115  int isWrite,
168116  void volatile **pp
168117 ){
168118  rbu_file *p = (rbu_file*)pFile;
168119  int rc = SQLITE_OK;
168120  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
168121 
168122  /* If not in RBU_STAGE_OAL, allow this call to pass through. Or, if this
168123  ** rbu is in the RBU_STAGE_OAL state, use heap memory for *-shm space
168124  ** instead of a file on disk. */
168125  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
168126  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
168127  if( iRegion<=p->nShm ){
168128  int nByte = (iRegion+1) * sizeof(char*);
168129  char **apNew = (char**)sqlite3_realloc64(p->apShm, nByte);
168130  if( apNew==0 ){
168131  rc = SQLITE_NOMEM;
168132  }else{
168133  memset(&apNew[p->nShm], 0, sizeof(char*) * (1 + iRegion - p->nShm));
168134  p->apShm = apNew;
168135  p->nShm = iRegion+1;
168136  }
168137  }
168138 
168139  if( rc==SQLITE_OK && p->apShm[iRegion]==0 ){
168140  char *pNew = (char*)sqlite3_malloc64(szRegion);
168141  if( pNew==0 ){
168142  rc = SQLITE_NOMEM;
168143  }else{
168144  memset(pNew, 0, szRegion);
168145  p->apShm[iRegion] = pNew;
168146  }
168147  }
168148 
168149  if( rc==SQLITE_OK ){
168150  *pp = p->apShm[iRegion];
168151  }else{
168152  *pp = 0;
168153  }
168154  }else{
168155  assert( p->apShm==0 );
168156  rc = p->pReal->pMethods->xShmMap(p->pReal, iRegion, szRegion, isWrite, pp);
168157  }
168158 
168159  return rc;
168160 }
168161 
168162 /*
168163 ** Memory barrier.
168164 */
168165 static void rbuVfsShmBarrier(sqlite3_file *pFile){
168166  rbu_file *p = (rbu_file *)pFile;
168167  p->pReal->pMethods->xShmBarrier(p->pReal);
168168 }
168169 
168170 /*
168171 ** The xShmUnmap method.
168172 */
168173 static int rbuVfsShmUnmap(sqlite3_file *pFile, int delFlag){
168174  rbu_file *p = (rbu_file*)pFile;
168175  int rc = SQLITE_OK;
168176  int eStage = (p->pRbu ? p->pRbu->eStage : 0);
168177 
168178  assert( p->openFlags & (SQLITE_OPEN_MAIN_DB|SQLITE_OPEN_TEMP_DB) );
168179  if( eStage==RBU_STAGE_OAL || eStage==RBU_STAGE_MOVE ){
168180  /* no-op */
168181  }else{
168182  /* Release the checkpointer and writer locks */
168183  rbuUnlockShm(p);
168184  rc = p->pReal->pMethods->xShmUnmap(p->pReal, delFlag);
168185  }
168186  return rc;
168187 }
168188 
168189 /*
168190 ** Given that zWal points to a buffer containing a wal file name passed to
168191 ** either the xOpen() or xAccess() VFS method, return a pointer to the
168192 ** file-handle opened by the same database connection on the corresponding
168193 ** database file.
168194 */
168195 static rbu_file *rbuFindMaindb(rbu_vfs *pRbuVfs, const char *zWal){
168196  rbu_file *pDb;
168197  sqlite3_mutex_enter(pRbuVfs->mutex);
168198  for(pDb=pRbuVfs->pMain; pDb && pDb->zWal!=zWal; pDb=pDb->pMainNext){}
168199  sqlite3_mutex_leave(pRbuVfs->mutex);
168200  return pDb;
168201 }
168202 
168203 /*
168204 ** A main database named zName has just been opened. The following
168205 ** function returns a pointer to a buffer owned by SQLite that contains
168206 ** the name of the *-wal file this db connection will use. SQLite
168207 ** happens to pass a pointer to this buffer when using xAccess()
168208 ** or xOpen() to operate on the *-wal file.
168209 */
168210 static const char *rbuMainToWal(const char *zName, int flags){
168211  int n = (int)strlen(zName);
168212  const char *z = &zName[n];
168213  if( flags & SQLITE_OPEN_URI ){
168214  int odd = 0;
168215  while( 1 ){
168216  if( z[0]==0 ){
168217  odd = 1 - odd;
168218  if( odd && z[1]==0 ) break;
168219  }
168220  z++;
168221  }
168222  z += 2;
168223  }else{
168224  while( *z==0 ) z++;
168225  }
168226  z += (n + 8 + 1);
168227  return z;
168228 }
168229 
168230 /*
168231 ** Open an rbu file handle.
168232 */
168233 static int rbuVfsOpen(
168234  sqlite3_vfs *pVfs,
168235  const char *zName,
168236  sqlite3_file *pFile,
168237  int flags,
168238  int *pOutFlags
168239 ){
168240  static sqlite3_io_methods rbuvfs_io_methods = {
168241  2, /* iVersion */
168242  rbuVfsClose, /* xClose */
168243  rbuVfsRead, /* xRead */
168244  rbuVfsWrite, /* xWrite */
168245  rbuVfsTruncate, /* xTruncate */
168246  rbuVfsSync, /* xSync */
168247  rbuVfsFileSize, /* xFileSize */
168248  rbuVfsLock, /* xLock */
168249  rbuVfsUnlock, /* xUnlock */
168250  rbuVfsCheckReservedLock, /* xCheckReservedLock */
168251  rbuVfsFileControl, /* xFileControl */
168252  rbuVfsSectorSize, /* xSectorSize */
168253  rbuVfsDeviceCharacteristics, /* xDeviceCharacteristics */
168254  rbuVfsShmMap, /* xShmMap */
168255  rbuVfsShmLock, /* xShmLock */
168256  rbuVfsShmBarrier, /* xShmBarrier */
168257  rbuVfsShmUnmap, /* xShmUnmap */
168258  0, 0 /* xFetch, xUnfetch */
168259  };
168260  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
168261  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
168262  rbu_file *pFd = (rbu_file *)pFile;
168263  int rc = SQLITE_OK;
168264  const char *zOpen = zName;
168265  int oflags = flags;
168266 
168267  memset(pFd, 0, sizeof(rbu_file));
168268  pFd->pReal = (sqlite3_file*)&pFd[1];
168269  pFd->pRbuVfs = pRbuVfs;
168270  pFd->openFlags = flags;
168271  if( zName ){
168272  if( flags & SQLITE_OPEN_MAIN_DB ){
168273  /* A main database has just been opened. The following block sets
168274  ** (pFd->zWal) to point to a buffer owned by SQLite that contains
168275  ** the name of the *-wal file this db connection will use. SQLite
168276  ** happens to pass a pointer to this buffer when using xAccess()
168277  ** or xOpen() to operate on the *-wal file. */
168278  pFd->zWal = rbuMainToWal(zName, flags);
168279  }
168280  else if( flags & SQLITE_OPEN_WAL ){
168281  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zName);
168282  if( pDb ){
168283  if( pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
168284  /* This call is to open a *-wal file. Intead, open the *-oal. This
168285  ** code ensures that the string passed to xOpen() is terminated by a
168286  ** pair of '\0' bytes in case the VFS attempts to extract a URI
168287  ** parameter from it. */
168288  const char *zBase = zName;
168289  size_t nCopy;
168290  char *zCopy;
168291  if( rbuIsVacuum(pDb->pRbu) ){
168292  zBase = sqlite3_db_filename(pDb->pRbu->dbRbu, "main");
168293  zBase = rbuMainToWal(zBase, SQLITE_OPEN_URI);
168294  }
168295  nCopy = strlen(zBase);
168296  zCopy = sqlite3_malloc64(nCopy+2);
168297  if( zCopy ){
168298  memcpy(zCopy, zBase, nCopy);
168299  zCopy[nCopy-3] = 'o';
168300  zCopy[nCopy] = '\0';
168301  zCopy[nCopy+1] = '\0';
168302  zOpen = (const char*)(pFd->zDel = zCopy);
168303  }else{
168304  rc = SQLITE_NOMEM;
168305  }
168306  pFd->pRbu = pDb->pRbu;
168307  }
168308  pDb->pWalFd = pFd;
168309  }
168310  }
168311  }
168312 
168313  if( oflags & SQLITE_OPEN_MAIN_DB
168314  && sqlite3_uri_boolean(zName, "rbu_memory", 0)
168315  ){
168316  assert( oflags & SQLITE_OPEN_MAIN_DB );
168319  zOpen = 0;
168320  }
168321 
168322  if( rc==SQLITE_OK ){
168323  rc = pRealVfs->xOpen(pRealVfs, zOpen, pFd->pReal, oflags, pOutFlags);
168324  }
168325  if( pFd->pReal->pMethods ){
168326  /* The xOpen() operation has succeeded. Set the sqlite3_file.pMethods
168327  ** pointer and, if the file is a main database file, link it into the
168328  ** mutex protected linked list of all such files. */
168329  pFile->pMethods = &rbuvfs_io_methods;
168330  if( flags & SQLITE_OPEN_MAIN_DB ){
168331  sqlite3_mutex_enter(pRbuVfs->mutex);
168332  pFd->pMainNext = pRbuVfs->pMain;
168333  pRbuVfs->pMain = pFd;
168334  sqlite3_mutex_leave(pRbuVfs->mutex);
168335  }
168336  }else{
168337  sqlite3_free(pFd->zDel);
168338  }
168339 
168340  return rc;
168341 }
168342 
168343 /*
168344 ** Delete the file located at zPath.
168345 */
168346 static int rbuVfsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
168347  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168348  return pRealVfs->xDelete(pRealVfs, zPath, dirSync);
168349 }
168350 
168351 /*
168352 ** Test for access permissions. Return true if the requested permission
168353 ** is available, or false otherwise.
168354 */
168355 static int rbuVfsAccess(
168356  sqlite3_vfs *pVfs,
168357  const char *zPath,
168358  int flags,
168359  int *pResOut
168360 ){
168361  rbu_vfs *pRbuVfs = (rbu_vfs*)pVfs;
168362  sqlite3_vfs *pRealVfs = pRbuVfs->pRealVfs;
168363  int rc;
168364 
168365  rc = pRealVfs->xAccess(pRealVfs, zPath, flags, pResOut);
168366 
168367  /* If this call is to check if a *-wal file associated with an RBU target
168368  ** database connection exists, and the RBU update is in RBU_STAGE_OAL,
168369  ** the following special handling is activated:
168370  **
168371  ** a) if the *-wal file does exist, return SQLITE_CANTOPEN. This
168372  ** ensures that the RBU extension never tries to update a database
168373  ** in wal mode, even if the first page of the database file has
168374  ** been damaged.
168375  **
168376  ** b) if the *-wal file does not exist, claim that it does anyway,
168377  ** causing SQLite to call xOpen() to open it. This call will also
168378  ** be intercepted (see the rbuVfsOpen() function) and the *-oal
168379  ** file opened instead.
168380  */
168381  if( rc==SQLITE_OK && flags==SQLITE_ACCESS_EXISTS ){
168382  rbu_file *pDb = rbuFindMaindb(pRbuVfs, zPath);
168383  if( pDb && pDb->pRbu && pDb->pRbu->eStage==RBU_STAGE_OAL ){
168384  if( *pResOut ){
168385  rc = SQLITE_CANTOPEN;
168386  }else{
168387  *pResOut = 1;
168388  }
168389  }
168390  }
168391 
168392  return rc;
168393 }
168394 
168395 /*
168396 ** Populate buffer zOut with the full canonical pathname corresponding
168397 ** to the pathname in zPath. zOut is guaranteed to point to a buffer
168398 ** of at least (DEVSYM_MAX_PATHNAME+1) bytes.
168399 */
168400 static int rbuVfsFullPathname(
168401  sqlite3_vfs *pVfs,
168402  const char *zPath,
168403  int nOut,
168404  char *zOut
168405 ){
168406  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168407  return pRealVfs->xFullPathname(pRealVfs, zPath, nOut, zOut);
168408 }
168409 
168410 #ifndef SQLITE_OMIT_LOAD_EXTENSION
168411 /*
168412 ** Open the dynamic library located at zPath and return a handle.
168413 */
168414 static void *rbuVfsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
168415  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168416  return pRealVfs->xDlOpen(pRealVfs, zPath);
168417 }
168418 
168419 /*
168420 ** Populate the buffer zErrMsg (size nByte bytes) with a human readable
168421 ** utf-8 string describing the most recent error encountered associated
168422 ** with dynamic libraries.
168423 */
168424 static void rbuVfsDlError(sqlite3_vfs *pVfs, int nByte, char *zErrMsg){
168425  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168426  pRealVfs->xDlError(pRealVfs, nByte, zErrMsg);
168427 }
168428 
168429 /*
168430 ** Return a pointer to the symbol zSymbol in the dynamic library pHandle.
168431 */
168432 static void (*rbuVfsDlSym(
168433  sqlite3_vfs *pVfs,
168434  void *pArg,
168435  const char *zSym
168436 ))(void){
168437  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168438  return pRealVfs->xDlSym(pRealVfs, pArg, zSym);
168439 }
168440 
168441 /*
168442 ** Close the dynamic library handle pHandle.
168443 */
168444 static void rbuVfsDlClose(sqlite3_vfs *pVfs, void *pHandle){
168445  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168446  pRealVfs->xDlClose(pRealVfs, pHandle);
168447 }
168448 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
168449 
168450 /*
168451 ** Populate the buffer pointed to by zBufOut with nByte bytes of
168452 ** random data.
168453 */
168454 static int rbuVfsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
168455  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168456  return pRealVfs->xRandomness(pRealVfs, nByte, zBufOut);
168457 }
168458 
168459 /*
168460 ** Sleep for nMicro microseconds. Return the number of microseconds
168461 ** actually slept.
168462 */
168463 static int rbuVfsSleep(sqlite3_vfs *pVfs, int nMicro){
168464  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168465  return pRealVfs->xSleep(pRealVfs, nMicro);
168466 }
168467 
168468 /*
168469 ** Return the current time as a Julian Day number in *pTimeOut.
168470 */
168471 static int rbuVfsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
168472  sqlite3_vfs *pRealVfs = ((rbu_vfs*)pVfs)->pRealVfs;
168473  return pRealVfs->xCurrentTime(pRealVfs, pTimeOut);
168474 }
168475 
168476 /*
168477 ** No-op.
168478 */
168479 static int rbuVfsGetLastError(sqlite3_vfs *pVfs, int a, char *b){
168480  return 0;
168481 }
168482 
168483 /*
168484 ** Deregister and destroy an RBU vfs created by an earlier call to
168485 ** sqlite3rbu_create_vfs().
168486 */
168487 SQLITE_API void SQLITE_STDCALL sqlite3rbu_destroy_vfs(const char *zName){
168488  sqlite3_vfs *pVfs = sqlite3_vfs_find(zName);
168489  if( pVfs && pVfs->xOpen==rbuVfsOpen ){
168490  sqlite3_mutex_free(((rbu_vfs*)pVfs)->mutex);
168491  sqlite3_vfs_unregister(pVfs);
168492  sqlite3_free(pVfs);
168493  }
168494 }
168495 
168496 /*
168497 ** Create an RBU VFS named zName that accesses the underlying file-system
168498 ** via existing VFS zParent. The new object is registered as a non-default
168499 ** VFS with SQLite before returning.
168500 */
168501 SQLITE_API int SQLITE_STDCALL sqlite3rbu_create_vfs(const char *zName, const char *zParent){
168502 
168503  /* Template for VFS */
168504  static sqlite3_vfs vfs_template = {
168505  1, /* iVersion */
168506  0, /* szOsFile */
168507  0, /* mxPathname */
168508  0, /* pNext */
168509  0, /* zName */
168510  0, /* pAppData */
168511  rbuVfsOpen, /* xOpen */
168512  rbuVfsDelete, /* xDelete */
168513  rbuVfsAccess, /* xAccess */
168514  rbuVfsFullPathname, /* xFullPathname */
168515 
168516 #ifndef SQLITE_OMIT_LOAD_EXTENSION
168517  rbuVfsDlOpen, /* xDlOpen */
168518  rbuVfsDlError, /* xDlError */
168519  rbuVfsDlSym, /* xDlSym */
168520  rbuVfsDlClose, /* xDlClose */
168521 #else
168522  0, 0, 0, 0,
168523 #endif
168524 
168525  rbuVfsRandomness, /* xRandomness */
168526  rbuVfsSleep, /* xSleep */
168527  rbuVfsCurrentTime, /* xCurrentTime */
168528  rbuVfsGetLastError, /* xGetLastError */
168529  0, /* xCurrentTimeInt64 (version 2) */
168530  0, 0, 0 /* Unimplemented version 3 methods */
168531  };
168532 
168533  rbu_vfs *pNew = 0; /* Newly allocated VFS */
168534  int rc = SQLITE_OK;
168535  size_t nName;
168536  size_t nByte;
168537 
168538  nName = strlen(zName);
168539  nByte = sizeof(rbu_vfs) + nName + 1;
168540  pNew = (rbu_vfs*)sqlite3_malloc64(nByte);
168541  if( pNew==0 ){
168542  rc = SQLITE_NOMEM;
168543  }else{
168544  sqlite3_vfs *pParent; /* Parent VFS */
168545  memset(pNew, 0, nByte);
168546  pParent = sqlite3_vfs_find(zParent);
168547  if( pParent==0 ){
168548  rc = SQLITE_NOTFOUND;
168549  }else{
168550  char *zSpace;
168551  memcpy(&pNew->base, &vfs_template, sizeof(sqlite3_vfs));
168552  pNew->base.mxPathname = pParent->mxPathname;
168553  pNew->base.szOsFile = sizeof(rbu_file) + pParent->szOsFile;
168554  pNew->pRealVfs = pParent;
168555  pNew->base.zName = (const char*)(zSpace = (char*)&pNew[1]);
168556  memcpy(zSpace, zName, nName);
168557 
168558  /* Allocate the mutex and register the new VFS (not as the default) */
168560  if( pNew->mutex==0 ){
168561  rc = SQLITE_NOMEM;
168562  }else{
168563  rc = sqlite3_vfs_register(&pNew->base, 0);
168564  }
168565  }
168566 
168567  if( rc!=SQLITE_OK ){
168568  sqlite3_mutex_free(pNew->mutex);
168569  sqlite3_free(pNew);
168570  }
168571  }
168572 
168573  return rc;
168574 }
168575 
168576 
168577 /**************************************************************************/
168578 
168579 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RBU) */
168580 
168581 /************** End of sqlite3rbu.c ******************************************/
168582 /************** Begin file dbstat.c ******************************************/
168583 /*
168584 ** 2010 July 12
168585 **
168586 ** The author disclaims copyright to this source code. In place of
168587 ** a legal notice, here is a blessing:
168588 **
168589 ** May you do good and not evil.
168590 ** May you find forgiveness for yourself and forgive others.
168591 ** May you share freely, never taking more than you give.
168592 **
168593 ******************************************************************************
168594 **
168595 ** This file contains an implementation of the "dbstat" virtual table.
168596 **
168597 ** The dbstat virtual table is used to extract low-level formatting
168598 ** information from an SQLite database in order to implement the
168599 ** "sqlite3_analyzer" utility. See the ../tool/spaceanal.tcl script
168600 ** for an example implementation.
168601 **
168602 ** Additional information is available on the "dbstat.html" page of the
168603 ** official SQLite documentation.
168604 */
168605 
168606 /* #include "sqliteInt.h" ** Requires access to internal data structures ** */
168607 #if (defined(SQLITE_ENABLE_DBSTAT_VTAB) || defined(SQLITE_TEST)) \
168608  && !defined(SQLITE_OMIT_VIRTUALTABLE)
168609 
168610 /*
168611 ** Page paths:
168612 **
168613 ** The value of the 'path' column describes the path taken from the
168614 ** root-node of the b-tree structure to each page. The value of the
168615 ** root-node path is '/'.
168616 **
168617 ** The value of the path for the left-most child page of the root of
168618 ** a b-tree is '/000/'. (Btrees store content ordered from left to right
168619 ** so the pages to the left have smaller keys than the pages to the right.)
168620 ** The next to left-most child of the root page is
168621 ** '/001', and so on, each sibling page identified by a 3-digit hex
168622 ** value. The children of the 451st left-most sibling have paths such
168623 ** as '/1c2/000/, '/1c2/001/' etc.
168624 **
168625 ** Overflow pages are specified by appending a '+' character and a
168626 ** six-digit hexadecimal value to the path to the cell they are linked
168627 ** from. For example, the three overflow pages in a chain linked from
168628 ** the left-most cell of the 450th child of the root page are identified
168629 ** by the paths:
168630 **
168631 ** '/1c2/000+000000' // First page in overflow chain
168632 ** '/1c2/000+000001' // Second page in overflow chain
168633 ** '/1c2/000+000002' // Third page in overflow chain
168634 **
168635 ** If the paths are sorted using the BINARY collation sequence, then
168636 ** the overflow pages associated with a cell will appear earlier in the
168637 ** sort-order than its child page:
168638 **
168639 ** '/1c2/000/' // Left-most child of 451st child of root
168640 */
168641 #define VTAB_SCHEMA \
168642  "CREATE TABLE xx( " \
168643  " name STRING, /* Name of table or index */" \
168644  " path INTEGER, /* Path to page from root */" \
168645  " pageno INTEGER, /* Page number */" \
168646  " pagetype STRING, /* 'internal', 'leaf' or 'overflow' */" \
168647  " ncell INTEGER, /* Cells on page (0 for overflow) */" \
168648  " payload INTEGER, /* Bytes of payload on this page */" \
168649  " unused INTEGER, /* Bytes of unused space on this page */" \
168650  " mx_payload INTEGER, /* Largest payload size of all cells */" \
168651  " pgoffset INTEGER, /* Offset of page in file */" \
168652  " pgsize INTEGER, /* Size of the page */" \
168653  " schema TEXT HIDDEN /* Database schema being analyzed */" \
168654  ");"
168655 
168656 
168657 typedef struct StatTable StatTable;
168658 typedef struct StatCursor StatCursor;
168659 typedef struct StatPage StatPage;
168660 typedef struct StatCell StatCell;
168661 
168662 struct StatCell {
168663  int nLocal; /* Bytes of local payload */
168664  u32 iChildPg; /* Child node (or 0 if this is a leaf) */
168665  int nOvfl; /* Entries in aOvfl[] */
168666  u32 *aOvfl; /* Array of overflow page numbers */
168667  int nLastOvfl; /* Bytes of payload on final overflow page */
168668  int iOvfl; /* Iterates through aOvfl[] */
168669 };
168670 
168671 struct StatPage {
168672  u32 iPgno;
168673  DbPage *pPg;
168674  int iCell;
168675 
168676  char *zPath; /* Path to this page */
168677 
168678  /* Variables populated by statDecodePage(): */
168679  u8 flags; /* Copy of flags byte */
168680  int nCell; /* Number of cells on page */
168681  int nUnused; /* Number of unused bytes on page */
168682  StatCell *aCell; /* Array of parsed cells */
168683  u32 iRightChildPg; /* Right-child page number (or 0) */
168684  int nMxPayload; /* Largest payload of any cell on this page */
168685 };
168686 
168687 struct StatCursor {
168688  sqlite3_vtab_cursor base;
168689  sqlite3_stmt *pStmt; /* Iterates through set of root pages */
168690  int isEof; /* After pStmt has returned SQLITE_DONE */
168691  int iDb; /* Schema used for this query */
168692 
168693  StatPage aPage[32];
168694  int iPage; /* Current entry in aPage[] */
168695 
168696  /* Values to return. */
168697  char *zName; /* Value of 'name' column */
168698  char *zPath; /* Value of 'path' column */
168699  u32 iPageno; /* Value of 'pageno' column */
168700  char *zPagetype; /* Value of 'pagetype' column */
168701  int nCell; /* Value of 'ncell' column */
168702  int nPayload; /* Value of 'payload' column */
168703  int nUnused; /* Value of 'unused' column */
168704  int nMxPayload; /* Value of 'mx_payload' column */
168705  i64 iOffset; /* Value of 'pgOffset' column */
168706  int szPage; /* Value of 'pgSize' column */
168707 };
168708 
168709 struct StatTable {
168710  sqlite3_vtab base;
168711  sqlite3 *db;
168712  int iDb; /* Index of database to analyze */
168713 };
168714 
168715 #ifndef get2byte
168716 # define get2byte(x) ((x)[0]<<8 | (x)[1])
168717 #endif
168718 
168719 /*
168720 ** Connect to or create a statvfs virtual table.
168721 */
168722 static int statConnect(
168723  sqlite3 *db,
168724  void *pAux,
168725  int argc, const char *const*argv,
168726  sqlite3_vtab **ppVtab,
168727  char **pzErr
168728 ){
168729  StatTable *pTab = 0;
168730  int rc = SQLITE_OK;
168731  int iDb;
168732 
168733  if( argc>=4 ){
168734  Token nm;
168735  sqlite3TokenInit(&nm, (char*)argv[3]);
168736  iDb = sqlite3FindDb(db, &nm);
168737  if( iDb<0 ){
168738  *pzErr = sqlite3_mprintf("no such database: %s", argv[3]);
168739  return SQLITE_ERROR;
168740  }
168741  }else{
168742  iDb = 0;
168743  }
168744  rc = sqlite3_declare_vtab(db, VTAB_SCHEMA);
168745  if( rc==SQLITE_OK ){
168746  pTab = (StatTable *)sqlite3_malloc64(sizeof(StatTable));
168747  if( pTab==0 ) rc = SQLITE_NOMEM_BKPT;
168748  }
168749 
168750  assert( rc==SQLITE_OK || pTab==0 );
168751  if( rc==SQLITE_OK ){
168752  memset(pTab, 0, sizeof(StatTable));
168753  pTab->db = db;
168754  pTab->iDb = iDb;
168755  }
168756 
168757  *ppVtab = (sqlite3_vtab*)pTab;
168758  return rc;
168759 }
168760 
168761 /*
168762 ** Disconnect from or destroy a statvfs virtual table.
168763 */
168764 static int statDisconnect(sqlite3_vtab *pVtab){
168765  sqlite3_free(pVtab);
168766  return SQLITE_OK;
168767 }
168768 
168769 /*
168770 ** There is no "best-index". This virtual table always does a linear
168771 ** scan. However, a schema=? constraint should cause this table to
168772 ** operate on a different database schema, so check for it.
168773 **
168774 ** idxNum is normally 0, but will be 1 if a schema=? constraint exists.
168775 */
168776 static int statBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
168777  int i;
168778 
168779  pIdxInfo->estimatedCost = 1.0e6; /* Initial cost estimate */
168780 
168781  /* Look for a valid schema=? constraint. If found, change the idxNum to
168782  ** 1 and request the value of that constraint be sent to xFilter. And
168783  ** lower the cost estimate to encourage the constrained version to be
168784  ** used.
168785  */
168786  for(i=0; i<pIdxInfo->nConstraint; i++){
168787  if( pIdxInfo->aConstraint[i].usable==0 ) continue;
168788  if( pIdxInfo->aConstraint[i].op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
168789  if( pIdxInfo->aConstraint[i].iColumn!=10 ) continue;
168790  pIdxInfo->idxNum = 1;
168791  pIdxInfo->estimatedCost = 1.0;
168792  pIdxInfo->aConstraintUsage[i].argvIndex = 1;
168793  pIdxInfo->aConstraintUsage[i].omit = 1;
168794  break;
168795  }
168796 
168797 
168798  /* Records are always returned in ascending order of (name, path).
168799  ** If this will satisfy the client, set the orderByConsumed flag so that
168800  ** SQLite does not do an external sort.
168801  */
168802  if( ( pIdxInfo->nOrderBy==1
168803  && pIdxInfo->aOrderBy[0].iColumn==0
168804  && pIdxInfo->aOrderBy[0].desc==0
168805  ) ||
168806  ( pIdxInfo->nOrderBy==2
168807  && pIdxInfo->aOrderBy[0].iColumn==0
168808  && pIdxInfo->aOrderBy[0].desc==0
168809  && pIdxInfo->aOrderBy[1].iColumn==1
168810  && pIdxInfo->aOrderBy[1].desc==0
168811  )
168812  ){
168813  pIdxInfo->orderByConsumed = 1;
168814  }
168815 
168816  return SQLITE_OK;
168817 }
168818 
168819 /*
168820 ** Open a new statvfs cursor.
168821 */
168822 static int statOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
168823  StatTable *pTab = (StatTable *)pVTab;
168824  StatCursor *pCsr;
168825 
168826  pCsr = (StatCursor *)sqlite3_malloc64(sizeof(StatCursor));
168827  if( pCsr==0 ){
168828  return SQLITE_NOMEM_BKPT;
168829  }else{
168830  memset(pCsr, 0, sizeof(StatCursor));
168831  pCsr->base.pVtab = pVTab;
168832  pCsr->iDb = pTab->iDb;
168833  }
168834 
168835  *ppCursor = (sqlite3_vtab_cursor *)pCsr;
168836  return SQLITE_OK;
168837 }
168838 
168839 static void statClearPage(StatPage *p){
168840  int i;
168841  if( p->aCell ){
168842  for(i=0; i<p->nCell; i++){
168843  sqlite3_free(p->aCell[i].aOvfl);
168844  }
168845  sqlite3_free(p->aCell);
168846  }
168847  sqlite3PagerUnref(p->pPg);
168848  sqlite3_free(p->zPath);
168849  memset(p, 0, sizeof(StatPage));
168850 }
168851 
168852 static void statResetCsr(StatCursor *pCsr){
168853  int i;
168854  sqlite3_reset(pCsr->pStmt);
168855  for(i=0; i<ArraySize(pCsr->aPage); i++){
168856  statClearPage(&pCsr->aPage[i]);
168857  }
168858  pCsr->iPage = 0;
168859  sqlite3_free(pCsr->zPath);
168860  pCsr->zPath = 0;
168861  pCsr->isEof = 0;
168862 }
168863 
168864 /*
168865 ** Close a statvfs cursor.
168866 */
168867 static int statClose(sqlite3_vtab_cursor *pCursor){
168868  StatCursor *pCsr = (StatCursor *)pCursor;
168869  statResetCsr(pCsr);
168870  sqlite3_finalize(pCsr->pStmt);
168871  sqlite3_free(pCsr);
168872  return SQLITE_OK;
168873 }
168874 
168875 static void getLocalPayload(
168876  int nUsable, /* Usable bytes per page */
168877  u8 flags, /* Page flags */
168878  int nTotal, /* Total record (payload) size */
168879  int *pnLocal /* OUT: Bytes stored locally */
168880 ){
168881  int nLocal;
168882  int nMinLocal;
168883  int nMaxLocal;
168884 
168885  if( flags==0x0D ){ /* Table leaf node */
168886  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
168887  nMaxLocal = nUsable - 35;
168888  }else{ /* Index interior and leaf nodes */
168889  nMinLocal = (nUsable - 12) * 32 / 255 - 23;
168890  nMaxLocal = (nUsable - 12) * 64 / 255 - 23;
168891  }
168892 
168893  nLocal = nMinLocal + (nTotal - nMinLocal) % (nUsable - 4);
168894  if( nLocal>nMaxLocal ) nLocal = nMinLocal;
168895  *pnLocal = nLocal;
168896 }
168897 
168898 static int statDecodePage(Btree *pBt, StatPage *p){
168899  int nUnused;
168900  int iOff;
168901  int nHdr;
168902  int isLeaf;
168903  int szPage;
168904 
168905  u8 *aData = sqlite3PagerGetData(p->pPg);
168906  u8 *aHdr = &aData[p->iPgno==1 ? 100 : 0];
168907 
168908  p->flags = aHdr[0];
168909  p->nCell = get2byte(&aHdr[3]);
168910  p->nMxPayload = 0;
168911 
168912  isLeaf = (p->flags==0x0A || p->flags==0x0D);
168913  nHdr = 12 - isLeaf*4 + (p->iPgno==1)*100;
168914 
168915  nUnused = get2byte(&aHdr[5]) - nHdr - 2*p->nCell;
168916  nUnused += (int)aHdr[7];
168917  iOff = get2byte(&aHdr[1]);
168918  while( iOff ){
168919  nUnused += get2byte(&aData[iOff+2]);
168920  iOff = get2byte(&aData[iOff]);
168921  }
168922  p->nUnused = nUnused;
168923  p->iRightChildPg = isLeaf ? 0 : sqlite3Get4byte(&aHdr[8]);
168924  szPage = sqlite3BtreeGetPageSize(pBt);
168925 
168926  if( p->nCell ){
168927  int i; /* Used to iterate through cells */
168928  int nUsable; /* Usable bytes per page */
168929 
168930  sqlite3BtreeEnter(pBt);
168931  nUsable = szPage - sqlite3BtreeGetReserveNoMutex(pBt);
168932  sqlite3BtreeLeave(pBt);
168933  p->aCell = sqlite3_malloc64((p->nCell+1) * sizeof(StatCell));
168934  if( p->aCell==0 ) return SQLITE_NOMEM_BKPT;
168935  memset(p->aCell, 0, (p->nCell+1) * sizeof(StatCell));
168936 
168937  for(i=0; i<p->nCell; i++){
168938  StatCell *pCell = &p->aCell[i];
168939 
168940  iOff = get2byte(&aData[nHdr+i*2]);
168941  if( !isLeaf ){
168942  pCell->iChildPg = sqlite3Get4byte(&aData[iOff]);
168943  iOff += 4;
168944  }
168945  if( p->flags==0x05 ){
168946  /* A table interior node. nPayload==0. */
168947  }else{
168948  u32 nPayload; /* Bytes of payload total (local+overflow) */
168949  int nLocal; /* Bytes of payload stored locally */
168950  iOff += getVarint32(&aData[iOff], nPayload);
168951  if( p->flags==0x0D ){
168952  u64 dummy;
168953  iOff += sqlite3GetVarint(&aData[iOff], &dummy);
168954  }
168955  if( nPayload>(u32)p->nMxPayload ) p->nMxPayload = nPayload;
168956  getLocalPayload(nUsable, p->flags, nPayload, &nLocal);
168957  pCell->nLocal = nLocal;
168958  assert( nLocal>=0 );
168959  assert( nPayload>=(u32)nLocal );
168960  assert( nLocal<=(nUsable-35) );
168961  if( nPayload>(u32)nLocal ){
168962  int j;
168963  int nOvfl = ((nPayload - nLocal) + nUsable-4 - 1) / (nUsable - 4);
168964  pCell->nLastOvfl = (nPayload-nLocal) - (nOvfl-1) * (nUsable-4);
168965  pCell->nOvfl = nOvfl;
168966  pCell->aOvfl = sqlite3_malloc64(sizeof(u32)*nOvfl);
168967  if( pCell->aOvfl==0 ) return SQLITE_NOMEM_BKPT;
168968  pCell->aOvfl[0] = sqlite3Get4byte(&aData[iOff+nLocal]);
168969  for(j=1; j<nOvfl; j++){
168970  int rc;
168971  u32 iPrev = pCell->aOvfl[j-1];
168972  DbPage *pPg = 0;
168973  rc = sqlite3PagerGet(sqlite3BtreePager(pBt), iPrev, &pPg, 0);
168974  if( rc!=SQLITE_OK ){
168975  assert( pPg==0 );
168976  return rc;
168977  }
168978  pCell->aOvfl[j] = sqlite3Get4byte(sqlite3PagerGetData(pPg));
168979  sqlite3PagerUnref(pPg);
168980  }
168981  }
168982  }
168983  }
168984  }
168985 
168986  return SQLITE_OK;
168987 }
168988 
168989 /*
168990 ** Populate the pCsr->iOffset and pCsr->szPage member variables. Based on
168991 ** the current value of pCsr->iPageno.
168992 */
168993 static void statSizeAndOffset(StatCursor *pCsr){
168994  StatTable *pTab = (StatTable *)((sqlite3_vtab_cursor *)pCsr)->pVtab;
168995  Btree *pBt = pTab->db->aDb[pTab->iDb].pBt;
168996  Pager *pPager = sqlite3BtreePager(pBt);
168997  sqlite3_file *fd;
168998  sqlite3_int64 x[2];
168999 
169000  /* The default page size and offset */
169001  pCsr->szPage = sqlite3BtreeGetPageSize(pBt);
169002  pCsr->iOffset = (i64)pCsr->szPage * (pCsr->iPageno - 1);
169003 
169004  /* If connected to a ZIPVFS backend, override the page size and
169005  ** offset with actual values obtained from ZIPVFS.
169006  */
169007  fd = sqlite3PagerFile(pPager);
169008  x[0] = pCsr->iPageno;
169009  if( fd->pMethods!=0 && sqlite3OsFileControl(fd, 230440, &x)==SQLITE_OK ){
169010  pCsr->iOffset = x[0];
169011  pCsr->szPage = (int)x[1];
169012  }
169013 }
169014 
169015 /*
169016 ** Move a statvfs cursor to the next entry in the file.
169017 */
169018 static int statNext(sqlite3_vtab_cursor *pCursor){
169019  int rc;
169020  int nPayload;
169021  char *z;
169022  StatCursor *pCsr = (StatCursor *)pCursor;
169023  StatTable *pTab = (StatTable *)pCursor->pVtab;
169024  Btree *pBt = pTab->db->aDb[pCsr->iDb].pBt;
169025  Pager *pPager = sqlite3BtreePager(pBt);
169026 
169027  sqlite3_free(pCsr->zPath);
169028  pCsr->zPath = 0;
169029 
169030 statNextRestart:
169031  if( pCsr->aPage[0].pPg==0 ){
169032  rc = sqlite3_step(pCsr->pStmt);
169033  if( rc==SQLITE_ROW ){
169034  int nPage;
169035  u32 iRoot = (u32)sqlite3_column_int64(pCsr->pStmt, 1);
169036  sqlite3PagerPagecount(pPager, &nPage);
169037  if( nPage==0 ){
169038  pCsr->isEof = 1;
169039  return sqlite3_reset(pCsr->pStmt);
169040  }
169041  rc = sqlite3PagerGet(pPager, iRoot, &pCsr->aPage[0].pPg, 0);
169042  pCsr->aPage[0].iPgno = iRoot;
169043  pCsr->aPage[0].iCell = 0;
169044  pCsr->aPage[0].zPath = z = sqlite3_mprintf("/");
169045  pCsr->iPage = 0;
169046  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
169047  }else{
169048  pCsr->isEof = 1;
169049  return sqlite3_reset(pCsr->pStmt);
169050  }
169051  }else{
169052 
169053  /* Page p itself has already been visited. */
169054  StatPage *p = &pCsr->aPage[pCsr->iPage];
169055 
169056  while( p->iCell<p->nCell ){
169057  StatCell *pCell = &p->aCell[p->iCell];
169058  if( pCell->iOvfl<pCell->nOvfl ){
169059  int nUsable;
169060  sqlite3BtreeEnter(pBt);
169061  nUsable = sqlite3BtreeGetPageSize(pBt) -
169063  sqlite3BtreeLeave(pBt);
169064  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
169065  pCsr->iPageno = pCell->aOvfl[pCell->iOvfl];
169066  pCsr->zPagetype = "overflow";
169067  pCsr->nCell = 0;
169068  pCsr->nMxPayload = 0;
169069  pCsr->zPath = z = sqlite3_mprintf(
169070  "%s%.3x+%.6x", p->zPath, p->iCell, pCell->iOvfl
169071  );
169072  if( pCell->iOvfl<pCell->nOvfl-1 ){
169073  pCsr->nUnused = 0;
169074  pCsr->nPayload = nUsable - 4;
169075  }else{
169076  pCsr->nPayload = pCell->nLastOvfl;
169077  pCsr->nUnused = nUsable - 4 - pCsr->nPayload;
169078  }
169079  pCell->iOvfl++;
169080  statSizeAndOffset(pCsr);
169081  return z==0 ? SQLITE_NOMEM_BKPT : SQLITE_OK;
169082  }
169083  if( p->iRightChildPg ) break;
169084  p->iCell++;
169085  }
169086 
169087  if( !p->iRightChildPg || p->iCell>p->nCell ){
169088  statClearPage(p);
169089  if( pCsr->iPage==0 ) return statNext(pCursor);
169090  pCsr->iPage--;
169091  goto statNextRestart; /* Tail recursion */
169092  }
169093  pCsr->iPage++;
169094  assert( p==&pCsr->aPage[pCsr->iPage-1] );
169095 
169096  if( p->iCell==p->nCell ){
169097  p[1].iPgno = p->iRightChildPg;
169098  }else{
169099  p[1].iPgno = p->aCell[p->iCell].iChildPg;
169100  }
169101  rc = sqlite3PagerGet(pPager, p[1].iPgno, &p[1].pPg, 0);
169102  p[1].iCell = 0;
169103  p[1].zPath = z = sqlite3_mprintf("%s%.3x/", p->zPath, p->iCell);
169104  p->iCell++;
169105  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
169106  }
169107 
169108 
169109  /* Populate the StatCursor fields with the values to be returned
169110  ** by the xColumn() and xRowid() methods.
169111  */
169112  if( rc==SQLITE_OK ){
169113  int i;
169114  StatPage *p = &pCsr->aPage[pCsr->iPage];
169115  pCsr->zName = (char *)sqlite3_column_text(pCsr->pStmt, 0);
169116  pCsr->iPageno = p->iPgno;
169117 
169118  rc = statDecodePage(pBt, p);
169119  if( rc==SQLITE_OK ){
169120  statSizeAndOffset(pCsr);
169121 
169122  switch( p->flags ){
169123  case 0x05: /* table internal */
169124  case 0x02: /* index internal */
169125  pCsr->zPagetype = "internal";
169126  break;
169127  case 0x0D: /* table leaf */
169128  case 0x0A: /* index leaf */
169129  pCsr->zPagetype = "leaf";
169130  break;
169131  default:
169132  pCsr->zPagetype = "corrupted";
169133  break;
169134  }
169135  pCsr->nCell = p->nCell;
169136  pCsr->nUnused = p->nUnused;
169137  pCsr->nMxPayload = p->nMxPayload;
169138  pCsr->zPath = z = sqlite3_mprintf("%s", p->zPath);
169139  if( z==0 ) rc = SQLITE_NOMEM_BKPT;
169140  nPayload = 0;
169141  for(i=0; i<p->nCell; i++){
169142  nPayload += p->aCell[i].nLocal;
169143  }
169144  pCsr->nPayload = nPayload;
169145  }
169146  }
169147 
169148  return rc;
169149 }
169150 
169151 static int statEof(sqlite3_vtab_cursor *pCursor){
169152  StatCursor *pCsr = (StatCursor *)pCursor;
169153  return pCsr->isEof;
169154 }
169155 
169156 static int statFilter(
169157  sqlite3_vtab_cursor *pCursor,
169158  int idxNum, const char *idxStr,
169159  int argc, sqlite3_value **argv
169160 ){
169161  StatCursor *pCsr = (StatCursor *)pCursor;
169162  StatTable *pTab = (StatTable*)(pCursor->pVtab);
169163  char *zSql;
169164  int rc = SQLITE_OK;
169165  char *zMaster;
169166 
169167  if( idxNum==1 ){
169168  const char *zDbase = (const char*)sqlite3_value_text(argv[0]);
169169  pCsr->iDb = sqlite3FindDbName(pTab->db, zDbase);
169170  if( pCsr->iDb<0 ){
169171  sqlite3_free(pCursor->pVtab->zErrMsg);
169172  pCursor->pVtab->zErrMsg = sqlite3_mprintf("no such schema: %s", zDbase);
169173  return pCursor->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM_BKPT;
169174  }
169175  }else{
169176  pCsr->iDb = pTab->iDb;
169177  }
169178  statResetCsr(pCsr);
169179  sqlite3_finalize(pCsr->pStmt);
169180  pCsr->pStmt = 0;
169181  zMaster = pCsr->iDb==1 ? "sqlite_temp_master" : "sqlite_master";
169182  zSql = sqlite3_mprintf(
169183  "SELECT 'sqlite_master' AS name, 1 AS rootpage, 'table' AS type"
169184  " UNION ALL "
169185  "SELECT name, rootpage, type"
169186  " FROM \"%w\".%s WHERE rootpage!=0"
169187  " ORDER BY name", pTab->db->aDb[pCsr->iDb].zName, zMaster);
169188  if( zSql==0 ){
169189  return SQLITE_NOMEM_BKPT;
169190  }else{
169191  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pCsr->pStmt, 0);
169192  sqlite3_free(zSql);
169193  }
169194 
169195  if( rc==SQLITE_OK ){
169196  rc = statNext(pCursor);
169197  }
169198  return rc;
169199 }
169200 
169201 static int statColumn(
169202  sqlite3_vtab_cursor *pCursor,
169203  sqlite3_context *ctx,
169204  int i
169205 ){
169206  StatCursor *pCsr = (StatCursor *)pCursor;
169207  switch( i ){
169208  case 0: /* name */
169209  sqlite3_result_text(ctx, pCsr->zName, -1, SQLITE_TRANSIENT);
169210  break;
169211  case 1: /* path */
169212  sqlite3_result_text(ctx, pCsr->zPath, -1, SQLITE_TRANSIENT);
169213  break;
169214  case 2: /* pageno */
169215  sqlite3_result_int64(ctx, pCsr->iPageno);
169216  break;
169217  case 3: /* pagetype */
169218  sqlite3_result_text(ctx, pCsr->zPagetype, -1, SQLITE_STATIC);
169219  break;
169220  case 4: /* ncell */
169221  sqlite3_result_int(ctx, pCsr->nCell);
169222  break;
169223  case 5: /* payload */
169224  sqlite3_result_int(ctx, pCsr->nPayload);
169225  break;
169226  case 6: /* unused */
169227  sqlite3_result_int(ctx, pCsr->nUnused);
169228  break;
169229  case 7: /* mx_payload */
169230  sqlite3_result_int(ctx, pCsr->nMxPayload);
169231  break;
169232  case 8: /* pgoffset */
169233  sqlite3_result_int64(ctx, pCsr->iOffset);
169234  break;
169235  case 9: /* pgsize */
169236  sqlite3_result_int(ctx, pCsr->szPage);
169237  break;
169238  default: { /* schema */
169239  sqlite3 *db = sqlite3_context_db_handle(ctx);
169240  int iDb = pCsr->iDb;
169241  sqlite3_result_text(ctx, db->aDb[iDb].zName, -1, SQLITE_STATIC);
169242  break;
169243  }
169244  }
169245  return SQLITE_OK;
169246 }
169247 
169248 static int statRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
169249  StatCursor *pCsr = (StatCursor *)pCursor;
169250  *pRowid = pCsr->iPageno;
169251  return SQLITE_OK;
169252 }
169253 
169254 /*
169255 ** Invoke this routine to register the "dbstat" virtual table module
169256 */
169257 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){
169258  static sqlite3_module dbstat_module = {
169259  0, /* iVersion */
169260  statConnect, /* xCreate */
169261  statConnect, /* xConnect */
169262  statBestIndex, /* xBestIndex */
169263  statDisconnect, /* xDisconnect */
169264  statDisconnect, /* xDestroy */
169265  statOpen, /* xOpen - open a cursor */
169266  statClose, /* xClose - close a cursor */
169267  statFilter, /* xFilter - configure scan constraints */
169268  statNext, /* xNext - advance a cursor */
169269  statEof, /* xEof - check for end of scan */
169270  statColumn, /* xColumn - read data */
169271  statRowid, /* xRowid - read data */
169272  0, /* xUpdate */
169273  0, /* xBegin */
169274  0, /* xSync */
169275  0, /* xCommit */
169276  0, /* xRollback */
169277  0, /* xFindMethod */
169278  0, /* xRename */
169279  };
169280  return sqlite3_create_module(db, "dbstat", &dbstat_module, 0);
169281 }
169282 #elif defined(SQLITE_ENABLE_DBSTAT_VTAB)
169283 SQLITE_PRIVATE int sqlite3DbstatRegister(sqlite3 *db){ return SQLITE_OK; }
169284 #endif /* SQLITE_ENABLE_DBSTAT_VTAB */
169285 
169286 /************** End of dbstat.c **********************************************/
169287 /************** Begin file sqlite3session.c **********************************/
169288 
169289 #if defined(SQLITE_ENABLE_SESSION) && defined(SQLITE_ENABLE_PREUPDATE_HOOK)
169290 /* #include "sqlite3session.h" */
169291 /* #include <assert.h> */
169292 /* #include <string.h> */
169293 
169294 #ifndef SQLITE_AMALGAMATION
169295 /* # include "sqliteInt.h" */
169296 /* # include "vdbeInt.h" */
169297 #endif
169298 
169299 typedef struct SessionTable SessionTable;
169300 typedef struct SessionChange SessionChange;
169301 typedef struct SessionBuffer SessionBuffer;
169302 typedef struct SessionInput SessionInput;
169303 
169304 /*
169305 ** Minimum chunk size used by streaming versions of functions.
169306 */
169307 #ifndef SESSIONS_STRM_CHUNK_SIZE
169308 # ifdef SQLITE_TEST
169309 # define SESSIONS_STRM_CHUNK_SIZE 64
169310 # else
169311 # define SESSIONS_STRM_CHUNK_SIZE 1024
169312 # endif
169313 #endif
169314 
169315 typedef struct SessionHook SessionHook;
169316 struct SessionHook {
169317  void *pCtx;
169318  int (*xOld)(void*,int,sqlite3_value**);
169319  int (*xNew)(void*,int,sqlite3_value**);
169320  int (*xCount)(void*);
169321  int (*xDepth)(void*);
169322 };
169323 
169324 /*
169325 ** Session handle structure.
169326 */
169327 struct sqlite3_session {
169328  sqlite3 *db; /* Database handle session is attached to */
169329  char *zDb; /* Name of database session is attached to */
169330  int bEnable; /* True if currently recording */
169331  int bIndirect; /* True if all changes are indirect */
169332  int bAutoAttach; /* True to auto-attach tables */
169333  int rc; /* Non-zero if an error has occurred */
169334  void *pFilterCtx; /* First argument to pass to xTableFilter */
169335  int (*xTableFilter)(void *pCtx, const char *zTab);
169336  sqlite3_session *pNext; /* Next session object on same db. */
169337  SessionTable *pTable; /* List of attached tables */
169338  SessionHook hook; /* APIs to grab new and old data with */
169339 };
169340 
169341 /*
169342 ** Instances of this structure are used to build strings or binary records.
169343 */
169344 struct SessionBuffer {
169345  u8 *aBuf; /* Pointer to changeset buffer */
169346  int nBuf; /* Size of buffer aBuf */
169347  int nAlloc; /* Size of allocation containing aBuf */
169348 };
169349 
169350 /*
169351 ** An object of this type is used internally as an abstraction for
169352 ** input data. Input data may be supplied either as a single large buffer
169353 ** (e.g. sqlite3changeset_start()) or using a stream function (e.g.
169354 ** sqlite3changeset_start_strm()).
169355 */
169356 struct SessionInput {
169357  int bNoDiscard; /* If true, discard no data */
169358  int iCurrent; /* Offset in aData[] of current change */
169359  int iNext; /* Offset in aData[] of next change */
169360  u8 *aData; /* Pointer to buffer containing changeset */
169361  int nData; /* Number of bytes in aData */
169362 
169363  SessionBuffer buf; /* Current read buffer */
169364  int (*xInput)(void*, void*, int*); /* Input stream call (or NULL) */
169365  void *pIn; /* First argument to xInput */
169366  int bEof; /* Set to true after xInput finished */
169367 };
169368 
169369 /*
169370 ** Structure for changeset iterators.
169371 */
169372 struct sqlite3_changeset_iter {
169373  SessionInput in; /* Input buffer or stream */
169374  SessionBuffer tblhdr; /* Buffer to hold apValue/zTab/abPK/ */
169375  int bPatchset; /* True if this is a patchset */
169376  int rc; /* Iterator error code */
169377  sqlite3_stmt *pConflict; /* Points to conflicting row, if any */
169378  char *zTab; /* Current table */
169379  int nCol; /* Number of columns in zTab */
169380  int op; /* Current operation */
169381  int bIndirect; /* True if current change was indirect */
169382  u8 *abPK; /* Primary key array */
169383  sqlite3_value **apValue; /* old.* and new.* values */
169384 };
169385 
169386 /*
169387 ** Each session object maintains a set of the following structures, one
169388 ** for each table the session object is monitoring. The structures are
169389 ** stored in a linked list starting at sqlite3_session.pTable.
169390 **
169391 ** The keys of the SessionTable.aChange[] hash table are all rows that have
169392 ** been modified in any way since the session object was attached to the
169393 ** table.
169394 **
169395 ** The data associated with each hash-table entry is a structure containing
169396 ** a subset of the initial values that the modified row contained at the
169397 ** start of the session. Or no initial values if the row was inserted.
169398 */
169399 struct SessionTable {
169400  SessionTable *pNext;
169401  char *zName; /* Local name of table */
169402  int nCol; /* Number of columns in table zName */
169403  const char **azCol; /* Column names */
169404  u8 *abPK; /* Array of primary key flags */
169405  int nEntry; /* Total number of entries in hash table */
169406  int nChange; /* Size of apChange[] array */
169407  SessionChange **apChange; /* Hash table buckets */
169408 };
169409 
169410 /*
169411 ** RECORD FORMAT:
169412 **
169413 ** The following record format is similar to (but not compatible with) that
169414 ** used in SQLite database files. This format is used as part of the
169415 ** change-set binary format, and so must be architecture independent.
169416 **
169417 ** Unlike the SQLite database record format, each field is self-contained -
169418 ** there is no separation of header and data. Each field begins with a
169419 ** single byte describing its type, as follows:
169420 **
169421 ** 0x00: Undefined value.
169422 ** 0x01: Integer value.
169423 ** 0x02: Real value.
169424 ** 0x03: Text value.
169425 ** 0x04: Blob value.
169426 ** 0x05: SQL NULL value.
169427 **
169428 ** Note that the above match the definitions of SQLITE_INTEGER, SQLITE_TEXT
169429 ** and so on in sqlite3.h. For undefined and NULL values, the field consists
169430 ** only of the single type byte. For other types of values, the type byte
169431 ** is followed by:
169432 **
169433 ** Text values:
169434 ** A varint containing the number of bytes in the value (encoded using
169435 ** UTF-8). Followed by a buffer containing the UTF-8 representation
169436 ** of the text value. There is no nul terminator.
169437 **
169438 ** Blob values:
169439 ** A varint containing the number of bytes in the value, followed by
169440 ** a buffer containing the value itself.
169441 **
169442 ** Integer values:
169443 ** An 8-byte big-endian integer value.
169444 **
169445 ** Real values:
169446 ** An 8-byte big-endian IEEE 754-2008 real value.
169447 **
169448 ** Varint values are encoded in the same way as varints in the SQLite
169449 ** record format.
169450 **
169451 ** CHANGESET FORMAT:
169452 **
169453 ** A changeset is a collection of DELETE, UPDATE and INSERT operations on
169454 ** one or more tables. Operations on a single table are grouped together,
169455 ** but may occur in any order (i.e. deletes, updates and inserts are all
169456 ** mixed together).
169457 **
169458 ** Each group of changes begins with a table header:
169459 **
169460 ** 1 byte: Constant 0x54 (capital 'T')
169461 ** Varint: Number of columns in the table.
169462 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169463 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169464 **
169465 ** Followed by one or more changes to the table.
169466 **
169467 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169468 ** 1 byte: The "indirect-change" flag.
169469 ** old.* record: (delete and update only)
169470 ** new.* record: (insert and update only)
169471 **
169472 ** The "old.*" and "new.*" records, if present, are N field records in the
169473 ** format described above under "RECORD FORMAT", where N is the number of
169474 ** columns in the table. The i'th field of each record is associated with
169475 ** the i'th column of the table, counting from left to right in the order
169476 ** in which columns were declared in the CREATE TABLE statement.
169477 **
169478 ** The new.* record that is part of each INSERT change contains the values
169479 ** that make up the new row. Similarly, the old.* record that is part of each
169480 ** DELETE change contains the values that made up the row that was deleted
169481 ** from the database. In the changeset format, the records that are part
169482 ** of INSERT or DELETE changes never contain any undefined (type byte 0x00)
169483 ** fields.
169484 **
169485 ** Within the old.* record associated with an UPDATE change, all fields
169486 ** associated with table columns that are not PRIMARY KEY columns and are
169487 ** not modified by the UPDATE change are set to "undefined". Other fields
169488 ** are set to the values that made up the row before the UPDATE that the
169489 ** change records took place. Within the new.* record, fields associated
169490 ** with table columns modified by the UPDATE change contain the new
169491 ** values. Fields associated with table columns that are not modified
169492 ** are set to "undefined".
169493 **
169494 ** PATCHSET FORMAT:
169495 **
169496 ** A patchset is also a collection of changes. It is similar to a changeset,
169497 ** but leaves undefined those fields that are not useful if no conflict
169498 ** resolution is required when applying the changeset.
169499 **
169500 ** Each group of changes begins with a table header:
169501 **
169502 ** 1 byte: Constant 0x50 (capital 'P')
169503 ** Varint: Number of columns in the table.
169504 ** nCol bytes: 0x01 for PK columns, 0x00 otherwise.
169505 ** N bytes: Unqualified table name (encoded using UTF-8). Nul-terminated.
169506 **
169507 ** Followed by one or more changes to the table.
169508 **
169509 ** 1 byte: Either SQLITE_INSERT (0x12), UPDATE (0x17) or DELETE (0x09).
169510 ** 1 byte: The "indirect-change" flag.
169511 ** single record: (PK fields for DELETE, PK and modified fields for UPDATE,
169512 ** full record for INSERT).
169513 **
169514 ** As in the changeset format, each field of the single record that is part
169515 ** of a patchset change is associated with the correspondingly positioned
169516 ** table column, counting from left to right within the CREATE TABLE
169517 ** statement.
169518 **
169519 ** For a DELETE change, all fields within the record except those associated
169520 ** with PRIMARY KEY columns are set to "undefined". The PRIMARY KEY fields
169521 ** contain the values identifying the row to delete.
169522 **
169523 ** For an UPDATE change, all fields except those associated with PRIMARY KEY
169524 ** columns and columns that are modified by the UPDATE are set to "undefined".
169525 ** PRIMARY KEY fields contain the values identifying the table row to update,
169526 ** and fields associated with modified columns contain the new column values.
169527 **
169528 ** The records associated with INSERT changes are in the same format as for
169529 ** changesets. It is not possible for a record associated with an INSERT
169530 ** change to contain a field set to "undefined".
169531 */
169532 
169533 /*
169534 ** For each row modified during a session, there exists a single instance of
169535 ** this structure stored in a SessionTable.aChange[] hash table.
169536 */
169537 struct SessionChange {
169538  int op; /* One of UPDATE, DELETE, INSERT */
169539  int bIndirect; /* True if this change is "indirect" */
169540  int nRecord; /* Number of bytes in buffer aRecord[] */
169541  u8 *aRecord; /* Buffer containing old.* record */
169542  SessionChange *pNext; /* For hash-table collisions */
169543 };
169544 
169545 /*
169546 ** Write a varint with value iVal into the buffer at aBuf. Return the
169547 ** number of bytes written.
169548 */
169549 static int sessionVarintPut(u8 *aBuf, int iVal){
169550  return putVarint32(aBuf, iVal);
169551 }
169552 
169553 /*
169554 ** Return the number of bytes required to store value iVal as a varint.
169555 */
169556 static int sessionVarintLen(int iVal){
169557  return sqlite3VarintLen(iVal);
169558 }
169559 
169560 /*
169561 ** Read a varint value from aBuf[] into *piVal. Return the number of
169562 ** bytes read.
169563 */
169564 static int sessionVarintGet(u8 *aBuf, int *piVal){
169565  return getVarint32(aBuf, *piVal);
169566 }
169567 
169568 /* Load an unaligned and unsigned 32-bit integer */
169569 #define SESSION_UINT32(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
169570 
169571 /*
169572 ** Read a 64-bit big-endian integer value from buffer aRec[]. Return
169573 ** the value read.
169574 */
169575 static sqlite3_int64 sessionGetI64(u8 *aRec){
169576  u64 x = SESSION_UINT32(aRec);
169577  u32 y = SESSION_UINT32(aRec+4);
169578  x = (x<<32) + y;
169579  return (sqlite3_int64)x;
169580 }
169581 
169582 /*
169583 ** Write a 64-bit big-endian integer value to the buffer aBuf[].
169584 */
169585 static void sessionPutI64(u8 *aBuf, sqlite3_int64 i){
169586  aBuf[0] = (i>>56) & 0xFF;
169587  aBuf[1] = (i>>48) & 0xFF;
169588  aBuf[2] = (i>>40) & 0xFF;
169589  aBuf[3] = (i>>32) & 0xFF;
169590  aBuf[4] = (i>>24) & 0xFF;
169591  aBuf[5] = (i>>16) & 0xFF;
169592  aBuf[6] = (i>> 8) & 0xFF;
169593  aBuf[7] = (i>> 0) & 0xFF;
169594 }
169595 
169596 /*
169597 ** This function is used to serialize the contents of value pValue (see
169598 ** comment titled "RECORD FORMAT" above).
169599 **
169600 ** If it is non-NULL, the serialized form of the value is written to
169601 ** buffer aBuf. *pnWrite is set to the number of bytes written before
169602 ** returning. Or, if aBuf is NULL, the only thing this function does is
169603 ** set *pnWrite.
169604 **
169605 ** If no error occurs, SQLITE_OK is returned. Or, if an OOM error occurs
169606 ** within a call to sqlite3_value_text() (may fail if the db is utf-16))
169607 ** SQLITE_NOMEM is returned.
169608 */
169609 static int sessionSerializeValue(
169610  u8 *aBuf, /* If non-NULL, write serialized value here */
169611  sqlite3_value *pValue, /* Value to serialize */
169612  int *pnWrite /* IN/OUT: Increment by bytes written */
169613 ){
169614  int nByte; /* Size of serialized value in bytes */
169615 
169616  if( pValue ){
169617  int eType; /* Value type (SQLITE_NULL, TEXT etc.) */
169618 
169619  eType = sqlite3_value_type(pValue);
169620  if( aBuf ) aBuf[0] = eType;
169621 
169622  switch( eType ){
169623  case SQLITE_NULL:
169624  nByte = 1;
169625  break;
169626 
169627  case SQLITE_INTEGER:
169628  case SQLITE_FLOAT:
169629  if( aBuf ){
169630  /* TODO: SQLite does something special to deal with mixed-endian
169631  ** floating point values (e.g. ARM7). This code probably should
169632  ** too. */
169633  u64 i;
169634  if( eType==SQLITE_INTEGER ){
169635  i = (u64)sqlite3_value_int64(pValue);
169636  }else{
169637  double r;
169638  assert( sizeof(double)==8 && sizeof(u64)==8 );
169639  r = sqlite3_value_double(pValue);
169640  memcpy(&i, &r, 8);
169641  }
169642  sessionPutI64(&aBuf[1], i);
169643  }
169644  nByte = 9;
169645  break;
169646 
169647  default: {
169648  u8 *z;
169649  int n;
169650  int nVarint;
169651 
169652  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
169653  if( eType==SQLITE_TEXT ){
169654  z = (u8 *)sqlite3_value_text(pValue);
169655  }else{
169656  z = (u8 *)sqlite3_value_blob(pValue);
169657  }
169658  n = sqlite3_value_bytes(pValue);
169659  if( z==0 && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169660  nVarint = sessionVarintLen(n);
169661 
169662  if( aBuf ){
169663  sessionVarintPut(&aBuf[1], n);
169664  memcpy(&aBuf[nVarint + 1], eType==SQLITE_TEXT ?
169665  sqlite3_value_text(pValue) : sqlite3_value_blob(pValue), n
169666  );
169667  }
169668 
169669  nByte = 1 + nVarint + n;
169670  break;
169671  }
169672  }
169673  }else{
169674  nByte = 1;
169675  if( aBuf ) aBuf[0] = '\0';
169676  }
169677 
169678  if( pnWrite ) *pnWrite += nByte;
169679  return SQLITE_OK;
169680 }
169681 
169682 
169683 /*
169684 ** This macro is used to calculate hash key values for data structures. In
169685 ** order to use this macro, the entire data structure must be represented
169686 ** as a series of unsigned integers. In order to calculate a hash-key value
169687 ** for a data structure represented as three such integers, the macro may
169688 ** then be used as follows:
169689 **
169690 ** int hash_key_value;
169691 ** hash_key_value = HASH_APPEND(0, <value 1>);
169692 ** hash_key_value = HASH_APPEND(hash_key_value, <value 2>);
169693 ** hash_key_value = HASH_APPEND(hash_key_value, <value 3>);
169694 **
169695 ** In practice, the data structures this macro is used for are the primary
169696 ** key values of modified rows.
169697 */
169698 #define HASH_APPEND(hash, add) ((hash) << 3) ^ (hash) ^ (unsigned int)(add)
169699 
169700 /*
169701 ** Append the hash of the 64-bit integer passed as the second argument to the
169702 ** hash-key value passed as the first. Return the new hash-key value.
169703 */
169704 static unsigned int sessionHashAppendI64(unsigned int h, i64 i){
169705  h = HASH_APPEND(h, i & 0xFFFFFFFF);
169706  return HASH_APPEND(h, (i>>32)&0xFFFFFFFF);
169707 }
169708 
169709 /*
169710 ** Append the hash of the blob passed via the second and third arguments to
169711 ** the hash-key value passed as the first. Return the new hash-key value.
169712 */
169713 static unsigned int sessionHashAppendBlob(unsigned int h, int n, const u8 *z){
169714  int i;
169715  for(i=0; i<n; i++) h = HASH_APPEND(h, z[i]);
169716  return h;
169717 }
169718 
169719 /*
169720 ** Append the hash of the data type passed as the second argument to the
169721 ** hash-key value passed as the first. Return the new hash-key value.
169722 */
169723 static unsigned int sessionHashAppendType(unsigned int h, int eType){
169724  return HASH_APPEND(h, eType);
169725 }
169726 
169727 /*
169728 ** This function may only be called from within a pre-update callback.
169729 ** It calculates a hash based on the primary key values of the old.* or
169730 ** new.* row currently available and, assuming no error occurs, writes it to
169731 ** *piHash before returning. If the primary key contains one or more NULL
169732 ** values, *pbNullPK is set to true before returning.
169733 **
169734 ** If an error occurs, an SQLite error code is returned and the final values
169735 ** of *piHash asn *pbNullPK are undefined. Otherwise, SQLITE_OK is returned
169736 ** and the output variables are set as described above.
169737 */
169738 static int sessionPreupdateHash(
169739  sqlite3_session *pSession, /* Session object that owns pTab */
169740  SessionTable *pTab, /* Session table handle */
169741  int bNew, /* True to hash the new.* PK */
169742  int *piHash, /* OUT: Hash value */
169743  int *pbNullPK /* OUT: True if there are NULL values in PK */
169744 ){
169745  unsigned int h = 0; /* Hash value to return */
169746  int i; /* Used to iterate through columns */
169747 
169748  assert( *pbNullPK==0 );
169749  assert( pTab->nCol==pSession->hook.xCount(pSession->hook.pCtx) );
169750  for(i=0; i<pTab->nCol; i++){
169751  if( pTab->abPK[i] ){
169752  int rc;
169753  int eType;
169754  sqlite3_value *pVal;
169755 
169756  if( bNew ){
169757  rc = pSession->hook.xNew(pSession->hook.pCtx, i, &pVal);
169758  }else{
169759  rc = pSession->hook.xOld(pSession->hook.pCtx, i, &pVal);
169760  }
169761  if( rc!=SQLITE_OK ) return rc;
169762 
169763  eType = sqlite3_value_type(pVal);
169764  h = sessionHashAppendType(h, eType);
169765  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169766  i64 iVal;
169767  if( eType==SQLITE_INTEGER ){
169768  iVal = sqlite3_value_int64(pVal);
169769  }else{
169770  double rVal = sqlite3_value_double(pVal);
169771  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
169772  memcpy(&iVal, &rVal, 8);
169773  }
169774  h = sessionHashAppendI64(h, iVal);
169775  }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
169776  const u8 *z;
169777  int n;
169778  if( eType==SQLITE_TEXT ){
169779  z = (const u8 *)sqlite3_value_text(pVal);
169780  }else{
169781  z = (const u8 *)sqlite3_value_blob(pVal);
169782  }
169783  n = sqlite3_value_bytes(pVal);
169784  if( !z && (eType!=SQLITE_BLOB || n>0) ) return SQLITE_NOMEM;
169785  h = sessionHashAppendBlob(h, n, z);
169786  }else{
169787  assert( eType==SQLITE_NULL );
169788  *pbNullPK = 1;
169789  }
169790  }
169791  }
169792 
169793  *piHash = (h % pTab->nChange);
169794  return SQLITE_OK;
169795 }
169796 
169797 /*
169798 ** The buffer that the argument points to contains a serialized SQL value.
169799 ** Return the number of bytes of space occupied by the value (including
169800 ** the type byte).
169801 */
169802 static int sessionSerialLen(u8 *a){
169803  int e = *a;
169804  int n;
169805  if( e==0 ) return 1;
169806  if( e==SQLITE_NULL ) return 1;
169807  if( e==SQLITE_INTEGER || e==SQLITE_FLOAT ) return 9;
169808  return sessionVarintGet(&a[1], &n) + 1 + n;
169809 }
169810 
169811 /*
169812 ** Based on the primary key values stored in change aRecord, calculate a
169813 ** hash key. Assume the has table has nBucket buckets. The hash keys
169814 ** calculated by this function are compatible with those calculated by
169815 ** sessionPreupdateHash().
169816 **
169817 ** The bPkOnly argument is non-zero if the record at aRecord[] is from
169818 ** a patchset DELETE. In this case the non-PK fields are omitted entirely.
169819 */
169820 static unsigned int sessionChangeHash(
169821  SessionTable *pTab, /* Table handle */
169822  int bPkOnly, /* Record consists of PK fields only */
169823  u8 *aRecord, /* Change record */
169824  int nBucket /* Assume this many buckets in hash table */
169825 ){
169826  unsigned int h = 0; /* Value to return */
169827  int i; /* Used to iterate through columns */
169828  u8 *a = aRecord; /* Used to iterate through change record */
169829 
169830  for(i=0; i<pTab->nCol; i++){
169831  int eType = *a;
169832  int isPK = pTab->abPK[i];
169833  if( bPkOnly && isPK==0 ) continue;
169834 
169835  /* It is not possible for eType to be SQLITE_NULL here. The session
169836  ** module does not record changes for rows with NULL values stored in
169837  ** primary key columns. */
169838  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
169839  || eType==SQLITE_TEXT || eType==SQLITE_BLOB
169840  || eType==SQLITE_NULL || eType==0
169841  );
169842  assert( !isPK || (eType!=0 && eType!=SQLITE_NULL) );
169843 
169844  if( isPK ){
169845  a++;
169846  h = sessionHashAppendType(h, eType);
169847  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
169848  h = sessionHashAppendI64(h, sessionGetI64(a));
169849  a += 8;
169850  }else{
169851  int n;
169852  a += sessionVarintGet(a, &n);
169853  h = sessionHashAppendBlob(h, n, a);
169854  a += n;
169855  }
169856  }else{
169857  a += sessionSerialLen(a);
169858  }
169859  }
169860  return (h % nBucket);
169861 }
169862 
169863 /*
169864 ** Arguments aLeft and aRight are pointers to change records for table pTab.
169865 ** This function returns true if the two records apply to the same row (i.e.
169866 ** have the same values stored in the primary key columns), or false
169867 ** otherwise.
169868 */
169869 static int sessionChangeEqual(
169870  SessionTable *pTab, /* Table used for PK definition */
169871  int bLeftPkOnly, /* True if aLeft[] contains PK fields only */
169872  u8 *aLeft, /* Change record */
169873  int bRightPkOnly, /* True if aRight[] contains PK fields only */
169874  u8 *aRight /* Change record */
169875 ){
169876  u8 *a1 = aLeft; /* Cursor to iterate through aLeft */
169877  u8 *a2 = aRight; /* Cursor to iterate through aRight */
169878  int iCol; /* Used to iterate through table columns */
169879 
169880  for(iCol=0; iCol<pTab->nCol; iCol++){
169881  if( pTab->abPK[iCol] ){
169882  int n1 = sessionSerialLen(a1);
169883  int n2 = sessionSerialLen(a2);
169884 
169885  if( pTab->abPK[iCol] && (n1!=n2 || memcmp(a1, a2, n1)) ){
169886  return 0;
169887  }
169888  a1 += n1;
169889  a2 += n2;
169890  }else{
169891  if( bLeftPkOnly==0 ) a1 += sessionSerialLen(a1);
169892  if( bRightPkOnly==0 ) a2 += sessionSerialLen(a2);
169893  }
169894  }
169895 
169896  return 1;
169897 }
169898 
169899 /*
169900 ** Arguments aLeft and aRight both point to buffers containing change
169901 ** records with nCol columns. This function "merges" the two records into
169902 ** a single records which is written to the buffer at *paOut. *paOut is
169903 ** then set to point to one byte after the last byte written before
169904 ** returning.
169905 **
169906 ** The merging of records is done as follows: For each column, if the
169907 ** aRight record contains a value for the column, copy the value from
169908 ** their. Otherwise, if aLeft contains a value, copy it. If neither
169909 ** record contains a value for a given column, then neither does the
169910 ** output record.
169911 */
169912 static void sessionMergeRecord(
169913  u8 **paOut,
169914  int nCol,
169915  u8 *aLeft,
169916  u8 *aRight
169917 ){
169918  u8 *a1 = aLeft; /* Cursor used to iterate through aLeft */
169919  u8 *a2 = aRight; /* Cursor used to iterate through aRight */
169920  u8 *aOut = *paOut; /* Output cursor */
169921  int iCol; /* Used to iterate from 0 to nCol */
169922 
169923  for(iCol=0; iCol<nCol; iCol++){
169924  int n1 = sessionSerialLen(a1);
169925  int n2 = sessionSerialLen(a2);
169926  if( *a2 ){
169927  memcpy(aOut, a2, n2);
169928  aOut += n2;
169929  }else{
169930  memcpy(aOut, a1, n1);
169931  aOut += n1;
169932  }
169933  a1 += n1;
169934  a2 += n2;
169935  }
169936 
169937  *paOut = aOut;
169938 }
169939 
169940 /*
169941 ** This is a helper function used by sessionMergeUpdate().
169942 **
169943 ** When this function is called, both *paOne and *paTwo point to a value
169944 ** within a change record. Before it returns, both have been advanced so
169945 ** as to point to the next value in the record.
169946 **
169947 ** If, when this function is called, *paTwo points to a valid value (i.e.
169948 ** *paTwo[0] is not 0x00 - the "no value" placeholder), a copy of the *paTwo
169949 ** pointer is returned and *pnVal is set to the number of bytes in the
169950 ** serialized value. Otherwise, a copy of *paOne is returned and *pnVal
169951 ** set to the number of bytes in the value at *paOne. If *paOne points
169952 ** to the "no value" placeholder, *pnVal is set to 1. In other words:
169953 **
169954 ** if( *paTwo is valid ) return *paTwo;
169955 ** return *paOne;
169956 **
169957 */
169958 static u8 *sessionMergeValue(
169959  u8 **paOne, /* IN/OUT: Left-hand buffer pointer */
169960  u8 **paTwo, /* IN/OUT: Right-hand buffer pointer */
169961  int *pnVal /* OUT: Bytes in returned value */
169962 ){
169963  u8 *a1 = *paOne;
169964  u8 *a2 = *paTwo;
169965  u8 *pRet = 0;
169966  int n1;
169967 
169968  assert( a1 );
169969  if( a2 ){
169970  int n2 = sessionSerialLen(a2);
169971  if( *a2 ){
169972  *pnVal = n2;
169973  pRet = a2;
169974  }
169975  *paTwo = &a2[n2];
169976  }
169977 
169978  n1 = sessionSerialLen(a1);
169979  if( pRet==0 ){
169980  *pnVal = n1;
169981  pRet = a1;
169982  }
169983  *paOne = &a1[n1];
169984 
169985  return pRet;
169986 }
169987 
169988 /*
169989 ** This function is used by changeset_concat() to merge two UPDATE changes
169990 ** on the same row.
169991 */
169992 static int sessionMergeUpdate(
169993  u8 **paOut, /* IN/OUT: Pointer to output buffer */
169994  SessionTable *pTab, /* Table change pertains to */
169995  int bPatchset, /* True if records are patchset records */
169996  u8 *aOldRecord1, /* old.* record for first change */
169997  u8 *aOldRecord2, /* old.* record for second change */
169998  u8 *aNewRecord1, /* new.* record for first change */
169999  u8 *aNewRecord2 /* new.* record for second change */
170000 ){
170001  u8 *aOld1 = aOldRecord1;
170002  u8 *aOld2 = aOldRecord2;
170003  u8 *aNew1 = aNewRecord1;
170004  u8 *aNew2 = aNewRecord2;
170005 
170006  u8 *aOut = *paOut;
170007  int i;
170008 
170009  if( bPatchset==0 ){
170010  int bRequired = 0;
170011 
170012  assert( aOldRecord1 && aNewRecord1 );
170013 
170014  /* Write the old.* vector first. */
170015  for(i=0; i<pTab->nCol; i++){
170016  int nOld;
170017  u8 *aOld;
170018  int nNew;
170019  u8 *aNew;
170020 
170021  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170022  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170023  if( pTab->abPK[i] || nOld!=nNew || memcmp(aOld, aNew, nNew) ){
170024  if( pTab->abPK[i]==0 ) bRequired = 1;
170025  memcpy(aOut, aOld, nOld);
170026  aOut += nOld;
170027  }else{
170028  *(aOut++) = '\0';
170029  }
170030  }
170031 
170032  if( !bRequired ) return 0;
170033  }
170034 
170035  /* Write the new.* vector */
170036  aOld1 = aOldRecord1;
170037  aOld2 = aOldRecord2;
170038  aNew1 = aNewRecord1;
170039  aNew2 = aNewRecord2;
170040  for(i=0; i<pTab->nCol; i++){
170041  int nOld;
170042  u8 *aOld;
170043  int nNew;
170044  u8 *aNew;
170045 
170046  aOld = sessionMergeValue(&aOld1, &aOld2, &nOld);
170047  aNew = sessionMergeValue(&aNew1, &aNew2, &nNew);
170048  if( bPatchset==0
170049  && (pTab->abPK[i] || (nOld==nNew && 0==memcmp(aOld, aNew, nNew)))
170050  ){
170051  *(aOut++) = '\0';
170052  }else{
170053  memcpy(aOut, aNew, nNew);
170054  aOut += nNew;
170055  }
170056  }
170057 
170058  *paOut = aOut;
170059  return 1;
170060 }
170061 
170062 /*
170063 ** This function is only called from within a pre-update-hook callback.
170064 ** It determines if the current pre-update-hook change affects the same row
170065 ** as the change stored in argument pChange. If so, it returns true. Otherwise
170066 ** if the pre-update-hook does not affect the same row as pChange, it returns
170067 ** false.
170068 */
170069 static int sessionPreupdateEqual(
170070  sqlite3_session *pSession, /* Session object that owns SessionTable */
170071  SessionTable *pTab, /* Table associated with change */
170072  SessionChange *pChange, /* Change to compare to */
170073  int op /* Current pre-update operation */
170074 ){
170075  int iCol; /* Used to iterate through columns */
170076  u8 *a = pChange->aRecord; /* Cursor used to scan change record */
170077 
170078  assert( op==SQLITE_INSERT || op==SQLITE_UPDATE || op==SQLITE_DELETE );
170079  for(iCol=0; iCol<pTab->nCol; iCol++){
170080  if( !pTab->abPK[iCol] ){
170081  a += sessionSerialLen(a);
170082  }else{
170083  sqlite3_value *pVal; /* Value returned by preupdate_new/old */
170084  int rc; /* Error code from preupdate_new/old */
170085  int eType = *a++; /* Type of value from change record */
170086 
170087  /* The following calls to preupdate_new() and preupdate_old() can not
170088  ** fail. This is because they cache their return values, and by the
170089  ** time control flows to here they have already been called once from
170090  ** within sessionPreupdateHash(). The first two asserts below verify
170091  ** this (that the method has already been called). */
170092  if( op==SQLITE_INSERT ){
170093  /* assert( db->pPreUpdate->pNewUnpacked || db->pPreUpdate->aNew ); */
170094  rc = pSession->hook.xNew(pSession->hook.pCtx, iCol, &pVal);
170095  }else{
170096  /* assert( db->pPreUpdate->pUnpacked ); */
170097  rc = pSession->hook.xOld(pSession->hook.pCtx, iCol, &pVal);
170098  }
170099  assert( rc==SQLITE_OK );
170100  if( sqlite3_value_type(pVal)!=eType ) return 0;
170101 
170102  /* A SessionChange object never has a NULL value in a PK column */
170103  assert( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT
170104  || eType==SQLITE_BLOB || eType==SQLITE_TEXT
170105  );
170106 
170107  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
170108  i64 iVal = sessionGetI64(a);
170109  a += 8;
170110  if( eType==SQLITE_INTEGER ){
170111  if( sqlite3_value_int64(pVal)!=iVal ) return 0;
170112  }else{
170113  double rVal;
170114  assert( sizeof(iVal)==8 && sizeof(rVal)==8 );
170115  memcpy(&rVal, &iVal, 8);
170116  if( sqlite3_value_double(pVal)!=rVal ) return 0;
170117  }
170118  }else{
170119  int n;
170120  const u8 *z;
170121  a += sessionVarintGet(a, &n);
170122  if( sqlite3_value_bytes(pVal)!=n ) return 0;
170123  if( eType==SQLITE_TEXT ){
170124  z = sqlite3_value_text(pVal);
170125  }else{
170126  z = sqlite3_value_blob(pVal);
170127  }
170128  if( memcmp(a, z, n) ) return 0;
170129  a += n;
170130  break;
170131  }
170132  }
170133  }
170134 
170135  return 1;
170136 }
170137 
170138 /*
170139 ** If required, grow the hash table used to store changes on table pTab
170140 ** (part of the session pSession). If a fatal OOM error occurs, set the
170141 ** session object to failed and return SQLITE_ERROR. Otherwise, return
170142 ** SQLITE_OK.
170143 **
170144 ** It is possible that a non-fatal OOM error occurs in this function. In
170145 ** that case the hash-table does not grow, but SQLITE_OK is returned anyway.
170146 ** Growing the hash table in this case is a performance optimization only,
170147 ** it is not required for correct operation.
170148 */
170149 static int sessionGrowHash(int bPatchset, SessionTable *pTab){
170150  if( pTab->nChange==0 || pTab->nEntry>=(pTab->nChange/2) ){
170151  int i;
170152  SessionChange **apNew;
170153  int nNew = (pTab->nChange ? pTab->nChange : 128) * 2;
170154 
170155  apNew = (SessionChange **)sqlite3_malloc(sizeof(SessionChange *) * nNew);
170156  if( apNew==0 ){
170157  if( pTab->nChange==0 ){
170158  return SQLITE_ERROR;
170159  }
170160  return SQLITE_OK;
170161  }
170162  memset(apNew, 0, sizeof(SessionChange *) * nNew);
170163 
170164  for(i=0; i<pTab->nChange; i++){
170165  SessionChange *p;
170166  SessionChange *pNext;
170167  for(p=pTab->apChange[i]; p; p=pNext){
170168  int bPkOnly = (p->op==SQLITE_DELETE && bPatchset);
170169  int iHash = sessionChangeHash(pTab, bPkOnly, p->aRecord, nNew);
170170  pNext = p->pNext;
170171  p->pNext = apNew[iHash];
170172  apNew[iHash] = p;
170173  }
170174  }
170175 
170176  sqlite3_free(pTab->apChange);
170177  pTab->nChange = nNew;
170178  pTab->apChange = apNew;
170179  }
170180 
170181  return SQLITE_OK;
170182 }
170183 
170184 /*
170185 ** This function queries the database for the names of the columns of table
170186 ** zThis, in schema zDb. It is expected that the table has nCol columns. If
170187 ** not, SQLITE_SCHEMA is returned and none of the output variables are
170188 ** populated.
170189 **
170190 ** Otherwise, if they are not NULL, variable *pnCol is set to the number
170191 ** of columns in the database table and variable *pzTab is set to point to a
170192 ** nul-terminated copy of the table name. *pazCol (if not NULL) is set to
170193 ** point to an array of pointers to column names. And *pabPK (again, if not
170194 ** NULL) is set to point to an array of booleans - true if the corresponding
170195 ** column is part of the primary key.
170196 **
170197 ** For example, if the table is declared as:
170198 **
170199 ** CREATE TABLE tbl1(w, x, y, z, PRIMARY KEY(w, z));
170200 **
170201 ** Then the four output variables are populated as follows:
170202 **
170203 ** *pnCol = 4
170204 ** *pzTab = "tbl1"
170205 ** *pazCol = {"w", "x", "y", "z"}
170206 ** *pabPK = {1, 0, 0, 1}
170207 **
170208 ** All returned buffers are part of the same single allocation, which must
170209 ** be freed using sqlite3_free() by the caller. If pazCol was not NULL, then
170210 ** pointer *pazCol should be freed to release all memory. Otherwise, pointer
170211 ** *pabPK. It is illegal for both pazCol and pabPK to be NULL.
170212 */
170213 static int sessionTableInfo(
170214  sqlite3 *db, /* Database connection */
170215  const char *zDb, /* Name of attached database (e.g. "main") */
170216  const char *zThis, /* Table name */
170217  int *pnCol, /* OUT: number of columns */
170218  const char **pzTab, /* OUT: Copy of zThis */
170219  const char ***pazCol, /* OUT: Array of column names for table */
170220  u8 **pabPK /* OUT: Array of booleans - true for PK col */
170221 ){
170222  char *zPragma;
170223  sqlite3_stmt *pStmt;
170224  int rc;
170225  int nByte;
170226  int nDbCol = 0;
170227  int nThis;
170228  int i;
170229  u8 *pAlloc = 0;
170230  char **azCol = 0;
170231  u8 *abPK = 0;
170232 
170233  assert( pazCol && pabPK );
170234 
170235  nThis = sqlite3Strlen30(zThis);
170236  zPragma = sqlite3_mprintf("PRAGMA '%q'.table_info('%q')", zDb, zThis);
170237  if( !zPragma ) return SQLITE_NOMEM;
170238 
170239  rc = sqlite3_prepare_v2(db, zPragma, -1, &pStmt, 0);
170240  sqlite3_free(zPragma);
170241  if( rc!=SQLITE_OK ) return rc;
170242 
170243  nByte = nThis + 1;
170244  while( SQLITE_ROW==sqlite3_step(pStmt) ){
170245  nByte += sqlite3_column_bytes(pStmt, 1);
170246  nDbCol++;
170247  }
170248  rc = sqlite3_reset(pStmt);
170249 
170250  if( rc==SQLITE_OK ){
170251  nByte += nDbCol * (sizeof(const char *) + sizeof(u8) + 1);
170252  pAlloc = sqlite3_malloc(nByte);
170253  if( pAlloc==0 ){
170254  rc = SQLITE_NOMEM;
170255  }
170256  }
170257  if( rc==SQLITE_OK ){
170258  azCol = (char **)pAlloc;
170259  pAlloc = (u8 *)&azCol[nDbCol];
170260  abPK = (u8 *)pAlloc;
170261  pAlloc = &abPK[nDbCol];
170262  if( pzTab ){
170263  memcpy(pAlloc, zThis, nThis+1);
170264  *pzTab = (char *)pAlloc;
170265  pAlloc += nThis+1;
170266  }
170267 
170268  i = 0;
170269  while( SQLITE_ROW==sqlite3_step(pStmt) ){
170270  int nName = sqlite3_column_bytes(pStmt, 1);
170271  const unsigned char *zName = sqlite3_column_text(pStmt, 1);
170272  if( zName==0 ) break;
170273  memcpy(pAlloc, zName, nName+1);
170274  azCol[i] = (char *)pAlloc;
170275  pAlloc += nName+1;
170276  abPK[i] = sqlite3_column_int(pStmt, 5);
170277  i++;
170278  }
170279  rc = sqlite3_reset(pStmt);
170280 
170281  }
170282 
170283  /* If successful, populate the output variables. Otherwise, zero them and
170284  ** free any allocation made. An error code will be returned in this case.
170285  */
170286  if( rc==SQLITE_OK ){
170287  *pazCol = (const char **)azCol;
170288  *pabPK = abPK;
170289  *pnCol = nDbCol;
170290  }else{
170291  *pazCol = 0;
170292  *pabPK = 0;
170293  *pnCol = 0;
170294  if( pzTab ) *pzTab = 0;
170295  sqlite3_free(azCol);
170296  }
170297  sqlite3_finalize(pStmt);
170298  return rc;
170299 }
170300 
170301 /*
170302 ** This function is only called from within a pre-update handler for a
170303 ** write to table pTab, part of session pSession. If this is the first
170304 ** write to this table, initalize the SessionTable.nCol, azCol[] and
170305 ** abPK[] arrays accordingly.
170306 **
170307 ** If an error occurs, an error code is stored in sqlite3_session.rc and
170308 ** non-zero returned. Or, if no error occurs but the table has no primary
170309 ** key, sqlite3_session.rc is left set to SQLITE_OK and non-zero returned to
170310 ** indicate that updates on this table should be ignored. SessionTable.abPK
170311 ** is set to NULL in this case.
170312 */
170313 static int sessionInitTable(sqlite3_session *pSession, SessionTable *pTab){
170314  if( pTab->nCol==0 ){
170315  u8 *abPK;
170316  assert( pTab->azCol==0 || pTab->abPK==0 );
170317  pSession->rc = sessionTableInfo(pSession->db, pSession->zDb,
170318  pTab->zName, &pTab->nCol, 0, &pTab->azCol, &abPK
170319  );
170320  if( pSession->rc==SQLITE_OK ){
170321  int i;
170322  for(i=0; i<pTab->nCol; i++){
170323  if( abPK[i] ){
170324  pTab->abPK = abPK;
170325  break;
170326  }
170327  }
170328  }
170329  }
170330  return (pSession->rc || pTab->abPK==0);
170331 }
170332 
170333 /*
170334 ** This function is only called from with a pre-update-hook reporting a
170335 ** change on table pTab (attached to session pSession). The type of change
170336 ** (UPDATE, INSERT, DELETE) is specified by the first argument.
170337 **
170338 ** Unless one is already present or an error occurs, an entry is added
170339 ** to the changed-rows hash table associated with table pTab.
170340 */
170341 static void sessionPreupdateOneChange(
170342  int op, /* One of SQLITE_UPDATE, INSERT, DELETE */
170343  sqlite3_session *pSession, /* Session object pTab is attached to */
170344  SessionTable *pTab /* Table that change applies to */
170345 ){
170346  int iHash;
170347  int bNull = 0;
170348  int rc = SQLITE_OK;
170349 
170350  if( pSession->rc ) return;
170351 
170352  /* Load table details if required */
170353  if( sessionInitTable(pSession, pTab) ) return;
170354 
170355  /* Check the number of columns in this xPreUpdate call matches the
170356  ** number of columns in the table. */
170357  if( pTab->nCol!=pSession->hook.xCount(pSession->hook.pCtx) ){
170358  pSession->rc = SQLITE_SCHEMA;
170359  return;
170360  }
170361 
170362  /* Grow the hash table if required */
170363  if( sessionGrowHash(0, pTab) ){
170364  pSession->rc = SQLITE_NOMEM;
170365  return;
170366  }
170367 
170368  /* Calculate the hash-key for this change. If the primary key of the row
170369  ** includes a NULL value, exit early. Such changes are ignored by the
170370  ** session module. */
170371  rc = sessionPreupdateHash(pSession, pTab, op==SQLITE_INSERT, &iHash, &bNull);
170372  if( rc!=SQLITE_OK ) goto error_out;
170373 
170374  if( bNull==0 ){
170375  /* Search the hash table for an existing record for this row. */
170376  SessionChange *pC;
170377  for(pC=pTab->apChange[iHash]; pC; pC=pC->pNext){
170378  if( sessionPreupdateEqual(pSession, pTab, pC, op) ) break;
170379  }
170380 
170381  if( pC==0 ){
170382  /* Create a new change object containing all the old values (if
170383  ** this is an SQLITE_UPDATE or SQLITE_DELETE), or just the PK
170384  ** values (if this is an INSERT). */
170385  SessionChange *pChange; /* New change object */
170386  int nByte; /* Number of bytes to allocate */
170387  int i; /* Used to iterate through columns */
170388 
170389  assert( rc==SQLITE_OK );
170390  pTab->nEntry++;
170391 
170392  /* Figure out how large an allocation is required */
170393  nByte = sizeof(SessionChange);
170394  for(i=0; i<pTab->nCol; i++){
170395  sqlite3_value *p = 0;
170396  if( op!=SQLITE_INSERT ){
170397  TESTONLY(int trc = ) pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170398  assert( trc==SQLITE_OK );
170399  }else if( pTab->abPK[i] ){
170400  TESTONLY(int trc = ) pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170401  assert( trc==SQLITE_OK );
170402  }
170403 
170404  /* This may fail if SQLite value p contains a utf-16 string that must
170405  ** be converted to utf-8 and an OOM error occurs while doing so. */
170406  rc = sessionSerializeValue(0, p, &nByte);
170407  if( rc!=SQLITE_OK ) goto error_out;
170408  }
170409 
170410  /* Allocate the change object */
170411  pChange = (SessionChange *)sqlite3_malloc(nByte);
170412  if( !pChange ){
170413  rc = SQLITE_NOMEM;
170414  goto error_out;
170415  }else{
170416  memset(pChange, 0, sizeof(SessionChange));
170417  pChange->aRecord = (u8 *)&pChange[1];
170418  }
170419 
170420  /* Populate the change object. None of the preupdate_old(),
170421  ** preupdate_new() or SerializeValue() calls below may fail as all
170422  ** required values and encodings have already been cached in memory.
170423  ** It is not possible for an OOM to occur in this block. */
170424  nByte = 0;
170425  for(i=0; i<pTab->nCol; i++){
170426  sqlite3_value *p = 0;
170427  if( op!=SQLITE_INSERT ){
170428  pSession->hook.xOld(pSession->hook.pCtx, i, &p);
170429  }else if( pTab->abPK[i] ){
170430  pSession->hook.xNew(pSession->hook.pCtx, i, &p);
170431  }
170432  sessionSerializeValue(&pChange->aRecord[nByte], p, &nByte);
170433  }
170434 
170435  /* Add the change to the hash-table */
170436  if( pSession->bIndirect || pSession->hook.xDepth(pSession->hook.pCtx) ){
170437  pChange->bIndirect = 1;
170438  }
170439  pChange->nRecord = nByte;
170440  pChange->op = op;
170441  pChange->pNext = pTab->apChange[iHash];
170442  pTab->apChange[iHash] = pChange;
170443 
170444  }else if( pC->bIndirect ){
170445  /* If the existing change is considered "indirect", but this current
170446  ** change is "direct", mark the change object as direct. */
170447  if( pSession->hook.xDepth(pSession->hook.pCtx)==0
170448  && pSession->bIndirect==0
170449  ){
170450  pC->bIndirect = 0;
170451  }
170452  }
170453  }
170454 
170455  /* If an error has occurred, mark the session object as failed. */
170456  error_out:
170457  if( rc!=SQLITE_OK ){
170458  pSession->rc = rc;
170459  }
170460 }
170461 
170462 static int sessionFindTable(
170463  sqlite3_session *pSession,
170464  const char *zName,
170465  SessionTable **ppTab
170466 ){
170467  int rc = SQLITE_OK;
170468  int nName = sqlite3Strlen30(zName);
170469  SessionTable *pRet;
170470 
170471  /* Search for an existing table */
170472  for(pRet=pSession->pTable; pRet; pRet=pRet->pNext){
170473  if( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) ) break;
170474  }
170475 
170476  if( pRet==0 && pSession->bAutoAttach ){
170477  /* If there is a table-filter configured, invoke it. If it returns 0,
170478  ** do not automatically add the new table. */
170479  if( pSession->xTableFilter==0
170480  || pSession->xTableFilter(pSession->pFilterCtx, zName)
170481  ){
170482  rc = sqlite3session_attach(pSession, zName);
170483  if( rc==SQLITE_OK ){
170484  for(pRet=pSession->pTable; pRet->pNext; pRet=pRet->pNext);
170485  assert( 0==sqlite3_strnicmp(pRet->zName, zName, nName+1) );
170486  }
170487  }
170488  }
170489 
170490  assert( rc==SQLITE_OK || pRet==0 );
170491  *ppTab = pRet;
170492  return rc;
170493 }
170494 
170495 /*
170496 ** The 'pre-update' hook registered by this module with SQLite databases.
170497 */
170498 static void xPreUpdate(
170499  void *pCtx, /* Copy of third arg to preupdate_hook() */
170500  sqlite3 *db, /* Database handle */
170501  int op, /* SQLITE_UPDATE, DELETE or INSERT */
170502  char const *zDb, /* Database name */
170503  char const *zName, /* Table name */
170504  sqlite3_int64 iKey1, /* Rowid of row about to be deleted/updated */
170505  sqlite3_int64 iKey2 /* New rowid value (for a rowid UPDATE) */
170506 ){
170507  sqlite3_session *pSession;
170508  int nDb = sqlite3Strlen30(zDb);
170509 
170510  assert( sqlite3_mutex_held(db->mutex) );
170511 
170512  for(pSession=(sqlite3_session *)pCtx; pSession; pSession=pSession->pNext){
170513  SessionTable *pTab;
170514 
170515  /* If this session is attached to a different database ("main", "temp"
170516  ** etc.), or if it is not currently enabled, there is nothing to do. Skip
170517  ** to the next session object attached to this database. */
170518  if( pSession->bEnable==0 ) continue;
170519  if( pSession->rc ) continue;
170520  if( sqlite3_strnicmp(zDb, pSession->zDb, nDb+1) ) continue;
170521 
170522  pSession->rc = sessionFindTable(pSession, zName, &pTab);
170523  if( pTab ){
170524  assert( pSession->rc==SQLITE_OK );
170525  sessionPreupdateOneChange(op, pSession, pTab);
170526  if( op==SQLITE_UPDATE ){
170527  sessionPreupdateOneChange(SQLITE_INSERT, pSession, pTab);
170528  }
170529  }
170530  }
170531 }
170532 
170533 /*
170534 ** The pre-update hook implementations.
170535 */
170536 static int sessionPreupdateOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170537  return sqlite3_preupdate_old((sqlite3*)pCtx, iVal, ppVal);
170538 }
170539 static int sessionPreupdateNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170540  return sqlite3_preupdate_new((sqlite3*)pCtx, iVal, ppVal);
170541 }
170542 static int sessionPreupdateCount(void *pCtx){
170543  return sqlite3_preupdate_count((sqlite3*)pCtx);
170544 }
170545 static int sessionPreupdateDepth(void *pCtx){
170546  return sqlite3_preupdate_depth((sqlite3*)pCtx);
170547 }
170548 
170549 /*
170550 ** Install the pre-update hooks on the session object passed as the only
170551 ** argument.
170552 */
170553 static void sessionPreupdateHooks(
170554  sqlite3_session *pSession
170555 ){
170556  pSession->hook.pCtx = (void*)pSession->db;
170557  pSession->hook.xOld = sessionPreupdateOld;
170558  pSession->hook.xNew = sessionPreupdateNew;
170559  pSession->hook.xCount = sessionPreupdateCount;
170560  pSession->hook.xDepth = sessionPreupdateDepth;
170561 }
170562 
170563 typedef struct SessionDiffCtx SessionDiffCtx;
170564 struct SessionDiffCtx {
170565  sqlite3_stmt *pStmt;
170566  int nOldOff;
170567 };
170568 
170569 /*
170570 ** The diff hook implementations.
170571 */
170572 static int sessionDiffOld(void *pCtx, int iVal, sqlite3_value **ppVal){
170573  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170574  *ppVal = sqlite3_column_value(p->pStmt, iVal+p->nOldOff);
170575  return SQLITE_OK;
170576 }
170577 static int sessionDiffNew(void *pCtx, int iVal, sqlite3_value **ppVal){
170578  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170579  *ppVal = sqlite3_column_value(p->pStmt, iVal);
170580  return SQLITE_OK;
170581 }
170582 static int sessionDiffCount(void *pCtx){
170583  SessionDiffCtx *p = (SessionDiffCtx*)pCtx;
170584  return p->nOldOff ? p->nOldOff : sqlite3_column_count(p->pStmt);
170585 }
170586 static int sessionDiffDepth(void *pCtx){
170587  return 0;
170588 }
170589 
170590 /*
170591 ** Install the diff hooks on the session object passed as the only
170592 ** argument.
170593 */
170594 static void sessionDiffHooks(
170595  sqlite3_session *pSession,
170596  SessionDiffCtx *pDiffCtx
170597 ){
170598  pSession->hook.pCtx = (void*)pDiffCtx;
170599  pSession->hook.xOld = sessionDiffOld;
170600  pSession->hook.xNew = sessionDiffNew;
170601  pSession->hook.xCount = sessionDiffCount;
170602  pSession->hook.xDepth = sessionDiffDepth;
170603 }
170604 
170605 static char *sessionExprComparePK(
170606  int nCol,
170607  const char *zDb1, const char *zDb2,
170608  const char *zTab,
170609  const char **azCol, u8 *abPK
170610 ){
170611  int i;
170612  const char *zSep = "";
170613  char *zRet = 0;
170614 
170615  for(i=0; i<nCol; i++){
170616  if( abPK[i] ){
170617  zRet = sqlite3_mprintf("%z%s\"%w\".\"%w\".\"%w\"=\"%w\".\"%w\".\"%w\"",
170618  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170619  );
170620  zSep = " AND ";
170621  if( zRet==0 ) break;
170622  }
170623  }
170624 
170625  return zRet;
170626 }
170627 
170628 static char *sessionExprCompareOther(
170629  int nCol,
170630  const char *zDb1, const char *zDb2,
170631  const char *zTab,
170632  const char **azCol, u8 *abPK
170633 ){
170634  int i;
170635  const char *zSep = "";
170636  char *zRet = 0;
170637  int bHave = 0;
170638 
170639  for(i=0; i<nCol; i++){
170640  if( abPK[i]==0 ){
170641  bHave = 1;
170642  zRet = sqlite3_mprintf(
170643  "%z%s\"%w\".\"%w\".\"%w\" IS NOT \"%w\".\"%w\".\"%w\"",
170644  zRet, zSep, zDb1, zTab, azCol[i], zDb2, zTab, azCol[i]
170645  );
170646  zSep = " OR ";
170647  if( zRet==0 ) break;
170648  }
170649  }
170650 
170651  if( bHave==0 ){
170652  assert( zRet==0 );
170653  zRet = sqlite3_mprintf("0");
170654  }
170655 
170656  return zRet;
170657 }
170658 
170659 static char *sessionSelectFindNew(
170660  int nCol,
170661  const char *zDb1, /* Pick rows in this db only */
170662  const char *zDb2, /* But not in this one */
170663  const char *zTbl, /* Table name */
170664  const char *zExpr
170665 ){
170666  char *zRet = sqlite3_mprintf(
170667  "SELECT * FROM \"%w\".\"%w\" WHERE NOT EXISTS ("
170668  " SELECT 1 FROM \"%w\".\"%w\" WHERE %s"
170669  ")",
170670  zDb1, zTbl, zDb2, zTbl, zExpr
170671  );
170672  return zRet;
170673 }
170674 
170675 static int sessionDiffFindNew(
170676  int op,
170677  sqlite3_session *pSession,
170678  SessionTable *pTab,
170679  const char *zDb1,
170680  const char *zDb2,
170681  char *zExpr
170682 ){
170683  int rc = SQLITE_OK;
170684  char *zStmt = sessionSelectFindNew(pTab->nCol, zDb1, zDb2, pTab->zName,zExpr);
170685 
170686  if( zStmt==0 ){
170687  rc = SQLITE_NOMEM;
170688  }else{
170689  sqlite3_stmt *pStmt;
170690  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170691  if( rc==SQLITE_OK ){
170692  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170693  pDiffCtx->pStmt = pStmt;
170694  pDiffCtx->nOldOff = 0;
170695  while( SQLITE_ROW==sqlite3_step(pStmt) ){
170696  sessionPreupdateOneChange(op, pSession, pTab);
170697  }
170698  rc = sqlite3_finalize(pStmt);
170699  }
170700  sqlite3_free(zStmt);
170701  }
170702 
170703  return rc;
170704 }
170705 
170706 static int sessionDiffFindModified(
170707  sqlite3_session *pSession,
170708  SessionTable *pTab,
170709  const char *zFrom,
170710  const char *zExpr
170711 ){
170712  int rc = SQLITE_OK;
170713 
170714  char *zExpr2 = sessionExprCompareOther(pTab->nCol,
170715  pSession->zDb, zFrom, pTab->zName, pTab->azCol, pTab->abPK
170716  );
170717  if( zExpr2==0 ){
170718  rc = SQLITE_NOMEM;
170719  }else{
170720  char *zStmt = sqlite3_mprintf(
170721  "SELECT * FROM \"%w\".\"%w\", \"%w\".\"%w\" WHERE %s AND (%z)",
170722  pSession->zDb, pTab->zName, zFrom, pTab->zName, zExpr, zExpr2
170723  );
170724  if( zStmt==0 ){
170725  rc = SQLITE_NOMEM;
170726  }else{
170727  sqlite3_stmt *pStmt;
170728  rc = sqlite3_prepare(pSession->db, zStmt, -1, &pStmt, 0);
170729 
170730  if( rc==SQLITE_OK ){
170731  SessionDiffCtx *pDiffCtx = (SessionDiffCtx*)pSession->hook.pCtx;
170732  pDiffCtx->pStmt = pStmt;
170733  pDiffCtx->nOldOff = pTab->nCol;
170734  while( SQLITE_ROW==sqlite3_step(pStmt) ){
170735  sessionPreupdateOneChange(SQLITE_UPDATE, pSession, pTab);
170736  }
170737  rc = sqlite3_finalize(pStmt);
170738  }
170739  sqlite3_free(zStmt);
170740  }
170741  }
170742 
170743  return rc;
170744 }
170745 
170746 SQLITE_API int SQLITE_STDCALL sqlite3session_diff(
170747  sqlite3_session *pSession,
170748  const char *zFrom,
170749  const char *zTbl,
170750  char **pzErrMsg
170751 ){
170752  const char *zDb = pSession->zDb;
170753  int rc = pSession->rc;
170754  SessionDiffCtx d;
170755 
170756  memset(&d, 0, sizeof(d));
170757  sessionDiffHooks(pSession, &d);
170758 
170759  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
170760  if( pzErrMsg ) *pzErrMsg = 0;
170761  if( rc==SQLITE_OK ){
170762  char *zExpr = 0;
170763  sqlite3 *db = pSession->db;
170764  SessionTable *pTo; /* Table zTbl */
170765 
170766  /* Locate and if necessary initialize the target table object */
170767  rc = sessionFindTable(pSession, zTbl, &pTo);
170768  if( pTo==0 ) goto diff_out;
170769  if( sessionInitTable(pSession, pTo) ){
170770  rc = pSession->rc;
170771  goto diff_out;
170772  }
170773 
170774  /* Check the table schemas match */
170775  if( rc==SQLITE_OK ){
170776  int bHasPk = 0;
170777  int bMismatch = 0;
170778  int nCol; /* Columns in zFrom.zTbl */
170779  u8 *abPK;
170780  const char **azCol = 0;
170781  rc = sessionTableInfo(db, zFrom, zTbl, &nCol, 0, &azCol, &abPK);
170782  if( rc==SQLITE_OK ){
170783  if( pTo->nCol!=nCol ){
170784  bMismatch = 1;
170785  }else{
170786  int i;
170787  for(i=0; i<nCol; i++){
170788  if( pTo->abPK[i]!=abPK[i] ) bMismatch = 1;
170789  if( sqlite3_stricmp(azCol[i], pTo->azCol[i]) ) bMismatch = 1;
170790  if( abPK[i] ) bHasPk = 1;
170791  }
170792  }
170793 
170794  }
170795  sqlite3_free((char*)azCol);
170796  if( bMismatch ){
170797  *pzErrMsg = sqlite3_mprintf("table schemas do not match");
170798  rc = SQLITE_SCHEMA;
170799  }
170800  if( bHasPk==0 ){
170801  /* Ignore tables with no primary keys */
170802  goto diff_out;
170803  }
170804  }
170805 
170806  if( rc==SQLITE_OK ){
170807  zExpr = sessionExprComparePK(pTo->nCol,
170808  zDb, zFrom, pTo->zName, pTo->azCol, pTo->abPK
170809  );
170810  }
170811 
170812  /* Find new rows */
170813  if( rc==SQLITE_OK ){
170814  rc = sessionDiffFindNew(SQLITE_INSERT, pSession, pTo, zDb, zFrom, zExpr);
170815  }
170816 
170817  /* Find old rows */
170818  if( rc==SQLITE_OK ){
170819  rc = sessionDiffFindNew(SQLITE_DELETE, pSession, pTo, zFrom, zDb, zExpr);
170820  }
170821 
170822  /* Find modified rows */
170823  if( rc==SQLITE_OK ){
170824  rc = sessionDiffFindModified(pSession, pTo, zFrom, zExpr);
170825  }
170826 
170827  sqlite3_free(zExpr);
170828  }
170829 
170830  diff_out:
170831  sessionPreupdateHooks(pSession);
170832  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
170833  return rc;
170834 }
170835 
170836 /*
170837 ** Create a session object. This session object will record changes to
170838 ** database zDb attached to connection db.
170839 */
170840 SQLITE_API int SQLITE_STDCALL sqlite3session_create(
170841  sqlite3 *db, /* Database handle */
170842  const char *zDb, /* Name of db (e.g. "main") */
170843  sqlite3_session **ppSession /* OUT: New session object */
170844 ){
170845  sqlite3_session *pNew; /* Newly allocated session object */
170846  sqlite3_session *pOld; /* Session object already attached to db */
170847  int nDb = sqlite3Strlen30(zDb); /* Length of zDb in bytes */
170848 
170849  /* Zero the output value in case an error occurs. */
170850  *ppSession = 0;
170851 
170852  /* Allocate and populate the new session object. */
170853  pNew = (sqlite3_session *)sqlite3_malloc(sizeof(sqlite3_session) + nDb + 1);
170854  if( !pNew ) return SQLITE_NOMEM;
170855  memset(pNew, 0, sizeof(sqlite3_session));
170856  pNew->db = db;
170857  pNew->zDb = (char *)&pNew[1];
170858  pNew->bEnable = 1;
170859  memcpy(pNew->zDb, zDb, nDb+1);
170860  sessionPreupdateHooks(pNew);
170861 
170862  /* Add the new session object to the linked list of session objects
170863  ** attached to database handle $db. Do this under the cover of the db
170864  ** handle mutex. */
170866  pOld = (sqlite3_session*)sqlite3_preupdate_hook(db, xPreUpdate, (void*)pNew);
170867  pNew->pNext = pOld;
170869 
170870  *ppSession = pNew;
170871  return SQLITE_OK;
170872 }
170873 
170874 /*
170875 ** Free the list of table objects passed as the first argument. The contents
170876 ** of the changed-rows hash tables are also deleted.
170877 */
170878 static void sessionDeleteTable(SessionTable *pList){
170879  SessionTable *pNext;
170880  SessionTable *pTab;
170881 
170882  for(pTab=pList; pTab; pTab=pNext){
170883  int i;
170884  pNext = pTab->pNext;
170885  for(i=0; i<pTab->nChange; i++){
170886  SessionChange *p;
170887  SessionChange *pNextChange;
170888  for(p=pTab->apChange[i]; p; p=pNextChange){
170889  pNextChange = p->pNext;
170890  sqlite3_free(p);
170891  }
170892  }
170893  sqlite3_free((char*)pTab->azCol); /* cast works around VC++ bug */
170894  sqlite3_free(pTab->apChange);
170895  sqlite3_free(pTab);
170896  }
170897 }
170898 
170899 /*
170900 ** Delete a session object previously allocated using sqlite3session_create().
170901 */
170902 SQLITE_API void SQLITE_STDCALL sqlite3session_delete(sqlite3_session *pSession){
170903  sqlite3 *db = pSession->db;
170904  sqlite3_session *pHead;
170905  sqlite3_session **pp;
170906 
170907  /* Unlink the session from the linked list of sessions attached to the
170908  ** database handle. Hold the db mutex while doing so. */
170910  pHead = (sqlite3_session*)sqlite3_preupdate_hook(db, 0, 0);
170911  for(pp=&pHead; ALWAYS((*pp)!=0); pp=&((*pp)->pNext)){
170912  if( (*pp)==pSession ){
170913  *pp = (*pp)->pNext;
170914  if( pHead ) sqlite3_preupdate_hook(db, xPreUpdate, (void*)pHead);
170915  break;
170916  }
170917  }
170919 
170920  /* Delete all attached table objects. And the contents of their
170921  ** associated hash-tables. */
170922  sessionDeleteTable(pSession->pTable);
170923 
170924  /* Free the session object itself. */
170925  sqlite3_free(pSession);
170926 }
170927 
170928 /*
170929 ** Set a table filter on a Session Object.
170930 */
170931 SQLITE_API void SQLITE_STDCALL sqlite3session_table_filter(
170932  sqlite3_session *pSession,
170933  int(*xFilter)(void*, const char*),
170934  void *pCtx /* First argument passed to xFilter */
170935 ){
170936  pSession->bAutoAttach = 1;
170937  pSession->pFilterCtx = pCtx;
170938  pSession->xTableFilter = xFilter;
170939 }
170940 
170941 /*
170942 ** Attach a table to a session. All subsequent changes made to the table
170943 ** while the session object is enabled will be recorded.
170944 **
170945 ** Only tables that have a PRIMARY KEY defined may be attached. It does
170946 ** not matter if the PRIMARY KEY is an "INTEGER PRIMARY KEY" (rowid alias)
170947 ** or not.
170948 */
170949 SQLITE_API int SQLITE_STDCALL sqlite3session_attach(
170950  sqlite3_session *pSession, /* Session object */
170951  const char *zName /* Table name */
170952 ){
170953  int rc = SQLITE_OK;
170954  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
170955 
170956  if( !zName ){
170957  pSession->bAutoAttach = 1;
170958  }else{
170959  SessionTable *pTab; /* New table object (if required) */
170960  int nName; /* Number of bytes in string zName */
170961 
170962  /* First search for an existing entry. If one is found, this call is
170963  ** a no-op. Return early. */
170964  nName = sqlite3Strlen30(zName);
170965  for(pTab=pSession->pTable; pTab; pTab=pTab->pNext){
170966  if( 0==sqlite3_strnicmp(pTab->zName, zName, nName+1) ) break;
170967  }
170968 
170969  if( !pTab ){
170970  /* Allocate new SessionTable object. */
170971  pTab = (SessionTable *)sqlite3_malloc(sizeof(SessionTable) + nName + 1);
170972  if( !pTab ){
170973  rc = SQLITE_NOMEM;
170974  }else{
170975  /* Populate the new SessionTable object and link it into the list.
170976  ** The new object must be linked onto the end of the list, not
170977  ** simply added to the start of it in order to ensure that tables
170978  ** appear in the correct order when a changeset or patchset is
170979  ** eventually generated. */
170980  SessionTable **ppTab;
170981  memset(pTab, 0, sizeof(SessionTable));
170982  pTab->zName = (char *)&pTab[1];
170983  memcpy(pTab->zName, zName, nName+1);
170984  for(ppTab=&pSession->pTable; *ppTab; ppTab=&(*ppTab)->pNext);
170985  *ppTab = pTab;
170986  }
170987  }
170988  }
170989 
170990  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
170991  return rc;
170992 }
170993 
170994 /*
170995 ** Ensure that there is room in the buffer to append nByte bytes of data.
170996 ** If not, use sqlite3_realloc() to grow the buffer so that there is.
170997 **
170998 ** If successful, return zero. Otherwise, if an OOM condition is encountered,
170999 ** set *pRc to SQLITE_NOMEM and return non-zero.
171000 */
171001 static int sessionBufferGrow(SessionBuffer *p, int nByte, int *pRc){
171002  if( *pRc==SQLITE_OK && p->nAlloc-p->nBuf<nByte ){
171003  u8 *aNew;
171004  int nNew = p->nAlloc ? p->nAlloc : 128;
171005  do {
171006  nNew = nNew*2;
171007  }while( nNew<(p->nBuf+nByte) );
171008 
171009  aNew = (u8 *)sqlite3_realloc(p->aBuf, nNew);
171010  if( 0==aNew ){
171011  *pRc = SQLITE_NOMEM;
171012  }else{
171013  p->aBuf = aNew;
171014  p->nAlloc = nNew;
171015  }
171016  }
171017  return (*pRc!=SQLITE_OK);
171018 }
171019 
171020 /*
171021 ** Append the value passed as the second argument to the buffer passed
171022 ** as the first.
171023 **
171024 ** This function is a no-op if *pRc is non-zero when it is called.
171025 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code
171026 ** before returning.
171027 */
171028 static void sessionAppendValue(SessionBuffer *p, sqlite3_value *pVal, int *pRc){
171029  int rc = *pRc;
171030  if( rc==SQLITE_OK ){
171031  int nByte = 0;
171032  rc = sessionSerializeValue(0, pVal, &nByte);
171033  sessionBufferGrow(p, nByte, &rc);
171034  if( rc==SQLITE_OK ){
171035  rc = sessionSerializeValue(&p->aBuf[p->nBuf], pVal, 0);
171036  p->nBuf += nByte;
171037  }else{
171038  *pRc = rc;
171039  }
171040  }
171041 }
171042 
171043 /*
171044 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171045 ** called. Otherwise, append a single byte to the buffer.
171046 **
171047 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171048 ** returning.
171049 */
171050 static void sessionAppendByte(SessionBuffer *p, u8 v, int *pRc){
171051  if( 0==sessionBufferGrow(p, 1, pRc) ){
171052  p->aBuf[p->nBuf++] = v;
171053  }
171054 }
171055 
171056 /*
171057 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171058 ** called. Otherwise, append a single varint to the buffer.
171059 **
171060 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171061 ** returning.
171062 */
171063 static void sessionAppendVarint(SessionBuffer *p, int v, int *pRc){
171064  if( 0==sessionBufferGrow(p, 9, pRc) ){
171065  p->nBuf += sessionVarintPut(&p->aBuf[p->nBuf], v);
171066  }
171067 }
171068 
171069 /*
171070 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171071 ** called. Otherwise, append a blob of data to the buffer.
171072 **
171073 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171074 ** returning.
171075 */
171076 static void sessionAppendBlob(
171077  SessionBuffer *p,
171078  const u8 *aBlob,
171079  int nBlob,
171080  int *pRc
171081 ){
171082  if( 0==sessionBufferGrow(p, nBlob, pRc) ){
171083  memcpy(&p->aBuf[p->nBuf], aBlob, nBlob);
171084  p->nBuf += nBlob;
171085  }
171086 }
171087 
171088 /*
171089 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171090 ** called. Otherwise, append a string to the buffer. All bytes in the string
171091 ** up to (but not including) the nul-terminator are written to the buffer.
171092 **
171093 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171094 ** returning.
171095 */
171096 static void sessionAppendStr(
171097  SessionBuffer *p,
171098  const char *zStr,
171099  int *pRc
171100 ){
171101  int nStr = sqlite3Strlen30(zStr);
171102  if( 0==sessionBufferGrow(p, nStr, pRc) ){
171103  memcpy(&p->aBuf[p->nBuf], zStr, nStr);
171104  p->nBuf += nStr;
171105  }
171106 }
171107 
171108 /*
171109 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171110 ** called. Otherwise, append the string representation of integer iVal
171111 ** to the buffer. No nul-terminator is written.
171112 **
171113 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171114 ** returning.
171115 */
171116 static void sessionAppendInteger(
171117  SessionBuffer *p, /* Buffer to append to */
171118  int iVal, /* Value to write the string rep. of */
171119  int *pRc /* IN/OUT: Error code */
171120 ){
171121  char aBuf[24];
171122  sqlite3_snprintf(sizeof(aBuf)-1, aBuf, "%d", iVal);
171123  sessionAppendStr(p, aBuf, pRc);
171124 }
171125 
171126 /*
171127 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171128 ** called. Otherwise, append the string zStr enclosed in quotes (") and
171129 ** with any embedded quote characters escaped to the buffer. No
171130 ** nul-terminator byte is written.
171131 **
171132 ** If an OOM condition is encountered, set *pRc to SQLITE_NOMEM before
171133 ** returning.
171134 */
171135 static void sessionAppendIdent(
171136  SessionBuffer *p, /* Buffer to a append to */
171137  const char *zStr, /* String to quote, escape and append */
171138  int *pRc /* IN/OUT: Error code */
171139 ){
171140  int nStr = sqlite3Strlen30(zStr)*2 + 2 + 1;
171141  if( 0==sessionBufferGrow(p, nStr, pRc) ){
171142  char *zOut = (char *)&p->aBuf[p->nBuf];
171143  const char *zIn = zStr;
171144  *zOut++ = '"';
171145  while( *zIn ){
171146  if( *zIn=='"' ) *zOut++ = '"';
171147  *zOut++ = *(zIn++);
171148  }
171149  *zOut++ = '"';
171150  p->nBuf = (int)((u8 *)zOut - p->aBuf);
171151  }
171152 }
171153 
171154 /*
171155 ** This function is a no-op if *pRc is other than SQLITE_OK when it is
171156 ** called. Otherwse, it appends the serialized version of the value stored
171157 ** in column iCol of the row that SQL statement pStmt currently points
171158 ** to to the buffer.
171159 */
171160 static void sessionAppendCol(
171161  SessionBuffer *p, /* Buffer to append to */
171162  sqlite3_stmt *pStmt, /* Handle pointing to row containing value */
171163  int iCol, /* Column to read value from */
171164  int *pRc /* IN/OUT: Error code */
171165 ){
171166  if( *pRc==SQLITE_OK ){
171167  int eType = sqlite3_column_type(pStmt, iCol);
171168  sessionAppendByte(p, (u8)eType, pRc);
171169  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171170  sqlite3_int64 i;
171171  u8 aBuf[8];
171172  if( eType==SQLITE_INTEGER ){
171173  i = sqlite3_column_int64(pStmt, iCol);
171174  }else{
171175  double r = sqlite3_column_double(pStmt, iCol);
171176  memcpy(&i, &r, 8);
171177  }
171178  sessionPutI64(aBuf, i);
171179  sessionAppendBlob(p, aBuf, 8, pRc);
171180  }
171181  if( eType==SQLITE_BLOB || eType==SQLITE_TEXT ){
171182  u8 *z;
171183  int nByte;
171184  if( eType==SQLITE_BLOB ){
171185  z = (u8 *)sqlite3_column_blob(pStmt, iCol);
171186  }else{
171187  z = (u8 *)sqlite3_column_text(pStmt, iCol);
171188  }
171189  nByte = sqlite3_column_bytes(pStmt, iCol);
171190  if( z || (eType==SQLITE_BLOB && nByte==0) ){
171191  sessionAppendVarint(p, nByte, pRc);
171192  sessionAppendBlob(p, z, nByte, pRc);
171193  }else{
171194  *pRc = SQLITE_NOMEM;
171195  }
171196  }
171197  }
171198 }
171199 
171200 /*
171201 **
171202 ** This function appends an update change to the buffer (see the comments
171203 ** under "CHANGESET FORMAT" at the top of the file). An update change
171204 ** consists of:
171205 **
171206 ** 1 byte: SQLITE_UPDATE (0x17)
171207 ** n bytes: old.* record (see RECORD FORMAT)
171208 ** m bytes: new.* record (see RECORD FORMAT)
171209 **
171210 ** The SessionChange object passed as the third argument contains the
171211 ** values that were stored in the row when the session began (the old.*
171212 ** values). The statement handle passed as the second argument points
171213 ** at the current version of the row (the new.* values).
171214 **
171215 ** If all of the old.* values are equal to their corresponding new.* value
171216 ** (i.e. nothing has changed), then no data at all is appended to the buffer.
171217 **
171218 ** Otherwise, the old.* record contains all primary key values and the
171219 ** original values of any fields that have been modified. The new.* record
171220 ** contains the new values of only those fields that have been modified.
171221 */
171222 static int sessionAppendUpdate(
171223  SessionBuffer *pBuf, /* Buffer to append to */
171224  int bPatchset, /* True for "patchset", 0 for "changeset" */
171225  sqlite3_stmt *pStmt, /* Statement handle pointing at new row */
171226  SessionChange *p, /* Object containing old values */
171227  u8 *abPK /* Boolean array - true for PK columns */
171228 ){
171229  int rc = SQLITE_OK;
171230  SessionBuffer buf2 = {0,0,0}; /* Buffer to accumulate new.* record in */
171231  int bNoop = 1; /* Set to zero if any values are modified */
171232  int nRewind = pBuf->nBuf; /* Set to zero if any values are modified */
171233  int i; /* Used to iterate through columns */
171234  u8 *pCsr = p->aRecord; /* Used to iterate through old.* values */
171235 
171236  sessionAppendByte(pBuf, SQLITE_UPDATE, &rc);
171237  sessionAppendByte(pBuf, p->bIndirect, &rc);
171238  for(i=0; i<sqlite3_column_count(pStmt); i++){
171239  int bChanged = 0;
171240  int nAdvance;
171241  int eType = *pCsr;
171242  switch( eType ){
171243  case SQLITE_NULL:
171244  nAdvance = 1;
171245  if( sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
171246  bChanged = 1;
171247  }
171248  break;
171249 
171250  case SQLITE_FLOAT:
171251  case SQLITE_INTEGER: {
171252  nAdvance = 9;
171253  if( eType==sqlite3_column_type(pStmt, i) ){
171254  sqlite3_int64 iVal = sessionGetI64(&pCsr[1]);
171255  if( eType==SQLITE_INTEGER ){
171256  if( iVal==sqlite3_column_int64(pStmt, i) ) break;
171257  }else{
171258  double dVal;
171259  memcpy(&dVal, &iVal, 8);
171260  if( dVal==sqlite3_column_double(pStmt, i) ) break;
171261  }
171262  }
171263  bChanged = 1;
171264  break;
171265  }
171266 
171267  default: {
171268  int nByte;
171269  int nHdr = 1 + sessionVarintGet(&pCsr[1], &nByte);
171270  assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
171271  nAdvance = nHdr + nByte;
171272  if( eType==sqlite3_column_type(pStmt, i)
171273  && nByte==sqlite3_column_bytes(pStmt, i)
171274  && 0==memcmp(&pCsr[nHdr], sqlite3_column_blob(pStmt, i), nByte)
171275  ){
171276  break;
171277  }
171278  bChanged = 1;
171279  }
171280  }
171281 
171282  /* If at least one field has been modified, this is not a no-op. */
171283  if( bChanged ) bNoop = 0;
171284 
171285  /* Add a field to the old.* record. This is omitted if this modules is
171286  ** currently generating a patchset. */
171287  if( bPatchset==0 ){
171288  if( bChanged || abPK[i] ){
171289  sessionAppendBlob(pBuf, pCsr, nAdvance, &rc);
171290  }else{
171291  sessionAppendByte(pBuf, 0, &rc);
171292  }
171293  }
171294 
171295  /* Add a field to the new.* record. Or the only record if currently
171296  ** generating a patchset. */
171297  if( bChanged || (bPatchset && abPK[i]) ){
171298  sessionAppendCol(&buf2, pStmt, i, &rc);
171299  }else{
171300  sessionAppendByte(&buf2, 0, &rc);
171301  }
171302 
171303  pCsr += nAdvance;
171304  }
171305 
171306  if( bNoop ){
171307  pBuf->nBuf = nRewind;
171308  }else{
171309  sessionAppendBlob(pBuf, buf2.aBuf, buf2.nBuf, &rc);
171310  }
171311  sqlite3_free(buf2.aBuf);
171312 
171313  return rc;
171314 }
171315 
171316 /*
171317 ** Append a DELETE change to the buffer passed as the first argument. Use
171318 ** the changeset format if argument bPatchset is zero, or the patchset
171319 ** format otherwise.
171320 */
171321 static int sessionAppendDelete(
171322  SessionBuffer *pBuf, /* Buffer to append to */
171323  int bPatchset, /* True for "patchset", 0 for "changeset" */
171324  SessionChange *p, /* Object containing old values */
171325  int nCol, /* Number of columns in table */
171326  u8 *abPK /* Boolean array - true for PK columns */
171327 ){
171328  int rc = SQLITE_OK;
171329 
171330  sessionAppendByte(pBuf, SQLITE_DELETE, &rc);
171331  sessionAppendByte(pBuf, p->bIndirect, &rc);
171332 
171333  if( bPatchset==0 ){
171334  sessionAppendBlob(pBuf, p->aRecord, p->nRecord, &rc);
171335  }else{
171336  int i;
171337  u8 *a = p->aRecord;
171338  for(i=0; i<nCol; i++){
171339  u8 *pStart = a;
171340  int eType = *a++;
171341 
171342  switch( eType ){
171343  case 0:
171344  case SQLITE_NULL:
171345  assert( abPK[i]==0 );
171346  break;
171347 
171348  case SQLITE_FLOAT:
171349  case SQLITE_INTEGER:
171350  a += 8;
171351  break;
171352 
171353  default: {
171354  int n;
171355  a += sessionVarintGet(a, &n);
171356  a += n;
171357  break;
171358  }
171359  }
171360  if( abPK[i] ){
171361  sessionAppendBlob(pBuf, pStart, (int)(a-pStart), &rc);
171362  }
171363  }
171364  assert( (a - p->aRecord)==p->nRecord );
171365  }
171366 
171367  return rc;
171368 }
171369 
171370 /*
171371 ** Formulate and prepare a SELECT statement to retrieve a row from table
171372 ** zTab in database zDb based on its primary key. i.e.
171373 **
171374 ** SELECT * FROM zDb.zTab WHERE pk1 = ? AND pk2 = ? AND ...
171375 */
171376 static int sessionSelectStmt(
171377  sqlite3 *db, /* Database handle */
171378  const char *zDb, /* Database name */
171379  const char *zTab, /* Table name */
171380  int nCol, /* Number of columns in table */
171381  const char **azCol, /* Names of table columns */
171382  u8 *abPK, /* PRIMARY KEY array */
171383  sqlite3_stmt **ppStmt /* OUT: Prepared SELECT statement */
171384 ){
171385  int rc = SQLITE_OK;
171386  int i;
171387  const char *zSep = "";
171388  SessionBuffer buf = {0, 0, 0};
171389 
171390  sessionAppendStr(&buf, "SELECT * FROM ", &rc);
171391  sessionAppendIdent(&buf, zDb, &rc);
171392  sessionAppendStr(&buf, ".", &rc);
171393  sessionAppendIdent(&buf, zTab, &rc);
171394  sessionAppendStr(&buf, " WHERE ", &rc);
171395  for(i=0; i<nCol; i++){
171396  if( abPK[i] ){
171397  sessionAppendStr(&buf, zSep, &rc);
171398  sessionAppendIdent(&buf, azCol[i], &rc);
171399  sessionAppendStr(&buf, " = ?", &rc);
171400  sessionAppendInteger(&buf, i+1, &rc);
171401  zSep = " AND ";
171402  }
171403  }
171404  if( rc==SQLITE_OK ){
171405  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, ppStmt, 0);
171406  }
171407  sqlite3_free(buf.aBuf);
171408  return rc;
171409 }
171410 
171411 /*
171412 ** Bind the PRIMARY KEY values from the change passed in argument pChange
171413 ** to the SELECT statement passed as the first argument. The SELECT statement
171414 ** is as prepared by function sessionSelectStmt().
171415 **
171416 ** Return SQLITE_OK if all PK values are successfully bound, or an SQLite
171417 ** error code (e.g. SQLITE_NOMEM) otherwise.
171418 */
171419 static int sessionSelectBind(
171420  sqlite3_stmt *pSelect, /* SELECT from sessionSelectStmt() */
171421  int nCol, /* Number of columns in table */
171422  u8 *abPK, /* PRIMARY KEY array */
171423  SessionChange *pChange /* Change structure */
171424 ){
171425  int i;
171426  int rc = SQLITE_OK;
171427  u8 *a = pChange->aRecord;
171428 
171429  for(i=0; i<nCol && rc==SQLITE_OK; i++){
171430  int eType = *a++;
171431 
171432  switch( eType ){
171433  case 0:
171434  case SQLITE_NULL:
171435  assert( abPK[i]==0 );
171436  break;
171437 
171438  case SQLITE_INTEGER: {
171439  if( abPK[i] ){
171440  i64 iVal = sessionGetI64(a);
171441  rc = sqlite3_bind_int64(pSelect, i+1, iVal);
171442  }
171443  a += 8;
171444  break;
171445  }
171446 
171447  case SQLITE_FLOAT: {
171448  if( abPK[i] ){
171449  double rVal;
171450  i64 iVal = sessionGetI64(a);
171451  memcpy(&rVal, &iVal, 8);
171452  rc = sqlite3_bind_double(pSelect, i+1, rVal);
171453  }
171454  a += 8;
171455  break;
171456  }
171457 
171458  case SQLITE_TEXT: {
171459  int n;
171460  a += sessionVarintGet(a, &n);
171461  if( abPK[i] ){
171462  rc = sqlite3_bind_text(pSelect, i+1, (char *)a, n, SQLITE_TRANSIENT);
171463  }
171464  a += n;
171465  break;
171466  }
171467 
171468  default: {
171469  int n;
171470  assert( eType==SQLITE_BLOB );
171471  a += sessionVarintGet(a, &n);
171472  if( abPK[i] ){
171473  rc = sqlite3_bind_blob(pSelect, i+1, a, n, SQLITE_TRANSIENT);
171474  }
171475  a += n;
171476  break;
171477  }
171478  }
171479  }
171480 
171481  return rc;
171482 }
171483 
171484 /*
171485 ** This function is a no-op if *pRc is set to other than SQLITE_OK when it
171486 ** is called. Otherwise, append a serialized table header (part of the binary
171487 ** changeset format) to buffer *pBuf. If an error occurs, set *pRc to an
171488 ** SQLite error code before returning.
171489 */
171490 static void sessionAppendTableHdr(
171491  SessionBuffer *pBuf, /* Append header to this buffer */
171492  int bPatchset, /* Use the patchset format if true */
171493  SessionTable *pTab, /* Table object to append header for */
171494  int *pRc /* IN/OUT: Error code */
171495 ){
171496  /* Write a table header */
171497  sessionAppendByte(pBuf, (bPatchset ? 'P' : 'T'), pRc);
171498  sessionAppendVarint(pBuf, pTab->nCol, pRc);
171499  sessionAppendBlob(pBuf, pTab->abPK, pTab->nCol, pRc);
171500  sessionAppendBlob(pBuf, (u8 *)pTab->zName, (int)strlen(pTab->zName)+1, pRc);
171501 }
171502 
171503 /*
171504 ** Generate either a changeset (if argument bPatchset is zero) or a patchset
171505 ** (if it is non-zero) based on the current contents of the session object
171506 ** passed as the first argument.
171507 **
171508 ** If no error occurs, SQLITE_OK is returned and the new changeset/patchset
171509 ** stored in output variables *pnChangeset and *ppChangeset. Or, if an error
171510 ** occurs, an SQLite error code is returned and both output variables set
171511 ** to 0.
171512 */
171513 static int sessionGenerateChangeset(
171514  sqlite3_session *pSession, /* Session object */
171515  int bPatchset, /* True for patchset, false for changeset */
171516  int (*xOutput)(void *pOut, const void *pData, int nData),
171517  void *pOut, /* First argument for xOutput */
171518  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171519  void **ppChangeset /* OUT: Buffer containing changeset */
171520 ){
171521  sqlite3 *db = pSession->db; /* Source database handle */
171522  SessionTable *pTab; /* Used to iterate through attached tables */
171523  SessionBuffer buf = {0,0,0}; /* Buffer in which to accumlate changeset */
171524  int rc; /* Return code */
171525 
171526  assert( xOutput==0 || (pnChangeset==0 && ppChangeset==0 ) );
171527 
171528  /* Zero the output variables in case an error occurs. If this session
171529  ** object is already in the error state (sqlite3_session.rc != SQLITE_OK),
171530  ** this call will be a no-op. */
171531  if( xOutput==0 ){
171532  *pnChangeset = 0;
171533  *ppChangeset = 0;
171534  }
171535 
171536  if( pSession->rc ) return pSession->rc;
171537  rc = sqlite3_exec(pSession->db, "SAVEPOINT changeset", 0, 0, 0);
171538  if( rc!=SQLITE_OK ) return rc;
171539 
171541 
171542  for(pTab=pSession->pTable; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
171543  if( pTab->nEntry ){
171544  const char *zName = pTab->zName;
171545  int nCol; /* Number of columns in table */
171546  u8 *abPK; /* Primary key array */
171547  const char **azCol = 0; /* Table columns */
171548  int i; /* Used to iterate through hash buckets */
171549  sqlite3_stmt *pSel = 0; /* SELECT statement to query table pTab */
171550  int nRewind = buf.nBuf; /* Initial size of write buffer */
171551  int nNoop; /* Size of buffer after writing tbl header */
171552 
171553  /* Check the table schema is still Ok. */
171554  rc = sessionTableInfo(db, pSession->zDb, zName, &nCol, 0, &azCol, &abPK);
171555  if( !rc && (pTab->nCol!=nCol || memcmp(abPK, pTab->abPK, nCol)) ){
171556  rc = SQLITE_SCHEMA;
171557  }
171558 
171559  /* Write a table header */
171560  sessionAppendTableHdr(&buf, bPatchset, pTab, &rc);
171561 
171562  /* Build and compile a statement to execute: */
171563  if( rc==SQLITE_OK ){
171564  rc = sessionSelectStmt(
171565  db, pSession->zDb, zName, nCol, azCol, abPK, &pSel);
171566  }
171567 
171568  nNoop = buf.nBuf;
171569  for(i=0; i<pTab->nChange && rc==SQLITE_OK; i++){
171570  SessionChange *p; /* Used to iterate through changes */
171571 
171572  for(p=pTab->apChange[i]; rc==SQLITE_OK && p; p=p->pNext){
171573  rc = sessionSelectBind(pSel, nCol, abPK, p);
171574  if( rc!=SQLITE_OK ) continue;
171575  if( sqlite3_step(pSel)==SQLITE_ROW ){
171576  if( p->op==SQLITE_INSERT ){
171577  int iCol;
171578  sessionAppendByte(&buf, SQLITE_INSERT, &rc);
171579  sessionAppendByte(&buf, p->bIndirect, &rc);
171580  for(iCol=0; iCol<nCol; iCol++){
171581  sessionAppendCol(&buf, pSel, iCol, &rc);
171582  }
171583  }else{
171584  rc = sessionAppendUpdate(&buf, bPatchset, pSel, p, abPK);
171585  }
171586  }else if( p->op!=SQLITE_INSERT ){
171587  rc = sessionAppendDelete(&buf, bPatchset, p, nCol, abPK);
171588  }
171589  if( rc==SQLITE_OK ){
171590  rc = sqlite3_reset(pSel);
171591  }
171592 
171593  /* If the buffer is now larger than SESSIONS_STRM_CHUNK_SIZE, pass
171594  ** its contents to the xOutput() callback. */
171595  if( xOutput
171596  && rc==SQLITE_OK
171597  && buf.nBuf>nNoop
171598  && buf.nBuf>SESSIONS_STRM_CHUNK_SIZE
171599  ){
171600  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171601  nNoop = -1;
171602  buf.nBuf = 0;
171603  }
171604 
171605  }
171606  }
171607 
171608  sqlite3_finalize(pSel);
171609  if( buf.nBuf==nNoop ){
171610  buf.nBuf = nRewind;
171611  }
171612  sqlite3_free((char*)azCol); /* cast works around VC++ bug */
171613  }
171614  }
171615 
171616  if( rc==SQLITE_OK ){
171617  if( xOutput==0 ){
171618  *pnChangeset = buf.nBuf;
171619  *ppChangeset = buf.aBuf;
171620  buf.aBuf = 0;
171621  }else if( buf.nBuf>0 ){
171622  rc = xOutput(pOut, (void*)buf.aBuf, buf.nBuf);
171623  }
171624  }
171625 
171626  sqlite3_free(buf.aBuf);
171627  sqlite3_exec(db, "RELEASE changeset", 0, 0, 0);
171629  return rc;
171630 }
171631 
171632 /*
171633 ** Obtain a changeset object containing all changes recorded by the
171634 ** session object passed as the first argument.
171635 **
171636 ** It is the responsibility of the caller to eventually free the buffer
171637 ** using sqlite3_free().
171638 */
171639 SQLITE_API int SQLITE_STDCALL sqlite3session_changeset(
171640  sqlite3_session *pSession, /* Session object */
171641  int *pnChangeset, /* OUT: Size of buffer at *ppChangeset */
171642  void **ppChangeset /* OUT: Buffer containing changeset */
171643 ){
171644  return sessionGenerateChangeset(pSession, 0, 0, 0, pnChangeset, ppChangeset);
171645 }
171646 
171647 /*
171648 ** Streaming version of sqlite3session_changeset().
171649 */
171650 SQLITE_API int SQLITE_STDCALL sqlite3session_changeset_strm(
171651  sqlite3_session *pSession,
171652  int (*xOutput)(void *pOut, const void *pData, int nData),
171653  void *pOut
171654 ){
171655  return sessionGenerateChangeset(pSession, 0, xOutput, pOut, 0, 0);
171656 }
171657 
171658 /*
171659 ** Streaming version of sqlite3session_patchset().
171660 */
171661 SQLITE_API int SQLITE_STDCALL sqlite3session_patchset_strm(
171662  sqlite3_session *pSession,
171663  int (*xOutput)(void *pOut, const void *pData, int nData),
171664  void *pOut
171665 ){
171666  return sessionGenerateChangeset(pSession, 1, xOutput, pOut, 0, 0);
171667 }
171668 
171669 /*
171670 ** Obtain a patchset object containing all changes recorded by the
171671 ** session object passed as the first argument.
171672 **
171673 ** It is the responsibility of the caller to eventually free the buffer
171674 ** using sqlite3_free().
171675 */
171676 SQLITE_API int SQLITE_STDCALL sqlite3session_patchset(
171677  sqlite3_session *pSession, /* Session object */
171678  int *pnPatchset, /* OUT: Size of buffer at *ppChangeset */
171679  void **ppPatchset /* OUT: Buffer containing changeset */
171680 ){
171681  return sessionGenerateChangeset(pSession, 1, 0, 0, pnPatchset, ppPatchset);
171682 }
171683 
171684 /*
171685 ** Enable or disable the session object passed as the first argument.
171686 */
171687 SQLITE_API int SQLITE_STDCALL sqlite3session_enable(sqlite3_session *pSession, int bEnable){
171688  int ret;
171689  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171690  if( bEnable>=0 ){
171691  pSession->bEnable = bEnable;
171692  }
171693  ret = pSession->bEnable;
171694  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171695  return ret;
171696 }
171697 
171698 /*
171699 ** Enable or disable the session object passed as the first argument.
171700 */
171701 SQLITE_API int SQLITE_STDCALL sqlite3session_indirect(sqlite3_session *pSession, int bIndirect){
171702  int ret;
171703  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171704  if( bIndirect>=0 ){
171705  pSession->bIndirect = bIndirect;
171706  }
171707  ret = pSession->bIndirect;
171708  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171709  return ret;
171710 }
171711 
171712 /*
171713 ** Return true if there have been no changes to monitored tables recorded
171714 ** by the session object passed as the only argument.
171715 */
171716 SQLITE_API int SQLITE_STDCALL sqlite3session_isempty(sqlite3_session *pSession){
171717  int ret = 0;
171718  SessionTable *pTab;
171719 
171720  sqlite3_mutex_enter(sqlite3_db_mutex(pSession->db));
171721  for(pTab=pSession->pTable; pTab && ret==0; pTab=pTab->pNext){
171722  ret = (pTab->nEntry>0);
171723  }
171724  sqlite3_mutex_leave(sqlite3_db_mutex(pSession->db));
171725 
171726  return (ret==0);
171727 }
171728 
171729 /*
171730 ** Do the work for either sqlite3changeset_start() or start_strm().
171731 */
171732 static int sessionChangesetStart(
171733  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171734  int (*xInput)(void *pIn, void *pData, int *pnData),
171735  void *pIn,
171736  int nChangeset, /* Size of buffer pChangeset in bytes */
171737  void *pChangeset /* Pointer to buffer containing changeset */
171738 ){
171739  sqlite3_changeset_iter *pRet; /* Iterator to return */
171740  int nByte; /* Number of bytes to allocate for iterator */
171741 
171742  assert( xInput==0 || (pChangeset==0 && nChangeset==0) );
171743 
171744  /* Zero the output variable in case an error occurs. */
171745  *pp = 0;
171746 
171747  /* Allocate and initialize the iterator structure. */
171748  nByte = sizeof(sqlite3_changeset_iter);
171749  pRet = (sqlite3_changeset_iter *)sqlite3_malloc(nByte);
171750  if( !pRet ) return SQLITE_NOMEM;
171751  memset(pRet, 0, sizeof(sqlite3_changeset_iter));
171752  pRet->in.aData = (u8 *)pChangeset;
171753  pRet->in.nData = nChangeset;
171754  pRet->in.xInput = xInput;
171755  pRet->in.pIn = pIn;
171756  pRet->in.bEof = (xInput ? 0 : 1);
171757 
171758  /* Populate the output variable and return success. */
171759  *pp = pRet;
171760  return SQLITE_OK;
171761 }
171762 
171763 /*
171764 ** Create an iterator used to iterate through the contents of a changeset.
171765 */
171766 SQLITE_API int SQLITE_STDCALL sqlite3changeset_start(
171767  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171768  int nChangeset, /* Size of buffer pChangeset in bytes */
171769  void *pChangeset /* Pointer to buffer containing changeset */
171770 ){
171771  return sessionChangesetStart(pp, 0, 0, nChangeset, pChangeset);
171772 }
171773 
171774 /*
171775 ** Streaming version of sqlite3changeset_start().
171776 */
171777 SQLITE_API int SQLITE_STDCALL sqlite3changeset_start_strm(
171778  sqlite3_changeset_iter **pp, /* OUT: Changeset iterator handle */
171779  int (*xInput)(void *pIn, void *pData, int *pnData),
171780  void *pIn
171781 ){
171782  return sessionChangesetStart(pp, xInput, pIn, 0, 0);
171783 }
171784 
171785 /*
171786 ** If the SessionInput object passed as the only argument is a streaming
171787 ** object and the buffer is full, discard some data to free up space.
171788 */
171789 static void sessionDiscardData(SessionInput *pIn){
171790  if( pIn->bEof && pIn->xInput && pIn->iNext>=SESSIONS_STRM_CHUNK_SIZE ){
171791  int nMove = pIn->buf.nBuf - pIn->iNext;
171792  assert( nMove>=0 );
171793  if( nMove>0 ){
171794  memmove(pIn->buf.aBuf, &pIn->buf.aBuf[pIn->iNext], nMove);
171795  }
171796  pIn->buf.nBuf -= pIn->iNext;
171797  pIn->iNext = 0;
171798  pIn->nData = pIn->buf.nBuf;
171799  }
171800 }
171801 
171802 /*
171803 ** Ensure that there are at least nByte bytes available in the buffer. Or,
171804 ** if there are not nByte bytes remaining in the input, that all available
171805 ** data is in the buffer.
171806 **
171807 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
171808 */
171809 static int sessionInputBuffer(SessionInput *pIn, int nByte){
171810  int rc = SQLITE_OK;
171811  if( pIn->xInput ){
171812  while( !pIn->bEof && (pIn->iNext+nByte)>=pIn->nData && rc==SQLITE_OK ){
171813  int nNew = SESSIONS_STRM_CHUNK_SIZE;
171814 
171815  if( pIn->bNoDiscard==0 ) sessionDiscardData(pIn);
171816  if( SQLITE_OK==sessionBufferGrow(&pIn->buf, nNew, &rc) ){
171817  rc = pIn->xInput(pIn->pIn, &pIn->buf.aBuf[pIn->buf.nBuf], &nNew);
171818  if( nNew==0 ){
171819  pIn->bEof = 1;
171820  }else{
171821  pIn->buf.nBuf += nNew;
171822  }
171823  }
171824 
171825  pIn->aData = pIn->buf.aBuf;
171826  pIn->nData = pIn->buf.nBuf;
171827  }
171828  }
171829  return rc;
171830 }
171831 
171832 /*
171833 ** When this function is called, *ppRec points to the start of a record
171834 ** that contains nCol values. This function advances the pointer *ppRec
171835 ** until it points to the byte immediately following that record.
171836 */
171837 static void sessionSkipRecord(
171838  u8 **ppRec, /* IN/OUT: Record pointer */
171839  int nCol /* Number of values in record */
171840 ){
171841  u8 *aRec = *ppRec;
171842  int i;
171843  for(i=0; i<nCol; i++){
171844  int eType = *aRec++;
171845  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171846  int nByte;
171847  aRec += sessionVarintGet((u8*)aRec, &nByte);
171848  aRec += nByte;
171849  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171850  aRec += 8;
171851  }
171852  }
171853 
171854  *ppRec = aRec;
171855 }
171856 
171857 /*
171858 ** This function sets the value of the sqlite3_value object passed as the
171859 ** first argument to a copy of the string or blob held in the aData[]
171860 ** buffer. SQLITE_OK is returned if successful, or SQLITE_NOMEM if an OOM
171861 ** error occurs.
171862 */
171863 static int sessionValueSetStr(
171864  sqlite3_value *pVal, /* Set the value of this object */
171865  u8 *aData, /* Buffer containing string or blob data */
171866  int nData, /* Size of buffer aData[] in bytes */
171867  u8 enc /* String encoding (0 for blobs) */
171868 ){
171869  /* In theory this code could just pass SQLITE_TRANSIENT as the final
171870  ** argument to sqlite3ValueSetStr() and have the copy created
171871  ** automatically. But doing so makes it difficult to detect any OOM
171872  ** error. Hence the code to create the copy externally. */
171873  u8 *aCopy = sqlite3_malloc(nData+1);
171874  if( aCopy==0 ) return SQLITE_NOMEM;
171875  memcpy(aCopy, aData, nData);
171876  sqlite3ValueSetStr(pVal, nData, (char*)aCopy, enc, sqlite3_free);
171877  return SQLITE_OK;
171878 }
171879 
171880 /*
171881 ** Deserialize a single record from a buffer in memory. See "RECORD FORMAT"
171882 ** for details.
171883 **
171884 ** When this function is called, *paChange points to the start of the record
171885 ** to deserialize. Assuming no error occurs, *paChange is set to point to
171886 ** one byte after the end of the same record before this function returns.
171887 ** If the argument abPK is NULL, then the record contains nCol values. Or,
171888 ** if abPK is other than NULL, then the record contains only the PK fields
171889 ** (in other words, it is a patchset DELETE record).
171890 **
171891 ** If successful, each element of the apOut[] array (allocated by the caller)
171892 ** is set to point to an sqlite3_value object containing the value read
171893 ** from the corresponding position in the record. If that value is not
171894 ** included in the record (i.e. because the record is part of an UPDATE change
171895 ** and the field was not modified), the corresponding element of apOut[] is
171896 ** set to NULL.
171897 **
171898 ** It is the responsibility of the caller to free all sqlite_value structures
171899 ** using sqlite3_free().
171900 **
171901 ** If an error occurs, an SQLite error code (e.g. SQLITE_NOMEM) is returned.
171902 ** The apOut[] array may have been partially populated in this case.
171903 */
171904 static int sessionReadRecord(
171905  SessionInput *pIn, /* Input data */
171906  int nCol, /* Number of values in record */
171907  u8 *abPK, /* Array of primary key flags, or NULL */
171908  sqlite3_value **apOut /* Write values to this array */
171909 ){
171910  int i; /* Used to iterate through columns */
171911  int rc = SQLITE_OK;
171912 
171913  for(i=0; i<nCol && rc==SQLITE_OK; i++){
171914  int eType = 0; /* Type of value (SQLITE_NULL, TEXT etc.) */
171915  if( abPK && abPK[i]==0 ) continue;
171916  rc = sessionInputBuffer(pIn, 9);
171917  if( rc==SQLITE_OK ){
171918  eType = pIn->aData[pIn->iNext++];
171919  }
171920 
171921  assert( apOut[i]==0 );
171922  if( eType ){
171923  apOut[i] = sqlite3ValueNew(0);
171924  if( !apOut[i] ) rc = SQLITE_NOMEM;
171925  }
171926 
171927  if( rc==SQLITE_OK ){
171928  u8 *aVal = &pIn->aData[pIn->iNext];
171929  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
171930  int nByte;
171931  pIn->iNext += sessionVarintGet(aVal, &nByte);
171932  rc = sessionInputBuffer(pIn, nByte);
171933  if( rc==SQLITE_OK ){
171934  u8 enc = (eType==SQLITE_TEXT ? SQLITE_UTF8 : 0);
171935  rc = sessionValueSetStr(apOut[i],&pIn->aData[pIn->iNext],nByte,enc);
171936  }
171937  pIn->iNext += nByte;
171938  }
171939  if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
171940  sqlite3_int64 v = sessionGetI64(aVal);
171941  if( eType==SQLITE_INTEGER ){
171942  sqlite3VdbeMemSetInt64(apOut[i], v);
171943  }else{
171944  double d;
171945  memcpy(&d, &v, 8);
171946  sqlite3VdbeMemSetDouble(apOut[i], d);
171947  }
171948  pIn->iNext += 8;
171949  }
171950  }
171951  }
171952 
171953  return rc;
171954 }
171955 
171956 /*
171957 ** The input pointer currently points to the second byte of a table-header.
171958 ** Specifically, to the following:
171959 **
171960 ** + number of columns in table (varint)
171961 ** + array of PK flags (1 byte per column),
171962 ** + table name (nul terminated).
171963 **
171964 ** This function ensures that all of the above is present in the input
171965 ** buffer (i.e. that it can be accessed without any calls to xInput()).
171966 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
171967 ** The input pointer is not moved.
171968 */
171969 static int sessionChangesetBufferTblhdr(SessionInput *pIn, int *pnByte){
171970  int rc = SQLITE_OK;
171971  int nCol = 0;
171972  int nRead = 0;
171973 
171974  rc = sessionInputBuffer(pIn, 9);
171975  if( rc==SQLITE_OK ){
171976  nRead += sessionVarintGet(&pIn->aData[pIn->iNext + nRead], &nCol);
171977  rc = sessionInputBuffer(pIn, nRead+nCol+100);
171978  nRead += nCol;
171979  }
171980 
171981  while( rc==SQLITE_OK ){
171982  while( (pIn->iNext + nRead)<pIn->nData && pIn->aData[pIn->iNext + nRead] ){
171983  nRead++;
171984  }
171985  if( (pIn->iNext + nRead)<pIn->nData ) break;
171986  rc = sessionInputBuffer(pIn, nRead + 100);
171987  }
171988  *pnByte = nRead+1;
171989  return rc;
171990 }
171991 
171992 /*
171993 ** The input pointer currently points to the first byte of the first field
171994 ** of a record consisting of nCol columns. This function ensures the entire
171995 ** record is buffered. It does not move the input pointer.
171996 **
171997 ** If successful, SQLITE_OK is returned and *pnByte is set to the size of
171998 ** the record in bytes. Otherwise, an SQLite error code is returned. The
171999 ** final value of *pnByte is undefined in this case.
172000 */
172001 static int sessionChangesetBufferRecord(
172002  SessionInput *pIn, /* Input data */
172003  int nCol, /* Number of columns in record */
172004  int *pnByte /* OUT: Size of record in bytes */
172005 ){
172006  int rc = SQLITE_OK;
172007  int nByte = 0;
172008  int i;
172009  for(i=0; rc==SQLITE_OK && i<nCol; i++){
172010  int eType;
172011  rc = sessionInputBuffer(pIn, nByte + 10);
172012  if( rc==SQLITE_OK ){
172013  eType = pIn->aData[pIn->iNext + nByte++];
172014  if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
172015  int n;
172016  nByte += sessionVarintGet(&pIn->aData[pIn->iNext+nByte], &n);
172017  nByte += n;
172018  rc = sessionInputBuffer(pIn, nByte);
172019  }else if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
172020  nByte += 8;
172021  }
172022  }
172023  }
172024  *pnByte = nByte;
172025  return rc;
172026 }
172027 
172028 /*
172029 ** The input pointer currently points to the second byte of a table-header.
172030 ** Specifically, to the following:
172031 **
172032 ** + number of columns in table (varint)
172033 ** + array of PK flags (1 byte per column),
172034 ** + table name (nul terminated).
172035 **
172036 ** This function decodes the table-header and populates the p->nCol,
172037 ** p->zTab and p->abPK[] variables accordingly. The p->apValue[] array is
172038 ** also allocated or resized according to the new value of p->nCol. The
172039 ** input pointer is left pointing to the byte following the table header.
172040 **
172041 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code
172042 ** is returned and the final values of the various fields enumerated above
172043 ** are undefined.
172044 */
172045 static int sessionChangesetReadTblhdr(sqlite3_changeset_iter *p){
172046  int rc;
172047  int nCopy;
172048  assert( p->rc==SQLITE_OK );
172049 
172050  rc = sessionChangesetBufferTblhdr(&p->in, &nCopy);
172051  if( rc==SQLITE_OK ){
172052  int nByte;
172053  int nVarint;
172054  nVarint = sessionVarintGet(&p->in.aData[p->in.iNext], &p->nCol);
172055  nCopy -= nVarint;
172056  p->in.iNext += nVarint;
172057  nByte = p->nCol * sizeof(sqlite3_value*) * 2 + nCopy;
172058  p->tblhdr.nBuf = 0;
172059  sessionBufferGrow(&p->tblhdr, nByte, &rc);
172060  }
172061 
172062  if( rc==SQLITE_OK ){
172063  int iPK = sizeof(sqlite3_value*)*p->nCol*2;
172064  memset(p->tblhdr.aBuf, 0, iPK);
172065  memcpy(&p->tblhdr.aBuf[iPK], &p->in.aData[p->in.iNext], nCopy);
172066  p->in.iNext += nCopy;
172067  }
172068 
172069  p->apValue = (sqlite3_value**)p->tblhdr.aBuf;
172070  p->abPK = (u8*)&p->apValue[p->nCol*2];
172071  p->zTab = (char*)&p->abPK[p->nCol];
172072  return (p->rc = rc);
172073 }
172074 
172075 /*
172076 ** Advance the changeset iterator to the next change.
172077 **
172078 ** If both paRec and pnRec are NULL, then this function works like the public
172079 ** API sqlite3changeset_next(). If SQLITE_ROW is returned, then the
172080 ** sqlite3changeset_new() and old() APIs may be used to query for values.
172081 **
172082 ** Otherwise, if paRec and pnRec are not NULL, then a pointer to the change
172083 ** record is written to *paRec before returning and the number of bytes in
172084 ** the record to *pnRec.
172085 **
172086 ** Either way, this function returns SQLITE_ROW if the iterator is
172087 ** successfully advanced to the next change in the changeset, an SQLite
172088 ** error code if an error occurs, or SQLITE_DONE if there are no further
172089 ** changes in the changeset.
172090 */
172091 static int sessionChangesetNext(
172092  sqlite3_changeset_iter *p, /* Changeset iterator */
172093  u8 **paRec, /* If non-NULL, store record pointer here */
172094  int *pnRec /* If non-NULL, store size of record here */
172095 ){
172096  int i;
172097  u8 op;
172098 
172099  assert( (paRec==0 && pnRec==0) || (paRec && pnRec) );
172100 
172101  /* If the iterator is in the error-state, return immediately. */
172102  if( p->rc!=SQLITE_OK ) return p->rc;
172103 
172104  /* Free the current contents of p->apValue[], if any. */
172105  if( p->apValue ){
172106  for(i=0; i<p->nCol*2; i++){
172107  sqlite3ValueFree(p->apValue[i]);
172108  }
172109  memset(p->apValue, 0, sizeof(sqlite3_value*)*p->nCol*2);
172110  }
172111 
172112  /* Make sure the buffer contains at least 10 bytes of input data, or all
172113  ** remaining data if there are less than 10 bytes available. This is
172114  ** sufficient either for the 'T' or 'P' byte and the varint that follows
172115  ** it, or for the two single byte values otherwise. */
172116  p->rc = sessionInputBuffer(&p->in, 2);
172117  if( p->rc!=SQLITE_OK ) return p->rc;
172118 
172119  /* If the iterator is already at the end of the changeset, return DONE. */
172120  if( p->in.iNext>=p->in.nData ){
172121  return SQLITE_DONE;
172122  }
172123 
172124  sessionDiscardData(&p->in);
172125  p->in.iCurrent = p->in.iNext;
172126 
172127  op = p->in.aData[p->in.iNext++];
172128  if( op=='T' || op=='P' ){
172129  p->bPatchset = (op=='P');
172130  if( sessionChangesetReadTblhdr(p) ) return p->rc;
172131  if( (p->rc = sessionInputBuffer(&p->in, 2)) ) return p->rc;
172132  p->in.iCurrent = p->in.iNext;
172133  op = p->in.aData[p->in.iNext++];
172134  }
172135 
172136  p->op = op;
172137  p->bIndirect = p->in.aData[p->in.iNext++];
172138  if( p->op!=SQLITE_UPDATE && p->op!=SQLITE_DELETE && p->op!=SQLITE_INSERT ){
172139  return (p->rc = SQLITE_CORRUPT_BKPT);
172140  }
172141 
172142  if( paRec ){
172143  int nVal; /* Number of values to buffer */
172144  if( p->bPatchset==0 && op==SQLITE_UPDATE ){
172145  nVal = p->nCol * 2;
172146  }else if( p->bPatchset && op==SQLITE_DELETE ){
172147  nVal = 0;
172148  for(i=0; i<p->nCol; i++) if( p->abPK[i] ) nVal++;
172149  }else{
172150  nVal = p->nCol;
172151  }
172152  p->rc = sessionChangesetBufferRecord(&p->in, nVal, pnRec);
172153  if( p->rc!=SQLITE_OK ) return p->rc;
172154  *paRec = &p->in.aData[p->in.iNext];
172155  p->in.iNext += *pnRec;
172156  }else{
172157 
172158  /* If this is an UPDATE or DELETE, read the old.* record. */
172159  if( p->op!=SQLITE_INSERT && (p->bPatchset==0 || p->op==SQLITE_DELETE) ){
172160  u8 *abPK = p->bPatchset ? p->abPK : 0;
172161  p->rc = sessionReadRecord(&p->in, p->nCol, abPK, p->apValue);
172162  if( p->rc!=SQLITE_OK ) return p->rc;
172163  }
172164 
172165  /* If this is an INSERT or UPDATE, read the new.* record. */
172166  if( p->op!=SQLITE_DELETE ){
172167  p->rc = sessionReadRecord(&p->in, p->nCol, 0, &p->apValue[p->nCol]);
172168  if( p->rc!=SQLITE_OK ) return p->rc;
172169  }
172170 
172171  if( p->bPatchset && p->op==SQLITE_UPDATE ){
172172  /* If this is an UPDATE that is part of a patchset, then all PK and
172173  ** modified fields are present in the new.* record. The old.* record
172174  ** is currently completely empty. This block shifts the PK fields from
172175  ** new.* to old.*, to accommodate the code that reads these arrays. */
172176  for(i=0; i<p->nCol; i++){
172177  assert( p->apValue[i]==0 );
172178  assert( p->abPK[i]==0 || p->apValue[i+p->nCol] );
172179  if( p->abPK[i] ){
172180  p->apValue[i] = p->apValue[i+p->nCol];
172181  p->apValue[i+p->nCol] = 0;
172182  }
172183  }
172184  }
172185  }
172186 
172187  return SQLITE_ROW;
172188 }
172189 
172190 /*
172191 ** Advance an iterator created by sqlite3changeset_start() to the next
172192 ** change in the changeset. This function may return SQLITE_ROW, SQLITE_DONE
172193 ** or SQLITE_CORRUPT.
172194 **
172195 ** This function may not be called on iterators passed to a conflict handler
172196 ** callback by changeset_apply().
172197 */
172198 SQLITE_API int SQLITE_STDCALL sqlite3changeset_next(sqlite3_changeset_iter *p){
172199  return sessionChangesetNext(p, 0, 0);
172200 }
172201 
172202 /*
172203 ** The following function extracts information on the current change
172204 ** from a changeset iterator. It may only be called after changeset_next()
172205 ** has returned SQLITE_ROW.
172206 */
172207 SQLITE_API int SQLITE_STDCALL sqlite3changeset_op(
172208  sqlite3_changeset_iter *pIter, /* Iterator handle */
172209  const char **pzTab, /* OUT: Pointer to table name */
172210  int *pnCol, /* OUT: Number of columns in table */
172211  int *pOp, /* OUT: SQLITE_INSERT, DELETE or UPDATE */
172212  int *pbIndirect /* OUT: True if change is indirect */
172213 ){
172214  *pOp = pIter->op;
172215  *pnCol = pIter->nCol;
172216  *pzTab = pIter->zTab;
172217  if( pbIndirect ) *pbIndirect = pIter->bIndirect;
172218  return SQLITE_OK;
172219 }
172220 
172221 /*
172222 ** Return information regarding the PRIMARY KEY and number of columns in
172223 ** the database table affected by the change that pIter currently points
172224 ** to. This function may only be called after changeset_next() returns
172225 ** SQLITE_ROW.
172226 */
172227 SQLITE_API int SQLITE_STDCALL sqlite3changeset_pk(
172228  sqlite3_changeset_iter *pIter, /* Iterator object */
172229  unsigned char **pabPK, /* OUT: Array of boolean - true for PK cols */
172230  int *pnCol /* OUT: Number of entries in output array */
172231 ){
172232  *pabPK = pIter->abPK;
172233  if( pnCol ) *pnCol = pIter->nCol;
172234  return SQLITE_OK;
172235 }
172236 
172237 /*
172238 ** This function may only be called while the iterator is pointing to an
172239 ** SQLITE_UPDATE or SQLITE_DELETE change (see sqlite3changeset_op()).
172240 ** Otherwise, SQLITE_MISUSE is returned.
172241 **
172242 ** It sets *ppValue to point to an sqlite3_value structure containing the
172243 ** iVal'th value in the old.* record. Or, if that particular value is not
172244 ** included in the record (because the change is an UPDATE and the field
172245 ** was not modified and is not a PK column), set *ppValue to NULL.
172246 **
172247 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172248 ** not modified. Otherwise, SQLITE_OK.
172249 */
172250 SQLITE_API int SQLITE_STDCALL sqlite3changeset_old(
172251  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172252  int iVal, /* Index of old.* value to retrieve */
172253  sqlite3_value **ppValue /* OUT: Old value (or NULL pointer) */
172254 ){
172255  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_DELETE ){
172256  return SQLITE_MISUSE;
172257  }
172258  if( iVal<0 || iVal>=pIter->nCol ){
172259  return SQLITE_RANGE;
172260  }
172261  *ppValue = pIter->apValue[iVal];
172262  return SQLITE_OK;
172263 }
172264 
172265 /*
172266 ** This function may only be called while the iterator is pointing to an
172267 ** SQLITE_UPDATE or SQLITE_INSERT change (see sqlite3changeset_op()).
172268 ** Otherwise, SQLITE_MISUSE is returned.
172269 **
172270 ** It sets *ppValue to point to an sqlite3_value structure containing the
172271 ** iVal'th value in the new.* record. Or, if that particular value is not
172272 ** included in the record (because the change is an UPDATE and the field
172273 ** was not modified), set *ppValue to NULL.
172274 **
172275 ** If value iVal is out-of-range, SQLITE_RANGE is returned and *ppValue is
172276 ** not modified. Otherwise, SQLITE_OK.
172277 */
172278 SQLITE_API int SQLITE_STDCALL sqlite3changeset_new(
172279  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172280  int iVal, /* Index of new.* value to retrieve */
172281  sqlite3_value **ppValue /* OUT: New value (or NULL pointer) */
172282 ){
172283  if( pIter->op!=SQLITE_UPDATE && pIter->op!=SQLITE_INSERT ){
172284  return SQLITE_MISUSE;
172285  }
172286  if( iVal<0 || iVal>=pIter->nCol ){
172287  return SQLITE_RANGE;
172288  }
172289  *ppValue = pIter->apValue[pIter->nCol+iVal];
172290  return SQLITE_OK;
172291 }
172292 
172293 /*
172294 ** The following two macros are used internally. They are similar to the
172295 ** sqlite3changeset_new() and sqlite3changeset_old() functions, except that
172296 ** they omit all error checking and return a pointer to the requested value.
172297 */
172298 #define sessionChangesetNew(pIter, iVal) (pIter)->apValue[(pIter)->nCol+(iVal)]
172299 #define sessionChangesetOld(pIter, iVal) (pIter)->apValue[(iVal)]
172300 
172301 /*
172302 ** This function may only be called with a changeset iterator that has been
172303 ** passed to an SQLITE_CHANGESET_DATA or SQLITE_CHANGESET_CONFLICT
172304 ** conflict-handler function. Otherwise, SQLITE_MISUSE is returned.
172305 **
172306 ** If successful, *ppValue is set to point to an sqlite3_value structure
172307 ** containing the iVal'th value of the conflicting record.
172308 **
172309 ** If value iVal is out-of-range or some other error occurs, an SQLite error
172310 ** code is returned. Otherwise, SQLITE_OK.
172311 */
172312 SQLITE_API int SQLITE_STDCALL sqlite3changeset_conflict(
172313  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172314  int iVal, /* Index of conflict record value to fetch */
172315  sqlite3_value **ppValue /* OUT: Value from conflicting row */
172316 ){
172317  if( !pIter->pConflict ){
172318  return SQLITE_MISUSE;
172319  }
172320  if( iVal<0 || iVal>=sqlite3_column_count(pIter->pConflict) ){
172321  return SQLITE_RANGE;
172322  }
172323  *ppValue = sqlite3_column_value(pIter->pConflict, iVal);
172324  return SQLITE_OK;
172325 }
172326 
172327 /*
172328 ** This function may only be called with an iterator passed to an
172329 ** SQLITE_CHANGESET_FOREIGN_KEY conflict handler callback. In this case
172330 ** it sets the output variable to the total number of known foreign key
172331 ** violations in the destination database and returns SQLITE_OK.
172332 **
172333 ** In all other cases this function returns SQLITE_MISUSE.
172334 */
172335 SQLITE_API int SQLITE_STDCALL sqlite3changeset_fk_conflicts(
172336  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172337  int *pnOut /* OUT: Number of FK violations */
172338 ){
172339  if( pIter->pConflict || pIter->apValue ){
172340  return SQLITE_MISUSE;
172341  }
172342  *pnOut = pIter->nCol;
172343  return SQLITE_OK;
172344 }
172345 
172346 
172347 /*
172348 ** Finalize an iterator allocated with sqlite3changeset_start().
172349 **
172350 ** This function may not be called on iterators passed to a conflict handler
172351 ** callback by changeset_apply().
172352 */
172353 SQLITE_API int SQLITE_STDCALL sqlite3changeset_finalize(sqlite3_changeset_iter *p){
172354  int rc = SQLITE_OK;
172355  if( p ){
172356  int i; /* Used to iterate through p->apValue[] */
172357  rc = p->rc;
172358  if( p->apValue ){
172359  for(i=0; i<p->nCol*2; i++) sqlite3ValueFree(p->apValue[i]);
172360  }
172361  sqlite3_free(p->tblhdr.aBuf);
172362  sqlite3_free(p->in.buf.aBuf);
172363  sqlite3_free(p);
172364  }
172365  return rc;
172366 }
172367 
172368 static int sessionChangesetInvert(
172369  SessionInput *pInput, /* Input changeset */
172370  int (*xOutput)(void *pOut, const void *pData, int nData),
172371  void *pOut,
172372  int *pnInverted, /* OUT: Number of bytes in output changeset */
172373  void **ppInverted /* OUT: Inverse of pChangeset */
172374 ){
172375  int rc = SQLITE_OK; /* Return value */
172376  SessionBuffer sOut; /* Output buffer */
172377  int nCol = 0; /* Number of cols in current table */
172378  u8 *abPK = 0; /* PK array for current table */
172379  sqlite3_value **apVal = 0; /* Space for values for UPDATE inversion */
172380  SessionBuffer sPK = {0, 0, 0}; /* PK array for current table */
172381 
172382  /* Initialize the output buffer */
172383  memset(&sOut, 0, sizeof(SessionBuffer));
172384 
172385  /* Zero the output variables in case an error occurs. */
172386  if( ppInverted ){
172387  *ppInverted = 0;
172388  *pnInverted = 0;
172389  }
172390 
172391  while( 1 ){
172392  u8 eType;
172393 
172394  /* Test for EOF. */
172395  if( (rc = sessionInputBuffer(pInput, 2)) ) goto finished_invert;
172396  if( pInput->iNext>=pInput->nData ) break;
172397  eType = pInput->aData[pInput->iNext];
172398 
172399  switch( eType ){
172400  case 'T': {
172401  /* A 'table' record consists of:
172402  **
172403  ** * A constant 'T' character,
172404  ** * Number of columns in said table (a varint),
172405  ** * An array of nCol bytes (sPK),
172406  ** * A nul-terminated table name.
172407  */
172408  int nByte;
172409  int nVar;
172410  pInput->iNext++;
172411  if( (rc = sessionChangesetBufferTblhdr(pInput, &nByte)) ){
172412  goto finished_invert;
172413  }
172414  nVar = sessionVarintGet(&pInput->aData[pInput->iNext], &nCol);
172415  sPK.nBuf = 0;
172416  sessionAppendBlob(&sPK, &pInput->aData[pInput->iNext+nVar], nCol, &rc);
172417  sessionAppendByte(&sOut, eType, &rc);
172418  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172419  if( rc ) goto finished_invert;
172420 
172421  pInput->iNext += nByte;
172422  sqlite3_free(apVal);
172423  apVal = 0;
172424  abPK = sPK.aBuf;
172425  break;
172426  }
172427 
172428  case SQLITE_INSERT:
172429  case SQLITE_DELETE: {
172430  int nByte;
172431  int bIndirect = pInput->aData[pInput->iNext+1];
172432  int eType2 = (eType==SQLITE_DELETE ? SQLITE_INSERT : SQLITE_DELETE);
172433  pInput->iNext += 2;
172434  assert( rc==SQLITE_OK );
172435  rc = sessionChangesetBufferRecord(pInput, nCol, &nByte);
172436  sessionAppendByte(&sOut, eType2, &rc);
172437  sessionAppendByte(&sOut, bIndirect, &rc);
172438  sessionAppendBlob(&sOut, &pInput->aData[pInput->iNext], nByte, &rc);
172439  pInput->iNext += nByte;
172440  if( rc ) goto finished_invert;
172441  break;
172442  }
172443 
172444  case SQLITE_UPDATE: {
172445  int iCol;
172446 
172447  if( 0==apVal ){
172448  apVal = (sqlite3_value **)sqlite3_malloc(sizeof(apVal[0])*nCol*2);
172449  if( 0==apVal ){
172450  rc = SQLITE_NOMEM;
172451  goto finished_invert;
172452  }
172453  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172454  }
172455 
172456  /* Write the header for the new UPDATE change. Same as the original. */
172457  sessionAppendByte(&sOut, eType, &rc);
172458  sessionAppendByte(&sOut, pInput->aData[pInput->iNext+1], &rc);
172459 
172460  /* Read the old.* and new.* records for the update change. */
172461  pInput->iNext += 2;
172462  rc = sessionReadRecord(pInput, nCol, 0, &apVal[0]);
172463  if( rc==SQLITE_OK ){
172464  rc = sessionReadRecord(pInput, nCol, 0, &apVal[nCol]);
172465  }
172466 
172467  /* Write the new old.* record. Consists of the PK columns from the
172468  ** original old.* record, and the other values from the original
172469  ** new.* record. */
172470  for(iCol=0; iCol<nCol; iCol++){
172471  sqlite3_value *pVal = apVal[iCol + (abPK[iCol] ? 0 : nCol)];
172472  sessionAppendValue(&sOut, pVal, &rc);
172473  }
172474 
172475  /* Write the new new.* record. Consists of a copy of all values
172476  ** from the original old.* record, except for the PK columns, which
172477  ** are set to "undefined". */
172478  for(iCol=0; iCol<nCol; iCol++){
172479  sqlite3_value *pVal = (abPK[iCol] ? 0 : apVal[iCol]);
172480  sessionAppendValue(&sOut, pVal, &rc);
172481  }
172482 
172483  for(iCol=0; iCol<nCol*2; iCol++){
172484  sqlite3ValueFree(apVal[iCol]);
172485  }
172486  memset(apVal, 0, sizeof(apVal[0])*nCol*2);
172487  if( rc!=SQLITE_OK ){
172488  goto finished_invert;
172489  }
172490 
172491  break;
172492  }
172493 
172494  default:
172495  rc = SQLITE_CORRUPT_BKPT;
172496  goto finished_invert;
172497  }
172498 
172499  assert( rc==SQLITE_OK );
172500  if( xOutput && sOut.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
172501  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172502  sOut.nBuf = 0;
172503  if( rc!=SQLITE_OK ) goto finished_invert;
172504  }
172505  }
172506 
172507  assert( rc==SQLITE_OK );
172508  if( pnInverted ){
172509  *pnInverted = sOut.nBuf;
172510  *ppInverted = sOut.aBuf;
172511  sOut.aBuf = 0;
172512  }else if( sOut.nBuf>0 ){
172513  rc = xOutput(pOut, sOut.aBuf, sOut.nBuf);
172514  }
172515 
172516  finished_invert:
172517  sqlite3_free(sOut.aBuf);
172518  sqlite3_free(apVal);
172519  sqlite3_free(sPK.aBuf);
172520  return rc;
172521 }
172522 
172523 
172524 /*
172525 ** Invert a changeset object.
172526 */
172527 SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert(
172528  int nChangeset, /* Number of bytes in input */
172529  const void *pChangeset, /* Input changeset */
172530  int *pnInverted, /* OUT: Number of bytes in output changeset */
172531  void **ppInverted /* OUT: Inverse of pChangeset */
172532 ){
172533  SessionInput sInput;
172534 
172535  /* Set up the input stream */
172536  memset(&sInput, 0, sizeof(SessionInput));
172537  sInput.nData = nChangeset;
172538  sInput.aData = (u8*)pChangeset;
172539 
172540  return sessionChangesetInvert(&sInput, 0, 0, pnInverted, ppInverted);
172541 }
172542 
172543 /*
172544 ** Streaming version of sqlite3changeset_invert().
172545 */
172546 SQLITE_API int SQLITE_STDCALL sqlite3changeset_invert_strm(
172547  int (*xInput)(void *pIn, void *pData, int *pnData),
172548  void *pIn,
172549  int (*xOutput)(void *pOut, const void *pData, int nData),
172550  void *pOut
172551 ){
172552  SessionInput sInput;
172553  int rc;
172554 
172555  /* Set up the input stream */
172556  memset(&sInput, 0, sizeof(SessionInput));
172557  sInput.xInput = xInput;
172558  sInput.pIn = pIn;
172559 
172560  rc = sessionChangesetInvert(&sInput, xOutput, pOut, 0, 0);
172561  sqlite3_free(sInput.buf.aBuf);
172562  return rc;
172563 }
172564 
172565 typedef struct SessionApplyCtx SessionApplyCtx;
172566 struct SessionApplyCtx {
172567  sqlite3 *db;
172568  sqlite3_stmt *pDelete; /* DELETE statement */
172569  sqlite3_stmt *pUpdate; /* UPDATE statement */
172570  sqlite3_stmt *pInsert; /* INSERT statement */
172571  sqlite3_stmt *pSelect; /* SELECT statement */
172572  int nCol; /* Size of azCol[] and abPK[] arrays */
172573  const char **azCol; /* Array of column names */
172574  u8 *abPK; /* Boolean array - true if column is in PK */
172575 
172576  int bDeferConstraints; /* True to defer constraints */
172577  SessionBuffer constraints; /* Deferred constraints are stored here */
172578 };
172579 
172580 /*
172581 ** Formulate a statement to DELETE a row from database db. Assuming a table
172582 ** structure like this:
172583 **
172584 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172585 **
172586 ** The DELETE statement looks like this:
172587 **
172588 ** DELETE FROM x WHERE a = :1 AND c = :3 AND (:5 OR b IS :2 AND d IS :4)
172589 **
172590 ** Variable :5 (nCol+1) is a boolean. It should be set to 0 if we require
172591 ** matching b and d values, or 1 otherwise. The second case comes up if the
172592 ** conflict handler is invoked with NOTFOUND and returns CHANGESET_REPLACE.
172593 **
172594 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pDelete is left
172595 ** pointing to the prepared version of the SQL statement.
172596 */
172597 static int sessionDeleteRow(
172598  sqlite3 *db, /* Database handle */
172599  const char *zTab, /* Table name */
172600  SessionApplyCtx *p /* Session changeset-apply context */
172601 ){
172602  int i;
172603  const char *zSep = "";
172604  int rc = SQLITE_OK;
172605  SessionBuffer buf = {0, 0, 0};
172606  int nPk = 0;
172607 
172608  sessionAppendStr(&buf, "DELETE FROM ", &rc);
172609  sessionAppendIdent(&buf, zTab, &rc);
172610  sessionAppendStr(&buf, " WHERE ", &rc);
172611 
172612  for(i=0; i<p->nCol; i++){
172613  if( p->abPK[i] ){
172614  nPk++;
172615  sessionAppendStr(&buf, zSep, &rc);
172616  sessionAppendIdent(&buf, p->azCol[i], &rc);
172617  sessionAppendStr(&buf, " = ?", &rc);
172618  sessionAppendInteger(&buf, i+1, &rc);
172619  zSep = " AND ";
172620  }
172621  }
172622 
172623  if( nPk<p->nCol ){
172624  sessionAppendStr(&buf, " AND (?", &rc);
172625  sessionAppendInteger(&buf, p->nCol+1, &rc);
172626  sessionAppendStr(&buf, " OR ", &rc);
172627 
172628  zSep = "";
172629  for(i=0; i<p->nCol; i++){
172630  if( !p->abPK[i] ){
172631  sessionAppendStr(&buf, zSep, &rc);
172632  sessionAppendIdent(&buf, p->azCol[i], &rc);
172633  sessionAppendStr(&buf, " IS ?", &rc);
172634  sessionAppendInteger(&buf, i+1, &rc);
172635  zSep = "AND ";
172636  }
172637  }
172638  sessionAppendStr(&buf, ")", &rc);
172639  }
172640 
172641  if( rc==SQLITE_OK ){
172642  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pDelete, 0);
172643  }
172644  sqlite3_free(buf.aBuf);
172645 
172646  return rc;
172647 }
172648 
172649 /*
172650 ** Formulate and prepare a statement to UPDATE a row from database db.
172651 ** Assuming a table structure like this:
172652 **
172653 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172654 **
172655 ** The UPDATE statement looks like this:
172656 **
172657 ** UPDATE x SET
172658 ** a = CASE WHEN ?2 THEN ?3 ELSE a END,
172659 ** b = CASE WHEN ?5 THEN ?6 ELSE b END,
172660 ** c = CASE WHEN ?8 THEN ?9 ELSE c END,
172661 ** d = CASE WHEN ?11 THEN ?12 ELSE d END
172662 ** WHERE a = ?1 AND c = ?7 AND (?13 OR
172663 ** (?5==0 OR b IS ?4) AND (?11==0 OR d IS ?10) AND
172664 ** )
172665 **
172666 ** For each column in the table, there are three variables to bind:
172667 **
172668 ** ?(i*3+1) The old.* value of the column, if any.
172669 ** ?(i*3+2) A boolean flag indicating that the value is being modified.
172670 ** ?(i*3+3) The new.* value of the column, if any.
172671 **
172672 ** Also, a boolean flag that, if set to true, causes the statement to update
172673 ** a row even if the non-PK values do not match. This is required if the
172674 ** conflict-handler is invoked with CHANGESET_DATA and returns
172675 ** CHANGESET_REPLACE. This is variable "?(nCol*3+1)".
172676 **
172677 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pUpdate is left
172678 ** pointing to the prepared version of the SQL statement.
172679 */
172680 static int sessionUpdateRow(
172681  sqlite3 *db, /* Database handle */
172682  const char *zTab, /* Table name */
172683  SessionApplyCtx *p /* Session changeset-apply context */
172684 ){
172685  int rc = SQLITE_OK;
172686  int i;
172687  const char *zSep = "";
172688  SessionBuffer buf = {0, 0, 0};
172689 
172690  /* Append "UPDATE tbl SET " */
172691  sessionAppendStr(&buf, "UPDATE ", &rc);
172692  sessionAppendIdent(&buf, zTab, &rc);
172693  sessionAppendStr(&buf, " SET ", &rc);
172694 
172695  /* Append the assignments */
172696  for(i=0; i<p->nCol; i++){
172697  sessionAppendStr(&buf, zSep, &rc);
172698  sessionAppendIdent(&buf, p->azCol[i], &rc);
172699  sessionAppendStr(&buf, " = CASE WHEN ?", &rc);
172700  sessionAppendInteger(&buf, i*3+2, &rc);
172701  sessionAppendStr(&buf, " THEN ?", &rc);
172702  sessionAppendInteger(&buf, i*3+3, &rc);
172703  sessionAppendStr(&buf, " ELSE ", &rc);
172704  sessionAppendIdent(&buf, p->azCol[i], &rc);
172705  sessionAppendStr(&buf, " END", &rc);
172706  zSep = ", ";
172707  }
172708 
172709  /* Append the PK part of the WHERE clause */
172710  sessionAppendStr(&buf, " WHERE ", &rc);
172711  for(i=0; i<p->nCol; i++){
172712  if( p->abPK[i] ){
172713  sessionAppendIdent(&buf, p->azCol[i], &rc);
172714  sessionAppendStr(&buf, " = ?", &rc);
172715  sessionAppendInteger(&buf, i*3+1, &rc);
172716  sessionAppendStr(&buf, " AND ", &rc);
172717  }
172718  }
172719 
172720  /* Append the non-PK part of the WHERE clause */
172721  sessionAppendStr(&buf, " (?", &rc);
172722  sessionAppendInteger(&buf, p->nCol*3+1, &rc);
172723  sessionAppendStr(&buf, " OR 1", &rc);
172724  for(i=0; i<p->nCol; i++){
172725  if( !p->abPK[i] ){
172726  sessionAppendStr(&buf, " AND (?", &rc);
172727  sessionAppendInteger(&buf, i*3+2, &rc);
172728  sessionAppendStr(&buf, "=0 OR ", &rc);
172729  sessionAppendIdent(&buf, p->azCol[i], &rc);
172730  sessionAppendStr(&buf, " IS ?", &rc);
172731  sessionAppendInteger(&buf, i*3+1, &rc);
172732  sessionAppendStr(&buf, ")", &rc);
172733  }
172734  }
172735  sessionAppendStr(&buf, ")", &rc);
172736 
172737  if( rc==SQLITE_OK ){
172738  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pUpdate, 0);
172739  }
172740  sqlite3_free(buf.aBuf);
172741 
172742  return rc;
172743 }
172744 
172745 /*
172746 ** Formulate and prepare an SQL statement to query table zTab by primary
172747 ** key. Assuming the following table structure:
172748 **
172749 ** CREATE TABLE x(a, b, c, d, PRIMARY KEY(a, c));
172750 **
172751 ** The SELECT statement looks like this:
172752 **
172753 ** SELECT * FROM x WHERE a = ?1 AND c = ?3
172754 **
172755 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pSelect is left
172756 ** pointing to the prepared version of the SQL statement.
172757 */
172758 static int sessionSelectRow(
172759  sqlite3 *db, /* Database handle */
172760  const char *zTab, /* Table name */
172761  SessionApplyCtx *p /* Session changeset-apply context */
172762 ){
172763  return sessionSelectStmt(
172764  db, "main", zTab, p->nCol, p->azCol, p->abPK, &p->pSelect);
172765 }
172766 
172767 /*
172768 ** Formulate and prepare an INSERT statement to add a record to table zTab.
172769 ** For example:
172770 **
172771 ** INSERT INTO main."zTab" VALUES(?1, ?2, ?3 ...);
172772 **
172773 ** If successful, SQLITE_OK is returned and SessionApplyCtx.pInsert is left
172774 ** pointing to the prepared version of the SQL statement.
172775 */
172776 static int sessionInsertRow(
172777  sqlite3 *db, /* Database handle */
172778  const char *zTab, /* Table name */
172779  SessionApplyCtx *p /* Session changeset-apply context */
172780 ){
172781  int rc = SQLITE_OK;
172782  int i;
172783  SessionBuffer buf = {0, 0, 0};
172784 
172785  sessionAppendStr(&buf, "INSERT INTO main.", &rc);
172786  sessionAppendIdent(&buf, zTab, &rc);
172787  sessionAppendStr(&buf, " VALUES(?", &rc);
172788  for(i=1; i<p->nCol; i++){
172789  sessionAppendStr(&buf, ", ?", &rc);
172790  }
172791  sessionAppendStr(&buf, ")", &rc);
172792 
172793  if( rc==SQLITE_OK ){
172794  rc = sqlite3_prepare_v2(db, (char *)buf.aBuf, buf.nBuf, &p->pInsert, 0);
172795  }
172796  sqlite3_free(buf.aBuf);
172797  return rc;
172798 }
172799 
172800 /*
172801 ** A wrapper around sqlite3_bind_value() that detects an extra problem.
172802 ** See comments in the body of this function for details.
172803 */
172804 static int sessionBindValue(
172805  sqlite3_stmt *pStmt, /* Statement to bind value to */
172806  int i, /* Parameter number to bind to */
172807  sqlite3_value *pVal /* Value to bind */
172808 ){
172809  int eType = sqlite3_value_type(pVal);
172810  /* COVERAGE: The (pVal->z==0) branch is never true using current versions
172811  ** of SQLite. If a malloc fails in an sqlite3_value_xxx() function, either
172812  ** the (pVal->z) variable remains as it was or the type of the value is
172813  ** set to SQLITE_NULL. */
172814  if( (eType==SQLITE_TEXT || eType==SQLITE_BLOB) && pVal->z==0 ){
172815  /* This condition occurs when an earlier OOM in a call to
172816  ** sqlite3_value_text() or sqlite3_value_blob() (perhaps from within
172817  ** a conflict-handler) has zeroed the pVal->z pointer. Return NOMEM. */
172818  return SQLITE_NOMEM;
172819  }
172820  return sqlite3_bind_value(pStmt, i, pVal);
172821 }
172822 
172823 /*
172824 ** Iterator pIter must point to an SQLITE_INSERT entry. This function
172825 ** transfers new.* values from the current iterator entry to statement
172826 ** pStmt. The table being inserted into has nCol columns.
172827 **
172828 ** New.* value $i from the iterator is bound to variable ($i+1) of
172829 ** statement pStmt. If parameter abPK is NULL, all values from 0 to (nCol-1)
172830 ** are transfered to the statement. Otherwise, if abPK is not NULL, it points
172831 ** to an array nCol elements in size. In this case only those values for
172832 ** which abPK[$i] is true are read from the iterator and bound to the
172833 ** statement.
172834 **
172835 ** An SQLite error code is returned if an error occurs. Otherwise, SQLITE_OK.
172836 */
172837 static int sessionBindRow(
172838  sqlite3_changeset_iter *pIter, /* Iterator to read values from */
172839  int(*xValue)(sqlite3_changeset_iter *, int, sqlite3_value **),
172840  int nCol, /* Number of columns */
172841  u8 *abPK, /* If not NULL, bind only if true */
172842  sqlite3_stmt *pStmt /* Bind values to this statement */
172843 ){
172844  int i;
172845  int rc = SQLITE_OK;
172846 
172847  /* Neither sqlite3changeset_old or sqlite3changeset_new can fail if the
172848  ** argument iterator points to a suitable entry. Make sure that xValue
172849  ** is one of these to guarantee that it is safe to ignore the return
172850  ** in the code below. */
172851  assert( xValue==sqlite3changeset_old || xValue==sqlite3changeset_new );
172852 
172853  for(i=0; rc==SQLITE_OK && i<nCol; i++){
172854  if( !abPK || abPK[i] ){
172855  sqlite3_value *pVal;
172856  (void)xValue(pIter, i, &pVal);
172857  rc = sessionBindValue(pStmt, i+1, pVal);
172858  }
172859  }
172860  return rc;
172861 }
172862 
172863 /*
172864 ** SQL statement pSelect is as generated by the sessionSelectRow() function.
172865 ** This function binds the primary key values from the change that changeset
172866 ** iterator pIter points to to the SELECT and attempts to seek to the table
172867 ** entry. If a row is found, the SELECT statement left pointing at the row
172868 ** and SQLITE_ROW is returned. Otherwise, if no row is found and no error
172869 ** has occured, the statement is reset and SQLITE_OK is returned. If an
172870 ** error occurs, the statement is reset and an SQLite error code is returned.
172871 **
172872 ** If this function returns SQLITE_ROW, the caller must eventually reset()
172873 ** statement pSelect. If any other value is returned, the statement does
172874 ** not require a reset().
172875 **
172876 ** If the iterator currently points to an INSERT record, bind values from the
172877 ** new.* record to the SELECT statement. Or, if it points to a DELETE or
172878 ** UPDATE, bind values from the old.* record.
172879 */
172880 static int sessionSeekToRow(
172881  sqlite3 *db, /* Database handle */
172882  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172883  u8 *abPK, /* Primary key flags array */
172884  sqlite3_stmt *pSelect /* SELECT statement from sessionSelectRow() */
172885 ){
172886  int rc; /* Return code */
172887  int nCol; /* Number of columns in table */
172888  int op; /* Changset operation (SQLITE_UPDATE etc.) */
172889  const char *zDummy; /* Unused */
172890 
172891  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
172892  rc = sessionBindRow(pIter,
172893  op==SQLITE_INSERT ? sqlite3changeset_new : sqlite3changeset_old,
172894  nCol, abPK, pSelect
172895  );
172896 
172897  if( rc==SQLITE_OK ){
172898  rc = sqlite3_step(pSelect);
172899  if( rc!=SQLITE_ROW ) rc = sqlite3_reset(pSelect);
172900  }
172901 
172902  return rc;
172903 }
172904 
172905 /*
172906 ** Invoke the conflict handler for the change that the changeset iterator
172907 ** currently points to.
172908 **
172909 ** Argument eType must be either CHANGESET_DATA or CHANGESET_CONFLICT.
172910 ** If argument pbReplace is NULL, then the type of conflict handler invoked
172911 ** depends solely on eType, as follows:
172912 **
172913 ** eType value Value passed to xConflict
172914 ** -------------------------------------------------
172915 ** CHANGESET_DATA CHANGESET_NOTFOUND
172916 ** CHANGESET_CONFLICT CHANGESET_CONSTRAINT
172917 **
172918 ** Or, if pbReplace is not NULL, then an attempt is made to find an existing
172919 ** record with the same primary key as the record about to be deleted, updated
172920 ** or inserted. If such a record can be found, it is available to the conflict
172921 ** handler as the "conflicting" record. In this case the type of conflict
172922 ** handler invoked is as follows:
172923 **
172924 ** eType value PK Record found? Value passed to xConflict
172925 ** ----------------------------------------------------------------
172926 ** CHANGESET_DATA Yes CHANGESET_DATA
172927 ** CHANGESET_DATA No CHANGESET_NOTFOUND
172928 ** CHANGESET_CONFLICT Yes CHANGESET_CONFLICT
172929 ** CHANGESET_CONFLICT No CHANGESET_CONSTRAINT
172930 **
172931 ** If pbReplace is not NULL, and a record with a matching PK is found, and
172932 ** the conflict handler function returns SQLITE_CHANGESET_REPLACE, *pbReplace
172933 ** is set to non-zero before returning SQLITE_OK.
172934 **
172935 ** If the conflict handler returns SQLITE_CHANGESET_ABORT, SQLITE_ABORT is
172936 ** returned. Or, if the conflict handler returns an invalid value,
172937 ** SQLITE_MISUSE. If the conflict handler returns SQLITE_CHANGESET_OMIT,
172938 ** this function returns SQLITE_OK.
172939 */
172940 static int sessionConflictHandler(
172941  int eType, /* Either CHANGESET_DATA or CONFLICT */
172942  SessionApplyCtx *p, /* changeset_apply() context */
172943  sqlite3_changeset_iter *pIter, /* Changeset iterator */
172944  int(*xConflict)(void *, int, sqlite3_changeset_iter*),
172945  void *pCtx, /* First argument for conflict handler */
172946  int *pbReplace /* OUT: Set to true if PK row is found */
172947 ){
172948  int res = 0; /* Value returned by conflict handler */
172949  int rc;
172950  int nCol;
172951  int op;
172952  const char *zDummy;
172953 
172954  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
172955 
172956  assert( eType==SQLITE_CHANGESET_CONFLICT || eType==SQLITE_CHANGESET_DATA );
172957  assert( SQLITE_CHANGESET_CONFLICT+1==SQLITE_CHANGESET_CONSTRAINT );
172958  assert( SQLITE_CHANGESET_DATA+1==SQLITE_CHANGESET_NOTFOUND );
172959 
172960  /* Bind the new.* PRIMARY KEY values to the SELECT statement. */
172961  if( pbReplace ){
172962  rc = sessionSeekToRow(p->db, pIter, p->abPK, p->pSelect);
172963  }else{
172964  rc = SQLITE_OK;
172965  }
172966 
172967  if( rc==SQLITE_ROW ){
172968  /* There exists another row with the new.* primary key. */
172969  pIter->pConflict = p->pSelect;
172970  res = xConflict(pCtx, eType, pIter);
172971  pIter->pConflict = 0;
172972  rc = sqlite3_reset(p->pSelect);
172973  }else if( rc==SQLITE_OK ){
172974  if( p->bDeferConstraints && eType==SQLITE_CHANGESET_CONFLICT ){
172975  /* Instead of invoking the conflict handler, append the change blob
172976  ** to the SessionApplyCtx.constraints buffer. */
172977  u8 *aBlob = &pIter->in.aData[pIter->in.iCurrent];
172978  int nBlob = pIter->in.iNext - pIter->in.iCurrent;
172979  sessionAppendBlob(&p->constraints, aBlob, nBlob, &rc);
172980  res = SQLITE_CHANGESET_OMIT;
172981  }else{
172982  /* No other row with the new.* primary key. */
172983  res = xConflict(pCtx, eType+1, pIter);
172984  if( res==SQLITE_CHANGESET_REPLACE ) rc = SQLITE_MISUSE;
172985  }
172986  }
172987 
172988  if( rc==SQLITE_OK ){
172989  switch( res ){
172990  case SQLITE_CHANGESET_REPLACE:
172991  assert( pbReplace );
172992  *pbReplace = 1;
172993  break;
172994 
172995  case SQLITE_CHANGESET_OMIT:
172996  break;
172997 
172998  case SQLITE_CHANGESET_ABORT:
172999  rc = SQLITE_ABORT;
173000  break;
173001 
173002  default:
173003  rc = SQLITE_MISUSE;
173004  break;
173005  }
173006  }
173007 
173008  return rc;
173009 }
173010 
173011 /*
173012 ** Attempt to apply the change that the iterator passed as the first argument
173013 ** currently points to to the database. If a conflict is encountered, invoke
173014 ** the conflict handler callback.
173015 **
173016 ** If argument pbRetry is NULL, then ignore any CHANGESET_DATA conflict. If
173017 ** one is encountered, update or delete the row with the matching primary key
173018 ** instead. Or, if pbRetry is not NULL and a CHANGESET_DATA conflict occurs,
173019 ** invoke the conflict handler. If it returns CHANGESET_REPLACE, set *pbRetry
173020 ** to true before returning. In this case the caller will invoke this function
173021 ** again, this time with pbRetry set to NULL.
173022 **
173023 ** If argument pbReplace is NULL and a CHANGESET_CONFLICT conflict is
173024 ** encountered invoke the conflict handler with CHANGESET_CONSTRAINT instead.
173025 ** Or, if pbReplace is not NULL, invoke it with CHANGESET_CONFLICT. If such
173026 ** an invocation returns SQLITE_CHANGESET_REPLACE, set *pbReplace to true
173027 ** before retrying. In this case the caller attempts to remove the conflicting
173028 ** row before invoking this function again, this time with pbReplace set
173029 ** to NULL.
173030 **
173031 ** If any conflict handler returns SQLITE_CHANGESET_ABORT, this function
173032 ** returns SQLITE_ABORT. Otherwise, if no error occurs, SQLITE_OK is
173033 ** returned.
173034 */
173035 static int sessionApplyOneOp(
173036  sqlite3_changeset_iter *pIter, /* Changeset iterator */
173037  SessionApplyCtx *p, /* changeset_apply() context */
173038  int(*xConflict)(void *, int, sqlite3_changeset_iter *),
173039  void *pCtx, /* First argument for the conflict handler */
173040  int *pbReplace, /* OUT: True to remove PK row and retry */
173041  int *pbRetry /* OUT: True to retry. */
173042 ){
173043  const char *zDummy;
173044  int op;
173045  int nCol;
173046  int rc = SQLITE_OK;
173047 
173048  assert( p->pDelete && p->pUpdate && p->pInsert && p->pSelect );
173049  assert( p->azCol && p->abPK );
173050  assert( !pbReplace || *pbReplace==0 );
173051 
173052  sqlite3changeset_op(pIter, &zDummy, &nCol, &op, 0);
173053 
173054  if( op==SQLITE_DELETE ){
173055 
173056  /* Bind values to the DELETE statement. If conflict handling is required,
173057  ** bind values for all columns and set bound variable (nCol+1) to true.
173058  ** Or, if conflict handling is not required, bind just the PK column
173059  ** values and, if it exists, set (nCol+1) to false. Conflict handling
173060  ** is not required if:
173061  **
173062  ** * this is a patchset, or
173063  ** * (pbRetry==0), or
173064  ** * all columns of the table are PK columns (in this case there is
173065  ** no (nCol+1) variable to bind to).
173066  */
173067  u8 *abPK = (pIter->bPatchset ? p->abPK : 0);
173068  rc = sessionBindRow(pIter, sqlite3changeset_old, nCol, abPK, p->pDelete);
173069  if( rc==SQLITE_OK && sqlite3_bind_parameter_count(p->pDelete)>nCol ){
173070  rc = sqlite3_bind_int(p->pDelete, nCol+1, (pbRetry==0 || abPK));
173071  }
173072  if( rc!=SQLITE_OK ) return rc;
173073 
173074  sqlite3_step(p->pDelete);
173075  rc = sqlite3_reset(p->pDelete);
173076  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173077  rc = sessionConflictHandler(
173078  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173079  );
173080  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173081  rc = sessionConflictHandler(
173082  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173083  );
173084  }
173085 
173086  }else if( op==SQLITE_UPDATE ){
173087  int i;
173088 
173089  /* Bind values to the UPDATE statement. */
173090  for(i=0; rc==SQLITE_OK && i<nCol; i++){
173091  sqlite3_value *pOld = sessionChangesetOld(pIter, i);
173092  sqlite3_value *pNew = sessionChangesetNew(pIter, i);
173093 
173094  sqlite3_bind_int(p->pUpdate, i*3+2, !!pNew);
173095  if( pOld ){
173096  rc = sessionBindValue(p->pUpdate, i*3+1, pOld);
173097  }
173098  if( rc==SQLITE_OK && pNew ){
173099  rc = sessionBindValue(p->pUpdate, i*3+3, pNew);
173100  }
173101  }
173102  if( rc==SQLITE_OK ){
173103  sqlite3_bind_int(p->pUpdate, nCol*3+1, pbRetry==0 || pIter->bPatchset);
173104  }
173105  if( rc!=SQLITE_OK ) return rc;
173106 
173107  /* Attempt the UPDATE. In the case of a NOTFOUND or DATA conflict,
173108  ** the result will be SQLITE_OK with 0 rows modified. */
173109  sqlite3_step(p->pUpdate);
173110  rc = sqlite3_reset(p->pUpdate);
173111 
173112  if( rc==SQLITE_OK && sqlite3_changes(p->db)==0 ){
173113  /* A NOTFOUND or DATA error. Search the table to see if it contains
173114  ** a row with a matching primary key. If so, this is a DATA conflict.
173115  ** Otherwise, if there is no primary key match, it is a NOTFOUND. */
173116 
173117  rc = sessionConflictHandler(
173118  SQLITE_CHANGESET_DATA, p, pIter, xConflict, pCtx, pbRetry
173119  );
173120 
173121  }else if( (rc&0xff)==SQLITE_CONSTRAINT ){
173122  /* This is always a CONSTRAINT conflict. */
173123  rc = sessionConflictHandler(
173124  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, 0
173125  );
173126  }
173127 
173128  }else{
173129  assert( op==SQLITE_INSERT );
173130  rc = sessionBindRow(pIter, sqlite3changeset_new, nCol, 0, p->pInsert);
173131  if( rc!=SQLITE_OK ) return rc;
173132 
173133  sqlite3_step(p->pInsert);
173134  rc = sqlite3_reset(p->pInsert);
173135  if( (rc&0xff)==SQLITE_CONSTRAINT ){
173136  rc = sessionConflictHandler(
173137  SQLITE_CHANGESET_CONFLICT, p, pIter, xConflict, pCtx, pbReplace
173138  );
173139  }
173140  }
173141 
173142  return rc;
173143 }
173144 
173145 /*
173146 ** Attempt to apply the change that the iterator passed as the first argument
173147 ** currently points to to the database. If a conflict is encountered, invoke
173148 ** the conflict handler callback.
173149 **
173150 ** The difference between this function and sessionApplyOne() is that this
173151 ** function handles the case where the conflict-handler is invoked and
173152 ** returns SQLITE_CHANGESET_REPLACE - indicating that the change should be
173153 ** retried in some manner.
173154 */
173155 static int sessionApplyOneWithRetry(
173156  sqlite3 *db, /* Apply change to "main" db of this handle */
173157  sqlite3_changeset_iter *pIter, /* Changeset iterator to read change from */
173158  SessionApplyCtx *pApply, /* Apply context */
173159  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173160  void *pCtx /* First argument passed to xConflict */
173161 ){
173162  int bReplace = 0;
173163  int bRetry = 0;
173164  int rc;
173165 
173166  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, &bReplace, &bRetry);
173167  assert( rc==SQLITE_OK || (bRetry==0 && bReplace==0) );
173168 
173169  /* If the bRetry flag is set, the change has not been applied due to an
173170  ** SQLITE_CHANGESET_DATA problem (i.e. this is an UPDATE or DELETE and
173171  ** a row with the correct PK is present in the db, but one or more other
173172  ** fields do not contain the expected values) and the conflict handler
173173  ** returned SQLITE_CHANGESET_REPLACE. In this case retry the operation,
173174  ** but pass NULL as the final argument so that sessionApplyOneOp() ignores
173175  ** the SQLITE_CHANGESET_DATA problem. */
173176  if( bRetry ){
173177  assert( pIter->op==SQLITE_UPDATE || pIter->op==SQLITE_DELETE );
173178  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173179  }
173180 
173181  /* If the bReplace flag is set, the change is an INSERT that has not
173182  ** been performed because the database already contains a row with the
173183  ** specified primary key and the conflict handler returned
173184  ** SQLITE_CHANGESET_REPLACE. In this case remove the conflicting row
173185  ** before reattempting the INSERT. */
173186  else if( bReplace ){
173187  assert( pIter->op==SQLITE_INSERT );
173188  rc = sqlite3_exec(db, "SAVEPOINT replace_op", 0, 0, 0);
173189  if( rc==SQLITE_OK ){
173190  rc = sessionBindRow(pIter,
173191  sqlite3changeset_new, pApply->nCol, pApply->abPK, pApply->pDelete);
173192  sqlite3_bind_int(pApply->pDelete, pApply->nCol+1, 1);
173193  }
173194  if( rc==SQLITE_OK ){
173195  sqlite3_step(pApply->pDelete);
173196  rc = sqlite3_reset(pApply->pDelete);
173197  }
173198  if( rc==SQLITE_OK ){
173199  rc = sessionApplyOneOp(pIter, pApply, xConflict, pCtx, 0, 0);
173200  }
173201  if( rc==SQLITE_OK ){
173202  rc = sqlite3_exec(db, "RELEASE replace_op", 0, 0, 0);
173203  }
173204  }
173205 
173206  return rc;
173207 }
173208 
173209 /*
173210 ** Retry the changes accumulated in the pApply->constraints buffer.
173211 */
173212 static int sessionRetryConstraints(
173213  sqlite3 *db,
173214  int bPatchset,
173215  const char *zTab,
173216  SessionApplyCtx *pApply,
173217  int(*xConflict)(void*, int, sqlite3_changeset_iter*),
173218  void *pCtx /* First argument passed to xConflict */
173219 ){
173220  int rc = SQLITE_OK;
173221 
173222  while( pApply->constraints.nBuf ){
173223  sqlite3_changeset_iter *pIter2 = 0;
173224  SessionBuffer cons = pApply->constraints;
173225  memset(&pApply->constraints, 0, sizeof(SessionBuffer));
173226 
173227  rc = sessionChangesetStart(&pIter2, 0, 0, cons.nBuf, cons.aBuf);
173228  if( rc==SQLITE_OK ){
173229  int nByte = 2*pApply->nCol*sizeof(sqlite3_value*);
173230  int rc2;
173231  pIter2->bPatchset = bPatchset;
173232  pIter2->zTab = (char*)zTab;
173233  pIter2->nCol = pApply->nCol;
173234  pIter2->abPK = pApply->abPK;
173235  sessionBufferGrow(&pIter2->tblhdr, nByte, &rc);
173236  pIter2->apValue = (sqlite3_value**)pIter2->tblhdr.aBuf;
173237  if( rc==SQLITE_OK ) memset(pIter2->apValue, 0, nByte);
173238 
173239  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter2) ){
173240  rc = sessionApplyOneWithRetry(db, pIter2, pApply, xConflict, pCtx);
173241  }
173242 
173243  rc2 = sqlite3changeset_finalize(pIter2);
173244  if( rc==SQLITE_OK ) rc = rc2;
173245  }
173246  assert( pApply->bDeferConstraints || pApply->constraints.nBuf==0 );
173247 
173248  sqlite3_free(cons.aBuf);
173249  if( rc!=SQLITE_OK ) break;
173250  if( pApply->constraints.nBuf>=cons.nBuf ){
173251  /* No progress was made on the last round. */
173252  pApply->bDeferConstraints = 0;
173253  }
173254  }
173255 
173256  return rc;
173257 }
173258 
173259 /*
173260 ** Argument pIter is a changeset iterator that has been initialized, but
173261 ** not yet passed to sqlite3changeset_next(). This function applies the
173262 ** changeset to the main database attached to handle "db". The supplied
173263 ** conflict handler callback is invoked to resolve any conflicts encountered
173264 ** while applying the change.
173265 */
173266 static int sessionChangesetApply(
173267  sqlite3 *db, /* Apply change to "main" db of this handle */
173268  sqlite3_changeset_iter *pIter, /* Changeset to apply */
173269  int(*xFilter)(
173270  void *pCtx, /* Copy of sixth arg to _apply() */
173271  const char *zTab /* Table name */
173272  ),
173273  int(*xConflict)(
173274  void *pCtx, /* Copy of fifth arg to _apply() */
173275  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173276  sqlite3_changeset_iter *p /* Handle describing change and conflict */
173277  ),
173278  void *pCtx /* First argument passed to xConflict */
173279 ){
173280  int schemaMismatch = 0;
173281  int rc; /* Return code */
173282  const char *zTab = 0; /* Name of current table */
173283  int nTab = 0; /* Result of sqlite3Strlen30(zTab) */
173284  SessionApplyCtx sApply; /* changeset_apply() context object */
173285  int bPatchset;
173286 
173287  assert( xConflict!=0 );
173288 
173289  pIter->in.bNoDiscard = 1;
173290  memset(&sApply, 0, sizeof(sApply));
173292  rc = sqlite3_exec(db, "SAVEPOINT changeset_apply", 0, 0, 0);
173293  if( rc==SQLITE_OK ){
173294  rc = sqlite3_exec(db, "PRAGMA defer_foreign_keys = 1", 0, 0, 0);
173295  }
173296  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3changeset_next(pIter) ){
173297  int nCol;
173298  int op;
173299  const char *zNew;
173300 
173301  sqlite3changeset_op(pIter, &zNew, &nCol, &op, 0);
173302 
173303  if( zTab==0 || sqlite3_strnicmp(zNew, zTab, nTab+1) ){
173304  u8 *abPK;
173305 
173306  rc = sessionRetryConstraints(
173307  db, pIter->bPatchset, zTab, &sApply, xConflict, pCtx
173308  );
173309  if( rc!=SQLITE_OK ) break;
173310 
173311  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173312  sqlite3_finalize(sApply.pDelete);
173313  sqlite3_finalize(sApply.pUpdate);
173314  sqlite3_finalize(sApply.pInsert);
173315  sqlite3_finalize(sApply.pSelect);
173316  memset(&sApply, 0, sizeof(sApply));
173317  sApply.db = db;
173318  sApply.bDeferConstraints = 1;
173319 
173320  /* If an xFilter() callback was specified, invoke it now. If the
173321  ** xFilter callback returns zero, skip this table. If it returns
173322  ** non-zero, proceed. */
173323  schemaMismatch = (xFilter && (0==xFilter(pCtx, zNew)));
173324  if( schemaMismatch ){
173325  zTab = sqlite3_mprintf("%s", zNew);
173326  if( zTab==0 ){
173327  rc = SQLITE_NOMEM;
173328  break;
173329  }
173330  nTab = (int)strlen(zTab);
173331  sApply.azCol = (const char **)zTab;
173332  }else{
173333  sqlite3changeset_pk(pIter, &abPK, 0);
173334  rc = sessionTableInfo(
173335  db, "main", zNew, &sApply.nCol, &zTab, &sApply.azCol, &sApply.abPK
173336  );
173337  if( rc!=SQLITE_OK ) break;
173338 
173339  if( sApply.nCol==0 ){
173340  schemaMismatch = 1;
173342  "sqlite3changeset_apply(): no such table: %s", zTab
173343  );
173344  }
173345  else if( sApply.nCol!=nCol ){
173346  schemaMismatch = 1;
173348  "sqlite3changeset_apply(): table %s has %d columns, expected %d",
173349  zTab, sApply.nCol, nCol
173350  );
173351  }
173352  else if( memcmp(sApply.abPK, abPK, nCol)!=0 ){
173353  schemaMismatch = 1;
173354  sqlite3_log(SQLITE_SCHEMA, "sqlite3changeset_apply(): "
173355  "primary key mismatch for table %s", zTab
173356  );
173357  }
173358  else if(
173359  (rc = sessionSelectRow(db, zTab, &sApply))
173360  || (rc = sessionUpdateRow(db, zTab, &sApply))
173361  || (rc = sessionDeleteRow(db, zTab, &sApply))
173362  || (rc = sessionInsertRow(db, zTab, &sApply))
173363  ){
173364  break;
173365  }
173366  nTab = sqlite3Strlen30(zTab);
173367  }
173368  }
173369 
173370  /* If there is a schema mismatch on the current table, proceed to the
173371  ** next change. A log message has already been issued. */
173372  if( schemaMismatch ) continue;
173373 
173374  rc = sessionApplyOneWithRetry(db, pIter, &sApply, xConflict, pCtx);
173375  }
173376 
173377  bPatchset = pIter->bPatchset;
173378  if( rc==SQLITE_OK ){
173379  rc = sqlite3changeset_finalize(pIter);
173380  }else{
173381  sqlite3changeset_finalize(pIter);
173382  }
173383 
173384  if( rc==SQLITE_OK ){
173385  rc = sessionRetryConstraints(db, bPatchset, zTab, &sApply, xConflict, pCtx);
173386  }
173387 
173388  if( rc==SQLITE_OK ){
173389  int nFk, notUsed;
173390  sqlite3_db_status(db, SQLITE_DBSTATUS_DEFERRED_FKS, &nFk, &notUsed, 0);
173391  if( nFk!=0 ){
173392  int res = SQLITE_CHANGESET_ABORT;
173393  sqlite3_changeset_iter sIter;
173394  memset(&sIter, 0, sizeof(sIter));
173395  sIter.nCol = nFk;
173396  res = xConflict(pCtx, SQLITE_CHANGESET_FOREIGN_KEY, &sIter);
173397  if( res!=SQLITE_CHANGESET_OMIT ){
173398  rc = SQLITE_CONSTRAINT;
173399  }
173400  }
173401  }
173402  sqlite3_exec(db, "PRAGMA defer_foreign_keys = 0", 0, 0, 0);
173403 
173404  if( rc==SQLITE_OK ){
173405  rc = sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173406  }else{
173407  sqlite3_exec(db, "ROLLBACK TO changeset_apply", 0, 0, 0);
173408  sqlite3_exec(db, "RELEASE changeset_apply", 0, 0, 0);
173409  }
173410 
173411  sqlite3_finalize(sApply.pInsert);
173412  sqlite3_finalize(sApply.pDelete);
173413  sqlite3_finalize(sApply.pUpdate);
173414  sqlite3_finalize(sApply.pSelect);
173415  sqlite3_free((char*)sApply.azCol); /* cast works around VC++ bug */
173416  sqlite3_free((char*)sApply.constraints.aBuf);
173418  return rc;
173419 }
173420 
173421 /*
173422 ** Apply the changeset passed via pChangeset/nChangeset to the main database
173423 ** attached to handle "db". Invoke the supplied conflict handler callback
173424 ** to resolve any conflicts encountered while applying the change.
173425 */
173426 SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply(
173427  sqlite3 *db, /* Apply change to "main" db of this handle */
173428  int nChangeset, /* Size of changeset in bytes */
173429  void *pChangeset, /* Changeset blob */
173430  int(*xFilter)(
173431  void *pCtx, /* Copy of sixth arg to _apply() */
173432  const char *zTab /* Table name */
173433  ),
173434  int(*xConflict)(
173435  void *pCtx, /* Copy of fifth arg to _apply() */
173436  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173437  sqlite3_changeset_iter *p /* Handle describing change and conflict */
173438  ),
173439  void *pCtx /* First argument passed to xConflict */
173440 ){
173441  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173442  int rc = sqlite3changeset_start(&pIter, nChangeset, pChangeset);
173443  if( rc==SQLITE_OK ){
173444  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173445  }
173446  return rc;
173447 }
173448 
173449 /*
173450 ** Apply the changeset passed via xInput/pIn to the main database
173451 ** attached to handle "db". Invoke the supplied conflict handler callback
173452 ** to resolve any conflicts encountered while applying the change.
173453 */
173454 SQLITE_API int SQLITE_STDCALL sqlite3changeset_apply_strm(
173455  sqlite3 *db, /* Apply change to "main" db of this handle */
173456  int (*xInput)(void *pIn, void *pData, int *pnData), /* Input function */
173457  void *pIn, /* First arg for xInput */
173458  int(*xFilter)(
173459  void *pCtx, /* Copy of sixth arg to _apply() */
173460  const char *zTab /* Table name */
173461  ),
173462  int(*xConflict)(
173463  void *pCtx, /* Copy of sixth arg to _apply() */
173464  int eConflict, /* DATA, MISSING, CONFLICT, CONSTRAINT */
173465  sqlite3_changeset_iter *p /* Handle describing change and conflict */
173466  ),
173467  void *pCtx /* First argument passed to xConflict */
173468 ){
173469  sqlite3_changeset_iter *pIter; /* Iterator to skip through changeset */
173470  int rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173471  if( rc==SQLITE_OK ){
173472  rc = sessionChangesetApply(db, pIter, xFilter, xConflict, pCtx);
173473  }
173474  return rc;
173475 }
173476 
173477 /*
173478 ** sqlite3_changegroup handle.
173479 */
173480 struct sqlite3_changegroup {
173481  int rc; /* Error code */
173482  int bPatch; /* True to accumulate patchsets */
173483  SessionTable *pList; /* List of tables in current patch */
173484 };
173485 
173486 /*
173487 ** This function is called to merge two changes to the same row together as
173488 ** part of an sqlite3changeset_concat() operation. A new change object is
173489 ** allocated and a pointer to it stored in *ppNew.
173490 */
173491 static int sessionChangeMerge(
173492  SessionTable *pTab, /* Table structure */
173493  int bPatchset, /* True for patchsets */
173494  SessionChange *pExist, /* Existing change */
173495  int op2, /* Second change operation */
173496  int bIndirect, /* True if second change is indirect */
173497  u8 *aRec, /* Second change record */
173498  int nRec, /* Number of bytes in aRec */
173499  SessionChange **ppNew /* OUT: Merged change */
173500 ){
173501  SessionChange *pNew = 0;
173502 
173503  if( !pExist ){
173504  pNew = (SessionChange *)sqlite3_malloc(sizeof(SessionChange) + nRec);
173505  if( !pNew ){
173506  return SQLITE_NOMEM;
173507  }
173508  memset(pNew, 0, sizeof(SessionChange));
173509  pNew->op = op2;
173510  pNew->bIndirect = bIndirect;
173511  pNew->nRecord = nRec;
173512  pNew->aRecord = (u8*)&pNew[1];
173513  memcpy(pNew->aRecord, aRec, nRec);
173514  }else{
173515  int op1 = pExist->op;
173516 
173517  /*
173518  ** op1=INSERT, op2=INSERT -> Unsupported. Discard op2.
173519  ** op1=INSERT, op2=UPDATE -> INSERT.
173520  ** op1=INSERT, op2=DELETE -> (none)
173521  **
173522  ** op1=UPDATE, op2=INSERT -> Unsupported. Discard op2.
173523  ** op1=UPDATE, op2=UPDATE -> UPDATE.
173524  ** op1=UPDATE, op2=DELETE -> DELETE.
173525  **
173526  ** op1=DELETE, op2=INSERT -> UPDATE.
173527  ** op1=DELETE, op2=UPDATE -> Unsupported. Discard op2.
173528  ** op1=DELETE, op2=DELETE -> Unsupported. Discard op2.
173529  */
173530  if( (op1==SQLITE_INSERT && op2==SQLITE_INSERT)
173531  || (op1==SQLITE_UPDATE && op2==SQLITE_INSERT)
173532  || (op1==SQLITE_DELETE && op2==SQLITE_UPDATE)
173533  || (op1==SQLITE_DELETE && op2==SQLITE_DELETE)
173534  ){
173535  pNew = pExist;
173536  }else if( op1==SQLITE_INSERT && op2==SQLITE_DELETE ){
173537  sqlite3_free(pExist);
173538  assert( pNew==0 );
173539  }else{
173540  u8 *aExist = pExist->aRecord;
173541  int nByte;
173542  u8 *aCsr;
173543 
173544  /* Allocate a new SessionChange object. Ensure that the aRecord[]
173545  ** buffer of the new object is large enough to hold any record that
173546  ** may be generated by combining the input records. */
173547  nByte = sizeof(SessionChange) + pExist->nRecord + nRec;
173548  pNew = (SessionChange *)sqlite3_malloc(nByte);
173549  if( !pNew ){
173550  sqlite3_free(pExist);
173551  return SQLITE_NOMEM;
173552  }
173553  memset(pNew, 0, sizeof(SessionChange));
173554  pNew->bIndirect = (bIndirect && pExist->bIndirect);
173555  aCsr = pNew->aRecord = (u8 *)&pNew[1];
173556 
173557  if( op1==SQLITE_INSERT ){ /* INSERT + UPDATE */
173558  u8 *a1 = aRec;
173559  assert( op2==SQLITE_UPDATE );
173560  pNew->op = SQLITE_INSERT;
173561  if( bPatchset==0 ) sessionSkipRecord(&a1, pTab->nCol);
173562  sessionMergeRecord(&aCsr, pTab->nCol, aExist, a1);
173563  }else if( op1==SQLITE_DELETE ){ /* DELETE + INSERT */
173564  assert( op2==SQLITE_INSERT );
173565  pNew->op = SQLITE_UPDATE;
173566  if( bPatchset ){
173567  memcpy(aCsr, aRec, nRec);
173568  aCsr += nRec;
173569  }else{
173570  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aExist, 0,aRec,0) ){
173571  sqlite3_free(pNew);
173572  pNew = 0;
173573  }
173574  }
173575  }else if( op2==SQLITE_UPDATE ){ /* UPDATE + UPDATE */
173576  u8 *a1 = aExist;
173577  u8 *a2 = aRec;
173578  assert( op1==SQLITE_UPDATE );
173579  if( bPatchset==0 ){
173580  sessionSkipRecord(&a1, pTab->nCol);
173581  sessionSkipRecord(&a2, pTab->nCol);
173582  }
173583  pNew->op = SQLITE_UPDATE;
173584  if( 0==sessionMergeUpdate(&aCsr, pTab, bPatchset, aRec, aExist,a1,a2) ){
173585  sqlite3_free(pNew);
173586  pNew = 0;
173587  }
173588  }else{ /* UPDATE + DELETE */
173589  assert( op1==SQLITE_UPDATE && op2==SQLITE_DELETE );
173590  pNew->op = SQLITE_DELETE;
173591  if( bPatchset ){
173592  memcpy(aCsr, aRec, nRec);
173593  aCsr += nRec;
173594  }else{
173595  sessionMergeRecord(&aCsr, pTab->nCol, aRec, aExist);
173596  }
173597  }
173598 
173599  if( pNew ){
173600  pNew->nRecord = (int)(aCsr - pNew->aRecord);
173601  }
173602  sqlite3_free(pExist);
173603  }
173604  }
173605 
173606  *ppNew = pNew;
173607  return SQLITE_OK;
173608 }
173609 
173610 /*
173611 ** Add all changes in the changeset traversed by the iterator passed as
173612 ** the first argument to the changegroup hash tables.
173613 */
173614 static int sessionChangesetToHash(
173615  sqlite3_changeset_iter *pIter, /* Iterator to read from */
173616  sqlite3_changegroup *pGrp /* Changegroup object to add changeset to */
173617 ){
173618  u8 *aRec;
173619  int nRec;
173620  int rc = SQLITE_OK;
173621  SessionTable *pTab = 0;
173622 
173623 
173624  while( SQLITE_ROW==sessionChangesetNext(pIter, &aRec, &nRec) ){
173625  const char *zNew;
173626  int nCol;
173627  int op;
173628  int iHash;
173629  int bIndirect;
173630  SessionChange *pChange;
173631  SessionChange *pExist = 0;
173632  SessionChange **pp;
173633 
173634  if( pGrp->pList==0 ){
173635  pGrp->bPatch = pIter->bPatchset;
173636  }else if( pIter->bPatchset!=pGrp->bPatch ){
173637  rc = SQLITE_ERROR;
173638  break;
173639  }
173640 
173641  sqlite3changeset_op(pIter, &zNew, &nCol, &op, &bIndirect);
173642  if( !pTab || sqlite3_stricmp(zNew, pTab->zName) ){
173643  /* Search the list for a matching table */
173644  int nNew = (int)strlen(zNew);
173645  u8 *abPK;
173646 
173647  sqlite3changeset_pk(pIter, &abPK, 0);
173648  for(pTab = pGrp->pList; pTab; pTab=pTab->pNext){
173649  if( 0==sqlite3_strnicmp(pTab->zName, zNew, nNew+1) ) break;
173650  }
173651  if( !pTab ){
173652  SessionTable **ppTab;
173653 
173654  pTab = sqlite3_malloc(sizeof(SessionTable) + nCol + nNew+1);
173655  if( !pTab ){
173656  rc = SQLITE_NOMEM;
173657  break;
173658  }
173659  memset(pTab, 0, sizeof(SessionTable));
173660  pTab->nCol = nCol;
173661  pTab->abPK = (u8*)&pTab[1];
173662  memcpy(pTab->abPK, abPK, nCol);
173663  pTab->zName = (char*)&pTab->abPK[nCol];
173664  memcpy(pTab->zName, zNew, nNew+1);
173665 
173666  /* The new object must be linked on to the end of the list, not
173667  ** simply added to the start of it. This is to ensure that the
173668  ** tables within the output of sqlite3changegroup_output() are in
173669  ** the right order. */
173670  for(ppTab=&pGrp->pList; *ppTab; ppTab=&(*ppTab)->pNext);
173671  *ppTab = pTab;
173672  }else if( pTab->nCol!=nCol || memcmp(pTab->abPK, abPK, nCol) ){
173673  rc = SQLITE_SCHEMA;
173674  break;
173675  }
173676  }
173677 
173678  if( sessionGrowHash(pIter->bPatchset, pTab) ){
173679  rc = SQLITE_NOMEM;
173680  break;
173681  }
173682  iHash = sessionChangeHash(
173683  pTab, (pIter->bPatchset && op==SQLITE_DELETE), aRec, pTab->nChange
173684  );
173685 
173686  /* Search for existing entry. If found, remove it from the hash table.
173687  ** Code below may link it back in.
173688  */
173689  for(pp=&pTab->apChange[iHash]; *pp; pp=&(*pp)->pNext){
173690  int bPkOnly1 = 0;
173691  int bPkOnly2 = 0;
173692  if( pIter->bPatchset ){
173693  bPkOnly1 = (*pp)->op==SQLITE_DELETE;
173694  bPkOnly2 = op==SQLITE_DELETE;
173695  }
173696  if( sessionChangeEqual(pTab, bPkOnly1, (*pp)->aRecord, bPkOnly2, aRec) ){
173697  pExist = *pp;
173698  *pp = (*pp)->pNext;
173699  pTab->nEntry--;
173700  break;
173701  }
173702  }
173703 
173704  rc = sessionChangeMerge(pTab,
173705  pIter->bPatchset, pExist, op, bIndirect, aRec, nRec, &pChange
173706  );
173707  if( rc ) break;
173708  if( pChange ){
173709  pChange->pNext = pTab->apChange[iHash];
173710  pTab->apChange[iHash] = pChange;
173711  pTab->nEntry++;
173712  }
173713  }
173714 
173715  if( rc==SQLITE_OK ) rc = pIter->rc;
173716  return rc;
173717 }
173718 
173719 /*
173720 ** Serialize a changeset (or patchset) based on all changesets (or patchsets)
173721 ** added to the changegroup object passed as the first argument.
173722 **
173723 ** If xOutput is not NULL, then the changeset/patchset is returned to the
173724 ** user via one or more calls to xOutput, as with the other streaming
173725 ** interfaces.
173726 **
173727 ** Or, if xOutput is NULL, then (*ppOut) is populated with a pointer to a
173728 ** buffer containing the output changeset before this function returns. In
173729 ** this case (*pnOut) is set to the size of the output buffer in bytes. It
173730 ** is the responsibility of the caller to free the output buffer using
173731 ** sqlite3_free() when it is no longer required.
173732 **
173733 ** If successful, SQLITE_OK is returned. Or, if an error occurs, an SQLite
173734 ** error code. If an error occurs and xOutput is NULL, (*ppOut) and (*pnOut)
173735 ** are both set to 0 before returning.
173736 */
173737 static int sessionChangegroupOutput(
173738  sqlite3_changegroup *pGrp,
173739  int (*xOutput)(void *pOut, const void *pData, int nData),
173740  void *pOut,
173741  int *pnOut,
173742  void **ppOut
173743 ){
173744  int rc = SQLITE_OK;
173745  SessionBuffer buf = {0, 0, 0};
173746  SessionTable *pTab;
173747  assert( xOutput==0 || (ppOut==0 && pnOut==0) );
173748 
173749  /* Create the serialized output changeset based on the contents of the
173750  ** hash tables attached to the SessionTable objects in list p->pList.
173751  */
173752  for(pTab=pGrp->pList; rc==SQLITE_OK && pTab; pTab=pTab->pNext){
173753  int i;
173754  if( pTab->nEntry==0 ) continue;
173755 
173756  sessionAppendTableHdr(&buf, pGrp->bPatch, pTab, &rc);
173757  for(i=0; i<pTab->nChange; i++){
173758  SessionChange *p;
173759  for(p=pTab->apChange[i]; p; p=p->pNext){
173760  sessionAppendByte(&buf, p->op, &rc);
173761  sessionAppendByte(&buf, p->bIndirect, &rc);
173762  sessionAppendBlob(&buf, p->aRecord, p->nRecord, &rc);
173763  }
173764  }
173765 
173766  if( rc==SQLITE_OK && xOutput && buf.nBuf>=SESSIONS_STRM_CHUNK_SIZE ){
173767  rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173768  buf.nBuf = 0;
173769  }
173770  }
173771 
173772  if( rc==SQLITE_OK ){
173773  if( xOutput ){
173774  if( buf.nBuf>0 ) rc = xOutput(pOut, buf.aBuf, buf.nBuf);
173775  }else{
173776  *ppOut = buf.aBuf;
173777  *pnOut = buf.nBuf;
173778  buf.aBuf = 0;
173779  }
173780  }
173781  sqlite3_free(buf.aBuf);
173782 
173783  return rc;
173784 }
173785 
173786 /*
173787 ** Allocate a new, empty, sqlite3_changegroup.
173788 */
173789 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_new(sqlite3_changegroup **pp){
173790  int rc = SQLITE_OK; /* Return code */
173791  sqlite3_changegroup *p; /* New object */
173792  p = (sqlite3_changegroup*)sqlite3_malloc(sizeof(sqlite3_changegroup));
173793  if( p==0 ){
173794  rc = SQLITE_NOMEM;
173795  }else{
173796  memset(p, 0, sizeof(sqlite3_changegroup));
173797  }
173798  *pp = p;
173799  return rc;
173800 }
173801 
173802 /*
173803 ** Add the changeset currently stored in buffer pData, size nData bytes,
173804 ** to changeset-group p.
173805 */
173806 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add(sqlite3_changegroup *pGrp, int nData, void *pData){
173807  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173808  int rc; /* Return code */
173809 
173810  rc = sqlite3changeset_start(&pIter, nData, pData);
173811  if( rc==SQLITE_OK ){
173812  rc = sessionChangesetToHash(pIter, pGrp);
173813  }
173814  sqlite3changeset_finalize(pIter);
173815  return rc;
173816 }
173817 
173818 /*
173819 ** Obtain a buffer containing a changeset representing the concatenation
173820 ** of all changesets added to the group so far.
173821 */
173822 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output(
173823  sqlite3_changegroup *pGrp,
173824  int *pnData,
173825  void **ppData
173826 ){
173827  return sessionChangegroupOutput(pGrp, 0, 0, pnData, ppData);
173828 }
173829 
173830 /*
173831 ** Streaming versions of changegroup_add().
173832 */
173833 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_add_strm(
173834  sqlite3_changegroup *pGrp,
173835  int (*xInput)(void *pIn, void *pData, int *pnData),
173836  void *pIn
173837 ){
173838  sqlite3_changeset_iter *pIter; /* Iterator opened on pData/nData */
173839  int rc; /* Return code */
173840 
173841  rc = sqlite3changeset_start_strm(&pIter, xInput, pIn);
173842  if( rc==SQLITE_OK ){
173843  rc = sessionChangesetToHash(pIter, pGrp);
173844  }
173845  sqlite3changeset_finalize(pIter);
173846  return rc;
173847 }
173848 
173849 /*
173850 ** Streaming versions of changegroup_output().
173851 */
173852 SQLITE_API int SQLITE_STDCALL sqlite3changegroup_output_strm(
173853  sqlite3_changegroup *pGrp,
173854  int (*xOutput)(void *pOut, const void *pData, int nData),
173855  void *pOut
173856 ){
173857  return sessionChangegroupOutput(pGrp, xOutput, pOut, 0, 0);
173858 }
173859 
173860 /*
173861 ** Delete a changegroup object.
173862 */
173863 SQLITE_API void SQLITE_STDCALL sqlite3changegroup_delete(sqlite3_changegroup *pGrp){
173864  if( pGrp ){
173865  sessionDeleteTable(pGrp->pList);
173866  sqlite3_free(pGrp);
173867  }
173868 }
173869 
173870 /*
173871 ** Combine two changesets together.
173872 */
173873 SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat(
173874  int nLeft, /* Number of bytes in lhs input */
173875  void *pLeft, /* Lhs input changeset */
173876  int nRight /* Number of bytes in rhs input */,
173877  void *pRight, /* Rhs input changeset */
173878  int *pnOut, /* OUT: Number of bytes in output changeset */
173879  void **ppOut /* OUT: changeset (left <concat> right) */
173880 ){
173881  sqlite3_changegroup *pGrp;
173882  int rc;
173883 
173884  rc = sqlite3changegroup_new(&pGrp);
173885  if( rc==SQLITE_OK ){
173886  rc = sqlite3changegroup_add(pGrp, nLeft, pLeft);
173887  }
173888  if( rc==SQLITE_OK ){
173889  rc = sqlite3changegroup_add(pGrp, nRight, pRight);
173890  }
173891  if( rc==SQLITE_OK ){
173892  rc = sqlite3changegroup_output(pGrp, pnOut, ppOut);
173893  }
173894  sqlite3changegroup_delete(pGrp);
173895 
173896  return rc;
173897 }
173898 
173899 /*
173900 ** Streaming version of sqlite3changeset_concat().
173901 */
173902 SQLITE_API int SQLITE_STDCALL sqlite3changeset_concat_strm(
173903  int (*xInputA)(void *pIn, void *pData, int *pnData),
173904  void *pInA,
173905  int (*xInputB)(void *pIn, void *pData, int *pnData),
173906  void *pInB,
173907  int (*xOutput)(void *pOut, const void *pData, int nData),
173908  void *pOut
173909 ){
173910  sqlite3_changegroup *pGrp;
173911  int rc;
173912 
173913  rc = sqlite3changegroup_new(&pGrp);
173914  if( rc==SQLITE_OK ){
173915  rc = sqlite3changegroup_add_strm(pGrp, xInputA, pInA);
173916  }
173917  if( rc==SQLITE_OK ){
173918  rc = sqlite3changegroup_add_strm(pGrp, xInputB, pInB);
173919  }
173920  if( rc==SQLITE_OK ){
173921  rc = sqlite3changegroup_output_strm(pGrp, xOutput, pOut);
173922  }
173923  sqlite3changegroup_delete(pGrp);
173924 
173925  return rc;
173926 }
173927 
173928 #endif /* SQLITE_ENABLE_SESSION && SQLITE_ENABLE_PREUPDATE_HOOK */
173929 
173930 /************** End of sqlite3session.c **************************************/
173931 /************** Begin file json1.c *******************************************/
173932 /*
173933 ** 2015-08-12
173934 **
173935 ** The author disclaims copyright to this source code. In place of
173936 ** a legal notice, here is a blessing:
173937 **
173938 ** May you do good and not evil.
173939 ** May you find forgiveness for yourself and forgive others.
173940 ** May you share freely, never taking more than you give.
173941 **
173942 ******************************************************************************
173943 **
173944 ** This SQLite extension implements JSON functions. The interface is
173945 ** modeled after MySQL JSON functions:
173946 **
173947 ** https://dev.mysql.com/doc/refman/5.7/en/json.html
173948 **
173949 ** For the time being, all JSON is stored as pure text. (We might add
173950 ** a JSONB type in the future which stores a binary encoding of JSON in
173951 ** a BLOB, but there is no support for JSONB in the current implementation.
173952 ** This implementation parses JSON text at 250 MB/s, so it is hard to see
173953 ** how JSONB might improve on that.)
173954 */
173955 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1)
173956 #if !defined(_SQLITEINT_H_)
173957 /* #include "sqlite3ext.h" */
173958 #endif
173960 /* #include <assert.h> */
173961 /* #include <string.h> */
173962 /* #include <stdlib.h> */
173963 /* #include <stdarg.h> */
173964 
173965 /* Mark a function parameter as unused, to suppress nuisance compiler
173966 ** warnings. */
173967 #ifndef UNUSED_PARAM
173968 # define UNUSED_PARAM(X) (void)(X)
173969 #endif
173970 
173971 #ifndef LARGEST_INT64
173972 # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
173973 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
173974 #endif
173975 
173976 /*
173977 ** Versions of isspace(), isalnum() and isdigit() to which it is safe
173978 ** to pass signed char values.
173979 */
173980 #ifdef sqlite3Isdigit
173981  /* Use the SQLite core versions if this routine is part of the
173982  ** SQLite amalgamation */
173983 # define safe_isdigit(x) sqlite3Isdigit(x)
173984 # define safe_isalnum(x) sqlite3Isalnum(x)
173985 #else
173986  /* Use the standard library for separate compilation */
173987 #include <ctype.h> /* amalgamator: keep */
173988 # define safe_isdigit(x) isdigit((unsigned char)(x))
173989 # define safe_isalnum(x) isalnum((unsigned char)(x))
173990 #endif
173991 
173992 /*
173993 ** Growing our own isspace() routine this way is twice as fast as
173994 ** the library isspace() function, resulting in a 7% overall performance
173995 ** increase for the parser. (Ubuntu14.10 gcc 4.8.4 x64 with -Os).
173996 */
173997 static const char jsonIsSpace[] = {
173998  0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0,
173999  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174000  1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174001  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174002  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174003  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174004  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174005  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174006  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174007  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174008  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174009  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174010  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174011  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174012  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174013  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
174014 };
174015 #define safe_isspace(x) (jsonIsSpace[(unsigned char)x])
174016 
174017 #ifndef SQLITE_AMALGAMATION
174018  /* Unsigned integer types. These are already defined in the sqliteInt.h,
174019  ** but the definitions need to be repeated for separate compilation. */
174020  typedef sqlite3_uint64 u64;
174021  typedef unsigned int u32;
174022  typedef unsigned char u8;
174023 #endif
174024 
174025 /* Objects */
174026 typedef struct JsonString JsonString;
174027 typedef struct JsonNode JsonNode;
174028 typedef struct JsonParse JsonParse;
174029 
174030 /* An instance of this object represents a JSON string
174031 ** under construction. Really, this is a generic string accumulator
174032 ** that can be and is used to create strings other than JSON.
174033 */
174034 struct JsonString {
174035  sqlite3_context *pCtx; /* Function context - put error messages here */
174036  char *zBuf; /* Append JSON content here */
174037  u64 nAlloc; /* Bytes of storage available in zBuf[] */
174038  u64 nUsed; /* Bytes of zBuf[] currently used */
174039  u8 bStatic; /* True if zBuf is static space */
174040  u8 bErr; /* True if an error has been encountered */
174041  char zSpace[100]; /* Initial static space */
174042 };
174043 
174044 /* JSON type values
174045 */
174046 #define JSON_NULL 0
174047 #define JSON_TRUE 1
174048 #define JSON_FALSE 2
174049 #define JSON_INT 3
174050 #define JSON_REAL 4
174051 #define JSON_STRING 5
174052 #define JSON_ARRAY 6
174053 #define JSON_OBJECT 7
174054 
174055 /* The "subtype" set for JSON values */
174056 #define JSON_SUBTYPE 74 /* Ascii for "J" */
174057 
174058 /*
174059 ** Names of the various JSON types:
174060 */
174061 static const char * const jsonType[] = {
174062  "null", "true", "false", "integer", "real", "text", "array", "object"
174063 };
174064 
174065 /* Bit values for the JsonNode.jnFlag field
174066 */
174067 #define JNODE_RAW 0x01 /* Content is raw, not JSON encoded */
174068 #define JNODE_ESCAPE 0x02 /* Content is text with \ escapes */
174069 #define JNODE_REMOVE 0x04 /* Do not output */
174070 #define JNODE_REPLACE 0x08 /* Replace with JsonNode.iVal */
174071 #define JNODE_APPEND 0x10 /* More ARRAY/OBJECT entries at u.iAppend */
174072 #define JNODE_LABEL 0x20 /* Is a label of an object */
174073 
174074 
174075 /* A single node of parsed JSON
174076 */
174077 struct JsonNode {
174078  u8 eType; /* One of the JSON_ type values */
174079  u8 jnFlags; /* JNODE flags */
174080  u8 iVal; /* Replacement value when JNODE_REPLACE */
174081  u32 n; /* Bytes of content, or number of sub-nodes */
174082  union {
174083  const char *zJContent; /* Content for INT, REAL, and STRING */
174084  u32 iAppend; /* More terms for ARRAY and OBJECT */
174085  u32 iKey; /* Key for ARRAY objects in json_tree() */
174086  } u;
174087 };
174088 
174089 /* A completely parsed JSON string
174090 */
174091 struct JsonParse {
174092  u32 nNode; /* Number of slots of aNode[] used */
174093  u32 nAlloc; /* Number of slots of aNode[] allocated */
174094  JsonNode *aNode; /* Array of nodes containing the parse */
174095  const char *zJson; /* Original JSON string */
174096  u32 *aUp; /* Index of parent of each node */
174097  u8 oom; /* Set to true if out of memory */
174098  u8 nErr; /* Number of errors seen */
174099 };
174100 
174101 /**************************************************************************
174102 ** Utility routines for dealing with JsonString objects
174103 **************************************************************************/
174104 
174105 /* Set the JsonString object to an empty string
174106 */
174107 static void jsonZero(JsonString *p){
174108  p->zBuf = p->zSpace;
174109  p->nAlloc = sizeof(p->zSpace);
174110  p->nUsed = 0;
174111  p->bStatic = 1;
174112 }
174113 
174114 /* Initialize the JsonString object
174115 */
174116 static void jsonInit(JsonString *p, sqlite3_context *pCtx){
174117  p->pCtx = pCtx;
174118  p->bErr = 0;
174119  jsonZero(p);
174120 }
174121 
174122 
174123 /* Free all allocated memory and reset the JsonString object back to its
174124 ** initial state.
174125 */
174126 static void jsonReset(JsonString *p){
174127  if( !p->bStatic ) sqlite3_free(p->zBuf);
174128  jsonZero(p);
174129 }
174130 
174131 
174132 /* Report an out-of-memory (OOM) condition
174133 */
174134 static void jsonOom(JsonString *p){
174135  p->bErr = 1;
174136  sqlite3_result_error_nomem(p->pCtx);
174137  jsonReset(p);
174138 }
174139 
174140 /* Enlarge pJson->zBuf so that it can hold at least N more bytes.
174141 ** Return zero on success. Return non-zero on an OOM error
174142 */
174143 static int jsonGrow(JsonString *p, u32 N){
174144  u64 nTotal = N<p->nAlloc ? p->nAlloc*2 : p->nAlloc+N+10;
174145  char *zNew;
174146  if( p->bStatic ){
174147  if( p->bErr ) return 1;
174148  zNew = sqlite3_malloc64(nTotal);
174149  if( zNew==0 ){
174150  jsonOom(p);
174151  return SQLITE_NOMEM;
174152  }
174153  memcpy(zNew, p->zBuf, (size_t)p->nUsed);
174154  p->zBuf = zNew;
174155  p->bStatic = 0;
174156  }else{
174157  zNew = sqlite3_realloc64(p->zBuf, nTotal);
174158  if( zNew==0 ){
174159  jsonOom(p);
174160  return SQLITE_NOMEM;
174161  }
174162  p->zBuf = zNew;
174163  }
174164  p->nAlloc = nTotal;
174165  return SQLITE_OK;
174166 }
174167 
174168 /* Append N bytes from zIn onto the end of the JsonString string.
174169 */
174170 static void jsonAppendRaw(JsonString *p, const char *zIn, u32 N){
174171  if( (N+p->nUsed >= p->nAlloc) && jsonGrow(p,N)!=0 ) return;
174172  memcpy(p->zBuf+p->nUsed, zIn, N);
174173  p->nUsed += N;
174174 }
174175 
174176 /* Append formatted text (not to exceed N bytes) to the JsonString.
174177 */
174178 static void jsonPrintf(int N, JsonString *p, const char *zFormat, ...){
174179  va_list ap;
174180  if( (p->nUsed + N >= p->nAlloc) && jsonGrow(p, N) ) return;
174181  va_start(ap, zFormat);
174182  sqlite3_vsnprintf(N, p->zBuf+p->nUsed, zFormat, ap);
174183  va_end(ap);
174184  p->nUsed += (int)strlen(p->zBuf+p->nUsed);
174185 }
174186 
174187 /* Append a single character
174188 */
174189 static void jsonAppendChar(JsonString *p, char c){
174190  if( p->nUsed>=p->nAlloc && jsonGrow(p,1)!=0 ) return;
174191  p->zBuf[p->nUsed++] = c;
174192 }
174193 
174194 /* Append a comma separator to the output buffer, if the previous
174195 ** character is not '[' or '{'.
174196 */
174197 static void jsonAppendSeparator(JsonString *p){
174198  char c;
174199  if( p->nUsed==0 ) return;
174200  c = p->zBuf[p->nUsed-1];
174201  if( c!='[' && c!='{' ) jsonAppendChar(p, ',');
174202 }
174203 
174204 /* Append the N-byte string in zIn to the end of the JsonString string
174205 ** under construction. Enclose the string in "..." and escape
174206 ** any double-quotes or backslash characters contained within the
174207 ** string.
174208 */
174209 static void jsonAppendString(JsonString *p, const char *zIn, u32 N){
174210  u32 i;
174211  if( (N+p->nUsed+2 >= p->nAlloc) && jsonGrow(p,N+2)!=0 ) return;
174212  p->zBuf[p->nUsed++] = '"';
174213  for(i=0; i<N; i++){
174214  unsigned char c = ((unsigned const char*)zIn)[i];
174215  if( c=='"' || c=='\\' ){
174216  json_simple_escape:
174217  if( (p->nUsed+N+3-i > p->nAlloc) && jsonGrow(p,N+3-i)!=0 ) return;
174218  p->zBuf[p->nUsed++] = '\\';
174219  }else if( c<=0x1f ){
174220  static const char aSpecial[] = {
174221  0, 0, 0, 0, 0, 0, 0, 0, 'b', 't', 'n', 0, 'f', 'r', 0, 0,
174222  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
174223  };
174224  assert( sizeof(aSpecial)==32 );
174225  assert( aSpecial['\b']=='b' );
174226  assert( aSpecial['\f']=='f' );
174227  assert( aSpecial['\n']=='n' );
174228  assert( aSpecial['\r']=='r' );
174229  assert( aSpecial['\t']=='t' );
174230  if( aSpecial[c] ){
174231  c = aSpecial[c];
174232  goto json_simple_escape;
174233  }
174234  if( (p->nUsed+N+7+i > p->nAlloc) && jsonGrow(p,N+7-i)!=0 ) return;
174235  p->zBuf[p->nUsed++] = '\\';
174236  p->zBuf[p->nUsed++] = 'u';
174237  p->zBuf[p->nUsed++] = '0';
174238  p->zBuf[p->nUsed++] = '0';
174239  p->zBuf[p->nUsed++] = '0' + (c>>4);
174240  c = "0123456789abcdef"[c&0xf];
174241  }
174242  p->zBuf[p->nUsed++] = c;
174243  }
174244  p->zBuf[p->nUsed++] = '"';
174245  assert( p->nUsed<p->nAlloc );
174246 }
174247 
174248 /*
174249 ** Append a function parameter value to the JSON string under
174250 ** construction.
174251 */
174252 static void jsonAppendValue(
174253  JsonString *p, /* Append to this JSON string */
174254  sqlite3_value *pValue /* Value to append */
174255 ){
174256  switch( sqlite3_value_type(pValue) ){
174257  case SQLITE_NULL: {
174258  jsonAppendRaw(p, "null", 4);
174259  break;
174260  }
174261  case SQLITE_INTEGER:
174262  case SQLITE_FLOAT: {
174263  const char *z = (const char*)sqlite3_value_text(pValue);
174264  u32 n = (u32)sqlite3_value_bytes(pValue);
174265  jsonAppendRaw(p, z, n);
174266  break;
174267  }
174268  case SQLITE_TEXT: {
174269  const char *z = (const char*)sqlite3_value_text(pValue);
174270  u32 n = (u32)sqlite3_value_bytes(pValue);
174271  if( sqlite3_value_subtype(pValue)==JSON_SUBTYPE ){
174272  jsonAppendRaw(p, z, n);
174273  }else{
174274  jsonAppendString(p, z, n);
174275  }
174276  break;
174277  }
174278  default: {
174279  if( p->bErr==0 ){
174280  sqlite3_result_error(p->pCtx, "JSON cannot hold BLOB values", -1);
174281  p->bErr = 2;
174282  jsonReset(p);
174283  }
174284  break;
174285  }
174286  }
174287 }
174288 
174289 
174290 /* Make the JSON in p the result of the SQL function.
174291 */
174292 static void jsonResult(JsonString *p){
174293  if( p->bErr==0 ){
174294  sqlite3_result_text64(p->pCtx, p->zBuf, p->nUsed,
174295  p->bStatic ? SQLITE_TRANSIENT : sqlite3_free,
174296  SQLITE_UTF8);
174297  jsonZero(p);
174298  }
174299  assert( p->bStatic );
174300 }
174301 
174302 /**************************************************************************
174303 ** Utility routines for dealing with JsonNode and JsonParse objects
174304 **************************************************************************/
174305 
174306 /*
174307 ** Return the number of consecutive JsonNode slots need to represent
174308 ** the parsed JSON at pNode. The minimum answer is 1. For ARRAY and
174309 ** OBJECT types, the number might be larger.
174310 **
174311 ** Appended elements are not counted. The value returned is the number
174312 ** by which the JsonNode counter should increment in order to go to the
174313 ** next peer value.
174314 */
174315 static u32 jsonNodeSize(JsonNode *pNode){
174316  return pNode->eType>=JSON_ARRAY ? pNode->n+1 : 1;
174317 }
174318 
174319 /*
174320 ** Reclaim all memory allocated by a JsonParse object. But do not
174321 ** delete the JsonParse object itself.
174322 */
174323 static void jsonParseReset(JsonParse *pParse){
174324  sqlite3_free(pParse->aNode);
174325  pParse->aNode = 0;
174326  pParse->nNode = 0;
174327  pParse->nAlloc = 0;
174328  sqlite3_free(pParse->aUp);
174329  pParse->aUp = 0;
174330 }
174331 
174332 /*
174333 ** Convert the JsonNode pNode into a pure JSON string and
174334 ** append to pOut. Subsubstructure is also included. Return
174335 ** the number of JsonNode objects that are encoded.
174336 */
174337 static void jsonRenderNode(
174338  JsonNode *pNode, /* The node to render */
174339  JsonString *pOut, /* Write JSON here */
174340  sqlite3_value **aReplace /* Replacement values */
174341 ){
174342  switch( pNode->eType ){
174343  default: {
174344  assert( pNode->eType==JSON_NULL );
174345  jsonAppendRaw(pOut, "null", 4);
174346  break;
174347  }
174348  case JSON_TRUE: {
174349  jsonAppendRaw(pOut, "true", 4);
174350  break;
174351  }
174352  case JSON_FALSE: {
174353  jsonAppendRaw(pOut, "false", 5);
174354  break;
174355  }
174356  case JSON_STRING: {
174357  if( pNode->jnFlags & JNODE_RAW ){
174358  jsonAppendString(pOut, pNode->u.zJContent, pNode->n);
174359  break;
174360  }
174361  /* Fall through into the next case */
174362  }
174363  case JSON_REAL:
174364  case JSON_INT: {
174365  jsonAppendRaw(pOut, pNode->u.zJContent, pNode->n);
174366  break;
174367  }
174368  case JSON_ARRAY: {
174369  u32 j = 1;
174370  jsonAppendChar(pOut, '[');
174371  for(;;){
174372  while( j<=pNode->n ){
174373  if( pNode[j].jnFlags & (JNODE_REMOVE|JNODE_REPLACE) ){
174374  if( pNode[j].jnFlags & JNODE_REPLACE ){
174375  jsonAppendSeparator(pOut);
174376  jsonAppendValue(pOut, aReplace[pNode[j].iVal]);
174377  }
174378  }else{
174379  jsonAppendSeparator(pOut);
174380  jsonRenderNode(&pNode[j], pOut, aReplace);
174381  }
174382  j += jsonNodeSize(&pNode[j]);
174383  }
174384  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
174385  pNode = &pNode[pNode->u.iAppend];
174386  j = 1;
174387  }
174388  jsonAppendChar(pOut, ']');
174389  break;
174390  }
174391  case JSON_OBJECT: {
174392  u32 j = 1;
174393  jsonAppendChar(pOut, '{');
174394  for(;;){
174395  while( j<=pNode->n ){
174396  if( (pNode[j+1].jnFlags & JNODE_REMOVE)==0 ){
174397  jsonAppendSeparator(pOut);
174398  jsonRenderNode(&pNode[j], pOut, aReplace);
174399  jsonAppendChar(pOut, ':');
174400  if( pNode[j+1].jnFlags & JNODE_REPLACE ){
174401  jsonAppendValue(pOut, aReplace[pNode[j+1].iVal]);
174402  }else{
174403  jsonRenderNode(&pNode[j+1], pOut, aReplace);
174404  }
174405  }
174406  j += 1 + jsonNodeSize(&pNode[j+1]);
174407  }
174408  if( (pNode->jnFlags & JNODE_APPEND)==0 ) break;
174409  pNode = &pNode[pNode->u.iAppend];
174410  j = 1;
174411  }
174412  jsonAppendChar(pOut, '}');
174413  break;
174414  }
174415  }
174416 }
174417 
174418 /*
174419 ** Return a JsonNode and all its descendents as a JSON string.
174420 */
174421 static void jsonReturnJson(
174422  JsonNode *pNode, /* Node to return */
174423  sqlite3_context *pCtx, /* Return value for this function */
174424  sqlite3_value **aReplace /* Array of replacement values */
174425 ){
174426  JsonString s;
174427  jsonInit(&s, pCtx);
174428  jsonRenderNode(pNode, &s, aReplace);
174429  jsonResult(&s);
174430  sqlite3_result_subtype(pCtx, JSON_SUBTYPE);
174431 }
174432 
174433 /*
174434 ** Make the JsonNode the return value of the function.
174435 */
174436 static void jsonReturn(
174437  JsonNode *pNode, /* Node to return */
174438  sqlite3_context *pCtx, /* Return value for this function */
174439  sqlite3_value **aReplace /* Array of replacement values */
174440 ){
174441  switch( pNode->eType ){
174442  default: {
174443  assert( pNode->eType==JSON_NULL );
174444  sqlite3_result_null(pCtx);
174445  break;
174446  }
174447  case JSON_TRUE: {
174448  sqlite3_result_int(pCtx, 1);
174449  break;
174450  }
174451  case JSON_FALSE: {
174452  sqlite3_result_int(pCtx, 0);
174453  break;
174454  }
174455  case JSON_INT: {
174456  sqlite3_int64 i = 0;
174457  const char *z = pNode->u.zJContent;
174458  if( z[0]=='-' ){ z++; }
174459  while( z[0]>='0' && z[0]<='9' ){
174460  unsigned v = *(z++) - '0';
174461  if( i>=LARGEST_INT64/10 ){
174462  if( i>LARGEST_INT64/10 ) goto int_as_real;
174463  if( z[0]>='0' && z[0]<='9' ) goto int_as_real;
174464  if( v==9 ) goto int_as_real;
174465  if( v==8 ){
174466  if( pNode->u.zJContent[0]=='-' ){
174468  goto int_done;
174469  }else{
174470  goto int_as_real;
174471  }
174472  }
174473  }
174474  i = i*10 + v;
174475  }
174476  if( pNode->u.zJContent[0]=='-' ){ i = -i; }
174477  sqlite3_result_int64(pCtx, i);
174478  int_done:
174479  break;
174480  int_as_real: /* fall through to real */;
174481  }
174482  case JSON_REAL: {
174483  double r;
174484 #ifdef SQLITE_AMALGAMATION
174485  const char *z = pNode->u.zJContent;
174487 #else
174488  r = strtod(pNode->u.zJContent, 0);
174489 #endif
174490  sqlite3_result_double(pCtx, r);
174491  break;
174492  }
174493  case JSON_STRING: {
174494 #if 0 /* Never happens because JNODE_RAW is only set by json_set(),
174495  ** json_insert() and json_replace() and those routines do not
174496  ** call jsonReturn() */
174497  if( pNode->jnFlags & JNODE_RAW ){
174498  sqlite3_result_text(pCtx, pNode->u.zJContent, pNode->n,
174499  SQLITE_TRANSIENT);
174500  }else
174501 #endif
174502  assert( (pNode->jnFlags & JNODE_RAW)==0 );
174503  if( (pNode->jnFlags & JNODE_ESCAPE)==0 ){
174504  /* JSON formatted without any backslash-escapes */
174505  sqlite3_result_text(pCtx, pNode->u.zJContent+1, pNode->n-2,
174506  SQLITE_TRANSIENT);
174507  }else{
174508  /* Translate JSON formatted string into raw text */
174509  u32 i;
174510  u32 n = pNode->n;
174511  const char *z = pNode->u.zJContent;
174512  char *zOut;
174513  u32 j;
174514  zOut = sqlite3_malloc( n+1 );
174515  if( zOut==0 ){
174517  break;
174518  }
174519  for(i=1, j=0; i<n-1; i++){
174520  char c = z[i];
174521  if( c!='\\' ){
174522  zOut[j++] = c;
174523  }else{
174524  c = z[++i];
174525  if( c=='u' ){
174526  u32 v = 0, k;
174527  for(k=0; k<4 && i<n-2; i++, k++){
174528  c = z[i+1];
174529  if( c>='0' && c<='9' ) v = v*16 + c - '0';
174530  else if( c>='A' && c<='F' ) v = v*16 + c - 'A' + 10;
174531  else if( c>='a' && c<='f' ) v = v*16 + c - 'a' + 10;
174532  else break;
174533  }
174534  if( v==0 ) break;
174535  if( v<=0x7f ){
174536  zOut[j++] = (char)v;
174537  }else if( v<=0x7ff ){
174538  zOut[j++] = (char)(0xc0 | (v>>6));
174539  zOut[j++] = 0x80 | (v&0x3f);
174540  }else{
174541  zOut[j++] = (char)(0xe0 | (v>>12));
174542  zOut[j++] = 0x80 | ((v>>6)&0x3f);
174543  zOut[j++] = 0x80 | (v&0x3f);
174544  }
174545  }else{
174546  if( c=='b' ){
174547  c = '\b';
174548  }else if( c=='f' ){
174549  c = '\f';
174550  }else if( c=='n' ){
174551  c = '\n';
174552  }else if( c=='r' ){
174553  c = '\r';
174554  }else if( c=='t' ){
174555  c = '\t';
174556  }
174557  zOut[j++] = c;
174558  }
174559  }
174560  }
174561  zOut[j] = 0;
174562  sqlite3_result_text(pCtx, zOut, j, sqlite3_free);
174563  }
174564  break;
174565  }
174566  case JSON_ARRAY:
174567  case JSON_OBJECT: {
174568  jsonReturnJson(pNode, pCtx, aReplace);
174569  break;
174570  }
174571  }
174572 }
174573 
174574 /* Forward reference */
174575 static int jsonParseAddNode(JsonParse*,u32,u32,const char*);
174576 
174577 /*
174578 ** A macro to hint to the compiler that a function should not be
174579 ** inlined.
174580 */
174581 #if defined(__GNUC__)
174582 # define JSON_NOINLINE __attribute__((noinline))
174583 #elif defined(_MSC_VER) && _MSC_VER>=1310
174584 # define JSON_NOINLINE __declspec(noinline)
174585 #else
174586 # define JSON_NOINLINE
174587 #endif
174588 
174589 
174590 static JSON_NOINLINE int jsonParseAddNodeExpand(
174591  JsonParse *pParse, /* Append the node to this object */
174592  u32 eType, /* Node type */
174593  u32 n, /* Content size or sub-node count */
174594  const char *zContent /* Content */
174595 ){
174596  u32 nNew;
174597  JsonNode *pNew;
174598  assert( pParse->nNode>=pParse->nAlloc );
174599  if( pParse->oom ) return -1;
174600  nNew = pParse->nAlloc*2 + 10;
174601  pNew = sqlite3_realloc(pParse->aNode, sizeof(JsonNode)*nNew);
174602  if( pNew==0 ){
174603  pParse->oom = 1;
174604  return -1;
174605  }
174606  pParse->nAlloc = nNew;
174607  pParse->aNode = pNew;
174608  assert( pParse->nNode<pParse->nAlloc );
174609  return jsonParseAddNode(pParse, eType, n, zContent);
174610 }
174611 
174612 /*
174613 ** Create a new JsonNode instance based on the arguments and append that
174614 ** instance to the JsonParse. Return the index in pParse->aNode[] of the
174615 ** new node, or -1 if a memory allocation fails.
174616 */
174617 static int jsonParseAddNode(
174618  JsonParse *pParse, /* Append the node to this object */
174619  u32 eType, /* Node type */
174620  u32 n, /* Content size or sub-node count */
174621  const char *zContent /* Content */
174622 ){
174623  JsonNode *p;
174624  if( pParse->nNode>=pParse->nAlloc ){
174625  return jsonParseAddNodeExpand(pParse, eType, n, zContent);
174626  }
174627  p = &pParse->aNode[pParse->nNode];
174628  p->eType = (u8)eType;
174629  p->jnFlags = 0;
174630  p->iVal = 0;
174631  p->n = n;
174632  p->u.zJContent = zContent;
174633  return pParse->nNode++;
174634 }
174635 
174636 /*
174637 ** Parse a single JSON value which begins at pParse->zJson[i]. Return the
174638 ** index of the first character past the end of the value parsed.
174639 **
174640 ** Return negative for a syntax error. Special cases: return -2 if the
174641 ** first non-whitespace character is '}' and return -3 if the first
174642 ** non-whitespace character is ']'.
174643 */
174644 static int jsonParseValue(JsonParse *pParse, u32 i){
174645  char c;
174646  u32 j;
174647  int iThis;
174648  int x;
174649  JsonNode *pNode;
174650  while( safe_isspace(pParse->zJson[i]) ){ i++; }
174651  if( (c = pParse->zJson[i])=='{' ){
174652  /* Parse object */
174653  iThis = jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
174654  if( iThis<0 ) return -1;
174655  for(j=i+1;;j++){
174656  while( safe_isspace(pParse->zJson[j]) ){ j++; }
174657  x = jsonParseValue(pParse, j);
174658  if( x<0 ){
174659  if( x==(-2) && pParse->nNode==(u32)iThis+1 ) return j+1;
174660  return -1;
174661  }
174662  if( pParse->oom ) return -1;
174663  pNode = &pParse->aNode[pParse->nNode-1];
174664  if( pNode->eType!=JSON_STRING ) return -1;
174665  pNode->jnFlags |= JNODE_LABEL;
174666  j = x;
174667  while( safe_isspace(pParse->zJson[j]) ){ j++; }
174668  if( pParse->zJson[j]!=':' ) return -1;
174669  j++;
174670  x = jsonParseValue(pParse, j);
174671  if( x<0 ) return -1;
174672  j = x;
174673  while( safe_isspace(pParse->zJson[j]) ){ j++; }
174674  c = pParse->zJson[j];
174675  if( c==',' ) continue;
174676  if( c!='}' ) return -1;
174677  break;
174678  }
174679  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
174680  return j+1;
174681  }else if( c=='[' ){
174682  /* Parse array */
174683  iThis = jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
174684  if( iThis<0 ) return -1;
174685  for(j=i+1;;j++){
174686  while( safe_isspace(pParse->zJson[j]) ){ j++; }
174687  x = jsonParseValue(pParse, j);
174688  if( x<0 ){
174689  if( x==(-3) && pParse->nNode==(u32)iThis+1 ) return j+1;
174690  return -1;
174691  }
174692  j = x;
174693  while( safe_isspace(pParse->zJson[j]) ){ j++; }
174694  c = pParse->zJson[j];
174695  if( c==',' ) continue;
174696  if( c!=']' ) return -1;
174697  break;
174698  }
174699  pParse->aNode[iThis].n = pParse->nNode - (u32)iThis - 1;
174700  return j+1;
174701  }else if( c=='"' ){
174702  /* Parse string */
174703  u8 jnFlags = 0;
174704  j = i+1;
174705  for(;;){
174706  c = pParse->zJson[j];
174707  if( c==0 ) return -1;
174708  if( c=='\\' ){
174709  c = pParse->zJson[++j];
174710  if( c==0 ) return -1;
174711  jnFlags = JNODE_ESCAPE;
174712  }else if( c=='"' ){
174713  break;
174714  }
174715  j++;
174716  }
174717  jsonParseAddNode(pParse, JSON_STRING, j+1-i, &pParse->zJson[i]);
174718  if( !pParse->oom ) pParse->aNode[pParse->nNode-1].jnFlags = jnFlags;
174719  return j+1;
174720  }else if( c=='n'
174721  && strncmp(pParse->zJson+i,"null",4)==0
174722  && !safe_isalnum(pParse->zJson[i+4]) ){
174723  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
174724  return i+4;
174725  }else if( c=='t'
174726  && strncmp(pParse->zJson+i,"true",4)==0
174727  && !safe_isalnum(pParse->zJson[i+4]) ){
174728  jsonParseAddNode(pParse, JSON_TRUE, 0, 0);
174729  return i+4;
174730  }else if( c=='f'
174731  && strncmp(pParse->zJson+i,"false",5)==0
174732  && !safe_isalnum(pParse->zJson[i+5]) ){
174733  jsonParseAddNode(pParse, JSON_FALSE, 0, 0);
174734  return i+5;
174735  }else if( c=='-' || (c>='0' && c<='9') ){
174736  /* Parse number */
174737  u8 seenDP = 0;
174738  u8 seenE = 0;
174739  j = i+1;
174740  for(;; j++){
174741  c = pParse->zJson[j];
174742  if( c>='0' && c<='9' ) continue;
174743  if( c=='.' ){
174744  if( pParse->zJson[j-1]=='-' ) return -1;
174745  if( seenDP ) return -1;
174746  seenDP = 1;
174747  continue;
174748  }
174749  if( c=='e' || c=='E' ){
174750  if( pParse->zJson[j-1]<'0' ) return -1;
174751  if( seenE ) return -1;
174752  seenDP = seenE = 1;
174753  c = pParse->zJson[j+1];
174754  if( c=='+' || c=='-' ){
174755  j++;
174756  c = pParse->zJson[j+1];
174757  }
174758  if( c<'0' || c>'9' ) return -1;
174759  continue;
174760  }
174761  break;
174762  }
174763  if( pParse->zJson[j-1]<'0' ) return -1;
174764  jsonParseAddNode(pParse, seenDP ? JSON_REAL : JSON_INT,
174765  j - i, &pParse->zJson[i]);
174766  return j;
174767  }else if( c=='}' ){
174768  return -2; /* End of {...} */
174769  }else if( c==']' ){
174770  return -3; /* End of [...] */
174771  }else if( c==0 ){
174772  return 0; /* End of file */
174773  }else{
174774  return -1; /* Syntax error */
174775  }
174776 }
174777 
174778 /*
174779 ** Parse a complete JSON string. Return 0 on success or non-zero if there
174780 ** are any errors. If an error occurs, free all memory associated with
174781 ** pParse.
174782 **
174783 ** pParse is uninitialized when this routine is called.
174784 */
174785 static int jsonParse(
174786  JsonParse *pParse, /* Initialize and fill this JsonParse object */
174787  sqlite3_context *pCtx, /* Report errors here */
174788  const char *zJson /* Input JSON text to be parsed */
174789 ){
174790  int i;
174791  memset(pParse, 0, sizeof(*pParse));
174792  if( zJson==0 ) return 1;
174793  pParse->zJson = zJson;
174794  i = jsonParseValue(pParse, 0);
174795  if( pParse->oom ) i = -1;
174796  if( i>0 ){
174797  while( safe_isspace(zJson[i]) ) i++;
174798  if( zJson[i] ) i = -1;
174799  }
174800  if( i<=0 ){
174801  if( pCtx!=0 ){
174802  if( pParse->oom ){
174804  }else{
174805  sqlite3_result_error(pCtx, "malformed JSON", -1);
174806  }
174807  }
174808  jsonParseReset(pParse);
174809  return 1;
174810  }
174811  return 0;
174812 }
174813 
174814 /* Mark node i of pParse as being a child of iParent. Call recursively
174815 ** to fill in all the descendants of node i.
174816 */
174817 static void jsonParseFillInParentage(JsonParse *pParse, u32 i, u32 iParent){
174818  JsonNode *pNode = &pParse->aNode[i];
174819  u32 j;
174820  pParse->aUp[i] = iParent;
174821  switch( pNode->eType ){
174822  case JSON_ARRAY: {
174823  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j)){
174824  jsonParseFillInParentage(pParse, i+j, i);
174825  }
174826  break;
174827  }
174828  case JSON_OBJECT: {
174829  for(j=1; j<=pNode->n; j += jsonNodeSize(pNode+j+1)+1){
174830  pParse->aUp[i+j] = i;
174831  jsonParseFillInParentage(pParse, i+j+1, i);
174832  }
174833  break;
174834  }
174835  default: {
174836  break;
174837  }
174838  }
174839 }
174840 
174841 /*
174842 ** Compute the parentage of all nodes in a completed parse.
174843 */
174844 static int jsonParseFindParents(JsonParse *pParse){
174845  u32 *aUp;
174846  assert( pParse->aUp==0 );
174847  aUp = pParse->aUp = sqlite3_malloc( sizeof(u32)*pParse->nNode );
174848  if( aUp==0 ){
174849  pParse->oom = 1;
174850  return SQLITE_NOMEM;
174851  }
174852  jsonParseFillInParentage(pParse, 0, 0);
174853  return SQLITE_OK;
174854 }
174855 
174856 /*
174857 ** Compare the OBJECT label at pNode against zKey,nKey. Return true on
174858 ** a match.
174859 */
174860 static int jsonLabelCompare(JsonNode *pNode, const char *zKey, u32 nKey){
174861  if( pNode->jnFlags & JNODE_RAW ){
174862  if( pNode->n!=nKey ) return 0;
174863  return strncmp(pNode->u.zJContent, zKey, nKey)==0;
174864  }else{
174865  if( pNode->n!=nKey+2 ) return 0;
174866  return strncmp(pNode->u.zJContent+1, zKey, nKey)==0;
174867  }
174868 }
174869 
174870 /* forward declaration */
174871 static JsonNode *jsonLookupAppend(JsonParse*,const char*,int*,const char**);
174872 
174873 /*
174874 ** Search along zPath to find the node specified. Return a pointer
174875 ** to that node, or NULL if zPath is malformed or if there is no such
174876 ** node.
174877 **
174878 ** If pApnd!=0, then try to append new nodes to complete zPath if it is
174879 ** possible to do so and if no existing node corresponds to zPath. If
174880 ** new nodes are appended *pApnd is set to 1.
174881 */
174882 static JsonNode *jsonLookupStep(
174883  JsonParse *pParse, /* The JSON to search */
174884  u32 iRoot, /* Begin the search at this node */
174885  const char *zPath, /* The path to search */
174886  int *pApnd, /* Append nodes to complete path if not NULL */
174887  const char **pzErr /* Make *pzErr point to any syntax error in zPath */
174888 ){
174889  u32 i, j, nKey;
174890  const char *zKey;
174891  JsonNode *pRoot = &pParse->aNode[iRoot];
174892  if( zPath[0]==0 ) return pRoot;
174893  if( zPath[0]=='.' ){
174894  if( pRoot->eType!=JSON_OBJECT ) return 0;
174895  zPath++;
174896  if( zPath[0]=='"' ){
174897  zKey = zPath + 1;
174898  for(i=1; zPath[i] && zPath[i]!='"'; i++){}
174899  nKey = i-1;
174900  if( zPath[i] ){
174901  i++;
174902  }else{
174903  *pzErr = zPath;
174904  return 0;
174905  }
174906  }else{
174907  zKey = zPath;
174908  for(i=0; zPath[i] && zPath[i]!='.' && zPath[i]!='['; i++){}
174909  nKey = i;
174910  }
174911  if( nKey==0 ){
174912  *pzErr = zPath;
174913  return 0;
174914  }
174915  j = 1;
174916  for(;;){
174917  while( j<=pRoot->n ){
174918  if( jsonLabelCompare(pRoot+j, zKey, nKey) ){
174919  return jsonLookupStep(pParse, iRoot+j+1, &zPath[i], pApnd, pzErr);
174920  }
174921  j++;
174922  j += jsonNodeSize(&pRoot[j]);
174923  }
174924  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
174925  iRoot += pRoot->u.iAppend;
174926  pRoot = &pParse->aNode[iRoot];
174927  j = 1;
174928  }
174929  if( pApnd ){
174930  u32 iStart, iLabel;
174931  JsonNode *pNode;
174932  iStart = jsonParseAddNode(pParse, JSON_OBJECT, 2, 0);
174933  iLabel = jsonParseAddNode(pParse, JSON_STRING, i, zPath);
174934  zPath += i;
174935  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
174936  if( pParse->oom ) return 0;
174937  if( pNode ){
174938  pRoot = &pParse->aNode[iRoot];
174939  pRoot->u.iAppend = iStart - iRoot;
174940  pRoot->jnFlags |= JNODE_APPEND;
174941  pParse->aNode[iLabel].jnFlags |= JNODE_RAW;
174942  }
174943  return pNode;
174944  }
174945  }else if( zPath[0]=='[' && safe_isdigit(zPath[1]) ){
174946  if( pRoot->eType!=JSON_ARRAY ) return 0;
174947  i = 0;
174948  j = 1;
174949  while( safe_isdigit(zPath[j]) ){
174950  i = i*10 + zPath[j] - '0';
174951  j++;
174952  }
174953  if( zPath[j]!=']' ){
174954  *pzErr = zPath;
174955  return 0;
174956  }
174957  zPath += j + 1;
174958  j = 1;
174959  for(;;){
174960  while( j<=pRoot->n && (i>0 || (pRoot[j].jnFlags & JNODE_REMOVE)!=0) ){
174961  if( (pRoot[j].jnFlags & JNODE_REMOVE)==0 ) i--;
174962  j += jsonNodeSize(&pRoot[j]);
174963  }
174964  if( (pRoot->jnFlags & JNODE_APPEND)==0 ) break;
174965  iRoot += pRoot->u.iAppend;
174966  pRoot = &pParse->aNode[iRoot];
174967  j = 1;
174968  }
174969  if( j<=pRoot->n ){
174970  return jsonLookupStep(pParse, iRoot+j, zPath, pApnd, pzErr);
174971  }
174972  if( i==0 && pApnd ){
174973  u32 iStart;
174974  JsonNode *pNode;
174975  iStart = jsonParseAddNode(pParse, JSON_ARRAY, 1, 0);
174976  pNode = jsonLookupAppend(pParse, zPath, pApnd, pzErr);
174977  if( pParse->oom ) return 0;
174978  if( pNode ){
174979  pRoot = &pParse->aNode[iRoot];
174980  pRoot->u.iAppend = iStart - iRoot;
174981  pRoot->jnFlags |= JNODE_APPEND;
174982  }
174983  return pNode;
174984  }
174985  }else{
174986  *pzErr = zPath;
174987  }
174988  return 0;
174989 }
174990 
174991 /*
174992 ** Append content to pParse that will complete zPath. Return a pointer
174993 ** to the inserted node, or return NULL if the append fails.
174994 */
174995 static JsonNode *jsonLookupAppend(
174996  JsonParse *pParse, /* Append content to the JSON parse */
174997  const char *zPath, /* Description of content to append */
174998  int *pApnd, /* Set this flag to 1 */
174999  const char **pzErr /* Make this point to any syntax error */
175000 ){
175001  *pApnd = 1;
175002  if( zPath[0]==0 ){
175003  jsonParseAddNode(pParse, JSON_NULL, 0, 0);
175004  return pParse->oom ? 0 : &pParse->aNode[pParse->nNode-1];
175005  }
175006  if( zPath[0]=='.' ){
175007  jsonParseAddNode(pParse, JSON_OBJECT, 0, 0);
175008  }else if( strncmp(zPath,"[0]",3)==0 ){
175009  jsonParseAddNode(pParse, JSON_ARRAY, 0, 0);
175010  }else{
175011  return 0;
175012  }
175013  if( pParse->oom ) return 0;
175014  return jsonLookupStep(pParse, pParse->nNode-1, zPath, pApnd, pzErr);
175015 }
175016 
175017 /*
175018 ** Return the text of a syntax error message on a JSON path. Space is
175019 ** obtained from sqlite3_malloc().
175020 */
175021 static char *jsonPathSyntaxError(const char *zErr){
175022  return sqlite3_mprintf("JSON path error near '%q'", zErr);
175023 }
175024 
175025 /*
175026 ** Do a node lookup using zPath. Return a pointer to the node on success.
175027 ** Return NULL if not found or if there is an error.
175028 **
175029 ** On an error, write an error message into pCtx and increment the
175030 ** pParse->nErr counter.
175031 **
175032 ** If pApnd!=NULL then try to append missing nodes and set *pApnd = 1 if
175033 ** nodes are appended.
175034 */
175035 static JsonNode *jsonLookup(
175036  JsonParse *pParse, /* The JSON to search */
175037  const char *zPath, /* The path to search */
175038  int *pApnd, /* Append nodes to complete path if not NULL */
175039  sqlite3_context *pCtx /* Report errors here, if not NULL */
175040 ){
175041  const char *zErr = 0;
175042  JsonNode *pNode = 0;
175043  char *zMsg;
175044 
175045  if( zPath==0 ) return 0;
175046  if( zPath[0]!='$' ){
175047  zErr = zPath;
175048  goto lookup_err;
175049  }
175050  zPath++;
175051  pNode = jsonLookupStep(pParse, 0, zPath, pApnd, &zErr);
175052  if( zErr==0 ) return pNode;
175053 
175054 lookup_err:
175055  pParse->nErr++;
175056  assert( zErr!=0 && pCtx!=0 );
175057  zMsg = jsonPathSyntaxError(zErr);
175058  if( zMsg ){
175059  sqlite3_result_error(pCtx, zMsg, -1);
175060  sqlite3_free(zMsg);
175061  }else{
175063  }
175064  return 0;
175065 }
175066 
175067 
175068 /*
175069 ** Report the wrong number of arguments for json_insert(), json_replace()
175070 ** or json_set().
175071 */
175072 static void jsonWrongNumArgs(
175073  sqlite3_context *pCtx,
175074  const char *zFuncName
175075 ){
175076  char *zMsg = sqlite3_mprintf("json_%s() needs an odd number of arguments",
175077  zFuncName);
175078  sqlite3_result_error(pCtx, zMsg, -1);
175079  sqlite3_free(zMsg);
175080 }
175081 
175082 
175083 /****************************************************************************
175084 ** SQL functions used for testing and debugging
175085 ****************************************************************************/
175086 
175087 #ifdef SQLITE_DEBUG
175088 /*
175089 ** The json_parse(JSON) function returns a string which describes
175090 ** a parse of the JSON provided. Or it returns NULL if JSON is not
175091 ** well-formed.
175092 */
175093 static void jsonParseFunc(
175094  sqlite3_context *ctx,
175095  int argc,
175096  sqlite3_value **argv
175097 ){
175098  JsonString s; /* Output string - not real JSON */
175099  JsonParse x; /* The parse */
175100  u32 i;
175101 
175102  assert( argc==1 );
175103  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175104  jsonParseFindParents(&x);
175105  jsonInit(&s, ctx);
175106  for(i=0; i<x.nNode; i++){
175107  const char *zType;
175108  if( x.aNode[i].jnFlags & JNODE_LABEL ){
175109  assert( x.aNode[i].eType==JSON_STRING );
175110  zType = "label";
175111  }else{
175112  zType = jsonType[x.aNode[i].eType];
175113  }
175114  jsonPrintf(100, &s,"node %3u: %7s n=%-4d up=%-4d",
175115  i, zType, x.aNode[i].n, x.aUp[i]);
175116  if( x.aNode[i].u.zJContent!=0 ){
175117  jsonAppendRaw(&s, " ", 1);
175118  jsonAppendRaw(&s, x.aNode[i].u.zJContent, x.aNode[i].n);
175119  }
175120  jsonAppendRaw(&s, "\n", 1);
175121  }
175122  jsonParseReset(&x);
175123  jsonResult(&s);
175124 }
175125 
175126 /*
175127 ** The json_test1(JSON) function return true (1) if the input is JSON
175128 ** text generated by another json function. It returns (0) if the input
175129 ** is not known to be JSON.
175130 */
175131 static void jsonTest1Func(
175132  sqlite3_context *ctx,
175133  int argc,
175134  sqlite3_value **argv
175135 ){
175136  UNUSED_PARAM(argc);
175137  sqlite3_result_int(ctx, sqlite3_value_subtype(argv[0])==JSON_SUBTYPE);
175138 }
175139 #endif /* SQLITE_DEBUG */
175140 
175141 /****************************************************************************
175142 ** Scalar SQL function implementations
175143 ****************************************************************************/
175144 
175145 /*
175146 ** Implementation of the json_array(VALUE,...) function. Return a JSON
175147 ** array that contains all values given in arguments. Or if any argument
175148 ** is a BLOB, throw an error.
175149 */
175150 static void jsonArrayFunc(
175151  sqlite3_context *ctx,
175152  int argc,
175153  sqlite3_value **argv
175154 ){
175155  int i;
175156  JsonString jx;
175157 
175158  jsonInit(&jx, ctx);
175159  jsonAppendChar(&jx, '[');
175160  for(i=0; i<argc; i++){
175161  jsonAppendSeparator(&jx);
175162  jsonAppendValue(&jx, argv[i]);
175163  }
175164  jsonAppendChar(&jx, ']');
175165  jsonResult(&jx);
175166  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
175167 }
175168 
175169 
175170 /*
175171 ** json_array_length(JSON)
175172 ** json_array_length(JSON, PATH)
175173 **
175174 ** Return the number of elements in the top-level JSON array.
175175 ** Return 0 if the input is not a well-formed JSON array.
175176 */
175177 static void jsonArrayLengthFunc(
175178  sqlite3_context *ctx,
175179  int argc,
175180  sqlite3_value **argv
175181 ){
175182  JsonParse x; /* The parse */
175183  sqlite3_int64 n = 0;
175184  u32 i;
175185  JsonNode *pNode;
175186 
175187  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175188  assert( x.nNode );
175189  if( argc==2 ){
175190  const char *zPath = (const char*)sqlite3_value_text(argv[1]);
175191  pNode = jsonLookup(&x, zPath, 0, ctx);
175192  }else{
175193  pNode = x.aNode;
175194  }
175195  if( pNode==0 ){
175196  x.nErr = 1;
175197  }else if( pNode->eType==JSON_ARRAY ){
175198  assert( (pNode->jnFlags & JNODE_APPEND)==0 );
175199  for(i=1; i<=pNode->n; n++){
175200  i += jsonNodeSize(&pNode[i]);
175201  }
175202  }
175203  if( x.nErr==0 ) sqlite3_result_int64(ctx, n);
175204  jsonParseReset(&x);
175205 }
175206 
175207 /*
175208 ** json_extract(JSON, PATH, ...)
175209 **
175210 ** Return the element described by PATH. Return NULL if there is no
175211 ** PATH element. If there are multiple PATHs, then return a JSON array
175212 ** with the result from each path. Throw an error if the JSON or any PATH
175213 ** is malformed.
175214 */
175215 static void jsonExtractFunc(
175216  sqlite3_context *ctx,
175217  int argc,
175218  sqlite3_value **argv
175219 ){
175220  JsonParse x; /* The parse */
175221  JsonNode *pNode;
175222  const char *zPath;
175223  JsonString jx;
175224  int i;
175225 
175226  if( argc<2 ) return;
175227  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175228  jsonInit(&jx, ctx);
175229  jsonAppendChar(&jx, '[');
175230  for(i=1; i<argc; i++){
175231  zPath = (const char*)sqlite3_value_text(argv[i]);
175232  pNode = jsonLookup(&x, zPath, 0, ctx);
175233  if( x.nErr ) break;
175234  if( argc>2 ){
175235  jsonAppendSeparator(&jx);
175236  if( pNode ){
175237  jsonRenderNode(pNode, &jx, 0);
175238  }else{
175239  jsonAppendRaw(&jx, "null", 4);
175240  }
175241  }else if( pNode ){
175242  jsonReturn(pNode, ctx, 0);
175243  }
175244  }
175245  if( argc>2 && i==argc ){
175246  jsonAppendChar(&jx, ']');
175247  jsonResult(&jx);
175248  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
175249  }
175250  jsonReset(&jx);
175251  jsonParseReset(&x);
175252 }
175253 
175254 /*
175255 ** Implementation of the json_object(NAME,VALUE,...) function. Return a JSON
175256 ** object that contains all name/value given in arguments. Or if any name
175257 ** is not a string or if any value is a BLOB, throw an error.
175258 */
175259 static void jsonObjectFunc(
175260  sqlite3_context *ctx,
175261  int argc,
175262  sqlite3_value **argv
175263 ){
175264  int i;
175265  JsonString jx;
175266  const char *z;
175267  u32 n;
175268 
175269  if( argc&1 ){
175270  sqlite3_result_error(ctx, "json_object() requires an even number "
175271  "of arguments", -1);
175272  return;
175273  }
175274  jsonInit(&jx, ctx);
175275  jsonAppendChar(&jx, '{');
175276  for(i=0; i<argc; i+=2){
175277  if( sqlite3_value_type(argv[i])!=SQLITE_TEXT ){
175278  sqlite3_result_error(ctx, "json_object() labels must be TEXT", -1);
175279  jsonReset(&jx);
175280  return;
175281  }
175282  jsonAppendSeparator(&jx);
175283  z = (const char*)sqlite3_value_text(argv[i]);
175284  n = (u32)sqlite3_value_bytes(argv[i]);
175285  jsonAppendString(&jx, z, n);
175286  jsonAppendChar(&jx, ':');
175287  jsonAppendValue(&jx, argv[i+1]);
175288  }
175289  jsonAppendChar(&jx, '}');
175290  jsonResult(&jx);
175291  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
175292 }
175293 
175294 
175295 /*
175296 ** json_remove(JSON, PATH, ...)
175297 **
175298 ** Remove the named elements from JSON and return the result. malformed
175299 ** JSON or PATH arguments result in an error.
175300 */
175301 static void jsonRemoveFunc(
175302  sqlite3_context *ctx,
175303  int argc,
175304  sqlite3_value **argv
175305 ){
175306  JsonParse x; /* The parse */
175307  JsonNode *pNode;
175308  const char *zPath;
175309  u32 i;
175310 
175311  if( argc<1 ) return;
175312  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175313  assert( x.nNode );
175314  for(i=1; i<(u32)argc; i++){
175315  zPath = (const char*)sqlite3_value_text(argv[i]);
175316  if( zPath==0 ) goto remove_done;
175317  pNode = jsonLookup(&x, zPath, 0, ctx);
175318  if( x.nErr ) goto remove_done;
175319  if( pNode ) pNode->jnFlags |= JNODE_REMOVE;
175320  }
175321  if( (x.aNode[0].jnFlags & JNODE_REMOVE)==0 ){
175322  jsonReturnJson(x.aNode, ctx, 0);
175323  }
175324 remove_done:
175325  jsonParseReset(&x);
175326 }
175327 
175328 /*
175329 ** json_replace(JSON, PATH, VALUE, ...)
175330 **
175331 ** Replace the value at PATH with VALUE. If PATH does not already exist,
175332 ** this routine is a no-op. If JSON or PATH is malformed, throw an error.
175333 */
175334 static void jsonReplaceFunc(
175335  sqlite3_context *ctx,
175336  int argc,
175337  sqlite3_value **argv
175338 ){
175339  JsonParse x; /* The parse */
175340  JsonNode *pNode;
175341  const char *zPath;
175342  u32 i;
175343 
175344  if( argc<1 ) return;
175345  if( (argc&1)==0 ) {
175346  jsonWrongNumArgs(ctx, "replace");
175347  return;
175348  }
175349  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175350  assert( x.nNode );
175351  for(i=1; i<(u32)argc; i+=2){
175352  zPath = (const char*)sqlite3_value_text(argv[i]);
175353  pNode = jsonLookup(&x, zPath, 0, ctx);
175354  if( x.nErr ) goto replace_err;
175355  if( pNode ){
175356  pNode->jnFlags |= (u8)JNODE_REPLACE;
175357  pNode->iVal = (u8)(i+1);
175358  }
175359  }
175360  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
175361  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
175362  }else{
175363  jsonReturnJson(x.aNode, ctx, argv);
175364  }
175365 replace_err:
175366  jsonParseReset(&x);
175367 }
175368 
175369 /*
175370 ** json_set(JSON, PATH, VALUE, ...)
175371 **
175372 ** Set the value at PATH to VALUE. Create the PATH if it does not already
175373 ** exist. Overwrite existing values that do exist.
175374 ** If JSON or PATH is malformed, throw an error.
175375 **
175376 ** json_insert(JSON, PATH, VALUE, ...)
175377 **
175378 ** Create PATH and initialize it to VALUE. If PATH already exists, this
175379 ** routine is a no-op. If JSON or PATH is malformed, throw an error.
175380 */
175381 static void jsonSetFunc(
175382  sqlite3_context *ctx,
175383  int argc,
175384  sqlite3_value **argv
175385 ){
175386  JsonParse x; /* The parse */
175387  JsonNode *pNode;
175388  const char *zPath;
175389  u32 i;
175390  int bApnd;
175391  int bIsSet = *(int*)sqlite3_user_data(ctx);
175392 
175393  if( argc<1 ) return;
175394  if( (argc&1)==0 ) {
175395  jsonWrongNumArgs(ctx, bIsSet ? "set" : "insert");
175396  return;
175397  }
175398  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175399  assert( x.nNode );
175400  for(i=1; i<(u32)argc; i+=2){
175401  zPath = (const char*)sqlite3_value_text(argv[i]);
175402  bApnd = 0;
175403  pNode = jsonLookup(&x, zPath, &bApnd, ctx);
175404  if( x.oom ){
175406  goto jsonSetDone;
175407  }else if( x.nErr ){
175408  goto jsonSetDone;
175409  }else if( pNode && (bApnd || bIsSet) ){
175410  pNode->jnFlags |= (u8)JNODE_REPLACE;
175411  pNode->iVal = (u8)(i+1);
175412  }
175413  }
175414  if( x.aNode[0].jnFlags & JNODE_REPLACE ){
175415  sqlite3_result_value(ctx, argv[x.aNode[0].iVal]);
175416  }else{
175417  jsonReturnJson(x.aNode, ctx, argv);
175418  }
175419 jsonSetDone:
175420  jsonParseReset(&x);
175421 }
175422 
175423 /*
175424 ** json_type(JSON)
175425 ** json_type(JSON, PATH)
175426 **
175427 ** Return the top-level "type" of a JSON string. Throw an error if
175428 ** either the JSON or PATH inputs are not well-formed.
175429 */
175430 static void jsonTypeFunc(
175431  sqlite3_context *ctx,
175432  int argc,
175433  sqlite3_value **argv
175434 ){
175435  JsonParse x; /* The parse */
175436  const char *zPath;
175437  JsonNode *pNode;
175438 
175439  if( jsonParse(&x, ctx, (const char*)sqlite3_value_text(argv[0])) ) return;
175440  assert( x.nNode );
175441  if( argc==2 ){
175442  zPath = (const char*)sqlite3_value_text(argv[1]);
175443  pNode = jsonLookup(&x, zPath, 0, ctx);
175444  }else{
175445  pNode = x.aNode;
175446  }
175447  if( pNode ){
175448  sqlite3_result_text(ctx, jsonType[pNode->eType], -1, SQLITE_STATIC);
175449  }
175450  jsonParseReset(&x);
175451 }
175452 
175453 /*
175454 ** json_valid(JSON)
175455 **
175456 ** Return 1 if JSON is a well-formed JSON string according to RFC-7159.
175457 ** Return 0 otherwise.
175458 */
175459 static void jsonValidFunc(
175460  sqlite3_context *ctx,
175461  int argc,
175462  sqlite3_value **argv
175463 ){
175464  JsonParse x; /* The parse */
175465  int rc = 0;
175466 
175467  UNUSED_PARAM(argc);
175468  if( jsonParse(&x, 0, (const char*)sqlite3_value_text(argv[0]))==0 ){
175469  rc = 1;
175470  }
175471  jsonParseReset(&x);
175472  sqlite3_result_int(ctx, rc);
175473 }
175474 
175475 
175476 /****************************************************************************
175477 ** Aggregate SQL function implementations
175478 ****************************************************************************/
175479 /*
175480 ** json_group_array(VALUE)
175481 **
175482 ** Return a JSON array composed of all values in the aggregate.
175483 */
175484 static void jsonArrayStep(
175485  sqlite3_context *ctx,
175486  int argc,
175487  sqlite3_value **argv
175488 ){
175489  JsonString *pStr;
175490  UNUSED_PARAM(argc);
175491  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
175492  if( pStr ){
175493  if( pStr->zBuf==0 ){
175494  jsonInit(pStr, ctx);
175495  jsonAppendChar(pStr, '[');
175496  }else{
175497  jsonAppendChar(pStr, ',');
175498  pStr->pCtx = ctx;
175499  }
175500  jsonAppendValue(pStr, argv[0]);
175501  }
175502 }
175503 static void jsonArrayFinal(sqlite3_context *ctx){
175504  JsonString *pStr;
175505  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
175506  if( pStr ){
175507  pStr->pCtx = ctx;
175508  jsonAppendChar(pStr, ']');
175509  if( pStr->bErr ){
175510  if( pStr->bErr==1 ) sqlite3_result_error_nomem(ctx);
175511  assert( pStr->bStatic );
175512  }else{
175513  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
175514  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
175515  pStr->bStatic = 1;
175516  }
175517  }else{
175518  sqlite3_result_text(ctx, "[]", 2, SQLITE_STATIC);
175519  }
175520  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
175521 }
175522 
175523 /*
175524 ** json_group_obj(NAME,VALUE)
175525 **
175526 ** Return a JSON object composed of all names and values in the aggregate.
175527 */
175528 static void jsonObjectStep(
175529  sqlite3_context *ctx,
175530  int argc,
175531  sqlite3_value **argv
175532 ){
175533  JsonString *pStr;
175534  const char *z;
175535  u32 n;
175536  UNUSED_PARAM(argc);
175537  pStr = (JsonString*)sqlite3_aggregate_context(ctx, sizeof(*pStr));
175538  if( pStr ){
175539  if( pStr->zBuf==0 ){
175540  jsonInit(pStr, ctx);
175541  jsonAppendChar(pStr, '{');
175542  }else{
175543  jsonAppendChar(pStr, ',');
175544  pStr->pCtx = ctx;
175545  }
175546  z = (const char*)sqlite3_value_text(argv[0]);
175547  n = (u32)sqlite3_value_bytes(argv[0]);
175548  jsonAppendString(pStr, z, n);
175549  jsonAppendChar(pStr, ':');
175550  jsonAppendValue(pStr, argv[1]);
175551  }
175552 }
175553 static void jsonObjectFinal(sqlite3_context *ctx){
175554  JsonString *pStr;
175555  pStr = (JsonString*)sqlite3_aggregate_context(ctx, 0);
175556  if( pStr ){
175557  jsonAppendChar(pStr, '}');
175558  if( pStr->bErr ){
175559  if( pStr->bErr==0 ) sqlite3_result_error_nomem(ctx);
175560  assert( pStr->bStatic );
175561  }else{
175562  sqlite3_result_text(ctx, pStr->zBuf, pStr->nUsed,
175563  pStr->bStatic ? SQLITE_TRANSIENT : sqlite3_free);
175564  pStr->bStatic = 1;
175565  }
175566  }else{
175567  sqlite3_result_text(ctx, "{}", 2, SQLITE_STATIC);
175568  }
175569  sqlite3_result_subtype(ctx, JSON_SUBTYPE);
175570 }
175571 
175572 
175573 #ifndef SQLITE_OMIT_VIRTUALTABLE
175574 /****************************************************************************
175575 ** The json_each virtual table
175576 ****************************************************************************/
175577 typedef struct JsonEachCursor JsonEachCursor;
175578 struct JsonEachCursor {
175579  sqlite3_vtab_cursor base; /* Base class - must be first */
175580  u32 iRowid; /* The rowid */
175581  u32 iBegin; /* The first node of the scan */
175582  u32 i; /* Index in sParse.aNode[] of current row */
175583  u32 iEnd; /* EOF when i equals or exceeds this value */
175584  u8 eType; /* Type of top-level element */
175585  u8 bRecursive; /* True for json_tree(). False for json_each() */
175586  char *zJson; /* Input JSON */
175587  char *zRoot; /* Path by which to filter zJson */
175588  JsonParse sParse; /* Parse of the input JSON */
175589 };
175590 
175591 /* Constructor for the json_each virtual table */
175592 static int jsonEachConnect(
175593  sqlite3 *db,
175594  void *pAux,
175595  int argc, const char *const*argv,
175596  sqlite3_vtab **ppVtab,
175597  char **pzErr
175598 ){
175599  sqlite3_vtab *pNew;
175600  int rc;
175601 
175602 /* Column numbers */
175603 #define JEACH_KEY 0
175604 #define JEACH_VALUE 1
175605 #define JEACH_TYPE 2
175606 #define JEACH_ATOM 3
175607 #define JEACH_ID 4
175608 #define JEACH_PARENT 5
175609 #define JEACH_FULLKEY 6
175610 #define JEACH_PATH 7
175611 #define JEACH_JSON 8
175612 #define JEACH_ROOT 9
175613 
175614  UNUSED_PARAM(pzErr);
175615  UNUSED_PARAM(argv);
175616  UNUSED_PARAM(argc);
175617  UNUSED_PARAM(pAux);
175618  rc = sqlite3_declare_vtab(db,
175619  "CREATE TABLE x(key,value,type,atom,id,parent,fullkey,path,"
175620  "json HIDDEN,root HIDDEN)");
175621  if( rc==SQLITE_OK ){
175622  pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
175623  if( pNew==0 ) return SQLITE_NOMEM;
175624  memset(pNew, 0, sizeof(*pNew));
175625  }
175626  return rc;
175627 }
175628 
175629 /* destructor for json_each virtual table */
175630 static int jsonEachDisconnect(sqlite3_vtab *pVtab){
175631  sqlite3_free(pVtab);
175632  return SQLITE_OK;
175633 }
175634 
175635 /* constructor for a JsonEachCursor object for json_each(). */
175636 static int jsonEachOpenEach(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
175637  JsonEachCursor *pCur;
175638 
175639  UNUSED_PARAM(p);
175640  pCur = sqlite3_malloc( sizeof(*pCur) );
175641  if( pCur==0 ) return SQLITE_NOMEM;
175642  memset(pCur, 0, sizeof(*pCur));
175643  *ppCursor = &pCur->base;
175644  return SQLITE_OK;
175645 }
175646 
175647 /* constructor for a JsonEachCursor object for json_tree(). */
175648 static int jsonEachOpenTree(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
175649  int rc = jsonEachOpenEach(p, ppCursor);
175650  if( rc==SQLITE_OK ){
175651  JsonEachCursor *pCur = (JsonEachCursor*)*ppCursor;
175652  pCur->bRecursive = 1;
175653  }
175654  return rc;
175655 }
175656 
175657 /* Reset a JsonEachCursor back to its original state. Free any memory
175658 ** held. */
175659 static void jsonEachCursorReset(JsonEachCursor *p){
175660  sqlite3_free(p->zJson);
175661  sqlite3_free(p->zRoot);
175662  jsonParseReset(&p->sParse);
175663  p->iRowid = 0;
175664  p->i = 0;
175665  p->iEnd = 0;
175666  p->eType = 0;
175667  p->zJson = 0;
175668  p->zRoot = 0;
175669 }
175670 
175671 /* Destructor for a jsonEachCursor object */
175672 static int jsonEachClose(sqlite3_vtab_cursor *cur){
175673  JsonEachCursor *p = (JsonEachCursor*)cur;
175674  jsonEachCursorReset(p);
175675  sqlite3_free(cur);
175676  return SQLITE_OK;
175677 }
175678 
175679 /* Return TRUE if the jsonEachCursor object has been advanced off the end
175680 ** of the JSON object */
175681 static int jsonEachEof(sqlite3_vtab_cursor *cur){
175682  JsonEachCursor *p = (JsonEachCursor*)cur;
175683  return p->i >= p->iEnd;
175684 }
175685 
175686 /* Advance the cursor to the next element for json_tree() */
175687 static int jsonEachNext(sqlite3_vtab_cursor *cur){
175688  JsonEachCursor *p = (JsonEachCursor*)cur;
175689  if( p->bRecursive ){
175690  if( p->sParse.aNode[p->i].jnFlags & JNODE_LABEL ) p->i++;
175691  p->i++;
175692  p->iRowid++;
175693  if( p->i<p->iEnd ){
175694  u32 iUp = p->sParse.aUp[p->i];
175695  JsonNode *pUp = &p->sParse.aNode[iUp];
175696  p->eType = pUp->eType;
175697  if( pUp->eType==JSON_ARRAY ){
175698  if( iUp==p->i-1 ){
175699  pUp->u.iKey = 0;
175700  }else{
175701  pUp->u.iKey++;
175702  }
175703  }
175704  }
175705  }else{
175706  switch( p->eType ){
175707  case JSON_ARRAY: {
175708  p->i += jsonNodeSize(&p->sParse.aNode[p->i]);
175709  p->iRowid++;
175710  break;
175711  }
175712  case JSON_OBJECT: {
175713  p->i += 1 + jsonNodeSize(&p->sParse.aNode[p->i+1]);
175714  p->iRowid++;
175715  break;
175716  }
175717  default: {
175718  p->i = p->iEnd;
175719  break;
175720  }
175721  }
175722  }
175723  return SQLITE_OK;
175724 }
175725 
175726 /* Append the name of the path for element i to pStr
175727 */
175728 static void jsonEachComputePath(
175729  JsonEachCursor *p, /* The cursor */
175730  JsonString *pStr, /* Write the path here */
175731  u32 i /* Path to this element */
175732 ){
175733  JsonNode *pNode, *pUp;
175734  u32 iUp;
175735  if( i==0 ){
175736  jsonAppendChar(pStr, '$');
175737  return;
175738  }
175739  iUp = p->sParse.aUp[i];
175740  jsonEachComputePath(p, pStr, iUp);
175741  pNode = &p->sParse.aNode[i];
175742  pUp = &p->sParse.aNode[iUp];
175743  if( pUp->eType==JSON_ARRAY ){
175744  jsonPrintf(30, pStr, "[%d]", pUp->u.iKey);
175745  }else{
175746  assert( pUp->eType==JSON_OBJECT );
175747  if( (pNode->jnFlags & JNODE_LABEL)==0 ) pNode--;
175748  assert( pNode->eType==JSON_STRING );
175749  assert( pNode->jnFlags & JNODE_LABEL );
175750  jsonPrintf(pNode->n+1, pStr, ".%.*s", pNode->n-2, pNode->u.zJContent+1);
175751  }
175752 }
175753 
175754 /* Return the value of a column */
175755 static int jsonEachColumn(
175756  sqlite3_vtab_cursor *cur, /* The cursor */
175757  sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
175758  int i /* Which column to return */
175759 ){
175760  JsonEachCursor *p = (JsonEachCursor*)cur;
175761  JsonNode *pThis = &p->sParse.aNode[p->i];
175762  switch( i ){
175763  case JEACH_KEY: {
175764  if( p->i==0 ) break;
175765  if( p->eType==JSON_OBJECT ){
175766  jsonReturn(pThis, ctx, 0);
175767  }else if( p->eType==JSON_ARRAY ){
175768  u32 iKey;
175769  if( p->bRecursive ){
175770  if( p->iRowid==0 ) break;
175771  iKey = p->sParse.aNode[p->sParse.aUp[p->i]].u.iKey;
175772  }else{
175773  iKey = p->iRowid;
175774  }
175775  sqlite3_result_int64(ctx, (sqlite3_int64)iKey);
175776  }
175777  break;
175778  }
175779  case JEACH_VALUE: {
175780  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
175781  jsonReturn(pThis, ctx, 0);
175782  break;
175783  }
175784  case JEACH_TYPE: {
175785  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
175786  sqlite3_result_text(ctx, jsonType[pThis->eType], -1, SQLITE_STATIC);
175787  break;
175788  }
175789  case JEACH_ATOM: {
175790  if( pThis->jnFlags & JNODE_LABEL ) pThis++;
175791  if( pThis->eType>=JSON_ARRAY ) break;
175792  jsonReturn(pThis, ctx, 0);
175793  break;
175794  }
175795  case JEACH_ID: {
175796  sqlite3_result_int64(ctx,
175797  (sqlite3_int64)p->i + ((pThis->jnFlags & JNODE_LABEL)!=0));
175798  break;
175799  }
175800  case JEACH_PARENT: {
175801  if( p->i>p->iBegin && p->bRecursive ){
175802  sqlite3_result_int64(ctx, (sqlite3_int64)p->sParse.aUp[p->i]);
175803  }
175804  break;
175805  }
175806  case JEACH_FULLKEY: {
175807  JsonString x;
175808  jsonInit(&x, ctx);
175809  if( p->bRecursive ){
175810  jsonEachComputePath(p, &x, p->i);
175811  }else{
175812  if( p->zRoot ){
175813  jsonAppendRaw(&x, p->zRoot, (int)strlen(p->zRoot));
175814  }else{
175815  jsonAppendChar(&x, '$');
175816  }
175817  if( p->eType==JSON_ARRAY ){
175818  jsonPrintf(30, &x, "[%d]", p->iRowid);
175819  }else{
175820  jsonPrintf(pThis->n, &x, ".%.*s", pThis->n-2, pThis->u.zJContent+1);
175821  }
175822  }
175823  jsonResult(&x);
175824  break;
175825  }
175826  case JEACH_PATH: {
175827  if( p->bRecursive ){
175828  JsonString x;
175829  jsonInit(&x, ctx);
175830  jsonEachComputePath(p, &x, p->sParse.aUp[p->i]);
175831  jsonResult(&x);
175832  break;
175833  }
175834  /* For json_each() path and root are the same so fall through
175835  ** into the root case */
175836  }
175837  case JEACH_ROOT: {
175838  const char *zRoot = p->zRoot;
175839  if( zRoot==0 ) zRoot = "$";
175840  sqlite3_result_text(ctx, zRoot, -1, SQLITE_STATIC);
175841  break;
175842  }
175843  case JEACH_JSON: {
175844  assert( i==JEACH_JSON );
175845  sqlite3_result_text(ctx, p->sParse.zJson, -1, SQLITE_STATIC);
175846  break;
175847  }
175848  }
175849  return SQLITE_OK;
175850 }
175851 
175852 /* Return the current rowid value */
175853 static int jsonEachRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
175854  JsonEachCursor *p = (JsonEachCursor*)cur;
175855  *pRowid = p->iRowid;
175856  return SQLITE_OK;
175857 }
175858 
175859 /* The query strategy is to look for an equality constraint on the json
175860 ** column. Without such a constraint, the table cannot operate. idxNum is
175861 ** 1 if the constraint is found, 3 if the constraint and zRoot are found,
175862 ** and 0 otherwise.
175863 */
175864 static int jsonEachBestIndex(
175865  sqlite3_vtab *tab,
175866  sqlite3_index_info *pIdxInfo
175867 ){
175868  int i;
175869  int jsonIdx = -1;
175870  int rootIdx = -1;
175871  const struct sqlite3_index_constraint *pConstraint;
175872 
175873  UNUSED_PARAM(tab);
175874  pConstraint = pIdxInfo->aConstraint;
175875  for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
175876  if( pConstraint->usable==0 ) continue;
175877  if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
175878  switch( pConstraint->iColumn ){
175879  case JEACH_JSON: jsonIdx = i; break;
175880  case JEACH_ROOT: rootIdx = i; break;
175881  default: /* no-op */ break;
175882  }
175883  }
175884  if( jsonIdx<0 ){
175885  pIdxInfo->idxNum = 0;
175886  pIdxInfo->estimatedCost = 1e99;
175887  }else{
175888  pIdxInfo->estimatedCost = 1.0;
175889  pIdxInfo->aConstraintUsage[jsonIdx].argvIndex = 1;
175890  pIdxInfo->aConstraintUsage[jsonIdx].omit = 1;
175891  if( rootIdx<0 ){
175892  pIdxInfo->idxNum = 1;
175893  }else{
175894  pIdxInfo->aConstraintUsage[rootIdx].argvIndex = 2;
175895  pIdxInfo->aConstraintUsage[rootIdx].omit = 1;
175896  pIdxInfo->idxNum = 3;
175897  }
175898  }
175899  return SQLITE_OK;
175900 }
175901 
175902 /* Start a search on a new JSON string */
175903 static int jsonEachFilter(
175904  sqlite3_vtab_cursor *cur,
175905  int idxNum, const char *idxStr,
175906  int argc, sqlite3_value **argv
175907 ){
175908  JsonEachCursor *p = (JsonEachCursor*)cur;
175909  const char *z;
175910  const char *zRoot = 0;
175911  sqlite3_int64 n;
175912 
175913  UNUSED_PARAM(idxStr);
175914  UNUSED_PARAM(argc);
175915  jsonEachCursorReset(p);
175916  if( idxNum==0 ) return SQLITE_OK;
175917  z = (const char*)sqlite3_value_text(argv[0]);
175918  if( z==0 ) return SQLITE_OK;
175919  n = sqlite3_value_bytes(argv[0]);
175920  p->zJson = sqlite3_malloc64( n+1 );
175921  if( p->zJson==0 ) return SQLITE_NOMEM;
175922  memcpy(p->zJson, z, (size_t)n+1);
175923  if( jsonParse(&p->sParse, 0, p->zJson) ){
175924  int rc = SQLITE_NOMEM;
175925  if( p->sParse.oom==0 ){
175926  sqlite3_free(cur->pVtab->zErrMsg);
175927  cur->pVtab->zErrMsg = sqlite3_mprintf("malformed JSON");
175928  if( cur->pVtab->zErrMsg ) rc = SQLITE_ERROR;
175929  }
175930  jsonEachCursorReset(p);
175931  return rc;
175932  }else if( p->bRecursive && jsonParseFindParents(&p->sParse) ){
175933  jsonEachCursorReset(p);
175934  return SQLITE_NOMEM;
175935  }else{
175936  JsonNode *pNode = 0;
175937  if( idxNum==3 ){
175938  const char *zErr = 0;
175939  zRoot = (const char*)sqlite3_value_text(argv[1]);
175940  if( zRoot==0 ) return SQLITE_OK;
175941  n = sqlite3_value_bytes(argv[1]);
175942  p->zRoot = sqlite3_malloc64( n+1 );
175943  if( p->zRoot==0 ) return SQLITE_NOMEM;
175944  memcpy(p->zRoot, zRoot, (size_t)n+1);
175945  if( zRoot[0]!='$' ){
175946  zErr = zRoot;
175947  }else{
175948  pNode = jsonLookupStep(&p->sParse, 0, p->zRoot+1, 0, &zErr);
175949  }
175950  if( zErr ){
175951  sqlite3_free(cur->pVtab->zErrMsg);
175952  cur->pVtab->zErrMsg = jsonPathSyntaxError(zErr);
175953  jsonEachCursorReset(p);
175954  return cur->pVtab->zErrMsg ? SQLITE_ERROR : SQLITE_NOMEM;
175955  }else if( pNode==0 ){
175956  return SQLITE_OK;
175957  }
175958  }else{
175959  pNode = p->sParse.aNode;
175960  }
175961  p->iBegin = p->i = (int)(pNode - p->sParse.aNode);
175962  p->eType = pNode->eType;
175963  if( p->eType>=JSON_ARRAY ){
175964  pNode->u.iKey = 0;
175965  p->iEnd = p->i + pNode->n + 1;
175966  if( p->bRecursive ){
175967  p->eType = p->sParse.aNode[p->sParse.aUp[p->i]].eType;
175968  if( p->i>0 && (p->sParse.aNode[p->i-1].jnFlags & JNODE_LABEL)!=0 ){
175969  p->i--;
175970  }
175971  }else{
175972  p->i++;
175973  }
175974  }else{
175975  p->iEnd = p->i+1;
175976  }
175977  }
175978  return SQLITE_OK;
175979 }
175980 
175981 /* The methods of the json_each virtual table */
175982 static sqlite3_module jsonEachModule = {
175983  0, /* iVersion */
175984  0, /* xCreate */
175985  jsonEachConnect, /* xConnect */
175986  jsonEachBestIndex, /* xBestIndex */
175987  jsonEachDisconnect, /* xDisconnect */
175988  0, /* xDestroy */
175989  jsonEachOpenEach, /* xOpen - open a cursor */
175990  jsonEachClose, /* xClose - close a cursor */
175991  jsonEachFilter, /* xFilter - configure scan constraints */
175992  jsonEachNext, /* xNext - advance a cursor */
175993  jsonEachEof, /* xEof - check for end of scan */
175994  jsonEachColumn, /* xColumn - read data */
175995  jsonEachRowid, /* xRowid - read data */
175996  0, /* xUpdate */
175997  0, /* xBegin */
175998  0, /* xSync */
175999  0, /* xCommit */
176000  0, /* xRollback */
176001  0, /* xFindMethod */
176002  0, /* xRename */
176003  0, /* xSavepoint */
176004  0, /* xRelease */
176005  0 /* xRollbackTo */
176006 };
176007 
176008 /* The methods of the json_tree virtual table. */
176009 static sqlite3_module jsonTreeModule = {
176010  0, /* iVersion */
176011  0, /* xCreate */
176012  jsonEachConnect, /* xConnect */
176013  jsonEachBestIndex, /* xBestIndex */
176014  jsonEachDisconnect, /* xDisconnect */
176015  0, /* xDestroy */
176016  jsonEachOpenTree, /* xOpen - open a cursor */
176017  jsonEachClose, /* xClose - close a cursor */
176018  jsonEachFilter, /* xFilter - configure scan constraints */
176019  jsonEachNext, /* xNext - advance a cursor */
176020  jsonEachEof, /* xEof - check for end of scan */
176021  jsonEachColumn, /* xColumn - read data */
176022  jsonEachRowid, /* xRowid - read data */
176023  0, /* xUpdate */
176024  0, /* xBegin */
176025  0, /* xSync */
176026  0, /* xCommit */
176027  0, /* xRollback */
176028  0, /* xFindMethod */
176029  0, /* xRename */
176030  0, /* xSavepoint */
176031  0, /* xRelease */
176032  0 /* xRollbackTo */
176033 };
176034 #endif /* SQLITE_OMIT_VIRTUALTABLE */
176035 
176036 /****************************************************************************
176037 ** The following routines are the only publically visible identifiers in this
176038 ** file. Call the following routines in order to register the various SQL
176039 ** functions and the virtual table implemented by this file.
176040 ****************************************************************************/
176041 
176042 SQLITE_PRIVATE int sqlite3Json1Init(sqlite3 *db){
176043  int rc = SQLITE_OK;
176044  unsigned int i;
176045  static const struct {
176046  const char *zName;
176047  int nArg;
176048  int flag;
176049  void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
176050  } aFunc[] = {
176051  { "json", 1, 0, jsonRemoveFunc },
176052  { "json_array", -1, 0, jsonArrayFunc },
176053  { "json_array_length", 1, 0, jsonArrayLengthFunc },
176054  { "json_array_length", 2, 0, jsonArrayLengthFunc },
176055  { "json_extract", -1, 0, jsonExtractFunc },
176056  { "json_insert", -1, 0, jsonSetFunc },
176057  { "json_object", -1, 0, jsonObjectFunc },
176058  { "json_remove", -1, 0, jsonRemoveFunc },
176059  { "json_replace", -1, 0, jsonReplaceFunc },
176060  { "json_set", -1, 1, jsonSetFunc },
176061  { "json_type", 1, 0, jsonTypeFunc },
176062  { "json_type", 2, 0, jsonTypeFunc },
176063  { "json_valid", 1, 0, jsonValidFunc },
176064 
176065 #if SQLITE_DEBUG
176066  /* DEBUG and TESTING functions */
176067  { "json_parse", 1, 0, jsonParseFunc },
176068  { "json_test1", 1, 0, jsonTest1Func },
176069 #endif
176070  };
176071  static const struct {
176072  const char *zName;
176073  int nArg;
176074  void (*xStep)(sqlite3_context*,int,sqlite3_value**);
176075  void (*xFinal)(sqlite3_context*);
176076  } aAgg[] = {
176077  { "json_group_array", 1, jsonArrayStep, jsonArrayFinal },
176078  { "json_group_object", 2, jsonObjectStep, jsonObjectFinal },
176079  };
176080 #ifndef SQLITE_OMIT_VIRTUALTABLE
176081  static const struct {
176082  const char *zName;
176083  sqlite3_module *pModule;
176084  } aMod[] = {
176085  { "json_each", &jsonEachModule },
176086  { "json_tree", &jsonTreeModule },
176087  };
176088 #endif
176089  for(i=0; i<sizeof(aFunc)/sizeof(aFunc[0]) && rc==SQLITE_OK; i++){
176090  rc = sqlite3_create_function(db, aFunc[i].zName, aFunc[i].nArg,
176092  (void*)&aFunc[i].flag,
176093  aFunc[i].xFunc, 0, 0);
176094  }
176095  for(i=0; i<sizeof(aAgg)/sizeof(aAgg[0]) && rc==SQLITE_OK; i++){
176096  rc = sqlite3_create_function(db, aAgg[i].zName, aAgg[i].nArg,
176098  0, aAgg[i].xStep, aAgg[i].xFinal);
176099  }
176100 #ifndef SQLITE_OMIT_VIRTUALTABLE
176101  for(i=0; i<sizeof(aMod)/sizeof(aMod[0]) && rc==SQLITE_OK; i++){
176102  rc = sqlite3_create_module(db, aMod[i].zName, aMod[i].pModule, 0);
176103  }
176104 #endif
176105  return rc;
176106 }
176107 
176108 
176109 #ifndef SQLITE_CORE
176110 #ifdef _WIN32
176111 __declspec(dllexport)
176112 #endif
176113 SQLITE_API int SQLITE_STDCALL sqlite3_json_init(
176114  sqlite3 *db,
176115  char **pzErrMsg,
176116  const sqlite3_api_routines *pApi
176117 ){
176118  SQLITE_EXTENSION_INIT2(pApi);
176119  (void)pzErrMsg; /* Unused parameter */
176120  return sqlite3Json1Init(db);
176121 }
176122 #endif
176123 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_JSON1) */
176124 
176125 /************** End of json1.c ***********************************************/
176126 /************** Begin file fts5.c ********************************************/
176127 
176128 
176129 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5)
176130 
176131 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
176132 # define NDEBUG 1
176133 #endif
176134 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
176135 # undef NDEBUG
176136 #endif
176137 
176138 /*
176139 ** 2014 May 31
176140 **
176141 ** The author disclaims copyright to this source code. In place of
176142 ** a legal notice, here is a blessing:
176143 **
176144 ** May you do good and not evil.
176145 ** May you find forgiveness for yourself and forgive others.
176146 ** May you share freely, never taking more than you give.
176147 **
176148 ******************************************************************************
176149 **
176150 ** Interfaces to extend FTS5. Using the interfaces defined in this file,
176151 ** FTS5 may be extended with:
176152 **
176153 ** * custom tokenizers, and
176154 ** * custom auxiliary functions.
176155 */
176156 
176157 
176158 #ifndef _FTS5_H
176159 #define _FTS5_H
176160 
176161 /* #include "sqlite3.h" */
176162 
176163 #if 0
176164 extern "C" {
176165 #endif
176166 
176167 /*************************************************************************
176168 ** CUSTOM AUXILIARY FUNCTIONS
176169 **
176170 ** Virtual table implementations may overload SQL functions by implementing
176171 ** the sqlite3_module.xFindFunction() method.
176172 */
176173 
176174 typedef struct Fts5ExtensionApi Fts5ExtensionApi;
176175 typedef struct Fts5Context Fts5Context;
176176 typedef struct Fts5PhraseIter Fts5PhraseIter;
176177 
176178 typedef void (*fts5_extension_function)(
176179  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
176180  Fts5Context *pFts, /* First arg to pass to pApi functions */
176181  sqlite3_context *pCtx, /* Context for returning result/error */
176182  int nVal, /* Number of values in apVal[] array */
176183  sqlite3_value **apVal /* Array of trailing arguments */
176184 );
176185 
176186 struct Fts5PhraseIter {
176187  const unsigned char *a;
176188  const unsigned char *b;
176189 };
176190 
176191 /*
176192 ** EXTENSION API FUNCTIONS
176193 **
176194 ** xUserData(pFts):
176195 ** Return a copy of the context pointer the extension function was
176196 ** registered with.
176197 **
176198 ** xColumnTotalSize(pFts, iCol, pnToken):
176199 ** If parameter iCol is less than zero, set output variable *pnToken
176200 ** to the total number of tokens in the FTS5 table. Or, if iCol is
176201 ** non-negative but less than the number of columns in the table, return
176202 ** the total number of tokens in column iCol, considering all rows in
176203 ** the FTS5 table.
176204 **
176205 ** If parameter iCol is greater than or equal to the number of columns
176206 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
176207 ** an OOM condition or IO error), an appropriate SQLite error code is
176208 ** returned.
176209 **
176210 ** xColumnCount(pFts):
176211 ** Return the number of columns in the table.
176212 **
176213 ** xColumnSize(pFts, iCol, pnToken):
176214 ** If parameter iCol is less than zero, set output variable *pnToken
176215 ** to the total number of tokens in the current row. Or, if iCol is
176216 ** non-negative but less than the number of columns in the table, set
176217 ** *pnToken to the number of tokens in column iCol of the current row.
176218 **
176219 ** If parameter iCol is greater than or equal to the number of columns
176220 ** in the table, SQLITE_RANGE is returned. Or, if an error occurs (e.g.
176221 ** an OOM condition or IO error), an appropriate SQLite error code is
176222 ** returned.
176223 **
176224 ** This function may be quite inefficient if used with an FTS5 table
176225 ** created with the "columnsize=0" option.
176226 **
176227 ** xColumnText:
176228 ** This function attempts to retrieve the text of column iCol of the
176229 ** current document. If successful, (*pz) is set to point to a buffer
176230 ** containing the text in utf-8 encoding, (*pn) is set to the size in bytes
176231 ** (not characters) of the buffer and SQLITE_OK is returned. Otherwise,
176232 ** if an error occurs, an SQLite error code is returned and the final values
176233 ** of (*pz) and (*pn) are undefined.
176234 **
176235 ** xPhraseCount:
176236 ** Returns the number of phrases in the current query expression.
176237 **
176238 ** xPhraseSize:
176239 ** Returns the number of tokens in phrase iPhrase of the query. Phrases
176240 ** are numbered starting from zero.
176241 **
176242 ** xInstCount:
176243 ** Set *pnInst to the total number of occurrences of all phrases within
176244 ** the query within the current row. Return SQLITE_OK if successful, or
176245 ** an error code (i.e. SQLITE_NOMEM) if an error occurs.
176246 **
176247 ** This API can be quite slow if used with an FTS5 table created with the
176248 ** "detail=none" or "detail=column" option. If the FTS5 table is created
176249 ** with either "detail=none" or "detail=column" and "content=" option
176250 ** (i.e. if it is a contentless table), then this API always returns 0.
176251 **
176252 ** xInst:
176253 ** Query for the details of phrase match iIdx within the current row.
176254 ** Phrase matches are numbered starting from zero, so the iIdx argument
176255 ** should be greater than or equal to zero and smaller than the value
176256 ** output by xInstCount().
176257 **
176258 ** Usually, output parameter *piPhrase is set to the phrase number, *piCol
176259 ** to the column in which it occurs and *piOff the token offset of the
176260 ** first token of the phrase. The exception is if the table was created
176261 ** with the offsets=0 option specified. In this case *piOff is always
176262 ** set to -1.
176263 **
176264 ** Returns SQLITE_OK if successful, or an error code (i.e. SQLITE_NOMEM)
176265 ** if an error occurs.
176266 **
176267 ** This API can be quite slow if used with an FTS5 table created with the
176268 ** "detail=none" or "detail=column" option.
176269 **
176270 ** xRowid:
176271 ** Returns the rowid of the current row.
176272 **
176273 ** xTokenize:
176274 ** Tokenize text using the tokenizer belonging to the FTS5 table.
176275 **
176276 ** xQueryPhrase(pFts5, iPhrase, pUserData, xCallback):
176277 ** This API function is used to query the FTS table for phrase iPhrase
176278 ** of the current query. Specifically, a query equivalent to:
176279 **
176280 ** ... FROM ftstable WHERE ftstable MATCH $p ORDER BY rowid
176281 **
176282 ** with $p set to a phrase equivalent to the phrase iPhrase of the
176283 ** current query is executed. Any column filter that applies to
176284 ** phrase iPhrase of the current query is included in $p. For each
176285 ** row visited, the callback function passed as the fourth argument
176286 ** is invoked. The context and API objects passed to the callback
176287 ** function may be used to access the properties of each matched row.
176288 ** Invoking Api.xUserData() returns a copy of the pointer passed as
176289 ** the third argument to pUserData.
176290 **
176291 ** If the callback function returns any value other than SQLITE_OK, the
176292 ** query is abandoned and the xQueryPhrase function returns immediately.
176293 ** If the returned value is SQLITE_DONE, xQueryPhrase returns SQLITE_OK.
176294 ** Otherwise, the error code is propagated upwards.
176295 **
176296 ** If the query runs to completion without incident, SQLITE_OK is returned.
176297 ** Or, if some error occurs before the query completes or is aborted by
176298 ** the callback, an SQLite error code is returned.
176299 **
176300 **
176301 ** xSetAuxdata(pFts5, pAux, xDelete)
176302 **
176303 ** Save the pointer passed as the second argument as the extension functions
176304 ** "auxiliary data". The pointer may then be retrieved by the current or any
176305 ** future invocation of the same fts5 extension function made as part of
176306 ** of the same MATCH query using the xGetAuxdata() API.
176307 **
176308 ** Each extension function is allocated a single auxiliary data slot for
176309 ** each FTS query (MATCH expression). If the extension function is invoked
176310 ** more than once for a single FTS query, then all invocations share a
176311 ** single auxiliary data context.
176312 **
176313 ** If there is already an auxiliary data pointer when this function is
176314 ** invoked, then it is replaced by the new pointer. If an xDelete callback
176315 ** was specified along with the original pointer, it is invoked at this
176316 ** point.
176317 **
176318 ** The xDelete callback, if one is specified, is also invoked on the
176319 ** auxiliary data pointer after the FTS5 query has finished.
176320 **
176321 ** If an error (e.g. an OOM condition) occurs within this function, an
176322 ** the auxiliary data is set to NULL and an error code returned. If the
176323 ** xDelete parameter was not NULL, it is invoked on the auxiliary data
176324 ** pointer before returning.
176325 **
176326 **
176327 ** xGetAuxdata(pFts5, bClear)
176328 **
176329 ** Returns the current auxiliary data pointer for the fts5 extension
176330 ** function. See the xSetAuxdata() method for details.
176331 **
176332 ** If the bClear argument is non-zero, then the auxiliary data is cleared
176333 ** (set to NULL) before this function returns. In this case the xDelete,
176334 ** if any, is not invoked.
176335 **
176336 **
176337 ** xRowCount(pFts5, pnRow)
176338 **
176339 ** This function is used to retrieve the total number of rows in the table.
176340 ** In other words, the same value that would be returned by:
176341 **
176342 ** SELECT count(*) FROM ftstable;
176343 **
176344 ** xPhraseFirst()
176345 ** This function is used, along with type Fts5PhraseIter and the xPhraseNext
176346 ** method, to iterate through all instances of a single query phrase within
176347 ** the current row. This is the same information as is accessible via the
176348 ** xInstCount/xInst APIs. While the xInstCount/xInst APIs are more convenient
176349 ** to use, this API may be faster under some circumstances. To iterate
176350 ** through instances of phrase iPhrase, use the following code:
176351 **
176352 ** Fts5PhraseIter iter;
176353 ** int iCol, iOff;
176354 ** for(pApi->xPhraseFirst(pFts, iPhrase, &iter, &iCol, &iOff);
176355 ** iCol>=0;
176356 ** pApi->xPhraseNext(pFts, &iter, &iCol, &iOff)
176357 ** ){
176358 ** // An instance of phrase iPhrase at offset iOff of column iCol
176359 ** }
176360 **
176361 ** The Fts5PhraseIter structure is defined above. Applications should not
176362 ** modify this structure directly - it should only be used as shown above
176363 ** with the xPhraseFirst() and xPhraseNext() API methods (and by
176364 ** xPhraseFirstColumn() and xPhraseNextColumn() as illustrated below).
176365 **
176366 ** This API can be quite slow if used with an FTS5 table created with the
176367 ** "detail=none" or "detail=column" option. If the FTS5 table is created
176368 ** with either "detail=none" or "detail=column" and "content=" option
176369 ** (i.e. if it is a contentless table), then this API always iterates
176370 ** through an empty set (all calls to xPhraseFirst() set iCol to -1).
176371 **
176372 ** xPhraseNext()
176373 ** See xPhraseFirst above.
176374 **
176375 ** xPhraseFirstColumn()
176376 ** This function and xPhraseNextColumn() are similar to the xPhraseFirst()
176377 ** and xPhraseNext() APIs described above. The difference is that instead
176378 ** of iterating through all instances of a phrase in the current row, these
176379 ** APIs are used to iterate through the set of columns in the current row
176380 ** that contain one or more instances of a specified phrase. For example:
176381 **
176382 ** Fts5PhraseIter iter;
176383 ** int iCol;
176384 ** for(pApi->xPhraseFirstColumn(pFts, iPhrase, &iter, &iCol);
176385 ** iCol>=0;
176386 ** pApi->xPhraseNextColumn(pFts, &iter, &iCol)
176387 ** ){
176388 ** // Column iCol contains at least one instance of phrase iPhrase
176389 ** }
176390 **
176391 ** This API can be quite slow if used with an FTS5 table created with the
176392 ** "detail=none" option. If the FTS5 table is created with either
176393 ** "detail=none" "content=" option (i.e. if it is a contentless table),
176394 ** then this API always iterates through an empty set (all calls to
176395 ** xPhraseFirstColumn() set iCol to -1).
176396 **
176397 ** The information accessed using this API and its companion
176398 ** xPhraseFirstColumn() may also be obtained using xPhraseFirst/xPhraseNext
176399 ** (or xInst/xInstCount). The chief advantage of this API is that it is
176400 ** significantly more efficient than those alternatives when used with
176401 ** "detail=column" tables.
176402 **
176403 ** xPhraseNextColumn()
176404 ** See xPhraseFirstColumn above.
176405 */
176406 struct Fts5ExtensionApi {
176407  int iVersion; /* Currently always set to 3 */
176408 
176409  void *(*xUserData)(Fts5Context*);
176410 
176411  int (*xColumnCount)(Fts5Context*);
176412  int (*xRowCount)(Fts5Context*, sqlite3_int64 *pnRow);
176413  int (*xColumnTotalSize)(Fts5Context*, int iCol, sqlite3_int64 *pnToken);
176414 
176415  int (*xTokenize)(Fts5Context*,
176416  const char *pText, int nText, /* Text to tokenize */
176417  void *pCtx, /* Context passed to xToken() */
176418  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
176419  );
176420 
176421  int (*xPhraseCount)(Fts5Context*);
176422  int (*xPhraseSize)(Fts5Context*, int iPhrase);
176423 
176424  int (*xInstCount)(Fts5Context*, int *pnInst);
176425  int (*xInst)(Fts5Context*, int iIdx, int *piPhrase, int *piCol, int *piOff);
176426 
176427  sqlite3_int64 (*xRowid)(Fts5Context*);
176428  int (*xColumnText)(Fts5Context*, int iCol, const char **pz, int *pn);
176429  int (*xColumnSize)(Fts5Context*, int iCol, int *pnToken);
176430 
176431  int (*xQueryPhrase)(Fts5Context*, int iPhrase, void *pUserData,
176432  int(*)(const Fts5ExtensionApi*,Fts5Context*,void*)
176433  );
176434  int (*xSetAuxdata)(Fts5Context*, void *pAux, void(*xDelete)(void*));
176435  void *(*xGetAuxdata)(Fts5Context*, int bClear);
176436 
176437  int (*xPhraseFirst)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*, int*);
176438  void (*xPhraseNext)(Fts5Context*, Fts5PhraseIter*, int *piCol, int *piOff);
176439 
176440  int (*xPhraseFirstColumn)(Fts5Context*, int iPhrase, Fts5PhraseIter*, int*);
176441  void (*xPhraseNextColumn)(Fts5Context*, Fts5PhraseIter*, int *piCol);
176442 };
176443 
176444 /*
176445 ** CUSTOM AUXILIARY FUNCTIONS
176446 *************************************************************************/
176447 
176448 /*************************************************************************
176449 ** CUSTOM TOKENIZERS
176450 **
176451 ** Applications may also register custom tokenizer types. A tokenizer
176452 ** is registered by providing fts5 with a populated instance of the
176453 ** following structure. All structure methods must be defined, setting
176454 ** any member of the fts5_tokenizer struct to NULL leads to undefined
176455 ** behaviour. The structure methods are expected to function as follows:
176456 **
176457 ** xCreate:
176458 ** This function is used to allocate and inititalize a tokenizer instance.
176459 ** A tokenizer instance is required to actually tokenize text.
176460 **
176461 ** The first argument passed to this function is a copy of the (void*)
176462 ** pointer provided by the application when the fts5_tokenizer object
176463 ** was registered with FTS5 (the third argument to xCreateTokenizer()).
176464 ** The second and third arguments are an array of nul-terminated strings
176465 ** containing the tokenizer arguments, if any, specified following the
176466 ** tokenizer name as part of the CREATE VIRTUAL TABLE statement used
176467 ** to create the FTS5 table.
176468 **
176469 ** The final argument is an output variable. If successful, (*ppOut)
176470 ** should be set to point to the new tokenizer handle and SQLITE_OK
176471 ** returned. If an error occurs, some value other than SQLITE_OK should
176472 ** be returned. In this case, fts5 assumes that the final value of *ppOut
176473 ** is undefined.
176474 **
176475 ** xDelete:
176476 ** This function is invoked to delete a tokenizer handle previously
176477 ** allocated using xCreate(). Fts5 guarantees that this function will
176478 ** be invoked exactly once for each successful call to xCreate().
176479 **
176480 ** xTokenize:
176481 ** This function is expected to tokenize the nText byte string indicated
176482 ** by argument pText. pText may or may not be nul-terminated. The first
176483 ** argument passed to this function is a pointer to an Fts5Tokenizer object
176484 ** returned by an earlier call to xCreate().
176485 **
176486 ** The second argument indicates the reason that FTS5 is requesting
176487 ** tokenization of the supplied text. This is always one of the following
176488 ** four values:
176489 **
176490 ** <ul><li> <b>FTS5_TOKENIZE_DOCUMENT</b> - A document is being inserted into
176491 ** or removed from the FTS table. The tokenizer is being invoked to
176492 ** determine the set of tokens to add to (or delete from) the
176493 ** FTS index.
176494 **
176495 ** <li> <b>FTS5_TOKENIZE_QUERY</b> - A MATCH query is being executed
176496 ** against the FTS index. The tokenizer is being called to tokenize
176497 ** a bareword or quoted string specified as part of the query.
176498 **
176499 ** <li> <b>(FTS5_TOKENIZE_QUERY | FTS5_TOKENIZE_PREFIX)</b> - Same as
176500 ** FTS5_TOKENIZE_QUERY, except that the bareword or quoted string is
176501 ** followed by a "*" character, indicating that the last token
176502 ** returned by the tokenizer will be treated as a token prefix.
176503 **
176504 ** <li> <b>FTS5_TOKENIZE_AUX</b> - The tokenizer is being invoked to
176505 ** satisfy an fts5_api.xTokenize() request made by an auxiliary
176506 ** function. Or an fts5_api.xColumnSize() request made by the same
176507 ** on a columnsize=0 database.
176508 ** </ul>
176509 **
176510 ** For each token in the input string, the supplied callback xToken() must
176511 ** be invoked. The first argument to it should be a copy of the pointer
176512 ** passed as the second argument to xTokenize(). The third and fourth
176513 ** arguments are a pointer to a buffer containing the token text, and the
176514 ** size of the token in bytes. The 4th and 5th arguments are the byte offsets
176515 ** of the first byte of and first byte immediately following the text from
176516 ** which the token is derived within the input.
176517 **
176518 ** The second argument passed to the xToken() callback ("tflags") should
176519 ** normally be set to 0. The exception is if the tokenizer supports
176520 ** synonyms. In this case see the discussion below for details.
176521 **
176522 ** FTS5 assumes the xToken() callback is invoked for each token in the
176523 ** order that they occur within the input text.
176524 **
176525 ** If an xToken() callback returns any value other than SQLITE_OK, then
176526 ** the tokenization should be abandoned and the xTokenize() method should
176527 ** immediately return a copy of the xToken() return value. Or, if the
176528 ** input buffer is exhausted, xTokenize() should return SQLITE_OK. Finally,
176529 ** if an error occurs with the xTokenize() implementation itself, it
176530 ** may abandon the tokenization and return any error code other than
176531 ** SQLITE_OK or SQLITE_DONE.
176532 **
176533 ** SYNONYM SUPPORT
176534 **
176535 ** Custom tokenizers may also support synonyms. Consider a case in which a
176536 ** user wishes to query for a phrase such as "first place". Using the
176537 ** built-in tokenizers, the FTS5 query 'first + place' will match instances
176538 ** of "first place" within the document set, but not alternative forms
176539 ** such as "1st place". In some applications, it would be better to match
176540 ** all instances of "first place" or "1st place" regardless of which form
176541 ** the user specified in the MATCH query text.
176542 **
176543 ** There are several ways to approach this in FTS5:
176544 **
176545 ** <ol><li> By mapping all synonyms to a single token. In this case, the
176546 ** In the above example, this means that the tokenizer returns the
176547 ** same token for inputs "first" and "1st". Say that token is in
176548 ** fact "first", so that when the user inserts the document "I won
176549 ** 1st place" entries are added to the index for tokens "i", "won",
176550 ** "first" and "place". If the user then queries for '1st + place',
176551 ** the tokenizer substitutes "first" for "1st" and the query works
176552 ** as expected.
176553 **
176554 ** <li> By adding multiple synonyms for a single term to the FTS index.
176555 ** In this case, when tokenizing query text, the tokenizer may
176556 ** provide multiple synonyms for a single term within the document.
176557 ** FTS5 then queries the index for each synonym individually. For
176558 ** example, faced with the query:
176559 **
176560 ** <codeblock>
176561 ** ... MATCH 'first place'</codeblock>
176562 **
176563 ** the tokenizer offers both "1st" and "first" as synonyms for the
176564 ** first token in the MATCH query and FTS5 effectively runs a query
176565 ** similar to:
176566 **
176567 ** <codeblock>
176568 ** ... MATCH '(first OR 1st) place'</codeblock>
176569 **
176570 ** except that, for the purposes of auxiliary functions, the query
176571 ** still appears to contain just two phrases - "(first OR 1st)"
176572 ** being treated as a single phrase.
176573 **
176574 ** <li> By adding multiple synonyms for a single term to the FTS index.
176575 ** Using this method, when tokenizing document text, the tokenizer
176576 ** provides multiple synonyms for each token. So that when a
176577 ** document such as "I won first place" is tokenized, entries are
176578 ** added to the FTS index for "i", "won", "first", "1st" and
176579 ** "place".
176580 **
176581 ** This way, even if the tokenizer does not provide synonyms
176582 ** when tokenizing query text (it should not - to do would be
176583 ** inefficient), it doesn't matter if the user queries for
176584 ** 'first + place' or '1st + place', as there are entires in the
176585 ** FTS index corresponding to both forms of the first token.
176586 ** </ol>
176587 **
176588 ** Whether it is parsing document or query text, any call to xToken that
176589 ** specifies a <i>tflags</i> argument with the FTS5_TOKEN_COLOCATED bit
176590 ** is considered to supply a synonym for the previous token. For example,
176591 ** when parsing the document "I won first place", a tokenizer that supports
176592 ** synonyms would call xToken() 5 times, as follows:
176593 **
176594 ** <codeblock>
176595 ** xToken(pCtx, 0, "i", 1, 0, 1);
176596 ** xToken(pCtx, 0, "won", 3, 2, 5);
176597 ** xToken(pCtx, 0, "first", 5, 6, 11);
176598 ** xToken(pCtx, FTS5_TOKEN_COLOCATED, "1st", 3, 6, 11);
176599 ** xToken(pCtx, 0, "place", 5, 12, 17);
176600 **</codeblock>
176601 **
176602 ** It is an error to specify the FTS5_TOKEN_COLOCATED flag the first time
176603 ** xToken() is called. Multiple synonyms may be specified for a single token
176604 ** by making multiple calls to xToken(FTS5_TOKEN_COLOCATED) in sequence.
176605 ** There is no limit to the number of synonyms that may be provided for a
176606 ** single token.
176607 **
176608 ** In many cases, method (1) above is the best approach. It does not add
176609 ** extra data to the FTS index or require FTS5 to query for multiple terms,
176610 ** so it is efficient in terms of disk space and query speed. However, it
176611 ** does not support prefix queries very well. If, as suggested above, the
176612 ** token "first" is subsituted for "1st" by the tokenizer, then the query:
176613 **
176614 ** <codeblock>
176615 ** ... MATCH '1s*'</codeblock>
176616 **
176617 ** will not match documents that contain the token "1st" (as the tokenizer
176618 ** will probably not map "1s" to any prefix of "first").
176619 **
176620 ** For full prefix support, method (3) may be preferred. In this case,
176621 ** because the index contains entries for both "first" and "1st", prefix
176622 ** queries such as 'fi*' or '1s*' will match correctly. However, because
176623 ** extra entries are added to the FTS index, this method uses more space
176624 ** within the database.
176625 **
176626 ** Method (2) offers a midpoint between (1) and (3). Using this method,
176627 ** a query such as '1s*' will match documents that contain the literal
176628 ** token "1st", but not "first" (assuming the tokenizer is not able to
176629 ** provide synonyms for prefixes). However, a non-prefix query like '1st'
176630 ** will match against "1st" and "first". This method does not require
176631 ** extra disk space, as no extra entries are added to the FTS index.
176632 ** On the other hand, it may require more CPU cycles to run MATCH queries,
176633 ** as separate queries of the FTS index are required for each synonym.
176634 **
176635 ** When using methods (2) or (3), it is important that the tokenizer only
176636 ** provide synonyms when tokenizing document text (method (2)) or query
176637 ** text (method (3)), not both. Doing so will not cause any errors, but is
176638 ** inefficient.
176639 */
176640 typedef struct Fts5Tokenizer Fts5Tokenizer;
176641 typedef struct fts5_tokenizer fts5_tokenizer;
176642 struct fts5_tokenizer {
176643  int (*xCreate)(void*, const char **azArg, int nArg, Fts5Tokenizer **ppOut);
176644  void (*xDelete)(Fts5Tokenizer*);
176645  int (*xTokenize)(Fts5Tokenizer*,
176646  void *pCtx,
176647  int flags, /* Mask of FTS5_TOKENIZE_* flags */
176648  const char *pText, int nText,
176649  int (*xToken)(
176650  void *pCtx, /* Copy of 2nd argument to xTokenize() */
176651  int tflags, /* Mask of FTS5_TOKEN_* flags */
176652  const char *pToken, /* Pointer to buffer containing token */
176653  int nToken, /* Size of token in bytes */
176654  int iStart, /* Byte offset of token within input text */
176655  int iEnd /* Byte offset of end of token within input text */
176656  )
176657  );
176658 };
176659 
176660 /* Flags that may be passed as the third argument to xTokenize() */
176661 #define FTS5_TOKENIZE_QUERY 0x0001
176662 #define FTS5_TOKENIZE_PREFIX 0x0002
176663 #define FTS5_TOKENIZE_DOCUMENT 0x0004
176664 #define FTS5_TOKENIZE_AUX 0x0008
176665 
176666 /* Flags that may be passed by the tokenizer implementation back to FTS5
176667 ** as the third argument to the supplied xToken callback. */
176668 #define FTS5_TOKEN_COLOCATED 0x0001 /* Same position as prev. token */
176669 
176670 /*
176671 ** END OF CUSTOM TOKENIZERS
176672 *************************************************************************/
176673 
176674 /*************************************************************************
176675 ** FTS5 EXTENSION REGISTRATION API
176676 */
176677 typedef struct fts5_api fts5_api;
176678 struct fts5_api {
176679  int iVersion; /* Currently always set to 2 */
176680 
176681  /* Create a new tokenizer */
176682  int (*xCreateTokenizer)(
176683  fts5_api *pApi,
176684  const char *zName,
176685  void *pContext,
176686  fts5_tokenizer *pTokenizer,
176687  void (*xDestroy)(void*)
176688  );
176689 
176690  /* Find an existing tokenizer */
176691  int (*xFindTokenizer)(
176692  fts5_api *pApi,
176693  const char *zName,
176694  void **ppContext,
176695  fts5_tokenizer *pTokenizer
176696  );
176697 
176698  /* Create a new auxiliary function */
176699  int (*xCreateFunction)(
176700  fts5_api *pApi,
176701  const char *zName,
176702  void *pContext,
176703  fts5_extension_function xFunction,
176704  void (*xDestroy)(void*)
176705  );
176706 };
176707 
176708 /*
176709 ** END OF REGISTRATION API
176710 *************************************************************************/
176711 
176712 #if 0
176713 } /* end of the 'extern "C"' block */
176714 #endif
176715 
176716 #endif /* _FTS5_H */
176717 
176718 
176719 /*
176720 ** 2014 May 31
176721 **
176722 ** The author disclaims copyright to this source code. In place of
176723 ** a legal notice, here is a blessing:
176724 **
176725 ** May you do good and not evil.
176726 ** May you find forgiveness for yourself and forgive others.
176727 ** May you share freely, never taking more than you give.
176728 **
176729 ******************************************************************************
176730 **
176731 */
176732 #ifndef _FTS5INT_H
176733 #define _FTS5INT_H
176734 
176735 /* #include "fts5.h" */
176736 /* #include "sqlite3ext.h" */
176738 
176739 /* #include <string.h> */
176740 /* #include <assert.h> */
176741 
176742 #ifndef SQLITE_AMALGAMATION
176743 
176744 typedef unsigned char u8;
176745 typedef unsigned int u32;
176746 typedef unsigned short u16;
176747 typedef short i16;
176748 typedef sqlite3_int64 i64;
176749 typedef sqlite3_uint64 u64;
176750 
176751 #define ArraySize(x) ((int)(sizeof(x) / sizeof(x[0])))
176752 
176753 #define testcase(x)
176754 #define ALWAYS(x) 1
176755 #define NEVER(x) 0
176756 
176757 #define MIN(x,y) (((x) < (y)) ? (x) : (y))
176758 #define MAX(x,y) (((x) > (y)) ? (x) : (y))
176759 
176760 /*
176761 ** Constants for the largest and smallest possible 64-bit signed integers.
176762 */
176763 # define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
176764 # define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
176765 
176766 #endif
176767 
176768 /* Truncate very long tokens to this many bytes. Hard limit is
176769 ** (65536-1-1-4-9)==65521 bytes. The limiting factor is the 16-bit offset
176770 ** field that occurs at the start of each leaf page (see fts5_index.c). */
176771 #define FTS5_MAX_TOKEN_SIZE 32768
176772 
176773 /*
176774 ** Maximum number of prefix indexes on single FTS5 table. This must be
176775 ** less than 32. If it is set to anything large than that, an #error
176776 ** directive in fts5_index.c will cause the build to fail.
176777 */
176778 #define FTS5_MAX_PREFIX_INDEXES 31
176779 
176780 #define FTS5_DEFAULT_NEARDIST 10
176781 #define FTS5_DEFAULT_RANK "bm25"
176782 
176783 /* Name of rank and rowid columns */
176784 #define FTS5_RANK_NAME "rank"
176785 #define FTS5_ROWID_NAME "rowid"
176786 
176787 #ifdef SQLITE_DEBUG
176788 # define FTS5_CORRUPT sqlite3Fts5Corrupt()
176789 static int sqlite3Fts5Corrupt(void);
176790 #else
176791 # define FTS5_CORRUPT SQLITE_CORRUPT_VTAB
176792 #endif
176793 
176794 /*
176795 ** The assert_nc() macro is similar to the assert() macro, except that it
176796 ** is used for assert() conditions that are true only if it can be
176797 ** guranteed that the database is not corrupt.
176798 */
176799 #ifdef SQLITE_DEBUG
176800 SQLITE_API extern int sqlite3_fts5_may_be_corrupt;
176801 # define assert_nc(x) assert(sqlite3_fts5_may_be_corrupt || (x))
176802 #else
176803 # define assert_nc(x) assert(x)
176804 #endif
176805 
176806 /* Mark a function parameter as unused, to suppress nuisance compiler
176807 ** warnings. */
176808 #ifndef UNUSED_PARAM
176809 # define UNUSED_PARAM(X) (void)(X)
176810 #endif
176811 
176812 #ifndef UNUSED_PARAM2
176813 # define UNUSED_PARAM2(X, Y) (void)(X), (void)(Y)
176814 #endif
176815 
176816 typedef struct Fts5Global Fts5Global;
176817 typedef struct Fts5Colset Fts5Colset;
176818 
176819 /* If a NEAR() clump or phrase may only match a specific set of columns,
176820 ** then an object of the following type is used to record the set of columns.
176821 ** Each entry in the aiCol[] array is a column that may be matched.
176822 **
176823 ** This object is used by fts5_expr.c and fts5_index.c.
176824 */
176825 struct Fts5Colset {
176826  int nCol;
176827  int aiCol[1];
176828 };
176829 
176830 
176831 
176832 /**************************************************************************
176833 ** Interface to code in fts5_config.c. fts5_config.c contains contains code
176834 ** to parse the arguments passed to the CREATE VIRTUAL TABLE statement.
176835 */
176836 
176837 typedef struct Fts5Config Fts5Config;
176838 
176839 /*
176840 ** An instance of the following structure encodes all information that can
176841 ** be gleaned from the CREATE VIRTUAL TABLE statement.
176842 **
176843 ** And all information loaded from the %_config table.
176844 **
176845 ** nAutomerge:
176846 ** The minimum number of segments that an auto-merge operation should
176847 ** attempt to merge together. A value of 1 sets the object to use the
176848 ** compile time default. Zero disables auto-merge altogether.
176849 **
176850 ** zContent:
176851 **
176852 ** zContentRowid:
176853 ** The value of the content_rowid= option, if one was specified. Or
176854 ** the string "rowid" otherwise. This text is not quoted - if it is
176855 ** used as part of an SQL statement it needs to be quoted appropriately.
176856 **
176857 ** zContentExprlist:
176858 **
176859 ** pzErrmsg:
176860 ** This exists in order to allow the fts5_index.c module to return a
176861 ** decent error message if it encounters a file-format version it does
176862 ** not understand.
176863 **
176864 ** bColumnsize:
176865 ** True if the %_docsize table is created.
176866 **
176867 ** bPrefixIndex:
176868 ** This is only used for debugging. If set to false, any prefix indexes
176869 ** are ignored. This value is configured using:
176870 **
176871 ** INSERT INTO tbl(tbl, rank) VALUES('prefix-index', $bPrefixIndex);
176872 **
176873 */
176874 struct Fts5Config {
176875  sqlite3 *db; /* Database handle */
176876  char *zDb; /* Database holding FTS index (e.g. "main") */
176877  char *zName; /* Name of FTS index */
176878  int nCol; /* Number of columns */
176879  char **azCol; /* Column names */
176880  u8 *abUnindexed; /* True for unindexed columns */
176881  int nPrefix; /* Number of prefix indexes */
176882  int *aPrefix; /* Sizes in bytes of nPrefix prefix indexes */
176883  int eContent; /* An FTS5_CONTENT value */
176884  char *zContent; /* content table */
176885  char *zContentRowid; /* "content_rowid=" option value */
176886  int bColumnsize; /* "columnsize=" option value (dflt==1) */
176887  int eDetail; /* FTS5_DETAIL_XXX value */
176888  char *zContentExprlist;
176889  Fts5Tokenizer *pTok;
176890  fts5_tokenizer *pTokApi;
176891 
176892  /* Values loaded from the %_config table */
176893  int iCookie; /* Incremented when %_config is modified */
176894  int pgsz; /* Approximate page size used in %_data */
176895  int nAutomerge; /* 'automerge' setting */
176896  int nCrisisMerge; /* Maximum allowed segments per level */
176897  int nUsermerge; /* 'usermerge' setting */
176898  int nHashSize; /* Bytes of memory for in-memory hash */
176899  char *zRank; /* Name of rank function */
176900  char *zRankArgs; /* Arguments to rank function */
176901 
176902  /* If non-NULL, points to sqlite3_vtab.base.zErrmsg. Often NULL. */
176903  char **pzErrmsg;
176904 
176905 #ifdef SQLITE_DEBUG
176906  int bPrefixIndex; /* True to use prefix-indexes */
176907 #endif
176908 };
176909 
176910 /* Current expected value of %_config table 'version' field */
176911 #define FTS5_CURRENT_VERSION 4
176912 
176913 #define FTS5_CONTENT_NORMAL 0
176914 #define FTS5_CONTENT_NONE 1
176915 #define FTS5_CONTENT_EXTERNAL 2
176916 
176917 #define FTS5_DETAIL_FULL 0
176918 #define FTS5_DETAIL_NONE 1
176919 #define FTS5_DETAIL_COLUMNS 2
176920 
176921 
176922 
176923 static int sqlite3Fts5ConfigParse(
176924  Fts5Global*, sqlite3*, int, const char **, Fts5Config**, char**
176925 );
176926 static void sqlite3Fts5ConfigFree(Fts5Config*);
176927 
176928 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig);
176929 
176930 static int sqlite3Fts5Tokenize(
176931  Fts5Config *pConfig, /* FTS5 Configuration object */
176932  int flags, /* FTS5_TOKENIZE_* flags */
176933  const char *pText, int nText, /* Text to tokenize */
176934  void *pCtx, /* Context passed to xToken() */
176935  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
176936 );
176937 
176938 static void sqlite3Fts5Dequote(char *z);
176939 
176940 /* Load the contents of the %_config table */
176941 static int sqlite3Fts5ConfigLoad(Fts5Config*, int);
176942 
176943 /* Set the value of a single config attribute */
176944 static int sqlite3Fts5ConfigSetValue(Fts5Config*, const char*, sqlite3_value*, int*);
176945 
176946 static int sqlite3Fts5ConfigParseRank(const char*, char**, char**);
176947 
176948 /*
176949 ** End of interface to code in fts5_config.c.
176950 **************************************************************************/
176951 
176952 /**************************************************************************
176953 ** Interface to code in fts5_buffer.c.
176954 */
176955 
176956 /*
176957 ** Buffer object for the incremental building of string data.
176958 */
176959 typedef struct Fts5Buffer Fts5Buffer;
176960 struct Fts5Buffer {
176961  u8 *p;
176962  int n;
176963  int nSpace;
176964 };
176965 
176966 static int sqlite3Fts5BufferSize(int*, Fts5Buffer*, u32);
176967 static void sqlite3Fts5BufferAppendVarint(int*, Fts5Buffer*, i64);
176968 static void sqlite3Fts5BufferAppendBlob(int*, Fts5Buffer*, u32, const u8*);
176969 static void sqlite3Fts5BufferAppendString(int *, Fts5Buffer*, const char*);
176970 static void sqlite3Fts5BufferFree(Fts5Buffer*);
176971 static void sqlite3Fts5BufferZero(Fts5Buffer*);
176972 static void sqlite3Fts5BufferSet(int*, Fts5Buffer*, int, const u8*);
176973 static void sqlite3Fts5BufferAppendPrintf(int *, Fts5Buffer*, char *zFmt, ...);
176974 
176975 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...);
176976 
176977 #define fts5BufferZero(x) sqlite3Fts5BufferZero(x)
176978 #define fts5BufferAppendVarint(a,b,c) sqlite3Fts5BufferAppendVarint(a,b,c)
176979 #define fts5BufferFree(a) sqlite3Fts5BufferFree(a)
176980 #define fts5BufferAppendBlob(a,b,c,d) sqlite3Fts5BufferAppendBlob(a,b,c,d)
176981 #define fts5BufferSet(a,b,c,d) sqlite3Fts5BufferSet(a,b,c,d)
176982 
176983 #define fts5BufferGrow(pRc,pBuf,nn) ( \
176984  (u32)((pBuf)->n) + (u32)(nn) <= (u32)((pBuf)->nSpace) ? 0 : \
176985  sqlite3Fts5BufferSize((pRc),(pBuf),(nn)+(pBuf)->n) \
176986 )
176987 
176988 /* Write and decode big-endian 32-bit integer values */
176989 static void sqlite3Fts5Put32(u8*, int);
176990 static int sqlite3Fts5Get32(const u8*);
176991 
176992 #define FTS5_POS2COLUMN(iPos) (int)(iPos >> 32)
176993 #define FTS5_POS2OFFSET(iPos) (int)(iPos & 0xFFFFFFFF)
176994 
176995 typedef struct Fts5PoslistReader Fts5PoslistReader;
176996 struct Fts5PoslistReader {
176997  /* Variables used only by sqlite3Fts5PoslistIterXXX() functions. */
176998  const u8 *a; /* Position list to iterate through */
176999  int n; /* Size of buffer at a[] in bytes */
177000  int i; /* Current offset in a[] */
177001 
177002  u8 bFlag; /* For client use (any custom purpose) */
177003 
177004  /* Output variables */
177005  u8 bEof; /* Set to true at EOF */
177006  i64 iPos; /* (iCol<<32) + iPos */
177007 };
177008 static int sqlite3Fts5PoslistReaderInit(
177009  const u8 *a, int n, /* Poslist buffer to iterate through */
177010  Fts5PoslistReader *pIter /* Iterator object to initialize */
177011 );
177012 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader*);
177013 
177014 typedef struct Fts5PoslistWriter Fts5PoslistWriter;
177015 struct Fts5PoslistWriter {
177016  i64 iPrev;
177017 };
177018 static int sqlite3Fts5PoslistWriterAppend(Fts5Buffer*, Fts5PoslistWriter*, i64);
177019 static void sqlite3Fts5PoslistSafeAppend(Fts5Buffer*, i64*, i64);
177020 
177021 static int sqlite3Fts5PoslistNext64(
177022  const u8 *a, int n, /* Buffer containing poslist */
177023  int *pi, /* IN/OUT: Offset within a[] */
177024  i64 *piOff /* IN/OUT: Current offset */
177025 );
177026 
177027 /* Malloc utility */
177028 static void *sqlite3Fts5MallocZero(int *pRc, int nByte);
177029 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn);
177030 
177031 /* Character set tests (like isspace(), isalpha() etc.) */
177032 static int sqlite3Fts5IsBareword(char t);
177033 
177034 
177035 /* Bucket of terms object used by the integrity-check in offsets=0 mode. */
177036 typedef struct Fts5Termset Fts5Termset;
177037 static int sqlite3Fts5TermsetNew(Fts5Termset**);
177038 static int sqlite3Fts5TermsetAdd(Fts5Termset*, int, const char*, int, int *pbPresent);
177039 static void sqlite3Fts5TermsetFree(Fts5Termset*);
177040 
177041 /*
177042 ** End of interface to code in fts5_buffer.c.
177043 **************************************************************************/
177044 
177045 /**************************************************************************
177046 ** Interface to code in fts5_index.c. fts5_index.c contains contains code
177047 ** to access the data stored in the %_data table.
177048 */
177049 
177050 typedef struct Fts5Index Fts5Index;
177051 typedef struct Fts5IndexIter Fts5IndexIter;
177052 
177053 struct Fts5IndexIter {
177054  i64 iRowid;
177055  const u8 *pData;
177056  int nData;
177057  u8 bEof;
177058 };
177059 
177060 #define sqlite3Fts5IterEof(x) ((x)->bEof)
177061 
177062 /*
177063 ** Values used as part of the flags argument passed to IndexQuery().
177064 */
177065 #define FTS5INDEX_QUERY_PREFIX 0x0001 /* Prefix query */
177066 #define FTS5INDEX_QUERY_DESC 0x0002 /* Docs in descending rowid order */
177067 #define FTS5INDEX_QUERY_TEST_NOIDX 0x0004 /* Do not use prefix index */
177068 #define FTS5INDEX_QUERY_SCAN 0x0008 /* Scan query (fts5vocab) */
177069 
177070 /* The following are used internally by the fts5_index.c module. They are
177071 ** defined here only to make it easier to avoid clashes with the flags
177072 ** above. */
177073 #define FTS5INDEX_QUERY_SKIPEMPTY 0x0010
177074 #define FTS5INDEX_QUERY_NOOUTPUT 0x0020
177075 
177076 /*
177077 ** Create/destroy an Fts5Index object.
177078 */
177079 static int sqlite3Fts5IndexOpen(Fts5Config *pConfig, int bCreate, Fts5Index**, char**);
177080 static int sqlite3Fts5IndexClose(Fts5Index *p);
177081 
177082 /*
177083 ** Return a simple checksum value based on the arguments.
177084 */
177085 static u64 sqlite3Fts5IndexEntryCksum(
177086  i64 iRowid,
177087  int iCol,
177088  int iPos,
177089  int iIdx,
177090  const char *pTerm,
177091  int nTerm
177092 );
177093 
177094 /*
177095 ** Argument p points to a buffer containing utf-8 text that is n bytes in
177096 ** size. Return the number of bytes in the nChar character prefix of the
177097 ** buffer, or 0 if there are less than nChar characters in total.
177098 */
177099 static int sqlite3Fts5IndexCharlenToBytelen(
177100  const char *p,
177101  int nByte,
177102  int nChar
177103 );
177104 
177105 /*
177106 ** Open a new iterator to iterate though all rowids that match the
177107 ** specified token or token prefix.
177108 */
177109 static int sqlite3Fts5IndexQuery(
177110  Fts5Index *p, /* FTS index to query */
177111  const char *pToken, int nToken, /* Token (or prefix) to query for */
177112  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
177113  Fts5Colset *pColset, /* Match these columns only */
177114  Fts5IndexIter **ppIter /* OUT: New iterator object */
177115 );
177116 
177117 /*
177118 ** The various operations on open token or token prefix iterators opened
177119 ** using sqlite3Fts5IndexQuery().
177120 */
177121 static int sqlite3Fts5IterNext(Fts5IndexIter*);
177122 static int sqlite3Fts5IterNextFrom(Fts5IndexIter*, i64 iMatch);
177123 
177124 /*
177125 ** Close an iterator opened by sqlite3Fts5IndexQuery().
177126 */
177127 static void sqlite3Fts5IterClose(Fts5IndexIter*);
177128 
177129 /*
177130 ** This interface is used by the fts5vocab module.
177131 */
177132 static const char *sqlite3Fts5IterTerm(Fts5IndexIter*, int*);
177133 static int sqlite3Fts5IterNextScan(Fts5IndexIter*);
177134 
177135 
177136 /*
177137 ** Insert or remove data to or from the index. Each time a document is
177138 ** added to or removed from the index, this function is called one or more
177139 ** times.
177140 **
177141 ** For an insert, it must be called once for each token in the new document.
177142 ** If the operation is a delete, it must be called (at least) once for each
177143 ** unique token in the document with an iCol value less than zero. The iPos
177144 ** argument is ignored for a delete.
177145 */
177146 static int sqlite3Fts5IndexWrite(
177147  Fts5Index *p, /* Index to write to */
177148  int iCol, /* Column token appears in (-ve -> delete) */
177149  int iPos, /* Position of token within column */
177150  const char *pToken, int nToken /* Token to add or remove to or from index */
177151 );
177152 
177153 /*
177154 ** Indicate that subsequent calls to sqlite3Fts5IndexWrite() pertain to
177155 ** document iDocid.
177156 */
177157 static int sqlite3Fts5IndexBeginWrite(
177158  Fts5Index *p, /* Index to write to */
177159  int bDelete, /* True if current operation is a delete */
177160  i64 iDocid /* Docid to add or remove data from */
177161 );
177162 
177163 /*
177164 ** Flush any data stored in the in-memory hash tables to the database.
177165 ** If the bCommit flag is true, also close any open blob handles.
177166 */
177167 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit);
177168 
177169 /*
177170 ** Discard any data stored in the in-memory hash tables. Do not write it
177171 ** to the database. Additionally, assume that the contents of the %_data
177172 ** table may have changed on disk. So any in-memory caches of %_data
177173 ** records must be invalidated.
177174 */
177175 static int sqlite3Fts5IndexRollback(Fts5Index *p);
177176 
177177 /*
177178 ** Get or set the "averages" values.
177179 */
177180 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize);
177181 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8*, int);
177182 
177183 /*
177184 ** Functions called by the storage module as part of integrity-check.
177185 */
177186 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index*, u64 cksum);
177187 
177188 /*
177189 ** Called during virtual module initialization to register UDF
177190 ** fts5_decode() with SQLite
177191 */
177192 static int sqlite3Fts5IndexInit(sqlite3*);
177193 
177194 static int sqlite3Fts5IndexSetCookie(Fts5Index*, int);
177195 
177196 /*
177197 ** Return the total number of entries read from the %_data table by
177198 ** this connection since it was created.
177199 */
177200 static int sqlite3Fts5IndexReads(Fts5Index *p);
177201 
177202 static int sqlite3Fts5IndexReinit(Fts5Index *p);
177203 static int sqlite3Fts5IndexOptimize(Fts5Index *p);
177204 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge);
177205 static int sqlite3Fts5IndexReset(Fts5Index *p);
177206 
177207 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p);
177208 
177209 /*
177210 ** End of interface to code in fts5_index.c.
177211 **************************************************************************/
177212 
177213 /**************************************************************************
177214 ** Interface to code in fts5_varint.c.
177215 */
177216 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v);
177217 static int sqlite3Fts5GetVarintLen(u32 iVal);
177218 static u8 sqlite3Fts5GetVarint(const unsigned char*, u64*);
177219 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v);
177220 
177221 #define fts5GetVarint32(a,b) sqlite3Fts5GetVarint32(a,(u32*)&b)
177222 #define fts5GetVarint sqlite3Fts5GetVarint
177223 
177224 #define fts5FastGetVarint32(a, iOff, nVal) { \
177225  nVal = (a)[iOff++]; \
177226  if( nVal & 0x80 ){ \
177227  iOff--; \
177228  iOff += fts5GetVarint32(&(a)[iOff], nVal); \
177229  } \
177230 }
177231 
177232 
177233 /*
177234 ** End of interface to code in fts5_varint.c.
177235 **************************************************************************/
177236 
177237 
177238 /**************************************************************************
177239 ** Interface to code in fts5.c.
177240 */
177241 
177242 static int sqlite3Fts5GetTokenizer(
177243  Fts5Global*,
177244  const char **azArg,
177245  int nArg,
177246  Fts5Tokenizer**,
177247  fts5_tokenizer**,
177248  char **pzErr
177249 );
177250 
177251 static Fts5Index *sqlite3Fts5IndexFromCsrid(Fts5Global*, i64, Fts5Config **);
177252 
177253 /*
177254 ** End of interface to code in fts5.c.
177255 **************************************************************************/
177256 
177257 /**************************************************************************
177258 ** Interface to code in fts5_hash.c.
177259 */
177260 typedef struct Fts5Hash Fts5Hash;
177261 
177262 /*
177263 ** Create a hash table, free a hash table.
177264 */
177265 static int sqlite3Fts5HashNew(Fts5Config*, Fts5Hash**, int *pnSize);
177266 static void sqlite3Fts5HashFree(Fts5Hash*);
177267 
177268 static int sqlite3Fts5HashWrite(
177269  Fts5Hash*,
177270  i64 iRowid, /* Rowid for this entry */
177271  int iCol, /* Column token appears in (-ve -> delete) */
177272  int iPos, /* Position of token within column */
177273  char bByte,
177274  const char *pToken, int nToken /* Token to add or remove to or from index */
177275 );
177276 
177277 /*
177278 ** Empty (but do not delete) a hash table.
177279 */
177280 static void sqlite3Fts5HashClear(Fts5Hash*);
177281 
177282 static int sqlite3Fts5HashQuery(
177283  Fts5Hash*, /* Hash table to query */
177284  const char *pTerm, int nTerm, /* Query term */
177285  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
177286  int *pnDoclist /* OUT: Size of doclist in bytes */
177287 );
177288 
177289 static int sqlite3Fts5HashScanInit(
177290  Fts5Hash*, /* Hash table to query */
177291  const char *pTerm, int nTerm /* Query prefix */
177292 );
177293 static void sqlite3Fts5HashScanNext(Fts5Hash*);
177294 static int sqlite3Fts5HashScanEof(Fts5Hash*);
177295 static void sqlite3Fts5HashScanEntry(Fts5Hash *,
177296  const char **pzTerm, /* OUT: term (nul-terminated) */
177297  const u8 **ppDoclist, /* OUT: pointer to doclist */
177298  int *pnDoclist /* OUT: size of doclist in bytes */
177299 );
177300 
177301 
177302 /*
177303 ** End of interface to code in fts5_hash.c.
177304 **************************************************************************/
177305 
177306 /**************************************************************************
177307 ** Interface to code in fts5_storage.c. fts5_storage.c contains contains
177308 ** code to access the data stored in the %_content and %_docsize tables.
177309 */
177310 
177311 #define FTS5_STMT_SCAN_ASC 0 /* SELECT rowid, * FROM ... ORDER BY 1 ASC */
177312 #define FTS5_STMT_SCAN_DESC 1 /* SELECT rowid, * FROM ... ORDER BY 1 DESC */
177313 #define FTS5_STMT_LOOKUP 2 /* SELECT rowid, * FROM ... WHERE rowid=? */
177314 
177315 typedef struct Fts5Storage Fts5Storage;
177316 
177317 static int sqlite3Fts5StorageOpen(Fts5Config*, Fts5Index*, int, Fts5Storage**, char**);
177318 static int sqlite3Fts5StorageClose(Fts5Storage *p);
177319 static int sqlite3Fts5StorageRename(Fts5Storage*, const char *zName);
177320 
177321 static int sqlite3Fts5DropAll(Fts5Config*);
177322 static int sqlite3Fts5CreateTable(Fts5Config*, const char*, const char*, int, char **);
177323 
177324 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64, sqlite3_value**);
177325 static int sqlite3Fts5StorageContentInsert(Fts5Storage *p, sqlite3_value**, i64*);
177326 static int sqlite3Fts5StorageIndexInsert(Fts5Storage *p, sqlite3_value**, i64);
177327 
177328 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p);
177329 
177330 static int sqlite3Fts5StorageStmt(Fts5Storage *p, int eStmt, sqlite3_stmt**, char**);
177331 static void sqlite3Fts5StorageStmtRelease(Fts5Storage *p, int eStmt, sqlite3_stmt*);
177332 
177333 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol);
177334 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnAvg);
177335 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow);
177336 
177337 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit);
177338 static int sqlite3Fts5StorageRollback(Fts5Storage *p);
177339 
177340 static int sqlite3Fts5StorageConfigValue(
177341  Fts5Storage *p, const char*, sqlite3_value*, int
177342 );
177343 
177344 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p);
177345 static int sqlite3Fts5StorageRebuild(Fts5Storage *p);
177346 static int sqlite3Fts5StorageOptimize(Fts5Storage *p);
177347 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge);
177348 static int sqlite3Fts5StorageReset(Fts5Storage *p);
177349 
177350 /*
177351 ** End of interface to code in fts5_storage.c.
177352 **************************************************************************/
177353 
177354 
177355 /**************************************************************************
177356 ** Interface to code in fts5_expr.c.
177357 */
177358 typedef struct Fts5Expr Fts5Expr;
177359 typedef struct Fts5ExprNode Fts5ExprNode;
177360 typedef struct Fts5Parse Fts5Parse;
177361 typedef struct Fts5Token Fts5Token;
177362 typedef struct Fts5ExprPhrase Fts5ExprPhrase;
177363 typedef struct Fts5ExprNearset Fts5ExprNearset;
177364 
177365 struct Fts5Token {
177366  const char *p; /* Token text (not NULL terminated) */
177367  int n; /* Size of buffer p in bytes */
177368 };
177369 
177370 /* Parse a MATCH expression. */
177371 static int sqlite3Fts5ExprNew(
177372  Fts5Config *pConfig,
177373  const char *zExpr,
177374  Fts5Expr **ppNew,
177375  char **pzErr
177376 );
177377 
177378 /*
177379 ** for(rc = sqlite3Fts5ExprFirst(pExpr, pIdx, bDesc);
177380 ** rc==SQLITE_OK && 0==sqlite3Fts5ExprEof(pExpr);
177381 ** rc = sqlite3Fts5ExprNext(pExpr)
177382 ** ){
177383 ** // The document with rowid iRowid matches the expression!
177384 ** i64 iRowid = sqlite3Fts5ExprRowid(pExpr);
177385 ** }
177386 */
177387 static int sqlite3Fts5ExprFirst(Fts5Expr*, Fts5Index *pIdx, i64 iMin, int bDesc);
177388 static int sqlite3Fts5ExprNext(Fts5Expr*, i64 iMax);
177389 static int sqlite3Fts5ExprEof(Fts5Expr*);
177390 static i64 sqlite3Fts5ExprRowid(Fts5Expr*);
177391 
177392 static void sqlite3Fts5ExprFree(Fts5Expr*);
177393 
177394 /* Called during startup to register a UDF with SQLite */
177395 static int sqlite3Fts5ExprInit(Fts5Global*, sqlite3*);
177396 
177397 static int sqlite3Fts5ExprPhraseCount(Fts5Expr*);
177398 static int sqlite3Fts5ExprPhraseSize(Fts5Expr*, int iPhrase);
177399 static int sqlite3Fts5ExprPoslist(Fts5Expr*, int, const u8 **);
177400 
177401 typedef struct Fts5PoslistPopulator Fts5PoslistPopulator;
177402 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr*, int);
177403 static int sqlite3Fts5ExprPopulatePoslists(
177404  Fts5Config*, Fts5Expr*, Fts5PoslistPopulator*, int, const char*, int
177405 );
177406 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr*, i64);
177407 static void sqlite3Fts5ExprClearEof(Fts5Expr*);
177408 
177409 static int sqlite3Fts5ExprClonePhrase(Fts5Expr*, int, Fts5Expr**);
177410 
177411 static int sqlite3Fts5ExprPhraseCollist(Fts5Expr *, int, const u8 **, int *);
177412 
177413 /*******************************************
177414 ** The fts5_expr.c API above this point is used by the other hand-written
177415 ** C code in this module. The interfaces below this point are called by
177416 ** the parser code in fts5parse.y. */
177417 
177418 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...);
177419 
177420 static Fts5ExprNode *sqlite3Fts5ParseNode(
177421  Fts5Parse *pParse,
177422  int eType,
177423  Fts5ExprNode *pLeft,
177424  Fts5ExprNode *pRight,
177425  Fts5ExprNearset *pNear
177426 );
177427 
177428 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
177429  Fts5Parse *pParse,
177430  Fts5ExprNode *pLeft,
177431  Fts5ExprNode *pRight
177432 );
177433 
177434 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
177435  Fts5Parse *pParse,
177436  Fts5ExprPhrase *pPhrase,
177437  Fts5Token *pToken,
177438  int bPrefix
177439 );
177440 
177441 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
177442  Fts5Parse*,
177443  Fts5ExprNearset*,
177444  Fts5ExprPhrase*
177445 );
177446 
177447 static Fts5Colset *sqlite3Fts5ParseColset(
177448  Fts5Parse*,
177449  Fts5Colset*,
177450  Fts5Token *
177451 );
177452 
177453 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase*);
177454 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset*);
177455 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode*);
177456 
177457 static void sqlite3Fts5ParseSetDistance(Fts5Parse*, Fts5ExprNearset*, Fts5Token*);
177458 static void sqlite3Fts5ParseSetColset(Fts5Parse*, Fts5ExprNearset*, Fts5Colset*);
177459 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p);
177460 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token*);
177461 
177462 /*
177463 ** End of interface to code in fts5_expr.c.
177464 **************************************************************************/
177465 
177466 
177467 
177468 /**************************************************************************
177469 ** Interface to code in fts5_aux.c.
177470 */
177471 
177472 static int sqlite3Fts5AuxInit(fts5_api*);
177473 /*
177474 ** End of interface to code in fts5_aux.c.
177475 **************************************************************************/
177476 
177477 /**************************************************************************
177478 ** Interface to code in fts5_tokenizer.c.
177479 */
177480 
177481 static int sqlite3Fts5TokenizerInit(fts5_api*);
177482 /*
177483 ** End of interface to code in fts5_tokenizer.c.
177484 **************************************************************************/
177485 
177486 /**************************************************************************
177487 ** Interface to code in fts5_vocab.c.
177488 */
177489 
177490 static int sqlite3Fts5VocabInit(Fts5Global*, sqlite3*);
177491 
177492 /*
177493 ** End of interface to code in fts5_vocab.c.
177494 **************************************************************************/
177495 
177496 
177497 /**************************************************************************
177498 ** Interface to automatically generated code in fts5_unicode2.c.
177499 */
177500 static int sqlite3Fts5UnicodeIsalnum(int c);
177501 static int sqlite3Fts5UnicodeIsdiacritic(int c);
177502 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic);
177503 /*
177504 ** End of interface to code in fts5_unicode2.c.
177505 **************************************************************************/
177506 
177507 #endif
177508 
177509 #define FTS5_OR 1
177510 #define FTS5_AND 2
177511 #define FTS5_NOT 3
177512 #define FTS5_TERM 4
177513 #define FTS5_COLON 5
177514 #define FTS5_LP 6
177515 #define FTS5_RP 7
177516 #define FTS5_LCP 8
177517 #define FTS5_RCP 9
177518 #define FTS5_STRING 10
177519 #define FTS5_COMMA 11
177520 #define FTS5_PLUS 12
177521 #define FTS5_STAR 13
177522 
177523 /*
177524 ** 2000-05-29
177525 **
177526 ** The author disclaims copyright to this source code. In place of
177527 ** a legal notice, here is a blessing:
177528 **
177529 ** May you do good and not evil.
177530 ** May you find forgiveness for yourself and forgive others.
177531 ** May you share freely, never taking more than you give.
177532 **
177533 *************************************************************************
177534 ** Driver template for the LEMON parser generator.
177535 **
177536 ** The "lemon" program processes an LALR(1) input grammar file, then uses
177537 ** this template to construct a parser. The "lemon" program inserts text
177538 ** at each "%%" line. Also, any "P-a-r-s-e" identifer prefix (without the
177539 ** interstitial "-" characters) contained in this template is changed into
177540 ** the value of the %name directive from the grammar. Otherwise, the content
177541 ** of this template is copied straight through into the generate parser
177542 ** source file.
177543 **
177544 ** The following is the concatenation of all %include directives from the
177545 ** input grammar file:
177546 */
177547 /* #include <stdio.h> */
177548 /************ Begin %include sections from the grammar ************************/
177549 
177550 /* #include "fts5Int.h" */
177551 /* #include "fts5parse.h" */
177552 
177553 /*
177554 ** Disable all error recovery processing in the parser push-down
177555 ** automaton.
177556 */
177557 #define fts5YYNOERRORRECOVERY 1
177558 
177559 /*
177560 ** Make fts5yytestcase() the same as testcase()
177561 */
177562 #define fts5yytestcase(X) testcase(X)
177563 
177564 /*
177565 ** Indicate that sqlite3ParserFree() will never be called with a null
177566 ** pointer.
177567 */
177568 #define fts5YYPARSEFREENOTNULL 1
177569 
177570 /*
177571 ** Alternative datatype for the argument to the malloc() routine passed
177572 ** into sqlite3ParserAlloc(). The default is size_t.
177573 */
177574 #define fts5YYMALLOCARGTYPE u64
177575 
177576 /**************** End of %include directives **********************************/
177577 /* These constants specify the various numeric values for terminal symbols
177578 ** in a format understandable to "makeheaders". This section is blank unless
177579 ** "lemon" is run with the "-m" command-line option.
177580 ***************** Begin makeheaders token definitions *************************/
177581 /**************** End makeheaders token definitions ***************************/
177582 
177583 /* The next sections is a series of control #defines.
177584 ** various aspects of the generated parser.
177585 ** fts5YYCODETYPE is the data type used to store the integer codes
177586 ** that represent terminal and non-terminal symbols.
177587 ** "unsigned char" is used if there are fewer than
177588 ** 256 symbols. Larger types otherwise.
177589 ** fts5YYNOCODE is a number of type fts5YYCODETYPE that is not used for
177590 ** any terminal or nonterminal symbol.
177591 ** fts5YYFALLBACK If defined, this indicates that one or more tokens
177592 ** (also known as: "terminal symbols") have fall-back
177593 ** values which should be used if the original symbol
177594 ** would not parse. This permits keywords to sometimes
177595 ** be used as identifiers, for example.
177596 ** fts5YYACTIONTYPE is the data type used for "action codes" - numbers
177597 ** that indicate what to do in response to the next
177598 ** token.
177599 ** sqlite3Fts5ParserFTS5TOKENTYPE is the data type used for minor type for terminal
177600 ** symbols. Background: A "minor type" is a semantic
177601 ** value associated with a terminal or non-terminal
177602 ** symbols. For example, for an "ID" terminal symbol,
177603 ** the minor type might be the name of the identifier.
177604 ** Each non-terminal can have a different minor type.
177605 ** Terminal symbols all have the same minor type, though.
177606 ** This macros defines the minor type for terminal
177607 ** symbols.
177608 ** fts5YYMINORTYPE is the data type used for all minor types.
177609 ** This is typically a union of many types, one of
177610 ** which is sqlite3Fts5ParserFTS5TOKENTYPE. The entry in the union
177611 ** for terminal symbols is called "fts5yy0".
177612 ** fts5YYSTACKDEPTH is the maximum depth of the parser's stack. If
177613 ** zero the stack is dynamically sized using realloc()
177614 ** sqlite3Fts5ParserARG_SDECL A static variable declaration for the %extra_argument
177615 ** sqlite3Fts5ParserARG_PDECL A parameter declaration for the %extra_argument
177616 ** sqlite3Fts5ParserARG_STORE Code to store %extra_argument into fts5yypParser
177617 ** sqlite3Fts5ParserARG_FETCH Code to extract %extra_argument from fts5yypParser
177618 ** fts5YYERRORSYMBOL is the code number of the error symbol. If not
177619 ** defined, then do no error processing.
177620 ** fts5YYNSTATE the combined number of states.
177621 ** fts5YYNRULE the number of rules in the grammar
177622 ** fts5YY_MAX_SHIFT Maximum value for shift actions
177623 ** fts5YY_MIN_SHIFTREDUCE Minimum value for shift-reduce actions
177624 ** fts5YY_MAX_SHIFTREDUCE Maximum value for shift-reduce actions
177625 ** fts5YY_MIN_REDUCE Maximum value for reduce actions
177626 ** fts5YY_ERROR_ACTION The fts5yy_action[] code for syntax error
177627 ** fts5YY_ACCEPT_ACTION The fts5yy_action[] code for accept
177628 ** fts5YY_NO_ACTION The fts5yy_action[] code for no-op
177629 */
177630 #ifndef INTERFACE
177631 # define INTERFACE 1
177632 #endif
177633 /************* Begin control #defines *****************************************/
177634 #define fts5YYCODETYPE unsigned char
177635 #define fts5YYNOCODE 27
177636 #define fts5YYACTIONTYPE unsigned char
177637 #define sqlite3Fts5ParserFTS5TOKENTYPE Fts5Token
177638 typedef union {
177639  int fts5yyinit;
177640  sqlite3Fts5ParserFTS5TOKENTYPE fts5yy0;
177641  Fts5Colset* fts5yy3;
177642  Fts5ExprPhrase* fts5yy11;
177643  Fts5ExprNode* fts5yy18;
177644  int fts5yy20;
177645  Fts5ExprNearset* fts5yy26;
177646 } fts5YYMINORTYPE;
177647 #ifndef fts5YYSTACKDEPTH
177648 #define fts5YYSTACKDEPTH 100
177649 #endif
177650 #define sqlite3Fts5ParserARG_SDECL Fts5Parse *pParse;
177651 #define sqlite3Fts5ParserARG_PDECL ,Fts5Parse *pParse
177652 #define sqlite3Fts5ParserARG_FETCH Fts5Parse *pParse = fts5yypParser->pParse
177653 #define sqlite3Fts5ParserARG_STORE fts5yypParser->pParse = pParse
177654 #define fts5YYNSTATE 26
177655 #define fts5YYNRULE 24
177656 #define fts5YY_MAX_SHIFT 25
177657 #define fts5YY_MIN_SHIFTREDUCE 40
177658 #define fts5YY_MAX_SHIFTREDUCE 63
177659 #define fts5YY_MIN_REDUCE 64
177660 #define fts5YY_MAX_REDUCE 87
177661 #define fts5YY_ERROR_ACTION 88
177662 #define fts5YY_ACCEPT_ACTION 89
177663 #define fts5YY_NO_ACTION 90
177664 /************* End control #defines *******************************************/
177665 
177666 /* Define the fts5yytestcase() macro to be a no-op if is not already defined
177667 ** otherwise.
177668 **
177669 ** Applications can choose to define fts5yytestcase() in the %include section
177670 ** to a macro that can assist in verifying code coverage. For production
177671 ** code the fts5yytestcase() macro should be turned off. But it is useful
177672 ** for testing.
177673 */
177674 #ifndef fts5yytestcase
177675 # define fts5yytestcase(X)
177676 #endif
177677 
177678 
177679 /* Next are the tables used to determine what action to take based on the
177680 ** current state and lookahead token. These tables are used to implement
177681 ** functions that take a state number and lookahead value and return an
177682 ** action integer.
177683 **
177684 ** Suppose the action integer is N. Then the action is determined as
177685 ** follows
177686 **
177687 ** 0 <= N <= fts5YY_MAX_SHIFT Shift N. That is, push the lookahead
177688 ** token onto the stack and goto state N.
177689 **
177690 ** N between fts5YY_MIN_SHIFTREDUCE Shift to an arbitrary state then
177691 ** and fts5YY_MAX_SHIFTREDUCE reduce by rule N-fts5YY_MIN_SHIFTREDUCE.
177692 **
177693 ** N between fts5YY_MIN_REDUCE Reduce by rule N-fts5YY_MIN_REDUCE
177694 ** and fts5YY_MAX_REDUCE
177695 
177696 ** N == fts5YY_ERROR_ACTION A syntax error has occurred.
177697 **
177698 ** N == fts5YY_ACCEPT_ACTION The parser accepts its input.
177699 **
177700 ** N == fts5YY_NO_ACTION No such action. Denotes unused
177701 ** slots in the fts5yy_action[] table.
177702 **
177703 ** The action table is constructed as a single large table named fts5yy_action[].
177704 ** Given state S and lookahead X, the action is computed as
177705 **
177706 ** fts5yy_action[ fts5yy_shift_ofst[S] + X ]
177707 **
177708 ** If the index value fts5yy_shift_ofst[S]+X is out of range or if the value
177709 ** fts5yy_lookahead[fts5yy_shift_ofst[S]+X] is not equal to X or if fts5yy_shift_ofst[S]
177710 ** is equal to fts5YY_SHIFT_USE_DFLT, it means that the action is not in the table
177711 ** and that fts5yy_default[S] should be used instead.
177712 **
177713 ** The formula above is for computing the action when the lookahead is
177714 ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
177715 ** a reduce action) then the fts5yy_reduce_ofst[] array is used in place of
177716 ** the fts5yy_shift_ofst[] array and fts5YY_REDUCE_USE_DFLT is used in place of
177717 ** fts5YY_SHIFT_USE_DFLT.
177718 **
177719 ** The following are the tables generated in this section:
177720 **
177721 ** fts5yy_action[] A single table containing all actions.
177722 ** fts5yy_lookahead[] A table containing the lookahead for each entry in
177723 ** fts5yy_action. Used to detect hash collisions.
177724 ** fts5yy_shift_ofst[] For each state, the offset into fts5yy_action for
177725 ** shifting terminals.
177726 ** fts5yy_reduce_ofst[] For each state, the offset into fts5yy_action for
177727 ** shifting non-terminals after a reduce.
177728 ** fts5yy_default[] Default action for each state.
177729 **
177730 *********** Begin parsing tables **********************************************/
177731 #define fts5YY_ACTTAB_COUNT (78)
177732 static const fts5YYACTIONTYPE fts5yy_action[] = {
177733  /* 0 */ 89, 15, 46, 5, 48, 24, 12, 19, 23, 14,
177734  /* 10 */ 46, 5, 48, 24, 20, 21, 23, 43, 46, 5,
177735  /* 20 */ 48, 24, 6, 18, 23, 17, 46, 5, 48, 24,
177736  /* 30 */ 75, 7, 23, 25, 46, 5, 48, 24, 62, 47,
177737  /* 40 */ 23, 48, 24, 7, 11, 23, 9, 3, 4, 2,
177738  /* 50 */ 62, 50, 52, 44, 64, 3, 4, 2, 49, 4,
177739  /* 60 */ 2, 1, 23, 11, 16, 9, 12, 2, 10, 61,
177740  /* 70 */ 53, 59, 62, 60, 22, 13, 55, 8,
177741 };
177742 static const fts5YYCODETYPE fts5yy_lookahead[] = {
177743  /* 0 */ 15, 16, 17, 18, 19, 20, 10, 11, 23, 16,
177744  /* 10 */ 17, 18, 19, 20, 23, 24, 23, 16, 17, 18,
177745  /* 20 */ 19, 20, 22, 23, 23, 16, 17, 18, 19, 20,
177746  /* 30 */ 5, 6, 23, 16, 17, 18, 19, 20, 13, 17,
177747  /* 40 */ 23, 19, 20, 6, 8, 23, 10, 1, 2, 3,
177748  /* 50 */ 13, 9, 10, 7, 0, 1, 2, 3, 19, 2,
177749  /* 60 */ 3, 6, 23, 8, 21, 10, 10, 3, 10, 25,
177750  /* 70 */ 10, 10, 13, 25, 12, 10, 7, 5,
177751 };
177752 #define fts5YY_SHIFT_USE_DFLT (-5)
177753 #define fts5YY_SHIFT_COUNT (25)
177754 #define fts5YY_SHIFT_MIN (-4)
177755 #define fts5YY_SHIFT_MAX (72)
177756 static const signed char fts5yy_shift_ofst[] = {
177757  /* 0 */ 55, 55, 55, 55, 55, 36, -4, 56, 58, 25,
177758  /* 10 */ 37, 60, 59, 59, 46, 54, 42, 57, 62, 61,
177759  /* 20 */ 62, 69, 65, 62, 72, 64,
177760 };
177761 #define fts5YY_REDUCE_USE_DFLT (-16)
177762 #define fts5YY_REDUCE_COUNT (13)
177763 #define fts5YY_REDUCE_MIN (-15)
177764 #define fts5YY_REDUCE_MAX (48)
177765 static const signed char fts5yy_reduce_ofst[] = {
177766  /* 0 */ -15, -7, 1, 9, 17, 22, -9, 0, 39, 44,
177767  /* 10 */ 44, 43, 44, 48,
177768 };
177769 static const fts5YYACTIONTYPE fts5yy_default[] = {
177770  /* 0 */ 88, 88, 88, 88, 88, 69, 82, 88, 88, 87,
177771  /* 10 */ 87, 88, 87, 87, 88, 88, 88, 66, 80, 88,
177772  /* 20 */ 81, 88, 88, 78, 88, 65,
177773 };
177774 /********** End of lemon-generated parsing tables *****************************/
177775 
177776 /* The next table maps tokens (terminal symbols) into fallback tokens.
177777 ** If a construct like the following:
177778 **
177779 ** %fallback ID X Y Z.
177780 **
177781 ** appears in the grammar, then ID becomes a fallback token for X, Y,
177782 ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
177783 ** but it does not parse, the type of the token is changed to ID and
177784 ** the parse is retried before an error is thrown.
177785 **
177786 ** This feature can be used, for example, to cause some keywords in a language
177787 ** to revert to identifiers if they keyword does not apply in the context where
177788 ** it appears.
177789 */
177790 #ifdef fts5YYFALLBACK
177791 static const fts5YYCODETYPE fts5yyFallback[] = {
177792 };
177793 #endif /* fts5YYFALLBACK */
177794 
177795 /* The following structure represents a single element of the
177796 ** parser's stack. Information stored includes:
177797 **
177798 ** + The state number for the parser at this level of the stack.
177799 **
177800 ** + The value of the token stored at this level of the stack.
177801 ** (In other words, the "major" token.)
177802 **
177803 ** + The semantic value stored at this level of the stack. This is
177804 ** the information used by the action routines in the grammar.
177805 ** It is sometimes called the "minor" token.
177806 **
177807 ** After the "shift" half of a SHIFTREDUCE action, the stateno field
177808 ** actually contains the reduce action for the second half of the
177809 ** SHIFTREDUCE.
177810 */
177811 struct fts5yyStackEntry {
177812  fts5YYACTIONTYPE stateno; /* The state-number, or reduce action in SHIFTREDUCE */
177813  fts5YYCODETYPE major; /* The major token value. This is the code
177814  ** number for the token at this stack level */
177815  fts5YYMINORTYPE minor; /* The user-supplied minor token value. This
177816  ** is the value of the token */
177817 };
177818 typedef struct fts5yyStackEntry fts5yyStackEntry;
177819 
177820 /* The state of the parser is completely contained in an instance of
177821 ** the following structure */
177822 struct fts5yyParser {
177823  int fts5yyidx; /* Index of top element in stack */
177824 #ifdef fts5YYTRACKMAXSTACKDEPTH
177825  int fts5yyidxMax; /* Maximum value of fts5yyidx */
177826 #endif
177827 #ifndef fts5YYNOERRORRECOVERY
177828  int fts5yyerrcnt; /* Shifts left before out of the error */
177829 #endif
177830  sqlite3Fts5ParserARG_SDECL /* A place to hold %extra_argument */
177831 #if fts5YYSTACKDEPTH<=0
177832  int fts5yystksz; /* Current side of the stack */
177833  fts5yyStackEntry *fts5yystack; /* The parser's stack */
177834 #else
177835  fts5yyStackEntry fts5yystack[fts5YYSTACKDEPTH]; /* The parser's stack */
177836 #endif
177837 };
177838 typedef struct fts5yyParser fts5yyParser;
177839 
177840 #ifndef NDEBUG
177841 /* #include <stdio.h> */
177842 static FILE *fts5yyTraceFILE = 0;
177843 static char *fts5yyTracePrompt = 0;
177844 #endif /* NDEBUG */
177845 
177846 #ifndef NDEBUG
177847 /*
177848 ** Turn parser tracing on by giving a stream to which to write the trace
177849 ** and a prompt to preface each trace message. Tracing is turned off
177850 ** by making either argument NULL
177851 **
177852 ** Inputs:
177853 ** <ul>
177854 ** <li> A FILE* to which trace output should be written.
177855 ** If NULL, then tracing is turned off.
177856 ** <li> A prefix string written at the beginning of every
177857 ** line of trace output. If NULL, then tracing is
177858 ** turned off.
177859 ** </ul>
177860 **
177861 ** Outputs:
177862 ** None.
177863 */
177864 static void sqlite3Fts5ParserTrace(FILE *TraceFILE, char *zTracePrompt){
177865  fts5yyTraceFILE = TraceFILE;
177866  fts5yyTracePrompt = zTracePrompt;
177867  if( fts5yyTraceFILE==0 ) fts5yyTracePrompt = 0;
177868  else if( fts5yyTracePrompt==0 ) fts5yyTraceFILE = 0;
177869 }
177870 #endif /* NDEBUG */
177871 
177872 #ifndef NDEBUG
177873 /* For tracing shifts, the names of all terminals and nonterminals
177874 ** are required. The following table supplies these names */
177875 static const char *const fts5yyTokenName[] = {
177876  "$", "OR", "AND", "NOT",
177877  "TERM", "COLON", "LP", "RP",
177878  "LCP", "RCP", "STRING", "COMMA",
177879  "PLUS", "STAR", "error", "input",
177880  "expr", "cnearset", "exprlist", "nearset",
177881  "colset", "colsetlist", "nearphrases", "phrase",
177882  "neardist_opt", "star_opt",
177883 };
177884 #endif /* NDEBUG */
177885 
177886 #ifndef NDEBUG
177887 /* For tracing reduce actions, the names of all rules are required.
177888 */
177889 static const char *const fts5yyRuleName[] = {
177890  /* 0 */ "input ::= expr",
177891  /* 1 */ "expr ::= expr AND expr",
177892  /* 2 */ "expr ::= expr OR expr",
177893  /* 3 */ "expr ::= expr NOT expr",
177894  /* 4 */ "expr ::= LP expr RP",
177895  /* 5 */ "expr ::= exprlist",
177896  /* 6 */ "exprlist ::= cnearset",
177897  /* 7 */ "exprlist ::= exprlist cnearset",
177898  /* 8 */ "cnearset ::= nearset",
177899  /* 9 */ "cnearset ::= colset COLON nearset",
177900  /* 10 */ "colset ::= LCP colsetlist RCP",
177901  /* 11 */ "colset ::= STRING",
177902  /* 12 */ "colsetlist ::= colsetlist STRING",
177903  /* 13 */ "colsetlist ::= STRING",
177904  /* 14 */ "nearset ::= phrase",
177905  /* 15 */ "nearset ::= STRING LP nearphrases neardist_opt RP",
177906  /* 16 */ "nearphrases ::= phrase",
177907  /* 17 */ "nearphrases ::= nearphrases phrase",
177908  /* 18 */ "neardist_opt ::=",
177909  /* 19 */ "neardist_opt ::= COMMA STRING",
177910  /* 20 */ "phrase ::= phrase PLUS STRING star_opt",
177911  /* 21 */ "phrase ::= STRING star_opt",
177912  /* 22 */ "star_opt ::= STAR",
177913  /* 23 */ "star_opt ::=",
177914 };
177915 #endif /* NDEBUG */
177916 
177917 
177918 #if fts5YYSTACKDEPTH<=0
177919 /*
177920 ** Try to increase the size of the parser stack.
177921 */
177922 static void fts5yyGrowStack(fts5yyParser *p){
177923  int newSize;
177924  fts5yyStackEntry *pNew;
177925 
177926  newSize = p->fts5yystksz*2 + 100;
177927  pNew = realloc(p->fts5yystack, newSize*sizeof(pNew[0]));
177928  if( pNew ){
177929  p->fts5yystack = pNew;
177930  p->fts5yystksz = newSize;
177931 #ifndef NDEBUG
177932  if( fts5yyTraceFILE ){
177933  fprintf(fts5yyTraceFILE,"%sStack grows to %d entries!\n",
177934  fts5yyTracePrompt, p->fts5yystksz);
177935  }
177936 #endif
177937  }
177938 }
177939 #endif
177940 
177941 /* Datatype of the argument to the memory allocated passed as the
177942 ** second argument to sqlite3Fts5ParserAlloc() below. This can be changed by
177943 ** putting an appropriate #define in the %include section of the input
177944 ** grammar.
177945 */
177946 #ifndef fts5YYMALLOCARGTYPE
177947 # define fts5YYMALLOCARGTYPE size_t
177948 #endif
177949 
177950 /*
177951 ** This function allocates a new parser.
177952 ** The only argument is a pointer to a function which works like
177953 ** malloc.
177954 **
177955 ** Inputs:
177956 ** A pointer to the function used to allocate memory.
177957 **
177958 ** Outputs:
177959 ** A pointer to a parser. This pointer is used in subsequent calls
177960 ** to sqlite3Fts5Parser and sqlite3Fts5ParserFree.
177961 */
177962 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(fts5YYMALLOCARGTYPE)){
177963  fts5yyParser *pParser;
177964  pParser = (fts5yyParser*)(*mallocProc)( (fts5YYMALLOCARGTYPE)sizeof(fts5yyParser) );
177965  if( pParser ){
177966  pParser->fts5yyidx = -1;
177967 #ifdef fts5YYTRACKMAXSTACKDEPTH
177968  pParser->fts5yyidxMax = 0;
177969 #endif
177970 #if fts5YYSTACKDEPTH<=0
177971  pParser->fts5yystack = NULL;
177972  pParser->fts5yystksz = 0;
177973  fts5yyGrowStack(pParser);
177974 #endif
177975  }
177976  return pParser;
177977 }
177978 
177979 /* The following function deletes the "minor type" or semantic value
177980 ** associated with a symbol. The symbol can be either a terminal
177981 ** or nonterminal. "fts5yymajor" is the symbol code, and "fts5yypminor" is
177982 ** a pointer to the value to be deleted. The code used to do the
177983 ** deletions is derived from the %destructor and/or %token_destructor
177984 ** directives of the input grammar.
177985 */
177986 static void fts5yy_destructor(
177987  fts5yyParser *fts5yypParser, /* The parser */
177988  fts5YYCODETYPE fts5yymajor, /* Type code for object to destroy */
177989  fts5YYMINORTYPE *fts5yypminor /* The object to be destroyed */
177990 ){
177991  sqlite3Fts5ParserARG_FETCH;
177992  switch( fts5yymajor ){
177993  /* Here is inserted the actions which take place when a
177994  ** terminal or non-terminal is destroyed. This can happen
177995  ** when the symbol is popped from the stack during a
177996  ** reduce or during error processing or when a parser is
177997  ** being destroyed before it is finished parsing.
177998  **
177999  ** Note: during a reduce, the only symbols destroyed are those
178000  ** which appear on the RHS of the rule, but which are *not* used
178001  ** inside the C code.
178002  */
178003 /********* Begin destructor definitions ***************************************/
178004  case 15: /* input */
178005 {
178006  (void)pParse;
178007 }
178008  break;
178009  case 16: /* expr */
178010  case 17: /* cnearset */
178011  case 18: /* exprlist */
178012 {
178013  sqlite3Fts5ParseNodeFree((fts5yypminor->fts5yy18));
178014 }
178015  break;
178016  case 19: /* nearset */
178017  case 22: /* nearphrases */
178018 {
178019  sqlite3Fts5ParseNearsetFree((fts5yypminor->fts5yy26));
178020 }
178021  break;
178022  case 20: /* colset */
178023  case 21: /* colsetlist */
178024 {
178025  sqlite3_free((fts5yypminor->fts5yy3));
178026 }
178027  break;
178028  case 23: /* phrase */
178029 {
178030  sqlite3Fts5ParsePhraseFree((fts5yypminor->fts5yy11));
178031 }
178032  break;
178033 /********* End destructor definitions *****************************************/
178034  default: break; /* If no destructor action specified: do nothing */
178035  }
178036 }
178037 
178038 /*
178039 ** Pop the parser's stack once.
178040 **
178041 ** If there is a destructor routine associated with the token which
178042 ** is popped from the stack, then call it.
178043 */
178044 static void fts5yy_pop_parser_stack(fts5yyParser *pParser){
178045  fts5yyStackEntry *fts5yytos;
178046  assert( pParser->fts5yyidx>=0 );
178047  fts5yytos = &pParser->fts5yystack[pParser->fts5yyidx--];
178048 #ifndef NDEBUG
178049  if( fts5yyTraceFILE ){
178050  fprintf(fts5yyTraceFILE,"%sPopping %s\n",
178051  fts5yyTracePrompt,
178052  fts5yyTokenName[fts5yytos->major]);
178053  }
178054 #endif
178055  fts5yy_destructor(pParser, fts5yytos->major, &fts5yytos->minor);
178056 }
178057 
178058 /*
178059 ** Deallocate and destroy a parser. Destructors are called for
178060 ** all stack elements before shutting the parser down.
178061 **
178062 ** If the fts5YYPARSEFREENEVERNULL macro exists (for example because it
178063 ** is defined in a %include section of the input grammar) then it is
178064 ** assumed that the input pointer is never NULL.
178065 */
178066 static void sqlite3Fts5ParserFree(
178067  void *p, /* The parser to be deleted */
178068  void (*freeProc)(void*) /* Function used to reclaim memory */
178069 ){
178070  fts5yyParser *pParser = (fts5yyParser*)p;
178071 #ifndef fts5YYPARSEFREENEVERNULL
178072  if( pParser==0 ) return;
178073 #endif
178074  while( pParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(pParser);
178075 #if fts5YYSTACKDEPTH<=0
178076  free(pParser->fts5yystack);
178077 #endif
178078  (*freeProc)((void*)pParser);
178079 }
178080 
178081 /*
178082 ** Return the peak depth of the stack for a parser.
178083 */
178084 #ifdef fts5YYTRACKMAXSTACKDEPTH
178085 static int sqlite3Fts5ParserStackPeak(void *p){
178086  fts5yyParser *pParser = (fts5yyParser*)p;
178087  return pParser->fts5yyidxMax;
178088 }
178089 #endif
178090 
178091 /*
178092 ** Find the appropriate action for a parser given the terminal
178093 ** look-ahead token iLookAhead.
178094 */
178095 static unsigned int fts5yy_find_shift_action(
178096  fts5yyParser *pParser, /* The parser */
178097  fts5YYCODETYPE iLookAhead /* The look-ahead token */
178098 ){
178099  int i;
178100  int stateno = pParser->fts5yystack[pParser->fts5yyidx].stateno;
178101 
178102  if( stateno>=fts5YY_MIN_REDUCE ) return stateno;
178103  assert( stateno <= fts5YY_SHIFT_COUNT );
178104  do{
178105  i = fts5yy_shift_ofst[stateno];
178106  if( i==fts5YY_SHIFT_USE_DFLT ) return fts5yy_default[stateno];
178107  assert( iLookAhead!=fts5YYNOCODE );
178108  i += iLookAhead;
178109  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
178110  if( iLookAhead>0 ){
178111 #ifdef fts5YYFALLBACK
178112  fts5YYCODETYPE iFallback; /* Fallback token */
178113  if( iLookAhead<sizeof(fts5yyFallback)/sizeof(fts5yyFallback[0])
178114  && (iFallback = fts5yyFallback[iLookAhead])!=0 ){
178115 #ifndef NDEBUG
178116  if( fts5yyTraceFILE ){
178117  fprintf(fts5yyTraceFILE, "%sFALLBACK %s => %s\n",
178118  fts5yyTracePrompt, fts5yyTokenName[iLookAhead], fts5yyTokenName[iFallback]);
178119  }
178120 #endif
178121  assert( fts5yyFallback[iFallback]==0 ); /* Fallback loop must terminate */
178122  iLookAhead = iFallback;
178123  continue;
178124  }
178125 #endif
178126 #ifdef fts5YYWILDCARD
178127  {
178128  int j = i - iLookAhead + fts5YYWILDCARD;
178129  if(
178130 #if fts5YY_SHIFT_MIN+fts5YYWILDCARD<0
178131  j>=0 &&
178132 #endif
178133 #if fts5YY_SHIFT_MAX+fts5YYWILDCARD>=fts5YY_ACTTAB_COUNT
178134  j<fts5YY_ACTTAB_COUNT &&
178135 #endif
178136  fts5yy_lookahead[j]==fts5YYWILDCARD
178137  ){
178138 #ifndef NDEBUG
178139  if( fts5yyTraceFILE ){
178140  fprintf(fts5yyTraceFILE, "%sWILDCARD %s => %s\n",
178141  fts5yyTracePrompt, fts5yyTokenName[iLookAhead],
178142  fts5yyTokenName[fts5YYWILDCARD]);
178143  }
178144 #endif /* NDEBUG */
178145  return fts5yy_action[j];
178146  }
178147  }
178148 #endif /* fts5YYWILDCARD */
178149  }
178150  return fts5yy_default[stateno];
178151  }else{
178152  return fts5yy_action[i];
178153  }
178154  }while(1);
178155 }
178156 
178157 /*
178158 ** Find the appropriate action for a parser given the non-terminal
178159 ** look-ahead token iLookAhead.
178160 */
178161 static int fts5yy_find_reduce_action(
178162  int stateno, /* Current state number */
178163  fts5YYCODETYPE iLookAhead /* The look-ahead token */
178164 ){
178165  int i;
178166 #ifdef fts5YYERRORSYMBOL
178167  if( stateno>fts5YY_REDUCE_COUNT ){
178168  return fts5yy_default[stateno];
178169  }
178170 #else
178171  assert( stateno<=fts5YY_REDUCE_COUNT );
178172 #endif
178173  i = fts5yy_reduce_ofst[stateno];
178174  assert( i!=fts5YY_REDUCE_USE_DFLT );
178175  assert( iLookAhead!=fts5YYNOCODE );
178176  i += iLookAhead;
178177 #ifdef fts5YYERRORSYMBOL
178178  if( i<0 || i>=fts5YY_ACTTAB_COUNT || fts5yy_lookahead[i]!=iLookAhead ){
178179  return fts5yy_default[stateno];
178180  }
178181 #else
178182  assert( i>=0 && i<fts5YY_ACTTAB_COUNT );
178183  assert( fts5yy_lookahead[i]==iLookAhead );
178184 #endif
178185  return fts5yy_action[i];
178186 }
178187 
178188 /*
178189 ** The following routine is called if the stack overflows.
178190 */
178191 static void fts5yyStackOverflow(fts5yyParser *fts5yypParser){
178192  sqlite3Fts5ParserARG_FETCH;
178193  fts5yypParser->fts5yyidx--;
178194 #ifndef NDEBUG
178195  if( fts5yyTraceFILE ){
178196  fprintf(fts5yyTraceFILE,"%sStack Overflow!\n",fts5yyTracePrompt);
178197  }
178198 #endif
178199  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
178200  /* Here code is inserted which will execute if the parser
178201  ** stack every overflows */
178202 /******** Begin %stack_overflow code ******************************************/
178203 
178204  sqlite3Fts5ParseError(pParse, "fts5: parser stack overflow");
178205 /******** End %stack_overflow code ********************************************/
178206  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
178207 }
178208 
178209 /*
178210 ** Print tracing information for a SHIFT action
178211 */
178212 #ifndef NDEBUG
178213 static void fts5yyTraceShift(fts5yyParser *fts5yypParser, int fts5yyNewState){
178214  if( fts5yyTraceFILE ){
178215  if( fts5yyNewState<fts5YYNSTATE ){
178216  fprintf(fts5yyTraceFILE,"%sShift '%s', go to state %d\n",
178217  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major],
178218  fts5yyNewState);
178219  }else{
178220  fprintf(fts5yyTraceFILE,"%sShift '%s'\n",
178221  fts5yyTracePrompt,fts5yyTokenName[fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major]);
178222  }
178223  }
178224 }
178225 #else
178226 # define fts5yyTraceShift(X,Y)
178227 #endif
178228 
178229 /*
178230 ** Perform a shift action.
178231 */
178232 static void fts5yy_shift(
178233  fts5yyParser *fts5yypParser, /* The parser to be shifted */
178234  int fts5yyNewState, /* The new state to shift in */
178235  int fts5yyMajor, /* The major token to shift in */
178236  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyMinor /* The minor token to shift in */
178237 ){
178238  fts5yyStackEntry *fts5yytos;
178239  fts5yypParser->fts5yyidx++;
178240 #ifdef fts5YYTRACKMAXSTACKDEPTH
178241  if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
178242  fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
178243  }
178244 #endif
178245 #if fts5YYSTACKDEPTH>0
178246  if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH ){
178247  fts5yyStackOverflow(fts5yypParser);
178248  return;
178249  }
178250 #else
178251  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
178252  fts5yyGrowStack(fts5yypParser);
178253  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz ){
178254  fts5yyStackOverflow(fts5yypParser);
178255  return;
178256  }
178257  }
178258 #endif
178259  fts5yytos = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
178260  fts5yytos->stateno = (fts5YYACTIONTYPE)fts5yyNewState;
178261  fts5yytos->major = (fts5YYCODETYPE)fts5yyMajor;
178262  fts5yytos->minor.fts5yy0 = fts5yyMinor;
178263  fts5yyTraceShift(fts5yypParser, fts5yyNewState);
178264 }
178265 
178266 /* The following table contains information about every rule that
178267 ** is used during the reduce.
178268 */
178269 static const struct {
178270  fts5YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
178271  unsigned char nrhs; /* Number of right-hand side symbols in the rule */
178272 } fts5yyRuleInfo[] = {
178273  { 15, 1 },
178274  { 16, 3 },
178275  { 16, 3 },
178276  { 16, 3 },
178277  { 16, 3 },
178278  { 16, 1 },
178279  { 18, 1 },
178280  { 18, 2 },
178281  { 17, 1 },
178282  { 17, 3 },
178283  { 20, 3 },
178284  { 20, 1 },
178285  { 21, 2 },
178286  { 21, 1 },
178287  { 19, 1 },
178288  { 19, 5 },
178289  { 22, 1 },
178290  { 22, 2 },
178291  { 24, 0 },
178292  { 24, 2 },
178293  { 23, 4 },
178294  { 23, 2 },
178295  { 25, 1 },
178296  { 25, 0 },
178297 };
178298 
178299 static void fts5yy_accept(fts5yyParser*); /* Forward Declaration */
178300 
178301 /*
178302 ** Perform a reduce action and the shift that must immediately
178303 ** follow the reduce.
178304 */
178305 static void fts5yy_reduce(
178306  fts5yyParser *fts5yypParser, /* The parser */
178307  unsigned int fts5yyruleno /* Number of the rule by which to reduce */
178308 ){
178309  int fts5yygoto; /* The next state */
178310  int fts5yyact; /* The next action */
178311  fts5yyStackEntry *fts5yymsp; /* The top of the parser's stack */
178312  int fts5yysize; /* Amount to pop the stack */
178313  sqlite3Fts5ParserARG_FETCH;
178314  fts5yymsp = &fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx];
178315 #ifndef NDEBUG
178316  if( fts5yyTraceFILE && fts5yyruleno<(int)(sizeof(fts5yyRuleName)/sizeof(fts5yyRuleName[0])) ){
178317  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
178318  fprintf(fts5yyTraceFILE, "%sReduce [%s], go to state %d.\n", fts5yyTracePrompt,
178319  fts5yyRuleName[fts5yyruleno], fts5yymsp[-fts5yysize].stateno);
178320  }
178321 #endif /* NDEBUG */
178322 
178323  /* Check that the stack is large enough to grow by a single entry
178324  ** if the RHS of the rule is empty. This ensures that there is room
178325  ** enough on the stack to push the LHS value */
178326  if( fts5yyRuleInfo[fts5yyruleno].nrhs==0 ){
178327 #ifdef fts5YYTRACKMAXSTACKDEPTH
178328  if( fts5yypParser->fts5yyidx>fts5yypParser->fts5yyidxMax ){
178329  fts5yypParser->fts5yyidxMax = fts5yypParser->fts5yyidx;
178330  }
178331 #endif
178332 #if fts5YYSTACKDEPTH>0
178333  if( fts5yypParser->fts5yyidx>=fts5YYSTACKDEPTH-1 ){
178334  fts5yyStackOverflow(fts5yypParser);
178335  return;
178336  }
178337 #else
178338  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz-1 ){
178339  fts5yyGrowStack(fts5yypParser);
178340  if( fts5yypParser->fts5yyidx>=fts5yypParser->fts5yystksz-1 ){
178341  fts5yyStackOverflow(fts5yypParser);
178342  return;
178343  }
178344  }
178345 #endif
178346  }
178347 
178348  switch( fts5yyruleno ){
178349  /* Beginning here are the reduction cases. A typical example
178350  ** follows:
178351  ** case 0:
178352  ** #line <lineno> <grammarfile>
178353  ** { ... } // User supplied code
178354  ** #line <lineno> <thisfile>
178355  ** break;
178356  */
178357 /********** Begin reduce actions **********************************************/
178358  fts5YYMINORTYPE fts5yylhsminor;
178359  case 0: /* input ::= expr */
178360 { sqlite3Fts5ParseFinished(pParse, fts5yymsp[0].minor.fts5yy18); }
178361  break;
178362  case 1: /* expr ::= expr AND expr */
178363 {
178364  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_AND, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
178365 }
178366  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178367  break;
178368  case 2: /* expr ::= expr OR expr */
178369 {
178370  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_OR, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
178371 }
178372  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178373  break;
178374  case 3: /* expr ::= expr NOT expr */
178375 {
178376  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_NOT, fts5yymsp[-2].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18, 0);
178377 }
178378  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178379  break;
178380  case 4: /* expr ::= LP expr RP */
178381 {fts5yymsp[-2].minor.fts5yy18 = fts5yymsp[-1].minor.fts5yy18;}
178382  break;
178383  case 5: /* expr ::= exprlist */
178384  case 6: /* exprlist ::= cnearset */ fts5yytestcase(fts5yyruleno==6);
178385 {fts5yylhsminor.fts5yy18 = fts5yymsp[0].minor.fts5yy18;}
178386  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178387  break;
178388  case 7: /* exprlist ::= exprlist cnearset */
178389 {
178390  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseImplicitAnd(pParse, fts5yymsp[-1].minor.fts5yy18, fts5yymsp[0].minor.fts5yy18);
178391 }
178392  fts5yymsp[-1].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178393  break;
178394  case 8: /* cnearset ::= nearset */
178395 {
178396  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
178397 }
178398  fts5yymsp[0].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178399  break;
178400  case 9: /* cnearset ::= colset COLON nearset */
178401 {
178402  sqlite3Fts5ParseSetColset(pParse, fts5yymsp[0].minor.fts5yy26, fts5yymsp[-2].minor.fts5yy3);
178403  fts5yylhsminor.fts5yy18 = sqlite3Fts5ParseNode(pParse, FTS5_STRING, 0, 0, fts5yymsp[0].minor.fts5yy26);
178404 }
178405  fts5yymsp[-2].minor.fts5yy18 = fts5yylhsminor.fts5yy18;
178406  break;
178407  case 10: /* colset ::= LCP colsetlist RCP */
178408 { fts5yymsp[-2].minor.fts5yy3 = fts5yymsp[-1].minor.fts5yy3; }
178409  break;
178410  case 11: /* colset ::= STRING */
178411 {
178412  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
178413 }
178414  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
178415  break;
178416  case 12: /* colsetlist ::= colsetlist STRING */
178417 {
178418  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, fts5yymsp[-1].minor.fts5yy3, &fts5yymsp[0].minor.fts5yy0); }
178419  fts5yymsp[-1].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
178420  break;
178421  case 13: /* colsetlist ::= STRING */
178422 {
178423  fts5yylhsminor.fts5yy3 = sqlite3Fts5ParseColset(pParse, 0, &fts5yymsp[0].minor.fts5yy0);
178424 }
178425  fts5yymsp[0].minor.fts5yy3 = fts5yylhsminor.fts5yy3;
178426  break;
178427  case 14: /* nearset ::= phrase */
178428 { fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11); }
178429  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
178430  break;
178431  case 15: /* nearset ::= STRING LP nearphrases neardist_opt RP */
178432 {
178433  sqlite3Fts5ParseNear(pParse, &fts5yymsp[-4].minor.fts5yy0);
178434  sqlite3Fts5ParseSetDistance(pParse, fts5yymsp[-2].minor.fts5yy26, &fts5yymsp[-1].minor.fts5yy0);
178435  fts5yylhsminor.fts5yy26 = fts5yymsp[-2].minor.fts5yy26;
178436 }
178437  fts5yymsp[-4].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
178438  break;
178439  case 16: /* nearphrases ::= phrase */
178440 {
178441  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, 0, fts5yymsp[0].minor.fts5yy11);
178442 }
178443  fts5yymsp[0].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
178444  break;
178445  case 17: /* nearphrases ::= nearphrases phrase */
178446 {
178447  fts5yylhsminor.fts5yy26 = sqlite3Fts5ParseNearset(pParse, fts5yymsp[-1].minor.fts5yy26, fts5yymsp[0].minor.fts5yy11);
178448 }
178449  fts5yymsp[-1].minor.fts5yy26 = fts5yylhsminor.fts5yy26;
178450  break;
178451  case 18: /* neardist_opt ::= */
178452 { fts5yymsp[1].minor.fts5yy0.p = 0; fts5yymsp[1].minor.fts5yy0.n = 0; }
178453  break;
178454  case 19: /* neardist_opt ::= COMMA STRING */
178455 { fts5yymsp[-1].minor.fts5yy0 = fts5yymsp[0].minor.fts5yy0; }
178456  break;
178457  case 20: /* phrase ::= phrase PLUS STRING star_opt */
178458 {
178459  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, fts5yymsp[-3].minor.fts5yy11, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
178460 }
178461  fts5yymsp[-3].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
178462  break;
178463  case 21: /* phrase ::= STRING star_opt */
178464 {
178465  fts5yylhsminor.fts5yy11 = sqlite3Fts5ParseTerm(pParse, 0, &fts5yymsp[-1].minor.fts5yy0, fts5yymsp[0].minor.fts5yy20);
178466 }
178467  fts5yymsp[-1].minor.fts5yy11 = fts5yylhsminor.fts5yy11;
178468  break;
178469  case 22: /* star_opt ::= STAR */
178470 { fts5yymsp[0].minor.fts5yy20 = 1; }
178471  break;
178472  case 23: /* star_opt ::= */
178473 { fts5yymsp[1].minor.fts5yy20 = 0; }
178474  break;
178475  default:
178476  break;
178477 /********** End reduce actions ************************************************/
178478  };
178479  assert( fts5yyruleno<sizeof(fts5yyRuleInfo)/sizeof(fts5yyRuleInfo[0]) );
178480  fts5yygoto = fts5yyRuleInfo[fts5yyruleno].lhs;
178481  fts5yysize = fts5yyRuleInfo[fts5yyruleno].nrhs;
178482  fts5yyact = fts5yy_find_reduce_action(fts5yymsp[-fts5yysize].stateno,(fts5YYCODETYPE)fts5yygoto);
178483  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
178484  if( fts5yyact>fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
178485  fts5yypParser->fts5yyidx -= fts5yysize - 1;
178486  fts5yymsp -= fts5yysize-1;
178487  fts5yymsp->stateno = (fts5YYACTIONTYPE)fts5yyact;
178488  fts5yymsp->major = (fts5YYCODETYPE)fts5yygoto;
178489  fts5yyTraceShift(fts5yypParser, fts5yyact);
178490  }else{
178491  assert( fts5yyact == fts5YY_ACCEPT_ACTION );
178492  fts5yypParser->fts5yyidx -= fts5yysize;
178493  fts5yy_accept(fts5yypParser);
178494  }
178495 }
178496 
178497 /*
178498 ** The following code executes when the parse fails
178499 */
178500 #ifndef fts5YYNOERRORRECOVERY
178501 static void fts5yy_parse_failed(
178502  fts5yyParser *fts5yypParser /* The parser */
178503 ){
178504  sqlite3Fts5ParserARG_FETCH;
178505 #ifndef NDEBUG
178506  if( fts5yyTraceFILE ){
178507  fprintf(fts5yyTraceFILE,"%sFail!\n",fts5yyTracePrompt);
178508  }
178509 #endif
178510  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
178511  /* Here code is inserted which will be executed whenever the
178512  ** parser fails */
178513 /************ Begin %parse_failure code ***************************************/
178514 /************ End %parse_failure code *****************************************/
178515  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
178516 }
178517 #endif /* fts5YYNOERRORRECOVERY */
178518 
178519 /*
178520 ** The following code executes when a syntax error first occurs.
178521 */
178522 static void fts5yy_syntax_error(
178523  fts5yyParser *fts5yypParser, /* The parser */
178524  int fts5yymajor, /* The major type of the error token */
178525  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The minor type of the error token */
178526 ){
178527  sqlite3Fts5ParserARG_FETCH;
178528 #define FTS5TOKEN fts5yyminor
178529 /************ Begin %syntax_error code ****************************************/
178530 
178531  UNUSED_PARAM(fts5yymajor); /* Silence a compiler warning */
178532  sqlite3Fts5ParseError(
178533  pParse, "fts5: syntax error near \"%.*s\"",FTS5TOKEN.n,FTS5TOKEN.p
178534  );
178535 /************ End %syntax_error code ******************************************/
178536  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
178537 }
178538 
178539 /*
178540 ** The following is executed when the parser accepts
178541 */
178542 static void fts5yy_accept(
178543  fts5yyParser *fts5yypParser /* The parser */
178544 ){
178545  sqlite3Fts5ParserARG_FETCH;
178546 #ifndef NDEBUG
178547  if( fts5yyTraceFILE ){
178548  fprintf(fts5yyTraceFILE,"%sAccept!\n",fts5yyTracePrompt);
178549  }
178550 #endif
178551  while( fts5yypParser->fts5yyidx>=0 ) fts5yy_pop_parser_stack(fts5yypParser);
178552  /* Here code is inserted which will be executed whenever the
178553  ** parser accepts */
178554 /*********** Begin %parse_accept code *****************************************/
178555 /*********** End %parse_accept code *******************************************/
178556  sqlite3Fts5ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
178557 }
178558 
178559 /* The main parser program.
178560 ** The first argument is a pointer to a structure obtained from
178561 ** "sqlite3Fts5ParserAlloc" which describes the current state of the parser.
178562 ** The second argument is the major token number. The third is
178563 ** the minor token. The fourth optional argument is whatever the
178564 ** user wants (and specified in the grammar) and is available for
178565 ** use by the action routines.
178566 **
178567 ** Inputs:
178568 ** <ul>
178569 ** <li> A pointer to the parser (an opaque structure.)
178570 ** <li> The major token number.
178571 ** <li> The minor token number.
178572 ** <li> An option argument of a grammar-specified type.
178573 ** </ul>
178574 **
178575 ** Outputs:
178576 ** None.
178577 */
178578 static void sqlite3Fts5Parser(
178579  void *fts5yyp, /* The parser */
178580  int fts5yymajor, /* The major token code number */
178581  sqlite3Fts5ParserFTS5TOKENTYPE fts5yyminor /* The value for the token */
178582  sqlite3Fts5ParserARG_PDECL /* Optional %extra_argument parameter */
178583 ){
178584  fts5YYMINORTYPE fts5yyminorunion;
178585  unsigned int fts5yyact; /* The parser action. */
178586 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
178587  int fts5yyendofinput; /* True if we are at the end of input */
178588 #endif
178589 #ifdef fts5YYERRORSYMBOL
178590  int fts5yyerrorhit = 0; /* True if fts5yymajor has invoked an error */
178591 #endif
178592  fts5yyParser *fts5yypParser; /* The parser */
178593 
178594  /* (re)initialize the parser, if necessary */
178595  fts5yypParser = (fts5yyParser*)fts5yyp;
178596  if( fts5yypParser->fts5yyidx<0 ){
178597 #if fts5YYSTACKDEPTH<=0
178598  if( fts5yypParser->fts5yystksz <=0 ){
178599  fts5yyStackOverflow(fts5yypParser);
178600  return;
178601  }
178602 #endif
178603  fts5yypParser->fts5yyidx = 0;
178604 #ifndef fts5YYNOERRORRECOVERY
178605  fts5yypParser->fts5yyerrcnt = -1;
178606 #endif
178607  fts5yypParser->fts5yystack[0].stateno = 0;
178608  fts5yypParser->fts5yystack[0].major = 0;
178609 #ifndef NDEBUG
178610  if( fts5yyTraceFILE ){
178611  fprintf(fts5yyTraceFILE,"%sInitialize. Empty stack. State 0\n",
178612  fts5yyTracePrompt);
178613  }
178614 #endif
178615  }
178616 #if !defined(fts5YYERRORSYMBOL) && !defined(fts5YYNOERRORRECOVERY)
178617  fts5yyendofinput = (fts5yymajor==0);
178618 #endif
178619  sqlite3Fts5ParserARG_STORE;
178620 
178621 #ifndef NDEBUG
178622  if( fts5yyTraceFILE ){
178623  fprintf(fts5yyTraceFILE,"%sInput '%s'\n",fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
178624  }
178625 #endif
178626 
178627  do{
178628  fts5yyact = fts5yy_find_shift_action(fts5yypParser,(fts5YYCODETYPE)fts5yymajor);
178629  if( fts5yyact <= fts5YY_MAX_SHIFTREDUCE ){
178630  if( fts5yyact > fts5YY_MAX_SHIFT ) fts5yyact += fts5YY_MIN_REDUCE - fts5YY_MIN_SHIFTREDUCE;
178631  fts5yy_shift(fts5yypParser,fts5yyact,fts5yymajor,fts5yyminor);
178632 #ifndef fts5YYNOERRORRECOVERY
178633  fts5yypParser->fts5yyerrcnt--;
178634 #endif
178635  fts5yymajor = fts5YYNOCODE;
178636  }else if( fts5yyact <= fts5YY_MAX_REDUCE ){
178637  fts5yy_reduce(fts5yypParser,fts5yyact-fts5YY_MIN_REDUCE);
178638  }else{
178639  assert( fts5yyact == fts5YY_ERROR_ACTION );
178640  fts5yyminorunion.fts5yy0 = fts5yyminor;
178641 #ifdef fts5YYERRORSYMBOL
178642  int fts5yymx;
178643 #endif
178644 #ifndef NDEBUG
178645  if( fts5yyTraceFILE ){
178646  fprintf(fts5yyTraceFILE,"%sSyntax Error!\n",fts5yyTracePrompt);
178647  }
178648 #endif
178649 #ifdef fts5YYERRORSYMBOL
178650  /* A syntax error has occurred.
178651  ** The response to an error depends upon whether or not the
178652  ** grammar defines an error token "ERROR".
178653  **
178654  ** This is what we do if the grammar does define ERROR:
178655  **
178656  ** * Call the %syntax_error function.
178657  **
178658  ** * Begin popping the stack until we enter a state where
178659  ** it is legal to shift the error symbol, then shift
178660  ** the error symbol.
178661  **
178662  ** * Set the error count to three.
178663  **
178664  ** * Begin accepting and shifting new tokens. No new error
178665  ** processing will occur until three tokens have been
178666  ** shifted successfully.
178667  **
178668  */
178669  if( fts5yypParser->fts5yyerrcnt<0 ){
178670  fts5yy_syntax_error(fts5yypParser,fts5yymajor,fts5yyminor);
178671  }
178672  fts5yymx = fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].major;
178673  if( fts5yymx==fts5YYERRORSYMBOL || fts5yyerrorhit ){
178674 #ifndef NDEBUG
178675  if( fts5yyTraceFILE ){
178676  fprintf(fts5yyTraceFILE,"%sDiscard input token %s\n",
178677  fts5yyTracePrompt,fts5yyTokenName[fts5yymajor]);
178678  }
178679 #endif
178680  fts5yy_destructor(fts5yypParser, (fts5YYCODETYPE)fts5yymajor, &fts5yyminorunion);
178681  fts5yymajor = fts5YYNOCODE;
178682  }else{
178683  while(
178684  fts5yypParser->fts5yyidx >= 0 &&
178685  fts5yymx != fts5YYERRORSYMBOL &&
178686  (fts5yyact = fts5yy_find_reduce_action(
178687  fts5yypParser->fts5yystack[fts5yypParser->fts5yyidx].stateno,
178688  fts5YYERRORSYMBOL)) >= fts5YY_MIN_REDUCE
178689  ){
178690  fts5yy_pop_parser_stack(fts5yypParser);
178691  }
178692  if( fts5yypParser->fts5yyidx < 0 || fts5yymajor==0 ){
178693  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
178694  fts5yy_parse_failed(fts5yypParser);
178695  fts5yymajor = fts5YYNOCODE;
178696  }else if( fts5yymx!=fts5YYERRORSYMBOL ){
178697  fts5yy_shift(fts5yypParser,fts5yyact,fts5YYERRORSYMBOL,fts5yyminor);
178698  }
178699  }
178700  fts5yypParser->fts5yyerrcnt = 3;
178701  fts5yyerrorhit = 1;
178702 #elif defined(fts5YYNOERRORRECOVERY)
178703  /* If the fts5YYNOERRORRECOVERY macro is defined, then do not attempt to
178704  ** do any kind of error recovery. Instead, simply invoke the syntax
178705  ** error routine and continue going as if nothing had happened.
178706  **
178707  ** Applications can set this macro (for example inside %include) if
178708  ** they intend to abandon the parse upon the first syntax error seen.
178709  */
178710  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
178711  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
178712  fts5yymajor = fts5YYNOCODE;
178713 
178714 #else /* fts5YYERRORSYMBOL is not defined */
178715  /* This is what we do if the grammar does not define ERROR:
178716  **
178717  ** * Report an error message, and throw away the input token.
178718  **
178719  ** * If the input token is $, then fail the parse.
178720  **
178721  ** As before, subsequent error messages are suppressed until
178722  ** three input tokens have been successfully shifted.
178723  */
178724  if( fts5yypParser->fts5yyerrcnt<=0 ){
178725  fts5yy_syntax_error(fts5yypParser,fts5yymajor, fts5yyminor);
178726  }
178727  fts5yypParser->fts5yyerrcnt = 3;
178728  fts5yy_destructor(fts5yypParser,(fts5YYCODETYPE)fts5yymajor,&fts5yyminorunion);
178729  if( fts5yyendofinput ){
178730  fts5yy_parse_failed(fts5yypParser);
178731  }
178732  fts5yymajor = fts5YYNOCODE;
178733 #endif
178734  }
178735  }while( fts5yymajor!=fts5YYNOCODE && fts5yypParser->fts5yyidx>=0 );
178736 #ifndef NDEBUG
178737  if( fts5yyTraceFILE ){
178738  int i;
178739  fprintf(fts5yyTraceFILE,"%sReturn. Stack=",fts5yyTracePrompt);
178740  for(i=1; i<=fts5yypParser->fts5yyidx; i++)
178741  fprintf(fts5yyTraceFILE,"%c%s", i==1 ? '[' : ' ',
178742  fts5yyTokenName[fts5yypParser->fts5yystack[i].major]);
178743  fprintf(fts5yyTraceFILE,"]\n");
178744  }
178745 #endif
178746  return;
178747 }
178748 
178749 /*
178750 ** 2014 May 31
178751 **
178752 ** The author disclaims copyright to this source code. In place of
178753 ** a legal notice, here is a blessing:
178754 **
178755 ** May you do good and not evil.
178756 ** May you find forgiveness for yourself and forgive others.
178757 ** May you share freely, never taking more than you give.
178758 **
178759 ******************************************************************************
178760 */
178761 
178762 
178763 /* #include "fts5Int.h" */
178764 #include <math.h> /* amalgamator: keep */
178765 
178766 /*
178767 ** Object used to iterate through all "coalesced phrase instances" in
178768 ** a single column of the current row. If the phrase instances in the
178769 ** column being considered do not overlap, this object simply iterates
178770 ** through them. Or, if they do overlap (share one or more tokens in
178771 ** common), each set of overlapping instances is treated as a single
178772 ** match. See documentation for the highlight() auxiliary function for
178773 ** details.
178774 **
178775 ** Usage is:
178776 **
178777 ** for(rc = fts5CInstIterNext(pApi, pFts, iCol, &iter);
178778 ** (rc==SQLITE_OK && 0==fts5CInstIterEof(&iter);
178779 ** rc = fts5CInstIterNext(&iter)
178780 ** ){
178781 ** printf("instance starts at %d, ends at %d\n", iter.iStart, iter.iEnd);
178782 ** }
178783 **
178784 */
178785 typedef struct CInstIter CInstIter;
178786 struct CInstIter {
178787  const Fts5ExtensionApi *pApi; /* API offered by current FTS version */
178788  Fts5Context *pFts; /* First arg to pass to pApi functions */
178789  int iCol; /* Column to search */
178790  int iInst; /* Next phrase instance index */
178791  int nInst; /* Total number of phrase instances */
178792 
178793  /* Output variables */
178794  int iStart; /* First token in coalesced phrase instance */
178795  int iEnd; /* Last token in coalesced phrase instance */
178796 };
178797 
178798 /*
178799 ** Advance the iterator to the next coalesced phrase instance. Return
178800 ** an SQLite error code if an error occurs, or SQLITE_OK otherwise.
178801 */
178802 static int fts5CInstIterNext(CInstIter *pIter){
178803  int rc = SQLITE_OK;
178804  pIter->iStart = -1;
178805  pIter->iEnd = -1;
178806 
178807  while( rc==SQLITE_OK && pIter->iInst<pIter->nInst ){
178808  int ip; int ic; int io;
178809  rc = pIter->pApi->xInst(pIter->pFts, pIter->iInst, &ip, &ic, &io);
178810  if( rc==SQLITE_OK ){
178811  if( ic==pIter->iCol ){
178812  int iEnd = io - 1 + pIter->pApi->xPhraseSize(pIter->pFts, ip);
178813  if( pIter->iStart<0 ){
178814  pIter->iStart = io;
178815  pIter->iEnd = iEnd;
178816  }else if( io<=pIter->iEnd ){
178817  if( iEnd>pIter->iEnd ) pIter->iEnd = iEnd;
178818  }else{
178819  break;
178820  }
178821  }
178822  pIter->iInst++;
178823  }
178824  }
178825 
178826  return rc;
178827 }
178828 
178829 /*
178830 ** Initialize the iterator object indicated by the final parameter to
178831 ** iterate through coalesced phrase instances in column iCol.
178832 */
178833 static int fts5CInstIterInit(
178834  const Fts5ExtensionApi *pApi,
178835  Fts5Context *pFts,
178836  int iCol,
178837  CInstIter *pIter
178838 ){
178839  int rc;
178840 
178841  memset(pIter, 0, sizeof(CInstIter));
178842  pIter->pApi = pApi;
178843  pIter->pFts = pFts;
178844  pIter->iCol = iCol;
178845  rc = pApi->xInstCount(pFts, &pIter->nInst);
178846 
178847  if( rc==SQLITE_OK ){
178848  rc = fts5CInstIterNext(pIter);
178849  }
178850 
178851  return rc;
178852 }
178853 
178854 
178855 
178856 /*************************************************************************
178857 ** Start of highlight() implementation.
178858 */
178859 typedef struct HighlightContext HighlightContext;
178860 struct HighlightContext {
178861  CInstIter iter; /* Coalesced Instance Iterator */
178862  int iPos; /* Current token offset in zIn[] */
178863  int iRangeStart; /* First token to include */
178864  int iRangeEnd; /* If non-zero, last token to include */
178865  const char *zOpen; /* Opening highlight */
178866  const char *zClose; /* Closing highlight */
178867  const char *zIn; /* Input text */
178868  int nIn; /* Size of input text in bytes */
178869  int iOff; /* Current offset within zIn[] */
178870  char *zOut; /* Output value */
178871 };
178872 
178873 /*
178874 ** Append text to the HighlightContext output string - p->zOut. Argument
178875 ** z points to a buffer containing n bytes of text to append. If n is
178876 ** negative, everything up until the first '\0' is appended to the output.
178877 **
178878 ** If *pRc is set to any value other than SQLITE_OK when this function is
178879 ** called, it is a no-op. If an error (i.e. an OOM condition) is encountered,
178880 ** *pRc is set to an error code before returning.
178881 */
178882 static void fts5HighlightAppend(
178883  int *pRc,
178884  HighlightContext *p,
178885  const char *z, int n
178886 ){
178887  if( *pRc==SQLITE_OK ){
178888  if( n<0 ) n = (int)strlen(z);
178889  p->zOut = sqlite3_mprintf("%z%.*s", p->zOut, n, z);
178890  if( p->zOut==0 ) *pRc = SQLITE_NOMEM;
178891  }
178892 }
178893 
178894 /*
178895 ** Tokenizer callback used by implementation of highlight() function.
178896 */
178897 static int fts5HighlightCb(
178898  void *pContext, /* Pointer to HighlightContext object */
178899  int tflags, /* Mask of FTS5_TOKEN_* flags */
178900  const char *pToken, /* Buffer containing token */
178901  int nToken, /* Size of token in bytes */
178902  int iStartOff, /* Start offset of token */
178903  int iEndOff /* End offset of token */
178904 ){
178905  HighlightContext *p = (HighlightContext*)pContext;
178906  int rc = SQLITE_OK;
178907  int iPos;
178908 
178909  UNUSED_PARAM2(pToken, nToken);
178910 
178911  if( tflags & FTS5_TOKEN_COLOCATED ) return SQLITE_OK;
178912  iPos = p->iPos++;
178913 
178914  if( p->iRangeEnd>0 ){
178915  if( iPos<p->iRangeStart || iPos>p->iRangeEnd ) return SQLITE_OK;
178916  if( p->iRangeStart && iPos==p->iRangeStart ) p->iOff = iStartOff;
178917  }
178918 
178919  if( iPos==p->iter.iStart ){
178920  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iStartOff - p->iOff);
178921  fts5HighlightAppend(&rc, p, p->zOpen, -1);
178922  p->iOff = iStartOff;
178923  }
178924 
178925  if( iPos==p->iter.iEnd ){
178926  if( p->iRangeEnd && p->iter.iStart<p->iRangeStart ){
178927  fts5HighlightAppend(&rc, p, p->zOpen, -1);
178928  }
178929  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
178930  fts5HighlightAppend(&rc, p, p->zClose, -1);
178931  p->iOff = iEndOff;
178932  if( rc==SQLITE_OK ){
178933  rc = fts5CInstIterNext(&p->iter);
178934  }
178935  }
178936 
178937  if( p->iRangeEnd>0 && iPos==p->iRangeEnd ){
178938  fts5HighlightAppend(&rc, p, &p->zIn[p->iOff], iEndOff - p->iOff);
178939  p->iOff = iEndOff;
178940  if( iPos<p->iter.iEnd ){
178941  fts5HighlightAppend(&rc, p, p->zClose, -1);
178942  }
178943  }
178944 
178945  return rc;
178946 }
178947 
178948 /*
178949 ** Implementation of highlight() function.
178950 */
178951 static void fts5HighlightFunction(
178952  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
178953  Fts5Context *pFts, /* First arg to pass to pApi functions */
178954  sqlite3_context *pCtx, /* Context for returning result/error */
178955  int nVal, /* Number of values in apVal[] array */
178956  sqlite3_value **apVal /* Array of trailing arguments */
178957 ){
178958  HighlightContext ctx;
178959  int rc;
178960  int iCol;
178961 
178962  if( nVal!=3 ){
178963  const char *zErr = "wrong number of arguments to function highlight()";
178964  sqlite3_result_error(pCtx, zErr, -1);
178965  return;
178966  }
178967 
178968  iCol = sqlite3_value_int(apVal[0]);
178969  memset(&ctx, 0, sizeof(HighlightContext));
178970  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
178971  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
178972  rc = pApi->xColumnText(pFts, iCol, &ctx.zIn, &ctx.nIn);
178973 
178974  if( ctx.zIn ){
178975  if( rc==SQLITE_OK ){
178976  rc = fts5CInstIterInit(pApi, pFts, iCol, &ctx.iter);
178977  }
178978 
178979  if( rc==SQLITE_OK ){
178980  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
178981  }
178982  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
178983 
178984  if( rc==SQLITE_OK ){
178985  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
178986  }
178987  sqlite3_free(ctx.zOut);
178988  }
178989  if( rc!=SQLITE_OK ){
178990  sqlite3_result_error_code(pCtx, rc);
178991  }
178992 }
178993 /*
178994 ** End of highlight() implementation.
178995 **************************************************************************/
178996 
178997 /*
178998 ** Implementation of snippet() function.
178999 */
179000 static void fts5SnippetFunction(
179001  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
179002  Fts5Context *pFts, /* First arg to pass to pApi functions */
179003  sqlite3_context *pCtx, /* Context for returning result/error */
179004  int nVal, /* Number of values in apVal[] array */
179005  sqlite3_value **apVal /* Array of trailing arguments */
179006 ){
179007  HighlightContext ctx;
179008  int rc = SQLITE_OK; /* Return code */
179009  int iCol; /* 1st argument to snippet() */
179010  const char *zEllips; /* 4th argument to snippet() */
179011  int nToken; /* 5th argument to snippet() */
179012  int nInst = 0; /* Number of instance matches this row */
179013  int i; /* Used to iterate through instances */
179014  int nPhrase; /* Number of phrases in query */
179015  unsigned char *aSeen; /* Array of "seen instance" flags */
179016  int iBestCol; /* Column containing best snippet */
179017  int iBestStart = 0; /* First token of best snippet */
179018  int iBestLast; /* Last token of best snippet */
179019  int nBestScore = 0; /* Score of best snippet */
179020  int nColSize = 0; /* Total size of iBestCol in tokens */
179021 
179022  if( nVal!=5 ){
179023  const char *zErr = "wrong number of arguments to function snippet()";
179024  sqlite3_result_error(pCtx, zErr, -1);
179025  return;
179026  }
179027 
179028  memset(&ctx, 0, sizeof(HighlightContext));
179029  iCol = sqlite3_value_int(apVal[0]);
179030  ctx.zOpen = (const char*)sqlite3_value_text(apVal[1]);
179031  ctx.zClose = (const char*)sqlite3_value_text(apVal[2]);
179032  zEllips = (const char*)sqlite3_value_text(apVal[3]);
179033  nToken = sqlite3_value_int(apVal[4]);
179034  iBestLast = nToken-1;
179035 
179036  iBestCol = (iCol>=0 ? iCol : 0);
179037  nPhrase = pApi->xPhraseCount(pFts);
179038  aSeen = sqlite3_malloc(nPhrase);
179039  if( aSeen==0 ){
179040  rc = SQLITE_NOMEM;
179041  }
179042 
179043  if( rc==SQLITE_OK ){
179044  rc = pApi->xInstCount(pFts, &nInst);
179045  }
179046  for(i=0; rc==SQLITE_OK && i<nInst; i++){
179047  int ip, iSnippetCol, iStart;
179048  memset(aSeen, 0, nPhrase);
179049  rc = pApi->xInst(pFts, i, &ip, &iSnippetCol, &iStart);
179050  if( rc==SQLITE_OK && (iCol<0 || iSnippetCol==iCol) ){
179051  int nScore = 1000;
179052  int iLast = iStart - 1 + pApi->xPhraseSize(pFts, ip);
179053  int j;
179054  aSeen[ip] = 1;
179055 
179056  for(j=i+1; rc==SQLITE_OK && j<nInst; j++){
179057  int ic; int io; int iFinal;
179058  rc = pApi->xInst(pFts, j, &ip, &ic, &io);
179059  iFinal = io + pApi->xPhraseSize(pFts, ip) - 1;
179060  if( rc==SQLITE_OK && ic==iSnippetCol && iLast<iStart+nToken ){
179061  nScore += aSeen[ip] ? 1000 : 1;
179062  aSeen[ip] = 1;
179063  if( iFinal>iLast ) iLast = iFinal;
179064  }
179065  }
179066 
179067  if( rc==SQLITE_OK && nScore>nBestScore ){
179068  iBestCol = iSnippetCol;
179069  iBestStart = iStart;
179070  iBestLast = iLast;
179071  nBestScore = nScore;
179072  }
179073  }
179074  }
179075 
179076  if( rc==SQLITE_OK ){
179077  rc = pApi->xColumnSize(pFts, iBestCol, &nColSize);
179078  }
179079  if( rc==SQLITE_OK ){
179080  rc = pApi->xColumnText(pFts, iBestCol, &ctx.zIn, &ctx.nIn);
179081  }
179082  if( ctx.zIn ){
179083  if( rc==SQLITE_OK ){
179084  rc = fts5CInstIterInit(pApi, pFts, iBestCol, &ctx.iter);
179085  }
179086 
179087  if( (iBestStart+nToken-1)>iBestLast ){
179088  iBestStart -= (iBestStart+nToken-1-iBestLast) / 2;
179089  }
179090  if( iBestStart+nToken>nColSize ){
179091  iBestStart = nColSize - nToken;
179092  }
179093  if( iBestStart<0 ) iBestStart = 0;
179094 
179095  ctx.iRangeStart = iBestStart;
179096  ctx.iRangeEnd = iBestStart + nToken - 1;
179097 
179098  if( iBestStart>0 ){
179099  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
179100  }
179101  if( rc==SQLITE_OK ){
179102  rc = pApi->xTokenize(pFts, ctx.zIn, ctx.nIn, (void*)&ctx,fts5HighlightCb);
179103  }
179104  if( ctx.iRangeEnd>=(nColSize-1) ){
179105  fts5HighlightAppend(&rc, &ctx, &ctx.zIn[ctx.iOff], ctx.nIn - ctx.iOff);
179106  }else{
179107  fts5HighlightAppend(&rc, &ctx, zEllips, -1);
179108  }
179109 
179110  if( rc==SQLITE_OK ){
179111  sqlite3_result_text(pCtx, (const char*)ctx.zOut, -1, SQLITE_TRANSIENT);
179112  }else{
179113  sqlite3_result_error_code(pCtx, rc);
179114  }
179115  sqlite3_free(ctx.zOut);
179116  }
179117  sqlite3_free(aSeen);
179118 }
179119 
179120 /************************************************************************/
179121 
179122 /*
179123 ** The first time the bm25() function is called for a query, an instance
179124 ** of the following structure is allocated and populated.
179125 */
179126 typedef struct Fts5Bm25Data Fts5Bm25Data;
179127 struct Fts5Bm25Data {
179128  int nPhrase; /* Number of phrases in query */
179129  double avgdl; /* Average number of tokens in each row */
179130  double *aIDF; /* IDF for each phrase */
179131  double *aFreq; /* Array used to calculate phrase freq. */
179132 };
179133 
179134 /*
179135 ** Callback used by fts5Bm25GetData() to count the number of rows in the
179136 ** table matched by each individual phrase within the query.
179137 */
179138 static int fts5CountCb(
179139  const Fts5ExtensionApi *pApi,
179140  Fts5Context *pFts,
179141  void *pUserData /* Pointer to sqlite3_int64 variable */
179142 ){
179143  sqlite3_int64 *pn = (sqlite3_int64*)pUserData;
179144  UNUSED_PARAM2(pApi, pFts);
179145  (*pn)++;
179146  return SQLITE_OK;
179147 }
179148 
179149 /*
179150 ** Set *ppData to point to the Fts5Bm25Data object for the current query.
179151 ** If the object has not already been allocated, allocate and populate it
179152 ** now.
179153 */
179154 static int fts5Bm25GetData(
179155  const Fts5ExtensionApi *pApi,
179156  Fts5Context *pFts,
179157  Fts5Bm25Data **ppData /* OUT: bm25-data object for this query */
179158 ){
179159  int rc = SQLITE_OK; /* Return code */
179160  Fts5Bm25Data *p; /* Object to return */
179161 
179162  p = pApi->xGetAuxdata(pFts, 0);
179163  if( p==0 ){
179164  int nPhrase; /* Number of phrases in query */
179165  sqlite3_int64 nRow = 0; /* Number of rows in table */
179166  sqlite3_int64 nToken = 0; /* Number of tokens in table */
179167  int nByte; /* Bytes of space to allocate */
179168  int i;
179169 
179170  /* Allocate the Fts5Bm25Data object */
179171  nPhrase = pApi->xPhraseCount(pFts);
179172  nByte = sizeof(Fts5Bm25Data) + nPhrase*2*sizeof(double);
179173  p = (Fts5Bm25Data*)sqlite3_malloc(nByte);
179174  if( p==0 ){
179175  rc = SQLITE_NOMEM;
179176  }else{
179177  memset(p, 0, nByte);
179178  p->nPhrase = nPhrase;
179179  p->aIDF = (double*)&p[1];
179180  p->aFreq = &p->aIDF[nPhrase];
179181  }
179182 
179183  /* Calculate the average document length for this FTS5 table */
179184  if( rc==SQLITE_OK ) rc = pApi->xRowCount(pFts, &nRow);
179185  if( rc==SQLITE_OK ) rc = pApi->xColumnTotalSize(pFts, -1, &nToken);
179186  if( rc==SQLITE_OK ) p->avgdl = (double)nToken / (double)nRow;
179187 
179188  /* Calculate an IDF for each phrase in the query */
179189  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
179190  sqlite3_int64 nHit = 0;
179191  rc = pApi->xQueryPhrase(pFts, i, (void*)&nHit, fts5CountCb);
179192  if( rc==SQLITE_OK ){
179193  /* Calculate the IDF (Inverse Document Frequency) for phrase i.
179194  ** This is done using the standard BM25 formula as found on wikipedia:
179195  **
179196  ** IDF = log( (N - nHit + 0.5) / (nHit + 0.5) )
179197  **
179198  ** where "N" is the total number of documents in the set and nHit
179199  ** is the number that contain at least one instance of the phrase
179200  ** under consideration.
179201  **
179202  ** The problem with this is that if (N < 2*nHit), the IDF is
179203  ** negative. Which is undesirable. So the mimimum allowable IDF is
179204  ** (1e-6) - roughly the same as a term that appears in just over
179205  ** half of set of 5,000,000 documents. */
179206  double idf = log( (nRow - nHit + 0.5) / (nHit + 0.5) );
179207  if( idf<=0.0 ) idf = 1e-6;
179208  p->aIDF[i] = idf;
179209  }
179210  }
179211 
179212  if( rc!=SQLITE_OK ){
179213  sqlite3_free(p);
179214  }else{
179215  rc = pApi->xSetAuxdata(pFts, p, sqlite3_free);
179216  }
179217  if( rc!=SQLITE_OK ) p = 0;
179218  }
179219  *ppData = p;
179220  return rc;
179221 }
179222 
179223 /*
179224 ** Implementation of bm25() function.
179225 */
179226 static void fts5Bm25Function(
179227  const Fts5ExtensionApi *pApi, /* API offered by current FTS version */
179228  Fts5Context *pFts, /* First arg to pass to pApi functions */
179229  sqlite3_context *pCtx, /* Context for returning result/error */
179230  int nVal, /* Number of values in apVal[] array */
179231  sqlite3_value **apVal /* Array of trailing arguments */
179232 ){
179233  const double k1 = 1.2; /* Constant "k1" from BM25 formula */
179234  const double b = 0.75; /* Constant "b" from BM25 formula */
179235  int rc = SQLITE_OK; /* Error code */
179236  double score = 0.0; /* SQL function return value */
179237  Fts5Bm25Data *pData; /* Values allocated/calculated once only */
179238  int i; /* Iterator variable */
179239  int nInst = 0; /* Value returned by xInstCount() */
179240  double D = 0.0; /* Total number of tokens in row */
179241  double *aFreq = 0; /* Array of phrase freq. for current row */
179242 
179243  /* Calculate the phrase frequency (symbol "f(qi,D)" in the documentation)
179244  ** for each phrase in the query for the current row. */
179245  rc = fts5Bm25GetData(pApi, pFts, &pData);
179246  if( rc==SQLITE_OK ){
179247  aFreq = pData->aFreq;
179248  memset(aFreq, 0, sizeof(double) * pData->nPhrase);
179249  rc = pApi->xInstCount(pFts, &nInst);
179250  }
179251  for(i=0; rc==SQLITE_OK && i<nInst; i++){
179252  int ip; int ic; int io;
179253  rc = pApi->xInst(pFts, i, &ip, &ic, &io);
179254  if( rc==SQLITE_OK ){
179255  double w = (nVal > ic) ? sqlite3_value_double(apVal[ic]) : 1.0;
179256  aFreq[ip] += w;
179257  }
179258  }
179259 
179260  /* Figure out the total size of the current row in tokens. */
179261  if( rc==SQLITE_OK ){
179262  int nTok;
179263  rc = pApi->xColumnSize(pFts, -1, &nTok);
179264  D = (double)nTok;
179265  }
179266 
179267  /* Determine the BM25 score for the current row. */
179268  for(i=0; rc==SQLITE_OK && i<pData->nPhrase; i++){
179269  score += pData->aIDF[i] * (
179270  ( aFreq[i] * (k1 + 1.0) ) /
179271  ( aFreq[i] + k1 * (1 - b + b * D / pData->avgdl) )
179272  );
179273  }
179274 
179275  /* If no error has occurred, return the calculated score. Otherwise,
179276  ** throw an SQL exception. */
179277  if( rc==SQLITE_OK ){
179278  sqlite3_result_double(pCtx, -1.0 * score);
179279  }else{
179280  sqlite3_result_error_code(pCtx, rc);
179281  }
179282 }
179283 
179284 static int sqlite3Fts5AuxInit(fts5_api *pApi){
179285  struct Builtin {
179286  const char *zFunc; /* Function name (nul-terminated) */
179287  void *pUserData; /* User-data pointer */
179288  fts5_extension_function xFunc;/* Callback function */
179289  void (*xDestroy)(void*); /* Destructor function */
179290  } aBuiltin [] = {
179291  { "snippet", 0, fts5SnippetFunction, 0 },
179292  { "highlight", 0, fts5HighlightFunction, 0 },
179293  { "bm25", 0, fts5Bm25Function, 0 },
179294  };
179295  int rc = SQLITE_OK; /* Return code */
179296  int i; /* To iterate through builtin functions */
179297 
179298  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
179299  rc = pApi->xCreateFunction(pApi,
179300  aBuiltin[i].zFunc,
179301  aBuiltin[i].pUserData,
179302  aBuiltin[i].xFunc,
179303  aBuiltin[i].xDestroy
179304  );
179305  }
179306 
179307  return rc;
179308 }
179309 
179310 
179311 
179312 /*
179313 ** 2014 May 31
179314 **
179315 ** The author disclaims copyright to this source code. In place of
179316 ** a legal notice, here is a blessing:
179317 **
179318 ** May you do good and not evil.
179319 ** May you find forgiveness for yourself and forgive others.
179320 ** May you share freely, never taking more than you give.
179321 **
179322 ******************************************************************************
179323 */
179324 
179325 
179326 
179327 /* #include "fts5Int.h" */
179328 
179329 static int sqlite3Fts5BufferSize(int *pRc, Fts5Buffer *pBuf, u32 nByte){
179330  if( (u32)pBuf->nSpace<nByte ){
179331  u32 nNew = pBuf->nSpace ? pBuf->nSpace : 64;
179332  u8 *pNew;
179333  while( nNew<nByte ){
179334  nNew = nNew * 2;
179335  }
179336  pNew = sqlite3_realloc(pBuf->p, nNew);
179337  if( pNew==0 ){
179338  *pRc = SQLITE_NOMEM;
179339  return 1;
179340  }else{
179341  pBuf->nSpace = nNew;
179342  pBuf->p = pNew;
179343  }
179344  }
179345  return 0;
179346 }
179347 
179348 
179349 /*
179350 ** Encode value iVal as an SQLite varint and append it to the buffer object
179351 ** pBuf. If an OOM error occurs, set the error code in p.
179352 */
179353 static void sqlite3Fts5BufferAppendVarint(int *pRc, Fts5Buffer *pBuf, i64 iVal){
179354  if( fts5BufferGrow(pRc, pBuf, 9) ) return;
179355  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iVal);
179356 }
179357 
179358 static void sqlite3Fts5Put32(u8 *aBuf, int iVal){
179359  aBuf[0] = (iVal>>24) & 0x00FF;
179360  aBuf[1] = (iVal>>16) & 0x00FF;
179361  aBuf[2] = (iVal>> 8) & 0x00FF;
179362  aBuf[3] = (iVal>> 0) & 0x00FF;
179363 }
179364 
179365 static int sqlite3Fts5Get32(const u8 *aBuf){
179366  return (aBuf[0] << 24) + (aBuf[1] << 16) + (aBuf[2] << 8) + aBuf[3];
179367 }
179368 
179369 /*
179370 ** Append buffer nData/pData to buffer pBuf. If an OOM error occurs, set
179371 ** the error code in p. If an error has already occurred when this function
179372 ** is called, it is a no-op.
179373 */
179374 static void sqlite3Fts5BufferAppendBlob(
179375  int *pRc,
179376  Fts5Buffer *pBuf,
179377  u32 nData,
179378  const u8 *pData
179379 ){
179380  assert_nc( *pRc || nData>=0 );
179381  if( fts5BufferGrow(pRc, pBuf, nData) ) return;
179382  memcpy(&pBuf->p[pBuf->n], pData, nData);
179383  pBuf->n += nData;
179384 }
179385 
179386 /*
179387 ** Append the nul-terminated string zStr to the buffer pBuf. This function
179388 ** ensures that the byte following the buffer data is set to 0x00, even
179389 ** though this byte is not included in the pBuf->n count.
179390 */
179391 static void sqlite3Fts5BufferAppendString(
179392  int *pRc,
179393  Fts5Buffer *pBuf,
179394  const char *zStr
179395 ){
179396  int nStr = (int)strlen(zStr);
179397  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nStr+1, (const u8*)zStr);
179398  pBuf->n--;
179399 }
179400 
179401 /*
179402 ** Argument zFmt is a printf() style format string. This function performs
179403 ** the printf() style processing, then appends the results to buffer pBuf.
179404 **
179405 ** Like sqlite3Fts5BufferAppendString(), this function ensures that the byte
179406 ** following the buffer data is set to 0x00, even though this byte is not
179407 ** included in the pBuf->n count.
179408 */
179409 static void sqlite3Fts5BufferAppendPrintf(
179410  int *pRc,
179411  Fts5Buffer *pBuf,
179412  char *zFmt, ...
179413 ){
179414  if( *pRc==SQLITE_OK ){
179415  char *zTmp;
179416  va_list ap;
179417  va_start(ap, zFmt);
179418  zTmp = sqlite3_vmprintf(zFmt, ap);
179419  va_end(ap);
179420 
179421  if( zTmp==0 ){
179422  *pRc = SQLITE_NOMEM;
179423  }else{
179424  sqlite3Fts5BufferAppendString(pRc, pBuf, zTmp);
179425  sqlite3_free(zTmp);
179426  }
179427  }
179428 }
179429 
179430 static char *sqlite3Fts5Mprintf(int *pRc, const char *zFmt, ...){
179431  char *zRet = 0;
179432  if( *pRc==SQLITE_OK ){
179433  va_list ap;
179434  va_start(ap, zFmt);
179435  zRet = sqlite3_vmprintf(zFmt, ap);
179436  va_end(ap);
179437  if( zRet==0 ){
179438  *pRc = SQLITE_NOMEM;
179439  }
179440  }
179441  return zRet;
179442 }
179443 
179444 
179445 /*
179446 ** Free any buffer allocated by pBuf. Zero the structure before returning.
179447 */
179448 static void sqlite3Fts5BufferFree(Fts5Buffer *pBuf){
179449  sqlite3_free(pBuf->p);
179450  memset(pBuf, 0, sizeof(Fts5Buffer));
179451 }
179452 
179453 /*
179454 ** Zero the contents of the buffer object. But do not free the associated
179455 ** memory allocation.
179456 */
179457 static void sqlite3Fts5BufferZero(Fts5Buffer *pBuf){
179458  pBuf->n = 0;
179459 }
179460 
179461 /*
179462 ** Set the buffer to contain nData/pData. If an OOM error occurs, leave an
179463 ** the error code in p. If an error has already occurred when this function
179464 ** is called, it is a no-op.
179465 */
179466 static void sqlite3Fts5BufferSet(
179467  int *pRc,
179468  Fts5Buffer *pBuf,
179469  int nData,
179470  const u8 *pData
179471 ){
179472  pBuf->n = 0;
179473  sqlite3Fts5BufferAppendBlob(pRc, pBuf, nData, pData);
179474 }
179475 
179476 static int sqlite3Fts5PoslistNext64(
179477  const u8 *a, int n, /* Buffer containing poslist */
179478  int *pi, /* IN/OUT: Offset within a[] */
179479  i64 *piOff /* IN/OUT: Current offset */
179480 ){
179481  int i = *pi;
179482  if( i>=n ){
179483  /* EOF */
179484  *piOff = -1;
179485  return 1;
179486  }else{
179487  i64 iOff = *piOff;
179488  int iVal;
179489  fts5FastGetVarint32(a, i, iVal);
179490  if( iVal==1 ){
179491  fts5FastGetVarint32(a, i, iVal);
179492  iOff = ((i64)iVal) << 32;
179493  fts5FastGetVarint32(a, i, iVal);
179494  }
179495  *piOff = iOff + (iVal-2);
179496  *pi = i;
179497  return 0;
179498  }
179499 }
179500 
179501 
179502 /*
179503 ** Advance the iterator object passed as the only argument. Return true
179504 ** if the iterator reaches EOF, or false otherwise.
179505 */
179506 static int sqlite3Fts5PoslistReaderNext(Fts5PoslistReader *pIter){
179507  if( sqlite3Fts5PoslistNext64(pIter->a, pIter->n, &pIter->i, &pIter->iPos) ){
179508  pIter->bEof = 1;
179509  }
179510  return pIter->bEof;
179511 }
179512 
179513 static int sqlite3Fts5PoslistReaderInit(
179514  const u8 *a, int n, /* Poslist buffer to iterate through */
179515  Fts5PoslistReader *pIter /* Iterator object to initialize */
179516 ){
179517  memset(pIter, 0, sizeof(*pIter));
179518  pIter->a = a;
179519  pIter->n = n;
179520  sqlite3Fts5PoslistReaderNext(pIter);
179521  return pIter->bEof;
179522 }
179523 
179524 /*
179525 ** Append position iPos to the position list being accumulated in buffer
179526 ** pBuf, which must be already be large enough to hold the new data.
179527 ** The previous position written to this list is *piPrev. *piPrev is set
179528 ** to iPos before returning.
179529 */
179530 static void sqlite3Fts5PoslistSafeAppend(
179531  Fts5Buffer *pBuf,
179532  i64 *piPrev,
179533  i64 iPos
179534 ){
179535  static const i64 colmask = ((i64)(0x7FFFFFFF)) << 32;
179536  if( (iPos & colmask) != (*piPrev & colmask) ){
179537  pBuf->p[pBuf->n++] = 1;
179538  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos>>32));
179539  *piPrev = (iPos & colmask);
179540  }
179541  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], (iPos-*piPrev)+2);
179542  *piPrev = iPos;
179543 }
179544 
179545 static int sqlite3Fts5PoslistWriterAppend(
179546  Fts5Buffer *pBuf,
179547  Fts5PoslistWriter *pWriter,
179548  i64 iPos
179549 ){
179550  int rc = 0; /* Initialized only to suppress erroneous warning from Clang */
179551  if( fts5BufferGrow(&rc, pBuf, 5+5+5) ) return rc;
179552  sqlite3Fts5PoslistSafeAppend(pBuf, &pWriter->iPrev, iPos);
179553  return SQLITE_OK;
179554 }
179555 
179556 static void *sqlite3Fts5MallocZero(int *pRc, int nByte){
179557  void *pRet = 0;
179558  if( *pRc==SQLITE_OK ){
179559  pRet = sqlite3_malloc(nByte);
179560  if( pRet==0 && nByte>0 ){
179561  *pRc = SQLITE_NOMEM;
179562  }else{
179563  memset(pRet, 0, nByte);
179564  }
179565  }
179566  return pRet;
179567 }
179568 
179569 /*
179570 ** Return a nul-terminated copy of the string indicated by pIn. If nIn
179571 ** is non-negative, then it is the length of the string in bytes. Otherwise,
179572 ** the length of the string is determined using strlen().
179573 **
179574 ** It is the responsibility of the caller to eventually free the returned
179575 ** buffer using sqlite3_free(). If an OOM error occurs, NULL is returned.
179576 */
179577 static char *sqlite3Fts5Strndup(int *pRc, const char *pIn, int nIn){
179578  char *zRet = 0;
179579  if( *pRc==SQLITE_OK ){
179580  if( nIn<0 ){
179581  nIn = (int)strlen(pIn);
179582  }
179583  zRet = (char*)sqlite3_malloc(nIn+1);
179584  if( zRet ){
179585  memcpy(zRet, pIn, nIn);
179586  zRet[nIn] = '\0';
179587  }else{
179588  *pRc = SQLITE_NOMEM;
179589  }
179590  }
179591  return zRet;
179592 }
179593 
179594 
179595 /*
179596 ** Return true if character 't' may be part of an FTS5 bareword, or false
179597 ** otherwise. Characters that may be part of barewords:
179598 **
179599 ** * All non-ASCII characters,
179600 ** * The 52 upper and lower case ASCII characters, and
179601 ** * The 10 integer ASCII characters.
179602 ** * The underscore character "_" (0x5F).
179603 ** * The unicode "subsitute" character (0x1A).
179604 */
179605 static int sqlite3Fts5IsBareword(char t){
179606  u8 aBareword[128] = {
179607  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00 .. 0x0F */
179608  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, /* 0x10 .. 0x1F */
179609  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20 .. 0x2F */
179610  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30 .. 0x3F */
179611  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40 .. 0x4F */
179612  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 0x50 .. 0x5F */
179613  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60 .. 0x6F */
179614  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 /* 0x70 .. 0x7F */
179615  };
179616 
179617  return (t & 0x80) || aBareword[(int)t];
179618 }
179619 
179620 
179621 /*************************************************************************
179622 */
179623 typedef struct Fts5TermsetEntry Fts5TermsetEntry;
179624 struct Fts5TermsetEntry {
179625  char *pTerm;
179626  int nTerm;
179627  int iIdx; /* Index (main or aPrefix[] entry) */
179628  Fts5TermsetEntry *pNext;
179629 };
179630 
179631 struct Fts5Termset {
179632  Fts5TermsetEntry *apHash[512];
179633 };
179634 
179635 static int sqlite3Fts5TermsetNew(Fts5Termset **pp){
179636  int rc = SQLITE_OK;
179637  *pp = sqlite3Fts5MallocZero(&rc, sizeof(Fts5Termset));
179638  return rc;
179639 }
179640 
179641 static int sqlite3Fts5TermsetAdd(
179642  Fts5Termset *p,
179643  int iIdx,
179644  const char *pTerm, int nTerm,
179645  int *pbPresent
179646 ){
179647  int rc = SQLITE_OK;
179648  *pbPresent = 0;
179649  if( p ){
179650  int i;
179651  u32 hash = 13;
179652  Fts5TermsetEntry *pEntry;
179653 
179654  /* Calculate a hash value for this term. This is the same hash checksum
179655  ** used by the fts5_hash.c module. This is not important for correct
179656  ** operation of the module, but is necessary to ensure that some tests
179657  ** designed to produce hash table collisions really do work. */
179658  for(i=nTerm-1; i>=0; i--){
179659  hash = (hash << 3) ^ hash ^ pTerm[i];
179660  }
179661  hash = (hash << 3) ^ hash ^ iIdx;
179662  hash = hash % ArraySize(p->apHash);
179663 
179664  for(pEntry=p->apHash[hash]; pEntry; pEntry=pEntry->pNext){
179665  if( pEntry->iIdx==iIdx
179666  && pEntry->nTerm==nTerm
179667  && memcmp(pEntry->pTerm, pTerm, nTerm)==0
179668  ){
179669  *pbPresent = 1;
179670  break;
179671  }
179672  }
179673 
179674  if( pEntry==0 ){
179675  pEntry = sqlite3Fts5MallocZero(&rc, sizeof(Fts5TermsetEntry) + nTerm);
179676  if( pEntry ){
179677  pEntry->pTerm = (char*)&pEntry[1];
179678  pEntry->nTerm = nTerm;
179679  pEntry->iIdx = iIdx;
179680  memcpy(pEntry->pTerm, pTerm, nTerm);
179681  pEntry->pNext = p->apHash[hash];
179682  p->apHash[hash] = pEntry;
179683  }
179684  }
179685  }
179686 
179687  return rc;
179688 }
179689 
179690 static void sqlite3Fts5TermsetFree(Fts5Termset *p){
179691  if( p ){
179692  u32 i;
179693  for(i=0; i<ArraySize(p->apHash); i++){
179694  Fts5TermsetEntry *pEntry = p->apHash[i];
179695  while( pEntry ){
179696  Fts5TermsetEntry *pDel = pEntry;
179697  pEntry = pEntry->pNext;
179698  sqlite3_free(pDel);
179699  }
179700  }
179701  sqlite3_free(p);
179702  }
179703 }
179704 
179705 /*
179706 ** 2014 Jun 09
179707 **
179708 ** The author disclaims copyright to this source code. In place of
179709 ** a legal notice, here is a blessing:
179710 **
179711 ** May you do good and not evil.
179712 ** May you find forgiveness for yourself and forgive others.
179713 ** May you share freely, never taking more than you give.
179714 **
179715 ******************************************************************************
179716 **
179717 ** This is an SQLite module implementing full-text search.
179718 */
179719 
179720 
179721 /* #include "fts5Int.h" */
179722 
179723 #define FTS5_DEFAULT_PAGE_SIZE 4050
179724 #define FTS5_DEFAULT_AUTOMERGE 4
179725 #define FTS5_DEFAULT_USERMERGE 4
179726 #define FTS5_DEFAULT_CRISISMERGE 16
179727 #define FTS5_DEFAULT_HASHSIZE (1024*1024)
179728 
179729 /* Maximum allowed page size */
179730 #define FTS5_MAX_PAGE_SIZE (128*1024)
179731 
179732 static int fts5_iswhitespace(char x){
179733  return (x==' ');
179734 }
179735 
179736 static int fts5_isopenquote(char x){
179737  return (x=='"' || x=='\'' || x=='[' || x=='`');
179738 }
179739 
179740 /*
179741 ** Argument pIn points to a character that is part of a nul-terminated
179742 ** string. Return a pointer to the first character following *pIn in
179743 ** the string that is not a white-space character.
179744 */
179745 static const char *fts5ConfigSkipWhitespace(const char *pIn){
179746  const char *p = pIn;
179747  if( p ){
179748  while( fts5_iswhitespace(*p) ){ p++; }
179749  }
179750  return p;
179751 }
179752 
179753 /*
179754 ** Argument pIn points to a character that is part of a nul-terminated
179755 ** string. Return a pointer to the first character following *pIn in
179756 ** the string that is not a "bareword" character.
179757 */
179758 static const char *fts5ConfigSkipBareword(const char *pIn){
179759  const char *p = pIn;
179760  while ( sqlite3Fts5IsBareword(*p) ) p++;
179761  if( p==pIn ) p = 0;
179762  return p;
179763 }
179764 
179765 static int fts5_isdigit(char a){
179766  return (a>='0' && a<='9');
179767 }
179768 
179769 
179770 
179771 static const char *fts5ConfigSkipLiteral(const char *pIn){
179772  const char *p = pIn;
179773  switch( *p ){
179774  case 'n': case 'N':
179775  if( sqlite3_strnicmp("null", p, 4)==0 ){
179776  p = &p[4];
179777  }else{
179778  p = 0;
179779  }
179780  break;
179781 
179782  case 'x': case 'X':
179783  p++;
179784  if( *p=='\'' ){
179785  p++;
179786  while( (*p>='a' && *p<='f')
179787  || (*p>='A' && *p<='F')
179788  || (*p>='0' && *p<='9')
179789  ){
179790  p++;
179791  }
179792  if( *p=='\'' && 0==((p-pIn)%2) ){
179793  p++;
179794  }else{
179795  p = 0;
179796  }
179797  }else{
179798  p = 0;
179799  }
179800  break;
179801 
179802  case '\'':
179803  p++;
179804  while( p ){
179805  if( *p=='\'' ){
179806  p++;
179807  if( *p!='\'' ) break;
179808  }
179809  p++;
179810  if( *p==0 ) p = 0;
179811  }
179812  break;
179813 
179814  default:
179815  /* maybe a number */
179816  if( *p=='+' || *p=='-' ) p++;
179817  while( fts5_isdigit(*p) ) p++;
179818 
179819  /* At this point, if the literal was an integer, the parse is
179820  ** finished. Or, if it is a floating point value, it may continue
179821  ** with either a decimal point or an 'E' character. */
179822  if( *p=='.' && fts5_isdigit(p[1]) ){
179823  p += 2;
179824  while( fts5_isdigit(*p) ) p++;
179825  }
179826  if( p==pIn ) p = 0;
179827 
179828  break;
179829  }
179830 
179831  return p;
179832 }
179833 
179834 /*
179835 ** The first character of the string pointed to by argument z is guaranteed
179836 ** to be an open-quote character (see function fts5_isopenquote()).
179837 **
179838 ** This function searches for the corresponding close-quote character within
179839 ** the string and, if found, dequotes the string in place and adds a new
179840 ** nul-terminator byte.
179841 **
179842 ** If the close-quote is found, the value returned is the byte offset of
179843 ** the character immediately following it. Or, if the close-quote is not
179844 ** found, -1 is returned. If -1 is returned, the buffer is left in an
179845 ** undefined state.
179846 */
179847 static int fts5Dequote(char *z){
179848  char q;
179849  int iIn = 1;
179850  int iOut = 0;
179851  q = z[0];
179852 
179853  /* Set stack variable q to the close-quote character */
179854  assert( q=='[' || q=='\'' || q=='"' || q=='`' );
179855  if( q=='[' ) q = ']';
179856 
179857  while( ALWAYS(z[iIn]) ){
179858  if( z[iIn]==q ){
179859  if( z[iIn+1]!=q ){
179860  /* Character iIn was the close quote. */
179861  iIn++;
179862  break;
179863  }else{
179864  /* Character iIn and iIn+1 form an escaped quote character. Skip
179865  ** the input cursor past both and copy a single quote character
179866  ** to the output buffer. */
179867  iIn += 2;
179868  z[iOut++] = q;
179869  }
179870  }else{
179871  z[iOut++] = z[iIn++];
179872  }
179873  }
179874 
179875  z[iOut] = '\0';
179876  return iIn;
179877 }
179878 
179879 /*
179880 ** Convert an SQL-style quoted string into a normal string by removing
179881 ** the quote characters. The conversion is done in-place. If the
179882 ** input does not begin with a quote character, then this routine
179883 ** is a no-op.
179884 **
179885 ** Examples:
179886 **
179887 ** "abc" becomes abc
179888 ** 'xyz' becomes xyz
179889 ** [pqr] becomes pqr
179890 ** `mno` becomes mno
179891 */
179892 static void sqlite3Fts5Dequote(char *z){
179893  char quote; /* Quote character (if any ) */
179894 
179895  assert( 0==fts5_iswhitespace(z[0]) );
179896  quote = z[0];
179897  if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
179898  fts5Dequote(z);
179899  }
179900 }
179901 
179902 
179903 struct Fts5Enum {
179904  const char *zName;
179905  int eVal;
179906 };
179907 typedef struct Fts5Enum Fts5Enum;
179908 
179909 static int fts5ConfigSetEnum(
179910  const Fts5Enum *aEnum,
179911  const char *zEnum,
179912  int *peVal
179913 ){
179914  int nEnum = (int)strlen(zEnum);
179915  int i;
179916  int iVal = -1;
179917 
179918  for(i=0; aEnum[i].zName; i++){
179919  if( sqlite3_strnicmp(aEnum[i].zName, zEnum, nEnum)==0 ){
179920  if( iVal>=0 ) return SQLITE_ERROR;
179921  iVal = aEnum[i].eVal;
179922  }
179923  }
179924 
179925  *peVal = iVal;
179926  return iVal<0 ? SQLITE_ERROR : SQLITE_OK;
179927 }
179928 
179929 /*
179930 ** Parse a "special" CREATE VIRTUAL TABLE directive and update
179931 ** configuration object pConfig as appropriate.
179932 **
179933 ** If successful, object pConfig is updated and SQLITE_OK returned. If
179934 ** an error occurs, an SQLite error code is returned and an error message
179935 ** may be left in *pzErr. It is the responsibility of the caller to
179936 ** eventually free any such error message using sqlite3_free().
179937 */
179938 static int fts5ConfigParseSpecial(
179939  Fts5Global *pGlobal,
179940  Fts5Config *pConfig, /* Configuration object to update */
179941  const char *zCmd, /* Special command to parse */
179942  const char *zArg, /* Argument to parse */
179943  char **pzErr /* OUT: Error message */
179944 ){
179945  int rc = SQLITE_OK;
179946  int nCmd = (int)strlen(zCmd);
179947  if( sqlite3_strnicmp("prefix", zCmd, nCmd)==0 ){
179948  const int nByte = sizeof(int) * FTS5_MAX_PREFIX_INDEXES;
179949  const char *p;
179950  int bFirst = 1;
179951  if( pConfig->aPrefix==0 ){
179952  pConfig->aPrefix = sqlite3Fts5MallocZero(&rc, nByte);
179953  if( rc ) return rc;
179954  }
179955 
179956  p = zArg;
179957  while( 1 ){
179958  int nPre = 0;
179959 
179960  while( p[0]==' ' ) p++;
179961  if( bFirst==0 && p[0]==',' ){
179962  p++;
179963  while( p[0]==' ' ) p++;
179964  }else if( p[0]=='\0' ){
179965  break;
179966  }
179967  if( p[0]<'0' || p[0]>'9' ){
179968  *pzErr = sqlite3_mprintf("malformed prefix=... directive");
179969  rc = SQLITE_ERROR;
179970  break;
179971  }
179972 
179973  if( pConfig->nPrefix==FTS5_MAX_PREFIX_INDEXES ){
179974  *pzErr = sqlite3_mprintf(
179975  "too many prefix indexes (max %d)", FTS5_MAX_PREFIX_INDEXES
179976  );
179977  rc = SQLITE_ERROR;
179978  break;
179979  }
179980 
179981  while( p[0]>='0' && p[0]<='9' && nPre<1000 ){
179982  nPre = nPre*10 + (p[0] - '0');
179983  p++;
179984  }
179985 
179986  if( nPre<=0 || nPre>=1000 ){
179987  *pzErr = sqlite3_mprintf("prefix length out of range (max 999)");
179988  rc = SQLITE_ERROR;
179989  break;
179990  }
179991 
179992  pConfig->aPrefix[pConfig->nPrefix] = nPre;
179993  pConfig->nPrefix++;
179994  bFirst = 0;
179995  }
179996  assert( pConfig->nPrefix<=FTS5_MAX_PREFIX_INDEXES );
179997  return rc;
179998  }
179999 
180000  if( sqlite3_strnicmp("tokenize", zCmd, nCmd)==0 ){
180001  const char *p = (const char*)zArg;
180002  int nArg = (int)strlen(zArg) + 1;
180003  char **azArg = sqlite3Fts5MallocZero(&rc, sizeof(char*) * nArg);
180004  char *pDel = sqlite3Fts5MallocZero(&rc, nArg * 2);
180005  char *pSpace = pDel;
180006 
180007  if( azArg && pSpace ){
180008  if( pConfig->pTok ){
180009  *pzErr = sqlite3_mprintf("multiple tokenize=... directives");
180010  rc = SQLITE_ERROR;
180011  }else{
180012  for(nArg=0; p && *p; nArg++){
180013  const char *p2 = fts5ConfigSkipWhitespace(p);
180014  if( *p2=='\'' ){
180015  p = fts5ConfigSkipLiteral(p2);
180016  }else{
180017  p = fts5ConfigSkipBareword(p2);
180018  }
180019  if( p ){
180020  memcpy(pSpace, p2, p-p2);
180021  azArg[nArg] = pSpace;
180022  sqlite3Fts5Dequote(pSpace);
180023  pSpace += (p - p2) + 1;
180024  p = fts5ConfigSkipWhitespace(p);
180025  }
180026  }
180027  if( p==0 ){
180028  *pzErr = sqlite3_mprintf("parse error in tokenize directive");
180029  rc = SQLITE_ERROR;
180030  }else{
180031  rc = sqlite3Fts5GetTokenizer(pGlobal,
180032  (const char**)azArg, nArg, &pConfig->pTok, &pConfig->pTokApi,
180033  pzErr
180034  );
180035  }
180036  }
180037  }
180038 
180039  sqlite3_free(azArg);
180040  sqlite3_free(pDel);
180041  return rc;
180042  }
180043 
180044  if( sqlite3_strnicmp("content", zCmd, nCmd)==0 ){
180045  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
180046  *pzErr = sqlite3_mprintf("multiple content=... directives");
180047  rc = SQLITE_ERROR;
180048  }else{
180049  if( zArg[0] ){
180050  pConfig->eContent = FTS5_CONTENT_EXTERNAL;
180051  pConfig->zContent = sqlite3Fts5Mprintf(&rc, "%Q.%Q", pConfig->zDb,zArg);
180052  }else{
180053  pConfig->eContent = FTS5_CONTENT_NONE;
180054  }
180055  }
180056  return rc;
180057  }
180058 
180059  if( sqlite3_strnicmp("content_rowid", zCmd, nCmd)==0 ){
180060  if( pConfig->zContentRowid ){
180061  *pzErr = sqlite3_mprintf("multiple content_rowid=... directives");
180062  rc = SQLITE_ERROR;
180063  }else{
180064  pConfig->zContentRowid = sqlite3Fts5Strndup(&rc, zArg, -1);
180065  }
180066  return rc;
180067  }
180068 
180069  if( sqlite3_strnicmp("columnsize", zCmd, nCmd)==0 ){
180070  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1]!='\0' ){
180071  *pzErr = sqlite3_mprintf("malformed columnsize=... directive");
180072  rc = SQLITE_ERROR;
180073  }else{
180074  pConfig->bColumnsize = (zArg[0]=='1');
180075  }
180076  return rc;
180077  }
180078 
180079  if( sqlite3_strnicmp("detail", zCmd, nCmd)==0 ){
180080  const Fts5Enum aDetail[] = {
180081  { "none", FTS5_DETAIL_NONE },
180082  { "full", FTS5_DETAIL_FULL },
180083  { "columns", FTS5_DETAIL_COLUMNS },
180084  { 0, 0 }
180085  };
180086 
180087  if( (rc = fts5ConfigSetEnum(aDetail, zArg, &pConfig->eDetail)) ){
180088  *pzErr = sqlite3_mprintf("malformed detail=... directive");
180089  }
180090  return rc;
180091  }
180092 
180093  *pzErr = sqlite3_mprintf("unrecognized option: \"%.*s\"", nCmd, zCmd);
180094  return SQLITE_ERROR;
180095 }
180096 
180097 /*
180098 ** Allocate an instance of the default tokenizer ("simple") at
180099 ** Fts5Config.pTokenizer. Return SQLITE_OK if successful, or an SQLite error
180100 ** code if an error occurs.
180101 */
180102 static int fts5ConfigDefaultTokenizer(Fts5Global *pGlobal, Fts5Config *pConfig){
180103  assert( pConfig->pTok==0 && pConfig->pTokApi==0 );
180104  return sqlite3Fts5GetTokenizer(
180105  pGlobal, 0, 0, &pConfig->pTok, &pConfig->pTokApi, 0
180106  );
180107 }
180108 
180109 /*
180110 ** Gobble up the first bareword or quoted word from the input buffer zIn.
180111 ** Return a pointer to the character immediately following the last in
180112 ** the gobbled word if successful, or a NULL pointer otherwise (failed
180113 ** to find close-quote character).
180114 **
180115 ** Before returning, set pzOut to point to a new buffer containing a
180116 ** nul-terminated, dequoted copy of the gobbled word. If the word was
180117 ** quoted, *pbQuoted is also set to 1 before returning.
180118 **
180119 ** If *pRc is other than SQLITE_OK when this function is called, it is
180120 ** a no-op (NULL is returned). Otherwise, if an OOM occurs within this
180121 ** function, *pRc is set to SQLITE_NOMEM before returning. *pRc is *not*
180122 ** set if a parse error (failed to find close quote) occurs.
180123 */
180124 static const char *fts5ConfigGobbleWord(
180125  int *pRc, /* IN/OUT: Error code */
180126  const char *zIn, /* Buffer to gobble string/bareword from */
180127  char **pzOut, /* OUT: malloc'd buffer containing str/bw */
180128  int *pbQuoted /* OUT: Set to true if dequoting required */
180129 ){
180130  const char *zRet = 0;
180131 
180132  int nIn = (int)strlen(zIn);
180133  char *zOut = sqlite3_malloc(nIn+1);
180134 
180135  assert( *pRc==SQLITE_OK );
180136  *pbQuoted = 0;
180137  *pzOut = 0;
180138 
180139  if( zOut==0 ){
180140  *pRc = SQLITE_NOMEM;
180141  }else{
180142  memcpy(zOut, zIn, nIn+1);
180143  if( fts5_isopenquote(zOut[0]) ){
180144  int ii = fts5Dequote(zOut);
180145  zRet = &zIn[ii];
180146  *pbQuoted = 1;
180147  }else{
180148  zRet = fts5ConfigSkipBareword(zIn);
180149  if( zRet ){
180150  zOut[zRet-zIn] = '\0';
180151  }
180152  }
180153  }
180154 
180155  if( zRet==0 ){
180156  sqlite3_free(zOut);
180157  }else{
180158  *pzOut = zOut;
180159  }
180160 
180161  return zRet;
180162 }
180163 
180164 static int fts5ConfigParseColumn(
180165  Fts5Config *p,
180166  char *zCol,
180167  char *zArg,
180168  char **pzErr
180169 ){
180170  int rc = SQLITE_OK;
180171  if( 0==sqlite3_stricmp(zCol, FTS5_RANK_NAME)
180172  || 0==sqlite3_stricmp(zCol, FTS5_ROWID_NAME)
180173  ){
180174  *pzErr = sqlite3_mprintf("reserved fts5 column name: %s", zCol);
180175  rc = SQLITE_ERROR;
180176  }else if( zArg ){
180177  if( 0==sqlite3_stricmp(zArg, "unindexed") ){
180178  p->abUnindexed[p->nCol] = 1;
180179  }else{
180180  *pzErr = sqlite3_mprintf("unrecognized column option: %s", zArg);
180181  rc = SQLITE_ERROR;
180182  }
180183  }
180184 
180185  p->azCol[p->nCol++] = zCol;
180186  return rc;
180187 }
180188 
180189 /*
180190 ** Populate the Fts5Config.zContentExprlist string.
180191 */
180192 static int fts5ConfigMakeExprlist(Fts5Config *p){
180193  int i;
180194  int rc = SQLITE_OK;
180195  Fts5Buffer buf = {0, 0, 0};
180196 
180197  sqlite3Fts5BufferAppendPrintf(&rc, &buf, "T.%Q", p->zContentRowid);
180198  if( p->eContent!=FTS5_CONTENT_NONE ){
180199  for(i=0; i<p->nCol; i++){
180200  if( p->eContent==FTS5_CONTENT_EXTERNAL ){
180201  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.%Q", p->azCol[i]);
180202  }else{
180203  sqlite3Fts5BufferAppendPrintf(&rc, &buf, ", T.c%d", i);
180204  }
180205  }
180206  }
180207 
180208  assert( p->zContentExprlist==0 );
180209  p->zContentExprlist = (char*)buf.p;
180210  return rc;
180211 }
180212 
180213 /*
180214 ** Arguments nArg/azArg contain the string arguments passed to the xCreate
180215 ** or xConnect method of the virtual table. This function attempts to
180216 ** allocate an instance of Fts5Config containing the results of parsing
180217 ** those arguments.
180218 **
180219 ** If successful, SQLITE_OK is returned and *ppOut is set to point to the
180220 ** new Fts5Config object. If an error occurs, an SQLite error code is
180221 ** returned, *ppOut is set to NULL and an error message may be left in
180222 ** *pzErr. It is the responsibility of the caller to eventually free any
180223 ** such error message using sqlite3_free().
180224 */
180225 static int sqlite3Fts5ConfigParse(
180226  Fts5Global *pGlobal,
180227  sqlite3 *db,
180228  int nArg, /* Number of arguments */
180229  const char **azArg, /* Array of nArg CREATE VIRTUAL TABLE args */
180230  Fts5Config **ppOut, /* OUT: Results of parse */
180231  char **pzErr /* OUT: Error message */
180232 ){
180233  int rc = SQLITE_OK; /* Return code */
180234  Fts5Config *pRet; /* New object to return */
180235  int i;
180236  int nByte;
180237 
180238  *ppOut = pRet = (Fts5Config*)sqlite3_malloc(sizeof(Fts5Config));
180239  if( pRet==0 ) return SQLITE_NOMEM;
180240  memset(pRet, 0, sizeof(Fts5Config));
180241  pRet->db = db;
180242  pRet->iCookie = -1;
180243 
180244  nByte = nArg * (sizeof(char*) + sizeof(u8));
180245  pRet->azCol = (char**)sqlite3Fts5MallocZero(&rc, nByte);
180246  pRet->abUnindexed = (u8*)&pRet->azCol[nArg];
180247  pRet->zDb = sqlite3Fts5Strndup(&rc, azArg[1], -1);
180248  pRet->zName = sqlite3Fts5Strndup(&rc, azArg[2], -1);
180249  pRet->bColumnsize = 1;
180250  pRet->eDetail = FTS5_DETAIL_FULL;
180251 #ifdef SQLITE_DEBUG
180252  pRet->bPrefixIndex = 1;
180253 #endif
180254  if( rc==SQLITE_OK && sqlite3_stricmp(pRet->zName, FTS5_RANK_NAME)==0 ){
180255  *pzErr = sqlite3_mprintf("reserved fts5 table name: %s", pRet->zName);
180256  rc = SQLITE_ERROR;
180257  }
180258 
180259  for(i=3; rc==SQLITE_OK && i<nArg; i++){
180260  const char *zOrig = azArg[i];
180261  const char *z;
180262  char *zOne = 0;
180263  char *zTwo = 0;
180264  int bOption = 0;
180265  int bMustBeCol = 0;
180266 
180267  z = fts5ConfigGobbleWord(&rc, zOrig, &zOne, &bMustBeCol);
180268  z = fts5ConfigSkipWhitespace(z);
180269  if( z && *z=='=' ){
180270  bOption = 1;
180271  z++;
180272  if( bMustBeCol ) z = 0;
180273  }
180274  z = fts5ConfigSkipWhitespace(z);
180275  if( z && z[0] ){
180276  int bDummy;
180277  z = fts5ConfigGobbleWord(&rc, z, &zTwo, &bDummy);
180278  if( z && z[0] ) z = 0;
180279  }
180280 
180281  if( rc==SQLITE_OK ){
180282  if( z==0 ){
180283  *pzErr = sqlite3_mprintf("parse error in \"%s\"", zOrig);
180284  rc = SQLITE_ERROR;
180285  }else{
180286  if( bOption ){
180287  rc = fts5ConfigParseSpecial(pGlobal, pRet, zOne, zTwo?zTwo:"", pzErr);
180288  }else{
180289  rc = fts5ConfigParseColumn(pRet, zOne, zTwo, pzErr);
180290  zOne = 0;
180291  }
180292  }
180293  }
180294 
180295  sqlite3_free(zOne);
180296  sqlite3_free(zTwo);
180297  }
180298 
180299  /* If a tokenizer= option was successfully parsed, the tokenizer has
180300  ** already been allocated. Otherwise, allocate an instance of the default
180301  ** tokenizer (unicode61) now. */
180302  if( rc==SQLITE_OK && pRet->pTok==0 ){
180303  rc = fts5ConfigDefaultTokenizer(pGlobal, pRet);
180304  }
180305 
180306  /* If no zContent option was specified, fill in the default values. */
180307  if( rc==SQLITE_OK && pRet->zContent==0 ){
180308  const char *zTail = 0;
180309  assert( pRet->eContent==FTS5_CONTENT_NORMAL
180310  || pRet->eContent==FTS5_CONTENT_NONE
180311  );
180312  if( pRet->eContent==FTS5_CONTENT_NORMAL ){
180313  zTail = "content";
180314  }else if( pRet->bColumnsize ){
180315  zTail = "docsize";
180316  }
180317 
180318  if( zTail ){
180319  pRet->zContent = sqlite3Fts5Mprintf(
180320  &rc, "%Q.'%q_%s'", pRet->zDb, pRet->zName, zTail
180321  );
180322  }
180323  }
180324 
180325  if( rc==SQLITE_OK && pRet->zContentRowid==0 ){
180326  pRet->zContentRowid = sqlite3Fts5Strndup(&rc, "rowid", -1);
180327  }
180328 
180329  /* Formulate the zContentExprlist text */
180330  if( rc==SQLITE_OK ){
180331  rc = fts5ConfigMakeExprlist(pRet);
180332  }
180333 
180334  if( rc!=SQLITE_OK ){
180335  sqlite3Fts5ConfigFree(pRet);
180336  *ppOut = 0;
180337  }
180338  return rc;
180339 }
180340 
180341 /*
180342 ** Free the configuration object passed as the only argument.
180343 */
180344 static void sqlite3Fts5ConfigFree(Fts5Config *pConfig){
180345  if( pConfig ){
180346  int i;
180347  if( pConfig->pTok ){
180348  pConfig->pTokApi->xDelete(pConfig->pTok);
180349  }
180350  sqlite3_free(pConfig->zDb);
180351  sqlite3_free(pConfig->zName);
180352  for(i=0; i<pConfig->nCol; i++){
180353  sqlite3_free(pConfig->azCol[i]);
180354  }
180355  sqlite3_free(pConfig->azCol);
180356  sqlite3_free(pConfig->aPrefix);
180357  sqlite3_free(pConfig->zRank);
180358  sqlite3_free(pConfig->zRankArgs);
180359  sqlite3_free(pConfig->zContent);
180360  sqlite3_free(pConfig->zContentRowid);
180361  sqlite3_free(pConfig->zContentExprlist);
180362  sqlite3_free(pConfig);
180363  }
180364 }
180365 
180366 /*
180367 ** Call sqlite3_declare_vtab() based on the contents of the configuration
180368 ** object passed as the only argument. Return SQLITE_OK if successful, or
180369 ** an SQLite error code if an error occurs.
180370 */
180371 static int sqlite3Fts5ConfigDeclareVtab(Fts5Config *pConfig){
180372  int i;
180373  int rc = SQLITE_OK;
180374  char *zSql;
180375 
180376  zSql = sqlite3Fts5Mprintf(&rc, "CREATE TABLE x(");
180377  for(i=0; zSql && i<pConfig->nCol; i++){
180378  const char *zSep = (i==0?"":", ");
180379  zSql = sqlite3Fts5Mprintf(&rc, "%z%s%Q", zSql, zSep, pConfig->azCol[i]);
180380  }
180381  zSql = sqlite3Fts5Mprintf(&rc, "%z, %Q HIDDEN, %s HIDDEN)",
180382  zSql, pConfig->zName, FTS5_RANK_NAME
180383  );
180384 
180385  assert( zSql || rc==SQLITE_NOMEM );
180386  if( zSql ){
180387  rc = sqlite3_declare_vtab(pConfig->db, zSql);
180388  sqlite3_free(zSql);
180389  }
180390 
180391  return rc;
180392 }
180393 
180394 /*
180395 ** Tokenize the text passed via the second and third arguments.
180396 **
180397 ** The callback is invoked once for each token in the input text. The
180398 ** arguments passed to it are, in order:
180399 **
180400 ** void *pCtx // Copy of 4th argument to sqlite3Fts5Tokenize()
180401 ** const char *pToken // Pointer to buffer containing token
180402 ** int nToken // Size of token in bytes
180403 ** int iStart // Byte offset of start of token within input text
180404 ** int iEnd // Byte offset of end of token within input text
180405 ** int iPos // Position of token in input (first token is 0)
180406 **
180407 ** If the callback returns a non-zero value the tokenization is abandoned
180408 ** and no further callbacks are issued.
180409 **
180410 ** This function returns SQLITE_OK if successful or an SQLite error code
180411 ** if an error occurs. If the tokenization was abandoned early because
180412 ** the callback returned SQLITE_DONE, this is not an error and this function
180413 ** still returns SQLITE_OK. Or, if the tokenization was abandoned early
180414 ** because the callback returned another non-zero value, it is assumed
180415 ** to be an SQLite error code and returned to the caller.
180416 */
180417 static int sqlite3Fts5Tokenize(
180418  Fts5Config *pConfig, /* FTS5 Configuration object */
180419  int flags, /* FTS5_TOKENIZE_* flags */
180420  const char *pText, int nText, /* Text to tokenize */
180421  void *pCtx, /* Context passed to xToken() */
180422  int (*xToken)(void*, int, const char*, int, int, int) /* Callback */
180423 ){
180424  if( pText==0 ) return SQLITE_OK;
180425  return pConfig->pTokApi->xTokenize(
180426  pConfig->pTok, pCtx, flags, pText, nText, xToken
180427  );
180428 }
180429 
180430 /*
180431 ** Argument pIn points to the first character in what is expected to be
180432 ** a comma-separated list of SQL literals followed by a ')' character.
180433 ** If it actually is this, return a pointer to the ')'. Otherwise, return
180434 ** NULL to indicate a parse error.
180435 */
180436 static const char *fts5ConfigSkipArgs(const char *pIn){
180437  const char *p = pIn;
180438 
180439  while( 1 ){
180440  p = fts5ConfigSkipWhitespace(p);
180441  p = fts5ConfigSkipLiteral(p);
180442  p = fts5ConfigSkipWhitespace(p);
180443  if( p==0 || *p==')' ) break;
180444  if( *p!=',' ){
180445  p = 0;
180446  break;
180447  }
180448  p++;
180449  }
180450 
180451  return p;
180452 }
180453 
180454 /*
180455 ** Parameter zIn contains a rank() function specification. The format of
180456 ** this is:
180457 **
180458 ** + Bareword (function name)
180459 ** + Open parenthesis - "("
180460 ** + Zero or more SQL literals in a comma separated list
180461 ** + Close parenthesis - ")"
180462 */
180463 static int sqlite3Fts5ConfigParseRank(
180464  const char *zIn, /* Input string */
180465  char **pzRank, /* OUT: Rank function name */
180466  char **pzRankArgs /* OUT: Rank function arguments */
180467 ){
180468  const char *p = zIn;
180469  const char *pRank;
180470  char *zRank = 0;
180471  char *zRankArgs = 0;
180472  int rc = SQLITE_OK;
180473 
180474  *pzRank = 0;
180475  *pzRankArgs = 0;
180476 
180477  if( p==0 ){
180478  rc = SQLITE_ERROR;
180479  }else{
180480  p = fts5ConfigSkipWhitespace(p);
180481  pRank = p;
180482  p = fts5ConfigSkipBareword(p);
180483 
180484  if( p ){
180485  zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank);
180486  if( zRank ) memcpy(zRank, pRank, p-pRank);
180487  }else{
180488  rc = SQLITE_ERROR;
180489  }
180490 
180491  if( rc==SQLITE_OK ){
180492  p = fts5ConfigSkipWhitespace(p);
180493  if( *p!='(' ) rc = SQLITE_ERROR;
180494  p++;
180495  }
180496  if( rc==SQLITE_OK ){
180497  const char *pArgs;
180498  p = fts5ConfigSkipWhitespace(p);
180499  pArgs = p;
180500  if( *p!=')' ){
180501  p = fts5ConfigSkipArgs(p);
180502  if( p==0 ){
180503  rc = SQLITE_ERROR;
180504  }else{
180505  zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs);
180506  if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs);
180507  }
180508  }
180509  }
180510  }
180511 
180512  if( rc!=SQLITE_OK ){
180513  sqlite3_free(zRank);
180514  assert( zRankArgs==0 );
180515  }else{
180516  *pzRank = zRank;
180517  *pzRankArgs = zRankArgs;
180518  }
180519  return rc;
180520 }
180521 
180522 static int sqlite3Fts5ConfigSetValue(
180523  Fts5Config *pConfig,
180524  const char *zKey,
180525  sqlite3_value *pVal,
180526  int *pbBadkey
180527 ){
180528  int rc = SQLITE_OK;
180529 
180530  if( 0==sqlite3_stricmp(zKey, "pgsz") ){
180531  int pgsz = 0;
180533  pgsz = sqlite3_value_int(pVal);
180534  }
180535  if( pgsz<=0 || pgsz>FTS5_MAX_PAGE_SIZE ){
180536  *pbBadkey = 1;
180537  }else{
180538  pConfig->pgsz = pgsz;
180539  }
180540  }
180541 
180542  else if( 0==sqlite3_stricmp(zKey, "hashsize") ){
180543  int nHashSize = -1;
180545  nHashSize = sqlite3_value_int(pVal);
180546  }
180547  if( nHashSize<=0 ){
180548  *pbBadkey = 1;
180549  }else{
180550  pConfig->nHashSize = nHashSize;
180551  }
180552  }
180553 
180554  else if( 0==sqlite3_stricmp(zKey, "automerge") ){
180555  int nAutomerge = -1;
180557  nAutomerge = sqlite3_value_int(pVal);
180558  }
180559  if( nAutomerge<0 || nAutomerge>64 ){
180560  *pbBadkey = 1;
180561  }else{
180562  if( nAutomerge==1 ) nAutomerge = FTS5_DEFAULT_AUTOMERGE;
180563  pConfig->nAutomerge = nAutomerge;
180564  }
180565  }
180566 
180567  else if( 0==sqlite3_stricmp(zKey, "usermerge") ){
180568  int nUsermerge = -1;
180570  nUsermerge = sqlite3_value_int(pVal);
180571  }
180572  if( nUsermerge<2 || nUsermerge>16 ){
180573  *pbBadkey = 1;
180574  }else{
180575  pConfig->nUsermerge = nUsermerge;
180576  }
180577  }
180578 
180579  else if( 0==sqlite3_stricmp(zKey, "crisismerge") ){
180580  int nCrisisMerge = -1;
180582  nCrisisMerge = sqlite3_value_int(pVal);
180583  }
180584  if( nCrisisMerge<0 ){
180585  *pbBadkey = 1;
180586  }else{
180587  if( nCrisisMerge<=1 ) nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
180588  pConfig->nCrisisMerge = nCrisisMerge;
180589  }
180590  }
180591 
180592  else if( 0==sqlite3_stricmp(zKey, "rank") ){
180593  const char *zIn = (const char*)sqlite3_value_text(pVal);
180594  char *zRank;
180595  char *zRankArgs;
180596  rc = sqlite3Fts5ConfigParseRank(zIn, &zRank, &zRankArgs);
180597  if( rc==SQLITE_OK ){
180598  sqlite3_free(pConfig->zRank);
180599  sqlite3_free(pConfig->zRankArgs);
180600  pConfig->zRank = zRank;
180601  pConfig->zRankArgs = zRankArgs;
180602  }else if( rc==SQLITE_ERROR ){
180603  rc = SQLITE_OK;
180604  *pbBadkey = 1;
180605  }
180606  }else{
180607  *pbBadkey = 1;
180608  }
180609  return rc;
180610 }
180611 
180612 /*
180613 ** Load the contents of the %_config table into memory.
180614 */
180615 static int sqlite3Fts5ConfigLoad(Fts5Config *pConfig, int iCookie){
180616  const char *zSelect = "SELECT k, v FROM %Q.'%q_config'";
180617  char *zSql;
180618  sqlite3_stmt *p = 0;
180619  int rc = SQLITE_OK;
180620  int iVersion = 0;
180621 
180622  /* Set default values */
180623  pConfig->pgsz = FTS5_DEFAULT_PAGE_SIZE;
180624  pConfig->nAutomerge = FTS5_DEFAULT_AUTOMERGE;
180625  pConfig->nUsermerge = FTS5_DEFAULT_USERMERGE;
180626  pConfig->nCrisisMerge = FTS5_DEFAULT_CRISISMERGE;
180627  pConfig->nHashSize = FTS5_DEFAULT_HASHSIZE;
180628 
180629  zSql = sqlite3Fts5Mprintf(&rc, zSelect, pConfig->zDb, pConfig->zName);
180630  if( zSql ){
180631  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p, 0);
180632  sqlite3_free(zSql);
180633  }
180634 
180635  assert( rc==SQLITE_OK || p==0 );
180636  if( rc==SQLITE_OK ){
180637  while( SQLITE_ROW==sqlite3_step(p) ){
180638  const char *zK = (const char*)sqlite3_column_text(p, 0);
180639  sqlite3_value *pVal = sqlite3_column_value(p, 1);
180640  if( 0==sqlite3_stricmp(zK, "version") ){
180641  iVersion = sqlite3_value_int(pVal);
180642  }else{
180643  int bDummy = 0;
180644  sqlite3Fts5ConfigSetValue(pConfig, zK, pVal, &bDummy);
180645  }
180646  }
180647  rc = sqlite3_finalize(p);
180648  }
180649 
180650  if( rc==SQLITE_OK && iVersion!=FTS5_CURRENT_VERSION ){
180651  rc = SQLITE_ERROR;
180652  if( pConfig->pzErrmsg ){
180653  assert( 0==*pConfig->pzErrmsg );
180654  *pConfig->pzErrmsg = sqlite3_mprintf(
180655  "invalid fts5 file format (found %d, expected %d) - run 'rebuild'",
180656  iVersion, FTS5_CURRENT_VERSION
180657  );
180658  }
180659  }
180660 
180661  if( rc==SQLITE_OK ){
180662  pConfig->iCookie = iCookie;
180663  }
180664  return rc;
180665 }
180666 
180667 /*
180668 ** 2014 May 31
180669 **
180670 ** The author disclaims copyright to this source code. In place of
180671 ** a legal notice, here is a blessing:
180672 **
180673 ** May you do good and not evil.
180674 ** May you find forgiveness for yourself and forgive others.
180675 ** May you share freely, never taking more than you give.
180676 **
180677 ******************************************************************************
180678 **
180679 */
180680 
180681 
180682 
180683 /* #include "fts5Int.h" */
180684 /* #include "fts5parse.h" */
180685 
180686 /*
180687 ** All token types in the generated fts5parse.h file are greater than 0.
180688 */
180689 #define FTS5_EOF 0
180690 
180691 #define FTS5_LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
180692 
180693 typedef struct Fts5ExprTerm Fts5ExprTerm;
180694 
180695 /*
180696 ** Functions generated by lemon from fts5parse.y.
180697 */
180698 static void *sqlite3Fts5ParserAlloc(void *(*mallocProc)(u64));
180699 static void sqlite3Fts5ParserFree(void*, void (*freeProc)(void*));
180700 static void sqlite3Fts5Parser(void*, int, Fts5Token, Fts5Parse*);
180701 #ifndef NDEBUG
180702 /* #include <stdio.h> */
180703 static void sqlite3Fts5ParserTrace(FILE*, char*);
180704 #endif
180705 
180706 
180707 struct Fts5Expr {
180708  Fts5Index *pIndex;
180709  Fts5Config *pConfig;
180710  Fts5ExprNode *pRoot;
180711  int bDesc; /* Iterate in descending rowid order */
180712  int nPhrase; /* Number of phrases in expression */
180713  Fts5ExprPhrase **apExprPhrase; /* Pointers to phrase objects */
180714 };
180715 
180716 /*
180717 ** eType:
180718 ** Expression node type. Always one of:
180719 **
180720 ** FTS5_AND (nChild, apChild valid)
180721 ** FTS5_OR (nChild, apChild valid)
180722 ** FTS5_NOT (nChild, apChild valid)
180723 ** FTS5_STRING (pNear valid)
180724 ** FTS5_TERM (pNear valid)
180725 */
180726 struct Fts5ExprNode {
180727  int eType; /* Node type */
180728  int bEof; /* True at EOF */
180729  int bNomatch; /* True if entry is not a match */
180730 
180731  /* Next method for this node. */
180732  int (*xNext)(Fts5Expr*, Fts5ExprNode*, int, i64);
180733 
180734  i64 iRowid; /* Current rowid */
180735  Fts5ExprNearset *pNear; /* For FTS5_STRING - cluster of phrases */
180736 
180737  /* Child nodes. For a NOT node, this array always contains 2 entries. For
180738  ** AND or OR nodes, it contains 2 or more entries. */
180739  int nChild; /* Number of child nodes */
180740  Fts5ExprNode *apChild[1]; /* Array of child nodes */
180741 };
180742 
180743 #define Fts5NodeIsString(p) ((p)->eType==FTS5_TERM || (p)->eType==FTS5_STRING)
180744 
180745 /*
180746 ** Invoke the xNext method of an Fts5ExprNode object. This macro should be
180747 ** used as if it has the same signature as the xNext() methods themselves.
180748 */
180749 #define fts5ExprNodeNext(a,b,c,d) (b)->xNext((a), (b), (c), (d))
180750 
180751 /*
180752 ** An instance of the following structure represents a single search term
180753 ** or term prefix.
180754 */
180755 struct Fts5ExprTerm {
180756  int bPrefix; /* True for a prefix term */
180757  char *zTerm; /* nul-terminated term */
180758  Fts5IndexIter *pIter; /* Iterator for this term */
180759  Fts5ExprTerm *pSynonym; /* Pointer to first in list of synonyms */
180760 };
180761 
180762 /*
180763 ** A phrase. One or more terms that must appear in a contiguous sequence
180764 ** within a document for it to match.
180765 */
180766 struct Fts5ExprPhrase {
180767  Fts5ExprNode *pNode; /* FTS5_STRING node this phrase is part of */
180768  Fts5Buffer poslist; /* Current position list */
180769  int nTerm; /* Number of entries in aTerm[] */
180770  Fts5ExprTerm aTerm[1]; /* Terms that make up this phrase */
180771 };
180772 
180773 /*
180774 ** One or more phrases that must appear within a certain token distance of
180775 ** each other within each matching document.
180776 */
180777 struct Fts5ExprNearset {
180778  int nNear; /* NEAR parameter */
180779  Fts5Colset *pColset; /* Columns to search (NULL -> all columns) */
180780  int nPhrase; /* Number of entries in aPhrase[] array */
180781  Fts5ExprPhrase *apPhrase[1]; /* Array of phrase pointers */
180782 };
180783 
180784 
180785 /*
180786 ** Parse context.
180787 */
180788 struct Fts5Parse {
180789  Fts5Config *pConfig;
180790  char *zErr;
180791  int rc;
180792  int nPhrase; /* Size of apPhrase array */
180793  Fts5ExprPhrase **apPhrase; /* Array of all phrases */
180794  Fts5ExprNode *pExpr; /* Result of a successful parse */
180795 };
180796 
180797 static void sqlite3Fts5ParseError(Fts5Parse *pParse, const char *zFmt, ...){
180798  va_list ap;
180799  va_start(ap, zFmt);
180800  if( pParse->rc==SQLITE_OK ){
180801  pParse->zErr = sqlite3_vmprintf(zFmt, ap);
180802  pParse->rc = SQLITE_ERROR;
180803  }
180804  va_end(ap);
180805 }
180806 
180807 static int fts5ExprIsspace(char t){
180808  return t==' ' || t=='\t' || t=='\n' || t=='\r';
180809 }
180810 
180811 /*
180812 ** Read the first token from the nul-terminated string at *pz.
180813 */
180814 static int fts5ExprGetToken(
180815  Fts5Parse *pParse,
180816  const char **pz, /* IN/OUT: Pointer into buffer */
180817  Fts5Token *pToken
180818 ){
180819  const char *z = *pz;
180820  int tok;
180821 
180822  /* Skip past any whitespace */
180823  while( fts5ExprIsspace(*z) ) z++;
180824 
180825  pToken->p = z;
180826  pToken->n = 1;
180827  switch( *z ){
180828  case '(': tok = FTS5_LP; break;
180829  case ')': tok = FTS5_RP; break;
180830  case '{': tok = FTS5_LCP; break;
180831  case '}': tok = FTS5_RCP; break;
180832  case ':': tok = FTS5_COLON; break;
180833  case ',': tok = FTS5_COMMA; break;
180834  case '+': tok = FTS5_PLUS; break;
180835  case '*': tok = FTS5_STAR; break;
180836  case '\0': tok = FTS5_EOF; break;
180837 
180838  case '"': {
180839  const char *z2;
180840  tok = FTS5_STRING;
180841 
180842  for(z2=&z[1]; 1; z2++){
180843  if( z2[0]=='"' ){
180844  z2++;
180845  if( z2[0]!='"' ) break;
180846  }
180847  if( z2[0]=='\0' ){
180848  sqlite3Fts5ParseError(pParse, "unterminated string");
180849  return FTS5_EOF;
180850  }
180851  }
180852  pToken->n = (z2 - z);
180853  break;
180854  }
180855 
180856  default: {
180857  const char *z2;
180858  if( sqlite3Fts5IsBareword(z[0])==0 ){
180859  sqlite3Fts5ParseError(pParse, "fts5: syntax error near \"%.1s\"", z);
180860  return FTS5_EOF;
180861  }
180862  tok = FTS5_STRING;
180863  for(z2=&z[1]; sqlite3Fts5IsBareword(*z2); z2++);
180864  pToken->n = (z2 - z);
180865  if( pToken->n==2 && memcmp(pToken->p, "OR", 2)==0 ) tok = FTS5_OR;
180866  if( pToken->n==3 && memcmp(pToken->p, "NOT", 3)==0 ) tok = FTS5_NOT;
180867  if( pToken->n==3 && memcmp(pToken->p, "AND", 3)==0 ) tok = FTS5_AND;
180868  break;
180869  }
180870  }
180871 
180872  *pz = &pToken->p[pToken->n];
180873  return tok;
180874 }
180875 
180876 static void *fts5ParseAlloc(u64 t){ return sqlite3_malloc((int)t); }
180877 static void fts5ParseFree(void *p){ sqlite3_free(p); }
180878 
180879 static int sqlite3Fts5ExprNew(
180880  Fts5Config *pConfig, /* FTS5 Configuration */
180881  const char *zExpr, /* Expression text */
180882  Fts5Expr **ppNew,
180883  char **pzErr
180884 ){
180885  Fts5Parse sParse;
180886  Fts5Token token;
180887  const char *z = zExpr;
180888  int t; /* Next token type */
180889  void *pEngine;
180890  Fts5Expr *pNew;
180891 
180892  *ppNew = 0;
180893  *pzErr = 0;
180894  memset(&sParse, 0, sizeof(sParse));
180895  pEngine = sqlite3Fts5ParserAlloc(fts5ParseAlloc);
180896  if( pEngine==0 ){ return SQLITE_NOMEM; }
180897  sParse.pConfig = pConfig;
180898 
180899  do {
180900  t = fts5ExprGetToken(&sParse, &z, &token);
180901  sqlite3Fts5Parser(pEngine, t, token, &sParse);
180902  }while( sParse.rc==SQLITE_OK && t!=FTS5_EOF );
180903  sqlite3Fts5ParserFree(pEngine, fts5ParseFree);
180904 
180905  assert( sParse.rc!=SQLITE_OK || sParse.zErr==0 );
180906  if( sParse.rc==SQLITE_OK ){
180907  *ppNew = pNew = sqlite3_malloc(sizeof(Fts5Expr));
180908  if( pNew==0 ){
180909  sParse.rc = SQLITE_NOMEM;
180910  sqlite3Fts5ParseNodeFree(sParse.pExpr);
180911  }else{
180912  if( !sParse.pExpr ){
180913  const int nByte = sizeof(Fts5ExprNode);
180914  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&sParse.rc, nByte);
180915  if( pNew->pRoot ){
180916  pNew->pRoot->bEof = 1;
180917  }
180918  }else{
180919  pNew->pRoot = sParse.pExpr;
180920  }
180921  pNew->pIndex = 0;
180922  pNew->pConfig = pConfig;
180923  pNew->apExprPhrase = sParse.apPhrase;
180924  pNew->nPhrase = sParse.nPhrase;
180925  sParse.apPhrase = 0;
180926  }
180927  }else{
180928  sqlite3Fts5ParseNodeFree(sParse.pExpr);
180929  }
180930 
180931  sqlite3_free(sParse.apPhrase);
180932  *pzErr = sParse.zErr;
180933  return sParse.rc;
180934 }
180935 
180936 /*
180937 ** Free the expression node object passed as the only argument.
180938 */
180939 static void sqlite3Fts5ParseNodeFree(Fts5ExprNode *p){
180940  if( p ){
180941  int i;
180942  for(i=0; i<p->nChild; i++){
180943  sqlite3Fts5ParseNodeFree(p->apChild[i]);
180944  }
180945  sqlite3Fts5ParseNearsetFree(p->pNear);
180946  sqlite3_free(p);
180947  }
180948 }
180949 
180950 /*
180951 ** Free the expression object passed as the only argument.
180952 */
180953 static void sqlite3Fts5ExprFree(Fts5Expr *p){
180954  if( p ){
180955  sqlite3Fts5ParseNodeFree(p->pRoot);
180956  sqlite3_free(p->apExprPhrase);
180957  sqlite3_free(p);
180958  }
180959 }
180960 
180961 /*
180962 ** Argument pTerm must be a synonym iterator. Return the current rowid
180963 ** that it points to.
180964 */
180965 static i64 fts5ExprSynonymRowid(Fts5ExprTerm *pTerm, int bDesc, int *pbEof){
180966  i64 iRet = 0;
180967  int bRetValid = 0;
180968  Fts5ExprTerm *p;
180969 
180970  assert( pTerm->pSynonym );
180971  assert( bDesc==0 || bDesc==1 );
180972  for(p=pTerm; p; p=p->pSynonym){
180973  if( 0==sqlite3Fts5IterEof(p->pIter) ){
180974  i64 iRowid = p->pIter->iRowid;
180975  if( bRetValid==0 || (bDesc!=(iRowid<iRet)) ){
180976  iRet = iRowid;
180977  bRetValid = 1;
180978  }
180979  }
180980  }
180981 
180982  if( pbEof && bRetValid==0 ) *pbEof = 1;
180983  return iRet;
180984 }
180985 
180986 /*
180987 ** Argument pTerm must be a synonym iterator.
180988 */
180989 static int fts5ExprSynonymList(
180990  Fts5ExprTerm *pTerm,
180991  i64 iRowid,
180992  Fts5Buffer *pBuf, /* Use this buffer for space if required */
180993  u8 **pa, int *pn
180994 ){
180995  Fts5PoslistReader aStatic[4];
180996  Fts5PoslistReader *aIter = aStatic;
180997  int nIter = 0;
180998  int nAlloc = 4;
180999  int rc = SQLITE_OK;
181000  Fts5ExprTerm *p;
181001 
181002  assert( pTerm->pSynonym );
181003  for(p=pTerm; p; p=p->pSynonym){
181004  Fts5IndexIter *pIter = p->pIter;
181005  if( sqlite3Fts5IterEof(pIter)==0 && pIter->iRowid==iRowid ){
181006  if( pIter->nData==0 ) continue;
181007  if( nIter==nAlloc ){
181008  int nByte = sizeof(Fts5PoslistReader) * nAlloc * 2;
181009  Fts5PoslistReader *aNew = (Fts5PoslistReader*)sqlite3_malloc(nByte);
181010  if( aNew==0 ){
181011  rc = SQLITE_NOMEM;
181012  goto synonym_poslist_out;
181013  }
181014  memcpy(aNew, aIter, sizeof(Fts5PoslistReader) * nIter);
181015  nAlloc = nAlloc*2;
181016  if( aIter!=aStatic ) sqlite3_free(aIter);
181017  aIter = aNew;
181018  }
181019  sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &aIter[nIter]);
181020  assert( aIter[nIter].bEof==0 );
181021  nIter++;
181022  }
181023  }
181024 
181025  if( nIter==1 ){
181026  *pa = (u8*)aIter[0].a;
181027  *pn = aIter[0].n;
181028  }else{
181029  Fts5PoslistWriter writer = {0};
181030  i64 iPrev = -1;
181031  fts5BufferZero(pBuf);
181032  while( 1 ){
181033  int i;
181034  i64 iMin = FTS5_LARGEST_INT64;
181035  for(i=0; i<nIter; i++){
181036  if( aIter[i].bEof==0 ){
181037  if( aIter[i].iPos==iPrev ){
181038  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) continue;
181039  }
181040  if( aIter[i].iPos<iMin ){
181041  iMin = aIter[i].iPos;
181042  }
181043  }
181044  }
181045  if( iMin==FTS5_LARGEST_INT64 || rc!=SQLITE_OK ) break;
181046  rc = sqlite3Fts5PoslistWriterAppend(pBuf, &writer, iMin);
181047  iPrev = iMin;
181048  }
181049  if( rc==SQLITE_OK ){
181050  *pa = pBuf->p;
181051  *pn = pBuf->n;
181052  }
181053  }
181054 
181055  synonym_poslist_out:
181056  if( aIter!=aStatic ) sqlite3_free(aIter);
181057  return rc;
181058 }
181059 
181060 
181061 /*
181062 ** All individual term iterators in pPhrase are guaranteed to be valid and
181063 ** pointing to the same rowid when this function is called. This function
181064 ** checks if the current rowid really is a match, and if so populates
181065 ** the pPhrase->poslist buffer accordingly. Output parameter *pbMatch
181066 ** is set to true if this is really a match, or false otherwise.
181067 **
181068 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
181069 ** otherwise. It is not considered an error code if the current rowid is
181070 ** not a match.
181071 */
181072 static int fts5ExprPhraseIsMatch(
181073  Fts5ExprNode *pNode, /* Node pPhrase belongs to */
181074  Fts5ExprPhrase *pPhrase, /* Phrase object to initialize */
181075  int *pbMatch /* OUT: Set to true if really a match */
181076 ){
181077  Fts5PoslistWriter writer = {0};
181078  Fts5PoslistReader aStatic[4];
181079  Fts5PoslistReader *aIter = aStatic;
181080  int i;
181081  int rc = SQLITE_OK;
181082 
181083  fts5BufferZero(&pPhrase->poslist);
181084 
181085  /* If the aStatic[] array is not large enough, allocate a large array
181086  ** using sqlite3_malloc(). This approach could be improved upon. */
181087  if( pPhrase->nTerm>ArraySize(aStatic) ){
181088  int nByte = sizeof(Fts5PoslistReader) * pPhrase->nTerm;
181089  aIter = (Fts5PoslistReader*)sqlite3_malloc(nByte);
181090  if( !aIter ) return SQLITE_NOMEM;
181091  }
181092  memset(aIter, 0, sizeof(Fts5PoslistReader) * pPhrase->nTerm);
181093 
181094  /* Initialize a term iterator for each term in the phrase */
181095  for(i=0; i<pPhrase->nTerm; i++){
181096  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
181097  int n = 0;
181098  int bFlag = 0;
181099  u8 *a = 0;
181100  if( pTerm->pSynonym ){
181101  Fts5Buffer buf = {0, 0, 0};
181102  rc = fts5ExprSynonymList(pTerm, pNode->iRowid, &buf, &a, &n);
181103  if( rc ){
181104  sqlite3_free(a);
181105  goto ismatch_out;
181106  }
181107  if( a==buf.p ) bFlag = 1;
181108  }else{
181109  a = (u8*)pTerm->pIter->pData;
181110  n = pTerm->pIter->nData;
181111  }
181112  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
181113  aIter[i].bFlag = (u8)bFlag;
181114  if( aIter[i].bEof ) goto ismatch_out;
181115  }
181116 
181117  while( 1 ){
181118  int bMatch;
181119  i64 iPos = aIter[0].iPos;
181120  do {
181121  bMatch = 1;
181122  for(i=0; i<pPhrase->nTerm; i++){
181123  Fts5PoslistReader *pPos = &aIter[i];
181124  i64 iAdj = iPos + i;
181125  if( pPos->iPos!=iAdj ){
181126  bMatch = 0;
181127  while( pPos->iPos<iAdj ){
181128  if( sqlite3Fts5PoslistReaderNext(pPos) ) goto ismatch_out;
181129  }
181130  if( pPos->iPos>iAdj ) iPos = pPos->iPos-i;
181131  }
181132  }
181133  }while( bMatch==0 );
181134 
181135  /* Append position iPos to the output */
181136  rc = sqlite3Fts5PoslistWriterAppend(&pPhrase->poslist, &writer, iPos);
181137  if( rc!=SQLITE_OK ) goto ismatch_out;
181138 
181139  for(i=0; i<pPhrase->nTerm; i++){
181140  if( sqlite3Fts5PoslistReaderNext(&aIter[i]) ) goto ismatch_out;
181141  }
181142  }
181143 
181144  ismatch_out:
181145  *pbMatch = (pPhrase->poslist.n>0);
181146  for(i=0; i<pPhrase->nTerm; i++){
181147  if( aIter[i].bFlag ) sqlite3_free((u8*)aIter[i].a);
181148  }
181149  if( aIter!=aStatic ) sqlite3_free(aIter);
181150  return rc;
181151 }
181152 
181153 typedef struct Fts5LookaheadReader Fts5LookaheadReader;
181154 struct Fts5LookaheadReader {
181155  const u8 *a; /* Buffer containing position list */
181156  int n; /* Size of buffer a[] in bytes */
181157  int i; /* Current offset in position list */
181158  i64 iPos; /* Current position */
181159  i64 iLookahead; /* Next position */
181160 };
181161 
181162 #define FTS5_LOOKAHEAD_EOF (((i64)1) << 62)
181163 
181164 static int fts5LookaheadReaderNext(Fts5LookaheadReader *p){
181165  p->iPos = p->iLookahead;
181166  if( sqlite3Fts5PoslistNext64(p->a, p->n, &p->i, &p->iLookahead) ){
181167  p->iLookahead = FTS5_LOOKAHEAD_EOF;
181168  }
181169  return (p->iPos==FTS5_LOOKAHEAD_EOF);
181170 }
181171 
181172 static int fts5LookaheadReaderInit(
181173  const u8 *a, int n, /* Buffer to read position list from */
181174  Fts5LookaheadReader *p /* Iterator object to initialize */
181175 ){
181176  memset(p, 0, sizeof(Fts5LookaheadReader));
181177  p->a = a;
181178  p->n = n;
181179  fts5LookaheadReaderNext(p);
181180  return fts5LookaheadReaderNext(p);
181181 }
181182 
181183 typedef struct Fts5NearTrimmer Fts5NearTrimmer;
181184 struct Fts5NearTrimmer {
181185  Fts5LookaheadReader reader; /* Input iterator */
181186  Fts5PoslistWriter writer; /* Writer context */
181187  Fts5Buffer *pOut; /* Output poslist */
181188 };
181189 
181190 /*
181191 ** The near-set object passed as the first argument contains more than
181192 ** one phrase. All phrases currently point to the same row. The
181193 ** Fts5ExprPhrase.poslist buffers are populated accordingly. This function
181194 ** tests if the current row contains instances of each phrase sufficiently
181195 ** close together to meet the NEAR constraint. Non-zero is returned if it
181196 ** does, or zero otherwise.
181197 **
181198 ** If in/out parameter (*pRc) is set to other than SQLITE_OK when this
181199 ** function is called, it is a no-op. Or, if an error (e.g. SQLITE_NOMEM)
181200 ** occurs within this function (*pRc) is set accordingly before returning.
181201 ** The return value is undefined in both these cases.
181202 **
181203 ** If no error occurs and non-zero (a match) is returned, the position-list
181204 ** of each phrase object is edited to contain only those entries that
181205 ** meet the constraint before returning.
181206 */
181207 static int fts5ExprNearIsMatch(int *pRc, Fts5ExprNearset *pNear){
181208  Fts5NearTrimmer aStatic[4];
181209  Fts5NearTrimmer *a = aStatic;
181210  Fts5ExprPhrase **apPhrase = pNear->apPhrase;
181211 
181212  int i;
181213  int rc = *pRc;
181214  int bMatch;
181215 
181216  assert( pNear->nPhrase>1 );
181217 
181218  /* If the aStatic[] array is not large enough, allocate a large array
181219  ** using sqlite3_malloc(). This approach could be improved upon. */
181220  if( pNear->nPhrase>ArraySize(aStatic) ){
181221  int nByte = sizeof(Fts5NearTrimmer) * pNear->nPhrase;
181222  a = (Fts5NearTrimmer*)sqlite3Fts5MallocZero(&rc, nByte);
181223  }else{
181224  memset(aStatic, 0, sizeof(aStatic));
181225  }
181226  if( rc!=SQLITE_OK ){
181227  *pRc = rc;
181228  return 0;
181229  }
181230 
181231  /* Initialize a lookahead iterator for each phrase. After passing the
181232  ** buffer and buffer size to the lookaside-reader init function, zero
181233  ** the phrase poslist buffer. The new poslist for the phrase (containing
181234  ** the same entries as the original with some entries removed on account
181235  ** of the NEAR constraint) is written over the original even as it is
181236  ** being read. This is safe as the entries for the new poslist are a
181237  ** subset of the old, so it is not possible for data yet to be read to
181238  ** be overwritten. */
181239  for(i=0; i<pNear->nPhrase; i++){
181240  Fts5Buffer *pPoslist = &apPhrase[i]->poslist;
181241  fts5LookaheadReaderInit(pPoslist->p, pPoslist->n, &a[i].reader);
181242  pPoslist->n = 0;
181243  a[i].pOut = pPoslist;
181244  }
181245 
181246  while( 1 ){
181247  int iAdv;
181248  i64 iMin;
181249  i64 iMax;
181250 
181251  /* This block advances the phrase iterators until they point to a set of
181252  ** entries that together comprise a match. */
181253  iMax = a[0].reader.iPos;
181254  do {
181255  bMatch = 1;
181256  for(i=0; i<pNear->nPhrase; i++){
181257  Fts5LookaheadReader *pPos = &a[i].reader;
181258  iMin = iMax - pNear->apPhrase[i]->nTerm - pNear->nNear;
181259  if( pPos->iPos<iMin || pPos->iPos>iMax ){
181260  bMatch = 0;
181261  while( pPos->iPos<iMin ){
181262  if( fts5LookaheadReaderNext(pPos) ) goto ismatch_out;
181263  }
181264  if( pPos->iPos>iMax ) iMax = pPos->iPos;
181265  }
181266  }
181267  }while( bMatch==0 );
181268 
181269  /* Add an entry to each output position list */
181270  for(i=0; i<pNear->nPhrase; i++){
181271  i64 iPos = a[i].reader.iPos;
181272  Fts5PoslistWriter *pWriter = &a[i].writer;
181273  if( a[i].pOut->n==0 || iPos!=pWriter->iPrev ){
181274  sqlite3Fts5PoslistWriterAppend(a[i].pOut, pWriter, iPos);
181275  }
181276  }
181277 
181278  iAdv = 0;
181279  iMin = a[0].reader.iLookahead;
181280  for(i=0; i<pNear->nPhrase; i++){
181281  if( a[i].reader.iLookahead < iMin ){
181282  iMin = a[i].reader.iLookahead;
181283  iAdv = i;
181284  }
181285  }
181286  if( fts5LookaheadReaderNext(&a[iAdv].reader) ) goto ismatch_out;
181287  }
181288 
181289  ismatch_out: {
181290  int bRet = a[0].pOut->n>0;
181291  *pRc = rc;
181292  if( a!=aStatic ) sqlite3_free(a);
181293  return bRet;
181294  }
181295 }
181296 
181297 /*
181298 ** Advance iterator pIter until it points to a value equal to or laster
181299 ** than the initial value of *piLast. If this means the iterator points
181300 ** to a value laster than *piLast, update *piLast to the new lastest value.
181301 **
181302 ** If the iterator reaches EOF, set *pbEof to true before returning. If
181303 ** an error occurs, set *pRc to an error code. If either *pbEof or *pRc
181304 ** are set, return a non-zero value. Otherwise, return zero.
181305 */
181306 static int fts5ExprAdvanceto(
181307  Fts5IndexIter *pIter, /* Iterator to advance */
181308  int bDesc, /* True if iterator is "rowid DESC" */
181309  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
181310  int *pRc, /* OUT: Error code */
181311  int *pbEof /* OUT: Set to true if EOF */
181312 ){
181313  i64 iLast = *piLast;
181314  i64 iRowid;
181315 
181316  iRowid = pIter->iRowid;
181317  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
181318  int rc = sqlite3Fts5IterNextFrom(pIter, iLast);
181319  if( rc || sqlite3Fts5IterEof(pIter) ){
181320  *pRc = rc;
181321  *pbEof = 1;
181322  return 1;
181323  }
181324  iRowid = pIter->iRowid;
181325  assert( (bDesc==0 && iRowid>=iLast) || (bDesc==1 && iRowid<=iLast) );
181326  }
181327  *piLast = iRowid;
181328 
181329  return 0;
181330 }
181331 
181332 static int fts5ExprSynonymAdvanceto(
181333  Fts5ExprTerm *pTerm, /* Term iterator to advance */
181334  int bDesc, /* True if iterator is "rowid DESC" */
181335  i64 *piLast, /* IN/OUT: Lastest rowid seen so far */
181336  int *pRc /* OUT: Error code */
181337 ){
181338  int rc = SQLITE_OK;
181339  i64 iLast = *piLast;
181340  Fts5ExprTerm *p;
181341  int bEof = 0;
181342 
181343  for(p=pTerm; rc==SQLITE_OK && p; p=p->pSynonym){
181344  if( sqlite3Fts5IterEof(p->pIter)==0 ){
181345  i64 iRowid = p->pIter->iRowid;
181346  if( (bDesc==0 && iLast>iRowid) || (bDesc && iLast<iRowid) ){
181347  rc = sqlite3Fts5IterNextFrom(p->pIter, iLast);
181348  }
181349  }
181350  }
181351 
181352  if( rc!=SQLITE_OK ){
181353  *pRc = rc;
181354  bEof = 1;
181355  }else{
181356  *piLast = fts5ExprSynonymRowid(pTerm, bDesc, &bEof);
181357  }
181358  return bEof;
181359 }
181360 
181361 
181362 static int fts5ExprNearTest(
181363  int *pRc,
181364  Fts5Expr *pExpr, /* Expression that pNear is a part of */
181365  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_STRING) */
181366 ){
181367  Fts5ExprNearset *pNear = pNode->pNear;
181368  int rc = *pRc;
181369 
181370  if( pExpr->pConfig->eDetail!=FTS5_DETAIL_FULL ){
181371  Fts5ExprTerm *pTerm;
181372  Fts5ExprPhrase *pPhrase = pNear->apPhrase[0];
181373  pPhrase->poslist.n = 0;
181374  for(pTerm=&pPhrase->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
181375  Fts5IndexIter *pIter = pTerm->pIter;
181376  if( sqlite3Fts5IterEof(pIter)==0 ){
181377  if( pIter->iRowid==pNode->iRowid && pIter->nData>0 ){
181378  pPhrase->poslist.n = 1;
181379  }
181380  }
181381  }
181382  return pPhrase->poslist.n;
181383  }else{
181384  int i;
181385 
181386  /* Check that each phrase in the nearset matches the current row.
181387  ** Populate the pPhrase->poslist buffers at the same time. If any
181388  ** phrase is not a match, break out of the loop early. */
181389  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
181390  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
181391  if( pPhrase->nTerm>1 || pPhrase->aTerm[0].pSynonym || pNear->pColset ){
181392  int bMatch = 0;
181393  rc = fts5ExprPhraseIsMatch(pNode, pPhrase, &bMatch);
181394  if( bMatch==0 ) break;
181395  }else{
181396  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
181397  fts5BufferSet(&rc, &pPhrase->poslist, pIter->nData, pIter->pData);
181398  }
181399  }
181400 
181401  *pRc = rc;
181402  if( i==pNear->nPhrase && (i==1 || fts5ExprNearIsMatch(pRc, pNear)) ){
181403  return 1;
181404  }
181405  return 0;
181406  }
181407 }
181408 
181409 
181410 /*
181411 ** Initialize all term iterators in the pNear object. If any term is found
181412 ** to match no documents at all, return immediately without initializing any
181413 ** further iterators.
181414 */
181415 static int fts5ExprNearInitAll(
181416  Fts5Expr *pExpr,
181417  Fts5ExprNode *pNode
181418 ){
181419  Fts5ExprNearset *pNear = pNode->pNear;
181420  int i, j;
181421  int rc = SQLITE_OK;
181422 
181423  assert( pNode->bNomatch==0 );
181424  for(i=0; rc==SQLITE_OK && i<pNear->nPhrase; i++){
181425  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
181426  for(j=0; j<pPhrase->nTerm; j++){
181427  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
181428  Fts5ExprTerm *p;
181429  int bEof = 1;
181430 
181431  for(p=pTerm; p && rc==SQLITE_OK; p=p->pSynonym){
181432  if( p->pIter ){
181433  sqlite3Fts5IterClose(p->pIter);
181434  p->pIter = 0;
181435  }
181436  rc = sqlite3Fts5IndexQuery(
181437  pExpr->pIndex, p->zTerm, (int)strlen(p->zTerm),
181438  (pTerm->bPrefix ? FTS5INDEX_QUERY_PREFIX : 0) |
181439  (pExpr->bDesc ? FTS5INDEX_QUERY_DESC : 0),
181440  pNear->pColset,
181441  &p->pIter
181442  );
181443  assert( rc==SQLITE_OK || p->pIter==0 );
181444  if( p->pIter && 0==sqlite3Fts5IterEof(p->pIter) ){
181445  bEof = 0;
181446  }
181447  }
181448 
181449  if( bEof ){
181450  pNode->bEof = 1;
181451  return rc;
181452  }
181453  }
181454  }
181455 
181456  return rc;
181457 }
181458 
181459 /*
181460 ** If pExpr is an ASC iterator, this function returns a value with the
181461 ** same sign as:
181462 **
181463 ** (iLhs - iRhs)
181464 **
181465 ** Otherwise, if this is a DESC iterator, the opposite is returned:
181466 **
181467 ** (iRhs - iLhs)
181468 */
181469 static int fts5RowidCmp(
181470  Fts5Expr *pExpr,
181471  i64 iLhs,
181472  i64 iRhs
181473 ){
181474  assert( pExpr->bDesc==0 || pExpr->bDesc==1 );
181475  if( pExpr->bDesc==0 ){
181476  if( iLhs<iRhs ) return -1;
181477  return (iLhs > iRhs);
181478  }else{
181479  if( iLhs>iRhs ) return -1;
181480  return (iLhs < iRhs);
181481  }
181482 }
181483 
181484 static void fts5ExprSetEof(Fts5ExprNode *pNode){
181485  int i;
181486  pNode->bEof = 1;
181487  pNode->bNomatch = 0;
181488  for(i=0; i<pNode->nChild; i++){
181489  fts5ExprSetEof(pNode->apChild[i]);
181490  }
181491 }
181492 
181493 static void fts5ExprNodeZeroPoslist(Fts5ExprNode *pNode){
181494  if( pNode->eType==FTS5_STRING || pNode->eType==FTS5_TERM ){
181495  Fts5ExprNearset *pNear = pNode->pNear;
181496  int i;
181497  for(i=0; i<pNear->nPhrase; i++){
181498  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
181499  pPhrase->poslist.n = 0;
181500  }
181501  }else{
181502  int i;
181503  for(i=0; i<pNode->nChild; i++){
181504  fts5ExprNodeZeroPoslist(pNode->apChild[i]);
181505  }
181506  }
181507 }
181508 
181509 
181510 
181511 /*
181512 ** Compare the values currently indicated by the two nodes as follows:
181513 **
181514 ** res = (*p1) - (*p2)
181515 **
181516 ** Nodes that point to values that come later in the iteration order are
181517 ** considered to be larger. Nodes at EOF are the largest of all.
181518 **
181519 ** This means that if the iteration order is ASC, then numerically larger
181520 ** rowids are considered larger. Or if it is the default DESC, numerically
181521 ** smaller rowids are larger.
181522 */
181523 static int fts5NodeCompare(
181524  Fts5Expr *pExpr,
181525  Fts5ExprNode *p1,
181526  Fts5ExprNode *p2
181527 ){
181528  if( p2->bEof ) return -1;
181529  if( p1->bEof ) return +1;
181530  return fts5RowidCmp(pExpr, p1->iRowid, p2->iRowid);
181531 }
181532 
181533 /*
181534 ** All individual term iterators in pNear are guaranteed to be valid when
181535 ** this function is called. This function checks if all term iterators
181536 ** point to the same rowid, and if not, advances them until they do.
181537 ** If an EOF is reached before this happens, *pbEof is set to true before
181538 ** returning.
181539 **
181540 ** SQLITE_OK is returned if an error occurs, or an SQLite error code
181541 ** otherwise. It is not considered an error code if an iterator reaches
181542 ** EOF.
181543 */
181544 static int fts5ExprNodeTest_STRING(
181545  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
181546  Fts5ExprNode *pNode
181547 ){
181548  Fts5ExprNearset *pNear = pNode->pNear;
181549  Fts5ExprPhrase *pLeft = pNear->apPhrase[0];
181550  int rc = SQLITE_OK;
181551  i64 iLast; /* Lastest rowid any iterator points to */
181552  int i, j; /* Phrase and token index, respectively */
181553  int bMatch; /* True if all terms are at the same rowid */
181554  const int bDesc = pExpr->bDesc;
181555 
181556  /* Check that this node should not be FTS5_TERM */
181557  assert( pNear->nPhrase>1
181558  || pNear->apPhrase[0]->nTerm>1
181559  || pNear->apPhrase[0]->aTerm[0].pSynonym
181560  );
181561 
181562  /* Initialize iLast, the "lastest" rowid any iterator points to. If the
181563  ** iterator skips through rowids in the default ascending order, this means
181564  ** the maximum rowid. Or, if the iterator is "ORDER BY rowid DESC", then it
181565  ** means the minimum rowid. */
181566  if( pLeft->aTerm[0].pSynonym ){
181567  iLast = fts5ExprSynonymRowid(&pLeft->aTerm[0], bDesc, 0);
181568  }else{
181569  iLast = pLeft->aTerm[0].pIter->iRowid;
181570  }
181571 
181572  do {
181573  bMatch = 1;
181574  for(i=0; i<pNear->nPhrase; i++){
181575  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
181576  for(j=0; j<pPhrase->nTerm; j++){
181577  Fts5ExprTerm *pTerm = &pPhrase->aTerm[j];
181578  if( pTerm->pSynonym ){
181579  i64 iRowid = fts5ExprSynonymRowid(pTerm, bDesc, 0);
181580  if( iRowid==iLast ) continue;
181581  bMatch = 0;
181582  if( fts5ExprSynonymAdvanceto(pTerm, bDesc, &iLast, &rc) ){
181583  pNode->bNomatch = 0;
181584  pNode->bEof = 1;
181585  return rc;
181586  }
181587  }else{
181588  Fts5IndexIter *pIter = pPhrase->aTerm[j].pIter;
181589  if( pIter->iRowid==iLast ) continue;
181590  bMatch = 0;
181591  if( fts5ExprAdvanceto(pIter, bDesc, &iLast, &rc, &pNode->bEof) ){
181592  return rc;
181593  }
181594  }
181595  }
181596  }
181597  }while( bMatch==0 );
181598 
181599  pNode->iRowid = iLast;
181600  pNode->bNomatch = ((0==fts5ExprNearTest(&rc, pExpr, pNode)) && rc==SQLITE_OK);
181601  assert( pNode->bEof==0 || pNode->bNomatch==0 );
181602 
181603  return rc;
181604 }
181605 
181606 /*
181607 ** Advance the first term iterator in the first phrase of pNear. Set output
181608 ** variable *pbEof to true if it reaches EOF or if an error occurs.
181609 **
181610 ** Return SQLITE_OK if successful, or an SQLite error code if an error
181611 ** occurs.
181612 */
181613 static int fts5ExprNodeNext_STRING(
181614  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
181615  Fts5ExprNode *pNode, /* FTS5_STRING or FTS5_TERM node */
181616  int bFromValid,
181617  i64 iFrom
181618 ){
181619  Fts5ExprTerm *pTerm = &pNode->pNear->apPhrase[0]->aTerm[0];
181620  int rc = SQLITE_OK;
181621 
181622  pNode->bNomatch = 0;
181623  if( pTerm->pSynonym ){
181624  int bEof = 1;
181625  Fts5ExprTerm *p;
181626 
181627  /* Find the firstest rowid any synonym points to. */
181628  i64 iRowid = fts5ExprSynonymRowid(pTerm, pExpr->bDesc, 0);
181629 
181630  /* Advance each iterator that currently points to iRowid. Or, if iFrom
181631  ** is valid - each iterator that points to a rowid before iFrom. */
181632  for(p=pTerm; p; p=p->pSynonym){
181633  if( sqlite3Fts5IterEof(p->pIter)==0 ){
181634  i64 ii = p->pIter->iRowid;
181635  if( ii==iRowid
181636  || (bFromValid && ii!=iFrom && (ii>iFrom)==pExpr->bDesc)
181637  ){
181638  if( bFromValid ){
181639  rc = sqlite3Fts5IterNextFrom(p->pIter, iFrom);
181640  }else{
181641  rc = sqlite3Fts5IterNext(p->pIter);
181642  }
181643  if( rc!=SQLITE_OK ) break;
181644  if( sqlite3Fts5IterEof(p->pIter)==0 ){
181645  bEof = 0;
181646  }
181647  }else{
181648  bEof = 0;
181649  }
181650  }
181651  }
181652 
181653  /* Set the EOF flag if either all synonym iterators are at EOF or an
181654  ** error has occurred. */
181655  pNode->bEof = (rc || bEof);
181656  }else{
181657  Fts5IndexIter *pIter = pTerm->pIter;
181658 
181659  assert( Fts5NodeIsString(pNode) );
181660  if( bFromValid ){
181661  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
181662  }else{
181663  rc = sqlite3Fts5IterNext(pIter);
181664  }
181665 
181666  pNode->bEof = (rc || sqlite3Fts5IterEof(pIter));
181667  }
181668 
181669  if( pNode->bEof==0 ){
181670  assert( rc==SQLITE_OK );
181671  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
181672  }
181673 
181674  return rc;
181675 }
181676 
181677 
181678 static int fts5ExprNodeTest_TERM(
181679  Fts5Expr *pExpr, /* Expression that pNear is a part of */
181680  Fts5ExprNode *pNode /* The "NEAR" node (FTS5_TERM) */
181681 ){
181682  /* As this "NEAR" object is actually a single phrase that consists
181683  ** of a single term only, grab pointers into the poslist managed by the
181684  ** fts5_index.c iterator object. This is much faster than synthesizing
181685  ** a new poslist the way we have to for more complicated phrase or NEAR
181686  ** expressions. */
181687  Fts5ExprPhrase *pPhrase = pNode->pNear->apPhrase[0];
181688  Fts5IndexIter *pIter = pPhrase->aTerm[0].pIter;
181689 
181690  assert( pNode->eType==FTS5_TERM );
181691  assert( pNode->pNear->nPhrase==1 && pPhrase->nTerm==1 );
181692  assert( pPhrase->aTerm[0].pSynonym==0 );
181693 
181694  pPhrase->poslist.n = pIter->nData;
181695  if( pExpr->pConfig->eDetail==FTS5_DETAIL_FULL ){
181696  pPhrase->poslist.p = (u8*)pIter->pData;
181697  }
181698  pNode->iRowid = pIter->iRowid;
181699  pNode->bNomatch = (pPhrase->poslist.n==0);
181700  return SQLITE_OK;
181701 }
181702 
181703 /*
181704 ** xNext() method for a node of type FTS5_TERM.
181705 */
181706 static int fts5ExprNodeNext_TERM(
181707  Fts5Expr *pExpr,
181708  Fts5ExprNode *pNode,
181709  int bFromValid,
181710  i64 iFrom
181711 ){
181712  int rc;
181713  Fts5IndexIter *pIter = pNode->pNear->apPhrase[0]->aTerm[0].pIter;
181714 
181715  assert( pNode->bEof==0 );
181716  if( bFromValid ){
181717  rc = sqlite3Fts5IterNextFrom(pIter, iFrom);
181718  }else{
181719  rc = sqlite3Fts5IterNext(pIter);
181720  }
181721  if( rc==SQLITE_OK && sqlite3Fts5IterEof(pIter)==0 ){
181722  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
181723  }else{
181724  pNode->bEof = 1;
181725  pNode->bNomatch = 0;
181726  }
181727  return rc;
181728 }
181729 
181730 static void fts5ExprNodeTest_OR(
181731  Fts5Expr *pExpr, /* Expression of which pNode is a part */
181732  Fts5ExprNode *pNode /* Expression node to test */
181733 ){
181734  Fts5ExprNode *pNext = pNode->apChild[0];
181735  int i;
181736 
181737  for(i=1; i<pNode->nChild; i++){
181738  Fts5ExprNode *pChild = pNode->apChild[i];
181739  int cmp = fts5NodeCompare(pExpr, pNext, pChild);
181740  if( cmp>0 || (cmp==0 && pChild->bNomatch==0) ){
181741  pNext = pChild;
181742  }
181743  }
181744  pNode->iRowid = pNext->iRowid;
181745  pNode->bEof = pNext->bEof;
181746  pNode->bNomatch = pNext->bNomatch;
181747 }
181748 
181749 static int fts5ExprNodeNext_OR(
181750  Fts5Expr *pExpr,
181751  Fts5ExprNode *pNode,
181752  int bFromValid,
181753  i64 iFrom
181754 ){
181755  int i;
181756  i64 iLast = pNode->iRowid;
181757 
181758  for(i=0; i<pNode->nChild; i++){
181759  Fts5ExprNode *p1 = pNode->apChild[i];
181760  assert( p1->bEof || fts5RowidCmp(pExpr, p1->iRowid, iLast)>=0 );
181761  if( p1->bEof==0 ){
181762  if( (p1->iRowid==iLast)
181763  || (bFromValid && fts5RowidCmp(pExpr, p1->iRowid, iFrom)<0)
181764  ){
181765  int rc = fts5ExprNodeNext(pExpr, p1, bFromValid, iFrom);
181766  if( rc!=SQLITE_OK ) return rc;
181767  }
181768  }
181769  }
181770 
181771  fts5ExprNodeTest_OR(pExpr, pNode);
181772  return SQLITE_OK;
181773 }
181774 
181775 /*
181776 ** Argument pNode is an FTS5_AND node.
181777 */
181778 static int fts5ExprNodeTest_AND(
181779  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
181780  Fts5ExprNode *pAnd /* FTS5_AND node to advance */
181781 ){
181782  int iChild;
181783  i64 iLast = pAnd->iRowid;
181784  int rc = SQLITE_OK;
181785  int bMatch;
181786 
181787  assert( pAnd->bEof==0 );
181788  do {
181789  pAnd->bNomatch = 0;
181790  bMatch = 1;
181791  for(iChild=0; iChild<pAnd->nChild; iChild++){
181792  Fts5ExprNode *pChild = pAnd->apChild[iChild];
181793  int cmp = fts5RowidCmp(pExpr, iLast, pChild->iRowid);
181794  if( cmp>0 ){
181795  /* Advance pChild until it points to iLast or laster */
181796  rc = fts5ExprNodeNext(pExpr, pChild, 1, iLast);
181797  if( rc!=SQLITE_OK ) return rc;
181798  }
181799 
181800  /* If the child node is now at EOF, so is the parent AND node. Otherwise,
181801  ** the child node is guaranteed to have advanced at least as far as
181802  ** rowid iLast. So if it is not at exactly iLast, pChild->iRowid is the
181803  ** new lastest rowid seen so far. */
181804  assert( pChild->bEof || fts5RowidCmp(pExpr, iLast, pChild->iRowid)<=0 );
181805  if( pChild->bEof ){
181806  fts5ExprSetEof(pAnd);
181807  bMatch = 1;
181808  break;
181809  }else if( iLast!=pChild->iRowid ){
181810  bMatch = 0;
181811  iLast = pChild->iRowid;
181812  }
181813 
181814  if( pChild->bNomatch ){
181815  pAnd->bNomatch = 1;
181816  }
181817  }
181818  }while( bMatch==0 );
181819 
181820  if( pAnd->bNomatch && pAnd!=pExpr->pRoot ){
181821  fts5ExprNodeZeroPoslist(pAnd);
181822  }
181823  pAnd->iRowid = iLast;
181824  return SQLITE_OK;
181825 }
181826 
181827 static int fts5ExprNodeNext_AND(
181828  Fts5Expr *pExpr,
181829  Fts5ExprNode *pNode,
181830  int bFromValid,
181831  i64 iFrom
181832 ){
181833  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
181834  if( rc==SQLITE_OK ){
181835  rc = fts5ExprNodeTest_AND(pExpr, pNode);
181836  }
181837  return rc;
181838 }
181839 
181840 static int fts5ExprNodeTest_NOT(
181841  Fts5Expr *pExpr, /* Expression pPhrase belongs to */
181842  Fts5ExprNode *pNode /* FTS5_NOT node to advance */
181843 ){
181844  int rc = SQLITE_OK;
181845  Fts5ExprNode *p1 = pNode->apChild[0];
181846  Fts5ExprNode *p2 = pNode->apChild[1];
181847  assert( pNode->nChild==2 );
181848 
181849  while( rc==SQLITE_OK && p1->bEof==0 ){
181850  int cmp = fts5NodeCompare(pExpr, p1, p2);
181851  if( cmp>0 ){
181852  rc = fts5ExprNodeNext(pExpr, p2, 1, p1->iRowid);
181853  cmp = fts5NodeCompare(pExpr, p1, p2);
181854  }
181855  assert( rc!=SQLITE_OK || cmp<=0 );
181856  if( cmp || p2->bNomatch ) break;
181857  rc = fts5ExprNodeNext(pExpr, p1, 0, 0);
181858  }
181859  pNode->bEof = p1->bEof;
181860  pNode->bNomatch = p1->bNomatch;
181861  pNode->iRowid = p1->iRowid;
181862  if( p1->bEof ){
181863  fts5ExprNodeZeroPoslist(p2);
181864  }
181865  return rc;
181866 }
181867 
181868 static int fts5ExprNodeNext_NOT(
181869  Fts5Expr *pExpr,
181870  Fts5ExprNode *pNode,
181871  int bFromValid,
181872  i64 iFrom
181873 ){
181874  int rc = fts5ExprNodeNext(pExpr, pNode->apChild[0], bFromValid, iFrom);
181875  if( rc==SQLITE_OK ){
181876  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
181877  }
181878  return rc;
181879 }
181880 
181881 /*
181882 ** If pNode currently points to a match, this function returns SQLITE_OK
181883 ** without modifying it. Otherwise, pNode is advanced until it does point
181884 ** to a match or EOF is reached.
181885 */
181886 static int fts5ExprNodeTest(
181887  Fts5Expr *pExpr, /* Expression of which pNode is a part */
181888  Fts5ExprNode *pNode /* Expression node to test */
181889 ){
181890  int rc = SQLITE_OK;
181891  if( pNode->bEof==0 ){
181892  switch( pNode->eType ){
181893 
181894  case FTS5_STRING: {
181895  rc = fts5ExprNodeTest_STRING(pExpr, pNode);
181896  break;
181897  }
181898 
181899  case FTS5_TERM: {
181900  rc = fts5ExprNodeTest_TERM(pExpr, pNode);
181901  break;
181902  }
181903 
181904  case FTS5_AND: {
181905  rc = fts5ExprNodeTest_AND(pExpr, pNode);
181906  break;
181907  }
181908 
181909  case FTS5_OR: {
181910  fts5ExprNodeTest_OR(pExpr, pNode);
181911  break;
181912  }
181913 
181914  default: assert( pNode->eType==FTS5_NOT ); {
181915  rc = fts5ExprNodeTest_NOT(pExpr, pNode);
181916  break;
181917  }
181918  }
181919  }
181920  return rc;
181921 }
181922 
181923 
181924 /*
181925 ** Set node pNode, which is part of expression pExpr, to point to the first
181926 ** match. If there are no matches, set the Node.bEof flag to indicate EOF.
181927 **
181928 ** Return an SQLite error code if an error occurs, or SQLITE_OK otherwise.
181929 ** It is not an error if there are no matches.
181930 */
181931 static int fts5ExprNodeFirst(Fts5Expr *pExpr, Fts5ExprNode *pNode){
181932  int rc = SQLITE_OK;
181933  pNode->bEof = 0;
181934  pNode->bNomatch = 0;
181935 
181936  if( Fts5NodeIsString(pNode) ){
181937  /* Initialize all term iterators in the NEAR object. */
181938  rc = fts5ExprNearInitAll(pExpr, pNode);
181939  }else if( pNode->xNext==0 ){
181940  pNode->bEof = 1;
181941  }else{
181942  int i;
181943  int nEof = 0;
181944  for(i=0; i<pNode->nChild && rc==SQLITE_OK; i++){
181945  Fts5ExprNode *pChild = pNode->apChild[i];
181946  rc = fts5ExprNodeFirst(pExpr, pNode->apChild[i]);
181947  assert( pChild->bEof==0 || pChild->bEof==1 );
181948  nEof += pChild->bEof;
181949  }
181950  pNode->iRowid = pNode->apChild[0]->iRowid;
181951 
181952  switch( pNode->eType ){
181953  case FTS5_AND:
181954  if( nEof>0 ) fts5ExprSetEof(pNode);
181955  break;
181956 
181957  case FTS5_OR:
181958  if( pNode->nChild==nEof ) fts5ExprSetEof(pNode);
181959  break;
181960 
181961  default:
181962  assert( pNode->eType==FTS5_NOT );
181963  pNode->bEof = pNode->apChild[0]->bEof;
181964  break;
181965  }
181966  }
181967 
181968  if( rc==SQLITE_OK ){
181969  rc = fts5ExprNodeTest(pExpr, pNode);
181970  }
181971  return rc;
181972 }
181973 
181974 
181975 /*
181976 ** Begin iterating through the set of documents in index pIdx matched by
181977 ** the MATCH expression passed as the first argument. If the "bDesc"
181978 ** parameter is passed a non-zero value, iteration is in descending rowid
181979 ** order. Or, if it is zero, in ascending order.
181980 **
181981 ** If iterating in ascending rowid order (bDesc==0), the first document
181982 ** visited is that with the smallest rowid that is larger than or equal
181983 ** to parameter iFirst. Or, if iterating in ascending order (bDesc==1),
181984 ** then the first document visited must have a rowid smaller than or
181985 ** equal to iFirst.
181986 **
181987 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
181988 ** is not considered an error if the query does not match any documents.
181989 */
181990 static int sqlite3Fts5ExprFirst(Fts5Expr *p, Fts5Index *pIdx, i64 iFirst, int bDesc){
181991  Fts5ExprNode *pRoot = p->pRoot;
181992  int rc; /* Return code */
181993 
181994  p->pIndex = pIdx;
181995  p->bDesc = bDesc;
181996  rc = fts5ExprNodeFirst(p, pRoot);
181997 
181998  /* If not at EOF but the current rowid occurs earlier than iFirst in
181999  ** the iteration order, move to document iFirst or later. */
182000  if( pRoot->bEof==0 && fts5RowidCmp(p, pRoot->iRowid, iFirst)<0 ){
182001  rc = fts5ExprNodeNext(p, pRoot, 1, iFirst);
182002  }
182003 
182004  /* If the iterator is not at a real match, skip forward until it is. */
182005  while( pRoot->bNomatch ){
182006  assert( pRoot->bEof==0 && rc==SQLITE_OK );
182007  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
182008  }
182009  return rc;
182010 }
182011 
182012 /*
182013 ** Move to the next document
182014 **
182015 ** Return SQLITE_OK if successful, or an SQLite error code otherwise. It
182016 ** is not considered an error if the query does not match any documents.
182017 */
182018 static int sqlite3Fts5ExprNext(Fts5Expr *p, i64 iLast){
182019  int rc;
182020  Fts5ExprNode *pRoot = p->pRoot;
182021  assert( pRoot->bEof==0 && pRoot->bNomatch==0 );
182022  do {
182023  rc = fts5ExprNodeNext(p, pRoot, 0, 0);
182024  assert( pRoot->bNomatch==0 || (rc==SQLITE_OK && pRoot->bEof==0) );
182025  }while( pRoot->bNomatch );
182026  if( fts5RowidCmp(p, pRoot->iRowid, iLast)>0 ){
182027  pRoot->bEof = 1;
182028  }
182029  return rc;
182030 }
182031 
182032 static int sqlite3Fts5ExprEof(Fts5Expr *p){
182033  return p->pRoot->bEof;
182034 }
182035 
182036 static i64 sqlite3Fts5ExprRowid(Fts5Expr *p){
182037  return p->pRoot->iRowid;
182038 }
182039 
182040 static int fts5ParseStringFromToken(Fts5Token *pToken, char **pz){
182041  int rc = SQLITE_OK;
182042  *pz = sqlite3Fts5Strndup(&rc, pToken->p, pToken->n);
182043  return rc;
182044 }
182045 
182046 /*
182047 ** Free the phrase object passed as the only argument.
182048 */
182049 static void fts5ExprPhraseFree(Fts5ExprPhrase *pPhrase){
182050  if( pPhrase ){
182051  int i;
182052  for(i=0; i<pPhrase->nTerm; i++){
182053  Fts5ExprTerm *pSyn;
182054  Fts5ExprTerm *pNext;
182055  Fts5ExprTerm *pTerm = &pPhrase->aTerm[i];
182056  sqlite3_free(pTerm->zTerm);
182057  sqlite3Fts5IterClose(pTerm->pIter);
182058  for(pSyn=pTerm->pSynonym; pSyn; pSyn=pNext){
182059  pNext = pSyn->pSynonym;
182060  sqlite3Fts5IterClose(pSyn->pIter);
182061  fts5BufferFree((Fts5Buffer*)&pSyn[1]);
182062  sqlite3_free(pSyn);
182063  }
182064  }
182065  if( pPhrase->poslist.nSpace>0 ) fts5BufferFree(&pPhrase->poslist);
182066  sqlite3_free(pPhrase);
182067  }
182068 }
182069 
182070 /*
182071 ** If argument pNear is NULL, then a new Fts5ExprNearset object is allocated
182072 ** and populated with pPhrase. Or, if pNear is not NULL, phrase pPhrase is
182073 ** appended to it and the results returned.
182074 **
182075 ** If an OOM error occurs, both the pNear and pPhrase objects are freed and
182076 ** NULL returned.
182077 */
182078 static Fts5ExprNearset *sqlite3Fts5ParseNearset(
182079  Fts5Parse *pParse, /* Parse context */
182080  Fts5ExprNearset *pNear, /* Existing nearset, or NULL */
182081  Fts5ExprPhrase *pPhrase /* Recently parsed phrase */
182082 ){
182083  const int SZALLOC = 8;
182084  Fts5ExprNearset *pRet = 0;
182085 
182086  if( pParse->rc==SQLITE_OK ){
182087  if( pPhrase==0 ){
182088  return pNear;
182089  }
182090  if( pNear==0 ){
182091  int nByte = sizeof(Fts5ExprNearset) + SZALLOC * sizeof(Fts5ExprPhrase*);
182092  pRet = sqlite3_malloc(nByte);
182093  if( pRet==0 ){
182094  pParse->rc = SQLITE_NOMEM;
182095  }else{
182096  memset(pRet, 0, nByte);
182097  }
182098  }else if( (pNear->nPhrase % SZALLOC)==0 ){
182099  int nNew = pNear->nPhrase + SZALLOC;
182100  int nByte = sizeof(Fts5ExprNearset) + nNew * sizeof(Fts5ExprPhrase*);
182101 
182102  pRet = (Fts5ExprNearset*)sqlite3_realloc(pNear, nByte);
182103  if( pRet==0 ){
182104  pParse->rc = SQLITE_NOMEM;
182105  }
182106  }else{
182107  pRet = pNear;
182108  }
182109  }
182110 
182111  if( pRet==0 ){
182112  assert( pParse->rc!=SQLITE_OK );
182113  sqlite3Fts5ParseNearsetFree(pNear);
182114  sqlite3Fts5ParsePhraseFree(pPhrase);
182115  }else{
182116  if( pRet->nPhrase>0 ){
182117  Fts5ExprPhrase *pLast = pRet->apPhrase[pRet->nPhrase-1];
182118  assert( pLast==pParse->apPhrase[pParse->nPhrase-2] );
182119  if( pPhrase->nTerm==0 ){
182120  fts5ExprPhraseFree(pPhrase);
182121  pRet->nPhrase--;
182122  pParse->nPhrase--;
182123  pPhrase = pLast;
182124  }else if( pLast->nTerm==0 ){
182125  fts5ExprPhraseFree(pLast);
182126  pParse->apPhrase[pParse->nPhrase-2] = pPhrase;
182127  pParse->nPhrase--;
182128  pRet->nPhrase--;
182129  }
182130  }
182131  pRet->apPhrase[pRet->nPhrase++] = pPhrase;
182132  }
182133  return pRet;
182134 }
182135 
182136 typedef struct TokenCtx TokenCtx;
182137 struct TokenCtx {
182138  Fts5ExprPhrase *pPhrase;
182139  int rc;
182140 };
182141 
182142 /*
182143 ** Callback for tokenizing terms used by ParseTerm().
182144 */
182145 static int fts5ParseTokenize(
182146  void *pContext, /* Pointer to Fts5InsertCtx object */
182147  int tflags, /* Mask of FTS5_TOKEN_* flags */
182148  const char *pToken, /* Buffer containing token */
182149  int nToken, /* Size of token in bytes */
182150  int iUnused1, /* Start offset of token */
182151  int iUnused2 /* End offset of token */
182152 ){
182153  int rc = SQLITE_OK;
182154  const int SZALLOC = 8;
182155  TokenCtx *pCtx = (TokenCtx*)pContext;
182156  Fts5ExprPhrase *pPhrase = pCtx->pPhrase;
182157 
182158  UNUSED_PARAM2(iUnused1, iUnused2);
182159 
182160  /* If an error has already occurred, this is a no-op */
182161  if( pCtx->rc!=SQLITE_OK ) return pCtx->rc;
182162  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
182163 
182164  if( pPhrase && pPhrase->nTerm>0 && (tflags & FTS5_TOKEN_COLOCATED) ){
182165  Fts5ExprTerm *pSyn;
182166  int nByte = sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer) + nToken+1;
182167  pSyn = (Fts5ExprTerm*)sqlite3_malloc(nByte);
182168  if( pSyn==0 ){
182169  rc = SQLITE_NOMEM;
182170  }else{
182171  memset(pSyn, 0, nByte);
182172  pSyn->zTerm = ((char*)pSyn) + sizeof(Fts5ExprTerm) + sizeof(Fts5Buffer);
182173  memcpy(pSyn->zTerm, pToken, nToken);
182174  pSyn->pSynonym = pPhrase->aTerm[pPhrase->nTerm-1].pSynonym;
182175  pPhrase->aTerm[pPhrase->nTerm-1].pSynonym = pSyn;
182176  }
182177  }else{
182178  Fts5ExprTerm *pTerm;
182179  if( pPhrase==0 || (pPhrase->nTerm % SZALLOC)==0 ){
182180  Fts5ExprPhrase *pNew;
182181  int nNew = SZALLOC + (pPhrase ? pPhrase->nTerm : 0);
182182 
182183  pNew = (Fts5ExprPhrase*)sqlite3_realloc(pPhrase,
182184  sizeof(Fts5ExprPhrase) + sizeof(Fts5ExprTerm) * nNew
182185  );
182186  if( pNew==0 ){
182187  rc = SQLITE_NOMEM;
182188  }else{
182189  if( pPhrase==0 ) memset(pNew, 0, sizeof(Fts5ExprPhrase));
182190  pCtx->pPhrase = pPhrase = pNew;
182191  pNew->nTerm = nNew - SZALLOC;
182192  }
182193  }
182194 
182195  if( rc==SQLITE_OK ){
182196  pTerm = &pPhrase->aTerm[pPhrase->nTerm++];
182197  memset(pTerm, 0, sizeof(Fts5ExprTerm));
182198  pTerm->zTerm = sqlite3Fts5Strndup(&rc, pToken, nToken);
182199  }
182200  }
182201 
182202  pCtx->rc = rc;
182203  return rc;
182204 }
182205 
182206 
182207 /*
182208 ** Free the phrase object passed as the only argument.
182209 */
182210 static void sqlite3Fts5ParsePhraseFree(Fts5ExprPhrase *pPhrase){
182211  fts5ExprPhraseFree(pPhrase);
182212 }
182213 
182214 /*
182215 ** Free the phrase object passed as the second argument.
182216 */
182217 static void sqlite3Fts5ParseNearsetFree(Fts5ExprNearset *pNear){
182218  if( pNear ){
182219  int i;
182220  for(i=0; i<pNear->nPhrase; i++){
182221  fts5ExprPhraseFree(pNear->apPhrase[i]);
182222  }
182223  sqlite3_free(pNear->pColset);
182224  sqlite3_free(pNear);
182225  }
182226 }
182227 
182228 static void sqlite3Fts5ParseFinished(Fts5Parse *pParse, Fts5ExprNode *p){
182229  assert( pParse->pExpr==0 );
182230  pParse->pExpr = p;
182231 }
182232 
182233 /*
182234 ** This function is called by the parser to process a string token. The
182235 ** string may or may not be quoted. In any case it is tokenized and a
182236 ** phrase object consisting of all tokens returned.
182237 */
182238 static Fts5ExprPhrase *sqlite3Fts5ParseTerm(
182239  Fts5Parse *pParse, /* Parse context */
182240  Fts5ExprPhrase *pAppend, /* Phrase to append to */
182241  Fts5Token *pToken, /* String to tokenize */
182242  int bPrefix /* True if there is a trailing "*" */
182243 ){
182244  Fts5Config *pConfig = pParse->pConfig;
182245  TokenCtx sCtx; /* Context object passed to callback */
182246  int rc; /* Tokenize return code */
182247  char *z = 0;
182248 
182249  memset(&sCtx, 0, sizeof(TokenCtx));
182250  sCtx.pPhrase = pAppend;
182251 
182252  rc = fts5ParseStringFromToken(pToken, &z);
182253  if( rc==SQLITE_OK ){
182254  int flags = FTS5_TOKENIZE_QUERY | (bPrefix ? FTS5_TOKENIZE_QUERY : 0);
182255  int n;
182256  sqlite3Fts5Dequote(z);
182257  n = (int)strlen(z);
182258  rc = sqlite3Fts5Tokenize(pConfig, flags, z, n, &sCtx, fts5ParseTokenize);
182259  }
182260  sqlite3_free(z);
182261  if( rc || (rc = sCtx.rc) ){
182262  pParse->rc = rc;
182263  fts5ExprPhraseFree(sCtx.pPhrase);
182264  sCtx.pPhrase = 0;
182265  }else{
182266 
182267  if( pAppend==0 ){
182268  if( (pParse->nPhrase % 8)==0 ){
182269  int nByte = sizeof(Fts5ExprPhrase*) * (pParse->nPhrase + 8);
182270  Fts5ExprPhrase **apNew;
182271  apNew = (Fts5ExprPhrase**)sqlite3_realloc(pParse->apPhrase, nByte);
182272  if( apNew==0 ){
182273  pParse->rc = SQLITE_NOMEM;
182274  fts5ExprPhraseFree(sCtx.pPhrase);
182275  return 0;
182276  }
182277  pParse->apPhrase = apNew;
182278  }
182279  pParse->nPhrase++;
182280  }
182281 
182282  if( sCtx.pPhrase==0 ){
182283  /* This happens when parsing a token or quoted phrase that contains
182284  ** no token characters at all. (e.g ... MATCH '""'). */
182285  sCtx.pPhrase = sqlite3Fts5MallocZero(&pParse->rc, sizeof(Fts5ExprPhrase));
182286  }else if( sCtx.pPhrase->nTerm ){
182287  sCtx.pPhrase->aTerm[sCtx.pPhrase->nTerm-1].bPrefix = bPrefix;
182288  }
182289  pParse->apPhrase[pParse->nPhrase-1] = sCtx.pPhrase;
182290  }
182291 
182292  return sCtx.pPhrase;
182293 }
182294 
182295 /*
182296 ** Create a new FTS5 expression by cloning phrase iPhrase of the
182297 ** expression passed as the second argument.
182298 */
182299 static int sqlite3Fts5ExprClonePhrase(
182300  Fts5Expr *pExpr,
182301  int iPhrase,
182302  Fts5Expr **ppNew
182303 ){
182304  int rc = SQLITE_OK; /* Return code */
182305  Fts5ExprPhrase *pOrig; /* The phrase extracted from pExpr */
182306  int i; /* Used to iterate through phrase terms */
182307  Fts5Expr *pNew = 0; /* Expression to return via *ppNew */
182308  TokenCtx sCtx = {0,0}; /* Context object for fts5ParseTokenize */
182309 
182310  pOrig = pExpr->apExprPhrase[iPhrase];
182311  pNew = (Fts5Expr*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Expr));
182312  if( rc==SQLITE_OK ){
182313  pNew->apExprPhrase = (Fts5ExprPhrase**)sqlite3Fts5MallocZero(&rc,
182314  sizeof(Fts5ExprPhrase*));
182315  }
182316  if( rc==SQLITE_OK ){
182317  pNew->pRoot = (Fts5ExprNode*)sqlite3Fts5MallocZero(&rc,
182318  sizeof(Fts5ExprNode));
182319  }
182320  if( rc==SQLITE_OK ){
182321  pNew->pRoot->pNear = (Fts5ExprNearset*)sqlite3Fts5MallocZero(&rc,
182322  sizeof(Fts5ExprNearset) + sizeof(Fts5ExprPhrase*));
182323  }
182324  if( rc==SQLITE_OK ){
182325  Fts5Colset *pColsetOrig = pOrig->pNode->pNear->pColset;
182326  if( pColsetOrig ){
182327  int nByte = sizeof(Fts5Colset) + pColsetOrig->nCol * sizeof(int);
182328  Fts5Colset *pColset = (Fts5Colset*)sqlite3Fts5MallocZero(&rc, nByte);
182329  if( pColset ){
182330  memcpy(pColset, pColsetOrig, nByte);
182331  }
182332  pNew->pRoot->pNear->pColset = pColset;
182333  }
182334  }
182335 
182336  for(i=0; rc==SQLITE_OK && i<pOrig->nTerm; i++){
182337  int tflags = 0;
182338  Fts5ExprTerm *p;
182339  for(p=&pOrig->aTerm[i]; p && rc==SQLITE_OK; p=p->pSynonym){
182340  const char *zTerm = p->zTerm;
182341  rc = fts5ParseTokenize((void*)&sCtx, tflags, zTerm, (int)strlen(zTerm),
182342  0, 0);
182343  tflags = FTS5_TOKEN_COLOCATED;
182344  }
182345  if( rc==SQLITE_OK ){
182346  sCtx.pPhrase->aTerm[i].bPrefix = pOrig->aTerm[i].bPrefix;
182347  }
182348  }
182349 
182350  if( rc==SQLITE_OK ){
182351  /* All the allocations succeeded. Put the expression object together. */
182352  pNew->pIndex = pExpr->pIndex;
182353  pNew->pConfig = pExpr->pConfig;
182354  pNew->nPhrase = 1;
182355  pNew->apExprPhrase[0] = sCtx.pPhrase;
182356  pNew->pRoot->pNear->apPhrase[0] = sCtx.pPhrase;
182357  pNew->pRoot->pNear->nPhrase = 1;
182358  sCtx.pPhrase->pNode = pNew->pRoot;
182359 
182360  if( pOrig->nTerm==1 && pOrig->aTerm[0].pSynonym==0 ){
182361  pNew->pRoot->eType = FTS5_TERM;
182362  pNew->pRoot->xNext = fts5ExprNodeNext_TERM;
182363  }else{
182364  pNew->pRoot->eType = FTS5_STRING;
182365  pNew->pRoot->xNext = fts5ExprNodeNext_STRING;
182366  }
182367  }else{
182368  sqlite3Fts5ExprFree(pNew);
182369  fts5ExprPhraseFree(sCtx.pPhrase);
182370  pNew = 0;
182371  }
182372 
182373  *ppNew = pNew;
182374  return rc;
182375 }
182376 
182377 
182378 /*
182379 ** Token pTok has appeared in a MATCH expression where the NEAR operator
182380 ** is expected. If token pTok does not contain "NEAR", store an error
182381 ** in the pParse object.
182382 */
182383 static void sqlite3Fts5ParseNear(Fts5Parse *pParse, Fts5Token *pTok){
182384  if( pTok->n!=4 || memcmp("NEAR", pTok->p, 4) ){
182385  sqlite3Fts5ParseError(
182386  pParse, "fts5: syntax error near \"%.*s\"", pTok->n, pTok->p
182387  );
182388  }
182389 }
182390 
182391 static void sqlite3Fts5ParseSetDistance(
182392  Fts5Parse *pParse,
182393  Fts5ExprNearset *pNear,
182394  Fts5Token *p
182395 ){
182396  if( pNear ){
182397  int nNear = 0;
182398  int i;
182399  if( p->n ){
182400  for(i=0; i<p->n; i++){
182401  char c = (char)p->p[i];
182402  if( c<'0' || c>'9' ){
182403  sqlite3Fts5ParseError(
182404  pParse, "expected integer, got \"%.*s\"", p->n, p->p
182405  );
182406  return;
182407  }
182408  nNear = nNear * 10 + (p->p[i] - '0');
182409  }
182410  }else{
182411  nNear = FTS5_DEFAULT_NEARDIST;
182412  }
182413  pNear->nNear = nNear;
182414  }
182415 }
182416 
182417 /*
182418 ** The second argument passed to this function may be NULL, or it may be
182419 ** an existing Fts5Colset object. This function returns a pointer to
182420 ** a new colset object containing the contents of (p) with new value column
182421 ** number iCol appended.
182422 **
182423 ** If an OOM error occurs, store an error code in pParse and return NULL.
182424 ** The old colset object (if any) is not freed in this case.
182425 */
182426 static Fts5Colset *fts5ParseColset(
182427  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
182428  Fts5Colset *p, /* Existing colset object */
182429  int iCol /* New column to add to colset object */
182430 ){
182431  int nCol = p ? p->nCol : 0; /* Num. columns already in colset object */
182432  Fts5Colset *pNew; /* New colset object to return */
182433 
182434  assert( pParse->rc==SQLITE_OK );
182435  assert( iCol>=0 && iCol<pParse->pConfig->nCol );
182436 
182437  pNew = sqlite3_realloc(p, sizeof(Fts5Colset) + sizeof(int)*nCol);
182438  if( pNew==0 ){
182439  pParse->rc = SQLITE_NOMEM;
182440  }else{
182441  int *aiCol = pNew->aiCol;
182442  int i, j;
182443  for(i=0; i<nCol; i++){
182444  if( aiCol[i]==iCol ) return pNew;
182445  if( aiCol[i]>iCol ) break;
182446  }
182447  for(j=nCol; j>i; j--){
182448  aiCol[j] = aiCol[j-1];
182449  }
182450  aiCol[i] = iCol;
182451  pNew->nCol = nCol+1;
182452 
182453 #ifndef NDEBUG
182454  /* Check that the array is in order and contains no duplicate entries. */
182455  for(i=1; i<pNew->nCol; i++) assert( pNew->aiCol[i]>pNew->aiCol[i-1] );
182456 #endif
182457  }
182458 
182459  return pNew;
182460 }
182461 
182462 static Fts5Colset *sqlite3Fts5ParseColset(
182463  Fts5Parse *pParse, /* Store SQLITE_NOMEM here if required */
182464  Fts5Colset *pColset, /* Existing colset object */
182465  Fts5Token *p
182466 ){
182467  Fts5Colset *pRet = 0;
182468  int iCol;
182469  char *z; /* Dequoted copy of token p */
182470 
182471  z = sqlite3Fts5Strndup(&pParse->rc, p->p, p->n);
182472  if( pParse->rc==SQLITE_OK ){
182473  Fts5Config *pConfig = pParse->pConfig;
182474  sqlite3Fts5Dequote(z);
182475  for(iCol=0; iCol<pConfig->nCol; iCol++){
182476  if( 0==sqlite3_stricmp(pConfig->azCol[iCol], z) ) break;
182477  }
182478  if( iCol==pConfig->nCol ){
182479  sqlite3Fts5ParseError(pParse, "no such column: %s", z);
182480  }else{
182481  pRet = fts5ParseColset(pParse, pColset, iCol);
182482  }
182483  sqlite3_free(z);
182484  }
182485 
182486  if( pRet==0 ){
182487  assert( pParse->rc!=SQLITE_OK );
182488  sqlite3_free(pColset);
182489  }
182490 
182491  return pRet;
182492 }
182493 
182494 static void sqlite3Fts5ParseSetColset(
182495  Fts5Parse *pParse,
182496  Fts5ExprNearset *pNear,
182497  Fts5Colset *pColset
182498 ){
182499  if( pParse->pConfig->eDetail==FTS5_DETAIL_NONE ){
182500  pParse->rc = SQLITE_ERROR;
182501  pParse->zErr = sqlite3_mprintf(
182502  "fts5: column queries are not supported (detail=none)"
182503  );
182504  sqlite3_free(pColset);
182505  return;
182506  }
182507 
182508  if( pNear ){
182509  pNear->pColset = pColset;
182510  }else{
182511  sqlite3_free(pColset);
182512  }
182513 }
182514 
182515 static void fts5ExprAssignXNext(Fts5ExprNode *pNode){
182516  switch( pNode->eType ){
182517  case FTS5_STRING: {
182518  Fts5ExprNearset *pNear = pNode->pNear;
182519  if( pNear->nPhrase==1 && pNear->apPhrase[0]->nTerm==1
182520  && pNear->apPhrase[0]->aTerm[0].pSynonym==0
182521  ){
182522  pNode->eType = FTS5_TERM;
182523  pNode->xNext = fts5ExprNodeNext_TERM;
182524  }else{
182525  pNode->xNext = fts5ExprNodeNext_STRING;
182526  }
182527  break;
182528  };
182529 
182530  case FTS5_OR: {
182531  pNode->xNext = fts5ExprNodeNext_OR;
182532  break;
182533  };
182534 
182535  case FTS5_AND: {
182536  pNode->xNext = fts5ExprNodeNext_AND;
182537  break;
182538  };
182539 
182540  default: assert( pNode->eType==FTS5_NOT ); {
182541  pNode->xNext = fts5ExprNodeNext_NOT;
182542  break;
182543  };
182544  }
182545 }
182546 
182547 static void fts5ExprAddChildren(Fts5ExprNode *p, Fts5ExprNode *pSub){
182548  if( p->eType!=FTS5_NOT && pSub->eType==p->eType ){
182549  int nByte = sizeof(Fts5ExprNode*) * pSub->nChild;
182550  memcpy(&p->apChild[p->nChild], pSub->apChild, nByte);
182551  p->nChild += pSub->nChild;
182552  sqlite3_free(pSub);
182553  }else{
182554  p->apChild[p->nChild++] = pSub;
182555  }
182556 }
182557 
182558 /*
182559 ** Allocate and return a new expression object. If anything goes wrong (i.e.
182560 ** OOM error), leave an error code in pParse and return NULL.
182561 */
182562 static Fts5ExprNode *sqlite3Fts5ParseNode(
182563  Fts5Parse *pParse, /* Parse context */
182564  int eType, /* FTS5_STRING, AND, OR or NOT */
182565  Fts5ExprNode *pLeft, /* Left hand child expression */
182566  Fts5ExprNode *pRight, /* Right hand child expression */
182567  Fts5ExprNearset *pNear /* For STRING expressions, the near cluster */
182568 ){
182569  Fts5ExprNode *pRet = 0;
182570 
182571  if( pParse->rc==SQLITE_OK ){
182572  int nChild = 0; /* Number of children of returned node */
182573  int nByte; /* Bytes of space to allocate for this node */
182574 
182575  assert( (eType!=FTS5_STRING && !pNear)
182576  || (eType==FTS5_STRING && !pLeft && !pRight)
182577  );
182578  if( eType==FTS5_STRING && pNear==0 ) return 0;
182579  if( eType!=FTS5_STRING && pLeft==0 ) return pRight;
182580  if( eType!=FTS5_STRING && pRight==0 ) return pLeft;
182581 
182582  if( eType==FTS5_NOT ){
182583  nChild = 2;
182584  }else if( eType==FTS5_AND || eType==FTS5_OR ){
182585  nChild = 2;
182586  if( pLeft->eType==eType ) nChild += pLeft->nChild-1;
182587  if( pRight->eType==eType ) nChild += pRight->nChild-1;
182588  }
182589 
182590  nByte = sizeof(Fts5ExprNode) + sizeof(Fts5ExprNode*)*(nChild-1);
182591  pRet = (Fts5ExprNode*)sqlite3Fts5MallocZero(&pParse->rc, nByte);
182592 
182593  if( pRet ){
182594  pRet->eType = eType;
182595  pRet->pNear = pNear;
182596  fts5ExprAssignXNext(pRet);
182597  if( eType==FTS5_STRING ){
182598  int iPhrase;
182599  for(iPhrase=0; iPhrase<pNear->nPhrase; iPhrase++){
182600  pNear->apPhrase[iPhrase]->pNode = pRet;
182601  if( pNear->apPhrase[iPhrase]->nTerm==0 ){
182602  pRet->xNext = 0;
182603  pRet->eType = FTS5_EOF;
182604  }
182605  }
182606 
182607  if( pParse->pConfig->eDetail!=FTS5_DETAIL_FULL
182608  && (pNear->nPhrase!=1 || pNear->apPhrase[0]->nTerm>1)
182609  ){
182610  assert( pParse->rc==SQLITE_OK );
182611  pParse->rc = SQLITE_ERROR;
182612  assert( pParse->zErr==0 );
182613  pParse->zErr = sqlite3_mprintf(
182614  "fts5: %s queries are not supported (detail!=full)",
182615  pNear->nPhrase==1 ? "phrase": "NEAR"
182616  );
182617  sqlite3_free(pRet);
182618  pRet = 0;
182619  }
182620 
182621  }else{
182622  fts5ExprAddChildren(pRet, pLeft);
182623  fts5ExprAddChildren(pRet, pRight);
182624  }
182625  }
182626  }
182627 
182628  if( pRet==0 ){
182629  assert( pParse->rc!=SQLITE_OK );
182630  sqlite3Fts5ParseNodeFree(pLeft);
182631  sqlite3Fts5ParseNodeFree(pRight);
182632  sqlite3Fts5ParseNearsetFree(pNear);
182633  }
182634  return pRet;
182635 }
182636 
182637 static Fts5ExprNode *sqlite3Fts5ParseImplicitAnd(
182638  Fts5Parse *pParse, /* Parse context */
182639  Fts5ExprNode *pLeft, /* Left hand child expression */
182640  Fts5ExprNode *pRight /* Right hand child expression */
182641 ){
182642  Fts5ExprNode *pRet = 0;
182643  Fts5ExprNode *pPrev;
182644 
182645  if( pParse->rc ){
182646  sqlite3Fts5ParseNodeFree(pLeft);
182647  sqlite3Fts5ParseNodeFree(pRight);
182648  }else{
182649 
182650  assert( pLeft->eType==FTS5_STRING
182651  || pLeft->eType==FTS5_TERM
182652  || pLeft->eType==FTS5_EOF
182653  || pLeft->eType==FTS5_AND
182654  );
182655  assert( pRight->eType==FTS5_STRING
182656  || pRight->eType==FTS5_TERM
182657  || pRight->eType==FTS5_EOF
182658  );
182659 
182660  if( pLeft->eType==FTS5_AND ){
182661  pPrev = pLeft->apChild[pLeft->nChild-1];
182662  }else{
182663  pPrev = pLeft;
182664  }
182665  assert( pPrev->eType==FTS5_STRING
182666  || pPrev->eType==FTS5_TERM
182667  || pPrev->eType==FTS5_EOF
182668  );
182669 
182670  if( pRight->eType==FTS5_EOF ){
182671  assert( pParse->apPhrase[pParse->nPhrase-1]==pRight->pNear->apPhrase[0] );
182672  sqlite3Fts5ParseNodeFree(pRight);
182673  pRet = pLeft;
182674  pParse->nPhrase--;
182675  }
182676  else if( pPrev->eType==FTS5_EOF ){
182677  Fts5ExprPhrase **ap;
182678 
182679  if( pPrev==pLeft ){
182680  pRet = pRight;
182681  }else{
182682  pLeft->apChild[pLeft->nChild-1] = pRight;
182683  pRet = pLeft;
182684  }
182685 
182686  ap = &pParse->apPhrase[pParse->nPhrase-1-pRight->pNear->nPhrase];
182687  assert( ap[0]==pPrev->pNear->apPhrase[0] );
182688  memmove(ap, &ap[1], sizeof(Fts5ExprPhrase*)*pRight->pNear->nPhrase);
182689  pParse->nPhrase--;
182690 
182691  sqlite3Fts5ParseNodeFree(pPrev);
182692  }
182693  else{
182694  pRet = sqlite3Fts5ParseNode(pParse, FTS5_AND, pLeft, pRight, 0);
182695  }
182696  }
182697 
182698  return pRet;
182699 }
182700 
182701 static char *fts5ExprTermPrint(Fts5ExprTerm *pTerm){
182702  int nByte = 0;
182703  Fts5ExprTerm *p;
182704  char *zQuoted;
182705 
182706  /* Determine the maximum amount of space required. */
182707  for(p=pTerm; p; p=p->pSynonym){
182708  nByte += (int)strlen(pTerm->zTerm) * 2 + 3 + 2;
182709  }
182710  zQuoted = sqlite3_malloc(nByte);
182711 
182712  if( zQuoted ){
182713  int i = 0;
182714  for(p=pTerm; p; p=p->pSynonym){
182715  char *zIn = p->zTerm;
182716  zQuoted[i++] = '"';
182717  while( *zIn ){
182718  if( *zIn=='"' ) zQuoted[i++] = '"';
182719  zQuoted[i++] = *zIn++;
182720  }
182721  zQuoted[i++] = '"';
182722  if( p->pSynonym ) zQuoted[i++] = '|';
182723  }
182724  if( pTerm->bPrefix ){
182725  zQuoted[i++] = ' ';
182726  zQuoted[i++] = '*';
182727  }
182728  zQuoted[i++] = '\0';
182729  }
182730  return zQuoted;
182731 }
182732 
182733 static char *fts5PrintfAppend(char *zApp, const char *zFmt, ...){
182734  char *zNew;
182735  va_list ap;
182736  va_start(ap, zFmt);
182737  zNew = sqlite3_vmprintf(zFmt, ap);
182738  va_end(ap);
182739  if( zApp && zNew ){
182740  char *zNew2 = sqlite3_mprintf("%s%s", zApp, zNew);
182741  sqlite3_free(zNew);
182742  zNew = zNew2;
182743  }
182744  sqlite3_free(zApp);
182745  return zNew;
182746 }
182747 
182748 /*
182749 ** Compose a tcl-readable representation of expression pExpr. Return a
182750 ** pointer to a buffer containing that representation. It is the
182751 ** responsibility of the caller to at some point free the buffer using
182752 ** sqlite3_free().
182753 */
182754 static char *fts5ExprPrintTcl(
182755  Fts5Config *pConfig,
182756  const char *zNearsetCmd,
182757  Fts5ExprNode *pExpr
182758 ){
182759  char *zRet = 0;
182760  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
182761  Fts5ExprNearset *pNear = pExpr->pNear;
182762  int i;
182763  int iTerm;
182764 
182765  zRet = fts5PrintfAppend(zRet, "%s ", zNearsetCmd);
182766  if( zRet==0 ) return 0;
182767  if( pNear->pColset ){
182768  int *aiCol = pNear->pColset->aiCol;
182769  int nCol = pNear->pColset->nCol;
182770  if( nCol==1 ){
182771  zRet = fts5PrintfAppend(zRet, "-col %d ", aiCol[0]);
182772  }else{
182773  zRet = fts5PrintfAppend(zRet, "-col {%d", aiCol[0]);
182774  for(i=1; i<pNear->pColset->nCol; i++){
182775  zRet = fts5PrintfAppend(zRet, " %d", aiCol[i]);
182776  }
182777  zRet = fts5PrintfAppend(zRet, "} ");
182778  }
182779  if( zRet==0 ) return 0;
182780  }
182781 
182782  if( pNear->nPhrase>1 ){
182783  zRet = fts5PrintfAppend(zRet, "-near %d ", pNear->nNear);
182784  if( zRet==0 ) return 0;
182785  }
182786 
182787  zRet = fts5PrintfAppend(zRet, "--");
182788  if( zRet==0 ) return 0;
182789 
182790  for(i=0; i<pNear->nPhrase; i++){
182791  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182792 
182793  zRet = fts5PrintfAppend(zRet, " {");
182794  for(iTerm=0; zRet && iTerm<pPhrase->nTerm; iTerm++){
182795  char *zTerm = pPhrase->aTerm[iTerm].zTerm;
182796  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" ", zTerm);
182797  if( pPhrase->aTerm[iTerm].bPrefix ){
182798  zRet = fts5PrintfAppend(zRet, "*");
182799  }
182800  }
182801 
182802  if( zRet ) zRet = fts5PrintfAppend(zRet, "}");
182803  if( zRet==0 ) return 0;
182804  }
182805 
182806  }else{
182807  char const *zOp = 0;
182808  int i;
182809  switch( pExpr->eType ){
182810  case FTS5_AND: zOp = "AND"; break;
182811  case FTS5_NOT: zOp = "NOT"; break;
182812  default:
182813  assert( pExpr->eType==FTS5_OR );
182814  zOp = "OR";
182815  break;
182816  }
182817 
182818  zRet = sqlite3_mprintf("%s", zOp);
182819  for(i=0; zRet && i<pExpr->nChild; i++){
182820  char *z = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->apChild[i]);
182821  if( !z ){
182822  sqlite3_free(zRet);
182823  zRet = 0;
182824  }else{
182825  zRet = fts5PrintfAppend(zRet, " [%z]", z);
182826  }
182827  }
182828  }
182829 
182830  return zRet;
182831 }
182832 
182833 static char *fts5ExprPrint(Fts5Config *pConfig, Fts5ExprNode *pExpr){
182834  char *zRet = 0;
182835  if( pExpr->eType==0 ){
182836  return sqlite3_mprintf("\"\"");
182837  }else
182838  if( pExpr->eType==FTS5_STRING || pExpr->eType==FTS5_TERM ){
182839  Fts5ExprNearset *pNear = pExpr->pNear;
182840  int i;
182841  int iTerm;
182842 
182843  if( pNear->pColset ){
182844  int iCol = pNear->pColset->aiCol[0];
182845  zRet = fts5PrintfAppend(zRet, "%s : ", pConfig->azCol[iCol]);
182846  if( zRet==0 ) return 0;
182847  }
182848 
182849  if( pNear->nPhrase>1 ){
182850  zRet = fts5PrintfAppend(zRet, "NEAR(");
182851  if( zRet==0 ) return 0;
182852  }
182853 
182854  for(i=0; i<pNear->nPhrase; i++){
182855  Fts5ExprPhrase *pPhrase = pNear->apPhrase[i];
182856  if( i!=0 ){
182857  zRet = fts5PrintfAppend(zRet, " ");
182858  if( zRet==0 ) return 0;
182859  }
182860  for(iTerm=0; iTerm<pPhrase->nTerm; iTerm++){
182861  char *zTerm = fts5ExprTermPrint(&pPhrase->aTerm[iTerm]);
182862  if( zTerm ){
182863  zRet = fts5PrintfAppend(zRet, "%s%s", iTerm==0?"":" + ", zTerm);
182864  sqlite3_free(zTerm);
182865  }
182866  if( zTerm==0 || zRet==0 ){
182867  sqlite3_free(zRet);
182868  return 0;
182869  }
182870  }
182871  }
182872 
182873  if( pNear->nPhrase>1 ){
182874  zRet = fts5PrintfAppend(zRet, ", %d)", pNear->nNear);
182875  if( zRet==0 ) return 0;
182876  }
182877 
182878  }else{
182879  char const *zOp = 0;
182880  int i;
182881 
182882  switch( pExpr->eType ){
182883  case FTS5_AND: zOp = " AND "; break;
182884  case FTS5_NOT: zOp = " NOT "; break;
182885  default:
182886  assert( pExpr->eType==FTS5_OR );
182887  zOp = " OR ";
182888  break;
182889  }
182890 
182891  for(i=0; i<pExpr->nChild; i++){
182892  char *z = fts5ExprPrint(pConfig, pExpr->apChild[i]);
182893  if( z==0 ){
182894  sqlite3_free(zRet);
182895  zRet = 0;
182896  }else{
182897  int e = pExpr->apChild[i]->eType;
182898  int b = (e!=FTS5_STRING && e!=FTS5_TERM && e!=FTS5_EOF);
182899  zRet = fts5PrintfAppend(zRet, "%s%s%z%s",
182900  (i==0 ? "" : zOp),
182901  (b?"(":""), z, (b?")":"")
182902  );
182903  }
182904  if( zRet==0 ) break;
182905  }
182906  }
182907 
182908  return zRet;
182909 }
182910 
182911 /*
182912 ** The implementation of user-defined scalar functions fts5_expr() (bTcl==0)
182913 ** and fts5_expr_tcl() (bTcl!=0).
182914 */
182915 static void fts5ExprFunction(
182916  sqlite3_context *pCtx, /* Function call context */
182917  int nArg, /* Number of args */
182918  sqlite3_value **apVal, /* Function arguments */
182919  int bTcl
182920 ){
182921  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
182922  sqlite3 *db = sqlite3_context_db_handle(pCtx);
182923  const char *zExpr = 0;
182924  char *zErr = 0;
182925  Fts5Expr *pExpr = 0;
182926  int rc;
182927  int i;
182928 
182929  const char **azConfig; /* Array of arguments for Fts5Config */
182930  const char *zNearsetCmd = "nearset";
182931  int nConfig; /* Size of azConfig[] */
182932  Fts5Config *pConfig = 0;
182933  int iArg = 1;
182934 
182935  if( nArg<1 ){
182936  zErr = sqlite3_mprintf("wrong number of arguments to function %s",
182937  bTcl ? "fts5_expr_tcl" : "fts5_expr"
182938  );
182939  sqlite3_result_error(pCtx, zErr, -1);
182940  sqlite3_free(zErr);
182941  return;
182942  }
182943 
182944  if( bTcl && nArg>1 ){
182945  zNearsetCmd = (const char*)sqlite3_value_text(apVal[1]);
182946  iArg = 2;
182947  }
182948 
182949  nConfig = 3 + (nArg-iArg);
182950  azConfig = (const char**)sqlite3_malloc(sizeof(char*) * nConfig);
182951  if( azConfig==0 ){
182953  return;
182954  }
182955  azConfig[0] = 0;
182956  azConfig[1] = "main";
182957  azConfig[2] = "tbl";
182958  for(i=3; iArg<nArg; iArg++){
182959  azConfig[i++] = (const char*)sqlite3_value_text(apVal[iArg]);
182960  }
182961 
182962  zExpr = (const char*)sqlite3_value_text(apVal[0]);
182963 
182964  rc = sqlite3Fts5ConfigParse(pGlobal, db, nConfig, azConfig, &pConfig, &zErr);
182965  if( rc==SQLITE_OK ){
182966  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pExpr, &zErr);
182967  }
182968  if( rc==SQLITE_OK ){
182969  char *zText;
182970  if( pExpr->pRoot->xNext==0 ){
182971  zText = sqlite3_mprintf("");
182972  }else if( bTcl ){
182973  zText = fts5ExprPrintTcl(pConfig, zNearsetCmd, pExpr->pRoot);
182974  }else{
182975  zText = fts5ExprPrint(pConfig, pExpr->pRoot);
182976  }
182977  if( zText==0 ){
182978  rc = SQLITE_NOMEM;
182979  }else{
182980  sqlite3_result_text(pCtx, zText, -1, SQLITE_TRANSIENT);
182981  sqlite3_free(zText);
182982  }
182983  }
182984 
182985  if( rc!=SQLITE_OK ){
182986  if( zErr ){
182987  sqlite3_result_error(pCtx, zErr, -1);
182988  sqlite3_free(zErr);
182989  }else{
182990  sqlite3_result_error_code(pCtx, rc);
182991  }
182992  }
182993  sqlite3_free((void *)azConfig);
182994  sqlite3Fts5ConfigFree(pConfig);
182995  sqlite3Fts5ExprFree(pExpr);
182996 }
182997 
182998 static void fts5ExprFunctionHr(
182999  sqlite3_context *pCtx, /* Function call context */
183000  int nArg, /* Number of args */
183001  sqlite3_value **apVal /* Function arguments */
183002 ){
183003  fts5ExprFunction(pCtx, nArg, apVal, 0);
183004 }
183005 static void fts5ExprFunctionTcl(
183006  sqlite3_context *pCtx, /* Function call context */
183007  int nArg, /* Number of args */
183008  sqlite3_value **apVal /* Function arguments */
183009 ){
183010  fts5ExprFunction(pCtx, nArg, apVal, 1);
183011 }
183012 
183013 /*
183014 ** The implementation of an SQLite user-defined-function that accepts a
183015 ** single integer as an argument. If the integer is an alpha-numeric
183016 ** unicode code point, 1 is returned. Otherwise 0.
183017 */
183018 static void fts5ExprIsAlnum(
183019  sqlite3_context *pCtx, /* Function call context */
183020  int nArg, /* Number of args */
183021  sqlite3_value **apVal /* Function arguments */
183022 ){
183023  int iCode;
183024  if( nArg!=1 ){
183025  sqlite3_result_error(pCtx,
183026  "wrong number of arguments to function fts5_isalnum", -1
183027  );
183028  return;
183029  }
183030  iCode = sqlite3_value_int(apVal[0]);
183031  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeIsalnum(iCode));
183032 }
183033 
183034 static void fts5ExprFold(
183035  sqlite3_context *pCtx, /* Function call context */
183036  int nArg, /* Number of args */
183037  sqlite3_value **apVal /* Function arguments */
183038 ){
183039  if( nArg!=1 && nArg!=2 ){
183040  sqlite3_result_error(pCtx,
183041  "wrong number of arguments to function fts5_fold", -1
183042  );
183043  }else{
183044  int iCode;
183045  int bRemoveDiacritics = 0;
183046  iCode = sqlite3_value_int(apVal[0]);
183047  if( nArg==2 ) bRemoveDiacritics = sqlite3_value_int(apVal[1]);
183048  sqlite3_result_int(pCtx, sqlite3Fts5UnicodeFold(iCode, bRemoveDiacritics));
183049  }
183050 }
183051 
183052 /*
183053 ** This is called during initialization to register the fts5_expr() scalar
183054 ** UDF with the SQLite handle passed as the only argument.
183055 */
183056 static int sqlite3Fts5ExprInit(Fts5Global *pGlobal, sqlite3 *db){
183057  struct Fts5ExprFunc {
183058  const char *z;
183059  void (*x)(sqlite3_context*,int,sqlite3_value**);
183060  } aFunc[] = {
183061  { "fts5_expr", fts5ExprFunctionHr },
183062  { "fts5_expr_tcl", fts5ExprFunctionTcl },
183063  { "fts5_isalnum", fts5ExprIsAlnum },
183064  { "fts5_fold", fts5ExprFold },
183065  };
183066  int i;
183067  int rc = SQLITE_OK;
183068  void *pCtx = (void*)pGlobal;
183069 
183070  for(i=0; rc==SQLITE_OK && i<ArraySize(aFunc); i++){
183071  struct Fts5ExprFunc *p = &aFunc[i];
183072  rc = sqlite3_create_function(db, p->z, -1, SQLITE_UTF8, pCtx, p->x, 0, 0);
183073  }
183074 
183075  /* Avoid a warning indicating that sqlite3Fts5ParserTrace() is unused */
183076 #ifndef NDEBUG
183077  (void)sqlite3Fts5ParserTrace;
183078 #endif
183079 
183080  return rc;
183081 }
183082 
183083 /*
183084 ** Return the number of phrases in expression pExpr.
183085 */
183086 static int sqlite3Fts5ExprPhraseCount(Fts5Expr *pExpr){
183087  return (pExpr ? pExpr->nPhrase : 0);
183088 }
183089 
183090 /*
183091 ** Return the number of terms in the iPhrase'th phrase in pExpr.
183092 */
183093 static int sqlite3Fts5ExprPhraseSize(Fts5Expr *pExpr, int iPhrase){
183094  if( iPhrase<0 || iPhrase>=pExpr->nPhrase ) return 0;
183095  return pExpr->apExprPhrase[iPhrase]->nTerm;
183096 }
183097 
183098 /*
183099 ** This function is used to access the current position list for phrase
183100 ** iPhrase.
183101 */
183102 static int sqlite3Fts5ExprPoslist(Fts5Expr *pExpr, int iPhrase, const u8 **pa){
183103  int nRet;
183104  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
183105  Fts5ExprNode *pNode = pPhrase->pNode;
183106  if( pNode->bEof==0 && pNode->iRowid==pExpr->pRoot->iRowid ){
183107  *pa = pPhrase->poslist.p;
183108  nRet = pPhrase->poslist.n;
183109  }else{
183110  *pa = 0;
183111  nRet = 0;
183112  }
183113  return nRet;
183114 }
183115 
183116 struct Fts5PoslistPopulator {
183117  Fts5PoslistWriter writer;
183118  int bOk; /* True if ok to populate */
183119  int bMiss;
183120 };
183121 
183122 static Fts5PoslistPopulator *sqlite3Fts5ExprClearPoslists(Fts5Expr *pExpr, int bLive){
183123  Fts5PoslistPopulator *pRet;
183124  pRet = sqlite3_malloc(sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
183125  if( pRet ){
183126  int i;
183127  memset(pRet, 0, sizeof(Fts5PoslistPopulator)*pExpr->nPhrase);
183128  for(i=0; i<pExpr->nPhrase; i++){
183129  Fts5Buffer *pBuf = &pExpr->apExprPhrase[i]->poslist;
183130  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
183131  assert( pExpr->apExprPhrase[i]->nTerm==1 );
183132  if( bLive &&
183133  (pBuf->n==0 || pNode->iRowid!=pExpr->pRoot->iRowid || pNode->bEof)
183134  ){
183135  pRet[i].bMiss = 1;
183136  }else{
183137  pBuf->n = 0;
183138  }
183139  }
183140  }
183141  return pRet;
183142 }
183143 
183144 struct Fts5ExprCtx {
183145  Fts5Expr *pExpr;
183146  Fts5PoslistPopulator *aPopulator;
183147  i64 iOff;
183148 };
183149 typedef struct Fts5ExprCtx Fts5ExprCtx;
183150 
183151 /*
183152 ** TODO: Make this more efficient!
183153 */
183154 static int fts5ExprColsetTest(Fts5Colset *pColset, int iCol){
183155  int i;
183156  for(i=0; i<pColset->nCol; i++){
183157  if( pColset->aiCol[i]==iCol ) return 1;
183158  }
183159  return 0;
183160 }
183161 
183162 static int fts5ExprPopulatePoslistsCb(
183163  void *pCtx, /* Copy of 2nd argument to xTokenize() */
183164  int tflags, /* Mask of FTS5_TOKEN_* flags */
183165  const char *pToken, /* Pointer to buffer containing token */
183166  int nToken, /* Size of token in bytes */
183167  int iUnused1, /* Byte offset of token within input text */
183168  int iUnused2 /* Byte offset of end of token within input text */
183169 ){
183170  Fts5ExprCtx *p = (Fts5ExprCtx*)pCtx;
183171  Fts5Expr *pExpr = p->pExpr;
183172  int i;
183173 
183174  UNUSED_PARAM2(iUnused1, iUnused2);
183175 
183176  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
183177  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ) p->iOff++;
183178  for(i=0; i<pExpr->nPhrase; i++){
183179  Fts5ExprTerm *pTerm;
183180  if( p->aPopulator[i].bOk==0 ) continue;
183181  for(pTerm=&pExpr->apExprPhrase[i]->aTerm[0]; pTerm; pTerm=pTerm->pSynonym){
183182  int nTerm = (int)strlen(pTerm->zTerm);
183183  if( (nTerm==nToken || (nTerm<nToken && pTerm->bPrefix))
183184  && memcmp(pTerm->zTerm, pToken, nTerm)==0
183185  ){
183186  int rc = sqlite3Fts5PoslistWriterAppend(
183187  &pExpr->apExprPhrase[i]->poslist, &p->aPopulator[i].writer, p->iOff
183188  );
183189  if( rc ) return rc;
183190  break;
183191  }
183192  }
183193  }
183194  return SQLITE_OK;
183195 }
183196 
183197 static int sqlite3Fts5ExprPopulatePoslists(
183198  Fts5Config *pConfig,
183199  Fts5Expr *pExpr,
183200  Fts5PoslistPopulator *aPopulator,
183201  int iCol,
183202  const char *z, int n
183203 ){
183204  int i;
183205  Fts5ExprCtx sCtx;
183206  sCtx.pExpr = pExpr;
183207  sCtx.aPopulator = aPopulator;
183208  sCtx.iOff = (((i64)iCol) << 32) - 1;
183209 
183210  for(i=0; i<pExpr->nPhrase; i++){
183211  Fts5ExprNode *pNode = pExpr->apExprPhrase[i]->pNode;
183212  Fts5Colset *pColset = pNode->pNear->pColset;
183213  if( (pColset && 0==fts5ExprColsetTest(pColset, iCol))
183214  || aPopulator[i].bMiss
183215  ){
183216  aPopulator[i].bOk = 0;
183217  }else{
183218  aPopulator[i].bOk = 1;
183219  }
183220  }
183221 
183222  return sqlite3Fts5Tokenize(pConfig,
183223  FTS5_TOKENIZE_DOCUMENT, z, n, (void*)&sCtx, fts5ExprPopulatePoslistsCb
183224  );
183225 }
183226 
183227 static void fts5ExprClearPoslists(Fts5ExprNode *pNode){
183228  if( pNode->eType==FTS5_TERM || pNode->eType==FTS5_STRING ){
183229  pNode->pNear->apPhrase[0]->poslist.n = 0;
183230  }else{
183231  int i;
183232  for(i=0; i<pNode->nChild; i++){
183233  fts5ExprClearPoslists(pNode->apChild[i]);
183234  }
183235  }
183236 }
183237 
183238 static int fts5ExprCheckPoslists(Fts5ExprNode *pNode, i64 iRowid){
183239  pNode->iRowid = iRowid;
183240  pNode->bEof = 0;
183241  switch( pNode->eType ){
183242  case FTS5_TERM:
183243  case FTS5_STRING:
183244  return (pNode->pNear->apPhrase[0]->poslist.n>0);
183245 
183246  case FTS5_AND: {
183247  int i;
183248  for(i=0; i<pNode->nChild; i++){
183249  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid)==0 ){
183250  fts5ExprClearPoslists(pNode);
183251  return 0;
183252  }
183253  }
183254  break;
183255  }
183256 
183257  case FTS5_OR: {
183258  int i;
183259  int bRet = 0;
183260  for(i=0; i<pNode->nChild; i++){
183261  if( fts5ExprCheckPoslists(pNode->apChild[i], iRowid) ){
183262  bRet = 1;
183263  }
183264  }
183265  return bRet;
183266  }
183267 
183268  default: {
183269  assert( pNode->eType==FTS5_NOT );
183270  if( 0==fts5ExprCheckPoslists(pNode->apChild[0], iRowid)
183271  || 0!=fts5ExprCheckPoslists(pNode->apChild[1], iRowid)
183272  ){
183273  fts5ExprClearPoslists(pNode);
183274  return 0;
183275  }
183276  break;
183277  }
183278  }
183279  return 1;
183280 }
183281 
183282 static void sqlite3Fts5ExprCheckPoslists(Fts5Expr *pExpr, i64 iRowid){
183283  fts5ExprCheckPoslists(pExpr->pRoot, iRowid);
183284 }
183285 
183286 static void fts5ExprClearEof(Fts5ExprNode *pNode){
183287  int i;
183288  for(i=0; i<pNode->nChild; i++){
183289  fts5ExprClearEof(pNode->apChild[i]);
183290  }
183291  pNode->bEof = 0;
183292 }
183293 static void sqlite3Fts5ExprClearEof(Fts5Expr *pExpr){
183294  fts5ExprClearEof(pExpr->pRoot);
183295 }
183296 
183297 /*
183298 ** This function is only called for detail=columns tables.
183299 */
183300 static int sqlite3Fts5ExprPhraseCollist(
183301  Fts5Expr *pExpr,
183302  int iPhrase,
183303  const u8 **ppCollist,
183304  int *pnCollist
183305 ){
183306  Fts5ExprPhrase *pPhrase = pExpr->apExprPhrase[iPhrase];
183307  Fts5ExprNode *pNode = pPhrase->pNode;
183308  int rc = SQLITE_OK;
183309 
183310  assert( iPhrase>=0 && iPhrase<pExpr->nPhrase );
183311  assert( pExpr->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
183312 
183313  if( pNode->bEof==0
183314  && pNode->iRowid==pExpr->pRoot->iRowid
183315  && pPhrase->poslist.n>0
183316  ){
183317  Fts5ExprTerm *pTerm = &pPhrase->aTerm[0];
183318  if( pTerm->pSynonym ){
183319  Fts5Buffer *pBuf = (Fts5Buffer*)&pTerm->pSynonym[1];
183320  rc = fts5ExprSynonymList(
183321  pTerm, pNode->iRowid, pBuf, (u8**)ppCollist, pnCollist
183322  );
183323  }else{
183324  *ppCollist = pPhrase->aTerm[0].pIter->pData;
183325  *pnCollist = pPhrase->aTerm[0].pIter->nData;
183326  }
183327  }else{
183328  *ppCollist = 0;
183329  *pnCollist = 0;
183330  }
183331 
183332  return rc;
183333 }
183334 
183335 
183336 /*
183337 ** 2014 August 11
183338 **
183339 ** The author disclaims copyright to this source code. In place of
183340 ** a legal notice, here is a blessing:
183341 **
183342 ** May you do good and not evil.
183343 ** May you find forgiveness for yourself and forgive others.
183344 ** May you share freely, never taking more than you give.
183345 **
183346 ******************************************************************************
183347 **
183348 */
183349 
183350 
183351 
183352 /* #include "fts5Int.h" */
183353 
183354 typedef struct Fts5HashEntry Fts5HashEntry;
183355 
183356 /*
183357 ** This file contains the implementation of an in-memory hash table used
183358 ** to accumuluate "term -> doclist" content before it is flused to a level-0
183359 ** segment.
183360 */
183361 
183362 
183363 struct Fts5Hash {
183364  int eDetail; /* Copy of Fts5Config.eDetail */
183365  int *pnByte; /* Pointer to bytes counter */
183366  int nEntry; /* Number of entries currently in hash */
183367  int nSlot; /* Size of aSlot[] array */
183368  Fts5HashEntry *pScan; /* Current ordered scan item */
183369  Fts5HashEntry **aSlot; /* Array of hash slots */
183370 };
183371 
183372 /*
183373 ** Each entry in the hash table is represented by an object of the
183374 ** following type. Each object, its key (zKey[]) and its current data
183375 ** are stored in a single memory allocation. The position list data
183376 ** immediately follows the key data in memory.
183377 **
183378 ** The data that follows the key is in a similar, but not identical format
183379 ** to the doclist data stored in the database. It is:
183380 **
183381 ** * Rowid, as a varint
183382 ** * Position list, without 0x00 terminator.
183383 ** * Size of previous position list and rowid, as a 4 byte
183384 ** big-endian integer.
183385 **
183386 ** iRowidOff:
183387 ** Offset of last rowid written to data area. Relative to first byte of
183388 ** structure.
183389 **
183390 ** nData:
183391 ** Bytes of data written since iRowidOff.
183392 */
183393 struct Fts5HashEntry {
183394  Fts5HashEntry *pHashNext; /* Next hash entry with same hash-key */
183395  Fts5HashEntry *pScanNext; /* Next entry in sorted order */
183396 
183397  int nAlloc; /* Total size of allocation */
183398  int iSzPoslist; /* Offset of space for 4-byte poslist size */
183399  int nData; /* Total bytes of data (incl. structure) */
183400  int nKey; /* Length of zKey[] in bytes */
183401  u8 bDel; /* Set delete-flag @ iSzPoslist */
183402  u8 bContent; /* Set content-flag (detail=none mode) */
183403  i16 iCol; /* Column of last value written */
183404  int iPos; /* Position of last value written */
183405  i64 iRowid; /* Rowid of last value written */
183406  char zKey[8]; /* Nul-terminated entry key */
183407 };
183408 
183409 /*
183410 ** Size of Fts5HashEntry without the zKey[] array.
183411 */
183412 #define FTS5_HASHENTRYSIZE (sizeof(Fts5HashEntry)-8)
183413 
183414 
183415 
183416 /*
183417 ** Allocate a new hash table.
183418 */
183419 static int sqlite3Fts5HashNew(Fts5Config *pConfig, Fts5Hash **ppNew, int *pnByte){
183420  int rc = SQLITE_OK;
183421  Fts5Hash *pNew;
183422 
183423  *ppNew = pNew = (Fts5Hash*)sqlite3_malloc(sizeof(Fts5Hash));
183424  if( pNew==0 ){
183425  rc = SQLITE_NOMEM;
183426  }else{
183427  int nByte;
183428  memset(pNew, 0, sizeof(Fts5Hash));
183429  pNew->pnByte = pnByte;
183430  pNew->eDetail = pConfig->eDetail;
183431 
183432  pNew->nSlot = 1024;
183433  nByte = sizeof(Fts5HashEntry*) * pNew->nSlot;
183434  pNew->aSlot = (Fts5HashEntry**)sqlite3_malloc(nByte);
183435  if( pNew->aSlot==0 ){
183436  sqlite3_free(pNew);
183437  *ppNew = 0;
183438  rc = SQLITE_NOMEM;
183439  }else{
183440  memset(pNew->aSlot, 0, nByte);
183441  }
183442  }
183443  return rc;
183444 }
183445 
183446 /*
183447 ** Free a hash table object.
183448 */
183449 static void sqlite3Fts5HashFree(Fts5Hash *pHash){
183450  if( pHash ){
183451  sqlite3Fts5HashClear(pHash);
183452  sqlite3_free(pHash->aSlot);
183453  sqlite3_free(pHash);
183454  }
183455 }
183456 
183457 /*
183458 ** Empty (but do not delete) a hash table.
183459 */
183460 static void sqlite3Fts5HashClear(Fts5Hash *pHash){
183461  int i;
183462  for(i=0; i<pHash->nSlot; i++){
183463  Fts5HashEntry *pNext;
183464  Fts5HashEntry *pSlot;
183465  for(pSlot=pHash->aSlot[i]; pSlot; pSlot=pNext){
183466  pNext = pSlot->pHashNext;
183467  sqlite3_free(pSlot);
183468  }
183469  }
183470  memset(pHash->aSlot, 0, pHash->nSlot * sizeof(Fts5HashEntry*));
183471  pHash->nEntry = 0;
183472 }
183473 
183474 static unsigned int fts5HashKey(int nSlot, const u8 *p, int n){
183475  int i;
183476  unsigned int h = 13;
183477  for(i=n-1; i>=0; i--){
183478  h = (h << 3) ^ h ^ p[i];
183479  }
183480  return (h % nSlot);
183481 }
183482 
183483 static unsigned int fts5HashKey2(int nSlot, u8 b, const u8 *p, int n){
183484  int i;
183485  unsigned int h = 13;
183486  for(i=n-1; i>=0; i--){
183487  h = (h << 3) ^ h ^ p[i];
183488  }
183489  h = (h << 3) ^ h ^ b;
183490  return (h % nSlot);
183491 }
183492 
183493 /*
183494 ** Resize the hash table by doubling the number of slots.
183495 */
183496 static int fts5HashResize(Fts5Hash *pHash){
183497  int nNew = pHash->nSlot*2;
183498  int i;
183499  Fts5HashEntry **apNew;
183500  Fts5HashEntry **apOld = pHash->aSlot;
183501 
183502  apNew = (Fts5HashEntry**)sqlite3_malloc(nNew*sizeof(Fts5HashEntry*));
183503  if( !apNew ) return SQLITE_NOMEM;
183504  memset(apNew, 0, nNew*sizeof(Fts5HashEntry*));
183505 
183506  for(i=0; i<pHash->nSlot; i++){
183507  while( apOld[i] ){
183508  int iHash;
183509  Fts5HashEntry *p = apOld[i];
183510  apOld[i] = p->pHashNext;
183511  iHash = fts5HashKey(nNew, (u8*)p->zKey, (int)strlen(p->zKey));
183512  p->pHashNext = apNew[iHash];
183513  apNew[iHash] = p;
183514  }
183515  }
183516 
183517  sqlite3_free(apOld);
183518  pHash->nSlot = nNew;
183519  pHash->aSlot = apNew;
183520  return SQLITE_OK;
183521 }
183522 
183523 static void fts5HashAddPoslistSize(Fts5Hash *pHash, Fts5HashEntry *p){
183524  if( p->iSzPoslist ){
183525  u8 *pPtr = (u8*)p;
183526  if( pHash->eDetail==FTS5_DETAIL_NONE ){
183527  assert( p->nData==p->iSzPoslist );
183528  if( p->bDel ){
183529  pPtr[p->nData++] = 0x00;
183530  if( p->bContent ){
183531  pPtr[p->nData++] = 0x00;
183532  }
183533  }
183534  }else{
183535  int nSz = (p->nData - p->iSzPoslist - 1); /* Size in bytes */
183536  int nPos = nSz*2 + p->bDel; /* Value of nPos field */
183537 
183538  assert( p->bDel==0 || p->bDel==1 );
183539  if( nPos<=127 ){
183540  pPtr[p->iSzPoslist] = (u8)nPos;
183541  }else{
183542  int nByte = sqlite3Fts5GetVarintLen((u32)nPos);
183543  memmove(&pPtr[p->iSzPoslist + nByte], &pPtr[p->iSzPoslist + 1], nSz);
183544  sqlite3Fts5PutVarint(&pPtr[p->iSzPoslist], nPos);
183545  p->nData += (nByte-1);
183546  }
183547  }
183548 
183549  p->iSzPoslist = 0;
183550  p->bDel = 0;
183551  p->bContent = 0;
183552  }
183553 }
183554 
183555 /*
183556 ** Add an entry to the in-memory hash table. The key is the concatenation
183557 ** of bByte and (pToken/nToken). The value is (iRowid/iCol/iPos).
183558 **
183559 ** (bByte || pToken) -> (iRowid,iCol,iPos)
183560 **
183561 ** Or, if iCol is negative, then the value is a delete marker.
183562 */
183563 static int sqlite3Fts5HashWrite(
183564  Fts5Hash *pHash,
183565  i64 iRowid, /* Rowid for this entry */
183566  int iCol, /* Column token appears in (-ve -> delete) */
183567  int iPos, /* Position of token within column */
183568  char bByte, /* First byte of token */
183569  const char *pToken, int nToken /* Token to add or remove to or from index */
183570 ){
183571  unsigned int iHash;
183572  Fts5HashEntry *p;
183573  u8 *pPtr;
183574  int nIncr = 0; /* Amount to increment (*pHash->pnByte) by */
183575  int bNew; /* If non-delete entry should be written */
183576 
183577  bNew = (pHash->eDetail==FTS5_DETAIL_FULL);
183578 
183579  /* Attempt to locate an existing hash entry */
183580  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
183581  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
183582  if( p->zKey[0]==bByte
183583  && p->nKey==nToken
183584  && memcmp(&p->zKey[1], pToken, nToken)==0
183585  ){
183586  break;
183587  }
183588  }
183589 
183590  /* If an existing hash entry cannot be found, create a new one. */
183591  if( p==0 ){
183592  /* Figure out how much space to allocate */
183593  int nByte = FTS5_HASHENTRYSIZE + (nToken+1) + 1 + 64;
183594  if( nByte<128 ) nByte = 128;
183595 
183596  /* Grow the Fts5Hash.aSlot[] array if necessary. */
183597  if( (pHash->nEntry*2)>=pHash->nSlot ){
183598  int rc = fts5HashResize(pHash);
183599  if( rc!=SQLITE_OK ) return rc;
183600  iHash = fts5HashKey2(pHash->nSlot, (u8)bByte, (const u8*)pToken, nToken);
183601  }
183602 
183603  /* Allocate new Fts5HashEntry and add it to the hash table. */
183604  p = (Fts5HashEntry*)sqlite3_malloc(nByte);
183605  if( !p ) return SQLITE_NOMEM;
183606  memset(p, 0, FTS5_HASHENTRYSIZE);
183607  p->nAlloc = nByte;
183608  p->zKey[0] = bByte;
183609  memcpy(&p->zKey[1], pToken, nToken);
183610  assert( iHash==fts5HashKey(pHash->nSlot, (u8*)p->zKey, nToken+1) );
183611  p->nKey = nToken;
183612  p->zKey[nToken+1] = '\0';
183613  p->nData = nToken+1 + 1 + FTS5_HASHENTRYSIZE;
183614  p->pHashNext = pHash->aSlot[iHash];
183615  pHash->aSlot[iHash] = p;
183616  pHash->nEntry++;
183617 
183618  /* Add the first rowid field to the hash-entry */
183619  p->nData += sqlite3Fts5PutVarint(&((u8*)p)[p->nData], iRowid);
183620  p->iRowid = iRowid;
183621 
183622  p->iSzPoslist = p->nData;
183623  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
183624  p->nData += 1;
183625  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
183626  }
183627 
183628  nIncr += p->nData;
183629  }else{
183630 
183631  /* Appending to an existing hash-entry. Check that there is enough
183632  ** space to append the largest possible new entry. Worst case scenario
183633  ** is:
183634  **
183635  ** + 9 bytes for a new rowid,
183636  ** + 4 byte reserved for the "poslist size" varint.
183637  ** + 1 byte for a "new column" byte,
183638  ** + 3 bytes for a new column number (16-bit max) as a varint,
183639  ** + 5 bytes for the new position offset (32-bit max).
183640  */
183641  if( (p->nAlloc - p->nData) < (9 + 4 + 1 + 3 + 5) ){
183642  int nNew = p->nAlloc * 2;
183643  Fts5HashEntry *pNew;
183644  Fts5HashEntry **pp;
183645  pNew = (Fts5HashEntry*)sqlite3_realloc(p, nNew);
183646  if( pNew==0 ) return SQLITE_NOMEM;
183647  pNew->nAlloc = nNew;
183648  for(pp=&pHash->aSlot[iHash]; *pp!=p; pp=&(*pp)->pHashNext);
183649  *pp = pNew;
183650  p = pNew;
183651  }
183652  nIncr -= p->nData;
183653  }
183654  assert( (p->nAlloc - p->nData) >= (9 + 4 + 1 + 3 + 5) );
183655 
183656  pPtr = (u8*)p;
183657 
183658  /* If this is a new rowid, append the 4-byte size field for the previous
183659  ** entry, and the new rowid for this entry. */
183660  if( iRowid!=p->iRowid ){
183661  fts5HashAddPoslistSize(pHash, p);
183662  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iRowid - p->iRowid);
183663  p->iRowid = iRowid;
183664  bNew = 1;
183665  p->iSzPoslist = p->nData;
183666  if( pHash->eDetail!=FTS5_DETAIL_NONE ){
183667  p->nData += 1;
183668  p->iCol = (pHash->eDetail==FTS5_DETAIL_FULL ? 0 : -1);
183669  p->iPos = 0;
183670  }
183671  }
183672 
183673  if( iCol>=0 ){
183674  if( pHash->eDetail==FTS5_DETAIL_NONE ){
183675  p->bContent = 1;
183676  }else{
183677  /* Append a new column value, if necessary */
183678  assert( iCol>=p->iCol );
183679  if( iCol!=p->iCol ){
183680  if( pHash->eDetail==FTS5_DETAIL_FULL ){
183681  pPtr[p->nData++] = 0x01;
183682  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iCol);
183683  p->iCol = (i16)iCol;
183684  p->iPos = 0;
183685  }else{
183686  bNew = 1;
183687  p->iCol = (i16)(iPos = iCol);
183688  }
183689  }
183690 
183691  /* Append the new position offset, if necessary */
183692  if( bNew ){
183693  p->nData += sqlite3Fts5PutVarint(&pPtr[p->nData], iPos - p->iPos + 2);
183694  p->iPos = iPos;
183695  }
183696  }
183697  }else{
183698  /* This is a delete. Set the delete flag. */
183699  p->bDel = 1;
183700  }
183701 
183702  nIncr += p->nData;
183703  *pHash->pnByte += nIncr;
183704  return SQLITE_OK;
183705 }
183706 
183707 
183708 /*
183709 ** Arguments pLeft and pRight point to linked-lists of hash-entry objects,
183710 ** each sorted in key order. This function merges the two lists into a
183711 ** single list and returns a pointer to its first element.
183712 */
183713 static Fts5HashEntry *fts5HashEntryMerge(
183714  Fts5HashEntry *pLeft,
183715  Fts5HashEntry *pRight
183716 ){
183717  Fts5HashEntry *p1 = pLeft;
183718  Fts5HashEntry *p2 = pRight;
183719  Fts5HashEntry *pRet = 0;
183720  Fts5HashEntry **ppOut = &pRet;
183721 
183722  while( p1 || p2 ){
183723  if( p1==0 ){
183724  *ppOut = p2;
183725  p2 = 0;
183726  }else if( p2==0 ){
183727  *ppOut = p1;
183728  p1 = 0;
183729  }else{
183730  int i = 0;
183731  while( p1->zKey[i]==p2->zKey[i] ) i++;
183732 
183733  if( ((u8)p1->zKey[i])>((u8)p2->zKey[i]) ){
183734  /* p2 is smaller */
183735  *ppOut = p2;
183736  ppOut = &p2->pScanNext;
183737  p2 = p2->pScanNext;
183738  }else{
183739  /* p1 is smaller */
183740  *ppOut = p1;
183741  ppOut = &p1->pScanNext;
183742  p1 = p1->pScanNext;
183743  }
183744  *ppOut = 0;
183745  }
183746  }
183747 
183748  return pRet;
183749 }
183750 
183751 /*
183752 ** Extract all tokens from hash table iHash and link them into a list
183753 ** in sorted order. The hash table is cleared before returning. It is
183754 ** the responsibility of the caller to free the elements of the returned
183755 ** list.
183756 */
183757 static int fts5HashEntrySort(
183758  Fts5Hash *pHash,
183759  const char *pTerm, int nTerm, /* Query prefix, if any */
183760  Fts5HashEntry **ppSorted
183761 ){
183762  const int nMergeSlot = 32;
183763  Fts5HashEntry **ap;
183764  Fts5HashEntry *pList;
183765  int iSlot;
183766  int i;
183767 
183768  *ppSorted = 0;
183769  ap = sqlite3_malloc(sizeof(Fts5HashEntry*) * nMergeSlot);
183770  if( !ap ) return SQLITE_NOMEM;
183771  memset(ap, 0, sizeof(Fts5HashEntry*) * nMergeSlot);
183772 
183773  for(iSlot=0; iSlot<pHash->nSlot; iSlot++){
183774  Fts5HashEntry *pIter;
183775  for(pIter=pHash->aSlot[iSlot]; pIter; pIter=pIter->pHashNext){
183776  if( pTerm==0 || 0==memcmp(pIter->zKey, pTerm, nTerm) ){
183777  Fts5HashEntry *pEntry = pIter;
183778  pEntry->pScanNext = 0;
183779  for(i=0; ap[i]; i++){
183780  pEntry = fts5HashEntryMerge(pEntry, ap[i]);
183781  ap[i] = 0;
183782  }
183783  ap[i] = pEntry;
183784  }
183785  }
183786  }
183787 
183788  pList = 0;
183789  for(i=0; i<nMergeSlot; i++){
183790  pList = fts5HashEntryMerge(pList, ap[i]);
183791  }
183792 
183793  pHash->nEntry = 0;
183794  sqlite3_free(ap);
183795  *ppSorted = pList;
183796  return SQLITE_OK;
183797 }
183798 
183799 /*
183800 ** Query the hash table for a doclist associated with term pTerm/nTerm.
183801 */
183802 static int sqlite3Fts5HashQuery(
183803  Fts5Hash *pHash, /* Hash table to query */
183804  const char *pTerm, int nTerm, /* Query term */
183805  const u8 **ppDoclist, /* OUT: Pointer to doclist for pTerm */
183806  int *pnDoclist /* OUT: Size of doclist in bytes */
183807 ){
183808  unsigned int iHash = fts5HashKey(pHash->nSlot, (const u8*)pTerm, nTerm);
183809  Fts5HashEntry *p;
183810 
183811  for(p=pHash->aSlot[iHash]; p; p=p->pHashNext){
183812  if( memcmp(p->zKey, pTerm, nTerm)==0 && p->zKey[nTerm]==0 ) break;
183813  }
183814 
183815  if( p ){
183816  fts5HashAddPoslistSize(pHash, p);
183817  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
183818  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
183819  }else{
183820  *ppDoclist = 0;
183821  *pnDoclist = 0;
183822  }
183823 
183824  return SQLITE_OK;
183825 }
183826 
183827 static int sqlite3Fts5HashScanInit(
183828  Fts5Hash *p, /* Hash table to query */
183829  const char *pTerm, int nTerm /* Query prefix */
183830 ){
183831  return fts5HashEntrySort(p, pTerm, nTerm, &p->pScan);
183832 }
183833 
183834 static void sqlite3Fts5HashScanNext(Fts5Hash *p){
183835  assert( !sqlite3Fts5HashScanEof(p) );
183836  p->pScan = p->pScan->pScanNext;
183837 }
183838 
183839 static int sqlite3Fts5HashScanEof(Fts5Hash *p){
183840  return (p->pScan==0);
183841 }
183842 
183843 static void sqlite3Fts5HashScanEntry(
183844  Fts5Hash *pHash,
183845  const char **pzTerm, /* OUT: term (nul-terminated) */
183846  const u8 **ppDoclist, /* OUT: pointer to doclist */
183847  int *pnDoclist /* OUT: size of doclist in bytes */
183848 ){
183849  Fts5HashEntry *p;
183850  if( (p = pHash->pScan) ){
183851  int nTerm = (int)strlen(p->zKey);
183852  fts5HashAddPoslistSize(pHash, p);
183853  *pzTerm = p->zKey;
183854  *ppDoclist = (const u8*)&p->zKey[nTerm+1];
183855  *pnDoclist = p->nData - (FTS5_HASHENTRYSIZE + nTerm + 1);
183856  }else{
183857  *pzTerm = 0;
183858  *ppDoclist = 0;
183859  *pnDoclist = 0;
183860  }
183861 }
183862 
183863 
183864 /*
183865 ** 2014 May 31
183866 **
183867 ** The author disclaims copyright to this source code. In place of
183868 ** a legal notice, here is a blessing:
183869 **
183870 ** May you do good and not evil.
183871 ** May you find forgiveness for yourself and forgive others.
183872 ** May you share freely, never taking more than you give.
183873 **
183874 ******************************************************************************
183875 **
183876 ** Low level access to the FTS index stored in the database file. The
183877 ** routines in this file file implement all read and write access to the
183878 ** %_data table. Other parts of the system access this functionality via
183879 ** the interface defined in fts5Int.h.
183880 */
183881 
183882 
183883 /* #include "fts5Int.h" */
183884 
183885 /*
183886 ** Overview:
183887 **
183888 ** The %_data table contains all the FTS indexes for an FTS5 virtual table.
183889 ** As well as the main term index, there may be up to 31 prefix indexes.
183890 ** The format is similar to FTS3/4, except that:
183891 **
183892 ** * all segment b-tree leaf data is stored in fixed size page records
183893 ** (e.g. 1000 bytes). A single doclist may span multiple pages. Care is
183894 ** taken to ensure it is possible to iterate in either direction through
183895 ** the entries in a doclist, or to seek to a specific entry within a
183896 ** doclist, without loading it into memory.
183897 **
183898 ** * large doclists that span many pages have associated "doclist index"
183899 ** records that contain a copy of the first rowid on each page spanned by
183900 ** the doclist. This is used to speed up seek operations, and merges of
183901 ** large doclists with very small doclists.
183902 **
183903 ** * extra fields in the "structure record" record the state of ongoing
183904 ** incremental merge operations.
183905 **
183906 */
183907 
183908 
183909 #define FTS5_OPT_WORK_UNIT 1000 /* Number of leaf pages per optimize step */
183910 #define FTS5_WORK_UNIT 64 /* Number of leaf pages in unit of work */
183911 
183912 #define FTS5_MIN_DLIDX_SIZE 4 /* Add dlidx if this many empty pages */
183913 
183914 #define FTS5_MAIN_PREFIX '0'
183915 
183916 #if FTS5_MAX_PREFIX_INDEXES > 31
183917 # error "FTS5_MAX_PREFIX_INDEXES is too large"
183918 #endif
183919 
183920 /*
183921 ** Details:
183922 **
183923 ** The %_data table managed by this module,
183924 **
183925 ** CREATE TABLE %_data(id INTEGER PRIMARY KEY, block BLOB);
183926 **
183927 ** , contains the following 5 types of records. See the comments surrounding
183928 ** the FTS5_*_ROWID macros below for a description of how %_data rowids are
183929 ** assigned to each fo them.
183930 **
183931 ** 1. Structure Records:
183932 **
183933 ** The set of segments that make up an index - the index structure - are
183934 ** recorded in a single record within the %_data table. The record consists
183935 ** of a single 32-bit configuration cookie value followed by a list of
183936 ** SQLite varints. If the FTS table features more than one index (because
183937 ** there are one or more prefix indexes), it is guaranteed that all share
183938 ** the same cookie value.
183939 **
183940 ** Immediately following the configuration cookie, the record begins with
183941 ** three varints:
183942 **
183943 ** + number of levels,
183944 ** + total number of segments on all levels,
183945 ** + value of write counter.
183946 **
183947 ** Then, for each level from 0 to nMax:
183948 **
183949 ** + number of input segments in ongoing merge.
183950 ** + total number of segments in level.
183951 ** + for each segment from oldest to newest:
183952 ** + segment id (always > 0)
183953 ** + first leaf page number (often 1, always greater than 0)
183954 ** + final leaf page number
183955 **
183956 ** 2. The Averages Record:
183957 **
183958 ** A single record within the %_data table. The data is a list of varints.
183959 ** The first value is the number of rows in the index. Then, for each column
183960 ** from left to right, the total number of tokens in the column for all
183961 ** rows of the table.
183962 **
183963 ** 3. Segment leaves:
183964 **
183965 ** TERM/DOCLIST FORMAT:
183966 **
183967 ** Most of each segment leaf is taken up by term/doclist data. The
183968 ** general format of term/doclist, starting with the first term
183969 ** on the leaf page, is:
183970 **
183971 ** varint : size of first term
183972 ** blob: first term data
183973 ** doclist: first doclist
183974 ** zero-or-more {
183975 ** varint: number of bytes in common with previous term
183976 ** varint: number of bytes of new term data (nNew)
183977 ** blob: nNew bytes of new term data
183978 ** doclist: next doclist
183979 ** }
183980 **
183981 ** doclist format:
183982 **
183983 ** varint: first rowid
183984 ** poslist: first poslist
183985 ** zero-or-more {
183986 ** varint: rowid delta (always > 0)
183987 ** poslist: next poslist
183988 ** }
183989 **
183990 ** poslist format:
183991 **
183992 ** varint: size of poslist in bytes multiplied by 2, not including
183993 ** this field. Plus 1 if this entry carries the "delete" flag.
183994 ** collist: collist for column 0
183995 ** zero-or-more {
183996 ** 0x01 byte
183997 ** varint: column number (I)
183998 ** collist: collist for column I
183999 ** }
184000 **
184001 ** collist format:
184002 **
184003 ** varint: first offset + 2
184004 ** zero-or-more {
184005 ** varint: offset delta + 2
184006 ** }
184007 **
184008 ** PAGE FORMAT
184009 **
184010 ** Each leaf page begins with a 4-byte header containing 2 16-bit
184011 ** unsigned integer fields in big-endian format. They are:
184012 **
184013 ** * The byte offset of the first rowid on the page, if it exists
184014 ** and occurs before the first term (otherwise 0).
184015 **
184016 ** * The byte offset of the start of the page footer. If the page
184017 ** footer is 0 bytes in size, then this field is the same as the
184018 ** size of the leaf page in bytes.
184019 **
184020 ** The page footer consists of a single varint for each term located
184021 ** on the page. Each varint is the byte offset of the current term
184022 ** within the page, delta-compressed against the previous value. In
184023 ** other words, the first varint in the footer is the byte offset of
184024 ** the first term, the second is the byte offset of the second less that
184025 ** of the first, and so on.
184026 **
184027 ** The term/doclist format described above is accurate if the entire
184028 ** term/doclist data fits on a single leaf page. If this is not the case,
184029 ** the format is changed in two ways:
184030 **
184031 ** + if the first rowid on a page occurs before the first term, it
184032 ** is stored as a literal value:
184033 **
184034 ** varint: first rowid
184035 **
184036 ** + the first term on each page is stored in the same way as the
184037 ** very first term of the segment:
184038 **
184039 ** varint : size of first term
184040 ** blob: first term data
184041 **
184042 ** 5. Segment doclist indexes:
184043 **
184044 ** Doclist indexes are themselves b-trees, however they usually consist of
184045 ** a single leaf record only. The format of each doclist index leaf page
184046 ** is:
184047 **
184048 ** * Flags byte. Bits are:
184049 ** 0x01: Clear if leaf is also the root page, otherwise set.
184050 **
184051 ** * Page number of fts index leaf page. As a varint.
184052 **
184053 ** * First rowid on page indicated by previous field. As a varint.
184054 **
184055 ** * A list of varints, one for each subsequent termless page. A
184056 ** positive delta if the termless page contains at least one rowid,
184057 ** or an 0x00 byte otherwise.
184058 **
184059 ** Internal doclist index nodes are:
184060 **
184061 ** * Flags byte. Bits are:
184062 ** 0x01: Clear for root page, otherwise set.
184063 **
184064 ** * Page number of first child page. As a varint.
184065 **
184066 ** * Copy of first rowid on page indicated by previous field. As a varint.
184067 **
184068 ** * A list of delta-encoded varints - the first rowid on each subsequent
184069 ** child page.
184070 **
184071 */
184072 
184073 /*
184074 ** Rowids for the averages and structure records in the %_data table.
184075 */
184076 #define FTS5_AVERAGES_ROWID 1 /* Rowid used for the averages record */
184077 #define FTS5_STRUCTURE_ROWID 10 /* The structure record */
184078 
184079 /*
184080 ** Macros determining the rowids used by segment leaves and dlidx leaves
184081 ** and nodes. All nodes and leaves are stored in the %_data table with large
184082 ** positive rowids.
184083 **
184084 ** Each segment has a unique non-zero 16-bit id.
184085 **
184086 ** The rowid for each segment leaf is found by passing the segment id and
184087 ** the leaf page number to the FTS5_SEGMENT_ROWID macro. Leaves are numbered
184088 ** sequentially starting from 1.
184089 */
184090 #define FTS5_DATA_ID_B 16 /* Max seg id number 65535 */
184091 #define FTS5_DATA_DLI_B 1 /* Doclist-index flag (1 bit) */
184092 #define FTS5_DATA_HEIGHT_B 5 /* Max dlidx tree height of 32 */
184093 #define FTS5_DATA_PAGE_B 31 /* Max page number of 2147483648 */
184094 
184095 #define fts5_dri(segid, dlidx, height, pgno) ( \
184096  ((i64)(segid) << (FTS5_DATA_PAGE_B+FTS5_DATA_HEIGHT_B+FTS5_DATA_DLI_B)) + \
184097  ((i64)(dlidx) << (FTS5_DATA_PAGE_B + FTS5_DATA_HEIGHT_B)) + \
184098  ((i64)(height) << (FTS5_DATA_PAGE_B)) + \
184099  ((i64)(pgno)) \
184100 )
184101 
184102 #define FTS5_SEGMENT_ROWID(segid, pgno) fts5_dri(segid, 0, 0, pgno)
184103 #define FTS5_DLIDX_ROWID(segid, height, pgno) fts5_dri(segid, 1, height, pgno)
184104 
184105 /*
184106 ** Maximum segments permitted in a single index
184107 */
184108 #define FTS5_MAX_SEGMENT 2000
184109 
184110 #ifdef SQLITE_DEBUG
184111 static int sqlite3Fts5Corrupt() { return SQLITE_CORRUPT_VTAB; }
184112 #endif
184113 
184114 
184115 /*
184116 ** Each time a blob is read from the %_data table, it is padded with this
184117 ** many zero bytes. This makes it easier to decode the various record formats
184118 ** without overreading if the records are corrupt.
184119 */
184120 #define FTS5_DATA_ZERO_PADDING 8
184121 #define FTS5_DATA_PADDING 20
184122 
184123 typedef struct Fts5Data Fts5Data;
184124 typedef struct Fts5DlidxIter Fts5DlidxIter;
184125 typedef struct Fts5DlidxLvl Fts5DlidxLvl;
184126 typedef struct Fts5DlidxWriter Fts5DlidxWriter;
184127 typedef struct Fts5Iter Fts5Iter;
184128 typedef struct Fts5PageWriter Fts5PageWriter;
184129 typedef struct Fts5SegIter Fts5SegIter;
184130 typedef struct Fts5DoclistIter Fts5DoclistIter;
184131 typedef struct Fts5SegWriter Fts5SegWriter;
184132 typedef struct Fts5Structure Fts5Structure;
184133 typedef struct Fts5StructureLevel Fts5StructureLevel;
184134 typedef struct Fts5StructureSegment Fts5StructureSegment;
184135 
184136 struct Fts5Data {
184137  u8 *p; /* Pointer to buffer containing record */
184138  int nn; /* Size of record in bytes */
184139  int szLeaf; /* Size of leaf without page-index */
184140 };
184141 
184142 /*
184143 ** One object per %_data table.
184144 */
184145 struct Fts5Index {
184146  Fts5Config *pConfig; /* Virtual table configuration */
184147  char *zDataTbl; /* Name of %_data table */
184148  int nWorkUnit; /* Leaf pages in a "unit" of work */
184149 
184150  /*
184151  ** Variables related to the accumulation of tokens and doclists within the
184152  ** in-memory hash tables before they are flushed to disk.
184153  */
184154  Fts5Hash *pHash; /* Hash table for in-memory data */
184155  int nPendingData; /* Current bytes of pending data */
184156  i64 iWriteRowid; /* Rowid for current doc being written */
184157  int bDelete; /* Current write is a delete */
184158 
184159  /* Error state. */
184160  int rc; /* Current error code */
184161 
184162  /* State used by the fts5DataXXX() functions. */
184163  sqlite3_blob *pReader; /* RO incr-blob open on %_data table */
184164  sqlite3_stmt *pWriter; /* "INSERT ... %_data VALUES(?,?)" */
184165  sqlite3_stmt *pDeleter; /* "DELETE FROM %_data ... id>=? AND id<=?" */
184166  sqlite3_stmt *pIdxWriter; /* "INSERT ... %_idx VALUES(?,?,?,?)" */
184167  sqlite3_stmt *pIdxDeleter; /* "DELETE FROM %_idx WHERE segid=? */
184168  sqlite3_stmt *pIdxSelect;
184169  int nRead; /* Total number of blocks read */
184170 
184171  sqlite3_stmt *pDataVersion;
184172  i64 iStructVersion; /* data_version when pStruct read */
184173  Fts5Structure *pStruct; /* Current db structure (or NULL) */
184174 };
184175 
184176 struct Fts5DoclistIter {
184177  u8 *aEof; /* Pointer to 1 byte past end of doclist */
184178 
184179  /* Output variables. aPoslist==0 at EOF */
184180  i64 iRowid;
184181  u8 *aPoslist;
184182  int nPoslist;
184183  int nSize;
184184 };
184185 
184186 /*
184187 ** The contents of the "structure" record for each index are represented
184188 ** using an Fts5Structure record in memory. Which uses instances of the
184189 ** other Fts5StructureXXX types as components.
184190 */
184191 struct Fts5StructureSegment {
184192  int iSegid; /* Segment id */
184193  int pgnoFirst; /* First leaf page number in segment */
184194  int pgnoLast; /* Last leaf page number in segment */
184195 };
184196 struct Fts5StructureLevel {
184197  int nMerge; /* Number of segments in incr-merge */
184198  int nSeg; /* Total number of segments on level */
184199  Fts5StructureSegment *aSeg; /* Array of segments. aSeg[0] is oldest. */
184200 };
184201 struct Fts5Structure {
184202  int nRef; /* Object reference count */
184203  u64 nWriteCounter; /* Total leaves written to level 0 */
184204  int nSegment; /* Total segments in this structure */
184205  int nLevel; /* Number of levels in this index */
184206  Fts5StructureLevel aLevel[1]; /* Array of nLevel level objects */
184207 };
184208 
184209 /*
184210 ** An object of type Fts5SegWriter is used to write to segments.
184211 */
184212 struct Fts5PageWriter {
184213  int pgno; /* Page number for this page */
184214  int iPrevPgidx; /* Previous value written into pgidx */
184215  Fts5Buffer buf; /* Buffer containing leaf data */
184216  Fts5Buffer pgidx; /* Buffer containing page-index */
184217  Fts5Buffer term; /* Buffer containing previous term on page */
184218 };
184219 struct Fts5DlidxWriter {
184220  int pgno; /* Page number for this page */
184221  int bPrevValid; /* True if iPrev is valid */
184222  i64 iPrev; /* Previous rowid value written to page */
184223  Fts5Buffer buf; /* Buffer containing page data */
184224 };
184225 struct Fts5SegWriter {
184226  int iSegid; /* Segid to write to */
184227  Fts5PageWriter writer; /* PageWriter object */
184228  i64 iPrevRowid; /* Previous rowid written to current leaf */
184229  u8 bFirstRowidInDoclist; /* True if next rowid is first in doclist */
184230  u8 bFirstRowidInPage; /* True if next rowid is first in page */
184231  /* TODO1: Can use (writer.pgidx.n==0) instead of bFirstTermInPage */
184232  u8 bFirstTermInPage; /* True if next term will be first in leaf */
184233  int nLeafWritten; /* Number of leaf pages written */
184234  int nEmpty; /* Number of contiguous term-less nodes */
184235 
184236  int nDlidx; /* Allocated size of aDlidx[] array */
184237  Fts5DlidxWriter *aDlidx; /* Array of Fts5DlidxWriter objects */
184238 
184239  /* Values to insert into the %_idx table */
184240  Fts5Buffer btterm; /* Next term to insert into %_idx table */
184241  int iBtPage; /* Page number corresponding to btterm */
184242 };
184243 
184244 typedef struct Fts5CResult Fts5CResult;
184245 struct Fts5CResult {
184246  u16 iFirst; /* aSeg[] index of firstest iterator */
184247  u8 bTermEq; /* True if the terms are equal */
184248 };
184249 
184250 /*
184251 ** Object for iterating through a single segment, visiting each term/rowid
184252 ** pair in the segment.
184253 **
184254 ** pSeg:
184255 ** The segment to iterate through.
184256 **
184257 ** iLeafPgno:
184258 ** Current leaf page number within segment.
184259 **
184260 ** iLeafOffset:
184261 ** Byte offset within the current leaf that is the first byte of the
184262 ** position list data (one byte passed the position-list size field).
184263 ** rowid field of the current entry. Usually this is the size field of the
184264 ** position list data. The exception is if the rowid for the current entry
184265 ** is the last thing on the leaf page.
184266 **
184267 ** pLeaf:
184268 ** Buffer containing current leaf page data. Set to NULL at EOF.
184269 **
184270 ** iTermLeafPgno, iTermLeafOffset:
184271 ** Leaf page number containing the last term read from the segment. And
184272 ** the offset immediately following the term data.
184273 **
184274 ** flags:
184275 ** Mask of FTS5_SEGITER_XXX values. Interpreted as follows:
184276 **
184277 ** FTS5_SEGITER_ONETERM:
184278 ** If set, set the iterator to point to EOF after the current doclist
184279 ** has been exhausted. Do not proceed to the next term in the segment.
184280 **
184281 ** FTS5_SEGITER_REVERSE:
184282 ** This flag is only ever set if FTS5_SEGITER_ONETERM is also set. If
184283 ** it is set, iterate through rowid in descending order instead of the
184284 ** default ascending order.
184285 **
184286 ** iRowidOffset/nRowidOffset/aRowidOffset:
184287 ** These are used if the FTS5_SEGITER_REVERSE flag is set.
184288 **
184289 ** For each rowid on the page corresponding to the current term, the
184290 ** corresponding aRowidOffset[] entry is set to the byte offset of the
184291 ** start of the "position-list-size" field within the page.
184292 **
184293 ** iTermIdx:
184294 ** Index of current term on iTermLeafPgno.
184295 */
184296 struct Fts5SegIter {
184297  Fts5StructureSegment *pSeg; /* Segment to iterate through */
184298  int flags; /* Mask of configuration flags */
184299  int iLeafPgno; /* Current leaf page number */
184300  Fts5Data *pLeaf; /* Current leaf data */
184301  Fts5Data *pNextLeaf; /* Leaf page (iLeafPgno+1) */
184302  int iLeafOffset; /* Byte offset within current leaf */
184303 
184304  /* Next method */
184305  void (*xNext)(Fts5Index*, Fts5SegIter*, int*);
184306 
184307  /* The page and offset from which the current term was read. The offset
184308  ** is the offset of the first rowid in the current doclist. */
184309  int iTermLeafPgno;
184310  int iTermLeafOffset;
184311 
184312  int iPgidxOff; /* Next offset in pgidx */
184313  int iEndofDoclist;
184314 
184315  /* The following are only used if the FTS5_SEGITER_REVERSE flag is set. */
184316  int iRowidOffset; /* Current entry in aRowidOffset[] */
184317  int nRowidOffset; /* Allocated size of aRowidOffset[] array */
184318  int *aRowidOffset; /* Array of offset to rowid fields */
184319 
184320  Fts5DlidxIter *pDlidx; /* If there is a doclist-index */
184321 
184322  /* Variables populated based on current entry. */
184323  Fts5Buffer term; /* Current term */
184324  i64 iRowid; /* Current rowid */
184325  int nPos; /* Number of bytes in current position list */
184326  u8 bDel; /* True if the delete flag is set */
184327 };
184328 
184329 /*
184330 ** Argument is a pointer to an Fts5Data structure that contains a
184331 ** leaf page.
184332 */
184333 #define ASSERT_SZLEAF_OK(x) assert( \
184334  (x)->szLeaf==(x)->nn || (x)->szLeaf==fts5GetU16(&(x)->p[2]) \
184335 )
184336 
184337 #define FTS5_SEGITER_ONETERM 0x01
184338 #define FTS5_SEGITER_REVERSE 0x02
184339 
184340 /*
184341 ** Argument is a pointer to an Fts5Data structure that contains a leaf
184342 ** page. This macro evaluates to true if the leaf contains no terms, or
184343 ** false if it contains at least one term.
184344 */
184345 #define fts5LeafIsTermless(x) ((x)->szLeaf >= (x)->nn)
184346 
184347 #define fts5LeafTermOff(x, i) (fts5GetU16(&(x)->p[(x)->szLeaf + (i)*2]))
184348 
184349 #define fts5LeafFirstRowidOff(x) (fts5GetU16((x)->p))
184350 
184351 /*
184352 ** Object for iterating through the merged results of one or more segments,
184353 ** visiting each term/rowid pair in the merged data.
184354 **
184355 ** nSeg is always a power of two greater than or equal to the number of
184356 ** segments that this object is merging data from. Both the aSeg[] and
184357 ** aFirst[] arrays are sized at nSeg entries. The aSeg[] array is padded
184358 ** with zeroed objects - these are handled as if they were iterators opened
184359 ** on empty segments.
184360 **
184361 ** The results of comparing segments aSeg[N] and aSeg[N+1], where N is an
184362 ** even number, is stored in aFirst[(nSeg+N)/2]. The "result" of the
184363 ** comparison in this context is the index of the iterator that currently
184364 ** points to the smaller term/rowid combination. Iterators at EOF are
184365 ** considered to be greater than all other iterators.
184366 **
184367 ** aFirst[1] contains the index in aSeg[] of the iterator that points to
184368 ** the smallest key overall. aFirst[0] is unused.
184369 **
184370 ** poslist:
184371 ** Used by sqlite3Fts5IterPoslist() when the poslist needs to be buffered.
184372 ** There is no way to tell if this is populated or not.
184373 */
184374 struct Fts5Iter {
184375  Fts5IndexIter base; /* Base class containing output vars */
184376 
184377  Fts5Index *pIndex; /* Index that owns this iterator */
184378  Fts5Structure *pStruct; /* Database structure for this iterator */
184379  Fts5Buffer poslist; /* Buffer containing current poslist */
184380  Fts5Colset *pColset; /* Restrict matches to these columns */
184381 
184382  /* Invoked to set output variables. */
184383  void (*xSetOutputs)(Fts5Iter*, Fts5SegIter*);
184384 
184385  int nSeg; /* Size of aSeg[] array */
184386  int bRev; /* True to iterate in reverse order */
184387  u8 bSkipEmpty; /* True to skip deleted entries */
184388 
184389  i64 iSwitchRowid; /* Firstest rowid of other than aFirst[1] */
184390  Fts5CResult *aFirst; /* Current merge state (see above) */
184391  Fts5SegIter aSeg[1]; /* Array of segment iterators */
184392 };
184393 
184394 
184395 /*
184396 ** An instance of the following type is used to iterate through the contents
184397 ** of a doclist-index record.
184398 **
184399 ** pData:
184400 ** Record containing the doclist-index data.
184401 **
184402 ** bEof:
184403 ** Set to true once iterator has reached EOF.
184404 **
184405 ** iOff:
184406 ** Set to the current offset within record pData.
184407 */
184408 struct Fts5DlidxLvl {
184409  Fts5Data *pData; /* Data for current page of this level */
184410  int iOff; /* Current offset into pData */
184411  int bEof; /* At EOF already */
184412  int iFirstOff; /* Used by reverse iterators */
184413 
184414  /* Output variables */
184415  int iLeafPgno; /* Page number of current leaf page */
184416  i64 iRowid; /* First rowid on leaf iLeafPgno */
184417 };
184418 struct Fts5DlidxIter {
184419  int nLvl;
184420  int iSegid;
184421  Fts5DlidxLvl aLvl[1];
184422 };
184423 
184424 static void fts5PutU16(u8 *aOut, u16 iVal){
184425  aOut[0] = (iVal>>8);
184426  aOut[1] = (iVal&0xFF);
184427 }
184428 
184429 static u16 fts5GetU16(const u8 *aIn){
184430  return ((u16)aIn[0] << 8) + aIn[1];
184431 }
184432 
184433 /*
184434 ** Allocate and return a buffer at least nByte bytes in size.
184435 **
184436 ** If an OOM error is encountered, return NULL and set the error code in
184437 ** the Fts5Index handle passed as the first argument.
184438 */
184439 static void *fts5IdxMalloc(Fts5Index *p, int nByte){
184440  return sqlite3Fts5MallocZero(&p->rc, nByte);
184441 }
184442 
184443 /*
184444 ** Compare the contents of the pLeft buffer with the pRight/nRight blob.
184445 **
184446 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
184447 ** +ve if pRight is smaller than pLeft. In other words:
184448 **
184449 ** res = *pLeft - *pRight
184450 */
184451 #ifdef SQLITE_DEBUG
184452 static int fts5BufferCompareBlob(
184453  Fts5Buffer *pLeft, /* Left hand side of comparison */
184454  const u8 *pRight, int nRight /* Right hand side of comparison */
184455 ){
184456  int nCmp = MIN(pLeft->n, nRight);
184457  int res = memcmp(pLeft->p, pRight, nCmp);
184458  return (res==0 ? (pLeft->n - nRight) : res);
184459 }
184460 #endif
184461 
184462 /*
184463 ** Compare the contents of the two buffers using memcmp(). If one buffer
184464 ** is a prefix of the other, it is considered the lesser.
184465 **
184466 ** Return -ve if pLeft is smaller than pRight, 0 if they are equal or
184467 ** +ve if pRight is smaller than pLeft. In other words:
184468 **
184469 ** res = *pLeft - *pRight
184470 */
184471 static int fts5BufferCompare(Fts5Buffer *pLeft, Fts5Buffer *pRight){
184472  int nCmp = MIN(pLeft->n, pRight->n);
184473  int res = memcmp(pLeft->p, pRight->p, nCmp);
184474  return (res==0 ? (pLeft->n - pRight->n) : res);
184475 }
184476 
184477 static int fts5LeafFirstTermOff(Fts5Data *pLeaf){
184478  int ret;
184479  fts5GetVarint32(&pLeaf->p[pLeaf->szLeaf], ret);
184480  return ret;
184481 }
184482 
184483 /*
184484 ** Close the read-only blob handle, if it is open.
184485 */
184486 static void fts5CloseReader(Fts5Index *p){
184487  if( p->pReader ){
184488  sqlite3_blob *pReader = p->pReader;
184489  p->pReader = 0;
184490  sqlite3_blob_close(pReader);
184491  }
184492 }
184493 
184494 
184495 /*
184496 ** Retrieve a record from the %_data table.
184497 **
184498 ** If an error occurs, NULL is returned and an error left in the
184499 ** Fts5Index object.
184500 */
184501 static Fts5Data *fts5DataRead(Fts5Index *p, i64 iRowid){
184502  Fts5Data *pRet = 0;
184503  if( p->rc==SQLITE_OK ){
184504  int rc = SQLITE_OK;
184505 
184506  if( p->pReader ){
184507  /* This call may return SQLITE_ABORT if there has been a savepoint
184508  ** rollback since it was last used. In this case a new blob handle
184509  ** is required. */
184510  sqlite3_blob *pBlob = p->pReader;
184511  p->pReader = 0;
184512  rc = sqlite3_blob_reopen(pBlob, iRowid);
184513  assert( p->pReader==0 );
184514  p->pReader = pBlob;
184515  if( rc!=SQLITE_OK ){
184516  fts5CloseReader(p);
184517  }
184518  if( rc==SQLITE_ABORT ) rc = SQLITE_OK;
184519  }
184520 
184521  /* If the blob handle is not open at this point, open it and seek
184522  ** to the requested entry. */
184523  if( p->pReader==0 && rc==SQLITE_OK ){
184524  Fts5Config *pConfig = p->pConfig;
184525  rc = sqlite3_blob_open(pConfig->db,
184526  pConfig->zDb, p->zDataTbl, "block", iRowid, 0, &p->pReader
184527  );
184528  }
184529 
184530  /* If either of the sqlite3_blob_open() or sqlite3_blob_reopen() calls
184531  ** above returned SQLITE_ERROR, return SQLITE_CORRUPT_VTAB instead.
184532  ** All the reasons those functions might return SQLITE_ERROR - missing
184533  ** table, missing row, non-blob/text in block column - indicate
184534  ** backing store corruption. */
184535  if( rc==SQLITE_ERROR ) rc = FTS5_CORRUPT;
184536 
184537  if( rc==SQLITE_OK ){
184538  u8 *aOut = 0; /* Read blob data into this buffer */
184539  int nByte = sqlite3_blob_bytes(p->pReader);
184540  int nAlloc = sizeof(Fts5Data) + nByte + FTS5_DATA_PADDING;
184541  pRet = (Fts5Data*)sqlite3_malloc(nAlloc);
184542  if( pRet ){
184543  pRet->nn = nByte;
184544  aOut = pRet->p = (u8*)&pRet[1];
184545  }else{
184546  rc = SQLITE_NOMEM;
184547  }
184548 
184549  if( rc==SQLITE_OK ){
184550  rc = sqlite3_blob_read(p->pReader, aOut, nByte, 0);
184551  }
184552  if( rc!=SQLITE_OK ){
184553  sqlite3_free(pRet);
184554  pRet = 0;
184555  }else{
184556  /* TODO1: Fix this */
184557  pRet->szLeaf = fts5GetU16(&pRet->p[2]);
184558  }
184559  }
184560  p->rc = rc;
184561  p->nRead++;
184562  }
184563 
184564  assert( (pRet==0)==(p->rc!=SQLITE_OK) );
184565  return pRet;
184566 }
184567 
184568 
184569 /*
184570 ** Release a reference to data record returned by an earlier call to
184571 ** fts5DataRead().
184572 */
184573 static void fts5DataRelease(Fts5Data *pData){
184574  sqlite3_free(pData);
184575 }
184576 
184577 static int fts5IndexPrepareStmt(
184578  Fts5Index *p,
184579  sqlite3_stmt **ppStmt,
184580  char *zSql
184581 ){
184582  if( p->rc==SQLITE_OK ){
184583  if( zSql ){
184584  p->rc = sqlite3_prepare_v2(p->pConfig->db, zSql, -1, ppStmt, 0);
184585  }else{
184586  p->rc = SQLITE_NOMEM;
184587  }
184588  }
184589  sqlite3_free(zSql);
184590  return p->rc;
184591 }
184592 
184593 
184594 /*
184595 ** INSERT OR REPLACE a record into the %_data table.
184596 */
184597 static void fts5DataWrite(Fts5Index *p, i64 iRowid, const u8 *pData, int nData){
184598  if( p->rc!=SQLITE_OK ) return;
184599 
184600  if( p->pWriter==0 ){
184601  Fts5Config *pConfig = p->pConfig;
184602  fts5IndexPrepareStmt(p, &p->pWriter, sqlite3_mprintf(
184603  "REPLACE INTO '%q'.'%q_data'(id, block) VALUES(?,?)",
184604  pConfig->zDb, pConfig->zName
184605  ));
184606  if( p->rc ) return;
184607  }
184608 
184609  sqlite3_bind_int64(p->pWriter, 1, iRowid);
184610  sqlite3_bind_blob(p->pWriter, 2, pData, nData, SQLITE_STATIC);
184611  sqlite3_step(p->pWriter);
184612  p->rc = sqlite3_reset(p->pWriter);
184613 }
184614 
184615 /*
184616 ** Execute the following SQL:
184617 **
184618 ** DELETE FROM %_data WHERE id BETWEEN $iFirst AND $iLast
184619 */
184620 static void fts5DataDelete(Fts5Index *p, i64 iFirst, i64 iLast){
184621  if( p->rc!=SQLITE_OK ) return;
184622 
184623  if( p->pDeleter==0 ){
184624  int rc;
184625  Fts5Config *pConfig = p->pConfig;
184626  char *zSql = sqlite3_mprintf(
184627  "DELETE FROM '%q'.'%q_data' WHERE id>=? AND id<=?",
184628  pConfig->zDb, pConfig->zName
184629  );
184630  if( zSql==0 ){
184631  rc = SQLITE_NOMEM;
184632  }else{
184633  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &p->pDeleter, 0);
184634  sqlite3_free(zSql);
184635  }
184636  if( rc!=SQLITE_OK ){
184637  p->rc = rc;
184638  return;
184639  }
184640  }
184641 
184642  sqlite3_bind_int64(p->pDeleter, 1, iFirst);
184643  sqlite3_bind_int64(p->pDeleter, 2, iLast);
184644  sqlite3_step(p->pDeleter);
184645  p->rc = sqlite3_reset(p->pDeleter);
184646 }
184647 
184648 /*
184649 ** Remove all records associated with segment iSegid.
184650 */
184651 static void fts5DataRemoveSegment(Fts5Index *p, int iSegid){
184652  i64 iFirst = FTS5_SEGMENT_ROWID(iSegid, 0);
184653  i64 iLast = FTS5_SEGMENT_ROWID(iSegid+1, 0)-1;
184654  fts5DataDelete(p, iFirst, iLast);
184655  if( p->pIdxDeleter==0 ){
184656  Fts5Config *pConfig = p->pConfig;
184657  fts5IndexPrepareStmt(p, &p->pIdxDeleter, sqlite3_mprintf(
184658  "DELETE FROM '%q'.'%q_idx' WHERE segid=?",
184659  pConfig->zDb, pConfig->zName
184660  ));
184661  }
184662  if( p->rc==SQLITE_OK ){
184663  sqlite3_bind_int(p->pIdxDeleter, 1, iSegid);
184664  sqlite3_step(p->pIdxDeleter);
184665  p->rc = sqlite3_reset(p->pIdxDeleter);
184666  }
184667 }
184668 
184669 /*
184670 ** Release a reference to an Fts5Structure object returned by an earlier
184671 ** call to fts5StructureRead() or fts5StructureDecode().
184672 */
184673 static void fts5StructureRelease(Fts5Structure *pStruct){
184674  if( pStruct && 0>=(--pStruct->nRef) ){
184675  int i;
184676  assert( pStruct->nRef==0 );
184677  for(i=0; i<pStruct->nLevel; i++){
184678  sqlite3_free(pStruct->aLevel[i].aSeg);
184679  }
184680  sqlite3_free(pStruct);
184681  }
184682 }
184683 
184684 static void fts5StructureRef(Fts5Structure *pStruct){
184685  pStruct->nRef++;
184686 }
184687 
184688 /*
184689 ** Deserialize and return the structure record currently stored in serialized
184690 ** form within buffer pData/nData.
184691 **
184692 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
184693 ** are over-allocated by one slot. This allows the structure contents
184694 ** to be more easily edited.
184695 **
184696 ** If an error occurs, *ppOut is set to NULL and an SQLite error code
184697 ** returned. Otherwise, *ppOut is set to point to the new object and
184698 ** SQLITE_OK returned.
184699 */
184700 static int fts5StructureDecode(
184701  const u8 *pData, /* Buffer containing serialized structure */
184702  int nData, /* Size of buffer pData in bytes */
184703  int *piCookie, /* Configuration cookie value */
184704  Fts5Structure **ppOut /* OUT: Deserialized object */
184705 ){
184706  int rc = SQLITE_OK;
184707  int i = 0;
184708  int iLvl;
184709  int nLevel = 0;
184710  int nSegment = 0;
184711  int nByte; /* Bytes of space to allocate at pRet */
184712  Fts5Structure *pRet = 0; /* Structure object to return */
184713 
184714  /* Grab the cookie value */
184715  if( piCookie ) *piCookie = sqlite3Fts5Get32(pData);
184716  i = 4;
184717 
184718  /* Read the total number of levels and segments from the start of the
184719  ** structure record. */
184720  i += fts5GetVarint32(&pData[i], nLevel);
184721  i += fts5GetVarint32(&pData[i], nSegment);
184722  nByte = (
184723  sizeof(Fts5Structure) + /* Main structure */
184724  sizeof(Fts5StructureLevel) * (nLevel-1) /* aLevel[] array */
184725  );
184726  pRet = (Fts5Structure*)sqlite3Fts5MallocZero(&rc, nByte);
184727 
184728  if( pRet ){
184729  pRet->nRef = 1;
184730  pRet->nLevel = nLevel;
184731  pRet->nSegment = nSegment;
184732  i += sqlite3Fts5GetVarint(&pData[i], &pRet->nWriteCounter);
184733 
184734  for(iLvl=0; rc==SQLITE_OK && iLvl<nLevel; iLvl++){
184735  Fts5StructureLevel *pLvl = &pRet->aLevel[iLvl];
184736  int nTotal = 0;
184737  int iSeg;
184738 
184739  if( i>=nData ){
184740  rc = FTS5_CORRUPT;
184741  }else{
184742  i += fts5GetVarint32(&pData[i], pLvl->nMerge);
184743  i += fts5GetVarint32(&pData[i], nTotal);
184744  assert( nTotal>=pLvl->nMerge );
184745  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&rc,
184746  nTotal * sizeof(Fts5StructureSegment)
184747  );
184748  }
184749 
184750  if( rc==SQLITE_OK ){
184751  pLvl->nSeg = nTotal;
184752  for(iSeg=0; iSeg<nTotal; iSeg++){
184753  if( i>=nData ){
184754  rc = FTS5_CORRUPT;
184755  break;
184756  }
184757  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].iSegid);
184758  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoFirst);
184759  i += fts5GetVarint32(&pData[i], pLvl->aSeg[iSeg].pgnoLast);
184760  }
184761  }
184762  }
184763  if( rc!=SQLITE_OK ){
184764  fts5StructureRelease(pRet);
184765  pRet = 0;
184766  }
184767  }
184768 
184769  *ppOut = pRet;
184770  return rc;
184771 }
184772 
184773 /*
184774 **
184775 */
184776 static void fts5StructureAddLevel(int *pRc, Fts5Structure **ppStruct){
184777  if( *pRc==SQLITE_OK ){
184778  Fts5Structure *pStruct = *ppStruct;
184779  int nLevel = pStruct->nLevel;
184780  int nByte = (
184781  sizeof(Fts5Structure) + /* Main structure */
184782  sizeof(Fts5StructureLevel) * (nLevel+1) /* aLevel[] array */
184783  );
184784 
184785  pStruct = sqlite3_realloc(pStruct, nByte);
184786  if( pStruct ){
184787  memset(&pStruct->aLevel[nLevel], 0, sizeof(Fts5StructureLevel));
184788  pStruct->nLevel++;
184789  *ppStruct = pStruct;
184790  }else{
184791  *pRc = SQLITE_NOMEM;
184792  }
184793  }
184794 }
184795 
184796 /*
184797 ** Extend level iLvl so that there is room for at least nExtra more
184798 ** segments.
184799 */
184800 static void fts5StructureExtendLevel(
184801  int *pRc,
184802  Fts5Structure *pStruct,
184803  int iLvl,
184804  int nExtra,
184805  int bInsert
184806 ){
184807  if( *pRc==SQLITE_OK ){
184808  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
184809  Fts5StructureSegment *aNew;
184810  int nByte;
184811 
184812  nByte = (pLvl->nSeg + nExtra) * sizeof(Fts5StructureSegment);
184813  aNew = sqlite3_realloc(pLvl->aSeg, nByte);
184814  if( aNew ){
184815  if( bInsert==0 ){
184816  memset(&aNew[pLvl->nSeg], 0, sizeof(Fts5StructureSegment) * nExtra);
184817  }else{
184818  int nMove = pLvl->nSeg * sizeof(Fts5StructureSegment);
184819  memmove(&aNew[nExtra], aNew, nMove);
184820  memset(aNew, 0, sizeof(Fts5StructureSegment) * nExtra);
184821  }
184822  pLvl->aSeg = aNew;
184823  }else{
184824  *pRc = SQLITE_NOMEM;
184825  }
184826  }
184827 }
184828 
184829 static Fts5Structure *fts5StructureReadUncached(Fts5Index *p){
184830  Fts5Structure *pRet = 0;
184831  Fts5Config *pConfig = p->pConfig;
184832  int iCookie; /* Configuration cookie */
184833  Fts5Data *pData;
184834 
184835  pData = fts5DataRead(p, FTS5_STRUCTURE_ROWID);
184836  if( p->rc==SQLITE_OK ){
184837  /* TODO: Do we need this if the leaf-index is appended? Probably... */
184838  memset(&pData->p[pData->nn], 0, FTS5_DATA_PADDING);
184839  p->rc = fts5StructureDecode(pData->p, pData->nn, &iCookie, &pRet);
184840  if( p->rc==SQLITE_OK && pConfig->iCookie!=iCookie ){
184841  p->rc = sqlite3Fts5ConfigLoad(pConfig, iCookie);
184842  }
184843  fts5DataRelease(pData);
184844  if( p->rc!=SQLITE_OK ){
184845  fts5StructureRelease(pRet);
184846  pRet = 0;
184847  }
184848  }
184849 
184850  return pRet;
184851 }
184852 
184853 static i64 fts5IndexDataVersion(Fts5Index *p){
184854  i64 iVersion = 0;
184855 
184856  if( p->rc==SQLITE_OK ){
184857  if( p->pDataVersion==0 ){
184858  p->rc = fts5IndexPrepareStmt(p, &p->pDataVersion,
184859  sqlite3_mprintf("PRAGMA %Q.data_version", p->pConfig->zDb)
184860  );
184861  if( p->rc ) return 0;
184862  }
184863 
184864  if( SQLITE_ROW==sqlite3_step(p->pDataVersion) ){
184865  iVersion = sqlite3_column_int64(p->pDataVersion, 0);
184866  }
184867  p->rc = sqlite3_reset(p->pDataVersion);
184868  }
184869 
184870  return iVersion;
184871 }
184872 
184873 /*
184874 ** Read, deserialize and return the structure record.
184875 **
184876 ** The Fts5Structure.aLevel[] and each Fts5StructureLevel.aSeg[] array
184877 ** are over-allocated as described for function fts5StructureDecode()
184878 ** above.
184879 **
184880 ** If an error occurs, NULL is returned and an error code left in the
184881 ** Fts5Index handle. If an error has already occurred when this function
184882 ** is called, it is a no-op.
184883 */
184884 static Fts5Structure *fts5StructureRead(Fts5Index *p){
184885 
184886  if( p->pStruct==0 ){
184887  p->iStructVersion = fts5IndexDataVersion(p);
184888  if( p->rc==SQLITE_OK ){
184889  p->pStruct = fts5StructureReadUncached(p);
184890  }
184891  }
184892 
184893 #if 0
184894  else{
184895  Fts5Structure *pTest = fts5StructureReadUncached(p);
184896  if( pTest ){
184897  int i, j;
184898  assert_nc( p->pStruct->nSegment==pTest->nSegment );
184899  assert_nc( p->pStruct->nLevel==pTest->nLevel );
184900  for(i=0; i<pTest->nLevel; i++){
184901  assert_nc( p->pStruct->aLevel[i].nMerge==pTest->aLevel[i].nMerge );
184902  assert_nc( p->pStruct->aLevel[i].nSeg==pTest->aLevel[i].nSeg );
184903  for(j=0; j<pTest->aLevel[i].nSeg; j++){
184904  Fts5StructureSegment *p1 = &pTest->aLevel[i].aSeg[j];
184905  Fts5StructureSegment *p2 = &p->pStruct->aLevel[i].aSeg[j];
184906  assert_nc( p1->iSegid==p2->iSegid );
184907  assert_nc( p1->pgnoFirst==p2->pgnoFirst );
184908  assert_nc( p1->pgnoLast==p2->pgnoLast );
184909  }
184910  }
184911  fts5StructureRelease(pTest);
184912  }
184913  }
184914 #endif
184915 
184916  if( p->rc!=SQLITE_OK ) return 0;
184917  assert( p->iStructVersion!=0 );
184918  assert( p->pStruct!=0 );
184919  fts5StructureRef(p->pStruct);
184920  return p->pStruct;
184921 }
184922 
184923 static void fts5StructureInvalidate(Fts5Index *p){
184924  if( p->pStruct ){
184925  fts5StructureRelease(p->pStruct);
184926  p->pStruct = 0;
184927  }
184928 }
184929 
184930 /*
184931 ** Return the total number of segments in index structure pStruct. This
184932 ** function is only ever used as part of assert() conditions.
184933 */
184934 #ifdef SQLITE_DEBUG
184935 static int fts5StructureCountSegments(Fts5Structure *pStruct){
184936  int nSegment = 0; /* Total number of segments */
184937  if( pStruct ){
184938  int iLvl; /* Used to iterate through levels */
184939  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
184940  nSegment += pStruct->aLevel[iLvl].nSeg;
184941  }
184942  }
184943 
184944  return nSegment;
184945 }
184946 #endif
184947 
184948 #define fts5BufferSafeAppendBlob(pBuf, pBlob, nBlob) { \
184949  assert( (pBuf)->nSpace>=((pBuf)->n+nBlob) ); \
184950  memcpy(&(pBuf)->p[(pBuf)->n], pBlob, nBlob); \
184951  (pBuf)->n += nBlob; \
184952 }
184953 
184954 #define fts5BufferSafeAppendVarint(pBuf, iVal) { \
184955  (pBuf)->n += sqlite3Fts5PutVarint(&(pBuf)->p[(pBuf)->n], (iVal)); \
184956  assert( (pBuf)->nSpace>=(pBuf)->n ); \
184957 }
184958 
184959 
184960 /*
184961 ** Serialize and store the "structure" record.
184962 **
184963 ** If an error occurs, leave an error code in the Fts5Index object. If an
184964 ** error has already occurred, this function is a no-op.
184965 */
184966 static void fts5StructureWrite(Fts5Index *p, Fts5Structure *pStruct){
184967  if( p->rc==SQLITE_OK ){
184968  Fts5Buffer buf; /* Buffer to serialize record into */
184969  int iLvl; /* Used to iterate through levels */
184970  int iCookie; /* Cookie value to store */
184971 
184972  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
184973  memset(&buf, 0, sizeof(Fts5Buffer));
184974 
184975  /* Append the current configuration cookie */
184976  iCookie = p->pConfig->iCookie;
184977  if( iCookie<0 ) iCookie = 0;
184978 
184979  if( 0==sqlite3Fts5BufferSize(&p->rc, &buf, 4+9+9+9) ){
184980  sqlite3Fts5Put32(buf.p, iCookie);
184981  buf.n = 4;
184982  fts5BufferSafeAppendVarint(&buf, pStruct->nLevel);
184983  fts5BufferSafeAppendVarint(&buf, pStruct->nSegment);
184984  fts5BufferSafeAppendVarint(&buf, (i64)pStruct->nWriteCounter);
184985  }
184986 
184987  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
184988  int iSeg; /* Used to iterate through segments */
184989  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
184990  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nMerge);
184991  fts5BufferAppendVarint(&p->rc, &buf, pLvl->nSeg);
184992  assert( pLvl->nMerge<=pLvl->nSeg );
184993 
184994  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
184995  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].iSegid);
184996  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoFirst);
184997  fts5BufferAppendVarint(&p->rc, &buf, pLvl->aSeg[iSeg].pgnoLast);
184998  }
184999  }
185000 
185001  fts5DataWrite(p, FTS5_STRUCTURE_ROWID, buf.p, buf.n);
185002  fts5BufferFree(&buf);
185003  }
185004 }
185005 
185006 #if 0
185007 static void fts5DebugStructure(int*,Fts5Buffer*,Fts5Structure*);
185008 static void fts5PrintStructure(const char *zCaption, Fts5Structure *pStruct){
185009  int rc = SQLITE_OK;
185010  Fts5Buffer buf;
185011  memset(&buf, 0, sizeof(buf));
185012  fts5DebugStructure(&rc, &buf, pStruct);
185013  fprintf(stdout, "%s: %s\n", zCaption, buf.p);
185014  fflush(stdout);
185015  fts5BufferFree(&buf);
185016 }
185017 #else
185018 # define fts5PrintStructure(x,y)
185019 #endif
185020 
185021 static int fts5SegmentSize(Fts5StructureSegment *pSeg){
185022  return 1 + pSeg->pgnoLast - pSeg->pgnoFirst;
185023 }
185024 
185025 /*
185026 ** Return a copy of index structure pStruct. Except, promote as many
185027 ** segments as possible to level iPromote. If an OOM occurs, NULL is
185028 ** returned.
185029 */
185030 static void fts5StructurePromoteTo(
185031  Fts5Index *p,
185032  int iPromote,
185033  int szPromote,
185034  Fts5Structure *pStruct
185035 ){
185036  int il, is;
185037  Fts5StructureLevel *pOut = &pStruct->aLevel[iPromote];
185038 
185039  if( pOut->nMerge==0 ){
185040  for(il=iPromote+1; il<pStruct->nLevel; il++){
185041  Fts5StructureLevel *pLvl = &pStruct->aLevel[il];
185042  if( pLvl->nMerge ) return;
185043  for(is=pLvl->nSeg-1; is>=0; is--){
185044  int sz = fts5SegmentSize(&pLvl->aSeg[is]);
185045  if( sz>szPromote ) return;
185046  fts5StructureExtendLevel(&p->rc, pStruct, iPromote, 1, 1);
185047  if( p->rc ) return;
185048  memcpy(pOut->aSeg, &pLvl->aSeg[is], sizeof(Fts5StructureSegment));
185049  pOut->nSeg++;
185050  pLvl->nSeg--;
185051  }
185052  }
185053  }
185054 }
185055 
185056 /*
185057 ** A new segment has just been written to level iLvl of index structure
185058 ** pStruct. This function determines if any segments should be promoted
185059 ** as a result. Segments are promoted in two scenarios:
185060 **
185061 ** a) If the segment just written is smaller than one or more segments
185062 ** within the previous populated level, it is promoted to the previous
185063 ** populated level.
185064 **
185065 ** b) If the segment just written is larger than the newest segment on
185066 ** the next populated level, then that segment, and any other adjacent
185067 ** segments that are also smaller than the one just written, are
185068 ** promoted.
185069 **
185070 ** If one or more segments are promoted, the structure object is updated
185071 ** to reflect this.
185072 */
185073 static void fts5StructurePromote(
185074  Fts5Index *p, /* FTS5 backend object */
185075  int iLvl, /* Index level just updated */
185076  Fts5Structure *pStruct /* Index structure */
185077 ){
185078  if( p->rc==SQLITE_OK ){
185079  int iTst;
185080  int iPromote = -1;
185081  int szPromote = 0; /* Promote anything this size or smaller */
185082  Fts5StructureSegment *pSeg; /* Segment just written */
185083  int szSeg; /* Size of segment just written */
185084  int nSeg = pStruct->aLevel[iLvl].nSeg;
185085 
185086  if( nSeg==0 ) return;
185087  pSeg = &pStruct->aLevel[iLvl].aSeg[pStruct->aLevel[iLvl].nSeg-1];
185088  szSeg = (1 + pSeg->pgnoLast - pSeg->pgnoFirst);
185089 
185090  /* Check for condition (a) */
185091  for(iTst=iLvl-1; iTst>=0 && pStruct->aLevel[iTst].nSeg==0; iTst--);
185092  if( iTst>=0 ){
185093  int i;
185094  int szMax = 0;
185095  Fts5StructureLevel *pTst = &pStruct->aLevel[iTst];
185096  assert( pTst->nMerge==0 );
185097  for(i=0; i<pTst->nSeg; i++){
185098  int sz = pTst->aSeg[i].pgnoLast - pTst->aSeg[i].pgnoFirst + 1;
185099  if( sz>szMax ) szMax = sz;
185100  }
185101  if( szMax>=szSeg ){
185102  /* Condition (a) is true. Promote the newest segment on level
185103  ** iLvl to level iTst. */
185104  iPromote = iTst;
185105  szPromote = szMax;
185106  }
185107  }
185108 
185109  /* If condition (a) is not met, assume (b) is true. StructurePromoteTo()
185110  ** is a no-op if it is not. */
185111  if( iPromote<0 ){
185112  iPromote = iLvl;
185113  szPromote = szSeg;
185114  }
185115  fts5StructurePromoteTo(p, iPromote, szPromote, pStruct);
185116  }
185117 }
185118 
185119 
185120 /*
185121 ** Advance the iterator passed as the only argument. If the end of the
185122 ** doclist-index page is reached, return non-zero.
185123 */
185124 static int fts5DlidxLvlNext(Fts5DlidxLvl *pLvl){
185125  Fts5Data *pData = pLvl->pData;
185126 
185127  if( pLvl->iOff==0 ){
185128  assert( pLvl->bEof==0 );
185129  pLvl->iOff = 1;
185130  pLvl->iOff += fts5GetVarint32(&pData->p[1], pLvl->iLeafPgno);
185131  pLvl->iOff += fts5GetVarint(&pData->p[pLvl->iOff], (u64*)&pLvl->iRowid);
185132  pLvl->iFirstOff = pLvl->iOff;
185133  }else{
185134  int iOff;
185135  for(iOff=pLvl->iOff; iOff<pData->nn; iOff++){
185136  if( pData->p[iOff] ) break;
185137  }
185138 
185139  if( iOff<pData->nn ){
185140  i64 iVal;
185141  pLvl->iLeafPgno += (iOff - pLvl->iOff) + 1;
185142  iOff += fts5GetVarint(&pData->p[iOff], (u64*)&iVal);
185143  pLvl->iRowid += iVal;
185144  pLvl->iOff = iOff;
185145  }else{
185146  pLvl->bEof = 1;
185147  }
185148  }
185149 
185150  return pLvl->bEof;
185151 }
185152 
185153 /*
185154 ** Advance the iterator passed as the only argument.
185155 */
185156 static int fts5DlidxIterNextR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
185157  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
185158 
185159  assert( iLvl<pIter->nLvl );
185160  if( fts5DlidxLvlNext(pLvl) ){
185161  if( (iLvl+1) < pIter->nLvl ){
185162  fts5DlidxIterNextR(p, pIter, iLvl+1);
185163  if( pLvl[1].bEof==0 ){
185164  fts5DataRelease(pLvl->pData);
185165  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
185166  pLvl->pData = fts5DataRead(p,
185167  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
185168  );
185169  if( pLvl->pData ) fts5DlidxLvlNext(pLvl);
185170  }
185171  }
185172  }
185173 
185174  return pIter->aLvl[0].bEof;
185175 }
185176 static int fts5DlidxIterNext(Fts5Index *p, Fts5DlidxIter *pIter){
185177  return fts5DlidxIterNextR(p, pIter, 0);
185178 }
185179 
185180 /*
185181 ** The iterator passed as the first argument has the following fields set
185182 ** as follows. This function sets up the rest of the iterator so that it
185183 ** points to the first rowid in the doclist-index.
185184 **
185185 ** pData:
185186 ** pointer to doclist-index record,
185187 **
185188 ** When this function is called pIter->iLeafPgno is the page number the
185189 ** doclist is associated with (the one featuring the term).
185190 */
185191 static int fts5DlidxIterFirst(Fts5DlidxIter *pIter){
185192  int i;
185193  for(i=0; i<pIter->nLvl; i++){
185194  fts5DlidxLvlNext(&pIter->aLvl[i]);
185195  }
185196  return pIter->aLvl[0].bEof;
185197 }
185198 
185199 
185200 static int fts5DlidxIterEof(Fts5Index *p, Fts5DlidxIter *pIter){
185201  return p->rc!=SQLITE_OK || pIter->aLvl[0].bEof;
185202 }
185203 
185204 static void fts5DlidxIterLast(Fts5Index *p, Fts5DlidxIter *pIter){
185205  int i;
185206 
185207  /* Advance each level to the last entry on the last page */
185208  for(i=pIter->nLvl-1; p->rc==SQLITE_OK && i>=0; i--){
185209  Fts5DlidxLvl *pLvl = &pIter->aLvl[i];
185210  while( fts5DlidxLvlNext(pLvl)==0 );
185211  pLvl->bEof = 0;
185212 
185213  if( i>0 ){
185214  Fts5DlidxLvl *pChild = &pLvl[-1];
185215  fts5DataRelease(pChild->pData);
185216  memset(pChild, 0, sizeof(Fts5DlidxLvl));
185217  pChild->pData = fts5DataRead(p,
185218  FTS5_DLIDX_ROWID(pIter->iSegid, i-1, pLvl->iLeafPgno)
185219  );
185220  }
185221  }
185222 }
185223 
185224 /*
185225 ** Move the iterator passed as the only argument to the previous entry.
185226 */
185227 static int fts5DlidxLvlPrev(Fts5DlidxLvl *pLvl){
185228  int iOff = pLvl->iOff;
185229 
185230  assert( pLvl->bEof==0 );
185231  if( iOff<=pLvl->iFirstOff ){
185232  pLvl->bEof = 1;
185233  }else{
185234  u8 *a = pLvl->pData->p;
185235  i64 iVal;
185236  int iLimit;
185237  int ii;
185238  int nZero = 0;
185239 
185240  /* Currently iOff points to the first byte of a varint. This block
185241  ** decrements iOff until it points to the first byte of the previous
185242  ** varint. Taking care not to read any memory locations that occur
185243  ** before the buffer in memory. */
185244  iLimit = (iOff>9 ? iOff-9 : 0);
185245  for(iOff--; iOff>iLimit; iOff--){
185246  if( (a[iOff-1] & 0x80)==0 ) break;
185247  }
185248 
185249  fts5GetVarint(&a[iOff], (u64*)&iVal);
185250  pLvl->iRowid -= iVal;
185251  pLvl->iLeafPgno--;
185252 
185253  /* Skip backwards past any 0x00 varints. */
185254  for(ii=iOff-1; ii>=pLvl->iFirstOff && a[ii]==0x00; ii--){
185255  nZero++;
185256  }
185257  if( ii>=pLvl->iFirstOff && (a[ii] & 0x80) ){
185258  /* The byte immediately before the last 0x00 byte has the 0x80 bit
185259  ** set. So the last 0x00 is only a varint 0 if there are 8 more 0x80
185260  ** bytes before a[ii]. */
185261  int bZero = 0; /* True if last 0x00 counts */
185262  if( (ii-8)>=pLvl->iFirstOff ){
185263  int j;
185264  for(j=1; j<=8 && (a[ii-j] & 0x80); j++);
185265  bZero = (j>8);
185266  }
185267  if( bZero==0 ) nZero--;
185268  }
185269  pLvl->iLeafPgno -= nZero;
185270  pLvl->iOff = iOff - nZero;
185271  }
185272 
185273  return pLvl->bEof;
185274 }
185275 
185276 static int fts5DlidxIterPrevR(Fts5Index *p, Fts5DlidxIter *pIter, int iLvl){
185277  Fts5DlidxLvl *pLvl = &pIter->aLvl[iLvl];
185278 
185279  assert( iLvl<pIter->nLvl );
185280  if( fts5DlidxLvlPrev(pLvl) ){
185281  if( (iLvl+1) < pIter->nLvl ){
185282  fts5DlidxIterPrevR(p, pIter, iLvl+1);
185283  if( pLvl[1].bEof==0 ){
185284  fts5DataRelease(pLvl->pData);
185285  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
185286  pLvl->pData = fts5DataRead(p,
185287  FTS5_DLIDX_ROWID(pIter->iSegid, iLvl, pLvl[1].iLeafPgno)
185288  );
185289  if( pLvl->pData ){
185290  while( fts5DlidxLvlNext(pLvl)==0 );
185291  pLvl->bEof = 0;
185292  }
185293  }
185294  }
185295  }
185296 
185297  return pIter->aLvl[0].bEof;
185298 }
185299 static int fts5DlidxIterPrev(Fts5Index *p, Fts5DlidxIter *pIter){
185300  return fts5DlidxIterPrevR(p, pIter, 0);
185301 }
185302 
185303 /*
185304 ** Free a doclist-index iterator object allocated by fts5DlidxIterInit().
185305 */
185306 static void fts5DlidxIterFree(Fts5DlidxIter *pIter){
185307  if( pIter ){
185308  int i;
185309  for(i=0; i<pIter->nLvl; i++){
185310  fts5DataRelease(pIter->aLvl[i].pData);
185311  }
185312  sqlite3_free(pIter);
185313  }
185314 }
185315 
185316 static Fts5DlidxIter *fts5DlidxIterInit(
185317  Fts5Index *p, /* Fts5 Backend to iterate within */
185318  int bRev, /* True for ORDER BY ASC */
185319  int iSegid, /* Segment id */
185320  int iLeafPg /* Leaf page number to load dlidx for */
185321 ){
185322  Fts5DlidxIter *pIter = 0;
185323  int i;
185324  int bDone = 0;
185325 
185326  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
185327  int nByte = sizeof(Fts5DlidxIter) + i * sizeof(Fts5DlidxLvl);
185328  Fts5DlidxIter *pNew;
185329 
185330  pNew = (Fts5DlidxIter*)sqlite3_realloc(pIter, nByte);
185331  if( pNew==0 ){
185332  p->rc = SQLITE_NOMEM;
185333  }else{
185334  i64 iRowid = FTS5_DLIDX_ROWID(iSegid, i, iLeafPg);
185335  Fts5DlidxLvl *pLvl = &pNew->aLvl[i];
185336  pIter = pNew;
185337  memset(pLvl, 0, sizeof(Fts5DlidxLvl));
185338  pLvl->pData = fts5DataRead(p, iRowid);
185339  if( pLvl->pData && (pLvl->pData->p[0] & 0x0001)==0 ){
185340  bDone = 1;
185341  }
185342  pIter->nLvl = i+1;
185343  }
185344  }
185345 
185346  if( p->rc==SQLITE_OK ){
185347  pIter->iSegid = iSegid;
185348  if( bRev==0 ){
185349  fts5DlidxIterFirst(pIter);
185350  }else{
185351  fts5DlidxIterLast(p, pIter);
185352  }
185353  }
185354 
185355  if( p->rc!=SQLITE_OK ){
185356  fts5DlidxIterFree(pIter);
185357  pIter = 0;
185358  }
185359 
185360  return pIter;
185361 }
185362 
185363 static i64 fts5DlidxIterRowid(Fts5DlidxIter *pIter){
185364  return pIter->aLvl[0].iRowid;
185365 }
185366 static int fts5DlidxIterPgno(Fts5DlidxIter *pIter){
185367  return pIter->aLvl[0].iLeafPgno;
185368 }
185369 
185370 /*
185371 ** Load the next leaf page into the segment iterator.
185372 */
185373 static void fts5SegIterNextPage(
185374  Fts5Index *p, /* FTS5 backend object */
185375  Fts5SegIter *pIter /* Iterator to advance to next page */
185376 ){
185377  Fts5Data *pLeaf;
185378  Fts5StructureSegment *pSeg = pIter->pSeg;
185379  fts5DataRelease(pIter->pLeaf);
185380  pIter->iLeafPgno++;
185381  if( pIter->pNextLeaf ){
185382  pIter->pLeaf = pIter->pNextLeaf;
185383  pIter->pNextLeaf = 0;
185384  }else if( pIter->iLeafPgno<=pSeg->pgnoLast ){
185385  pIter->pLeaf = fts5DataRead(p,
185386  FTS5_SEGMENT_ROWID(pSeg->iSegid, pIter->iLeafPgno)
185387  );
185388  }else{
185389  pIter->pLeaf = 0;
185390  }
185391  pLeaf = pIter->pLeaf;
185392 
185393  if( pLeaf ){
185394  pIter->iPgidxOff = pLeaf->szLeaf;
185395  if( fts5LeafIsTermless(pLeaf) ){
185396  pIter->iEndofDoclist = pLeaf->nn+1;
185397  }else{
185398  pIter->iPgidxOff += fts5GetVarint32(&pLeaf->p[pIter->iPgidxOff],
185399  pIter->iEndofDoclist
185400  );
185401  }
185402  }
185403 }
185404 
185405 /*
185406 ** Argument p points to a buffer containing a varint to be interpreted as a
185407 ** position list size field. Read the varint and return the number of bytes
185408 ** read. Before returning, set *pnSz to the number of bytes in the position
185409 ** list, and *pbDel to true if the delete flag is set, or false otherwise.
185410 */
185411 static int fts5GetPoslistSize(const u8 *p, int *pnSz, int *pbDel){
185412  int nSz;
185413  int n = 0;
185414  fts5FastGetVarint32(p, n, nSz);
185415  assert_nc( nSz>=0 );
185416  *pnSz = nSz/2;
185417  *pbDel = nSz & 0x0001;
185418  return n;
185419 }
185420 
185421 /*
185422 ** Fts5SegIter.iLeafOffset currently points to the first byte of a
185423 ** position-list size field. Read the value of the field and store it
185424 ** in the following variables:
185425 **
185426 ** Fts5SegIter.nPos
185427 ** Fts5SegIter.bDel
185428 **
185429 ** Leave Fts5SegIter.iLeafOffset pointing to the first byte of the
185430 ** position list content (if any).
185431 */
185432 static void fts5SegIterLoadNPos(Fts5Index *p, Fts5SegIter *pIter){
185433  if( p->rc==SQLITE_OK ){
185434  int iOff = pIter->iLeafOffset; /* Offset to read at */
185435  ASSERT_SZLEAF_OK(pIter->pLeaf);
185436  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
185437  int iEod = MIN(pIter->iEndofDoclist, pIter->pLeaf->szLeaf);
185438  pIter->bDel = 0;
185439  pIter->nPos = 1;
185440  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
185441  pIter->bDel = 1;
185442  iOff++;
185443  if( iOff<iEod && pIter->pLeaf->p[iOff]==0 ){
185444  pIter->nPos = 1;
185445  iOff++;
185446  }else{
185447  pIter->nPos = 0;
185448  }
185449  }
185450  }else{
185451  int nSz;
185452  fts5FastGetVarint32(pIter->pLeaf->p, iOff, nSz);
185453  pIter->bDel = (nSz & 0x0001);
185454  pIter->nPos = nSz>>1;
185455  assert_nc( pIter->nPos>=0 );
185456  }
185457  pIter->iLeafOffset = iOff;
185458  }
185459 }
185460 
185461 static void fts5SegIterLoadRowid(Fts5Index *p, Fts5SegIter *pIter){
185462  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
185463  int iOff = pIter->iLeafOffset;
185464 
185465  ASSERT_SZLEAF_OK(pIter->pLeaf);
185466  if( iOff>=pIter->pLeaf->szLeaf ){
185467  fts5SegIterNextPage(p, pIter);
185468  if( pIter->pLeaf==0 ){
185469  if( p->rc==SQLITE_OK ) p->rc = FTS5_CORRUPT;
185470  return;
185471  }
185472  iOff = 4;
185473  a = pIter->pLeaf->p;
185474  }
185475  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
185476  pIter->iLeafOffset = iOff;
185477 }
185478 
185479 /*
185480 ** Fts5SegIter.iLeafOffset currently points to the first byte of the
185481 ** "nSuffix" field of a term. Function parameter nKeep contains the value
185482 ** of the "nPrefix" field (if there was one - it is passed 0 if this is
185483 ** the first term in the segment).
185484 **
185485 ** This function populates:
185486 **
185487 ** Fts5SegIter.term
185488 ** Fts5SegIter.rowid
185489 **
185490 ** accordingly and leaves (Fts5SegIter.iLeafOffset) set to the content of
185491 ** the first position list. The position list belonging to document
185492 ** (Fts5SegIter.iRowid).
185493 */
185494 static void fts5SegIterLoadTerm(Fts5Index *p, Fts5SegIter *pIter, int nKeep){
185495  u8 *a = pIter->pLeaf->p; /* Buffer to read data from */
185496  int iOff = pIter->iLeafOffset; /* Offset to read at */
185497  int nNew; /* Bytes of new data */
185498 
185499  iOff += fts5GetVarint32(&a[iOff], nNew);
185500  if( iOff+nNew>pIter->pLeaf->nn ){
185501  p->rc = FTS5_CORRUPT;
185502  return;
185503  }
185504  pIter->term.n = nKeep;
185505  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
185506  iOff += nNew;
185507  pIter->iTermLeafOffset = iOff;
185508  pIter->iTermLeafPgno = pIter->iLeafPgno;
185509  pIter->iLeafOffset = iOff;
185510 
185511  if( pIter->iPgidxOff>=pIter->pLeaf->nn ){
185512  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
185513  }else{
185514  int nExtra;
185515  pIter->iPgidxOff += fts5GetVarint32(&a[pIter->iPgidxOff], nExtra);
185516  pIter->iEndofDoclist += nExtra;
185517  }
185518 
185519  fts5SegIterLoadRowid(p, pIter);
185520 }
185521 
185522 static void fts5SegIterNext(Fts5Index*, Fts5SegIter*, int*);
185523 static void fts5SegIterNext_Reverse(Fts5Index*, Fts5SegIter*, int*);
185524 static void fts5SegIterNext_None(Fts5Index*, Fts5SegIter*, int*);
185525 
185526 static void fts5SegIterSetNext(Fts5Index *p, Fts5SegIter *pIter){
185527  if( pIter->flags & FTS5_SEGITER_REVERSE ){
185528  pIter->xNext = fts5SegIterNext_Reverse;
185529  }else if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
185530  pIter->xNext = fts5SegIterNext_None;
185531  }else{
185532  pIter->xNext = fts5SegIterNext;
185533  }
185534 }
185535 
185536 /*
185537 ** Initialize the iterator object pIter to iterate through the entries in
185538 ** segment pSeg. The iterator is left pointing to the first entry when
185539 ** this function returns.
185540 **
185541 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
185542 ** an error has already occurred when this function is called, it is a no-op.
185543 */
185544 static void fts5SegIterInit(
185545  Fts5Index *p, /* FTS index object */
185546  Fts5StructureSegment *pSeg, /* Description of segment */
185547  Fts5SegIter *pIter /* Object to populate */
185548 ){
185549  if( pSeg->pgnoFirst==0 ){
185550  /* This happens if the segment is being used as an input to an incremental
185551  ** merge and all data has already been "trimmed". See function
185552  ** fts5TrimSegments() for details. In this case leave the iterator empty.
185553  ** The caller will see the (pIter->pLeaf==0) and assume the iterator is
185554  ** at EOF already. */
185555  assert( pIter->pLeaf==0 );
185556  return;
185557  }
185558 
185559  if( p->rc==SQLITE_OK ){
185560  memset(pIter, 0, sizeof(*pIter));
185561  fts5SegIterSetNext(p, pIter);
185562  pIter->pSeg = pSeg;
185563  pIter->iLeafPgno = pSeg->pgnoFirst-1;
185564  fts5SegIterNextPage(p, pIter);
185565  }
185566 
185567  if( p->rc==SQLITE_OK ){
185568  pIter->iLeafOffset = 4;
185569  assert_nc( pIter->pLeaf->nn>4 );
185570  assert( fts5LeafFirstTermOff(pIter->pLeaf)==4 );
185571  pIter->iPgidxOff = pIter->pLeaf->szLeaf+1;
185572  fts5SegIterLoadTerm(p, pIter, 0);
185573  fts5SegIterLoadNPos(p, pIter);
185574  }
185575 }
185576 
185577 /*
185578 ** This function is only ever called on iterators created by calls to
185579 ** Fts5IndexQuery() with the FTS5INDEX_QUERY_DESC flag set.
185580 **
185581 ** The iterator is in an unusual state when this function is called: the
185582 ** Fts5SegIter.iLeafOffset variable is set to the offset of the start of
185583 ** the position-list size field for the first relevant rowid on the page.
185584 ** Fts5SegIter.rowid is set, but nPos and bDel are not.
185585 **
185586 ** This function advances the iterator so that it points to the last
185587 ** relevant rowid on the page and, if necessary, initializes the
185588 ** aRowidOffset[] and iRowidOffset variables. At this point the iterator
185589 ** is in its regular state - Fts5SegIter.iLeafOffset points to the first
185590 ** byte of the position list content associated with said rowid.
185591 */
185592 static void fts5SegIterReverseInitPage(Fts5Index *p, Fts5SegIter *pIter){
185593  int eDetail = p->pConfig->eDetail;
185594  int n = pIter->pLeaf->szLeaf;
185595  int i = pIter->iLeafOffset;
185596  u8 *a = pIter->pLeaf->p;
185597  int iRowidOffset = 0;
185598 
185599  if( n>pIter->iEndofDoclist ){
185600  n = pIter->iEndofDoclist;
185601  }
185602 
185603  ASSERT_SZLEAF_OK(pIter->pLeaf);
185604  while( 1 ){
185605  i64 iDelta = 0;
185606 
185607  if( eDetail==FTS5_DETAIL_NONE ){
185608  /* todo */
185609  if( i<n && a[i]==0 ){
185610  i++;
185611  if( i<n && a[i]==0 ) i++;
185612  }
185613  }else{
185614  int nPos;
185615  int bDummy;
185616  i += fts5GetPoslistSize(&a[i], &nPos, &bDummy);
185617  i += nPos;
185618  }
185619  if( i>=n ) break;
185620  i += fts5GetVarint(&a[i], (u64*)&iDelta);
185621  pIter->iRowid += iDelta;
185622 
185623  /* If necessary, grow the pIter->aRowidOffset[] array. */
185624  if( iRowidOffset>=pIter->nRowidOffset ){
185625  int nNew = pIter->nRowidOffset + 8;
185626  int *aNew = (int*)sqlite3_realloc(pIter->aRowidOffset, nNew*sizeof(int));
185627  if( aNew==0 ){
185628  p->rc = SQLITE_NOMEM;
185629  break;
185630  }
185631  pIter->aRowidOffset = aNew;
185632  pIter->nRowidOffset = nNew;
185633  }
185634 
185635  pIter->aRowidOffset[iRowidOffset++] = pIter->iLeafOffset;
185636  pIter->iLeafOffset = i;
185637  }
185638  pIter->iRowidOffset = iRowidOffset;
185639  fts5SegIterLoadNPos(p, pIter);
185640 }
185641 
185642 /*
185643 **
185644 */
185645 static void fts5SegIterReverseNewPage(Fts5Index *p, Fts5SegIter *pIter){
185646  assert( pIter->flags & FTS5_SEGITER_REVERSE );
185647  assert( pIter->flags & FTS5_SEGITER_ONETERM );
185648 
185649  fts5DataRelease(pIter->pLeaf);
185650  pIter->pLeaf = 0;
185651  while( p->rc==SQLITE_OK && pIter->iLeafPgno>pIter->iTermLeafPgno ){
185652  Fts5Data *pNew;
185653  pIter->iLeafPgno--;
185654  pNew = fts5DataRead(p, FTS5_SEGMENT_ROWID(
185655  pIter->pSeg->iSegid, pIter->iLeafPgno
185656  ));
185657  if( pNew ){
185658  /* iTermLeafOffset may be equal to szLeaf if the term is the last
185659  ** thing on the page - i.e. the first rowid is on the following page.
185660  ** In this case leave pIter->pLeaf==0, this iterator is at EOF. */
185661  if( pIter->iLeafPgno==pIter->iTermLeafPgno ){
185662  assert( pIter->pLeaf==0 );
185663  if( pIter->iTermLeafOffset<pNew->szLeaf ){
185664  pIter->pLeaf = pNew;
185665  pIter->iLeafOffset = pIter->iTermLeafOffset;
185666  }
185667  }else{
185668  int iRowidOff;
185669  iRowidOff = fts5LeafFirstRowidOff(pNew);
185670  if( iRowidOff ){
185671  pIter->pLeaf = pNew;
185672  pIter->iLeafOffset = iRowidOff;
185673  }
185674  }
185675 
185676  if( pIter->pLeaf ){
185677  u8 *a = &pIter->pLeaf->p[pIter->iLeafOffset];
185678  pIter->iLeafOffset += fts5GetVarint(a, (u64*)&pIter->iRowid);
185679  break;
185680  }else{
185681  fts5DataRelease(pNew);
185682  }
185683  }
185684  }
185685 
185686  if( pIter->pLeaf ){
185687  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
185688  fts5SegIterReverseInitPage(p, pIter);
185689  }
185690 }
185691 
185692 /*
185693 ** Return true if the iterator passed as the second argument currently
185694 ** points to a delete marker. A delete marker is an entry with a 0 byte
185695 ** position-list.
185696 */
185697 static int fts5MultiIterIsEmpty(Fts5Index *p, Fts5Iter *pIter){
185698  Fts5SegIter *pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
185699  return (p->rc==SQLITE_OK && pSeg->pLeaf && pSeg->nPos==0);
185700 }
185701 
185702 /*
185703 ** Advance iterator pIter to the next entry.
185704 **
185705 ** This version of fts5SegIterNext() is only used by reverse iterators.
185706 */
185707 static void fts5SegIterNext_Reverse(
185708  Fts5Index *p, /* FTS5 backend object */
185709  Fts5SegIter *pIter, /* Iterator to advance */
185710  int *pbUnused /* Unused */
185711 ){
185712  assert( pIter->flags & FTS5_SEGITER_REVERSE );
185713  assert( pIter->pNextLeaf==0 );
185714  UNUSED_PARAM(pbUnused);
185715 
185716  if( pIter->iRowidOffset>0 ){
185717  u8 *a = pIter->pLeaf->p;
185718  int iOff;
185719  i64 iDelta;
185720 
185721  pIter->iRowidOffset--;
185722  pIter->iLeafOffset = pIter->aRowidOffset[pIter->iRowidOffset];
185723  fts5SegIterLoadNPos(p, pIter);
185724  iOff = pIter->iLeafOffset;
185725  if( p->pConfig->eDetail!=FTS5_DETAIL_NONE ){
185726  iOff += pIter->nPos;
185727  }
185728  fts5GetVarint(&a[iOff], (u64*)&iDelta);
185729  pIter->iRowid -= iDelta;
185730  }else{
185731  fts5SegIterReverseNewPage(p, pIter);
185732  }
185733 }
185734 
185735 /*
185736 ** Advance iterator pIter to the next entry.
185737 **
185738 ** This version of fts5SegIterNext() is only used if detail=none and the
185739 ** iterator is not a reverse direction iterator.
185740 */
185741 static void fts5SegIterNext_None(
185742  Fts5Index *p, /* FTS5 backend object */
185743  Fts5SegIter *pIter, /* Iterator to advance */
185744  int *pbNewTerm /* OUT: Set for new term */
185745 ){
185746  int iOff;
185747 
185748  assert( p->rc==SQLITE_OK );
185749  assert( (pIter->flags & FTS5_SEGITER_REVERSE)==0 );
185750  assert( p->pConfig->eDetail==FTS5_DETAIL_NONE );
185751 
185752  ASSERT_SZLEAF_OK(pIter->pLeaf);
185753  iOff = pIter->iLeafOffset;
185754 
185755  /* Next entry is on the next page */
185756  if( pIter->pSeg && iOff>=pIter->pLeaf->szLeaf ){
185757  fts5SegIterNextPage(p, pIter);
185758  if( p->rc || pIter->pLeaf==0 ) return;
185759  pIter->iRowid = 0;
185760  iOff = 4;
185761  }
185762 
185763  if( iOff<pIter->iEndofDoclist ){
185764  /* Next entry is on the current page */
185765  i64 iDelta;
185766  iOff += sqlite3Fts5GetVarint(&pIter->pLeaf->p[iOff], (u64*)&iDelta);
185767  pIter->iLeafOffset = iOff;
185768  pIter->iRowid += iDelta;
185769  }else if( (pIter->flags & FTS5_SEGITER_ONETERM)==0 ){
185770  if( pIter->pSeg ){
185771  int nKeep = 0;
185772  if( iOff!=fts5LeafFirstTermOff(pIter->pLeaf) ){
185773  iOff += fts5GetVarint32(&pIter->pLeaf->p[iOff], nKeep);
185774  }
185775  pIter->iLeafOffset = iOff;
185776  fts5SegIterLoadTerm(p, pIter, nKeep);
185777  }else{
185778  const u8 *pList = 0;
185779  const char *zTerm = 0;
185780  int nList;
185781  sqlite3Fts5HashScanNext(p->pHash);
185782  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
185783  if( pList==0 ) goto next_none_eof;
185784  pIter->pLeaf->p = (u8*)pList;
185785  pIter->pLeaf->nn = nList;
185786  pIter->pLeaf->szLeaf = nList;
185787  pIter->iEndofDoclist = nList;
185788  sqlite3Fts5BufferSet(&p->rc,&pIter->term, (int)strlen(zTerm), (u8*)zTerm);
185789  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
185790  }
185791 
185792  if( pbNewTerm ) *pbNewTerm = 1;
185793  }else{
185794  goto next_none_eof;
185795  }
185796 
185797  fts5SegIterLoadNPos(p, pIter);
185798 
185799  return;
185800  next_none_eof:
185801  fts5DataRelease(pIter->pLeaf);
185802  pIter->pLeaf = 0;
185803 }
185804 
185805 
185806 /*
185807 ** Advance iterator pIter to the next entry.
185808 **
185809 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. It
185810 ** is not considered an error if the iterator reaches EOF. If an error has
185811 ** already occurred when this function is called, it is a no-op.
185812 */
185813 static void fts5SegIterNext(
185814  Fts5Index *p, /* FTS5 backend object */
185815  Fts5SegIter *pIter, /* Iterator to advance */
185816  int *pbNewTerm /* OUT: Set for new term */
185817 ){
185818  Fts5Data *pLeaf = pIter->pLeaf;
185819  int iOff;
185820  int bNewTerm = 0;
185821  int nKeep = 0;
185822  u8 *a;
185823  int n;
185824 
185825  assert( pbNewTerm==0 || *pbNewTerm==0 );
185826  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
185827 
185828  /* Search for the end of the position list within the current page. */
185829  a = pLeaf->p;
185830  n = pLeaf->szLeaf;
185831 
185832  ASSERT_SZLEAF_OK(pLeaf);
185833  iOff = pIter->iLeafOffset + pIter->nPos;
185834 
185835  if( iOff<n ){
185836  /* The next entry is on the current page. */
185837  assert_nc( iOff<=pIter->iEndofDoclist );
185838  if( iOff>=pIter->iEndofDoclist ){
185839  bNewTerm = 1;
185840  if( iOff!=fts5LeafFirstTermOff(pLeaf) ){
185841  iOff += fts5GetVarint32(&a[iOff], nKeep);
185842  }
185843  }else{
185844  u64 iDelta;
185845  iOff += sqlite3Fts5GetVarint(&a[iOff], &iDelta);
185846  pIter->iRowid += iDelta;
185847  assert_nc( iDelta>0 );
185848  }
185849  pIter->iLeafOffset = iOff;
185850 
185851  }else if( pIter->pSeg==0 ){
185852  const u8 *pList = 0;
185853  const char *zTerm = 0;
185854  int nList = 0;
185855  assert( (pIter->flags & FTS5_SEGITER_ONETERM) || pbNewTerm );
185856  if( 0==(pIter->flags & FTS5_SEGITER_ONETERM) ){
185857  sqlite3Fts5HashScanNext(p->pHash);
185858  sqlite3Fts5HashScanEntry(p->pHash, &zTerm, &pList, &nList);
185859  }
185860  if( pList==0 ){
185861  fts5DataRelease(pIter->pLeaf);
185862  pIter->pLeaf = 0;
185863  }else{
185864  pIter->pLeaf->p = (u8*)pList;
185865  pIter->pLeaf->nn = nList;
185866  pIter->pLeaf->szLeaf = nList;
185867  pIter->iEndofDoclist = nList+1;
185868  sqlite3Fts5BufferSet(&p->rc, &pIter->term, (int)strlen(zTerm),
185869  (u8*)zTerm);
185870  pIter->iLeafOffset = fts5GetVarint(pList, (u64*)&pIter->iRowid);
185871  *pbNewTerm = 1;
185872  }
185873  }else{
185874  iOff = 0;
185875  /* Next entry is not on the current page */
185876  while( iOff==0 ){
185877  fts5SegIterNextPage(p, pIter);
185878  pLeaf = pIter->pLeaf;
185879  if( pLeaf==0 ) break;
185880  ASSERT_SZLEAF_OK(pLeaf);
185881  if( (iOff = fts5LeafFirstRowidOff(pLeaf)) && iOff<pLeaf->szLeaf ){
185882  iOff += sqlite3Fts5GetVarint(&pLeaf->p[iOff], (u64*)&pIter->iRowid);
185883  pIter->iLeafOffset = iOff;
185884 
185885  if( pLeaf->nn>pLeaf->szLeaf ){
185886  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
185887  &pLeaf->p[pLeaf->szLeaf], pIter->iEndofDoclist
185888  );
185889  }
185890 
185891  }
185892  else if( pLeaf->nn>pLeaf->szLeaf ){
185893  pIter->iPgidxOff = pLeaf->szLeaf + fts5GetVarint32(
185894  &pLeaf->p[pLeaf->szLeaf], iOff
185895  );
185896  pIter->iLeafOffset = iOff;
185897  pIter->iEndofDoclist = iOff;
185898  bNewTerm = 1;
185899  }
185900  assert_nc( iOff<pLeaf->szLeaf );
185901  if( iOff>pLeaf->szLeaf ){
185902  p->rc = FTS5_CORRUPT;
185903  return;
185904  }
185905  }
185906  }
185907 
185908  /* Check if the iterator is now at EOF. If so, return early. */
185909  if( pIter->pLeaf ){
185910  if( bNewTerm ){
185911  if( pIter->flags & FTS5_SEGITER_ONETERM ){
185912  fts5DataRelease(pIter->pLeaf);
185913  pIter->pLeaf = 0;
185914  }else{
185915  fts5SegIterLoadTerm(p, pIter, nKeep);
185916  fts5SegIterLoadNPos(p, pIter);
185917  if( pbNewTerm ) *pbNewTerm = 1;
185918  }
185919  }else{
185920  /* The following could be done by calling fts5SegIterLoadNPos(). But
185921  ** this block is particularly performance critical, so equivalent
185922  ** code is inlined.
185923  **
185924  ** Later: Switched back to fts5SegIterLoadNPos() because it supports
185925  ** detail=none mode. Not ideal.
185926  */
185927  int nSz;
185928  assert( p->rc==SQLITE_OK );
185929  fts5FastGetVarint32(pIter->pLeaf->p, pIter->iLeafOffset, nSz);
185930  pIter->bDel = (nSz & 0x0001);
185931  pIter->nPos = nSz>>1;
185932  assert_nc( pIter->nPos>=0 );
185933  }
185934  }
185935 }
185936 
185937 #define SWAPVAL(T, a, b) { T tmp; tmp=a; a=b; b=tmp; }
185938 
185939 #define fts5IndexSkipVarint(a, iOff) { \
185940  int iEnd = iOff+9; \
185941  while( (a[iOff++] & 0x80) && iOff<iEnd ); \
185942 }
185943 
185944 /*
185945 ** Iterator pIter currently points to the first rowid in a doclist. This
185946 ** function sets the iterator up so that iterates in reverse order through
185947 ** the doclist.
185948 */
185949 static void fts5SegIterReverse(Fts5Index *p, Fts5SegIter *pIter){
185950  Fts5DlidxIter *pDlidx = pIter->pDlidx;
185951  Fts5Data *pLast = 0;
185952  int pgnoLast = 0;
185953 
185954  if( pDlidx ){
185955  int iSegid = pIter->pSeg->iSegid;
185956  pgnoLast = fts5DlidxIterPgno(pDlidx);
185957  pLast = fts5DataRead(p, FTS5_SEGMENT_ROWID(iSegid, pgnoLast));
185958  }else{
185959  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
185960 
185961  /* Currently, Fts5SegIter.iLeafOffset points to the first byte of
185962  ** position-list content for the current rowid. Back it up so that it
185963  ** points to the start of the position-list size field. */
185964  int iPoslist;
185965  if( pIter->iTermLeafPgno==pIter->iLeafPgno ){
185966  iPoslist = pIter->iTermLeafOffset;
185967  }else{
185968  iPoslist = 4;
185969  }
185970  fts5IndexSkipVarint(pLeaf->p, iPoslist);
185971  pIter->iLeafOffset = iPoslist;
185972 
185973  /* If this condition is true then the largest rowid for the current
185974  ** term may not be stored on the current page. So search forward to
185975  ** see where said rowid really is. */
185976  if( pIter->iEndofDoclist>=pLeaf->szLeaf ){
185977  int pgno;
185978  Fts5StructureSegment *pSeg = pIter->pSeg;
185979 
185980  /* The last rowid in the doclist may not be on the current page. Search
185981  ** forward to find the page containing the last rowid. */
185982  for(pgno=pIter->iLeafPgno+1; !p->rc && pgno<=pSeg->pgnoLast; pgno++){
185983  i64 iAbs = FTS5_SEGMENT_ROWID(pSeg->iSegid, pgno);
185984  Fts5Data *pNew = fts5DataRead(p, iAbs);
185985  if( pNew ){
185986  int iRowid, bTermless;
185987  iRowid = fts5LeafFirstRowidOff(pNew);
185988  bTermless = fts5LeafIsTermless(pNew);
185989  if( iRowid ){
185990  SWAPVAL(Fts5Data*, pNew, pLast);
185991  pgnoLast = pgno;
185992  }
185993  fts5DataRelease(pNew);
185994  if( bTermless==0 ) break;
185995  }
185996  }
185997  }
185998  }
185999 
186000  /* If pLast is NULL at this point, then the last rowid for this doclist
186001  ** lies on the page currently indicated by the iterator. In this case
186002  ** pIter->iLeafOffset is already set to point to the position-list size
186003  ** field associated with the first relevant rowid on the page.
186004  **
186005  ** Or, if pLast is non-NULL, then it is the page that contains the last
186006  ** rowid. In this case configure the iterator so that it points to the
186007  ** first rowid on this page.
186008  */
186009  if( pLast ){
186010  int iOff;
186011  fts5DataRelease(pIter->pLeaf);
186012  pIter->pLeaf = pLast;
186013  pIter->iLeafPgno = pgnoLast;
186014  iOff = fts5LeafFirstRowidOff(pLast);
186015  iOff += fts5GetVarint(&pLast->p[iOff], (u64*)&pIter->iRowid);
186016  pIter->iLeafOffset = iOff;
186017 
186018  if( fts5LeafIsTermless(pLast) ){
186019  pIter->iEndofDoclist = pLast->nn+1;
186020  }else{
186021  pIter->iEndofDoclist = fts5LeafFirstTermOff(pLast);
186022  }
186023 
186024  }
186025 
186026  fts5SegIterReverseInitPage(p, pIter);
186027 }
186028 
186029 /*
186030 ** Iterator pIter currently points to the first rowid of a doclist.
186031 ** There is a doclist-index associated with the final term on the current
186032 ** page. If the current term is the last term on the page, load the
186033 ** doclist-index from disk and initialize an iterator at (pIter->pDlidx).
186034 */
186035 static void fts5SegIterLoadDlidx(Fts5Index *p, Fts5SegIter *pIter){
186036  int iSeg = pIter->pSeg->iSegid;
186037  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
186038  Fts5Data *pLeaf = pIter->pLeaf; /* Current leaf data */
186039 
186040  assert( pIter->flags & FTS5_SEGITER_ONETERM );
186041  assert( pIter->pDlidx==0 );
186042 
186043  /* Check if the current doclist ends on this page. If it does, return
186044  ** early without loading the doclist-index (as it belongs to a different
186045  ** term. */
186046  if( pIter->iTermLeafPgno==pIter->iLeafPgno
186047  && pIter->iEndofDoclist<pLeaf->szLeaf
186048  ){
186049  return;
186050  }
186051 
186052  pIter->pDlidx = fts5DlidxIterInit(p, bRev, iSeg, pIter->iTermLeafPgno);
186053 }
186054 
186055 /*
186056 ** The iterator object passed as the second argument currently contains
186057 ** no valid values except for the Fts5SegIter.pLeaf member variable. This
186058 ** function searches the leaf page for a term matching (pTerm/nTerm).
186059 **
186060 ** If the specified term is found on the page, then the iterator is left
186061 ** pointing to it. If argument bGe is zero and the term is not found,
186062 ** the iterator is left pointing at EOF.
186063 **
186064 ** If bGe is non-zero and the specified term is not found, then the
186065 ** iterator is left pointing to the smallest term in the segment that
186066 ** is larger than the specified term, even if this term is not on the
186067 ** current page.
186068 */
186069 static void fts5LeafSeek(
186070  Fts5Index *p, /* Leave any error code here */
186071  int bGe, /* True for a >= search */
186072  Fts5SegIter *pIter, /* Iterator to seek */
186073  const u8 *pTerm, int nTerm /* Term to search for */
186074 ){
186075  int iOff;
186076  const u8 *a = pIter->pLeaf->p;
186077  int szLeaf = pIter->pLeaf->szLeaf;
186078  int n = pIter->pLeaf->nn;
186079 
186080  int nMatch = 0;
186081  int nKeep = 0;
186082  int nNew = 0;
186083  int iTermOff;
186084  int iPgidx; /* Current offset in pgidx */
186085  int bEndOfPage = 0;
186086 
186087  assert( p->rc==SQLITE_OK );
186088 
186089  iPgidx = szLeaf;
186090  iPgidx += fts5GetVarint32(&a[iPgidx], iTermOff);
186091  iOff = iTermOff;
186092  if( iOff>n ){
186093  p->rc = FTS5_CORRUPT;
186094  return;
186095  }
186096 
186097  while( 1 ){
186098 
186099  /* Figure out how many new bytes are in this term */
186100  fts5FastGetVarint32(a, iOff, nNew);
186101  if( nKeep<nMatch ){
186102  goto search_failed;
186103  }
186104 
186105  assert( nKeep>=nMatch );
186106  if( nKeep==nMatch ){
186107  int nCmp;
186108  int i;
186109  nCmp = MIN(nNew, nTerm-nMatch);
186110  for(i=0; i<nCmp; i++){
186111  if( a[iOff+i]!=pTerm[nMatch+i] ) break;
186112  }
186113  nMatch += i;
186114 
186115  if( nTerm==nMatch ){
186116  if( i==nNew ){
186117  goto search_success;
186118  }else{
186119  goto search_failed;
186120  }
186121  }else if( i<nNew && a[iOff+i]>pTerm[nMatch] ){
186122  goto search_failed;
186123  }
186124  }
186125 
186126  if( iPgidx>=n ){
186127  bEndOfPage = 1;
186128  break;
186129  }
186130 
186131  iPgidx += fts5GetVarint32(&a[iPgidx], nKeep);
186132  iTermOff += nKeep;
186133  iOff = iTermOff;
186134 
186135  /* Read the nKeep field of the next term. */
186136  fts5FastGetVarint32(a, iOff, nKeep);
186137  }
186138 
186139  search_failed:
186140  if( bGe==0 ){
186141  fts5DataRelease(pIter->pLeaf);
186142  pIter->pLeaf = 0;
186143  return;
186144  }else if( bEndOfPage ){
186145  do {
186146  fts5SegIterNextPage(p, pIter);
186147  if( pIter->pLeaf==0 ) return;
186148  a = pIter->pLeaf->p;
186149  if( fts5LeafIsTermless(pIter->pLeaf)==0 ){
186150  iPgidx = pIter->pLeaf->szLeaf;
186151  iPgidx += fts5GetVarint32(&pIter->pLeaf->p[iPgidx], iOff);
186152  if( iOff<4 || iOff>=pIter->pLeaf->szLeaf ){
186153  p->rc = FTS5_CORRUPT;
186154  }else{
186155  nKeep = 0;
186156  iTermOff = iOff;
186157  n = pIter->pLeaf->nn;
186158  iOff += fts5GetVarint32(&a[iOff], nNew);
186159  break;
186160  }
186161  }
186162  }while( 1 );
186163  }
186164 
186165  search_success:
186166 
186167  pIter->iLeafOffset = iOff + nNew;
186168  pIter->iTermLeafOffset = pIter->iLeafOffset;
186169  pIter->iTermLeafPgno = pIter->iLeafPgno;
186170 
186171  fts5BufferSet(&p->rc, &pIter->term, nKeep, pTerm);
186172  fts5BufferAppendBlob(&p->rc, &pIter->term, nNew, &a[iOff]);
186173 
186174  if( iPgidx>=n ){
186175  pIter->iEndofDoclist = pIter->pLeaf->nn+1;
186176  }else{
186177  int nExtra;
186178  iPgidx += fts5GetVarint32(&a[iPgidx], nExtra);
186179  pIter->iEndofDoclist = iTermOff + nExtra;
186180  }
186181  pIter->iPgidxOff = iPgidx;
186182 
186183  fts5SegIterLoadRowid(p, pIter);
186184  fts5SegIterLoadNPos(p, pIter);
186185 }
186186 
186187 static sqlite3_stmt *fts5IdxSelectStmt(Fts5Index *p){
186188  if( p->pIdxSelect==0 ){
186189  Fts5Config *pConfig = p->pConfig;
186190  fts5IndexPrepareStmt(p, &p->pIdxSelect, sqlite3_mprintf(
186191  "SELECT pgno FROM '%q'.'%q_idx' WHERE "
186192  "segid=? AND term<=? ORDER BY term DESC LIMIT 1",
186193  pConfig->zDb, pConfig->zName
186194  ));
186195  }
186196  return p->pIdxSelect;
186197 }
186198 
186199 /*
186200 ** Initialize the object pIter to point to term pTerm/nTerm within segment
186201 ** pSeg. If there is no such term in the index, the iterator is set to EOF.
186202 **
186203 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
186204 ** an error has already occurred when this function is called, it is a no-op.
186205 */
186206 static void fts5SegIterSeekInit(
186207  Fts5Index *p, /* FTS5 backend */
186208  const u8 *pTerm, int nTerm, /* Term to seek to */
186209  int flags, /* Mask of FTS5INDEX_XXX flags */
186210  Fts5StructureSegment *pSeg, /* Description of segment */
186211  Fts5SegIter *pIter /* Object to populate */
186212 ){
186213  int iPg = 1;
186214  int bGe = (flags & FTS5INDEX_QUERY_SCAN);
186215  int bDlidx = 0; /* True if there is a doclist-index */
186216  sqlite3_stmt *pIdxSelect = 0;
186217 
186218  assert( bGe==0 || (flags & FTS5INDEX_QUERY_DESC)==0 );
186219  assert( pTerm && nTerm );
186220  memset(pIter, 0, sizeof(*pIter));
186221  pIter->pSeg = pSeg;
186222 
186223  /* This block sets stack variable iPg to the leaf page number that may
186224  ** contain term (pTerm/nTerm), if it is present in the segment. */
186225  pIdxSelect = fts5IdxSelectStmt(p);
186226  if( p->rc ) return;
186227  sqlite3_bind_int(pIdxSelect, 1, pSeg->iSegid);
186228  sqlite3_bind_blob(pIdxSelect, 2, pTerm, nTerm, SQLITE_STATIC);
186229  if( SQLITE_ROW==sqlite3_step(pIdxSelect) ){
186230  i64 val = sqlite3_column_int(pIdxSelect, 0);
186231  iPg = (int)(val>>1);
186232  bDlidx = (val & 0x0001);
186233  }
186234  p->rc = sqlite3_reset(pIdxSelect);
186235 
186236  if( iPg<pSeg->pgnoFirst ){
186237  iPg = pSeg->pgnoFirst;
186238  bDlidx = 0;
186239  }
186240 
186241  pIter->iLeafPgno = iPg - 1;
186242  fts5SegIterNextPage(p, pIter);
186243 
186244  if( pIter->pLeaf ){
186245  fts5LeafSeek(p, bGe, pIter, pTerm, nTerm);
186246  }
186247 
186248  if( p->rc==SQLITE_OK && bGe==0 ){
186249  pIter->flags |= FTS5_SEGITER_ONETERM;
186250  if( pIter->pLeaf ){
186251  if( flags & FTS5INDEX_QUERY_DESC ){
186252  pIter->flags |= FTS5_SEGITER_REVERSE;
186253  }
186254  if( bDlidx ){
186255  fts5SegIterLoadDlidx(p, pIter);
186256  }
186257  if( flags & FTS5INDEX_QUERY_DESC ){
186258  fts5SegIterReverse(p, pIter);
186259  }
186260  }
186261  }
186262 
186263  fts5SegIterSetNext(p, pIter);
186264 
186265  /* Either:
186266  **
186267  ** 1) an error has occurred, or
186268  ** 2) the iterator points to EOF, or
186269  ** 3) the iterator points to an entry with term (pTerm/nTerm), or
186270  ** 4) the FTS5INDEX_QUERY_SCAN flag was set and the iterator points
186271  ** to an entry with a term greater than or equal to (pTerm/nTerm).
186272  */
186273  assert( p->rc!=SQLITE_OK /* 1 */
186274  || pIter->pLeaf==0 /* 2 */
186275  || fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)==0 /* 3 */
186276  || (bGe && fts5BufferCompareBlob(&pIter->term, pTerm, nTerm)>0) /* 4 */
186277  );
186278 }
186279 
186280 /*
186281 ** Initialize the object pIter to point to term pTerm/nTerm within the
186282 ** in-memory hash table. If there is no such term in the hash-table, the
186283 ** iterator is set to EOF.
186284 **
186285 ** If an error occurs, Fts5Index.rc is set to an appropriate error code. If
186286 ** an error has already occurred when this function is called, it is a no-op.
186287 */
186288 static void fts5SegIterHashInit(
186289  Fts5Index *p, /* FTS5 backend */
186290  const u8 *pTerm, int nTerm, /* Term to seek to */
186291  int flags, /* Mask of FTS5INDEX_XXX flags */
186292  Fts5SegIter *pIter /* Object to populate */
186293 ){
186294  const u8 *pList = 0;
186295  int nList = 0;
186296  const u8 *z = 0;
186297  int n = 0;
186298 
186299  assert( p->pHash );
186300  assert( p->rc==SQLITE_OK );
186301 
186302  if( pTerm==0 || (flags & FTS5INDEX_QUERY_SCAN) ){
186303  p->rc = sqlite3Fts5HashScanInit(p->pHash, (const char*)pTerm, nTerm);
186304  sqlite3Fts5HashScanEntry(p->pHash, (const char**)&z, &pList, &nList);
186305  n = (z ? (int)strlen((const char*)z) : 0);
186306  }else{
186307  pIter->flags |= FTS5_SEGITER_ONETERM;
186308  sqlite3Fts5HashQuery(p->pHash, (const char*)pTerm, nTerm, &pList, &nList);
186309  z = pTerm;
186310  n = nTerm;
186311  }
186312 
186313  if( pList ){
186314  Fts5Data *pLeaf;
186315  sqlite3Fts5BufferSet(&p->rc, &pIter->term, n, z);
186316  pLeaf = fts5IdxMalloc(p, sizeof(Fts5Data));
186317  if( pLeaf==0 ) return;
186318  pLeaf->p = (u8*)pList;
186319  pLeaf->nn = pLeaf->szLeaf = nList;
186320  pIter->pLeaf = pLeaf;
186321  pIter->iLeafOffset = fts5GetVarint(pLeaf->p, (u64*)&pIter->iRowid);
186322  pIter->iEndofDoclist = pLeaf->nn;
186323 
186324  if( flags & FTS5INDEX_QUERY_DESC ){
186325  pIter->flags |= FTS5_SEGITER_REVERSE;
186326  fts5SegIterReverseInitPage(p, pIter);
186327  }else{
186328  fts5SegIterLoadNPos(p, pIter);
186329  }
186330  }
186331 
186332  fts5SegIterSetNext(p, pIter);
186333 }
186334 
186335 /*
186336 ** Zero the iterator passed as the only argument.
186337 */
186338 static void fts5SegIterClear(Fts5SegIter *pIter){
186339  fts5BufferFree(&pIter->term);
186340  fts5DataRelease(pIter->pLeaf);
186341  fts5DataRelease(pIter->pNextLeaf);
186342  fts5DlidxIterFree(pIter->pDlidx);
186343  sqlite3_free(pIter->aRowidOffset);
186344  memset(pIter, 0, sizeof(Fts5SegIter));
186345 }
186346 
186347 #ifdef SQLITE_DEBUG
186348 
186349 /*
186350 ** This function is used as part of the big assert() procedure implemented by
186351 ** fts5AssertMultiIterSetup(). It ensures that the result currently stored
186352 ** in *pRes is the correct result of comparing the current positions of the
186353 ** two iterators.
186354 */
186355 static void fts5AssertComparisonResult(
186356  Fts5Iter *pIter,
186357  Fts5SegIter *p1,
186358  Fts5SegIter *p2,
186359  Fts5CResult *pRes
186360 ){
186361  int i1 = p1 - pIter->aSeg;
186362  int i2 = p2 - pIter->aSeg;
186363 
186364  if( p1->pLeaf || p2->pLeaf ){
186365  if( p1->pLeaf==0 ){
186366  assert( pRes->iFirst==i2 );
186367  }else if( p2->pLeaf==0 ){
186368  assert( pRes->iFirst==i1 );
186369  }else{
186370  int nMin = MIN(p1->term.n, p2->term.n);
186371  int res = memcmp(p1->term.p, p2->term.p, nMin);
186372  if( res==0 ) res = p1->term.n - p2->term.n;
186373 
186374  if( res==0 ){
186375  assert( pRes->bTermEq==1 );
186376  assert( p1->iRowid!=p2->iRowid );
186377  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : 1;
186378  }else{
186379  assert( pRes->bTermEq==0 );
186380  }
186381 
186382  if( res<0 ){
186383  assert( pRes->iFirst==i1 );
186384  }else{
186385  assert( pRes->iFirst==i2 );
186386  }
186387  }
186388  }
186389 }
186390 
186391 /*
186392 ** This function is a no-op unless SQLITE_DEBUG is defined when this module
186393 ** is compiled. In that case, this function is essentially an assert()
186394 ** statement used to verify that the contents of the pIter->aFirst[] array
186395 ** are correct.
186396 */
186397 static void fts5AssertMultiIterSetup(Fts5Index *p, Fts5Iter *pIter){
186398  if( p->rc==SQLITE_OK ){
186399  Fts5SegIter *pFirst = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
186400  int i;
186401 
186402  assert( (pFirst->pLeaf==0)==pIter->base.bEof );
186403 
186404  /* Check that pIter->iSwitchRowid is set correctly. */
186405  for(i=0; i<pIter->nSeg; i++){
186406  Fts5SegIter *p1 = &pIter->aSeg[i];
186407  assert( p1==pFirst
186408  || p1->pLeaf==0
186409  || fts5BufferCompare(&pFirst->term, &p1->term)
186410  || p1->iRowid==pIter->iSwitchRowid
186411  || (p1->iRowid<pIter->iSwitchRowid)==pIter->bRev
186412  );
186413  }
186414 
186415  for(i=0; i<pIter->nSeg; i+=2){
186416  Fts5SegIter *p1 = &pIter->aSeg[i];
186417  Fts5SegIter *p2 = &pIter->aSeg[i+1];
186418  Fts5CResult *pRes = &pIter->aFirst[(pIter->nSeg + i) / 2];
186419  fts5AssertComparisonResult(pIter, p1, p2, pRes);
186420  }
186421 
186422  for(i=1; i<(pIter->nSeg / 2); i+=2){
186423  Fts5SegIter *p1 = &pIter->aSeg[ pIter->aFirst[i*2].iFirst ];
186424  Fts5SegIter *p2 = &pIter->aSeg[ pIter->aFirst[i*2+1].iFirst ];
186425  Fts5CResult *pRes = &pIter->aFirst[i];
186426  fts5AssertComparisonResult(pIter, p1, p2, pRes);
186427  }
186428  }
186429 }
186430 #else
186431 # define fts5AssertMultiIterSetup(x,y)
186432 #endif
186433 
186434 /*
186435 ** Do the comparison necessary to populate pIter->aFirst[iOut].
186436 **
186437 ** If the returned value is non-zero, then it is the index of an entry
186438 ** in the pIter->aSeg[] array that is (a) not at EOF, and (b) pointing
186439 ** to a key that is a duplicate of another, higher priority,
186440 ** segment-iterator in the pSeg->aSeg[] array.
186441 */
186442 static int fts5MultiIterDoCompare(Fts5Iter *pIter, int iOut){
186443  int i1; /* Index of left-hand Fts5SegIter */
186444  int i2; /* Index of right-hand Fts5SegIter */
186445  int iRes;
186446  Fts5SegIter *p1; /* Left-hand Fts5SegIter */
186447  Fts5SegIter *p2; /* Right-hand Fts5SegIter */
186448  Fts5CResult *pRes = &pIter->aFirst[iOut];
186449 
186450  assert( iOut<pIter->nSeg && iOut>0 );
186451  assert( pIter->bRev==0 || pIter->bRev==1 );
186452 
186453  if( iOut>=(pIter->nSeg/2) ){
186454  i1 = (iOut - pIter->nSeg/2) * 2;
186455  i2 = i1 + 1;
186456  }else{
186457  i1 = pIter->aFirst[iOut*2].iFirst;
186458  i2 = pIter->aFirst[iOut*2+1].iFirst;
186459  }
186460  p1 = &pIter->aSeg[i1];
186461  p2 = &pIter->aSeg[i2];
186462 
186463  pRes->bTermEq = 0;
186464  if( p1->pLeaf==0 ){ /* If p1 is at EOF */
186465  iRes = i2;
186466  }else if( p2->pLeaf==0 ){ /* If p2 is at EOF */
186467  iRes = i1;
186468  }else{
186469  int res = fts5BufferCompare(&p1->term, &p2->term);
186470  if( res==0 ){
186471  assert( i2>i1 );
186472  assert( i2!=0 );
186473  pRes->bTermEq = 1;
186474  if( p1->iRowid==p2->iRowid ){
186475  p1->bDel = p2->bDel;
186476  return i2;
186477  }
186478  res = ((p1->iRowid > p2->iRowid)==pIter->bRev) ? -1 : +1;
186479  }
186480  assert( res!=0 );
186481  if( res<0 ){
186482  iRes = i1;
186483  }else{
186484  iRes = i2;
186485  }
186486  }
186487 
186488  pRes->iFirst = (u16)iRes;
186489  return 0;
186490 }
186491 
186492 /*
186493 ** Move the seg-iter so that it points to the first rowid on page iLeafPgno.
186494 ** It is an error if leaf iLeafPgno does not exist or contains no rowids.
186495 */
186496 static void fts5SegIterGotoPage(
186497  Fts5Index *p, /* FTS5 backend object */
186498  Fts5SegIter *pIter, /* Iterator to advance */
186499  int iLeafPgno
186500 ){
186501  assert( iLeafPgno>pIter->iLeafPgno );
186502 
186503  if( iLeafPgno>pIter->pSeg->pgnoLast ){
186504  p->rc = FTS5_CORRUPT;
186505  }else{
186506  fts5DataRelease(pIter->pNextLeaf);
186507  pIter->pNextLeaf = 0;
186508  pIter->iLeafPgno = iLeafPgno-1;
186509  fts5SegIterNextPage(p, pIter);
186510  assert( p->rc!=SQLITE_OK || pIter->iLeafPgno==iLeafPgno );
186511 
186512  if( p->rc==SQLITE_OK ){
186513  int iOff;
186514  u8 *a = pIter->pLeaf->p;
186515  int n = pIter->pLeaf->szLeaf;
186516 
186517  iOff = fts5LeafFirstRowidOff(pIter->pLeaf);
186518  if( iOff<4 || iOff>=n ){
186519  p->rc = FTS5_CORRUPT;
186520  }else{
186521  iOff += fts5GetVarint(&a[iOff], (u64*)&pIter->iRowid);
186522  pIter->iLeafOffset = iOff;
186523  fts5SegIterLoadNPos(p, pIter);
186524  }
186525  }
186526  }
186527 }
186528 
186529 /*
186530 ** Advance the iterator passed as the second argument until it is at or
186531 ** past rowid iFrom. Regardless of the value of iFrom, the iterator is
186532 ** always advanced at least once.
186533 */
186534 static void fts5SegIterNextFrom(
186535  Fts5Index *p, /* FTS5 backend object */
186536  Fts5SegIter *pIter, /* Iterator to advance */
186537  i64 iMatch /* Advance iterator at least this far */
186538 ){
186539  int bRev = (pIter->flags & FTS5_SEGITER_REVERSE);
186540  Fts5DlidxIter *pDlidx = pIter->pDlidx;
186541  int iLeafPgno = pIter->iLeafPgno;
186542  int bMove = 1;
186543 
186544  assert( pIter->flags & FTS5_SEGITER_ONETERM );
186545  assert( pIter->pDlidx );
186546  assert( pIter->pLeaf );
186547 
186548  if( bRev==0 ){
186549  while( !fts5DlidxIterEof(p, pDlidx) && iMatch>fts5DlidxIterRowid(pDlidx) ){
186550  iLeafPgno = fts5DlidxIterPgno(pDlidx);
186551  fts5DlidxIterNext(p, pDlidx);
186552  }
186553  assert_nc( iLeafPgno>=pIter->iLeafPgno || p->rc );
186554  if( iLeafPgno>pIter->iLeafPgno ){
186555  fts5SegIterGotoPage(p, pIter, iLeafPgno);
186556  bMove = 0;
186557  }
186558  }else{
186559  assert( pIter->pNextLeaf==0 );
186560  assert( iMatch<pIter->iRowid );
186561  while( !fts5DlidxIterEof(p, pDlidx) && iMatch<fts5DlidxIterRowid(pDlidx) ){
186562  fts5DlidxIterPrev(p, pDlidx);
186563  }
186564  iLeafPgno = fts5DlidxIterPgno(pDlidx);
186565 
186566  assert( fts5DlidxIterEof(p, pDlidx) || iLeafPgno<=pIter->iLeafPgno );
186567 
186568  if( iLeafPgno<pIter->iLeafPgno ){
186569  pIter->iLeafPgno = iLeafPgno+1;
186570  fts5SegIterReverseNewPage(p, pIter);
186571  bMove = 0;
186572  }
186573  }
186574 
186575  do{
186576  if( bMove && p->rc==SQLITE_OK ) pIter->xNext(p, pIter, 0);
186577  if( pIter->pLeaf==0 ) break;
186578  if( bRev==0 && pIter->iRowid>=iMatch ) break;
186579  if( bRev!=0 && pIter->iRowid<=iMatch ) break;
186580  bMove = 1;
186581  }while( p->rc==SQLITE_OK );
186582 }
186583 
186584 
186585 /*
186586 ** Free the iterator object passed as the second argument.
186587 */
186588 static void fts5MultiIterFree(Fts5Iter *pIter){
186589  if( pIter ){
186590  int i;
186591  for(i=0; i<pIter->nSeg; i++){
186592  fts5SegIterClear(&pIter->aSeg[i]);
186593  }
186594  fts5StructureRelease(pIter->pStruct);
186595  fts5BufferFree(&pIter->poslist);
186596  sqlite3_free(pIter);
186597  }
186598 }
186599 
186600 static void fts5MultiIterAdvanced(
186601  Fts5Index *p, /* FTS5 backend to iterate within */
186602  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
186603  int iChanged, /* Index of sub-iterator just advanced */
186604  int iMinset /* Minimum entry in aFirst[] to set */
186605 ){
186606  int i;
186607  for(i=(pIter->nSeg+iChanged)/2; i>=iMinset && p->rc==SQLITE_OK; i=i/2){
186608  int iEq;
186609  if( (iEq = fts5MultiIterDoCompare(pIter, i)) ){
186610  Fts5SegIter *pSeg = &pIter->aSeg[iEq];
186611  assert( p->rc==SQLITE_OK );
186612  pSeg->xNext(p, pSeg, 0);
186613  i = pIter->nSeg + iEq;
186614  }
186615  }
186616 }
186617 
186618 /*
186619 ** Sub-iterator iChanged of iterator pIter has just been advanced. It still
186620 ** points to the same term though - just a different rowid. This function
186621 ** attempts to update the contents of the pIter->aFirst[] accordingly.
186622 ** If it does so successfully, 0 is returned. Otherwise 1.
186623 **
186624 ** If non-zero is returned, the caller should call fts5MultiIterAdvanced()
186625 ** on the iterator instead. That function does the same as this one, except
186626 ** that it deals with more complicated cases as well.
186627 */
186628 static int fts5MultiIterAdvanceRowid(
186629  Fts5Iter *pIter, /* Iterator to update aFirst[] array for */
186630  int iChanged, /* Index of sub-iterator just advanced */
186631  Fts5SegIter **ppFirst
186632 ){
186633  Fts5SegIter *pNew = &pIter->aSeg[iChanged];
186634 
186635  if( pNew->iRowid==pIter->iSwitchRowid
186636  || (pNew->iRowid<pIter->iSwitchRowid)==pIter->bRev
186637  ){
186638  int i;
186639  Fts5SegIter *pOther = &pIter->aSeg[iChanged ^ 0x0001];
186640  pIter->iSwitchRowid = pIter->bRev ? SMALLEST_INT64 : LARGEST_INT64;
186641  for(i=(pIter->nSeg+iChanged)/2; 1; i=i/2){
186642  Fts5CResult *pRes = &pIter->aFirst[i];
186643 
186644  assert( pNew->pLeaf );
186645  assert( pRes->bTermEq==0 || pOther->pLeaf );
186646 
186647  if( pRes->bTermEq ){
186648  if( pNew->iRowid==pOther->iRowid ){
186649  return 1;
186650  }else if( (pOther->iRowid>pNew->iRowid)==pIter->bRev ){
186651  pIter->iSwitchRowid = pOther->iRowid;
186652  pNew = pOther;
186653  }else if( (pOther->iRowid>pIter->iSwitchRowid)==pIter->bRev ){
186654  pIter->iSwitchRowid = pOther->iRowid;
186655  }
186656  }
186657  pRes->iFirst = (u16)(pNew - pIter->aSeg);
186658  if( i==1 ) break;
186659 
186660  pOther = &pIter->aSeg[ pIter->aFirst[i ^ 0x0001].iFirst ];
186661  }
186662  }
186663 
186664  *ppFirst = pNew;
186665  return 0;
186666 }
186667 
186668 /*
186669 ** Set the pIter->bEof variable based on the state of the sub-iterators.
186670 */
186671 static void fts5MultiIterSetEof(Fts5Iter *pIter){
186672  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
186673  pIter->base.bEof = pSeg->pLeaf==0;
186674  pIter->iSwitchRowid = pSeg->iRowid;
186675 }
186676 
186677 /*
186678 ** Move the iterator to the next entry.
186679 **
186680 ** If an error occurs, an error code is left in Fts5Index.rc. It is not
186681 ** considered an error if the iterator reaches EOF, or if it is already at
186682 ** EOF when this function is called.
186683 */
186684 static void fts5MultiIterNext(
186685  Fts5Index *p,
186686  Fts5Iter *pIter,
186687  int bFrom, /* True if argument iFrom is valid */
186688  i64 iFrom /* Advance at least as far as this */
186689 ){
186690  int bUseFrom = bFrom;
186691  while( p->rc==SQLITE_OK ){
186692  int iFirst = pIter->aFirst[1].iFirst;
186693  int bNewTerm = 0;
186694  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
186695  assert( p->rc==SQLITE_OK );
186696  if( bUseFrom && pSeg->pDlidx ){
186697  fts5SegIterNextFrom(p, pSeg, iFrom);
186698  }else{
186699  pSeg->xNext(p, pSeg, &bNewTerm);
186700  }
186701 
186702  if( pSeg->pLeaf==0 || bNewTerm
186703  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
186704  ){
186705  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
186706  fts5MultiIterSetEof(pIter);
186707  pSeg = &pIter->aSeg[pIter->aFirst[1].iFirst];
186708  if( pSeg->pLeaf==0 ) return;
186709  }
186710 
186711  fts5AssertMultiIterSetup(p, pIter);
186712  assert( pSeg==&pIter->aSeg[pIter->aFirst[1].iFirst] && pSeg->pLeaf );
186713  if( pIter->bSkipEmpty==0 || pSeg->nPos ){
186714  pIter->xSetOutputs(pIter, pSeg);
186715  return;
186716  }
186717  bUseFrom = 0;
186718  }
186719 }
186720 
186721 static void fts5MultiIterNext2(
186722  Fts5Index *p,
186723  Fts5Iter *pIter,
186724  int *pbNewTerm /* OUT: True if *might* be new term */
186725 ){
186726  assert( pIter->bSkipEmpty );
186727  if( p->rc==SQLITE_OK ){
186728  do {
186729  int iFirst = pIter->aFirst[1].iFirst;
186730  Fts5SegIter *pSeg = &pIter->aSeg[iFirst];
186731  int bNewTerm = 0;
186732 
186733  assert( p->rc==SQLITE_OK );
186734  pSeg->xNext(p, pSeg, &bNewTerm);
186735  if( pSeg->pLeaf==0 || bNewTerm
186736  || fts5MultiIterAdvanceRowid(pIter, iFirst, &pSeg)
186737  ){
186738  fts5MultiIterAdvanced(p, pIter, iFirst, 1);
186739  fts5MultiIterSetEof(pIter);
186740  *pbNewTerm = 1;
186741  }else{
186742  *pbNewTerm = 0;
186743  }
186744  fts5AssertMultiIterSetup(p, pIter);
186745 
186746  }while( fts5MultiIterIsEmpty(p, pIter) );
186747  }
186748 }
186749 
186750 static void fts5IterSetOutputs_Noop(Fts5Iter *pUnused1, Fts5SegIter *pUnused2){
186751  UNUSED_PARAM2(pUnused1, pUnused2);
186752 }
186753 
186754 static Fts5Iter *fts5MultiIterAlloc(
186755  Fts5Index *p, /* FTS5 backend to iterate within */
186756  int nSeg
186757 ){
186758  Fts5Iter *pNew;
186759  int nSlot; /* Power of two >= nSeg */
186760 
186761  for(nSlot=2; nSlot<nSeg; nSlot=nSlot*2);
186762  pNew = fts5IdxMalloc(p,
186763  sizeof(Fts5Iter) + /* pNew */
186764  sizeof(Fts5SegIter) * (nSlot-1) + /* pNew->aSeg[] */
186765  sizeof(Fts5CResult) * nSlot /* pNew->aFirst[] */
186766  );
186767  if( pNew ){
186768  pNew->nSeg = nSlot;
186769  pNew->aFirst = (Fts5CResult*)&pNew->aSeg[nSlot];
186770  pNew->pIndex = p;
186771  pNew->xSetOutputs = fts5IterSetOutputs_Noop;
186772  }
186773  return pNew;
186774 }
186775 
186776 static void fts5PoslistCallback(
186777  Fts5Index *pUnused,
186778  void *pContext,
186779  const u8 *pChunk, int nChunk
186780 ){
186781  UNUSED_PARAM(pUnused);
186782  assert_nc( nChunk>=0 );
186783  if( nChunk>0 ){
186784  fts5BufferSafeAppendBlob((Fts5Buffer*)pContext, pChunk, nChunk);
186785  }
186786 }
186787 
186788 typedef struct PoslistCallbackCtx PoslistCallbackCtx;
186789 struct PoslistCallbackCtx {
186790  Fts5Buffer *pBuf; /* Append to this buffer */
186791  Fts5Colset *pColset; /* Restrict matches to this column */
186792  int eState; /* See above */
186793 };
186794 
186795 typedef struct PoslistOffsetsCtx PoslistOffsetsCtx;
186796 struct PoslistOffsetsCtx {
186797  Fts5Buffer *pBuf; /* Append to this buffer */
186798  Fts5Colset *pColset; /* Restrict matches to this column */
186799  int iRead;
186800  int iWrite;
186801 };
186802 
186803 /*
186804 ** TODO: Make this more efficient!
186805 */
186806 static int fts5IndexColsetTest(Fts5Colset *pColset, int iCol){
186807  int i;
186808  for(i=0; i<pColset->nCol; i++){
186809  if( pColset->aiCol[i]==iCol ) return 1;
186810  }
186811  return 0;
186812 }
186813 
186814 static void fts5PoslistOffsetsCallback(
186815  Fts5Index *pUnused,
186816  void *pContext,
186817  const u8 *pChunk, int nChunk
186818 ){
186819  PoslistOffsetsCtx *pCtx = (PoslistOffsetsCtx*)pContext;
186820  UNUSED_PARAM(pUnused);
186821  assert_nc( nChunk>=0 );
186822  if( nChunk>0 ){
186823  int i = 0;
186824  while( i<nChunk ){
186825  int iVal;
186826  i += fts5GetVarint32(&pChunk[i], iVal);
186827  iVal += pCtx->iRead - 2;
186828  pCtx->iRead = iVal;
186829  if( fts5IndexColsetTest(pCtx->pColset, iVal) ){
186830  fts5BufferSafeAppendVarint(pCtx->pBuf, iVal + 2 - pCtx->iWrite);
186831  pCtx->iWrite = iVal;
186832  }
186833  }
186834  }
186835 }
186836 
186837 static void fts5PoslistFilterCallback(
186838  Fts5Index *pUnused,
186839  void *pContext,
186840  const u8 *pChunk, int nChunk
186841 ){
186842  PoslistCallbackCtx *pCtx = (PoslistCallbackCtx*)pContext;
186843  UNUSED_PARAM(pUnused);
186844  assert_nc( nChunk>=0 );
186845  if( nChunk>0 ){
186846  /* Search through to find the first varint with value 1. This is the
186847  ** start of the next columns hits. */
186848  int i = 0;
186849  int iStart = 0;
186850 
186851  if( pCtx->eState==2 ){
186852  int iCol;
186853  fts5FastGetVarint32(pChunk, i, iCol);
186854  if( fts5IndexColsetTest(pCtx->pColset, iCol) ){
186855  pCtx->eState = 1;
186856  fts5BufferSafeAppendVarint(pCtx->pBuf, 1);
186857  }else{
186858  pCtx->eState = 0;
186859  }
186860  }
186861 
186862  do {
186863  while( i<nChunk && pChunk[i]!=0x01 ){
186864  while( pChunk[i] & 0x80 ) i++;
186865  i++;
186866  }
186867  if( pCtx->eState ){
186868  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
186869  }
186870  if( i<nChunk ){
186871  int iCol;
186872  iStart = i;
186873  i++;
186874  if( i>=nChunk ){
186875  pCtx->eState = 2;
186876  }else{
186877  fts5FastGetVarint32(pChunk, i, iCol);
186878  pCtx->eState = fts5IndexColsetTest(pCtx->pColset, iCol);
186879  if( pCtx->eState ){
186880  fts5BufferSafeAppendBlob(pCtx->pBuf, &pChunk[iStart], i-iStart);
186881  iStart = i;
186882  }
186883  }
186884  }
186885  }while( i<nChunk );
186886  }
186887 }
186888 
186889 static void fts5ChunkIterate(
186890  Fts5Index *p, /* Index object */
186891  Fts5SegIter *pSeg, /* Poslist of this iterator */
186892  void *pCtx, /* Context pointer for xChunk callback */
186893  void (*xChunk)(Fts5Index*, void*, const u8*, int)
186894 ){
186895  int nRem = pSeg->nPos; /* Number of bytes still to come */
186896  Fts5Data *pData = 0;
186897  u8 *pChunk = &pSeg->pLeaf->p[pSeg->iLeafOffset];
186898  int nChunk = MIN(nRem, pSeg->pLeaf->szLeaf - pSeg->iLeafOffset);
186899  int pgno = pSeg->iLeafPgno;
186900  int pgnoSave = 0;
186901 
186902  /* This function does notmwork with detail=none databases. */
186903  assert( p->pConfig->eDetail!=FTS5_DETAIL_NONE );
186904 
186905  if( (pSeg->flags & FTS5_SEGITER_REVERSE)==0 ){
186906  pgnoSave = pgno+1;
186907  }
186908 
186909  while( 1 ){
186910  xChunk(p, pCtx, pChunk, nChunk);
186911  nRem -= nChunk;
186912  fts5DataRelease(pData);
186913  if( nRem<=0 ){
186914  break;
186915  }else{
186916  pgno++;
186917  pData = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->pSeg->iSegid, pgno));
186918  if( pData==0 ) break;
186919  pChunk = &pData->p[4];
186920  nChunk = MIN(nRem, pData->szLeaf - 4);
186921  if( pgno==pgnoSave ){
186922  assert( pSeg->pNextLeaf==0 );
186923  pSeg->pNextLeaf = pData;
186924  pData = 0;
186925  }
186926  }
186927  }
186928 }
186929 
186930 /*
186931 ** Iterator pIter currently points to a valid entry (not EOF). This
186932 ** function appends the position list data for the current entry to
186933 ** buffer pBuf. It does not make a copy of the position-list size
186934 ** field.
186935 */
186936 static void fts5SegiterPoslist(
186937  Fts5Index *p,
186938  Fts5SegIter *pSeg,
186939  Fts5Colset *pColset,
186940  Fts5Buffer *pBuf
186941 ){
186942  if( 0==fts5BufferGrow(&p->rc, pBuf, pSeg->nPos) ){
186943  if( pColset==0 ){
186944  fts5ChunkIterate(p, pSeg, (void*)pBuf, fts5PoslistCallback);
186945  }else{
186946  if( p->pConfig->eDetail==FTS5_DETAIL_FULL ){
186947  PoslistCallbackCtx sCtx;
186948  sCtx.pBuf = pBuf;
186949  sCtx.pColset = pColset;
186950  sCtx.eState = fts5IndexColsetTest(pColset, 0);
186951  assert( sCtx.eState==0 || sCtx.eState==1 );
186952  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistFilterCallback);
186953  }else{
186954  PoslistOffsetsCtx sCtx;
186955  memset(&sCtx, 0, sizeof(sCtx));
186956  sCtx.pBuf = pBuf;
186957  sCtx.pColset = pColset;
186958  fts5ChunkIterate(p, pSeg, (void*)&sCtx, fts5PoslistOffsetsCallback);
186959  }
186960  }
186961  }
186962 }
186963 
186964 /*
186965 ** IN/OUT parameter (*pa) points to a position list n bytes in size. If
186966 ** the position list contains entries for column iCol, then (*pa) is set
186967 ** to point to the sub-position-list for that column and the number of
186968 ** bytes in it returned. Or, if the argument position list does not
186969 ** contain any entries for column iCol, return 0.
186970 */
186971 static int fts5IndexExtractCol(
186972  const u8 **pa, /* IN/OUT: Pointer to poslist */
186973  int n, /* IN: Size of poslist in bytes */
186974  int iCol /* Column to extract from poslist */
186975 ){
186976  int iCurrent = 0; /* Anything before the first 0x01 is col 0 */
186977  const u8 *p = *pa;
186978  const u8 *pEnd = &p[n]; /* One byte past end of position list */
186979 
186980  while( iCol>iCurrent ){
186981  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
186982  ** not part of a varint. Note that it is not possible for a negative
186983  ** or extremely large varint to occur within an uncorrupted position
186984  ** list. So the last byte of each varint may be assumed to have a clear
186985  ** 0x80 bit. */
186986  while( *p!=0x01 ){
186987  while( *p++ & 0x80 );
186988  if( p>=pEnd ) return 0;
186989  }
186990  *pa = p++;
186991  iCurrent = *p++;
186992  if( iCurrent & 0x80 ){
186993  p--;
186994  p += fts5GetVarint32(p, iCurrent);
186995  }
186996  }
186997  if( iCol!=iCurrent ) return 0;
186998 
186999  /* Advance pointer p until it points to pEnd or an 0x01 byte that is
187000  ** not part of a varint */
187001  while( p<pEnd && *p!=0x01 ){
187002  while( *p++ & 0x80 );
187003  }
187004 
187005  return p - (*pa);
187006 }
187007 
187008 static int fts5IndexExtractColset (
187009  Fts5Colset *pColset, /* Colset to filter on */
187010  const u8 *pPos, int nPos, /* Position list */
187011  Fts5Buffer *pBuf /* Output buffer */
187012 ){
187013  int rc = SQLITE_OK;
187014  int i;
187015 
187016  fts5BufferZero(pBuf);
187017  for(i=0; i<pColset->nCol; i++){
187018  const u8 *pSub = pPos;
187019  int nSub = fts5IndexExtractCol(&pSub, nPos, pColset->aiCol[i]);
187020  if( nSub ){
187021  fts5BufferAppendBlob(&rc, pBuf, nSub, pSub);
187022  }
187023  }
187024  return rc;
187025 }
187026 
187027 /*
187028 ** xSetOutputs callback used by detail=none tables.
187029 */
187030 static void fts5IterSetOutputs_None(Fts5Iter *pIter, Fts5SegIter *pSeg){
187031  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_NONE );
187032  pIter->base.iRowid = pSeg->iRowid;
187033  pIter->base.nData = pSeg->nPos;
187034 }
187035 
187036 /*
187037 ** xSetOutputs callback used by detail=full and detail=col tables when no
187038 ** column filters are specified.
187039 */
187040 static void fts5IterSetOutputs_Nocolset(Fts5Iter *pIter, Fts5SegIter *pSeg){
187041  pIter->base.iRowid = pSeg->iRowid;
187042  pIter->base.nData = pSeg->nPos;
187043 
187044  assert( pIter->pIndex->pConfig->eDetail!=FTS5_DETAIL_NONE );
187045  assert( pIter->pColset==0 );
187046 
187047  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
187048  /* All data is stored on the current page. Populate the output
187049  ** variables to point into the body of the page object. */
187050  pIter->base.pData = &pSeg->pLeaf->p[pSeg->iLeafOffset];
187051  }else{
187052  /* The data is distributed over two or more pages. Copy it into the
187053  ** Fts5Iter.poslist buffer and then set the output pointer to point
187054  ** to this buffer. */
187055  fts5BufferZero(&pIter->poslist);
187056  fts5SegiterPoslist(pIter->pIndex, pSeg, 0, &pIter->poslist);
187057  pIter->base.pData = pIter->poslist.p;
187058  }
187059 }
187060 
187061 /*
187062 ** xSetOutputs callback used by detail=col when there is a column filter
187063 ** and there are 100 or more columns. Also called as a fallback from
187064 ** fts5IterSetOutputs_Col100 if the column-list spans more than one page.
187065 */
187066 static void fts5IterSetOutputs_Col(Fts5Iter *pIter, Fts5SegIter *pSeg){
187067  fts5BufferZero(&pIter->poslist);
187068  fts5SegiterPoslist(pIter->pIndex, pSeg, pIter->pColset, &pIter->poslist);
187069  pIter->base.iRowid = pSeg->iRowid;
187070  pIter->base.pData = pIter->poslist.p;
187071  pIter->base.nData = pIter->poslist.n;
187072 }
187073 
187074 /*
187075 ** xSetOutputs callback used when:
187076 **
187077 ** * detail=col,
187078 ** * there is a column filter, and
187079 ** * the table contains 100 or fewer columns.
187080 **
187081 ** The last point is to ensure all column numbers are stored as
187082 ** single-byte varints.
187083 */
187084 static void fts5IterSetOutputs_Col100(Fts5Iter *pIter, Fts5SegIter *pSeg){
187085 
187086  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_COLUMNS );
187087  assert( pIter->pColset );
187088 
187089  if( pSeg->iLeafOffset+pSeg->nPos>pSeg->pLeaf->szLeaf ){
187090  fts5IterSetOutputs_Col(pIter, pSeg);
187091  }else{
187092  u8 *a = (u8*)&pSeg->pLeaf->p[pSeg->iLeafOffset];
187093  u8 *pEnd = (u8*)&a[pSeg->nPos];
187094  int iPrev = 0;
187095  int *aiCol = pIter->pColset->aiCol;
187096  int *aiColEnd = &aiCol[pIter->pColset->nCol];
187097 
187098  u8 *aOut = pIter->poslist.p;
187099  int iPrevOut = 0;
187100 
187101  pIter->base.iRowid = pSeg->iRowid;
187102 
187103  while( a<pEnd ){
187104  iPrev += (int)a++[0] - 2;
187105  while( *aiCol<iPrev ){
187106  aiCol++;
187107  if( aiCol==aiColEnd ) goto setoutputs_col_out;
187108  }
187109  if( *aiCol==iPrev ){
187110  *aOut++ = (u8)((iPrev - iPrevOut) + 2);
187111  iPrevOut = iPrev;
187112  }
187113  }
187114 
187115 setoutputs_col_out:
187116  pIter->base.pData = pIter->poslist.p;
187117  pIter->base.nData = aOut - pIter->poslist.p;
187118  }
187119 }
187120 
187121 /*
187122 ** xSetOutputs callback used by detail=full when there is a column filter.
187123 */
187124 static void fts5IterSetOutputs_Full(Fts5Iter *pIter, Fts5SegIter *pSeg){
187125  Fts5Colset *pColset = pIter->pColset;
187126  pIter->base.iRowid = pSeg->iRowid;
187127 
187128  assert( pIter->pIndex->pConfig->eDetail==FTS5_DETAIL_FULL );
187129  assert( pColset );
187130 
187131  if( pSeg->iLeafOffset+pSeg->nPos<=pSeg->pLeaf->szLeaf ){
187132  /* All data is stored on the current page. Populate the output
187133  ** variables to point into the body of the page object. */
187134  const u8 *a = &pSeg->pLeaf->p[pSeg->iLeafOffset];
187135  if( pColset->nCol==1 ){
187136  pIter->base.nData = fts5IndexExtractCol(&a, pSeg->nPos,pColset->aiCol[0]);
187137  pIter->base.pData = a;
187138  }else{
187139  fts5BufferZero(&pIter->poslist);
187140  fts5IndexExtractColset(pColset, a, pSeg->nPos, &pIter->poslist);
187141  pIter->base.pData = pIter->poslist.p;
187142  pIter->base.nData = pIter->poslist.n;
187143  }
187144  }else{
187145  /* The data is distributed over two or more pages. Copy it into the
187146  ** Fts5Iter.poslist buffer and then set the output pointer to point
187147  ** to this buffer. */
187148  fts5BufferZero(&pIter->poslist);
187149  fts5SegiterPoslist(pIter->pIndex, pSeg, pColset, &pIter->poslist);
187150  pIter->base.pData = pIter->poslist.p;
187151  pIter->base.nData = pIter->poslist.n;
187152  }
187153 }
187154 
187155 static void fts5IterSetOutputCb(int *pRc, Fts5Iter *pIter){
187156  if( *pRc==SQLITE_OK ){
187157  Fts5Config *pConfig = pIter->pIndex->pConfig;
187158  if( pConfig->eDetail==FTS5_DETAIL_NONE ){
187159  pIter->xSetOutputs = fts5IterSetOutputs_None;
187160  }
187161 
187162  else if( pIter->pColset==0 ){
187163  pIter->xSetOutputs = fts5IterSetOutputs_Nocolset;
187164  }
187165 
187166  else if( pConfig->eDetail==FTS5_DETAIL_FULL ){
187167  pIter->xSetOutputs = fts5IterSetOutputs_Full;
187168  }
187169 
187170  else{
187171  assert( pConfig->eDetail==FTS5_DETAIL_COLUMNS );
187172  if( pConfig->nCol<=100 ){
187173  pIter->xSetOutputs = fts5IterSetOutputs_Col100;
187174  sqlite3Fts5BufferSize(pRc, &pIter->poslist, pConfig->nCol);
187175  }else{
187176  pIter->xSetOutputs = fts5IterSetOutputs_Col;
187177  }
187178  }
187179  }
187180 }
187181 
187182 
187183 /*
187184 ** Allocate a new Fts5Iter object.
187185 **
187186 ** The new object will be used to iterate through data in structure pStruct.
187187 ** If iLevel is -ve, then all data in all segments is merged. Or, if iLevel
187188 ** is zero or greater, data from the first nSegment segments on level iLevel
187189 ** is merged.
187190 **
187191 ** The iterator initially points to the first term/rowid entry in the
187192 ** iterated data.
187193 */
187194 static void fts5MultiIterNew(
187195  Fts5Index *p, /* FTS5 backend to iterate within */
187196  Fts5Structure *pStruct, /* Structure of specific index */
187197  int flags, /* FTS5INDEX_QUERY_XXX flags */
187198  Fts5Colset *pColset, /* Colset to filter on (or NULL) */
187199  const u8 *pTerm, int nTerm, /* Term to seek to (or NULL/0) */
187200  int iLevel, /* Level to iterate (-1 for all) */
187201  int nSegment, /* Number of segments to merge (iLevel>=0) */
187202  Fts5Iter **ppOut /* New object */
187203 ){
187204  int nSeg = 0; /* Number of segment-iters in use */
187205  int iIter = 0; /* */
187206  int iSeg; /* Used to iterate through segments */
187207  Fts5StructureLevel *pLvl;
187208  Fts5Iter *pNew;
187209 
187210  assert( (pTerm==0 && nTerm==0) || iLevel<0 );
187211 
187212  /* Allocate space for the new multi-seg-iterator. */
187213  if( p->rc==SQLITE_OK ){
187214  if( iLevel<0 ){
187215  assert( pStruct->nSegment==fts5StructureCountSegments(pStruct) );
187216  nSeg = pStruct->nSegment;
187217  nSeg += (p->pHash ? 1 : 0);
187218  }else{
187219  nSeg = MIN(pStruct->aLevel[iLevel].nSeg, nSegment);
187220  }
187221  }
187222  *ppOut = pNew = fts5MultiIterAlloc(p, nSeg);
187223  if( pNew==0 ) return;
187224  pNew->bRev = (0!=(flags & FTS5INDEX_QUERY_DESC));
187225  pNew->bSkipEmpty = (0!=(flags & FTS5INDEX_QUERY_SKIPEMPTY));
187226  pNew->pStruct = pStruct;
187227  pNew->pColset = pColset;
187228  fts5StructureRef(pStruct);
187229  if( (flags & FTS5INDEX_QUERY_NOOUTPUT)==0 ){
187230  fts5IterSetOutputCb(&p->rc, pNew);
187231  }
187232 
187233  /* Initialize each of the component segment iterators. */
187234  if( p->rc==SQLITE_OK ){
187235  if( iLevel<0 ){
187236  Fts5StructureLevel *pEnd = &pStruct->aLevel[pStruct->nLevel];
187237  if( p->pHash ){
187238  /* Add a segment iterator for the current contents of the hash table. */
187239  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
187240  fts5SegIterHashInit(p, pTerm, nTerm, flags, pIter);
187241  }
187242  for(pLvl=&pStruct->aLevel[0]; pLvl<pEnd; pLvl++){
187243  for(iSeg=pLvl->nSeg-1; iSeg>=0; iSeg--){
187244  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
187245  Fts5SegIter *pIter = &pNew->aSeg[iIter++];
187246  if( pTerm==0 ){
187247  fts5SegIterInit(p, pSeg, pIter);
187248  }else{
187249  fts5SegIterSeekInit(p, pTerm, nTerm, flags, pSeg, pIter);
187250  }
187251  }
187252  }
187253  }else{
187254  pLvl = &pStruct->aLevel[iLevel];
187255  for(iSeg=nSeg-1; iSeg>=0; iSeg--){
187256  fts5SegIterInit(p, &pLvl->aSeg[iSeg], &pNew->aSeg[iIter++]);
187257  }
187258  }
187259  assert( iIter==nSeg );
187260  }
187261 
187262  /* If the above was successful, each component iterators now points
187263  ** to the first entry in its segment. In this case initialize the
187264  ** aFirst[] array. Or, if an error has occurred, free the iterator
187265  ** object and set the output variable to NULL. */
187266  if( p->rc==SQLITE_OK ){
187267  for(iIter=pNew->nSeg-1; iIter>0; iIter--){
187268  int iEq;
187269  if( (iEq = fts5MultiIterDoCompare(pNew, iIter)) ){
187270  Fts5SegIter *pSeg = &pNew->aSeg[iEq];
187271  if( p->rc==SQLITE_OK ) pSeg->xNext(p, pSeg, 0);
187272  fts5MultiIterAdvanced(p, pNew, iEq, iIter);
187273  }
187274  }
187275  fts5MultiIterSetEof(pNew);
187276  fts5AssertMultiIterSetup(p, pNew);
187277 
187278  if( pNew->bSkipEmpty && fts5MultiIterIsEmpty(p, pNew) ){
187279  fts5MultiIterNext(p, pNew, 0, 0);
187280  }else if( pNew->base.bEof==0 ){
187281  Fts5SegIter *pSeg = &pNew->aSeg[pNew->aFirst[1].iFirst];
187282  pNew->xSetOutputs(pNew, pSeg);
187283  }
187284 
187285  }else{
187286  fts5MultiIterFree(pNew);
187287  *ppOut = 0;
187288  }
187289 }
187290 
187291 /*
187292 ** Create an Fts5Iter that iterates through the doclist provided
187293 ** as the second argument.
187294 */
187295 static void fts5MultiIterNew2(
187296  Fts5Index *p, /* FTS5 backend to iterate within */
187297  Fts5Data *pData, /* Doclist to iterate through */
187298  int bDesc, /* True for descending rowid order */
187299  Fts5Iter **ppOut /* New object */
187300 ){
187301  Fts5Iter *pNew;
187302  pNew = fts5MultiIterAlloc(p, 2);
187303  if( pNew ){
187304  Fts5SegIter *pIter = &pNew->aSeg[1];
187305 
187306  pIter->flags = FTS5_SEGITER_ONETERM;
187307  if( pData->szLeaf>0 ){
187308  pIter->pLeaf = pData;
187309  pIter->iLeafOffset = fts5GetVarint(pData->p, (u64*)&pIter->iRowid);
187310  pIter->iEndofDoclist = pData->nn;
187311  pNew->aFirst[1].iFirst = 1;
187312  if( bDesc ){
187313  pNew->bRev = 1;
187314  pIter->flags |= FTS5_SEGITER_REVERSE;
187315  fts5SegIterReverseInitPage(p, pIter);
187316  }else{
187317  fts5SegIterLoadNPos(p, pIter);
187318  }
187319  pData = 0;
187320  }else{
187321  pNew->base.bEof = 1;
187322  }
187323  fts5SegIterSetNext(p, pIter);
187324 
187325  *ppOut = pNew;
187326  }
187327 
187328  fts5DataRelease(pData);
187329 }
187330 
187331 /*
187332 ** Return true if the iterator is at EOF or if an error has occurred.
187333 ** False otherwise.
187334 */
187335 static int fts5MultiIterEof(Fts5Index *p, Fts5Iter *pIter){
187336  assert( p->rc
187337  || (pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf==0)==pIter->base.bEof
187338  );
187339  return (p->rc || pIter->base.bEof);
187340 }
187341 
187342 /*
187343 ** Return the rowid of the entry that the iterator currently points
187344 ** to. If the iterator points to EOF when this function is called the
187345 ** results are undefined.
187346 */
187347 static i64 fts5MultiIterRowid(Fts5Iter *pIter){
187348  assert( pIter->aSeg[ pIter->aFirst[1].iFirst ].pLeaf );
187349  return pIter->aSeg[ pIter->aFirst[1].iFirst ].iRowid;
187350 }
187351 
187352 /*
187353 ** Move the iterator to the next entry at or following iMatch.
187354 */
187355 static void fts5MultiIterNextFrom(
187356  Fts5Index *p,
187357  Fts5Iter *pIter,
187358  i64 iMatch
187359 ){
187360  while( 1 ){
187361  i64 iRowid;
187362  fts5MultiIterNext(p, pIter, 1, iMatch);
187363  if( fts5MultiIterEof(p, pIter) ) break;
187364  iRowid = fts5MultiIterRowid(pIter);
187365  if( pIter->bRev==0 && iRowid>=iMatch ) break;
187366  if( pIter->bRev!=0 && iRowid<=iMatch ) break;
187367  }
187368 }
187369 
187370 /*
187371 ** Return a pointer to a buffer containing the term associated with the
187372 ** entry that the iterator currently points to.
187373 */
187374 static const u8 *fts5MultiIterTerm(Fts5Iter *pIter, int *pn){
187375  Fts5SegIter *p = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
187376  *pn = p->term.n;
187377  return p->term.p;
187378 }
187379 
187380 /*
187381 ** Allocate a new segment-id for the structure pStruct. The new segment
187382 ** id must be between 1 and 65335 inclusive, and must not be used by
187383 ** any currently existing segment. If a free segment id cannot be found,
187384 ** SQLITE_FULL is returned.
187385 **
187386 ** If an error has already occurred, this function is a no-op. 0 is
187387 ** returned in this case.
187388 */
187389 static int fts5AllocateSegid(Fts5Index *p, Fts5Structure *pStruct){
187390  int iSegid = 0;
187391 
187392  if( p->rc==SQLITE_OK ){
187393  if( pStruct->nSegment>=FTS5_MAX_SEGMENT ){
187394  p->rc = SQLITE_FULL;
187395  }else{
187396  /* FTS5_MAX_SEGMENT is currently defined as 2000. So the following
187397  ** array is 63 elements, or 252 bytes, in size. */
187398  u32 aUsed[(FTS5_MAX_SEGMENT+31) / 32];
187399  int iLvl, iSeg;
187400  int i;
187401  u32 mask;
187402  memset(aUsed, 0, sizeof(aUsed));
187403  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187404  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
187405  int iId = pStruct->aLevel[iLvl].aSeg[iSeg].iSegid;
187406  if( iId<=FTS5_MAX_SEGMENT ){
187407  aUsed[(iId-1) / 32] |= 1 << ((iId-1) % 32);
187408  }
187409  }
187410  }
187411 
187412  for(i=0; aUsed[i]==0xFFFFFFFF; i++);
187413  mask = aUsed[i];
187414  for(iSegid=0; mask & (1 << iSegid); iSegid++);
187415  iSegid += 1 + i*32;
187416 
187417 #ifdef SQLITE_DEBUG
187418  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
187419  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
187420  assert( iSegid!=pStruct->aLevel[iLvl].aSeg[iSeg].iSegid );
187421  }
187422  }
187423  assert( iSegid>0 && iSegid<=FTS5_MAX_SEGMENT );
187424 
187425  {
187426  sqlite3_stmt *pIdxSelect = fts5IdxSelectStmt(p);
187427  if( p->rc==SQLITE_OK ){
187428  u8 aBlob[2] = {0xff, 0xff};
187429  sqlite3_bind_int(pIdxSelect, 1, iSegid);
187430  sqlite3_bind_blob(pIdxSelect, 2, aBlob, 2, SQLITE_STATIC);
187431  assert( sqlite3_step(pIdxSelect)!=SQLITE_ROW );
187432  p->rc = sqlite3_reset(pIdxSelect);
187433  }
187434  }
187435 #endif
187436  }
187437  }
187438 
187439  return iSegid;
187440 }
187441 
187442 /*
187443 ** Discard all data currently cached in the hash-tables.
187444 */
187445 static void fts5IndexDiscardData(Fts5Index *p){
187446  assert( p->pHash || p->nPendingData==0 );
187447  if( p->pHash ){
187448  sqlite3Fts5HashClear(p->pHash);
187449  p->nPendingData = 0;
187450  }
187451 }
187452 
187453 /*
187454 ** Return the size of the prefix, in bytes, that buffer
187455 ** (pNew/<length-unknown>) shares with buffer (pOld/nOld).
187456 **
187457 ** Buffer (pNew/<length-unknown>) is guaranteed to be greater
187458 ** than buffer (pOld/nOld).
187459 */
187460 static int fts5PrefixCompress(int nOld, const u8 *pOld, const u8 *pNew){
187461  int i;
187462  for(i=0; i<nOld; i++){
187463  if( pOld[i]!=pNew[i] ) break;
187464  }
187465  return i;
187466 }
187467 
187468 static void fts5WriteDlidxClear(
187469  Fts5Index *p,
187470  Fts5SegWriter *pWriter,
187471  int bFlush /* If true, write dlidx to disk */
187472 ){
187473  int i;
187474  assert( bFlush==0 || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n>0) );
187475  for(i=0; i<pWriter->nDlidx; i++){
187476  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
187477  if( pDlidx->buf.n==0 ) break;
187478  if( bFlush ){
187479  assert( pDlidx->pgno!=0 );
187480  fts5DataWrite(p,
187481  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
187482  pDlidx->buf.p, pDlidx->buf.n
187483  );
187484  }
187485  sqlite3Fts5BufferZero(&pDlidx->buf);
187486  pDlidx->bPrevValid = 0;
187487  }
187488 }
187489 
187490 /*
187491 ** Grow the pWriter->aDlidx[] array to at least nLvl elements in size.
187492 ** Any new array elements are zeroed before returning.
187493 */
187494 static int fts5WriteDlidxGrow(
187495  Fts5Index *p,
187496  Fts5SegWriter *pWriter,
187497  int nLvl
187498 ){
187499  if( p->rc==SQLITE_OK && nLvl>=pWriter->nDlidx ){
187500  Fts5DlidxWriter *aDlidx = (Fts5DlidxWriter*)sqlite3_realloc(
187501  pWriter->aDlidx, sizeof(Fts5DlidxWriter) * nLvl
187502  );
187503  if( aDlidx==0 ){
187504  p->rc = SQLITE_NOMEM;
187505  }else{
187506  int nByte = sizeof(Fts5DlidxWriter) * (nLvl - pWriter->nDlidx);
187507  memset(&aDlidx[pWriter->nDlidx], 0, nByte);
187508  pWriter->aDlidx = aDlidx;
187509  pWriter->nDlidx = nLvl;
187510  }
187511  }
187512  return p->rc;
187513 }
187514 
187515 /*
187516 ** If the current doclist-index accumulating in pWriter->aDlidx[] is large
187517 ** enough, flush it to disk and return 1. Otherwise discard it and return
187518 ** zero.
187519 */
187520 static int fts5WriteFlushDlidx(Fts5Index *p, Fts5SegWriter *pWriter){
187521  int bFlag = 0;
187522 
187523  /* If there were FTS5_MIN_DLIDX_SIZE or more empty leaf pages written
187524  ** to the database, also write the doclist-index to disk. */
187525  if( pWriter->aDlidx[0].buf.n>0 && pWriter->nEmpty>=FTS5_MIN_DLIDX_SIZE ){
187526  bFlag = 1;
187527  }
187528  fts5WriteDlidxClear(p, pWriter, bFlag);
187529  pWriter->nEmpty = 0;
187530  return bFlag;
187531 }
187532 
187533 /*
187534 ** This function is called whenever processing of the doclist for the
187535 ** last term on leaf page (pWriter->iBtPage) is completed.
187536 **
187537 ** The doclist-index for that term is currently stored in-memory within the
187538 ** Fts5SegWriter.aDlidx[] array. If it is large enough, this function
187539 ** writes it out to disk. Or, if it is too small to bother with, discards
187540 ** it.
187541 **
187542 ** Fts5SegWriter.btterm currently contains the first term on page iBtPage.
187543 */
187544 static void fts5WriteFlushBtree(Fts5Index *p, Fts5SegWriter *pWriter){
187545  int bFlag;
187546 
187547  assert( pWriter->iBtPage || pWriter->nEmpty==0 );
187548  if( pWriter->iBtPage==0 ) return;
187549  bFlag = fts5WriteFlushDlidx(p, pWriter);
187550 
187551  if( p->rc==SQLITE_OK ){
187552  const char *z = (pWriter->btterm.n>0?(const char*)pWriter->btterm.p:"");
187553  /* The following was already done in fts5WriteInit(): */
187554  /* sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid); */
187555  sqlite3_bind_blob(p->pIdxWriter, 2, z, pWriter->btterm.n, SQLITE_STATIC);
187556  sqlite3_bind_int64(p->pIdxWriter, 3, bFlag + ((i64)pWriter->iBtPage<<1));
187557  sqlite3_step(p->pIdxWriter);
187558  p->rc = sqlite3_reset(p->pIdxWriter);
187559  }
187560  pWriter->iBtPage = 0;
187561 }
187562 
187563 /*
187564 ** This is called once for each leaf page except the first that contains
187565 ** at least one term. Argument (nTerm/pTerm) is the split-key - a term that
187566 ** is larger than all terms written to earlier leaves, and equal to or
187567 ** smaller than the first term on the new leaf.
187568 **
187569 ** If an error occurs, an error code is left in Fts5Index.rc. If an error
187570 ** has already occurred when this function is called, it is a no-op.
187571 */
187572 static void fts5WriteBtreeTerm(
187573  Fts5Index *p, /* FTS5 backend object */
187574  Fts5SegWriter *pWriter, /* Writer object */
187575  int nTerm, const u8 *pTerm /* First term on new page */
187576 ){
187577  fts5WriteFlushBtree(p, pWriter);
187578  fts5BufferSet(&p->rc, &pWriter->btterm, nTerm, pTerm);
187579  pWriter->iBtPage = pWriter->writer.pgno;
187580 }
187581 
187582 /*
187583 ** This function is called when flushing a leaf page that contains no
187584 ** terms at all to disk.
187585 */
187586 static void fts5WriteBtreeNoTerm(
187587  Fts5Index *p, /* FTS5 backend object */
187588  Fts5SegWriter *pWriter /* Writer object */
187589 ){
187590  /* If there were no rowids on the leaf page either and the doclist-index
187591  ** has already been started, append an 0x00 byte to it. */
187592  if( pWriter->bFirstRowidInPage && pWriter->aDlidx[0].buf.n>0 ){
187593  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[0];
187594  assert( pDlidx->bPrevValid );
187595  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, 0);
187596  }
187597 
187598  /* Increment the "number of sequential leaves without a term" counter. */
187599  pWriter->nEmpty++;
187600 }
187601 
187602 static i64 fts5DlidxExtractFirstRowid(Fts5Buffer *pBuf){
187603  i64 iRowid;
187604  int iOff;
187605 
187606  iOff = 1 + fts5GetVarint(&pBuf->p[1], (u64*)&iRowid);
187607  fts5GetVarint(&pBuf->p[iOff], (u64*)&iRowid);
187608  return iRowid;
187609 }
187610 
187611 /*
187612 ** Rowid iRowid has just been appended to the current leaf page. It is the
187613 ** first on the page. This function appends an appropriate entry to the current
187614 ** doclist-index.
187615 */
187616 static void fts5WriteDlidxAppend(
187617  Fts5Index *p,
187618  Fts5SegWriter *pWriter,
187619  i64 iRowid
187620 ){
187621  int i;
187622  int bDone = 0;
187623 
187624  for(i=0; p->rc==SQLITE_OK && bDone==0; i++){
187625  i64 iVal;
187626  Fts5DlidxWriter *pDlidx = &pWriter->aDlidx[i];
187627 
187628  if( pDlidx->buf.n>=p->pConfig->pgsz ){
187629  /* The current doclist-index page is full. Write it to disk and push
187630  ** a copy of iRowid (which will become the first rowid on the next
187631  ** doclist-index leaf page) up into the next level of the b-tree
187632  ** hierarchy. If the node being flushed is currently the root node,
187633  ** also push its first rowid upwards. */
187634  pDlidx->buf.p[0] = 0x01; /* Not the root node */
187635  fts5DataWrite(p,
187636  FTS5_DLIDX_ROWID(pWriter->iSegid, i, pDlidx->pgno),
187637  pDlidx->buf.p, pDlidx->buf.n
187638  );
187639  fts5WriteDlidxGrow(p, pWriter, i+2);
187640  pDlidx = &pWriter->aDlidx[i];
187641  if( p->rc==SQLITE_OK && pDlidx[1].buf.n==0 ){
187642  i64 iFirst = fts5DlidxExtractFirstRowid(&pDlidx->buf);
187643 
187644  /* This was the root node. Push its first rowid up to the new root. */
187645  pDlidx[1].pgno = pDlidx->pgno;
187646  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, 0);
187647  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, pDlidx->pgno);
187648  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx[1].buf, iFirst);
187649  pDlidx[1].bPrevValid = 1;
187650  pDlidx[1].iPrev = iFirst;
187651  }
187652 
187653  sqlite3Fts5BufferZero(&pDlidx->buf);
187654  pDlidx->bPrevValid = 0;
187655  pDlidx->pgno++;
187656  }else{
187657  bDone = 1;
187658  }
187659 
187660  if( pDlidx->bPrevValid ){
187661  iVal = iRowid - pDlidx->iPrev;
187662  }else{
187663  i64 iPgno = (i==0 ? pWriter->writer.pgno : pDlidx[-1].pgno);
187664  assert( pDlidx->buf.n==0 );
187665  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, !bDone);
187666  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iPgno);
187667  iVal = iRowid;
187668  }
187669 
187670  sqlite3Fts5BufferAppendVarint(&p->rc, &pDlidx->buf, iVal);
187671  pDlidx->bPrevValid = 1;
187672  pDlidx->iPrev = iRowid;
187673  }
187674 }
187675 
187676 static void fts5WriteFlushLeaf(Fts5Index *p, Fts5SegWriter *pWriter){
187677  static const u8 zero[] = { 0x00, 0x00, 0x00, 0x00 };
187678  Fts5PageWriter *pPage = &pWriter->writer;
187679  i64 iRowid;
187680 
187681 static int nCall = 0;
187682 nCall++;
187683 
187684  assert( (pPage->pgidx.n==0)==(pWriter->bFirstTermInPage) );
187685 
187686  /* Set the szLeaf header field. */
187687  assert( 0==fts5GetU16(&pPage->buf.p[2]) );
187688  fts5PutU16(&pPage->buf.p[2], (u16)pPage->buf.n);
187689 
187690  if( pWriter->bFirstTermInPage ){
187691  /* No term was written to this page. */
187692  assert( pPage->pgidx.n==0 );
187693  fts5WriteBtreeNoTerm(p, pWriter);
187694  }else{
187695  /* Append the pgidx to the page buffer. Set the szLeaf header field. */
187696  fts5BufferAppendBlob(&p->rc, &pPage->buf, pPage->pgidx.n, pPage->pgidx.p);
187697  }
187698 
187699  /* Write the page out to disk */
187700  iRowid = FTS5_SEGMENT_ROWID(pWriter->iSegid, pPage->pgno);
187701  fts5DataWrite(p, iRowid, pPage->buf.p, pPage->buf.n);
187702 
187703  /* Initialize the next page. */
187704  fts5BufferZero(&pPage->buf);
187705  fts5BufferZero(&pPage->pgidx);
187706  fts5BufferAppendBlob(&p->rc, &pPage->buf, 4, zero);
187707  pPage->iPrevPgidx = 0;
187708  pPage->pgno++;
187709 
187710  /* Increase the leaves written counter */
187711  pWriter->nLeafWritten++;
187712 
187713  /* The new leaf holds no terms or rowids */
187714  pWriter->bFirstTermInPage = 1;
187715  pWriter->bFirstRowidInPage = 1;
187716 }
187717 
187718 /*
187719 ** Append term pTerm/nTerm to the segment being written by the writer passed
187720 ** as the second argument.
187721 **
187722 ** If an error occurs, set the Fts5Index.rc error code. If an error has
187723 ** already occurred, this function is a no-op.
187724 */
187725 static void fts5WriteAppendTerm(
187726  Fts5Index *p,
187727  Fts5SegWriter *pWriter,
187728  int nTerm, const u8 *pTerm
187729 ){
187730  int nPrefix; /* Bytes of prefix compression for term */
187731  Fts5PageWriter *pPage = &pWriter->writer;
187732  Fts5Buffer *pPgidx = &pWriter->writer.pgidx;
187733 
187734  assert( p->rc==SQLITE_OK );
187735  assert( pPage->buf.n>=4 );
187736  assert( pPage->buf.n>4 || pWriter->bFirstTermInPage );
187737 
187738  /* If the current leaf page is full, flush it to disk. */
187739  if( (pPage->buf.n + pPgidx->n + nTerm + 2)>=p->pConfig->pgsz ){
187740  if( pPage->buf.n>4 ){
187741  fts5WriteFlushLeaf(p, pWriter);
187742  }
187743  fts5BufferGrow(&p->rc, &pPage->buf, nTerm+FTS5_DATA_PADDING);
187744  }
187745 
187746  /* TODO1: Updating pgidx here. */
187747  pPgidx->n += sqlite3Fts5PutVarint(
187748  &pPgidx->p[pPgidx->n], pPage->buf.n - pPage->iPrevPgidx
187749  );
187750  pPage->iPrevPgidx = pPage->buf.n;
187751 #if 0
187752  fts5PutU16(&pPgidx->p[pPgidx->n], pPage->buf.n);
187753  pPgidx->n += 2;
187754 #endif
187755 
187756  if( pWriter->bFirstTermInPage ){
187757  nPrefix = 0;
187758  if( pPage->pgno!=1 ){
187759  /* This is the first term on a leaf that is not the leftmost leaf in
187760  ** the segment b-tree. In this case it is necessary to add a term to
187761  ** the b-tree hierarchy that is (a) larger than the largest term
187762  ** already written to the segment and (b) smaller than or equal to
187763  ** this term. In other words, a prefix of (pTerm/nTerm) that is one
187764  ** byte longer than the longest prefix (pTerm/nTerm) shares with the
187765  ** previous term.
187766  **
187767  ** Usually, the previous term is available in pPage->term. The exception
187768  ** is if this is the first term written in an incremental-merge step.
187769  ** In this case the previous term is not available, so just write a
187770  ** copy of (pTerm/nTerm) into the parent node. This is slightly
187771  ** inefficient, but still correct. */
187772  int n = nTerm;
187773  if( pPage->term.n ){
187774  n = 1 + fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
187775  }
187776  fts5WriteBtreeTerm(p, pWriter, n, pTerm);
187777  pPage = &pWriter->writer;
187778  }
187779  }else{
187780  nPrefix = fts5PrefixCompress(pPage->term.n, pPage->term.p, pTerm);
187781  fts5BufferAppendVarint(&p->rc, &pPage->buf, nPrefix);
187782  }
187783 
187784  /* Append the number of bytes of new data, then the term data itself
187785  ** to the page. */
187786  fts5BufferAppendVarint(&p->rc, &pPage->buf, nTerm - nPrefix);
187787  fts5BufferAppendBlob(&p->rc, &pPage->buf, nTerm - nPrefix, &pTerm[nPrefix]);
187788 
187789  /* Update the Fts5PageWriter.term field. */
187790  fts5BufferSet(&p->rc, &pPage->term, nTerm, pTerm);
187791  pWriter->bFirstTermInPage = 0;
187792 
187793  pWriter->bFirstRowidInPage = 0;
187794  pWriter->bFirstRowidInDoclist = 1;
187795 
187796  assert( p->rc || (pWriter->nDlidx>0 && pWriter->aDlidx[0].buf.n==0) );
187797  pWriter->aDlidx[0].pgno = pPage->pgno;
187798 }
187799 
187800 /*
187801 ** Append a rowid and position-list size field to the writers output.
187802 */
187803 static void fts5WriteAppendRowid(
187804  Fts5Index *p,
187805  Fts5SegWriter *pWriter,
187806  i64 iRowid
187807 ){
187808  if( p->rc==SQLITE_OK ){
187809  Fts5PageWriter *pPage = &pWriter->writer;
187810 
187811  if( (pPage->buf.n + pPage->pgidx.n)>=p->pConfig->pgsz ){
187812  fts5WriteFlushLeaf(p, pWriter);
187813  }
187814 
187815  /* If this is to be the first rowid written to the page, set the
187816  ** rowid-pointer in the page-header. Also append a value to the dlidx
187817  ** buffer, in case a doclist-index is required. */
187818  if( pWriter->bFirstRowidInPage ){
187819  fts5PutU16(pPage->buf.p, (u16)pPage->buf.n);
187820  fts5WriteDlidxAppend(p, pWriter, iRowid);
187821  }
187822 
187823  /* Write the rowid. */
187824  if( pWriter->bFirstRowidInDoclist || pWriter->bFirstRowidInPage ){
187825  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid);
187826  }else{
187827  assert( p->rc || iRowid>pWriter->iPrevRowid );
187828  fts5BufferAppendVarint(&p->rc, &pPage->buf, iRowid - pWriter->iPrevRowid);
187829  }
187830  pWriter->iPrevRowid = iRowid;
187831  pWriter->bFirstRowidInDoclist = 0;
187832  pWriter->bFirstRowidInPage = 0;
187833  }
187834 }
187835 
187836 static void fts5WriteAppendPoslistData(
187837  Fts5Index *p,
187838  Fts5SegWriter *pWriter,
187839  const u8 *aData,
187840  int nData
187841 ){
187842  Fts5PageWriter *pPage = &pWriter->writer;
187843  const u8 *a = aData;
187844  int n = nData;
187845 
187846  assert( p->pConfig->pgsz>0 );
187847  while( p->rc==SQLITE_OK
187848  && (pPage->buf.n + pPage->pgidx.n + n)>=p->pConfig->pgsz
187849  ){
187850  int nReq = p->pConfig->pgsz - pPage->buf.n - pPage->pgidx.n;
187851  int nCopy = 0;
187852  while( nCopy<nReq ){
187853  i64 dummy;
187854  nCopy += fts5GetVarint(&a[nCopy], (u64*)&dummy);
187855  }
187856  fts5BufferAppendBlob(&p->rc, &pPage->buf, nCopy, a);
187857  a += nCopy;
187858  n -= nCopy;
187859  fts5WriteFlushLeaf(p, pWriter);
187860  }
187861  if( n>0 ){
187862  fts5BufferAppendBlob(&p->rc, &pPage->buf, n, a);
187863  }
187864 }
187865 
187866 /*
187867 ** Flush any data cached by the writer object to the database. Free any
187868 ** allocations associated with the writer.
187869 */
187870 static void fts5WriteFinish(
187871  Fts5Index *p,
187872  Fts5SegWriter *pWriter, /* Writer object */
187873  int *pnLeaf /* OUT: Number of leaf pages in b-tree */
187874 ){
187875  int i;
187876  Fts5PageWriter *pLeaf = &pWriter->writer;
187877  if( p->rc==SQLITE_OK ){
187878  assert( pLeaf->pgno>=1 );
187879  if( pLeaf->buf.n>4 ){
187880  fts5WriteFlushLeaf(p, pWriter);
187881  }
187882  *pnLeaf = pLeaf->pgno-1;
187883  if( pLeaf->pgno>1 ){
187884  fts5WriteFlushBtree(p, pWriter);
187885  }
187886  }
187887  fts5BufferFree(&pLeaf->term);
187888  fts5BufferFree(&pLeaf->buf);
187889  fts5BufferFree(&pLeaf->pgidx);
187890  fts5BufferFree(&pWriter->btterm);
187891 
187892  for(i=0; i<pWriter->nDlidx; i++){
187893  sqlite3Fts5BufferFree(&pWriter->aDlidx[i].buf);
187894  }
187895  sqlite3_free(pWriter->aDlidx);
187896 }
187897 
187898 static void fts5WriteInit(
187899  Fts5Index *p,
187900  Fts5SegWriter *pWriter,
187901  int iSegid
187902 ){
187903  const int nBuffer = p->pConfig->pgsz + FTS5_DATA_PADDING;
187904 
187905  memset(pWriter, 0, sizeof(Fts5SegWriter));
187906  pWriter->iSegid = iSegid;
187907 
187908  fts5WriteDlidxGrow(p, pWriter, 1);
187909  pWriter->writer.pgno = 1;
187910  pWriter->bFirstTermInPage = 1;
187911  pWriter->iBtPage = 1;
187912 
187913  assert( pWriter->writer.buf.n==0 );
187914  assert( pWriter->writer.pgidx.n==0 );
187915 
187916  /* Grow the two buffers to pgsz + padding bytes in size. */
187917  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.pgidx, nBuffer);
187918  sqlite3Fts5BufferSize(&p->rc, &pWriter->writer.buf, nBuffer);
187919 
187920  if( p->pIdxWriter==0 ){
187921  Fts5Config *pConfig = p->pConfig;
187922  fts5IndexPrepareStmt(p, &p->pIdxWriter, sqlite3_mprintf(
187923  "INSERT INTO '%q'.'%q_idx'(segid,term,pgno) VALUES(?,?,?)",
187924  pConfig->zDb, pConfig->zName
187925  ));
187926  }
187927 
187928  if( p->rc==SQLITE_OK ){
187929  /* Initialize the 4-byte leaf-page header to 0x00. */
187930  memset(pWriter->writer.buf.p, 0, 4);
187931  pWriter->writer.buf.n = 4;
187932 
187933  /* Bind the current output segment id to the index-writer. This is an
187934  ** optimization over binding the same value over and over as rows are
187935  ** inserted into %_idx by the current writer. */
187936  sqlite3_bind_int(p->pIdxWriter, 1, pWriter->iSegid);
187937  }
187938 }
187939 
187940 /*
187941 ** Iterator pIter was used to iterate through the input segments of on an
187942 ** incremental merge operation. This function is called if the incremental
187943 ** merge step has finished but the input has not been completely exhausted.
187944 */
187945 static void fts5TrimSegments(Fts5Index *p, Fts5Iter *pIter){
187946  int i;
187947  Fts5Buffer buf;
187948  memset(&buf, 0, sizeof(Fts5Buffer));
187949  for(i=0; i<pIter->nSeg; i++){
187950  Fts5SegIter *pSeg = &pIter->aSeg[i];
187951  if( pSeg->pSeg==0 ){
187952  /* no-op */
187953  }else if( pSeg->pLeaf==0 ){
187954  /* All keys from this input segment have been transfered to the output.
187955  ** Set both the first and last page-numbers to 0 to indicate that the
187956  ** segment is now empty. */
187957  pSeg->pSeg->pgnoLast = 0;
187958  pSeg->pSeg->pgnoFirst = 0;
187959  }else{
187960  int iOff = pSeg->iTermLeafOffset; /* Offset on new first leaf page */
187961  i64 iLeafRowid;
187962  Fts5Data *pData;
187963  int iId = pSeg->pSeg->iSegid;
187964  u8 aHdr[4] = {0x00, 0x00, 0x00, 0x00};
187965 
187966  iLeafRowid = FTS5_SEGMENT_ROWID(iId, pSeg->iTermLeafPgno);
187967  pData = fts5DataRead(p, iLeafRowid);
187968  if( pData ){
187969  fts5BufferZero(&buf);
187970  fts5BufferGrow(&p->rc, &buf, pData->nn);
187971  fts5BufferAppendBlob(&p->rc, &buf, sizeof(aHdr), aHdr);
187972  fts5BufferAppendVarint(&p->rc, &buf, pSeg->term.n);
187973  fts5BufferAppendBlob(&p->rc, &buf, pSeg->term.n, pSeg->term.p);
187974  fts5BufferAppendBlob(&p->rc, &buf, pData->szLeaf-iOff, &pData->p[iOff]);
187975  if( p->rc==SQLITE_OK ){
187976  /* Set the szLeaf field */
187977  fts5PutU16(&buf.p[2], (u16)buf.n);
187978  }
187979 
187980  /* Set up the new page-index array */
187981  fts5BufferAppendVarint(&p->rc, &buf, 4);
187982  if( pSeg->iLeafPgno==pSeg->iTermLeafPgno
187983  && pSeg->iEndofDoclist<pData->szLeaf
187984  ){
187985  int nDiff = pData->szLeaf - pSeg->iEndofDoclist;
187986  fts5BufferAppendVarint(&p->rc, &buf, buf.n - 1 - nDiff - 4);
187987  fts5BufferAppendBlob(&p->rc, &buf,
187988  pData->nn - pSeg->iPgidxOff, &pData->p[pSeg->iPgidxOff]
187989  );
187990  }
187991 
187992  fts5DataRelease(pData);
187993  pSeg->pSeg->pgnoFirst = pSeg->iTermLeafPgno;
187994  fts5DataDelete(p, FTS5_SEGMENT_ROWID(iId, 1), iLeafRowid);
187995  fts5DataWrite(p, iLeafRowid, buf.p, buf.n);
187996  }
187997  }
187998  }
187999  fts5BufferFree(&buf);
188000 }
188001 
188002 static void fts5MergeChunkCallback(
188003  Fts5Index *p,
188004  void *pCtx,
188005  const u8 *pChunk, int nChunk
188006 ){
188007  Fts5SegWriter *pWriter = (Fts5SegWriter*)pCtx;
188008  fts5WriteAppendPoslistData(p, pWriter, pChunk, nChunk);
188009 }
188010 
188011 /*
188012 **
188013 */
188014 static void fts5IndexMergeLevel(
188015  Fts5Index *p, /* FTS5 backend object */
188016  Fts5Structure **ppStruct, /* IN/OUT: Stucture of index */
188017  int iLvl, /* Level to read input from */
188018  int *pnRem /* Write up to this many output leaves */
188019 ){
188020  Fts5Structure *pStruct = *ppStruct;
188021  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
188022  Fts5StructureLevel *pLvlOut;
188023  Fts5Iter *pIter = 0; /* Iterator to read input data */
188024  int nRem = pnRem ? *pnRem : 0; /* Output leaf pages left to write */
188025  int nInput; /* Number of input segments */
188026  Fts5SegWriter writer; /* Writer object */
188027  Fts5StructureSegment *pSeg; /* Output segment */
188028  Fts5Buffer term;
188029  int bOldest; /* True if the output segment is the oldest */
188030  int eDetail = p->pConfig->eDetail;
188031  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
188032 
188033  assert( iLvl<pStruct->nLevel );
188034  assert( pLvl->nMerge<=pLvl->nSeg );
188035 
188036  memset(&writer, 0, sizeof(Fts5SegWriter));
188037  memset(&term, 0, sizeof(Fts5Buffer));
188038  if( pLvl->nMerge ){
188039  pLvlOut = &pStruct->aLevel[iLvl+1];
188040  assert( pLvlOut->nSeg>0 );
188041  nInput = pLvl->nMerge;
188042  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg-1];
188043 
188044  fts5WriteInit(p, &writer, pSeg->iSegid);
188045  writer.writer.pgno = pSeg->pgnoLast+1;
188046  writer.iBtPage = 0;
188047  }else{
188048  int iSegid = fts5AllocateSegid(p, pStruct);
188049 
188050  /* Extend the Fts5Structure object as required to ensure the output
188051  ** segment exists. */
188052  if( iLvl==pStruct->nLevel-1 ){
188053  fts5StructureAddLevel(&p->rc, ppStruct);
188054  pStruct = *ppStruct;
188055  }
188056  fts5StructureExtendLevel(&p->rc, pStruct, iLvl+1, 1, 0);
188057  if( p->rc ) return;
188058  pLvl = &pStruct->aLevel[iLvl];
188059  pLvlOut = &pStruct->aLevel[iLvl+1];
188060 
188061  fts5WriteInit(p, &writer, iSegid);
188062 
188063  /* Add the new segment to the output level */
188064  pSeg = &pLvlOut->aSeg[pLvlOut->nSeg];
188065  pLvlOut->nSeg++;
188066  pSeg->pgnoFirst = 1;
188067  pSeg->iSegid = iSegid;
188068  pStruct->nSegment++;
188069 
188070  /* Read input from all segments in the input level */
188071  nInput = pLvl->nSeg;
188072  }
188073  bOldest = (pLvlOut->nSeg==1 && pStruct->nLevel==iLvl+2);
188074 
188075  assert( iLvl>=0 );
188076  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, iLvl, nInput, &pIter);
188077  fts5MultiIterEof(p, pIter)==0;
188078  fts5MultiIterNext(p, pIter, 0, 0)
188079  ){
188080  Fts5SegIter *pSegIter = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
188081  int nPos; /* position-list size field value */
188082  int nTerm;
188083  const u8 *pTerm;
188084 
188085  /* Check for key annihilation. */
188086  if( pSegIter->nPos==0 && (bOldest || pSegIter->bDel==0) ) continue;
188087 
188088  pTerm = fts5MultiIterTerm(pIter, &nTerm);
188089  if( nTerm!=term.n || memcmp(pTerm, term.p, nTerm) ){
188090  if( pnRem && writer.nLeafWritten>nRem ){
188091  break;
188092  }
188093 
188094  /* This is a new term. Append a term to the output segment. */
188095  fts5WriteAppendTerm(p, &writer, nTerm, pTerm);
188096  fts5BufferSet(&p->rc, &term, nTerm, pTerm);
188097  }
188098 
188099  /* Append the rowid to the output */
188100  /* WRITEPOSLISTSIZE */
188101  fts5WriteAppendRowid(p, &writer, fts5MultiIterRowid(pIter));
188102 
188103  if( eDetail==FTS5_DETAIL_NONE ){
188104  if( pSegIter->bDel ){
188105  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
188106  if( pSegIter->nPos>0 ){
188107  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, 0);
188108  }
188109  }
188110  }else{
188111  /* Append the position-list data to the output */
188112  nPos = pSegIter->nPos*2 + pSegIter->bDel;
188113  fts5BufferAppendVarint(&p->rc, &writer.writer.buf, nPos);
188114  fts5ChunkIterate(p, pSegIter, (void*)&writer, fts5MergeChunkCallback);
188115  }
188116  }
188117 
188118  /* Flush the last leaf page to disk. Set the output segment b-tree height
188119  ** and last leaf page number at the same time. */
188120  fts5WriteFinish(p, &writer, &pSeg->pgnoLast);
188121 
188122  if( fts5MultiIterEof(p, pIter) ){
188123  int i;
188124 
188125  /* Remove the redundant segments from the %_data table */
188126  for(i=0; i<nInput; i++){
188127  fts5DataRemoveSegment(p, pLvl->aSeg[i].iSegid);
188128  }
188129 
188130  /* Remove the redundant segments from the input level */
188131  if( pLvl->nSeg!=nInput ){
188132  int nMove = (pLvl->nSeg - nInput) * sizeof(Fts5StructureSegment);
188133  memmove(pLvl->aSeg, &pLvl->aSeg[nInput], nMove);
188134  }
188135  pStruct->nSegment -= nInput;
188136  pLvl->nSeg -= nInput;
188137  pLvl->nMerge = 0;
188138  if( pSeg->pgnoLast==0 ){
188139  pLvlOut->nSeg--;
188140  pStruct->nSegment--;
188141  }
188142  }else{
188143  assert( pSeg->pgnoLast>0 );
188144  fts5TrimSegments(p, pIter);
188145  pLvl->nMerge = nInput;
188146  }
188147 
188148  fts5MultiIterFree(pIter);
188149  fts5BufferFree(&term);
188150  if( pnRem ) *pnRem -= writer.nLeafWritten;
188151 }
188152 
188153 /*
188154 ** Do up to nPg pages of automerge work on the index.
188155 **
188156 ** Return true if any changes were actually made, or false otherwise.
188157 */
188158 static int fts5IndexMerge(
188159  Fts5Index *p, /* FTS5 backend object */
188160  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
188161  int nPg, /* Pages of work to do */
188162  int nMin /* Minimum number of segments to merge */
188163 ){
188164  int nRem = nPg;
188165  int bRet = 0;
188166  Fts5Structure *pStruct = *ppStruct;
188167  while( nRem>0 && p->rc==SQLITE_OK ){
188168  int iLvl; /* To iterate through levels */
188169  int iBestLvl = 0; /* Level offering the most input segments */
188170  int nBest = 0; /* Number of input segments on best level */
188171 
188172  /* Set iBestLvl to the level to read input segments from. */
188173  assert( pStruct->nLevel>0 );
188174  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
188175  Fts5StructureLevel *pLvl = &pStruct->aLevel[iLvl];
188176  if( pLvl->nMerge ){
188177  if( pLvl->nMerge>nBest ){
188178  iBestLvl = iLvl;
188179  nBest = pLvl->nMerge;
188180  }
188181  break;
188182  }
188183  if( pLvl->nSeg>nBest ){
188184  nBest = pLvl->nSeg;
188185  iBestLvl = iLvl;
188186  }
188187  }
188188 
188189  /* If nBest is still 0, then the index must be empty. */
188190 #ifdef SQLITE_DEBUG
188191  for(iLvl=0; nBest==0 && iLvl<pStruct->nLevel; iLvl++){
188192  assert( pStruct->aLevel[iLvl].nSeg==0 );
188193  }
188194 #endif
188195 
188196  if( nBest<nMin && pStruct->aLevel[iBestLvl].nMerge==0 ){
188197  break;
188198  }
188199  bRet = 1;
188200  fts5IndexMergeLevel(p, &pStruct, iBestLvl, &nRem);
188201  if( p->rc==SQLITE_OK && pStruct->aLevel[iBestLvl].nMerge==0 ){
188202  fts5StructurePromote(p, iBestLvl+1, pStruct);
188203  }
188204  }
188205  *ppStruct = pStruct;
188206  return bRet;
188207 }
188208 
188209 /*
188210 ** A total of nLeaf leaf pages of data has just been flushed to a level-0
188211 ** segment. This function updates the write-counter accordingly and, if
188212 ** necessary, performs incremental merge work.
188213 **
188214 ** If an error occurs, set the Fts5Index.rc error code. If an error has
188215 ** already occurred, this function is a no-op.
188216 */
188217 static void fts5IndexAutomerge(
188218  Fts5Index *p, /* FTS5 backend object */
188219  Fts5Structure **ppStruct, /* IN/OUT: Current structure of index */
188220  int nLeaf /* Number of output leaves just written */
188221 ){
188222  if( p->rc==SQLITE_OK && p->pConfig->nAutomerge>0 ){
188223  Fts5Structure *pStruct = *ppStruct;
188224  u64 nWrite; /* Initial value of write-counter */
188225  int nWork; /* Number of work-quanta to perform */
188226  int nRem; /* Number of leaf pages left to write */
188227 
188228  /* Update the write-counter. While doing so, set nWork. */
188229  nWrite = pStruct->nWriteCounter;
188230  nWork = (int)(((nWrite + nLeaf) / p->nWorkUnit) - (nWrite / p->nWorkUnit));
188231  pStruct->nWriteCounter += nLeaf;
188232  nRem = (int)(p->nWorkUnit * nWork * pStruct->nLevel);
188233 
188234  fts5IndexMerge(p, ppStruct, nRem, p->pConfig->nAutomerge);
188235  }
188236 }
188237 
188238 static void fts5IndexCrisismerge(
188239  Fts5Index *p, /* FTS5 backend object */
188240  Fts5Structure **ppStruct /* IN/OUT: Current structure of index */
188241 ){
188242  const int nCrisis = p->pConfig->nCrisisMerge;
188243  Fts5Structure *pStruct = *ppStruct;
188244  int iLvl = 0;
188245 
188246  assert( p->rc!=SQLITE_OK || pStruct->nLevel>0 );
188247  while( p->rc==SQLITE_OK && pStruct->aLevel[iLvl].nSeg>=nCrisis ){
188248  fts5IndexMergeLevel(p, &pStruct, iLvl, 0);
188249  assert( p->rc!=SQLITE_OK || pStruct->nLevel>(iLvl+1) );
188250  fts5StructurePromote(p, iLvl+1, pStruct);
188251  iLvl++;
188252  }
188253  *ppStruct = pStruct;
188254 }
188255 
188256 static int fts5IndexReturn(Fts5Index *p){
188257  int rc = p->rc;
188258  p->rc = SQLITE_OK;
188259  return rc;
188260 }
188261 
188262 typedef struct Fts5FlushCtx Fts5FlushCtx;
188263 struct Fts5FlushCtx {
188264  Fts5Index *pIdx;
188265  Fts5SegWriter writer;
188266 };
188267 
188268 /*
188269 ** Buffer aBuf[] contains a list of varints, all small enough to fit
188270 ** in a 32-bit integer. Return the size of the largest prefix of this
188271 ** list nMax bytes or less in size.
188272 */
188273 static int fts5PoslistPrefix(const u8 *aBuf, int nMax){
188274  int ret;
188275  u32 dummy;
188276  ret = fts5GetVarint32(aBuf, dummy);
188277  if( ret<nMax ){
188278  while( 1 ){
188279  int i = fts5GetVarint32(&aBuf[ret], dummy);
188280  if( (ret + i) > nMax ) break;
188281  ret += i;
188282  }
188283  }
188284  return ret;
188285 }
188286 
188287 /*
188288 ** Flush the contents of in-memory hash table iHash to a new level-0
188289 ** segment on disk. Also update the corresponding structure record.
188290 **
188291 ** If an error occurs, set the Fts5Index.rc error code. If an error has
188292 ** already occurred, this function is a no-op.
188293 */
188294 static void fts5FlushOneHash(Fts5Index *p){
188295  Fts5Hash *pHash = p->pHash;
188296  Fts5Structure *pStruct;
188297  int iSegid;
188298  int pgnoLast = 0; /* Last leaf page number in segment */
188299 
188300  /* Obtain a reference to the index structure and allocate a new segment-id
188301  ** for the new level-0 segment. */
188302  pStruct = fts5StructureRead(p);
188303  iSegid = fts5AllocateSegid(p, pStruct);
188304  fts5StructureInvalidate(p);
188305 
188306  if( iSegid ){
188307  const int pgsz = p->pConfig->pgsz;
188308  int eDetail = p->pConfig->eDetail;
188309  Fts5StructureSegment *pSeg; /* New segment within pStruct */
188310  Fts5Buffer *pBuf; /* Buffer in which to assemble leaf page */
188311  Fts5Buffer *pPgidx; /* Buffer in which to assemble pgidx */
188312 
188313  Fts5SegWriter writer;
188314  fts5WriteInit(p, &writer, iSegid);
188315 
188316  pBuf = &writer.writer.buf;
188317  pPgidx = &writer.writer.pgidx;
188318 
188319  /* fts5WriteInit() should have initialized the buffers to (most likely)
188320  ** the maximum space required. */
188321  assert( p->rc || pBuf->nSpace>=(pgsz + FTS5_DATA_PADDING) );
188322  assert( p->rc || pPgidx->nSpace>=(pgsz + FTS5_DATA_PADDING) );
188323 
188324  /* Begin scanning through hash table entries. This loop runs once for each
188325  ** term/doclist currently stored within the hash table. */
188326  if( p->rc==SQLITE_OK ){
188327  p->rc = sqlite3Fts5HashScanInit(pHash, 0, 0);
188328  }
188329  while( p->rc==SQLITE_OK && 0==sqlite3Fts5HashScanEof(pHash) ){
188330  const char *zTerm; /* Buffer containing term */
188331  const u8 *pDoclist; /* Pointer to doclist for this term */
188332  int nDoclist; /* Size of doclist in bytes */
188333 
188334  /* Write the term for this entry to disk. */
188335  sqlite3Fts5HashScanEntry(pHash, &zTerm, &pDoclist, &nDoclist);
188336  fts5WriteAppendTerm(p, &writer, (int)strlen(zTerm), (const u8*)zTerm);
188337 
188338  assert( writer.bFirstRowidInPage==0 );
188339  if( pgsz>=(pBuf->n + pPgidx->n + nDoclist + 1) ){
188340  /* The entire doclist will fit on the current leaf. */
188341  fts5BufferSafeAppendBlob(pBuf, pDoclist, nDoclist);
188342  }else{
188343  i64 iRowid = 0;
188344  i64 iDelta = 0;
188345  int iOff = 0;
188346 
188347  /* The entire doclist will not fit on this leaf. The following
188348  ** loop iterates through the poslists that make up the current
188349  ** doclist. */
188350  while( p->rc==SQLITE_OK && iOff<nDoclist ){
188351  iOff += fts5GetVarint(&pDoclist[iOff], (u64*)&iDelta);
188352  iRowid += iDelta;
188353 
188354  if( writer.bFirstRowidInPage ){
188355  fts5PutU16(&pBuf->p[0], (u16)pBuf->n); /* first rowid on page */
188356  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iRowid);
188357  writer.bFirstRowidInPage = 0;
188358  fts5WriteDlidxAppend(p, &writer, iRowid);
188359  }else{
188360  pBuf->n += sqlite3Fts5PutVarint(&pBuf->p[pBuf->n], iDelta);
188361  }
188362  assert( pBuf->n<=pBuf->nSpace );
188363 
188364  if( eDetail==FTS5_DETAIL_NONE ){
188365  if( iOff<nDoclist && pDoclist[iOff]==0 ){
188366  pBuf->p[pBuf->n++] = 0;
188367  iOff++;
188368  if( iOff<nDoclist && pDoclist[iOff]==0 ){
188369  pBuf->p[pBuf->n++] = 0;
188370  iOff++;
188371  }
188372  }
188373  if( (pBuf->n + pPgidx->n)>=pgsz ){
188374  fts5WriteFlushLeaf(p, &writer);
188375  }
188376  }else{
188377  int bDummy;
188378  int nPos;
188379  int nCopy = fts5GetPoslistSize(&pDoclist[iOff], &nPos, &bDummy);
188380  nCopy += nPos;
188381  if( (pBuf->n + pPgidx->n + nCopy) <= pgsz ){
188382  /* The entire poslist will fit on the current leaf. So copy
188383  ** it in one go. */
188384  fts5BufferSafeAppendBlob(pBuf, &pDoclist[iOff], nCopy);
188385  }else{
188386  /* The entire poslist will not fit on this leaf. So it needs
188387  ** to be broken into sections. The only qualification being
188388  ** that each varint must be stored contiguously. */
188389  const u8 *pPoslist = &pDoclist[iOff];
188390  int iPos = 0;
188391  while( p->rc==SQLITE_OK ){
188392  int nSpace = pgsz - pBuf->n - pPgidx->n;
188393  int n = 0;
188394  if( (nCopy - iPos)<=nSpace ){
188395  n = nCopy - iPos;
188396  }else{
188397  n = fts5PoslistPrefix(&pPoslist[iPos], nSpace);
188398  }
188399  assert( n>0 );
188400  fts5BufferSafeAppendBlob(pBuf, &pPoslist[iPos], n);
188401  iPos += n;
188402  if( (pBuf->n + pPgidx->n)>=pgsz ){
188403  fts5WriteFlushLeaf(p, &writer);
188404  }
188405  if( iPos>=nCopy ) break;
188406  }
188407  }
188408  iOff += nCopy;
188409  }
188410  }
188411  }
188412 
188413  /* TODO2: Doclist terminator written here. */
188414  /* pBuf->p[pBuf->n++] = '\0'; */
188415  assert( pBuf->n<=pBuf->nSpace );
188416  sqlite3Fts5HashScanNext(pHash);
188417  }
188418  sqlite3Fts5HashClear(pHash);
188419  fts5WriteFinish(p, &writer, &pgnoLast);
188420 
188421  /* Update the Fts5Structure. It is written back to the database by the
188422  ** fts5StructureRelease() call below. */
188423  if( pStruct->nLevel==0 ){
188424  fts5StructureAddLevel(&p->rc, &pStruct);
188425  }
188426  fts5StructureExtendLevel(&p->rc, pStruct, 0, 1, 0);
188427  if( p->rc==SQLITE_OK ){
188428  pSeg = &pStruct->aLevel[0].aSeg[ pStruct->aLevel[0].nSeg++ ];
188429  pSeg->iSegid = iSegid;
188430  pSeg->pgnoFirst = 1;
188431  pSeg->pgnoLast = pgnoLast;
188432  pStruct->nSegment++;
188433  }
188434  fts5StructurePromote(p, 0, pStruct);
188435  }
188436 
188437  fts5IndexAutomerge(p, &pStruct, pgnoLast);
188438  fts5IndexCrisismerge(p, &pStruct);
188439  fts5StructureWrite(p, pStruct);
188440  fts5StructureRelease(pStruct);
188441 }
188442 
188443 /*
188444 ** Flush any data stored in the in-memory hash tables to the database.
188445 */
188446 static void fts5IndexFlush(Fts5Index *p){
188447  /* Unless it is empty, flush the hash table to disk */
188448  if( p->nPendingData ){
188449  assert( p->pHash );
188450  p->nPendingData = 0;
188451  fts5FlushOneHash(p);
188452  }
188453 }
188454 
188455 static Fts5Structure *fts5IndexOptimizeStruct(
188456  Fts5Index *p,
188457  Fts5Structure *pStruct
188458 ){
188459  Fts5Structure *pNew = 0;
188460  int nByte = sizeof(Fts5Structure);
188461  int nSeg = pStruct->nSegment;
188462  int i;
188463 
188464  /* Figure out if this structure requires optimization. A structure does
188465  ** not require optimization if either:
188466  **
188467  ** + it consists of fewer than two segments, or
188468  ** + all segments are on the same level, or
188469  ** + all segments except one are currently inputs to a merge operation.
188470  **
188471  ** In the first case, return NULL. In the second, increment the ref-count
188472  ** on *pStruct and return a copy of the pointer to it.
188473  */
188474  if( nSeg<2 ) return 0;
188475  for(i=0; i<pStruct->nLevel; i++){
188476  int nThis = pStruct->aLevel[i].nSeg;
188477  if( nThis==nSeg || (nThis==nSeg-1 && pStruct->aLevel[i].nMerge==nThis) ){
188478  fts5StructureRef(pStruct);
188479  return pStruct;
188480  }
188481  assert( pStruct->aLevel[i].nMerge<=nThis );
188482  }
188483 
188484  nByte += (pStruct->nLevel+1) * sizeof(Fts5StructureLevel);
188485  pNew = (Fts5Structure*)sqlite3Fts5MallocZero(&p->rc, nByte);
188486 
188487  if( pNew ){
188488  Fts5StructureLevel *pLvl;
188489  nByte = nSeg * sizeof(Fts5StructureSegment);
188490  pNew->nLevel = pStruct->nLevel+1;
188491  pNew->nRef = 1;
188492  pNew->nWriteCounter = pStruct->nWriteCounter;
188493  pLvl = &pNew->aLevel[pStruct->nLevel];
188494  pLvl->aSeg = (Fts5StructureSegment*)sqlite3Fts5MallocZero(&p->rc, nByte);
188495  if( pLvl->aSeg ){
188496  int iLvl, iSeg;
188497  int iSegOut = 0;
188498  /* Iterate through all segments, from oldest to newest. Add them to
188499  ** the new Fts5Level object so that pLvl->aSeg[0] is the oldest
188500  ** segment in the data structure. */
188501  for(iLvl=pStruct->nLevel-1; iLvl>=0; iLvl--){
188502  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
188503  pLvl->aSeg[iSegOut] = pStruct->aLevel[iLvl].aSeg[iSeg];
188504  iSegOut++;
188505  }
188506  }
188507  pNew->nSegment = pLvl->nSeg = nSeg;
188508  }else{
188509  sqlite3_free(pNew);
188510  pNew = 0;
188511  }
188512  }
188513 
188514  return pNew;
188515 }
188516 
188517 static int sqlite3Fts5IndexOptimize(Fts5Index *p){
188518  Fts5Structure *pStruct;
188519  Fts5Structure *pNew = 0;
188520 
188521  assert( p->rc==SQLITE_OK );
188522  fts5IndexFlush(p);
188523  pStruct = fts5StructureRead(p);
188524  fts5StructureInvalidate(p);
188525 
188526  if( pStruct ){
188527  pNew = fts5IndexOptimizeStruct(p, pStruct);
188528  }
188529  fts5StructureRelease(pStruct);
188530 
188531  assert( pNew==0 || pNew->nSegment>0 );
188532  if( pNew ){
188533  int iLvl;
188534  for(iLvl=0; pNew->aLevel[iLvl].nSeg==0; iLvl++){}
188535  while( p->rc==SQLITE_OK && pNew->aLevel[iLvl].nSeg>0 ){
188536  int nRem = FTS5_OPT_WORK_UNIT;
188537  fts5IndexMergeLevel(p, &pNew, iLvl, &nRem);
188538  }
188539 
188540  fts5StructureWrite(p, pNew);
188541  fts5StructureRelease(pNew);
188542  }
188543 
188544  return fts5IndexReturn(p);
188545 }
188546 
188547 /*
188548 ** This is called to implement the special "VALUES('merge', $nMerge)"
188549 ** INSERT command.
188550 */
188551 static int sqlite3Fts5IndexMerge(Fts5Index *p, int nMerge){
188552  Fts5Structure *pStruct = fts5StructureRead(p);
188553  if( pStruct ){
188554  int nMin = p->pConfig->nUsermerge;
188555  fts5StructureInvalidate(p);
188556  if( nMerge<0 ){
188557  Fts5Structure *pNew = fts5IndexOptimizeStruct(p, pStruct);
188558  fts5StructureRelease(pStruct);
188559  pStruct = pNew;
188560  nMin = 2;
188561  nMerge = nMerge*-1;
188562  }
188563  if( pStruct && pStruct->nLevel ){
188564  if( fts5IndexMerge(p, &pStruct, nMerge, nMin) ){
188565  fts5StructureWrite(p, pStruct);
188566  }
188567  }
188568  fts5StructureRelease(pStruct);
188569  }
188570  return fts5IndexReturn(p);
188571 }
188572 
188573 static void fts5AppendRowid(
188574  Fts5Index *p,
188575  i64 iDelta,
188576  Fts5Iter *pUnused,
188577  Fts5Buffer *pBuf
188578 ){
188579  UNUSED_PARAM(pUnused);
188580  fts5BufferAppendVarint(&p->rc, pBuf, iDelta);
188581 }
188582 
188583 static void fts5AppendPoslist(
188584  Fts5Index *p,
188585  i64 iDelta,
188586  Fts5Iter *pMulti,
188587  Fts5Buffer *pBuf
188588 ){
188589  int nData = pMulti->base.nData;
188590  assert( nData>0 );
188591  if( p->rc==SQLITE_OK && 0==fts5BufferGrow(&p->rc, pBuf, nData+9+9) ){
188592  fts5BufferSafeAppendVarint(pBuf, iDelta);
188593  fts5BufferSafeAppendVarint(pBuf, nData*2);
188594  fts5BufferSafeAppendBlob(pBuf, pMulti->base.pData, nData);
188595  }
188596 }
188597 
188598 
188599 static void fts5DoclistIterNext(Fts5DoclistIter *pIter){
188600  u8 *p = pIter->aPoslist + pIter->nSize + pIter->nPoslist;
188601 
188602  assert( pIter->aPoslist );
188603  if( p>=pIter->aEof ){
188604  pIter->aPoslist = 0;
188605  }else{
188606  i64 iDelta;
188607 
188608  p += fts5GetVarint(p, (u64*)&iDelta);
188609  pIter->iRowid += iDelta;
188610 
188611  /* Read position list size */
188612  if( p[0] & 0x80 ){
188613  int nPos;
188614  pIter->nSize = fts5GetVarint32(p, nPos);
188615  pIter->nPoslist = (nPos>>1);
188616  }else{
188617  pIter->nPoslist = ((int)(p[0])) >> 1;
188618  pIter->nSize = 1;
188619  }
188620 
188621  pIter->aPoslist = p;
188622  }
188623 }
188624 
188625 static void fts5DoclistIterInit(
188626  Fts5Buffer *pBuf,
188627  Fts5DoclistIter *pIter
188628 ){
188629  memset(pIter, 0, sizeof(*pIter));
188630  pIter->aPoslist = pBuf->p;
188631  pIter->aEof = &pBuf->p[pBuf->n];
188632  fts5DoclistIterNext(pIter);
188633 }
188634 
188635 #if 0
188636 /*
188637 ** Append a doclist to buffer pBuf.
188638 **
188639 ** This function assumes that space within the buffer has already been
188640 ** allocated.
188641 */
188642 static void fts5MergeAppendDocid(
188643  Fts5Buffer *pBuf, /* Buffer to write to */
188644  i64 *piLastRowid, /* IN/OUT: Previous rowid written (if any) */
188645  i64 iRowid /* Rowid to append */
188646 ){
188647  assert( pBuf->n!=0 || (*piLastRowid)==0 );
188648  fts5BufferSafeAppendVarint(pBuf, iRowid - *piLastRowid);
188649  *piLastRowid = iRowid;
188650 }
188651 #endif
188652 
188653 #define fts5MergeAppendDocid(pBuf, iLastRowid, iRowid) { \
188654  assert( (pBuf)->n!=0 || (iLastRowid)==0 ); \
188655  fts5BufferSafeAppendVarint((pBuf), (iRowid) - (iLastRowid)); \
188656  (iLastRowid) = (iRowid); \
188657 }
188658 
188659 /*
188660 ** Swap the contents of buffer *p1 with that of *p2.
188661 */
188662 static void fts5BufferSwap(Fts5Buffer *p1, Fts5Buffer *p2){
188663  Fts5Buffer tmp = *p1;
188664  *p1 = *p2;
188665  *p2 = tmp;
188666 }
188667 
188668 static void fts5NextRowid(Fts5Buffer *pBuf, int *piOff, i64 *piRowid){
188669  int i = *piOff;
188670  if( i>=pBuf->n ){
188671  *piOff = -1;
188672  }else{
188673  u64 iVal;
188674  *piOff = i + sqlite3Fts5GetVarint(&pBuf->p[i], &iVal);
188675  *piRowid += iVal;
188676  }
188677 }
188678 
188679 /*
188680 ** This is the equivalent of fts5MergePrefixLists() for detail=none mode.
188681 ** In this case the buffers consist of a delta-encoded list of rowids only.
188682 */
188683 static void fts5MergeRowidLists(
188684  Fts5Index *p, /* FTS5 backend object */
188685  Fts5Buffer *p1, /* First list to merge */
188686  Fts5Buffer *p2 /* Second list to merge */
188687 ){
188688  int i1 = 0;
188689  int i2 = 0;
188690  i64 iRowid1 = 0;
188691  i64 iRowid2 = 0;
188692  i64 iOut = 0;
188693 
188694  Fts5Buffer out;
188695  memset(&out, 0, sizeof(out));
188696  sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n);
188697  if( p->rc ) return;
188698 
188699  fts5NextRowid(p1, &i1, &iRowid1);
188700  fts5NextRowid(p2, &i2, &iRowid2);
188701  while( i1>=0 || i2>=0 ){
188702  if( i1>=0 && (i2<0 || iRowid1<iRowid2) ){
188703  assert( iOut==0 || iRowid1>iOut );
188704  fts5BufferSafeAppendVarint(&out, iRowid1 - iOut);
188705  iOut = iRowid1;
188706  fts5NextRowid(p1, &i1, &iRowid1);
188707  }else{
188708  assert( iOut==0 || iRowid2>iOut );
188709  fts5BufferSafeAppendVarint(&out, iRowid2 - iOut);
188710  iOut = iRowid2;
188711  if( i1>=0 && iRowid1==iRowid2 ){
188712  fts5NextRowid(p1, &i1, &iRowid1);
188713  }
188714  fts5NextRowid(p2, &i2, &iRowid2);
188715  }
188716  }
188717 
188718  fts5BufferSwap(&out, p1);
188719  fts5BufferFree(&out);
188720 }
188721 
188722 /*
188723 ** Buffers p1 and p2 contain doclists. This function merges the content
188724 ** of the two doclists together and sets buffer p1 to the result before
188725 ** returning.
188726 **
188727 ** If an error occurs, an error code is left in p->rc. If an error has
188728 ** already occurred, this function is a no-op.
188729 */
188730 static void fts5MergePrefixLists(
188731  Fts5Index *p, /* FTS5 backend object */
188732  Fts5Buffer *p1, /* First list to merge */
188733  Fts5Buffer *p2 /* Second list to merge */
188734 ){
188735  if( p2->n ){
188736  i64 iLastRowid = 0;
188737  Fts5DoclistIter i1;
188738  Fts5DoclistIter i2;
188739  Fts5Buffer out = {0, 0, 0};
188740  Fts5Buffer tmp = {0, 0, 0};
188741 
188742  if( sqlite3Fts5BufferSize(&p->rc, &out, p1->n + p2->n) ) return;
188743  fts5DoclistIterInit(p1, &i1);
188744  fts5DoclistIterInit(p2, &i2);
188745 
188746  while( 1 ){
188747  if( i1.iRowid<i2.iRowid ){
188748  /* Copy entry from i1 */
188749  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
188750  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.nPoslist+i1.nSize);
188751  fts5DoclistIterNext(&i1);
188752  if( i1.aPoslist==0 ) break;
188753  }
188754  else if( i2.iRowid!=i1.iRowid ){
188755  /* Copy entry from i2 */
188756  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
188757  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.nPoslist+i2.nSize);
188758  fts5DoclistIterNext(&i2);
188759  if( i2.aPoslist==0 ) break;
188760  }
188761  else{
188762  /* Merge the two position lists. */
188763  i64 iPos1 = 0;
188764  i64 iPos2 = 0;
188765  int iOff1 = 0;
188766  int iOff2 = 0;
188767  u8 *a1 = &i1.aPoslist[i1.nSize];
188768  u8 *a2 = &i2.aPoslist[i2.nSize];
188769 
188770  i64 iPrev = 0;
188771  Fts5PoslistWriter writer;
188772  memset(&writer, 0, sizeof(writer));
188773 
188774  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
188775  fts5BufferZero(&tmp);
188776  sqlite3Fts5BufferSize(&p->rc, &tmp, i1.nPoslist + i2.nPoslist);
188777  if( p->rc ) break;
188778 
188779  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
188780  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
188781  assert( iPos1>=0 && iPos2>=0 );
188782 
188783  if( iPos1<iPos2 ){
188784  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
188785  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
188786  }else{
188787  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
188788  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
188789  }
188790 
188791  if( iPos1>=0 && iPos2>=0 ){
188792  while( 1 ){
188793  if( iPos1<iPos2 ){
188794  if( iPos1!=iPrev ){
188795  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
188796  }
188797  sqlite3Fts5PoslistNext64(a1, i1.nPoslist, &iOff1, &iPos1);
188798  if( iPos1<0 ) break;
188799  }else{
188800  assert( iPos2!=iPrev );
188801  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
188802  sqlite3Fts5PoslistNext64(a2, i2.nPoslist, &iOff2, &iPos2);
188803  if( iPos2<0 ) break;
188804  }
188805  }
188806  }
188807 
188808  if( iPos1>=0 ){
188809  if( iPos1!=iPrev ){
188810  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos1);
188811  }
188812  fts5BufferSafeAppendBlob(&tmp, &a1[iOff1], i1.nPoslist-iOff1);
188813  }else{
188814  assert( iPos2>=0 && iPos2!=iPrev );
188815  sqlite3Fts5PoslistSafeAppend(&tmp, &iPrev, iPos2);
188816  fts5BufferSafeAppendBlob(&tmp, &a2[iOff2], i2.nPoslist-iOff2);
188817  }
188818 
188819  /* WRITEPOSLISTSIZE */
188820  fts5BufferSafeAppendVarint(&out, tmp.n * 2);
188821  fts5BufferSafeAppendBlob(&out, tmp.p, tmp.n);
188822  fts5DoclistIterNext(&i1);
188823  fts5DoclistIterNext(&i2);
188824  if( i1.aPoslist==0 || i2.aPoslist==0 ) break;
188825  }
188826  }
188827 
188828  if( i1.aPoslist ){
188829  fts5MergeAppendDocid(&out, iLastRowid, i1.iRowid);
188830  fts5BufferSafeAppendBlob(&out, i1.aPoslist, i1.aEof - i1.aPoslist);
188831  }
188832  else if( i2.aPoslist ){
188833  fts5MergeAppendDocid(&out, iLastRowid, i2.iRowid);
188834  fts5BufferSafeAppendBlob(&out, i2.aPoslist, i2.aEof - i2.aPoslist);
188835  }
188836 
188837  fts5BufferSet(&p->rc, p1, out.n, out.p);
188838  fts5BufferFree(&tmp);
188839  fts5BufferFree(&out);
188840  }
188841 }
188842 
188843 static void fts5SetupPrefixIter(
188844  Fts5Index *p, /* Index to read from */
188845  int bDesc, /* True for "ORDER BY rowid DESC" */
188846  const u8 *pToken, /* Buffer containing prefix to match */
188847  int nToken, /* Size of buffer pToken in bytes */
188848  Fts5Colset *pColset, /* Restrict matches to these columns */
188849  Fts5Iter **ppIter /* OUT: New iterator */
188850 ){
188851  Fts5Structure *pStruct;
188852  Fts5Buffer *aBuf;
188853  const int nBuf = 32;
188854 
188855  void (*xMerge)(Fts5Index*, Fts5Buffer*, Fts5Buffer*);
188856  void (*xAppend)(Fts5Index*, i64, Fts5Iter*, Fts5Buffer*);
188857  if( p->pConfig->eDetail==FTS5_DETAIL_NONE ){
188858  xMerge = fts5MergeRowidLists;
188859  xAppend = fts5AppendRowid;
188860  }else{
188861  xMerge = fts5MergePrefixLists;
188862  xAppend = fts5AppendPoslist;
188863  }
188864 
188865  aBuf = (Fts5Buffer*)fts5IdxMalloc(p, sizeof(Fts5Buffer)*nBuf);
188866  pStruct = fts5StructureRead(p);
188867 
188868  if( aBuf && pStruct ){
188869  const int flags = FTS5INDEX_QUERY_SCAN
188870  | FTS5INDEX_QUERY_SKIPEMPTY
188871  | FTS5INDEX_QUERY_NOOUTPUT;
188872  int i;
188873  i64 iLastRowid = 0;
188874  Fts5Iter *p1 = 0; /* Iterator used to gather data from index */
188875  Fts5Data *pData;
188876  Fts5Buffer doclist;
188877  int bNewTerm = 1;
188878 
188879  memset(&doclist, 0, sizeof(doclist));
188880  fts5MultiIterNew(p, pStruct, flags, pColset, pToken, nToken, -1, 0, &p1);
188881  fts5IterSetOutputCb(&p->rc, p1);
188882  for( /* no-op */ ;
188883  fts5MultiIterEof(p, p1)==0;
188884  fts5MultiIterNext2(p, p1, &bNewTerm)
188885  ){
188886  Fts5SegIter *pSeg = &p1->aSeg[ p1->aFirst[1].iFirst ];
188887  int nTerm = pSeg->term.n;
188888  const u8 *pTerm = pSeg->term.p;
188889  p1->xSetOutputs(p1, pSeg);
188890 
188891  assert_nc( memcmp(pToken, pTerm, MIN(nToken, nTerm))<=0 );
188892  if( bNewTerm ){
188893  if( nTerm<nToken || memcmp(pToken, pTerm, nToken) ) break;
188894  }
188895 
188896  if( p1->base.nData==0 ) continue;
188897 
188898  if( p1->base.iRowid<=iLastRowid && doclist.n>0 ){
188899  for(i=0; p->rc==SQLITE_OK && doclist.n; i++){
188900  assert( i<nBuf );
188901  if( aBuf[i].n==0 ){
188902  fts5BufferSwap(&doclist, &aBuf[i]);
188903  fts5BufferZero(&doclist);
188904  }else{
188905  xMerge(p, &doclist, &aBuf[i]);
188906  fts5BufferZero(&aBuf[i]);
188907  }
188908  }
188909  iLastRowid = 0;
188910  }
188911 
188912  xAppend(p, p1->base.iRowid-iLastRowid, p1, &doclist);
188913  iLastRowid = p1->base.iRowid;
188914  }
188915 
188916  for(i=0; i<nBuf; i++){
188917  if( p->rc==SQLITE_OK ){
188918  xMerge(p, &doclist, &aBuf[i]);
188919  }
188920  fts5BufferFree(&aBuf[i]);
188921  }
188922  fts5MultiIterFree(p1);
188923 
188924  pData = fts5IdxMalloc(p, sizeof(Fts5Data) + doclist.n);
188925  if( pData ){
188926  pData->p = (u8*)&pData[1];
188927  pData->nn = pData->szLeaf = doclist.n;
188928  memcpy(pData->p, doclist.p, doclist.n);
188929  fts5MultiIterNew2(p, pData, bDesc, ppIter);
188930  }
188931  fts5BufferFree(&doclist);
188932  }
188933 
188934  fts5StructureRelease(pStruct);
188935  sqlite3_free(aBuf);
188936 }
188937 
188938 
188939 /*
188940 ** Indicate that all subsequent calls to sqlite3Fts5IndexWrite() pertain
188941 ** to the document with rowid iRowid.
188942 */
188943 static int sqlite3Fts5IndexBeginWrite(Fts5Index *p, int bDelete, i64 iRowid){
188944  assert( p->rc==SQLITE_OK );
188945 
188946  /* Allocate the hash table if it has not already been allocated */
188947  if( p->pHash==0 ){
188948  p->rc = sqlite3Fts5HashNew(p->pConfig, &p->pHash, &p->nPendingData);
188949  }
188950 
188951  /* Flush the hash table to disk if required */
188952  if( iRowid<p->iWriteRowid
188953  || (iRowid==p->iWriteRowid && p->bDelete==0)
188954  || (p->nPendingData > p->pConfig->nHashSize)
188955  ){
188956  fts5IndexFlush(p);
188957  }
188958 
188959  p->iWriteRowid = iRowid;
188960  p->bDelete = bDelete;
188961  return fts5IndexReturn(p);
188962 }
188963 
188964 /*
188965 ** Commit data to disk.
188966 */
188967 static int sqlite3Fts5IndexSync(Fts5Index *p, int bCommit){
188968  assert( p->rc==SQLITE_OK );
188969  fts5IndexFlush(p);
188970  if( bCommit ) fts5CloseReader(p);
188971  return fts5IndexReturn(p);
188972 }
188973 
188974 /*
188975 ** Discard any data stored in the in-memory hash tables. Do not write it
188976 ** to the database. Additionally, assume that the contents of the %_data
188977 ** table may have changed on disk. So any in-memory caches of %_data
188978 ** records must be invalidated.
188979 */
188980 static int sqlite3Fts5IndexRollback(Fts5Index *p){
188981  fts5CloseReader(p);
188982  fts5IndexDiscardData(p);
188983  fts5StructureInvalidate(p);
188984  /* assert( p->rc==SQLITE_OK ); */
188985  return SQLITE_OK;
188986 }
188987 
188988 /*
188989 ** The %_data table is completely empty when this function is called. This
188990 ** function populates it with the initial structure objects for each index,
188991 ** and the initial version of the "averages" record (a zero-byte blob).
188992 */
188993 static int sqlite3Fts5IndexReinit(Fts5Index *p){
188994  Fts5Structure s;
188995  fts5StructureInvalidate(p);
188996  memset(&s, 0, sizeof(Fts5Structure));
188997  fts5DataWrite(p, FTS5_AVERAGES_ROWID, (const u8*)"", 0);
188998  fts5StructureWrite(p, &s);
188999  return fts5IndexReturn(p);
189000 }
189001 
189002 /*
189003 ** Open a new Fts5Index handle. If the bCreate argument is true, create
189004 ** and initialize the underlying %_data table.
189005 **
189006 ** If successful, set *pp to point to the new object and return SQLITE_OK.
189007 ** Otherwise, set *pp to NULL and return an SQLite error code.
189008 */
189009 static int sqlite3Fts5IndexOpen(
189010  Fts5Config *pConfig,
189011  int bCreate,
189012  Fts5Index **pp,
189013  char **pzErr
189014 ){
189015  int rc = SQLITE_OK;
189016  Fts5Index *p; /* New object */
189017 
189018  *pp = p = (Fts5Index*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Index));
189019  if( rc==SQLITE_OK ){
189020  p->pConfig = pConfig;
189021  p->nWorkUnit = FTS5_WORK_UNIT;
189022  p->zDataTbl = sqlite3Fts5Mprintf(&rc, "%s_data", pConfig->zName);
189023  if( p->zDataTbl && bCreate ){
189024  rc = sqlite3Fts5CreateTable(
189025  pConfig, "data", "id INTEGER PRIMARY KEY, block BLOB", 0, pzErr
189026  );
189027  if( rc==SQLITE_OK ){
189028  rc = sqlite3Fts5CreateTable(pConfig, "idx",
189029  "segid, term, pgno, PRIMARY KEY(segid, term)",
189030  1, pzErr
189031  );
189032  }
189033  if( rc==SQLITE_OK ){
189034  rc = sqlite3Fts5IndexReinit(p);
189035  }
189036  }
189037  }
189038 
189039  assert( rc!=SQLITE_OK || p->rc==SQLITE_OK );
189040  if( rc ){
189041  sqlite3Fts5IndexClose(p);
189042  *pp = 0;
189043  }
189044  return rc;
189045 }
189046 
189047 /*
189048 ** Close a handle opened by an earlier call to sqlite3Fts5IndexOpen().
189049 */
189050 static int sqlite3Fts5IndexClose(Fts5Index *p){
189051  int rc = SQLITE_OK;
189052  if( p ){
189053  assert( p->pReader==0 );
189054  fts5StructureInvalidate(p);
189055  sqlite3_finalize(p->pWriter);
189056  sqlite3_finalize(p->pDeleter);
189057  sqlite3_finalize(p->pIdxWriter);
189058  sqlite3_finalize(p->pIdxDeleter);
189059  sqlite3_finalize(p->pIdxSelect);
189060  sqlite3_finalize(p->pDataVersion);
189061  sqlite3Fts5HashFree(p->pHash);
189062  sqlite3_free(p->zDataTbl);
189063  sqlite3_free(p);
189064  }
189065  return rc;
189066 }
189067 
189068 /*
189069 ** Argument p points to a buffer containing utf-8 text that is n bytes in
189070 ** size. Return the number of bytes in the nChar character prefix of the
189071 ** buffer, or 0 if there are less than nChar characters in total.
189072 */
189073 static int sqlite3Fts5IndexCharlenToBytelen(
189074  const char *p,
189075  int nByte,
189076  int nChar
189077 ){
189078  int n = 0;
189079  int i;
189080  for(i=0; i<nChar; i++){
189081  if( n>=nByte ) return 0; /* Input contains fewer than nChar chars */
189082  if( (unsigned char)p[n++]>=0xc0 ){
189083  while( (p[n] & 0xc0)==0x80 ) n++;
189084  }
189085  }
189086  return n;
189087 }
189088 
189089 /*
189090 ** pIn is a UTF-8 encoded string, nIn bytes in size. Return the number of
189091 ** unicode characters in the string.
189092 */
189093 static int fts5IndexCharlen(const char *pIn, int nIn){
189094  int nChar = 0;
189095  int i = 0;
189096  while( i<nIn ){
189097  if( (unsigned char)pIn[i++]>=0xc0 ){
189098  while( i<nIn && (pIn[i] & 0xc0)==0x80 ) i++;
189099  }
189100  nChar++;
189101  }
189102  return nChar;
189103 }
189104 
189105 /*
189106 ** Insert or remove data to or from the index. Each time a document is
189107 ** added to or removed from the index, this function is called one or more
189108 ** times.
189109 **
189110 ** For an insert, it must be called once for each token in the new document.
189111 ** If the operation is a delete, it must be called (at least) once for each
189112 ** unique token in the document with an iCol value less than zero. The iPos
189113 ** argument is ignored for a delete.
189114 */
189115 static int sqlite3Fts5IndexWrite(
189116  Fts5Index *p, /* Index to write to */
189117  int iCol, /* Column token appears in (-ve -> delete) */
189118  int iPos, /* Position of token within column */
189119  const char *pToken, int nToken /* Token to add or remove to or from index */
189120 ){
189121  int i; /* Used to iterate through indexes */
189122  int rc = SQLITE_OK; /* Return code */
189123  Fts5Config *pConfig = p->pConfig;
189124 
189125  assert( p->rc==SQLITE_OK );
189126  assert( (iCol<0)==p->bDelete );
189127 
189128  /* Add the entry to the main terms index. */
189129  rc = sqlite3Fts5HashWrite(
189130  p->pHash, p->iWriteRowid, iCol, iPos, FTS5_MAIN_PREFIX, pToken, nToken
189131  );
189132 
189133  for(i=0; i<pConfig->nPrefix && rc==SQLITE_OK; i++){
189134  const int nChar = pConfig->aPrefix[i];
189135  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
189136  if( nByte ){
189137  rc = sqlite3Fts5HashWrite(p->pHash,
189138  p->iWriteRowid, iCol, iPos, (char)(FTS5_MAIN_PREFIX+i+1), pToken,
189139  nByte
189140  );
189141  }
189142  }
189143 
189144  return rc;
189145 }
189146 
189147 /*
189148 ** Open a new iterator to iterate though all rowid that match the
189149 ** specified token or token prefix.
189150 */
189151 static int sqlite3Fts5IndexQuery(
189152  Fts5Index *p, /* FTS index to query */
189153  const char *pToken, int nToken, /* Token (or prefix) to query for */
189154  int flags, /* Mask of FTS5INDEX_QUERY_X flags */
189155  Fts5Colset *pColset, /* Match these columns only */
189156  Fts5IndexIter **ppIter /* OUT: New iterator object */
189157 ){
189158  Fts5Config *pConfig = p->pConfig;
189159  Fts5Iter *pRet = 0;
189160  Fts5Buffer buf = {0, 0, 0};
189161 
189162  /* If the QUERY_SCAN flag is set, all other flags must be clear. */
189163  assert( (flags & FTS5INDEX_QUERY_SCAN)==0 || flags==FTS5INDEX_QUERY_SCAN );
189164 
189165  if( sqlite3Fts5BufferSize(&p->rc, &buf, nToken+1)==0 ){
189166  int iIdx = 0; /* Index to search */
189167  memcpy(&buf.p[1], pToken, nToken);
189168 
189169  /* Figure out which index to search and set iIdx accordingly. If this
189170  ** is a prefix query for which there is no prefix index, set iIdx to
189171  ** greater than pConfig->nPrefix to indicate that the query will be
189172  ** satisfied by scanning multiple terms in the main index.
189173  **
189174  ** If the QUERY_TEST_NOIDX flag was specified, then this must be a
189175  ** prefix-query. Instead of using a prefix-index (if one exists),
189176  ** evaluate the prefix query using the main FTS index. This is used
189177  ** for internal sanity checking by the integrity-check in debug
189178  ** mode only. */
189179 #ifdef SQLITE_DEBUG
189180  if( pConfig->bPrefixIndex==0 || (flags & FTS5INDEX_QUERY_TEST_NOIDX) ){
189181  assert( flags & FTS5INDEX_QUERY_PREFIX );
189182  iIdx = 1+pConfig->nPrefix;
189183  }else
189184 #endif
189185  if( flags & FTS5INDEX_QUERY_PREFIX ){
189186  int nChar = fts5IndexCharlen(pToken, nToken);
189187  for(iIdx=1; iIdx<=pConfig->nPrefix; iIdx++){
189188  if( pConfig->aPrefix[iIdx-1]==nChar ) break;
189189  }
189190  }
189191 
189192  if( iIdx<=pConfig->nPrefix ){
189193  /* Straight index lookup */
189194  Fts5Structure *pStruct = fts5StructureRead(p);
189195  buf.p[0] = (u8)(FTS5_MAIN_PREFIX + iIdx);
189196  if( pStruct ){
189197  fts5MultiIterNew(p, pStruct, flags | FTS5INDEX_QUERY_SKIPEMPTY,
189198  pColset, buf.p, nToken+1, -1, 0, &pRet
189199  );
189200  fts5StructureRelease(pStruct);
189201  }
189202  }else{
189203  /* Scan multiple terms in the main index */
189204  int bDesc = (flags & FTS5INDEX_QUERY_DESC)!=0;
189205  buf.p[0] = FTS5_MAIN_PREFIX;
189206  fts5SetupPrefixIter(p, bDesc, buf.p, nToken+1, pColset, &pRet);
189207  assert( p->rc!=SQLITE_OK || pRet->pColset==0 );
189208  fts5IterSetOutputCb(&p->rc, pRet);
189209  if( p->rc==SQLITE_OK ){
189210  Fts5SegIter *pSeg = &pRet->aSeg[pRet->aFirst[1].iFirst];
189211  if( pSeg->pLeaf ) pRet->xSetOutputs(pRet, pSeg);
189212  }
189213  }
189214 
189215  if( p->rc ){
189216  sqlite3Fts5IterClose(&pRet->base);
189217  pRet = 0;
189218  fts5CloseReader(p);
189219  }
189220 
189221  *ppIter = &pRet->base;
189222  sqlite3Fts5BufferFree(&buf);
189223  }
189224  return fts5IndexReturn(p);
189225 }
189226 
189227 /*
189228 ** Return true if the iterator passed as the only argument is at EOF.
189229 */
189230 /*
189231 ** Move to the next matching rowid.
189232 */
189233 static int sqlite3Fts5IterNext(Fts5IndexIter *pIndexIter){
189234  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
189235  assert( pIter->pIndex->rc==SQLITE_OK );
189236  fts5MultiIterNext(pIter->pIndex, pIter, 0, 0);
189237  return fts5IndexReturn(pIter->pIndex);
189238 }
189239 
189240 /*
189241 ** Move to the next matching term/rowid. Used by the fts5vocab module.
189242 */
189243 static int sqlite3Fts5IterNextScan(Fts5IndexIter *pIndexIter){
189244  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
189245  Fts5Index *p = pIter->pIndex;
189246 
189247  assert( pIter->pIndex->rc==SQLITE_OK );
189248 
189249  fts5MultiIterNext(p, pIter, 0, 0);
189250  if( p->rc==SQLITE_OK ){
189251  Fts5SegIter *pSeg = &pIter->aSeg[ pIter->aFirst[1].iFirst ];
189252  if( pSeg->pLeaf && pSeg->term.p[0]!=FTS5_MAIN_PREFIX ){
189253  fts5DataRelease(pSeg->pLeaf);
189254  pSeg->pLeaf = 0;
189255  pIter->base.bEof = 1;
189256  }
189257  }
189258 
189259  return fts5IndexReturn(pIter->pIndex);
189260 }
189261 
189262 /*
189263 ** Move to the next matching rowid that occurs at or after iMatch. The
189264 ** definition of "at or after" depends on whether this iterator iterates
189265 ** in ascending or descending rowid order.
189266 */
189267 static int sqlite3Fts5IterNextFrom(Fts5IndexIter *pIndexIter, i64 iMatch){
189268  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
189269  fts5MultiIterNextFrom(pIter->pIndex, pIter, iMatch);
189270  return fts5IndexReturn(pIter->pIndex);
189271 }
189272 
189273 /*
189274 ** Return the current term.
189275 */
189276 static const char *sqlite3Fts5IterTerm(Fts5IndexIter *pIndexIter, int *pn){
189277  int n;
189278  const char *z = (const char*)fts5MultiIterTerm((Fts5Iter*)pIndexIter, &n);
189279  *pn = n-1;
189280  return &z[1];
189281 }
189282 
189283 /*
189284 ** Close an iterator opened by an earlier call to sqlite3Fts5IndexQuery().
189285 */
189286 static void sqlite3Fts5IterClose(Fts5IndexIter *pIndexIter){
189287  if( pIndexIter ){
189288  Fts5Iter *pIter = (Fts5Iter*)pIndexIter;
189289  Fts5Index *pIndex = pIter->pIndex;
189290  fts5MultiIterFree(pIter);
189291  fts5CloseReader(pIndex);
189292  }
189293 }
189294 
189295 /*
189296 ** Read and decode the "averages" record from the database.
189297 **
189298 ** Parameter anSize must point to an array of size nCol, where nCol is
189299 ** the number of user defined columns in the FTS table.
189300 */
189301 static int sqlite3Fts5IndexGetAverages(Fts5Index *p, i64 *pnRow, i64 *anSize){
189302  int nCol = p->pConfig->nCol;
189303  Fts5Data *pData;
189304 
189305  *pnRow = 0;
189306  memset(anSize, 0, sizeof(i64) * nCol);
189307  pData = fts5DataRead(p, FTS5_AVERAGES_ROWID);
189308  if( p->rc==SQLITE_OK && pData->nn ){
189309  int i = 0;
189310  int iCol;
189311  i += fts5GetVarint(&pData->p[i], (u64*)pnRow);
189312  for(iCol=0; i<pData->nn && iCol<nCol; iCol++){
189313  i += fts5GetVarint(&pData->p[i], (u64*)&anSize[iCol]);
189314  }
189315  }
189316 
189317  fts5DataRelease(pData);
189318  return fts5IndexReturn(p);
189319 }
189320 
189321 /*
189322 ** Replace the current "averages" record with the contents of the buffer
189323 ** supplied as the second argument.
189324 */
189325 static int sqlite3Fts5IndexSetAverages(Fts5Index *p, const u8 *pData, int nData){
189326  assert( p->rc==SQLITE_OK );
189327  fts5DataWrite(p, FTS5_AVERAGES_ROWID, pData, nData);
189328  return fts5IndexReturn(p);
189329 }
189330 
189331 /*
189332 ** Return the total number of blocks this module has read from the %_data
189333 ** table since it was created.
189334 */
189335 static int sqlite3Fts5IndexReads(Fts5Index *p){
189336  return p->nRead;
189337 }
189338 
189339 /*
189340 ** Set the 32-bit cookie value stored at the start of all structure
189341 ** records to the value passed as the second argument.
189342 **
189343 ** Return SQLITE_OK if successful, or an SQLite error code if an error
189344 ** occurs.
189345 */
189346 static int sqlite3Fts5IndexSetCookie(Fts5Index *p, int iNew){
189347  int rc; /* Return code */
189348  Fts5Config *pConfig = p->pConfig; /* Configuration object */
189349  u8 aCookie[4]; /* Binary representation of iNew */
189350  sqlite3_blob *pBlob = 0;
189351 
189352  assert( p->rc==SQLITE_OK );
189353  sqlite3Fts5Put32(aCookie, iNew);
189354 
189355  rc = sqlite3_blob_open(pConfig->db, pConfig->zDb, p->zDataTbl,
189356  "block", FTS5_STRUCTURE_ROWID, 1, &pBlob
189357  );
189358  if( rc==SQLITE_OK ){
189359  sqlite3_blob_write(pBlob, aCookie, 4, 0);
189360  rc = sqlite3_blob_close(pBlob);
189361  }
189362 
189363  return rc;
189364 }
189365 
189366 static int sqlite3Fts5IndexLoadConfig(Fts5Index *p){
189367  Fts5Structure *pStruct;
189368  pStruct = fts5StructureRead(p);
189369  fts5StructureRelease(pStruct);
189370  return fts5IndexReturn(p);
189371 }
189372 
189373 
189374 /*************************************************************************
189375 **************************************************************************
189376 ** Below this point is the implementation of the integrity-check
189377 ** functionality.
189378 */
189379 
189380 /*
189381 ** Return a simple checksum value based on the arguments.
189382 */
189383 static u64 sqlite3Fts5IndexEntryCksum(
189384  i64 iRowid,
189385  int iCol,
189386  int iPos,
189387  int iIdx,
189388  const char *pTerm,
189389  int nTerm
189390 ){
189391  int i;
189392  u64 ret = iRowid;
189393  ret += (ret<<3) + iCol;
189394  ret += (ret<<3) + iPos;
189395  if( iIdx>=0 ) ret += (ret<<3) + (FTS5_MAIN_PREFIX + iIdx);
189396  for(i=0; i<nTerm; i++) ret += (ret<<3) + pTerm[i];
189397  return ret;
189398 }
189399 
189400 #ifdef SQLITE_DEBUG
189401 /*
189402 ** This function is purely an internal test. It does not contribute to
189403 ** FTS functionality, or even the integrity-check, in any way.
189404 **
189405 ** Instead, it tests that the same set of pgno/rowid combinations are
189406 ** visited regardless of whether the doclist-index identified by parameters
189407 ** iSegid/iLeaf is iterated in forwards or reverse order.
189408 */
189409 static void fts5TestDlidxReverse(
189410  Fts5Index *p,
189411  int iSegid, /* Segment id to load from */
189412  int iLeaf /* Load doclist-index for this leaf */
189413 ){
189414  Fts5DlidxIter *pDlidx = 0;
189415  u64 cksum1 = 13;
189416  u64 cksum2 = 13;
189417 
189418  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iLeaf);
189419  fts5DlidxIterEof(p, pDlidx)==0;
189420  fts5DlidxIterNext(p, pDlidx)
189421  ){
189422  i64 iRowid = fts5DlidxIterRowid(pDlidx);
189423  int pgno = fts5DlidxIterPgno(pDlidx);
189424  assert( pgno>iLeaf );
189425  cksum1 += iRowid + ((i64)pgno<<32);
189426  }
189427  fts5DlidxIterFree(pDlidx);
189428  pDlidx = 0;
189429 
189430  for(pDlidx=fts5DlidxIterInit(p, 1, iSegid, iLeaf);
189431  fts5DlidxIterEof(p, pDlidx)==0;
189432  fts5DlidxIterPrev(p, pDlidx)
189433  ){
189434  i64 iRowid = fts5DlidxIterRowid(pDlidx);
189435  int pgno = fts5DlidxIterPgno(pDlidx);
189436  assert( fts5DlidxIterPgno(pDlidx)>iLeaf );
189437  cksum2 += iRowid + ((i64)pgno<<32);
189438  }
189439  fts5DlidxIterFree(pDlidx);
189440  pDlidx = 0;
189441 
189442  if( p->rc==SQLITE_OK && cksum1!=cksum2 ) p->rc = FTS5_CORRUPT;
189443 }
189444 
189445 static int fts5QueryCksum(
189446  Fts5Index *p, /* Fts5 index object */
189447  int iIdx,
189448  const char *z, /* Index key to query for */
189449  int n, /* Size of index key in bytes */
189450  int flags, /* Flags for Fts5IndexQuery */
189451  u64 *pCksum /* IN/OUT: Checksum value */
189452 ){
189453  int eDetail = p->pConfig->eDetail;
189454  u64 cksum = *pCksum;
189455  Fts5IndexIter *pIter = 0;
189456  int rc = sqlite3Fts5IndexQuery(p, z, n, flags, 0, &pIter);
189457 
189458  while( rc==SQLITE_OK && 0==sqlite3Fts5IterEof(pIter) ){
189459  i64 rowid = pIter->iRowid;
189460 
189461  if( eDetail==FTS5_DETAIL_NONE ){
189462  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, 0, 0, iIdx, z, n);
189463  }else{
189464  Fts5PoslistReader sReader;
189465  for(sqlite3Fts5PoslistReaderInit(pIter->pData, pIter->nData, &sReader);
189466  sReader.bEof==0;
189467  sqlite3Fts5PoslistReaderNext(&sReader)
189468  ){
189469  int iCol = FTS5_POS2COLUMN(sReader.iPos);
189470  int iOff = FTS5_POS2OFFSET(sReader.iPos);
189471  cksum ^= sqlite3Fts5IndexEntryCksum(rowid, iCol, iOff, iIdx, z, n);
189472  }
189473  }
189474  if( rc==SQLITE_OK ){
189475  rc = sqlite3Fts5IterNext(pIter);
189476  }
189477  }
189478  sqlite3Fts5IterClose(pIter);
189479 
189480  *pCksum = cksum;
189481  return rc;
189482 }
189483 
189484 
189485 /*
189486 ** This function is also purely an internal test. It does not contribute to
189487 ** FTS functionality, or even the integrity-check, in any way.
189488 */
189489 static void fts5TestTerm(
189490  Fts5Index *p,
189491  Fts5Buffer *pPrev, /* Previous term */
189492  const char *z, int n, /* Possibly new term to test */
189493  u64 expected,
189494  u64 *pCksum
189495 ){
189496  int rc = p->rc;
189497  if( pPrev->n==0 ){
189498  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
189499  }else
189500  if( rc==SQLITE_OK && (pPrev->n!=n || memcmp(pPrev->p, z, n)) ){
189501  u64 cksum3 = *pCksum;
189502  const char *zTerm = (const char*)&pPrev->p[1]; /* term sans prefix-byte */
189503  int nTerm = pPrev->n-1; /* Size of zTerm in bytes */
189504  int iIdx = (pPrev->p[0] - FTS5_MAIN_PREFIX);
189505  int flags = (iIdx==0 ? 0 : FTS5INDEX_QUERY_PREFIX);
189506  u64 ck1 = 0;
189507  u64 ck2 = 0;
189508 
189509  /* Check that the results returned for ASC and DESC queries are
189510  ** the same. If not, call this corruption. */
189511  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, flags, &ck1);
189512  if( rc==SQLITE_OK ){
189513  int f = flags|FTS5INDEX_QUERY_DESC;
189514  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
189515  }
189516  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
189517 
189518  /* If this is a prefix query, check that the results returned if the
189519  ** the index is disabled are the same. In both ASC and DESC order.
189520  **
189521  ** This check may only be performed if the hash table is empty. This
189522  ** is because the hash table only supports a single scan query at
189523  ** a time, and the multi-iter loop from which this function is called
189524  ** is already performing such a scan. */
189525  if( p->nPendingData==0 ){
189526  if( iIdx>0 && rc==SQLITE_OK ){
189527  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX;
189528  ck2 = 0;
189529  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
189530  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
189531  }
189532  if( iIdx>0 && rc==SQLITE_OK ){
189533  int f = flags|FTS5INDEX_QUERY_TEST_NOIDX|FTS5INDEX_QUERY_DESC;
189534  ck2 = 0;
189535  rc = fts5QueryCksum(p, iIdx, zTerm, nTerm, f, &ck2);
189536  if( rc==SQLITE_OK && ck1!=ck2 ) rc = FTS5_CORRUPT;
189537  }
189538  }
189539 
189540  cksum3 ^= ck1;
189541  fts5BufferSet(&rc, pPrev, n, (const u8*)z);
189542 
189543  if( rc==SQLITE_OK && cksum3!=expected ){
189544  rc = FTS5_CORRUPT;
189545  }
189546  *pCksum = cksum3;
189547  }
189548  p->rc = rc;
189549 }
189550 
189551 #else
189552 # define fts5TestDlidxReverse(x,y,z)
189553 # define fts5TestTerm(u,v,w,x,y,z)
189554 #endif
189555 
189556 /*
189557 ** Check that:
189558 **
189559 ** 1) All leaves of pSeg between iFirst and iLast (inclusive) exist and
189560 ** contain zero terms.
189561 ** 2) All leaves of pSeg between iNoRowid and iLast (inclusive) exist and
189562 ** contain zero rowids.
189563 */
189564 static void fts5IndexIntegrityCheckEmpty(
189565  Fts5Index *p,
189566  Fts5StructureSegment *pSeg, /* Segment to check internal consistency */
189567  int iFirst,
189568  int iNoRowid,
189569  int iLast
189570 ){
189571  int i;
189572 
189573  /* Now check that the iter.nEmpty leaves following the current leaf
189574  ** (a) exist and (b) contain no terms. */
189575  for(i=iFirst; p->rc==SQLITE_OK && i<=iLast; i++){
189576  Fts5Data *pLeaf = fts5DataRead(p, FTS5_SEGMENT_ROWID(pSeg->iSegid, i));
189577  if( pLeaf ){
189578  if( !fts5LeafIsTermless(pLeaf) ) p->rc = FTS5_CORRUPT;
189579  if( i>=iNoRowid && 0!=fts5LeafFirstRowidOff(pLeaf) ) p->rc = FTS5_CORRUPT;
189580  }
189581  fts5DataRelease(pLeaf);
189582  }
189583 }
189584 
189585 static void fts5IntegrityCheckPgidx(Fts5Index *p, Fts5Data *pLeaf){
189586  int iTermOff = 0;
189587  int ii;
189588 
189589  Fts5Buffer buf1 = {0,0,0};
189590  Fts5Buffer buf2 = {0,0,0};
189591 
189592  ii = pLeaf->szLeaf;
189593  while( ii<pLeaf->nn && p->rc==SQLITE_OK ){
189594  int res;
189595  int iOff;
189596  int nIncr;
189597 
189598  ii += fts5GetVarint32(&pLeaf->p[ii], nIncr);
189599  iTermOff += nIncr;
189600  iOff = iTermOff;
189601 
189602  if( iOff>=pLeaf->szLeaf ){
189603  p->rc = FTS5_CORRUPT;
189604  }else if( iTermOff==nIncr ){
189605  int nByte;
189606  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
189607  if( (iOff+nByte)>pLeaf->szLeaf ){
189608  p->rc = FTS5_CORRUPT;
189609  }else{
189610  fts5BufferSet(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
189611  }
189612  }else{
189613  int nKeep, nByte;
189614  iOff += fts5GetVarint32(&pLeaf->p[iOff], nKeep);
189615  iOff += fts5GetVarint32(&pLeaf->p[iOff], nByte);
189616  if( nKeep>buf1.n || (iOff+nByte)>pLeaf->szLeaf ){
189617  p->rc = FTS5_CORRUPT;
189618  }else{
189619  buf1.n = nKeep;
189620  fts5BufferAppendBlob(&p->rc, &buf1, nByte, &pLeaf->p[iOff]);
189621  }
189622 
189623  if( p->rc==SQLITE_OK ){
189624  res = fts5BufferCompare(&buf1, &buf2);
189625  if( res<=0 ) p->rc = FTS5_CORRUPT;
189626  }
189627  }
189628  fts5BufferSet(&p->rc, &buf2, buf1.n, buf1.p);
189629  }
189630 
189631  fts5BufferFree(&buf1);
189632  fts5BufferFree(&buf2);
189633 }
189634 
189635 static void fts5IndexIntegrityCheckSegment(
189636  Fts5Index *p, /* FTS5 backend object */
189637  Fts5StructureSegment *pSeg /* Segment to check internal consistency */
189638 ){
189639  Fts5Config *pConfig = p->pConfig;
189640  sqlite3_stmt *pStmt = 0;
189641  int rc2;
189642  int iIdxPrevLeaf = pSeg->pgnoFirst-1;
189643  int iDlidxPrevLeaf = pSeg->pgnoLast;
189644 
189645  if( pSeg->pgnoFirst==0 ) return;
189646 
189647  fts5IndexPrepareStmt(p, &pStmt, sqlite3_mprintf(
189648  "SELECT segid, term, (pgno>>1), (pgno&1) FROM %Q.'%q_idx' WHERE segid=%d",
189649  pConfig->zDb, pConfig->zName, pSeg->iSegid
189650  ));
189651 
189652  /* Iterate through the b-tree hierarchy. */
189653  while( p->rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
189654  i64 iRow; /* Rowid for this leaf */
189655  Fts5Data *pLeaf; /* Data for this leaf */
189656 
189657  int nIdxTerm = sqlite3_column_bytes(pStmt, 1);
189658  const char *zIdxTerm = (const char*)sqlite3_column_text(pStmt, 1);
189659  int iIdxLeaf = sqlite3_column_int(pStmt, 2);
189660  int bIdxDlidx = sqlite3_column_int(pStmt, 3);
189661 
189662  /* If the leaf in question has already been trimmed from the segment,
189663  ** ignore this b-tree entry. Otherwise, load it into memory. */
189664  if( iIdxLeaf<pSeg->pgnoFirst ) continue;
189665  iRow = FTS5_SEGMENT_ROWID(pSeg->iSegid, iIdxLeaf);
189666  pLeaf = fts5DataRead(p, iRow);
189667  if( pLeaf==0 ) break;
189668 
189669  /* Check that the leaf contains at least one term, and that it is equal
189670  ** to or larger than the split-key in zIdxTerm. Also check that if there
189671  ** is also a rowid pointer within the leaf page header, it points to a
189672  ** location before the term. */
189673  if( pLeaf->nn<=pLeaf->szLeaf ){
189674  p->rc = FTS5_CORRUPT;
189675  }else{
189676  int iOff; /* Offset of first term on leaf */
189677  int iRowidOff; /* Offset of first rowid on leaf */
189678  int nTerm; /* Size of term on leaf in bytes */
189679  int res; /* Comparison of term and split-key */
189680 
189681  iOff = fts5LeafFirstTermOff(pLeaf);
189682  iRowidOff = fts5LeafFirstRowidOff(pLeaf);
189683  if( iRowidOff>=iOff ){
189684  p->rc = FTS5_CORRUPT;
189685  }else{
189686  iOff += fts5GetVarint32(&pLeaf->p[iOff], nTerm);
189687  res = memcmp(&pLeaf->p[iOff], zIdxTerm, MIN(nTerm, nIdxTerm));
189688  if( res==0 ) res = nTerm - nIdxTerm;
189689  if( res<0 ) p->rc = FTS5_CORRUPT;
189690  }
189691 
189692  fts5IntegrityCheckPgidx(p, pLeaf);
189693  }
189694  fts5DataRelease(pLeaf);
189695  if( p->rc ) break;
189696 
189697  /* Now check that the iter.nEmpty leaves following the current leaf
189698  ** (a) exist and (b) contain no terms. */
189699  fts5IndexIntegrityCheckEmpty(
189700  p, pSeg, iIdxPrevLeaf+1, iDlidxPrevLeaf+1, iIdxLeaf-1
189701  );
189702  if( p->rc ) break;
189703 
189704  /* If there is a doclist-index, check that it looks right. */
189705  if( bIdxDlidx ){
189706  Fts5DlidxIter *pDlidx = 0; /* For iterating through doclist index */
189707  int iPrevLeaf = iIdxLeaf;
189708  int iSegid = pSeg->iSegid;
189709  int iPg = 0;
189710  i64 iKey;
189711 
189712  for(pDlidx=fts5DlidxIterInit(p, 0, iSegid, iIdxLeaf);
189713  fts5DlidxIterEof(p, pDlidx)==0;
189714  fts5DlidxIterNext(p, pDlidx)
189715  ){
189716 
189717  /* Check any rowid-less pages that occur before the current leaf. */
189718  for(iPg=iPrevLeaf+1; iPg<fts5DlidxIterPgno(pDlidx); iPg++){
189719  iKey = FTS5_SEGMENT_ROWID(iSegid, iPg);
189720  pLeaf = fts5DataRead(p, iKey);
189721  if( pLeaf ){
189722  if( fts5LeafFirstRowidOff(pLeaf)!=0 ) p->rc = FTS5_CORRUPT;
189723  fts5DataRelease(pLeaf);
189724  }
189725  }
189726  iPrevLeaf = fts5DlidxIterPgno(pDlidx);
189727 
189728  /* Check that the leaf page indicated by the iterator really does
189729  ** contain the rowid suggested by the same. */
189730  iKey = FTS5_SEGMENT_ROWID(iSegid, iPrevLeaf);
189731  pLeaf = fts5DataRead(p, iKey);
189732  if( pLeaf ){
189733  i64 iRowid;
189734  int iRowidOff = fts5LeafFirstRowidOff(pLeaf);
189735  ASSERT_SZLEAF_OK(pLeaf);
189736  if( iRowidOff>=pLeaf->szLeaf ){
189737  p->rc = FTS5_CORRUPT;
189738  }else{
189739  fts5GetVarint(&pLeaf->p[iRowidOff], (u64*)&iRowid);
189740  if( iRowid!=fts5DlidxIterRowid(pDlidx) ) p->rc = FTS5_CORRUPT;
189741  }
189742  fts5DataRelease(pLeaf);
189743  }
189744  }
189745 
189746  iDlidxPrevLeaf = iPg;
189747  fts5DlidxIterFree(pDlidx);
189748  fts5TestDlidxReverse(p, iSegid, iIdxLeaf);
189749  }else{
189750  iDlidxPrevLeaf = pSeg->pgnoLast;
189751  /* TODO: Check there is no doclist index */
189752  }
189753 
189754  iIdxPrevLeaf = iIdxLeaf;
189755  }
189756 
189757  rc2 = sqlite3_finalize(pStmt);
189758  if( p->rc==SQLITE_OK ) p->rc = rc2;
189759 
189760  /* Page iter.iLeaf must now be the rightmost leaf-page in the segment */
189761 #if 0
189762  if( p->rc==SQLITE_OK && iter.iLeaf!=pSeg->pgnoLast ){
189763  p->rc = FTS5_CORRUPT;
189764  }
189765 #endif
189766 }
189767 
189768 
189769 /*
189770 ** Run internal checks to ensure that the FTS index (a) is internally
189771 ** consistent and (b) contains entries for which the XOR of the checksums
189772 ** as calculated by sqlite3Fts5IndexEntryCksum() is cksum.
189773 **
189774 ** Return SQLITE_CORRUPT if any of the internal checks fail, or if the
189775 ** checksum does not match. Return SQLITE_OK if all checks pass without
189776 ** error, or some other SQLite error code if another error (e.g. OOM)
189777 ** occurs.
189778 */
189779 static int sqlite3Fts5IndexIntegrityCheck(Fts5Index *p, u64 cksum){
189780  int eDetail = p->pConfig->eDetail;
189781  u64 cksum2 = 0; /* Checksum based on contents of indexes */
189782  Fts5Buffer poslist = {0,0,0}; /* Buffer used to hold a poslist */
189783  Fts5Iter *pIter; /* Used to iterate through entire index */
189784  Fts5Structure *pStruct; /* Index structure */
189785 
189786 #ifdef SQLITE_DEBUG
189787  /* Used by extra internal tests only run if NDEBUG is not defined */
189788  u64 cksum3 = 0; /* Checksum based on contents of indexes */
189789  Fts5Buffer term = {0,0,0}; /* Buffer used to hold most recent term */
189790 #endif
189791  const int flags = FTS5INDEX_QUERY_NOOUTPUT;
189792 
189793  /* Load the FTS index structure */
189794  pStruct = fts5StructureRead(p);
189795 
189796  /* Check that the internal nodes of each segment match the leaves */
189797  if( pStruct ){
189798  int iLvl, iSeg;
189799  for(iLvl=0; iLvl<pStruct->nLevel; iLvl++){
189800  for(iSeg=0; iSeg<pStruct->aLevel[iLvl].nSeg; iSeg++){
189801  Fts5StructureSegment *pSeg = &pStruct->aLevel[iLvl].aSeg[iSeg];
189802  fts5IndexIntegrityCheckSegment(p, pSeg);
189803  }
189804  }
189805  }
189806 
189807  /* The cksum argument passed to this function is a checksum calculated
189808  ** based on all expected entries in the FTS index (including prefix index
189809  ** entries). This block checks that a checksum calculated based on the
189810  ** actual contents of FTS index is identical.
189811  **
189812  ** Two versions of the same checksum are calculated. The first (stack
189813  ** variable cksum2) based on entries extracted from the full-text index
189814  ** while doing a linear scan of each individual index in turn.
189815  **
189816  ** As each term visited by the linear scans, a separate query for the
189817  ** same term is performed. cksum3 is calculated based on the entries
189818  ** extracted by these queries.
189819  */
189820  for(fts5MultiIterNew(p, pStruct, flags, 0, 0, 0, -1, 0, &pIter);
189821  fts5MultiIterEof(p, pIter)==0;
189822  fts5MultiIterNext(p, pIter, 0, 0)
189823  ){
189824  int n; /* Size of term in bytes */
189825  i64 iPos = 0; /* Position read from poslist */
189826  int iOff = 0; /* Offset within poslist */
189827  i64 iRowid = fts5MultiIterRowid(pIter);
189828  char *z = (char*)fts5MultiIterTerm(pIter, &n);
189829 
189830  /* If this is a new term, query for it. Update cksum3 with the results. */
189831  fts5TestTerm(p, &term, z, n, cksum2, &cksum3);
189832 
189833  if( eDetail==FTS5_DETAIL_NONE ){
189834  if( 0==fts5MultiIterIsEmpty(p, pIter) ){
189835  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, 0, 0, -1, z, n);
189836  }
189837  }else{
189838  poslist.n = 0;
189839  fts5SegiterPoslist(p, &pIter->aSeg[pIter->aFirst[1].iFirst], 0, &poslist);
189840  while( 0==sqlite3Fts5PoslistNext64(poslist.p, poslist.n, &iOff, &iPos) ){
189841  int iCol = FTS5_POS2COLUMN(iPos);
189842  int iTokOff = FTS5_POS2OFFSET(iPos);
189843  cksum2 ^= sqlite3Fts5IndexEntryCksum(iRowid, iCol, iTokOff, -1, z, n);
189844  }
189845  }
189846  }
189847  fts5TestTerm(p, &term, 0, 0, cksum2, &cksum3);
189848 
189849  fts5MultiIterFree(pIter);
189850  if( p->rc==SQLITE_OK && cksum!=cksum2 ) p->rc = FTS5_CORRUPT;
189851 
189852  fts5StructureRelease(pStruct);
189853 #ifdef SQLITE_DEBUG
189854  fts5BufferFree(&term);
189855 #endif
189856  fts5BufferFree(&poslist);
189857  return fts5IndexReturn(p);
189858 }
189859 
189860 /*************************************************************************
189861 **************************************************************************
189862 ** Below this point is the implementation of the fts5_decode() scalar
189863 ** function only.
189864 */
189865 
189866 /*
189867 ** Decode a segment-data rowid from the %_data table. This function is
189868 ** the opposite of macro FTS5_SEGMENT_ROWID().
189869 */
189870 static void fts5DecodeRowid(
189871  i64 iRowid, /* Rowid from %_data table */
189872  int *piSegid, /* OUT: Segment id */
189873  int *pbDlidx, /* OUT: Dlidx flag */
189874  int *piHeight, /* OUT: Height */
189875  int *piPgno /* OUT: Page number */
189876 ){
189877  *piPgno = (int)(iRowid & (((i64)1 << FTS5_DATA_PAGE_B) - 1));
189878  iRowid >>= FTS5_DATA_PAGE_B;
189879 
189880  *piHeight = (int)(iRowid & (((i64)1 << FTS5_DATA_HEIGHT_B) - 1));
189881  iRowid >>= FTS5_DATA_HEIGHT_B;
189882 
189883  *pbDlidx = (int)(iRowid & 0x0001);
189884  iRowid >>= FTS5_DATA_DLI_B;
189885 
189886  *piSegid = (int)(iRowid & (((i64)1 << FTS5_DATA_ID_B) - 1));
189887 }
189888 
189889 static void fts5DebugRowid(int *pRc, Fts5Buffer *pBuf, i64 iKey){
189890  int iSegid, iHeight, iPgno, bDlidx; /* Rowid compenents */
189891  fts5DecodeRowid(iKey, &iSegid, &bDlidx, &iHeight, &iPgno);
189892 
189893  if( iSegid==0 ){
189894  if( iKey==FTS5_AVERAGES_ROWID ){
189895  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{averages} ");
189896  }else{
189897  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{structure}");
189898  }
189899  }
189900  else{
189901  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "{%ssegid=%d h=%d pgno=%d}",
189902  bDlidx ? "dlidx " : "", iSegid, iHeight, iPgno
189903  );
189904  }
189905 }
189906 
189907 static void fts5DebugStructure(
189908  int *pRc, /* IN/OUT: error code */
189909  Fts5Buffer *pBuf,
189910  Fts5Structure *p
189911 ){
189912  int iLvl, iSeg; /* Iterate through levels, segments */
189913 
189914  for(iLvl=0; iLvl<p->nLevel; iLvl++){
189915  Fts5StructureLevel *pLvl = &p->aLevel[iLvl];
189916  sqlite3Fts5BufferAppendPrintf(pRc, pBuf,
189917  " {lvl=%d nMerge=%d nSeg=%d", iLvl, pLvl->nMerge, pLvl->nSeg
189918  );
189919  for(iSeg=0; iSeg<pLvl->nSeg; iSeg++){
189920  Fts5StructureSegment *pSeg = &pLvl->aSeg[iSeg];
189921  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " {id=%d leaves=%d..%d}",
189922  pSeg->iSegid, pSeg->pgnoFirst, pSeg->pgnoLast
189923  );
189924  }
189925  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "}");
189926  }
189927 }
189928 
189929 /*
189930 ** This is part of the fts5_decode() debugging aid.
189931 **
189932 ** Arguments pBlob/nBlob contain a serialized Fts5Structure object. This
189933 ** function appends a human-readable representation of the same object
189934 ** to the buffer passed as the second argument.
189935 */
189936 static void fts5DecodeStructure(
189937  int *pRc, /* IN/OUT: error code */
189938  Fts5Buffer *pBuf,
189939  const u8 *pBlob, int nBlob
189940 ){
189941  int rc; /* Return code */
189942  Fts5Structure *p = 0; /* Decoded structure object */
189943 
189944  rc = fts5StructureDecode(pBlob, nBlob, 0, &p);
189945  if( rc!=SQLITE_OK ){
189946  *pRc = rc;
189947  return;
189948  }
189949 
189950  fts5DebugStructure(pRc, pBuf, p);
189951  fts5StructureRelease(p);
189952 }
189953 
189954 /*
189955 ** This is part of the fts5_decode() debugging aid.
189956 **
189957 ** Arguments pBlob/nBlob contain an "averages" record. This function
189958 ** appends a human-readable representation of record to the buffer passed
189959 ** as the second argument.
189960 */
189961 static void fts5DecodeAverages(
189962  int *pRc, /* IN/OUT: error code */
189963  Fts5Buffer *pBuf,
189964  const u8 *pBlob, int nBlob
189965 ){
189966  int i = 0;
189967  const char *zSpace = "";
189968 
189969  while( i<nBlob ){
189970  u64 iVal;
189971  i += sqlite3Fts5GetVarint(&pBlob[i], &iVal);
189972  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, "%s%d", zSpace, (int)iVal);
189973  zSpace = " ";
189974  }
189975 }
189976 
189977 /*
189978 ** Buffer (a/n) is assumed to contain a list of serialized varints. Read
189979 ** each varint and append its string representation to buffer pBuf. Return
189980 ** after either the input buffer is exhausted or a 0 value is read.
189981 **
189982 ** The return value is the number of bytes read from the input buffer.
189983 */
189984 static int fts5DecodePoslist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
189985  int iOff = 0;
189986  while( iOff<n ){
189987  int iVal;
189988  iOff += fts5GetVarint32(&a[iOff], iVal);
189989  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %d", iVal);
189990  }
189991  return iOff;
189992 }
189993 
189994 /*
189995 ** The start of buffer (a/n) contains the start of a doclist. The doclist
189996 ** may or may not finish within the buffer. This function appends a text
189997 ** representation of the part of the doclist that is present to buffer
189998 ** pBuf.
189999 **
190000 ** The return value is the number of bytes read from the input buffer.
190001 */
190002 static int fts5DecodeDoclist(int *pRc, Fts5Buffer *pBuf, const u8 *a, int n){
190003  i64 iDocid = 0;
190004  int iOff = 0;
190005 
190006  if( n>0 ){
190007  iOff = sqlite3Fts5GetVarint(a, (u64*)&iDocid);
190008  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
190009  }
190010  while( iOff<n ){
190011  int nPos;
190012  int bDel;
190013  iOff += fts5GetPoslistSize(&a[iOff], &nPos, &bDel);
190014  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " nPos=%d%s", nPos, bDel?"*":"");
190015  iOff += fts5DecodePoslist(pRc, pBuf, &a[iOff], MIN(n-iOff, nPos));
190016  if( iOff<n ){
190017  i64 iDelta;
190018  iOff += sqlite3Fts5GetVarint(&a[iOff], (u64*)&iDelta);
190019  iDocid += iDelta;
190020  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " id=%lld", iDocid);
190021  }
190022  }
190023 
190024  return iOff;
190025 }
190026 
190027 /*
190028 ** This function is part of the fts5_decode() debugging function. It is
190029 ** only ever used with detail=none tables.
190030 **
190031 ** Buffer (pData/nData) contains a doclist in the format used by detail=none
190032 ** tables. This function appends a human-readable version of that list to
190033 ** buffer pBuf.
190034 **
190035 ** If *pRc is other than SQLITE_OK when this function is called, it is a
190036 ** no-op. If an OOM or other error occurs within this function, *pRc is
190037 ** set to an SQLite error code before returning. The final state of buffer
190038 ** pBuf is undefined in this case.
190039 */
190040 static void fts5DecodeRowidList(
190041  int *pRc, /* IN/OUT: Error code */
190042  Fts5Buffer *pBuf, /* Buffer to append text to */
190043  const u8 *pData, int nData /* Data to decode list-of-rowids from */
190044 ){
190045  int i = 0;
190046  i64 iRowid = 0;
190047 
190048  while( i<nData ){
190049  const char *zApp = "";
190050  u64 iVal;
190051  i += sqlite3Fts5GetVarint(&pData[i], &iVal);
190052  iRowid += iVal;
190053 
190054  if( i<nData && pData[i]==0x00 ){
190055  i++;
190056  if( i<nData && pData[i]==0x00 ){
190057  i++;
190058  zApp = "+";
190059  }else{
190060  zApp = "*";
190061  }
190062  }
190063 
190064  sqlite3Fts5BufferAppendPrintf(pRc, pBuf, " %lld%s", iRowid, zApp);
190065  }
190066 }
190067 
190068 /*
190069 ** The implementation of user-defined scalar function fts5_decode().
190070 */
190071 static void fts5DecodeFunction(
190072  sqlite3_context *pCtx, /* Function call context */
190073  int nArg, /* Number of args (always 2) */
190074  sqlite3_value **apVal /* Function arguments */
190075 ){
190076  i64 iRowid; /* Rowid for record being decoded */
190077  int iSegid,iHeight,iPgno,bDlidx;/* Rowid components */
190078  const u8 *aBlob; int n; /* Record to decode */
190079  u8 *a = 0;
190080  Fts5Buffer s; /* Build up text to return here */
190081  int rc = SQLITE_OK; /* Return code */
190082  int nSpace = 0;
190083  int eDetailNone = (sqlite3_user_data(pCtx)!=0);
190084 
190085  assert( nArg==2 );
190086  UNUSED_PARAM(nArg);
190087  memset(&s, 0, sizeof(Fts5Buffer));
190088  iRowid = sqlite3_value_int64(apVal[0]);
190089 
190090  /* Make a copy of the second argument (a blob) in aBlob[]. The aBlob[]
190091  ** copy is followed by FTS5_DATA_ZERO_PADDING 0x00 bytes, which prevents
190092  ** buffer overreads even if the record is corrupt. */
190093  n = sqlite3_value_bytes(apVal[1]);
190094  aBlob = sqlite3_value_blob(apVal[1]);
190095  nSpace = n + FTS5_DATA_ZERO_PADDING;
190096  a = (u8*)sqlite3Fts5MallocZero(&rc, nSpace);
190097  if( a==0 ) goto decode_out;
190098  memcpy(a, aBlob, n);
190099 
190100 
190101  fts5DecodeRowid(iRowid, &iSegid, &bDlidx, &iHeight, &iPgno);
190102 
190103  fts5DebugRowid(&rc, &s, iRowid);
190104  if( bDlidx ){
190105  Fts5Data dlidx;
190106  Fts5DlidxLvl lvl;
190107 
190108  dlidx.p = a;
190109  dlidx.nn = n;
190110 
190111  memset(&lvl, 0, sizeof(Fts5DlidxLvl));
190112  lvl.pData = &dlidx;
190113  lvl.iLeafPgno = iPgno;
190114 
190115  for(fts5DlidxLvlNext(&lvl); lvl.bEof==0; fts5DlidxLvlNext(&lvl)){
190116  sqlite3Fts5BufferAppendPrintf(&rc, &s,
190117  " %d(%lld)", lvl.iLeafPgno, lvl.iRowid
190118  );
190119  }
190120  }else if( iSegid==0 ){
190121  if( iRowid==FTS5_AVERAGES_ROWID ){
190122  fts5DecodeAverages(&rc, &s, a, n);
190123  }else{
190124  fts5DecodeStructure(&rc, &s, a, n);
190125  }
190126  }else if( eDetailNone ){
190127  Fts5Buffer term; /* Current term read from page */
190128  int szLeaf;
190129  int iPgidxOff = szLeaf = fts5GetU16(&a[2]);
190130  int iTermOff;
190131  int nKeep = 0;
190132  int iOff;
190133 
190134  memset(&term, 0, sizeof(Fts5Buffer));
190135 
190136  /* Decode any entries that occur before the first term. */
190137  if( szLeaf<n ){
190138  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], iTermOff);
190139  }else{
190140  iTermOff = szLeaf;
190141  }
190142  fts5DecodeRowidList(&rc, &s, &a[4], iTermOff-4);
190143 
190144  iOff = iTermOff;
190145  while( iOff<szLeaf ){
190146  int nAppend;
190147 
190148  /* Read the term data for the next term*/
190149  iOff += fts5GetVarint32(&a[iOff], nAppend);
190150  term.n = nKeep;
190151  fts5BufferAppendBlob(&rc, &term, nAppend, &a[iOff]);
190152  sqlite3Fts5BufferAppendPrintf(
190153  &rc, &s, " term=%.*s", term.n, (const char*)term.p
190154  );
190155  iOff += nAppend;
190156 
190157  /* Figure out where the doclist for this term ends */
190158  if( iPgidxOff<n ){
190159  int nIncr;
190160  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nIncr);
190161  iTermOff += nIncr;
190162  }else{
190163  iTermOff = szLeaf;
190164  }
190165 
190166  fts5DecodeRowidList(&rc, &s, &a[iOff], iTermOff-iOff);
190167  iOff = iTermOff;
190168  if( iOff<szLeaf ){
190169  iOff += fts5GetVarint32(&a[iOff], nKeep);
190170  }
190171  }
190172 
190173  fts5BufferFree(&term);
190174  }else{
190175  Fts5Buffer term; /* Current term read from page */
190176  int szLeaf; /* Offset of pgidx in a[] */
190177  int iPgidxOff;
190178  int iPgidxPrev = 0; /* Previous value read from pgidx */
190179  int iTermOff = 0;
190180  int iRowidOff = 0;
190181  int iOff;
190182  int nDoclist;
190183 
190184  memset(&term, 0, sizeof(Fts5Buffer));
190185 
190186  if( n<4 ){
190187  sqlite3Fts5BufferSet(&rc, &s, 7, (const u8*)"corrupt");
190188  goto decode_out;
190189  }else{
190190  iRowidOff = fts5GetU16(&a[0]);
190191  iPgidxOff = szLeaf = fts5GetU16(&a[2]);
190192  if( iPgidxOff<n ){
190193  fts5GetVarint32(&a[iPgidxOff], iTermOff);
190194  }
190195  }
190196 
190197  /* Decode the position list tail at the start of the page */
190198  if( iRowidOff!=0 ){
190199  iOff = iRowidOff;
190200  }else if( iTermOff!=0 ){
190201  iOff = iTermOff;
190202  }else{
190203  iOff = szLeaf;
190204  }
190205  fts5DecodePoslist(&rc, &s, &a[4], iOff-4);
190206 
190207  /* Decode any more doclist data that appears on the page before the
190208  ** first term. */
190209  nDoclist = (iTermOff ? iTermOff : szLeaf) - iOff;
190210  fts5DecodeDoclist(&rc, &s, &a[iOff], nDoclist);
190211 
190212  while( iPgidxOff<n ){
190213  int bFirst = (iPgidxOff==szLeaf); /* True for first term on page */
190214  int nByte; /* Bytes of data */
190215  int iEnd;
190216 
190217  iPgidxOff += fts5GetVarint32(&a[iPgidxOff], nByte);
190218  iPgidxPrev += nByte;
190219  iOff = iPgidxPrev;
190220 
190221  if( iPgidxOff<n ){
190222  fts5GetVarint32(&a[iPgidxOff], nByte);
190223  iEnd = iPgidxPrev + nByte;
190224  }else{
190225  iEnd = szLeaf;
190226  }
190227 
190228  if( bFirst==0 ){
190229  iOff += fts5GetVarint32(&a[iOff], nByte);
190230  term.n = nByte;
190231  }
190232  iOff += fts5GetVarint32(&a[iOff], nByte);
190233  fts5BufferAppendBlob(&rc, &term, nByte, &a[iOff]);
190234  iOff += nByte;
190235 
190236  sqlite3Fts5BufferAppendPrintf(
190237  &rc, &s, " term=%.*s", term.n, (const char*)term.p
190238  );
190239  iOff += fts5DecodeDoclist(&rc, &s, &a[iOff], iEnd-iOff);
190240  }
190241 
190242  fts5BufferFree(&term);
190243  }
190244 
190245  decode_out:
190246  sqlite3_free(a);
190247  if( rc==SQLITE_OK ){
190248  sqlite3_result_text(pCtx, (const char*)s.p, s.n, SQLITE_TRANSIENT);
190249  }else{
190250  sqlite3_result_error_code(pCtx, rc);
190251  }
190252  fts5BufferFree(&s);
190253 }
190254 
190255 /*
190256 ** The implementation of user-defined scalar function fts5_rowid().
190257 */
190258 static void fts5RowidFunction(
190259  sqlite3_context *pCtx, /* Function call context */
190260  int nArg, /* Number of args (always 2) */
190261  sqlite3_value **apVal /* Function arguments */
190262 ){
190263  const char *zArg;
190264  if( nArg==0 ){
190265  sqlite3_result_error(pCtx, "should be: fts5_rowid(subject, ....)", -1);
190266  }else{
190267  zArg = (const char*)sqlite3_value_text(apVal[0]);
190268  if( 0==sqlite3_stricmp(zArg, "segment") ){
190269  i64 iRowid;
190270  int segid, pgno;
190271  if( nArg!=3 ){
190272  sqlite3_result_error(pCtx,
190273  "should be: fts5_rowid('segment', segid, pgno))", -1
190274  );
190275  }else{
190276  segid = sqlite3_value_int(apVal[1]);
190277  pgno = sqlite3_value_int(apVal[2]);
190278  iRowid = FTS5_SEGMENT_ROWID(segid, pgno);
190279  sqlite3_result_int64(pCtx, iRowid);
190280  }
190281  }else{
190282  sqlite3_result_error(pCtx,
190283  "first arg to fts5_rowid() must be 'segment'" , -1
190284  );
190285  }
190286  }
190287 }
190288 
190289 /*
190290 ** This is called as part of registering the FTS5 module with database
190291 ** connection db. It registers several user-defined scalar functions useful
190292 ** with FTS5.
190293 **
190294 ** If successful, SQLITE_OK is returned. If an error occurs, some other
190295 ** SQLite error code is returned instead.
190296 */
190297 static int sqlite3Fts5IndexInit(sqlite3 *db){
190298  int rc = sqlite3_create_function(
190299  db, "fts5_decode", 2, SQLITE_UTF8, 0, fts5DecodeFunction, 0, 0
190300  );
190301 
190302  if( rc==SQLITE_OK ){
190304  db, "fts5_decode_none", 2,
190305  SQLITE_UTF8, (void*)db, fts5DecodeFunction, 0, 0
190306  );
190307  }
190308 
190309  if( rc==SQLITE_OK ){
190311  db, "fts5_rowid", -1, SQLITE_UTF8, 0, fts5RowidFunction, 0, 0
190312  );
190313  }
190314  return rc;
190315 }
190316 
190317 
190318 static int sqlite3Fts5IndexReset(Fts5Index *p){
190319  assert( p->pStruct==0 || p->iStructVersion!=0 );
190320  if( fts5IndexDataVersion(p)!=p->iStructVersion ){
190321  fts5StructureInvalidate(p);
190322  }
190323  return fts5IndexReturn(p);
190324 }
190325 
190326 /*
190327 ** 2014 Jun 09
190328 **
190329 ** The author disclaims copyright to this source code. In place of
190330 ** a legal notice, here is a blessing:
190331 **
190332 ** May you do good and not evil.
190333 ** May you find forgiveness for yourself and forgive others.
190334 ** May you share freely, never taking more than you give.
190335 **
190336 ******************************************************************************
190337 **
190338 ** This is an SQLite module implementing full-text search.
190339 */
190340 
190341 
190342 /* #include "fts5Int.h" */
190343 
190344 /*
190345 ** This variable is set to false when running tests for which the on disk
190346 ** structures should not be corrupt. Otherwise, true. If it is false, extra
190347 ** assert() conditions in the fts5 code are activated - conditions that are
190348 ** only true if it is guaranteed that the fts5 database is not corrupt.
190349 */
190350 SQLITE_API int sqlite3_fts5_may_be_corrupt = 1;
190351 
190352 
190353 typedef struct Fts5Auxdata Fts5Auxdata;
190354 typedef struct Fts5Auxiliary Fts5Auxiliary;
190355 typedef struct Fts5Cursor Fts5Cursor;
190356 typedef struct Fts5Sorter Fts5Sorter;
190357 typedef struct Fts5Table Fts5Table;
190358 typedef struct Fts5TokenizerModule Fts5TokenizerModule;
190359 
190360 /*
190361 ** NOTES ON TRANSACTIONS:
190362 **
190363 ** SQLite invokes the following virtual table methods as transactions are
190364 ** opened and closed by the user:
190365 **
190366 ** xBegin(): Start of a new transaction.
190367 ** xSync(): Initial part of two-phase commit.
190368 ** xCommit(): Final part of two-phase commit.
190369 ** xRollback(): Rollback the transaction.
190370 **
190371 ** Anything that is required as part of a commit that may fail is performed
190372 ** in the xSync() callback. Current versions of SQLite ignore any errors
190373 ** returned by xCommit().
190374 **
190375 ** And as sub-transactions are opened/closed:
190376 **
190377 ** xSavepoint(int S): Open savepoint S.
190378 ** xRelease(int S): Commit and close savepoint S.
190379 ** xRollbackTo(int S): Rollback to start of savepoint S.
190380 **
190381 ** During a write-transaction the fts5_index.c module may cache some data
190382 ** in-memory. It is flushed to disk whenever xSync(), xRelease() or
190383 ** xSavepoint() is called. And discarded whenever xRollback() or xRollbackTo()
190384 ** is called.
190385 **
190386 ** Additionally, if SQLITE_DEBUG is defined, an instance of the following
190387 ** structure is used to record the current transaction state. This information
190388 ** is not required, but it is used in the assert() statements executed by
190389 ** function fts5CheckTransactionState() (see below).
190390 */
190391 struct Fts5TransactionState {
190392  int eState; /* 0==closed, 1==open, 2==synced */
190393  int iSavepoint; /* Number of open savepoints (0 -> none) */
190394 };
190395 
190396 /*
190397 ** A single object of this type is allocated when the FTS5 module is
190398 ** registered with a database handle. It is used to store pointers to
190399 ** all registered FTS5 extensions - tokenizers and auxiliary functions.
190400 */
190401 struct Fts5Global {
190402  fts5_api api; /* User visible part of object (see fts5.h) */
190403  sqlite3 *db; /* Associated database connection */
190404  i64 iNextId; /* Used to allocate unique cursor ids */
190405  Fts5Auxiliary *pAux; /* First in list of all aux. functions */
190406  Fts5TokenizerModule *pTok; /* First in list of all tokenizer modules */
190407  Fts5TokenizerModule *pDfltTok; /* Default tokenizer module */
190408  Fts5Cursor *pCsr; /* First in list of all open cursors */
190409 };
190410 
190411 /*
190412 ** Each auxiliary function registered with the FTS5 module is represented
190413 ** by an object of the following type. All such objects are stored as part
190414 ** of the Fts5Global.pAux list.
190415 */
190416 struct Fts5Auxiliary {
190417  Fts5Global *pGlobal; /* Global context for this function */
190418  char *zFunc; /* Function name (nul-terminated) */
190419  void *pUserData; /* User-data pointer */
190420  fts5_extension_function xFunc; /* Callback function */
190421  void (*xDestroy)(void*); /* Destructor function */
190422  Fts5Auxiliary *pNext; /* Next registered auxiliary function */
190423 };
190424 
190425 /*
190426 ** Each tokenizer module registered with the FTS5 module is represented
190427 ** by an object of the following type. All such objects are stored as part
190428 ** of the Fts5Global.pTok list.
190429 */
190430 struct Fts5TokenizerModule {
190431  char *zName; /* Name of tokenizer */
190432  void *pUserData; /* User pointer passed to xCreate() */
190433  fts5_tokenizer x; /* Tokenizer functions */
190434  void (*xDestroy)(void*); /* Destructor function */
190435  Fts5TokenizerModule *pNext; /* Next registered tokenizer module */
190436 };
190437 
190438 /*
190439 ** Virtual-table object.
190440 */
190441 struct Fts5Table {
190442  sqlite3_vtab base; /* Base class used by SQLite core */
190443  Fts5Config *pConfig; /* Virtual table configuration */
190444  Fts5Index *pIndex; /* Full-text index */
190445  Fts5Storage *pStorage; /* Document store */
190446  Fts5Global *pGlobal; /* Global (connection wide) data */
190447  Fts5Cursor *pSortCsr; /* Sort data from this cursor */
190448 #ifdef SQLITE_DEBUG
190449  struct Fts5TransactionState ts;
190450 #endif
190451 };
190452 
190453 struct Fts5MatchPhrase {
190454  Fts5Buffer *pPoslist; /* Pointer to current poslist */
190455  int nTerm; /* Size of phrase in terms */
190456 };
190457 
190458 /*
190459 ** pStmt:
190460 ** SELECT rowid, <fts> FROM <fts> ORDER BY +rank;
190461 **
190462 ** aIdx[]:
190463 ** There is one entry in the aIdx[] array for each phrase in the query,
190464 ** the value of which is the offset within aPoslist[] following the last
190465 ** byte of the position list for the corresponding phrase.
190466 */
190467 struct Fts5Sorter {
190468  sqlite3_stmt *pStmt;
190469  i64 iRowid; /* Current rowid */
190470  const u8 *aPoslist; /* Position lists for current row */
190471  int nIdx; /* Number of entries in aIdx[] */
190472  int aIdx[1]; /* Offsets into aPoslist for current row */
190473 };
190474 
190475 
190476 /*
190477 ** Virtual-table cursor object.
190478 **
190479 ** iSpecial:
190480 ** If this is a 'special' query (refer to function fts5SpecialMatch()),
190481 ** then this variable contains the result of the query.
190482 **
190483 ** iFirstRowid, iLastRowid:
190484 ** These variables are only used for FTS5_PLAN_MATCH cursors. Assuming the
190485 ** cursor iterates in ascending order of rowids, iFirstRowid is the lower
190486 ** limit of rowids to return, and iLastRowid the upper. In other words, the
190487 ** WHERE clause in the user's query might have been:
190488 **
190489 ** <tbl> MATCH <expr> AND rowid BETWEEN $iFirstRowid AND $iLastRowid
190490 **
190491 ** If the cursor iterates in descending order of rowid, iFirstRowid
190492 ** is the upper limit (i.e. the "first" rowid visited) and iLastRowid
190493 ** the lower.
190494 */
190495 struct Fts5Cursor {
190496  sqlite3_vtab_cursor base; /* Base class used by SQLite core */
190497  Fts5Cursor *pNext; /* Next cursor in Fts5Cursor.pCsr list */
190498  int *aColumnSize; /* Values for xColumnSize() */
190499  i64 iCsrId; /* Cursor id */
190500 
190501  /* Zero from this point onwards on cursor reset */
190502  int ePlan; /* FTS5_PLAN_XXX value */
190503  int bDesc; /* True for "ORDER BY rowid DESC" queries */
190504  i64 iFirstRowid; /* Return no rowids earlier than this */
190505  i64 iLastRowid; /* Return no rowids later than this */
190506  sqlite3_stmt *pStmt; /* Statement used to read %_content */
190507  Fts5Expr *pExpr; /* Expression for MATCH queries */
190508  Fts5Sorter *pSorter; /* Sorter for "ORDER BY rank" queries */
190509  int csrflags; /* Mask of cursor flags (see below) */
190510  i64 iSpecial; /* Result of special query */
190511 
190512  /* "rank" function. Populated on demand from vtab.xColumn(). */
190513  char *zRank; /* Custom rank function */
190514  char *zRankArgs; /* Custom rank function args */
190515  Fts5Auxiliary *pRank; /* Rank callback (or NULL) */
190516  int nRankArg; /* Number of trailing arguments for rank() */
190517  sqlite3_value **apRankArg; /* Array of trailing arguments */
190518  sqlite3_stmt *pRankArgStmt; /* Origin of objects in apRankArg[] */
190519 
190520  /* Auxiliary data storage */
190521  Fts5Auxiliary *pAux; /* Currently executing extension function */
190522  Fts5Auxdata *pAuxdata; /* First in linked list of saved aux-data */
190523 
190524  /* Cache used by auxiliary functions xInst() and xInstCount() */
190525  Fts5PoslistReader *aInstIter; /* One for each phrase */
190526  int nInstAlloc; /* Size of aInst[] array (entries / 3) */
190527  int nInstCount; /* Number of phrase instances */
190528  int *aInst; /* 3 integers per phrase instance */
190529 };
190530 
190531 /*
190532 ** Bits that make up the "idxNum" parameter passed indirectly by
190533 ** xBestIndex() to xFilter().
190534 */
190535 #define FTS5_BI_MATCH 0x0001 /* <tbl> MATCH ? */
190536 #define FTS5_BI_RANK 0x0002 /* rank MATCH ? */
190537 #define FTS5_BI_ROWID_EQ 0x0004 /* rowid == ? */
190538 #define FTS5_BI_ROWID_LE 0x0008 /* rowid <= ? */
190539 #define FTS5_BI_ROWID_GE 0x0010 /* rowid >= ? */
190540 
190541 #define FTS5_BI_ORDER_RANK 0x0020
190542 #define FTS5_BI_ORDER_ROWID 0x0040
190543 #define FTS5_BI_ORDER_DESC 0x0080
190544 
190545 /*
190546 ** Values for Fts5Cursor.csrflags
190547 */
190548 #define FTS5CSR_EOF 0x01
190549 #define FTS5CSR_REQUIRE_CONTENT 0x02
190550 #define FTS5CSR_REQUIRE_DOCSIZE 0x04
190551 #define FTS5CSR_REQUIRE_INST 0x08
190552 #define FTS5CSR_FREE_ZRANK 0x10
190553 #define FTS5CSR_REQUIRE_RESEEK 0x20
190554 #define FTS5CSR_REQUIRE_POSLIST 0x40
190555 
190556 #define BitFlagAllTest(x,y) (((x) & (y))==(y))
190557 #define BitFlagTest(x,y) (((x) & (y))!=0)
190558 
190559 
190560 /*
190561 ** Macros to Set(), Clear() and Test() cursor flags.
190562 */
190563 #define CsrFlagSet(pCsr, flag) ((pCsr)->csrflags |= (flag))
190564 #define CsrFlagClear(pCsr, flag) ((pCsr)->csrflags &= ~(flag))
190565 #define CsrFlagTest(pCsr, flag) ((pCsr)->csrflags & (flag))
190566 
190567 struct Fts5Auxdata {
190568  Fts5Auxiliary *pAux; /* Extension to which this belongs */
190569  void *pPtr; /* Pointer value */
190570  void(*xDelete)(void*); /* Destructor */
190571  Fts5Auxdata *pNext; /* Next object in linked list */
190572 };
190573 
190574 #ifdef SQLITE_DEBUG
190575 #define FTS5_BEGIN 1
190576 #define FTS5_SYNC 2
190577 #define FTS5_COMMIT 3
190578 #define FTS5_ROLLBACK 4
190579 #define FTS5_SAVEPOINT 5
190580 #define FTS5_RELEASE 6
190581 #define FTS5_ROLLBACKTO 7
190582 static void fts5CheckTransactionState(Fts5Table *p, int op, int iSavepoint){
190583  switch( op ){
190584  case FTS5_BEGIN:
190585  assert( p->ts.eState==0 );
190586  p->ts.eState = 1;
190587  p->ts.iSavepoint = -1;
190588  break;
190589 
190590  case FTS5_SYNC:
190591  assert( p->ts.eState==1 );
190592  p->ts.eState = 2;
190593  break;
190594 
190595  case FTS5_COMMIT:
190596  assert( p->ts.eState==2 );
190597  p->ts.eState = 0;
190598  break;
190599 
190600  case FTS5_ROLLBACK:
190601  assert( p->ts.eState==1 || p->ts.eState==2 || p->ts.eState==0 );
190602  p->ts.eState = 0;
190603  break;
190604 
190605  case FTS5_SAVEPOINT:
190606  assert( p->ts.eState==1 );
190607  assert( iSavepoint>=0 );
190608  assert( iSavepoint>p->ts.iSavepoint );
190609  p->ts.iSavepoint = iSavepoint;
190610  break;
190611 
190612  case FTS5_RELEASE:
190613  assert( p->ts.eState==1 );
190614  assert( iSavepoint>=0 );
190615  assert( iSavepoint<=p->ts.iSavepoint );
190616  p->ts.iSavepoint = iSavepoint-1;
190617  break;
190618 
190619  case FTS5_ROLLBACKTO:
190620  assert( p->ts.eState==1 );
190621  assert( iSavepoint>=0 );
190622  assert( iSavepoint<=p->ts.iSavepoint );
190623  p->ts.iSavepoint = iSavepoint;
190624  break;
190625  }
190626 }
190627 #else
190628 # define fts5CheckTransactionState(x,y,z)
190629 #endif
190630 
190631 /*
190632 ** Return true if pTab is a contentless table.
190633 */
190634 static int fts5IsContentless(Fts5Table *pTab){
190635  return pTab->pConfig->eContent==FTS5_CONTENT_NONE;
190636 }
190637 
190638 /*
190639 ** Delete a virtual table handle allocated by fts5InitVtab().
190640 */
190641 static void fts5FreeVtab(Fts5Table *pTab){
190642  if( pTab ){
190643  sqlite3Fts5IndexClose(pTab->pIndex);
190644  sqlite3Fts5StorageClose(pTab->pStorage);
190645  sqlite3Fts5ConfigFree(pTab->pConfig);
190646  sqlite3_free(pTab);
190647  }
190648 }
190649 
190650 /*
190651 ** The xDisconnect() virtual table method.
190652 */
190653 static int fts5DisconnectMethod(sqlite3_vtab *pVtab){
190654  fts5FreeVtab((Fts5Table*)pVtab);
190655  return SQLITE_OK;
190656 }
190657 
190658 /*
190659 ** The xDestroy() virtual table method.
190660 */
190661 static int fts5DestroyMethod(sqlite3_vtab *pVtab){
190662  Fts5Table *pTab = (Fts5Table*)pVtab;
190663  int rc = sqlite3Fts5DropAll(pTab->pConfig);
190664  if( rc==SQLITE_OK ){
190665  fts5FreeVtab((Fts5Table*)pVtab);
190666  }
190667  return rc;
190668 }
190669 
190670 /*
190671 ** This function is the implementation of both the xConnect and xCreate
190672 ** methods of the FTS3 virtual table.
190673 **
190674 ** The argv[] array contains the following:
190675 **
190676 ** argv[0] -> module name ("fts5")
190677 ** argv[1] -> database name
190678 ** argv[2] -> table name
190679 ** argv[...] -> "column name" and other module argument fields.
190680 */
190681 static int fts5InitVtab(
190682  int bCreate, /* True for xCreate, false for xConnect */
190683  sqlite3 *db, /* The SQLite database connection */
190684  void *pAux, /* Hash table containing tokenizers */
190685  int argc, /* Number of elements in argv array */
190686  const char * const *argv, /* xCreate/xConnect argument array */
190687  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
190688  char **pzErr /* Write any error message here */
190689 ){
190690  Fts5Global *pGlobal = (Fts5Global*)pAux;
190691  const char **azConfig = (const char**)argv;
190692  int rc = SQLITE_OK; /* Return code */
190693  Fts5Config *pConfig = 0; /* Results of parsing argc/argv */
190694  Fts5Table *pTab = 0; /* New virtual table object */
190695 
190696  /* Allocate the new vtab object and parse the configuration */
190697  pTab = (Fts5Table*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Table));
190698  if( rc==SQLITE_OK ){
190699  rc = sqlite3Fts5ConfigParse(pGlobal, db, argc, azConfig, &pConfig, pzErr);
190700  assert( (rc==SQLITE_OK && *pzErr==0) || pConfig==0 );
190701  }
190702  if( rc==SQLITE_OK ){
190703  pTab->pConfig = pConfig;
190704  pTab->pGlobal = pGlobal;
190705  }
190706 
190707  /* Open the index sub-system */
190708  if( rc==SQLITE_OK ){
190709  rc = sqlite3Fts5IndexOpen(pConfig, bCreate, &pTab->pIndex, pzErr);
190710  }
190711 
190712  /* Open the storage sub-system */
190713  if( rc==SQLITE_OK ){
190714  rc = sqlite3Fts5StorageOpen(
190715  pConfig, pTab->pIndex, bCreate, &pTab->pStorage, pzErr
190716  );
190717  }
190718 
190719  /* Call sqlite3_declare_vtab() */
190720  if( rc==SQLITE_OK ){
190721  rc = sqlite3Fts5ConfigDeclareVtab(pConfig);
190722  }
190723 
190724  /* Load the initial configuration */
190725  if( rc==SQLITE_OK ){
190726  assert( pConfig->pzErrmsg==0 );
190727  pConfig->pzErrmsg = pzErr;
190728  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
190729  sqlite3Fts5IndexRollback(pTab->pIndex);
190730  pConfig->pzErrmsg = 0;
190731  }
190732 
190733  if( rc!=SQLITE_OK ){
190734  fts5FreeVtab(pTab);
190735  pTab = 0;
190736  }else if( bCreate ){
190737  fts5CheckTransactionState(pTab, FTS5_BEGIN, 0);
190738  }
190739  *ppVTab = (sqlite3_vtab*)pTab;
190740  return rc;
190741 }
190742 
190743 /*
190744 ** The xConnect() and xCreate() methods for the virtual table. All the
190745 ** work is done in function fts5InitVtab().
190746 */
190747 static int fts5ConnectMethod(
190748  sqlite3 *db, /* Database connection */
190749  void *pAux, /* Pointer to tokenizer hash table */
190750  int argc, /* Number of elements in argv array */
190751  const char * const *argv, /* xCreate/xConnect argument array */
190752  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
190753  char **pzErr /* OUT: sqlite3_malloc'd error message */
190754 ){
190755  return fts5InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
190756 }
190757 static int fts5CreateMethod(
190758  sqlite3 *db, /* Database connection */
190759  void *pAux, /* Pointer to tokenizer hash table */
190760  int argc, /* Number of elements in argv array */
190761  const char * const *argv, /* xCreate/xConnect argument array */
190762  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
190763  char **pzErr /* OUT: sqlite3_malloc'd error message */
190764 ){
190765  return fts5InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
190766 }
190767 
190768 /*
190769 ** The different query plans.
190770 */
190771 #define FTS5_PLAN_MATCH 1 /* (<tbl> MATCH ?) */
190772 #define FTS5_PLAN_SOURCE 2 /* A source cursor for SORTED_MATCH */
190773 #define FTS5_PLAN_SPECIAL 3 /* An internal query */
190774 #define FTS5_PLAN_SORTED_MATCH 4 /* (<tbl> MATCH ? ORDER BY rank) */
190775 #define FTS5_PLAN_SCAN 5 /* No usable constraint */
190776 #define FTS5_PLAN_ROWID 6 /* (rowid = ?) */
190777 
190778 /*
190779 ** Set the SQLITE_INDEX_SCAN_UNIQUE flag in pIdxInfo->flags. Unless this
190780 ** extension is currently being used by a version of SQLite too old to
190781 ** support index-info flags. In that case this function is a no-op.
190782 */
190783 static void fts5SetUniqueFlag(sqlite3_index_info *pIdxInfo){
190784 #if SQLITE_VERSION_NUMBER>=3008012
190785 #ifndef SQLITE_CORE
190786  if( sqlite3_libversion_number()>=3008012 )
190787 #endif
190788  {
190789  pIdxInfo->idxFlags |= SQLITE_INDEX_SCAN_UNIQUE;
190790  }
190791 #endif
190792 }
190793 
190794 /*
190795 ** Implementation of the xBestIndex method for FTS5 tables. Within the
190796 ** WHERE constraint, it searches for the following:
190797 **
190798 ** 1. A MATCH constraint against the special column.
190799 ** 2. A MATCH constraint against the "rank" column.
190800 ** 3. An == constraint against the rowid column.
190801 ** 4. A < or <= constraint against the rowid column.
190802 ** 5. A > or >= constraint against the rowid column.
190803 **
190804 ** Within the ORDER BY, either:
190805 **
190806 ** 5. ORDER BY rank [ASC|DESC]
190807 ** 6. ORDER BY rowid [ASC|DESC]
190808 **
190809 ** Costs are assigned as follows:
190810 **
190811 ** a) If an unusable MATCH operator is present in the WHERE clause, the
190812 ** cost is unconditionally set to 1e50 (a really big number).
190813 **
190814 ** a) If a MATCH operator is present, the cost depends on the other
190815 ** constraints also present. As follows:
190816 **
190817 ** * No other constraints: cost=1000.0
190818 ** * One rowid range constraint: cost=750.0
190819 ** * Both rowid range constraints: cost=500.0
190820 ** * An == rowid constraint: cost=100.0
190821 **
190822 ** b) Otherwise, if there is no MATCH:
190823 **
190824 ** * No other constraints: cost=1000000.0
190825 ** * One rowid range constraint: cost=750000.0
190826 ** * Both rowid range constraints: cost=250000.0
190827 ** * An == rowid constraint: cost=10.0
190828 **
190829 ** Costs are not modified by the ORDER BY clause.
190830 */
190831 static int fts5BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
190832  Fts5Table *pTab = (Fts5Table*)pVTab;
190833  Fts5Config *pConfig = pTab->pConfig;
190834  int idxFlags = 0; /* Parameter passed through to xFilter() */
190835  int bHasMatch;
190836  int iNext;
190837  int i;
190838 
190839  struct Constraint {
190840  int op; /* Mask against sqlite3_index_constraint.op */
190841  int fts5op; /* FTS5 mask for idxFlags */
190842  int iCol; /* 0==rowid, 1==tbl, 2==rank */
190843  int omit; /* True to omit this if found */
190844  int iConsIndex; /* Index in pInfo->aConstraint[] */
190845  } aConstraint[] = {
190847  FTS5_BI_MATCH, 1, 1, -1},
190849  FTS5_BI_RANK, 2, 1, -1},
190850  {SQLITE_INDEX_CONSTRAINT_EQ, FTS5_BI_ROWID_EQ, 0, 0, -1},
190852  FTS5_BI_ROWID_LE, 0, 0, -1},
190854  FTS5_BI_ROWID_GE, 0, 0, -1},
190855  };
190856 
190857  int aColMap[3];
190858  aColMap[0] = -1;
190859  aColMap[1] = pConfig->nCol;
190860  aColMap[2] = pConfig->nCol+1;
190861 
190862  /* Set idxFlags flags for all WHERE clause terms that will be used. */
190863  for(i=0; i<pInfo->nConstraint; i++){
190864  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
190865  int j;
190866  for(j=0; j<ArraySize(aConstraint); j++){
190867  struct Constraint *pC = &aConstraint[j];
190868  if( p->iColumn==aColMap[pC->iCol] && p->op & pC->op ){
190869  if( p->usable ){
190870  pC->iConsIndex = i;
190871  idxFlags |= pC->fts5op;
190872  }else if( j==0 ){
190873  /* As there exists an unusable MATCH constraint this is an
190874  ** unusable plan. Set a prohibitively high cost. */
190875  pInfo->estimatedCost = 1e50;
190876  return SQLITE_OK;
190877  }
190878  }
190879  }
190880  }
190881 
190882  /* Set idxFlags flags for the ORDER BY clause */
190883  if( pInfo->nOrderBy==1 ){
190884  int iSort = pInfo->aOrderBy[0].iColumn;
190885  if( iSort==(pConfig->nCol+1) && BitFlagTest(idxFlags, FTS5_BI_MATCH) ){
190886  idxFlags |= FTS5_BI_ORDER_RANK;
190887  }else if( iSort==-1 ){
190888  idxFlags |= FTS5_BI_ORDER_ROWID;
190889  }
190890  if( BitFlagTest(idxFlags, FTS5_BI_ORDER_RANK|FTS5_BI_ORDER_ROWID) ){
190891  pInfo->orderByConsumed = 1;
190892  if( pInfo->aOrderBy[0].desc ){
190893  idxFlags |= FTS5_BI_ORDER_DESC;
190894  }
190895  }
190896  }
190897 
190898  /* Calculate the estimated cost based on the flags set in idxFlags. */
190899  bHasMatch = BitFlagTest(idxFlags, FTS5_BI_MATCH);
190900  if( BitFlagTest(idxFlags, FTS5_BI_ROWID_EQ) ){
190901  pInfo->estimatedCost = bHasMatch ? 100.0 : 10.0;
190902  if( bHasMatch==0 ) fts5SetUniqueFlag(pInfo);
190903  }else if( BitFlagAllTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
190904  pInfo->estimatedCost = bHasMatch ? 500.0 : 250000.0;
190905  }else if( BitFlagTest(idxFlags, FTS5_BI_ROWID_LE|FTS5_BI_ROWID_GE) ){
190906  pInfo->estimatedCost = bHasMatch ? 750.0 : 750000.0;
190907  }else{
190908  pInfo->estimatedCost = bHasMatch ? 1000.0 : 1000000.0;
190909  }
190910 
190911  /* Assign argvIndex values to each constraint in use. */
190912  iNext = 1;
190913  for(i=0; i<ArraySize(aConstraint); i++){
190914  struct Constraint *pC = &aConstraint[i];
190915  if( pC->iConsIndex>=0 ){
190916  pInfo->aConstraintUsage[pC->iConsIndex].argvIndex = iNext++;
190917  pInfo->aConstraintUsage[pC->iConsIndex].omit = (unsigned char)pC->omit;
190918  }
190919  }
190920 
190921  pInfo->idxNum = idxFlags;
190922  return SQLITE_OK;
190923 }
190924 
190925 static int fts5NewTransaction(Fts5Table *pTab){
190926  Fts5Cursor *pCsr;
190927  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
190928  if( pCsr->base.pVtab==(sqlite3_vtab*)pTab ) return SQLITE_OK;
190929  }
190930  return sqlite3Fts5StorageReset(pTab->pStorage);
190931 }
190932 
190933 /*
190934 ** Implementation of xOpen method.
190935 */
190936 static int fts5OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
190937  Fts5Table *pTab = (Fts5Table*)pVTab;
190938  Fts5Config *pConfig = pTab->pConfig;
190939  Fts5Cursor *pCsr = 0; /* New cursor object */
190940  int nByte; /* Bytes of space to allocate */
190941  int rc; /* Return code */
190942 
190943  rc = fts5NewTransaction(pTab);
190944  if( rc==SQLITE_OK ){
190945  nByte = sizeof(Fts5Cursor) + pConfig->nCol * sizeof(int);
190946  pCsr = (Fts5Cursor*)sqlite3_malloc(nByte);
190947  if( pCsr ){
190948  Fts5Global *pGlobal = pTab->pGlobal;
190949  memset(pCsr, 0, nByte);
190950  pCsr->aColumnSize = (int*)&pCsr[1];
190951  pCsr->pNext = pGlobal->pCsr;
190952  pGlobal->pCsr = pCsr;
190953  pCsr->iCsrId = ++pGlobal->iNextId;
190954  }else{
190955  rc = SQLITE_NOMEM;
190956  }
190957  }
190958  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
190959  return rc;
190960 }
190961 
190962 static int fts5StmtType(Fts5Cursor *pCsr){
190963  if( pCsr->ePlan==FTS5_PLAN_SCAN ){
190964  return (pCsr->bDesc) ? FTS5_STMT_SCAN_DESC : FTS5_STMT_SCAN_ASC;
190965  }
190966  return FTS5_STMT_LOOKUP;
190967 }
190968 
190969 /*
190970 ** This function is called after the cursor passed as the only argument
190971 ** is moved to point at a different row. It clears all cached data
190972 ** specific to the previous row stored by the cursor object.
190973 */
190974 static void fts5CsrNewrow(Fts5Cursor *pCsr){
190975  CsrFlagSet(pCsr,
190976  FTS5CSR_REQUIRE_CONTENT
190977  | FTS5CSR_REQUIRE_DOCSIZE
190978  | FTS5CSR_REQUIRE_INST
190979  | FTS5CSR_REQUIRE_POSLIST
190980  );
190981 }
190982 
190983 static void fts5FreeCursorComponents(Fts5Cursor *pCsr){
190984  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
190985  Fts5Auxdata *pData;
190986  Fts5Auxdata *pNext;
190987 
190988  sqlite3_free(pCsr->aInstIter);
190989  sqlite3_free(pCsr->aInst);
190990  if( pCsr->pStmt ){
190991  int eStmt = fts5StmtType(pCsr);
190992  sqlite3Fts5StorageStmtRelease(pTab->pStorage, eStmt, pCsr->pStmt);
190993  }
190994  if( pCsr->pSorter ){
190995  Fts5Sorter *pSorter = pCsr->pSorter;
190996  sqlite3_finalize(pSorter->pStmt);
190997  sqlite3_free(pSorter);
190998  }
190999 
191000  if( pCsr->ePlan!=FTS5_PLAN_SOURCE ){
191001  sqlite3Fts5ExprFree(pCsr->pExpr);
191002  }
191003 
191004  for(pData=pCsr->pAuxdata; pData; pData=pNext){
191005  pNext = pData->pNext;
191006  if( pData->xDelete ) pData->xDelete(pData->pPtr);
191007  sqlite3_free(pData);
191008  }
191009 
191010  sqlite3_finalize(pCsr->pRankArgStmt);
191011  sqlite3_free(pCsr->apRankArg);
191012 
191013  if( CsrFlagTest(pCsr, FTS5CSR_FREE_ZRANK) ){
191014  sqlite3_free(pCsr->zRank);
191015  sqlite3_free(pCsr->zRankArgs);
191016  }
191017 
191018  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan - (u8*)pCsr));
191019 }
191020 
191021 
191022 /*
191023 ** Close the cursor. For additional information see the documentation
191024 ** on the xClose method of the virtual table interface.
191025 */
191026 static int fts5CloseMethod(sqlite3_vtab_cursor *pCursor){
191027  if( pCursor ){
191028  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
191029  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
191030  Fts5Cursor **pp;
191031 
191032  fts5FreeCursorComponents(pCsr);
191033  /* Remove the cursor from the Fts5Global.pCsr list */
191034  for(pp=&pTab->pGlobal->pCsr; (*pp)!=pCsr; pp=&(*pp)->pNext);
191035  *pp = pCsr->pNext;
191036 
191037  sqlite3_free(pCsr);
191038  }
191039  return SQLITE_OK;
191040 }
191041 
191042 static int fts5SorterNext(Fts5Cursor *pCsr){
191043  Fts5Sorter *pSorter = pCsr->pSorter;
191044  int rc;
191045 
191046  rc = sqlite3_step(pSorter->pStmt);
191047  if( rc==SQLITE_DONE ){
191048  rc = SQLITE_OK;
191049  CsrFlagSet(pCsr, FTS5CSR_EOF);
191050  }else if( rc==SQLITE_ROW ){
191051  const u8 *a;
191052  const u8 *aBlob;
191053  int nBlob;
191054  int i;
191055  int iOff = 0;
191056  rc = SQLITE_OK;
191057 
191058  pSorter->iRowid = sqlite3_column_int64(pSorter->pStmt, 0);
191059  nBlob = sqlite3_column_bytes(pSorter->pStmt, 1);
191060  aBlob = a = sqlite3_column_blob(pSorter->pStmt, 1);
191061 
191062  /* nBlob==0 in detail=none mode. */
191063  if( nBlob>0 ){
191064  for(i=0; i<(pSorter->nIdx-1); i++){
191065  int iVal;
191066  a += fts5GetVarint32(a, iVal);
191067  iOff += iVal;
191068  pSorter->aIdx[i] = iOff;
191069  }
191070  pSorter->aIdx[i] = &aBlob[nBlob] - a;
191071  pSorter->aPoslist = a;
191072  }
191073 
191074  fts5CsrNewrow(pCsr);
191075  }
191076 
191077  return rc;
191078 }
191079 
191080 
191081 /*
191082 ** Set the FTS5CSR_REQUIRE_RESEEK flag on all FTS5_PLAN_MATCH cursors
191083 ** open on table pTab.
191084 */
191085 static void fts5TripCursors(Fts5Table *pTab){
191086  Fts5Cursor *pCsr;
191087  for(pCsr=pTab->pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
191088  if( pCsr->ePlan==FTS5_PLAN_MATCH
191089  && pCsr->base.pVtab==(sqlite3_vtab*)pTab
191090  ){
191091  CsrFlagSet(pCsr, FTS5CSR_REQUIRE_RESEEK);
191092  }
191093  }
191094 }
191095 
191096 /*
191097 ** If the REQUIRE_RESEEK flag is set on the cursor passed as the first
191098 ** argument, close and reopen all Fts5IndexIter iterators that the cursor
191099 ** is using. Then attempt to move the cursor to a rowid equal to or laster
191100 ** (in the cursors sort order - ASC or DESC) than the current rowid.
191101 **
191102 ** If the new rowid is not equal to the old, set output parameter *pbSkip
191103 ** to 1 before returning. Otherwise, leave it unchanged.
191104 **
191105 ** Return SQLITE_OK if successful or if no reseek was required, or an
191106 ** error code if an error occurred.
191107 */
191108 static int fts5CursorReseek(Fts5Cursor *pCsr, int *pbSkip){
191109  int rc = SQLITE_OK;
191110  assert( *pbSkip==0 );
191111  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_RESEEK) ){
191112  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191113  int bDesc = pCsr->bDesc;
191114  i64 iRowid = sqlite3Fts5ExprRowid(pCsr->pExpr);
191115 
191116  rc = sqlite3Fts5ExprFirst(pCsr->pExpr, pTab->pIndex, iRowid, bDesc);
191117  if( rc==SQLITE_OK && iRowid!=sqlite3Fts5ExprRowid(pCsr->pExpr) ){
191118  *pbSkip = 1;
191119  }
191120 
191121  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_RESEEK);
191122  fts5CsrNewrow(pCsr);
191123  if( sqlite3Fts5ExprEof(pCsr->pExpr) ){
191124  CsrFlagSet(pCsr, FTS5CSR_EOF);
191125  *pbSkip = 1;
191126  }
191127  }
191128  return rc;
191129 }
191130 
191131 
191132 /*
191133 ** Advance the cursor to the next row in the table that matches the
191134 ** search criteria.
191135 **
191136 ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
191137 ** even if we reach end-of-file. The fts5EofMethod() will be called
191138 ** subsequently to determine whether or not an EOF was hit.
191139 */
191140 static int fts5NextMethod(sqlite3_vtab_cursor *pCursor){
191141  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
191142  int rc;
191143 
191144  assert( (pCsr->ePlan<3)==
191145  (pCsr->ePlan==FTS5_PLAN_MATCH || pCsr->ePlan==FTS5_PLAN_SOURCE)
191146  );
191147  assert( !CsrFlagTest(pCsr, FTS5CSR_EOF) );
191148 
191149  if( pCsr->ePlan<3 ){
191150  int bSkip = 0;
191151  if( (rc = fts5CursorReseek(pCsr, &bSkip)) || bSkip ) return rc;
191152  rc = sqlite3Fts5ExprNext(pCsr->pExpr, pCsr->iLastRowid);
191153  CsrFlagSet(pCsr, sqlite3Fts5ExprEof(pCsr->pExpr));
191154  fts5CsrNewrow(pCsr);
191155  }else{
191156  switch( pCsr->ePlan ){
191157  case FTS5_PLAN_SPECIAL: {
191158  CsrFlagSet(pCsr, FTS5CSR_EOF);
191159  rc = SQLITE_OK;
191160  break;
191161  }
191162 
191163  case FTS5_PLAN_SORTED_MATCH: {
191164  rc = fts5SorterNext(pCsr);
191165  break;
191166  }
191167 
191168  default:
191169  rc = sqlite3_step(pCsr->pStmt);
191170  if( rc!=SQLITE_ROW ){
191171  CsrFlagSet(pCsr, FTS5CSR_EOF);
191172  rc = sqlite3_reset(pCsr->pStmt);
191173  }else{
191174  rc = SQLITE_OK;
191175  }
191176  break;
191177  }
191178  }
191179 
191180  return rc;
191181 }
191182 
191183 
191184 static int fts5PrepareStatement(
191185  sqlite3_stmt **ppStmt,
191186  Fts5Config *pConfig,
191187  const char *zFmt,
191188  ...
191189 ){
191190  sqlite3_stmt *pRet = 0;
191191  int rc;
191192  char *zSql;
191193  va_list ap;
191194 
191195  va_start(ap, zFmt);
191196  zSql = sqlite3_vmprintf(zFmt, ap);
191197  if( zSql==0 ){
191198  rc = SQLITE_NOMEM;
191199  }else{
191200  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pRet, 0);
191201  if( rc!=SQLITE_OK ){
191202  *pConfig->pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(pConfig->db));
191203  }
191204  sqlite3_free(zSql);
191205  }
191206 
191207  va_end(ap);
191208  *ppStmt = pRet;
191209  return rc;
191210 }
191211 
191212 static int fts5CursorFirstSorted(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
191213  Fts5Config *pConfig = pTab->pConfig;
191214  Fts5Sorter *pSorter;
191215  int nPhrase;
191216  int nByte;
191217  int rc;
191218  const char *zRank = pCsr->zRank;
191219  const char *zRankArgs = pCsr->zRankArgs;
191220 
191221  nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
191222  nByte = sizeof(Fts5Sorter) + sizeof(int) * (nPhrase-1);
191223  pSorter = (Fts5Sorter*)sqlite3_malloc(nByte);
191224  if( pSorter==0 ) return SQLITE_NOMEM;
191225  memset(pSorter, 0, nByte);
191226  pSorter->nIdx = nPhrase;
191227 
191228  /* TODO: It would be better to have some system for reusing statement
191229  ** handles here, rather than preparing a new one for each query. But that
191230  ** is not possible as SQLite reference counts the virtual table objects.
191231  ** And since the statement required here reads from this very virtual
191232  ** table, saving it creates a circular reference.
191233  **
191234  ** If SQLite a built-in statement cache, this wouldn't be a problem. */
191235  rc = fts5PrepareStatement(&pSorter->pStmt, pConfig,
191236  "SELECT rowid, rank FROM %Q.%Q ORDER BY %s(%s%s%s) %s",
191237  pConfig->zDb, pConfig->zName, zRank, pConfig->zName,
191238  (zRankArgs ? ", " : ""),
191239  (zRankArgs ? zRankArgs : ""),
191240  bDesc ? "DESC" : "ASC"
191241  );
191242 
191243  pCsr->pSorter = pSorter;
191244  if( rc==SQLITE_OK ){
191245  assert( pTab->pSortCsr==0 );
191246  pTab->pSortCsr = pCsr;
191247  rc = fts5SorterNext(pCsr);
191248  pTab->pSortCsr = 0;
191249  }
191250 
191251  if( rc!=SQLITE_OK ){
191252  sqlite3_finalize(pSorter->pStmt);
191253  sqlite3_free(pSorter);
191254  pCsr->pSorter = 0;
191255  }
191256 
191257  return rc;
191258 }
191259 
191260 static int fts5CursorFirst(Fts5Table *pTab, Fts5Cursor *pCsr, int bDesc){
191261  int rc;
191262  Fts5Expr *pExpr = pCsr->pExpr;
191263  rc = sqlite3Fts5ExprFirst(pExpr, pTab->pIndex, pCsr->iFirstRowid, bDesc);
191264  if( sqlite3Fts5ExprEof(pExpr) ){
191265  CsrFlagSet(pCsr, FTS5CSR_EOF);
191266  }
191267  fts5CsrNewrow(pCsr);
191268  return rc;
191269 }
191270 
191271 /*
191272 ** Process a "special" query. A special query is identified as one with a
191273 ** MATCH expression that begins with a '*' character. The remainder of
191274 ** the text passed to the MATCH operator are used as the special query
191275 ** parameters.
191276 */
191277 static int fts5SpecialMatch(
191278  Fts5Table *pTab,
191279  Fts5Cursor *pCsr,
191280  const char *zQuery
191281 ){
191282  int rc = SQLITE_OK; /* Return code */
191283  const char *z = zQuery; /* Special query text */
191284  int n; /* Number of bytes in text at z */
191285 
191286  while( z[0]==' ' ) z++;
191287  for(n=0; z[n] && z[n]!=' '; n++);
191288 
191289  assert( pTab->base.zErrMsg==0 );
191290  pCsr->ePlan = FTS5_PLAN_SPECIAL;
191291 
191292  if( 0==sqlite3_strnicmp("reads", z, n) ){
191293  pCsr->iSpecial = sqlite3Fts5IndexReads(pTab->pIndex);
191294  }
191295  else if( 0==sqlite3_strnicmp("id", z, n) ){
191296  pCsr->iSpecial = pCsr->iCsrId;
191297  }
191298  else{
191299  /* An unrecognized directive. Return an error message. */
191300  pTab->base.zErrMsg = sqlite3_mprintf("unknown special query: %.*s", n, z);
191301  rc = SQLITE_ERROR;
191302  }
191303 
191304  return rc;
191305 }
191306 
191307 /*
191308 ** Search for an auxiliary function named zName that can be used with table
191309 ** pTab. If one is found, return a pointer to the corresponding Fts5Auxiliary
191310 ** structure. Otherwise, if no such function exists, return NULL.
191311 */
191312 static Fts5Auxiliary *fts5FindAuxiliary(Fts5Table *pTab, const char *zName){
191313  Fts5Auxiliary *pAux;
191314 
191315  for(pAux=pTab->pGlobal->pAux; pAux; pAux=pAux->pNext){
191316  if( sqlite3_stricmp(zName, pAux->zFunc)==0 ) return pAux;
191317  }
191318 
191319  /* No function of the specified name was found. Return 0. */
191320  return 0;
191321 }
191322 
191323 
191324 static int fts5FindRankFunction(Fts5Cursor *pCsr){
191325  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191326  Fts5Config *pConfig = pTab->pConfig;
191327  int rc = SQLITE_OK;
191328  Fts5Auxiliary *pAux = 0;
191329  const char *zRank = pCsr->zRank;
191330  const char *zRankArgs = pCsr->zRankArgs;
191331 
191332  if( zRankArgs ){
191333  char *zSql = sqlite3Fts5Mprintf(&rc, "SELECT %s", zRankArgs);
191334  if( zSql ){
191335  sqlite3_stmt *pStmt = 0;
191336  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pStmt, 0);
191337  sqlite3_free(zSql);
191338  assert( rc==SQLITE_OK || pCsr->pRankArgStmt==0 );
191339  if( rc==SQLITE_OK ){
191340  if( SQLITE_ROW==sqlite3_step(pStmt) ){
191341  int nByte;
191342  pCsr->nRankArg = sqlite3_column_count(pStmt);
191343  nByte = sizeof(sqlite3_value*)*pCsr->nRankArg;
191344  pCsr->apRankArg = (sqlite3_value**)sqlite3Fts5MallocZero(&rc, nByte);
191345  if( rc==SQLITE_OK ){
191346  int i;
191347  for(i=0; i<pCsr->nRankArg; i++){
191348  pCsr->apRankArg[i] = sqlite3_column_value(pStmt, i);
191349  }
191350  }
191351  pCsr->pRankArgStmt = pStmt;
191352  }else{
191353  rc = sqlite3_finalize(pStmt);
191354  assert( rc!=SQLITE_OK );
191355  }
191356  }
191357  }
191358  }
191359 
191360  if( rc==SQLITE_OK ){
191361  pAux = fts5FindAuxiliary(pTab, zRank);
191362  if( pAux==0 ){
191363  assert( pTab->base.zErrMsg==0 );
191364  pTab->base.zErrMsg = sqlite3_mprintf("no such function: %s", zRank);
191365  rc = SQLITE_ERROR;
191366  }
191367  }
191368 
191369  pCsr->pRank = pAux;
191370  return rc;
191371 }
191372 
191373 
191374 static int fts5CursorParseRank(
191375  Fts5Config *pConfig,
191376  Fts5Cursor *pCsr,
191377  sqlite3_value *pRank
191378 ){
191379  int rc = SQLITE_OK;
191380  if( pRank ){
191381  const char *z = (const char*)sqlite3_value_text(pRank);
191382  char *zRank = 0;
191383  char *zRankArgs = 0;
191384 
191385  if( z==0 ){
191386  if( sqlite3_value_type(pRank)==SQLITE_NULL ) rc = SQLITE_ERROR;
191387  }else{
191388  rc = sqlite3Fts5ConfigParseRank(z, &zRank, &zRankArgs);
191389  }
191390  if( rc==SQLITE_OK ){
191391  pCsr->zRank = zRank;
191392  pCsr->zRankArgs = zRankArgs;
191393  CsrFlagSet(pCsr, FTS5CSR_FREE_ZRANK);
191394  }else if( rc==SQLITE_ERROR ){
191395  pCsr->base.pVtab->zErrMsg = sqlite3_mprintf(
191396  "parse error in rank function: %s", z
191397  );
191398  }
191399  }else{
191400  if( pConfig->zRank ){
191401  pCsr->zRank = (char*)pConfig->zRank;
191402  pCsr->zRankArgs = (char*)pConfig->zRankArgs;
191403  }else{
191404  pCsr->zRank = (char*)FTS5_DEFAULT_RANK;
191405  pCsr->zRankArgs = 0;
191406  }
191407  }
191408  return rc;
191409 }
191410 
191411 static i64 fts5GetRowidLimit(sqlite3_value *pVal, i64 iDefault){
191412  if( pVal ){
191413  int eType = sqlite3_value_numeric_type(pVal);
191414  if( eType==SQLITE_INTEGER ){
191415  return sqlite3_value_int64(pVal);
191416  }
191417  }
191418  return iDefault;
191419 }
191420 
191421 /*
191422 ** This is the xFilter interface for the virtual table. See
191423 ** the virtual table xFilter method documentation for additional
191424 ** information.
191425 **
191426 ** There are three possible query strategies:
191427 **
191428 ** 1. Full-text search using a MATCH operator.
191429 ** 2. A by-rowid lookup.
191430 ** 3. A full-table scan.
191431 */
191432 static int fts5FilterMethod(
191433  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
191434  int idxNum, /* Strategy index */
191435  const char *zUnused, /* Unused */
191436  int nVal, /* Number of elements in apVal */
191437  sqlite3_value **apVal /* Arguments for the indexing scheme */
191438 ){
191439  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
191440  Fts5Config *pConfig = pTab->pConfig;
191441  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
191442  int rc = SQLITE_OK; /* Error code */
191443  int iVal = 0; /* Counter for apVal[] */
191444  int bDesc; /* True if ORDER BY [rank|rowid] DESC */
191445  int bOrderByRank; /* True if ORDER BY rank */
191446  sqlite3_value *pMatch = 0; /* <tbl> MATCH ? expression (or NULL) */
191447  sqlite3_value *pRank = 0; /* rank MATCH ? expression (or NULL) */
191448  sqlite3_value *pRowidEq = 0; /* rowid = ? expression (or NULL) */
191449  sqlite3_value *pRowidLe = 0; /* rowid <= ? expression (or NULL) */
191450  sqlite3_value *pRowidGe = 0; /* rowid >= ? expression (or NULL) */
191451  char **pzErrmsg = pConfig->pzErrmsg;
191452 
191453  UNUSED_PARAM(zUnused);
191454  UNUSED_PARAM(nVal);
191455 
191456  if( pCsr->ePlan ){
191457  fts5FreeCursorComponents(pCsr);
191458  memset(&pCsr->ePlan, 0, sizeof(Fts5Cursor) - ((u8*)&pCsr->ePlan-(u8*)pCsr));
191459  }
191460 
191461  assert( pCsr->pStmt==0 );
191462  assert( pCsr->pExpr==0 );
191463  assert( pCsr->csrflags==0 );
191464  assert( pCsr->pRank==0 );
191465  assert( pCsr->zRank==0 );
191466  assert( pCsr->zRankArgs==0 );
191467 
191468  assert( pzErrmsg==0 || pzErrmsg==&pTab->base.zErrMsg );
191469  pConfig->pzErrmsg = &pTab->base.zErrMsg;
191470 
191471  /* Decode the arguments passed through to this function.
191472  **
191473  ** Note: The following set of if(...) statements must be in the same
191474  ** order as the corresponding entries in the struct at the top of
191475  ** fts5BestIndexMethod(). */
191476  if( BitFlagTest(idxNum, FTS5_BI_MATCH) ) pMatch = apVal[iVal++];
191477  if( BitFlagTest(idxNum, FTS5_BI_RANK) ) pRank = apVal[iVal++];
191478  if( BitFlagTest(idxNum, FTS5_BI_ROWID_EQ) ) pRowidEq = apVal[iVal++];
191479  if( BitFlagTest(idxNum, FTS5_BI_ROWID_LE) ) pRowidLe = apVal[iVal++];
191480  if( BitFlagTest(idxNum, FTS5_BI_ROWID_GE) ) pRowidGe = apVal[iVal++];
191481  assert( iVal==nVal );
191482  bOrderByRank = ((idxNum & FTS5_BI_ORDER_RANK) ? 1 : 0);
191483  pCsr->bDesc = bDesc = ((idxNum & FTS5_BI_ORDER_DESC) ? 1 : 0);
191484 
191485  /* Set the cursor upper and lower rowid limits. Only some strategies
191486  ** actually use them. This is ok, as the xBestIndex() method leaves the
191487  ** sqlite3_index_constraint.omit flag clear for range constraints
191488  ** on the rowid field. */
191489  if( pRowidEq ){
191490  pRowidLe = pRowidGe = pRowidEq;
191491  }
191492  if( bDesc ){
191493  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
191494  pCsr->iLastRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
191495  }else{
191496  pCsr->iLastRowid = fts5GetRowidLimit(pRowidLe, LARGEST_INT64);
191497  pCsr->iFirstRowid = fts5GetRowidLimit(pRowidGe, SMALLEST_INT64);
191498  }
191499 
191500  if( pTab->pSortCsr ){
191501  /* If pSortCsr is non-NULL, then this call is being made as part of
191502  ** processing for a "... MATCH <expr> ORDER BY rank" query (ePlan is
191503  ** set to FTS5_PLAN_SORTED_MATCH). pSortCsr is the cursor that will
191504  ** return results to the user for this query. The current cursor
191505  ** (pCursor) is used to execute the query issued by function
191506  ** fts5CursorFirstSorted() above. */
191507  assert( pRowidEq==0 && pRowidLe==0 && pRowidGe==0 && pRank==0 );
191508  assert( nVal==0 && pMatch==0 && bOrderByRank==0 && bDesc==0 );
191509  assert( pCsr->iLastRowid==LARGEST_INT64 );
191510  assert( pCsr->iFirstRowid==SMALLEST_INT64 );
191511  pCsr->ePlan = FTS5_PLAN_SOURCE;
191512  pCsr->pExpr = pTab->pSortCsr->pExpr;
191513  rc = fts5CursorFirst(pTab, pCsr, bDesc);
191514  sqlite3Fts5ExprClearEof(pCsr->pExpr);
191515  }else if( pMatch ){
191516  const char *zExpr = (const char*)sqlite3_value_text(apVal[0]);
191517  if( zExpr==0 ) zExpr = "";
191518 
191519  rc = fts5CursorParseRank(pConfig, pCsr, pRank);
191520  if( rc==SQLITE_OK ){
191521  if( zExpr[0]=='*' ){
191522  /* The user has issued a query of the form "MATCH '*...'". This
191523  ** indicates that the MATCH expression is not a full text query,
191524  ** but a request for an internal parameter. */
191525  rc = fts5SpecialMatch(pTab, pCsr, &zExpr[1]);
191526  }else{
191527  char **pzErr = &pTab->base.zErrMsg;
191528  rc = sqlite3Fts5ExprNew(pConfig, zExpr, &pCsr->pExpr, pzErr);
191529  if( rc==SQLITE_OK ){
191530  if( bOrderByRank ){
191531  pCsr->ePlan = FTS5_PLAN_SORTED_MATCH;
191532  rc = fts5CursorFirstSorted(pTab, pCsr, bDesc);
191533  }else{
191534  pCsr->ePlan = FTS5_PLAN_MATCH;
191535  rc = fts5CursorFirst(pTab, pCsr, bDesc);
191536  }
191537  }
191538  }
191539  }
191540  }else if( pConfig->zContent==0 ){
191541  *pConfig->pzErrmsg = sqlite3_mprintf(
191542  "%s: table does not support scanning", pConfig->zName
191543  );
191544  rc = SQLITE_ERROR;
191545  }else{
191546  /* This is either a full-table scan (ePlan==FTS5_PLAN_SCAN) or a lookup
191547  ** by rowid (ePlan==FTS5_PLAN_ROWID). */
191548  pCsr->ePlan = (pRowidEq ? FTS5_PLAN_ROWID : FTS5_PLAN_SCAN);
191549  rc = sqlite3Fts5StorageStmt(
191550  pTab->pStorage, fts5StmtType(pCsr), &pCsr->pStmt, &pTab->base.zErrMsg
191551  );
191552  if( rc==SQLITE_OK ){
191553  if( pCsr->ePlan==FTS5_PLAN_ROWID ){
191554  sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
191555  }else{
191556  sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iFirstRowid);
191557  sqlite3_bind_int64(pCsr->pStmt, 2, pCsr->iLastRowid);
191558  }
191559  rc = fts5NextMethod(pCursor);
191560  }
191561  }
191562 
191563  pConfig->pzErrmsg = pzErrmsg;
191564  return rc;
191565 }
191566 
191567 /*
191568 ** This is the xEof method of the virtual table. SQLite calls this
191569 ** routine to find out if it has reached the end of a result set.
191570 */
191571 static int fts5EofMethod(sqlite3_vtab_cursor *pCursor){
191572  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
191573  return (CsrFlagTest(pCsr, FTS5CSR_EOF) ? 1 : 0);
191574 }
191575 
191576 /*
191577 ** Return the rowid that the cursor currently points to.
191578 */
191579 static i64 fts5CursorRowid(Fts5Cursor *pCsr){
191580  assert( pCsr->ePlan==FTS5_PLAN_MATCH
191581  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
191582  || pCsr->ePlan==FTS5_PLAN_SOURCE
191583  );
191584  if( pCsr->pSorter ){
191585  return pCsr->pSorter->iRowid;
191586  }else{
191587  return sqlite3Fts5ExprRowid(pCsr->pExpr);
191588  }
191589 }
191590 
191591 /*
191592 ** This is the xRowid method. The SQLite core calls this routine to
191593 ** retrieve the rowid for the current row of the result set. fts5
191594 ** exposes %_content.rowid as the rowid for the virtual table. The
191595 ** rowid should be written to *pRowid.
191596 */
191597 static int fts5RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
191598  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
191599  int ePlan = pCsr->ePlan;
191600 
191601  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
191602  switch( ePlan ){
191603  case FTS5_PLAN_SPECIAL:
191604  *pRowid = 0;
191605  break;
191606 
191607  case FTS5_PLAN_SOURCE:
191608  case FTS5_PLAN_MATCH:
191609  case FTS5_PLAN_SORTED_MATCH:
191610  *pRowid = fts5CursorRowid(pCsr);
191611  break;
191612 
191613  default:
191614  *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
191615  break;
191616  }
191617 
191618  return SQLITE_OK;
191619 }
191620 
191621 /*
191622 ** If the cursor requires seeking (bSeekRequired flag is set), seek it.
191623 ** Return SQLITE_OK if no error occurs, or an SQLite error code otherwise.
191624 **
191625 ** If argument bErrormsg is true and an error occurs, an error message may
191626 ** be left in sqlite3_vtab.zErrMsg.
191627 */
191628 static int fts5SeekCursor(Fts5Cursor *pCsr, int bErrormsg){
191629  int rc = SQLITE_OK;
191630 
191631  /* If the cursor does not yet have a statement handle, obtain one now. */
191632  if( pCsr->pStmt==0 ){
191633  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191634  int eStmt = fts5StmtType(pCsr);
191635  rc = sqlite3Fts5StorageStmt(
191636  pTab->pStorage, eStmt, &pCsr->pStmt, (bErrormsg?&pTab->base.zErrMsg:0)
191637  );
191638  assert( rc!=SQLITE_OK || pTab->base.zErrMsg==0 );
191639  assert( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) );
191640  }
191641 
191642  if( rc==SQLITE_OK && CsrFlagTest(pCsr, FTS5CSR_REQUIRE_CONTENT) ){
191643  assert( pCsr->pExpr );
191644  sqlite3_reset(pCsr->pStmt);
191645  sqlite3_bind_int64(pCsr->pStmt, 1, fts5CursorRowid(pCsr));
191646  rc = sqlite3_step(pCsr->pStmt);
191647  if( rc==SQLITE_ROW ){
191648  rc = SQLITE_OK;
191649  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_CONTENT);
191650  }else{
191651  rc = sqlite3_reset(pCsr->pStmt);
191652  if( rc==SQLITE_OK ){
191653  rc = FTS5_CORRUPT;
191654  }
191655  }
191656  }
191657  return rc;
191658 }
191659 
191660 static void fts5SetVtabError(Fts5Table *p, const char *zFormat, ...){
191661  va_list ap; /* ... printf arguments */
191662  va_start(ap, zFormat);
191663  assert( p->base.zErrMsg==0 );
191664  p->base.zErrMsg = sqlite3_vmprintf(zFormat, ap);
191665  va_end(ap);
191666 }
191667 
191668 /*
191669 ** This function is called to handle an FTS INSERT command. In other words,
191670 ** an INSERT statement of the form:
191671 **
191672 ** INSERT INTO fts(fts) VALUES($pCmd)
191673 ** INSERT INTO fts(fts, rank) VALUES($pCmd, $pVal)
191674 **
191675 ** Argument pVal is the value assigned to column "fts" by the INSERT
191676 ** statement. This function returns SQLITE_OK if successful, or an SQLite
191677 ** error code if an error occurs.
191678 **
191679 ** The commands implemented by this function are documented in the "Special
191680 ** INSERT Directives" section of the documentation. It should be updated if
191681 ** more commands are added to this function.
191682 */
191683 static int fts5SpecialInsert(
191684  Fts5Table *pTab, /* Fts5 table object */
191685  const char *zCmd, /* Text inserted into table-name column */
191686  sqlite3_value *pVal /* Value inserted into rank column */
191687 ){
191688  Fts5Config *pConfig = pTab->pConfig;
191689  int rc = SQLITE_OK;
191690  int bError = 0;
191691 
191692  if( 0==sqlite3_stricmp("delete-all", zCmd) ){
191693  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
191694  fts5SetVtabError(pTab,
191695  "'delete-all' may only be used with a "
191696  "contentless or external content fts5 table"
191697  );
191698  rc = SQLITE_ERROR;
191699  }else{
191700  rc = sqlite3Fts5StorageDeleteAll(pTab->pStorage);
191701  }
191702  }else if( 0==sqlite3_stricmp("rebuild", zCmd) ){
191703  if( pConfig->eContent==FTS5_CONTENT_NONE ){
191704  fts5SetVtabError(pTab,
191705  "'rebuild' may not be used with a contentless fts5 table"
191706  );
191707  rc = SQLITE_ERROR;
191708  }else{
191709  rc = sqlite3Fts5StorageRebuild(pTab->pStorage);
191710  }
191711  }else if( 0==sqlite3_stricmp("optimize", zCmd) ){
191712  rc = sqlite3Fts5StorageOptimize(pTab->pStorage);
191713  }else if( 0==sqlite3_stricmp("merge", zCmd) ){
191714  int nMerge = sqlite3_value_int(pVal);
191715  rc = sqlite3Fts5StorageMerge(pTab->pStorage, nMerge);
191716  }else if( 0==sqlite3_stricmp("integrity-check", zCmd) ){
191717  rc = sqlite3Fts5StorageIntegrity(pTab->pStorage);
191718 #ifdef SQLITE_DEBUG
191719  }else if( 0==sqlite3_stricmp("prefix-index", zCmd) ){
191720  pConfig->bPrefixIndex = sqlite3_value_int(pVal);
191721 #endif
191722  }else{
191723  rc = sqlite3Fts5IndexLoadConfig(pTab->pIndex);
191724  if( rc==SQLITE_OK ){
191725  rc = sqlite3Fts5ConfigSetValue(pTab->pConfig, zCmd, pVal, &bError);
191726  }
191727  if( rc==SQLITE_OK ){
191728  if( bError ){
191729  rc = SQLITE_ERROR;
191730  }else{
191731  rc = sqlite3Fts5StorageConfigValue(pTab->pStorage, zCmd, pVal, 0);
191732  }
191733  }
191734  }
191735  return rc;
191736 }
191737 
191738 static int fts5SpecialDelete(
191739  Fts5Table *pTab,
191740  sqlite3_value **apVal
191741 ){
191742  int rc = SQLITE_OK;
191743  int eType1 = sqlite3_value_type(apVal[1]);
191744  if( eType1==SQLITE_INTEGER ){
191745  sqlite3_int64 iDel = sqlite3_value_int64(apVal[1]);
191746  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, &apVal[2]);
191747  }
191748  return rc;
191749 }
191750 
191751 static void fts5StorageInsert(
191752  int *pRc,
191753  Fts5Table *pTab,
191754  sqlite3_value **apVal,
191755  i64 *piRowid
191756 ){
191757  int rc = *pRc;
191758  if( rc==SQLITE_OK ){
191759  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, piRowid);
191760  }
191761  if( rc==SQLITE_OK ){
191762  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *piRowid);
191763  }
191764  *pRc = rc;
191765 }
191766 
191767 /*
191768 ** This function is the implementation of the xUpdate callback used by
191769 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
191770 ** inserted, updated or deleted.
191771 **
191772 ** A delete specifies a single argument - the rowid of the row to remove.
191773 **
191774 ** Update and insert operations pass:
191775 **
191776 ** 1. The "old" rowid, or NULL.
191777 ** 2. The "new" rowid.
191778 ** 3. Values for each of the nCol matchable columns.
191779 ** 4. Values for the two hidden columns (<tablename> and "rank").
191780 */
191781 static int fts5UpdateMethod(
191782  sqlite3_vtab *pVtab, /* Virtual table handle */
191783  int nArg, /* Size of argument array */
191784  sqlite3_value **apVal, /* Array of arguments */
191785  sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
191786 ){
191787  Fts5Table *pTab = (Fts5Table*)pVtab;
191788  Fts5Config *pConfig = pTab->pConfig;
191789  int eType0; /* value_type() of apVal[0] */
191790  int rc = SQLITE_OK; /* Return code */
191791 
191792  /* A transaction must be open when this is called. */
191793  assert( pTab->ts.eState==1 );
191794 
191795  assert( pVtab->zErrMsg==0 );
191796  assert( nArg==1 || nArg==(2+pConfig->nCol+2) );
191797  assert( nArg==1
191798  || sqlite3_value_type(apVal[1])==SQLITE_INTEGER
191799  || sqlite3_value_type(apVal[1])==SQLITE_NULL
191800  );
191801  assert( pTab->pConfig->pzErrmsg==0 );
191802  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
191803 
191804  /* Put any active cursors into REQUIRE_SEEK state. */
191805  fts5TripCursors(pTab);
191806 
191807  eType0 = sqlite3_value_type(apVal[0]);
191808  if( eType0==SQLITE_NULL
191809  && sqlite3_value_type(apVal[2+pConfig->nCol])!=SQLITE_NULL
191810  ){
191811  /* A "special" INSERT op. These are handled separately. */
191812  const char *z = (const char*)sqlite3_value_text(apVal[2+pConfig->nCol]);
191813  if( pConfig->eContent!=FTS5_CONTENT_NORMAL
191814  && 0==sqlite3_stricmp("delete", z)
191815  ){
191816  rc = fts5SpecialDelete(pTab, apVal);
191817  }else{
191818  rc = fts5SpecialInsert(pTab, z, apVal[2 + pConfig->nCol + 1]);
191819  }
191820  }else{
191821  /* A regular INSERT, UPDATE or DELETE statement. The trick here is that
191822  ** any conflict on the rowid value must be detected before any
191823  ** modifications are made to the database file. There are 4 cases:
191824  **
191825  ** 1) DELETE
191826  ** 2) UPDATE (rowid not modified)
191827  ** 3) UPDATE (rowid modified)
191828  ** 4) INSERT
191829  **
191830  ** Cases 3 and 4 may violate the rowid constraint.
191831  */
191832  int eConflict = SQLITE_ABORT;
191833  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
191834  eConflict = sqlite3_vtab_on_conflict(pConfig->db);
191835  }
191836 
191837  assert( eType0==SQLITE_INTEGER || eType0==SQLITE_NULL );
191838  assert( nArg!=1 || eType0==SQLITE_INTEGER );
191839 
191840  /* Filter out attempts to run UPDATE or DELETE on contentless tables.
191841  ** This is not suported. */
191842  if( eType0==SQLITE_INTEGER && fts5IsContentless(pTab) ){
191843  pTab->base.zErrMsg = sqlite3_mprintf(
191844  "cannot %s contentless fts5 table: %s",
191845  (nArg>1 ? "UPDATE" : "DELETE from"), pConfig->zName
191846  );
191847  rc = SQLITE_ERROR;
191848  }
191849 
191850  /* DELETE */
191851  else if( nArg==1 ){
191852  i64 iDel = sqlite3_value_int64(apVal[0]); /* Rowid to delete */
191853  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iDel, 0);
191854  }
191855 
191856  /* INSERT */
191857  else if( eType0!=SQLITE_INTEGER ){
191858  /* If this is a REPLACE, first remove the current entry (if any) */
191859  if( eConflict==SQLITE_REPLACE
191860  && sqlite3_value_type(apVal[1])==SQLITE_INTEGER
191861  ){
191862  i64 iNew = sqlite3_value_int64(apVal[1]); /* Rowid to delete */
191863  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
191864  }
191865  fts5StorageInsert(&rc, pTab, apVal, pRowid);
191866  }
191867 
191868  /* UPDATE */
191869  else{
191870  i64 iOld = sqlite3_value_int64(apVal[0]); /* Old rowid */
191871  i64 iNew = sqlite3_value_int64(apVal[1]); /* New rowid */
191872  if( iOld!=iNew ){
191873  if( eConflict==SQLITE_REPLACE ){
191874  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
191875  if( rc==SQLITE_OK ){
191876  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iNew, 0);
191877  }
191878  fts5StorageInsert(&rc, pTab, apVal, pRowid);
191879  }else{
191880  rc = sqlite3Fts5StorageContentInsert(pTab->pStorage, apVal, pRowid);
191881  if( rc==SQLITE_OK ){
191882  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
191883  }
191884  if( rc==SQLITE_OK ){
191885  rc = sqlite3Fts5StorageIndexInsert(pTab->pStorage, apVal, *pRowid);
191886  }
191887  }
191888  }else{
191889  rc = sqlite3Fts5StorageDelete(pTab->pStorage, iOld, 0);
191890  fts5StorageInsert(&rc, pTab, apVal, pRowid);
191891  }
191892  }
191893  }
191894 
191895  pTab->pConfig->pzErrmsg = 0;
191896  return rc;
191897 }
191898 
191899 /*
191900 ** Implementation of xSync() method.
191901 */
191902 static int fts5SyncMethod(sqlite3_vtab *pVtab){
191903  int rc;
191904  Fts5Table *pTab = (Fts5Table*)pVtab;
191905  fts5CheckTransactionState(pTab, FTS5_SYNC, 0);
191906  pTab->pConfig->pzErrmsg = &pTab->base.zErrMsg;
191907  fts5TripCursors(pTab);
191908  rc = sqlite3Fts5StorageSync(pTab->pStorage, 1);
191909  pTab->pConfig->pzErrmsg = 0;
191910  return rc;
191911 }
191912 
191913 /*
191914 ** Implementation of xBegin() method.
191915 */
191916 static int fts5BeginMethod(sqlite3_vtab *pVtab){
191917  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_BEGIN, 0);
191918  fts5NewTransaction((Fts5Table*)pVtab);
191919  return SQLITE_OK;
191920 }
191921 
191922 /*
191923 ** Implementation of xCommit() method. This is a no-op. The contents of
191924 ** the pending-terms hash-table have already been flushed into the database
191925 ** by fts5SyncMethod().
191926 */
191927 static int fts5CommitMethod(sqlite3_vtab *pVtab){
191928  UNUSED_PARAM(pVtab); /* Call below is a no-op for NDEBUG builds */
191929  fts5CheckTransactionState((Fts5Table*)pVtab, FTS5_COMMIT, 0);
191930  return SQLITE_OK;
191931 }
191932 
191933 /*
191934 ** Implementation of xRollback(). Discard the contents of the pending-terms
191935 ** hash-table. Any changes made to the database are reverted by SQLite.
191936 */
191937 static int fts5RollbackMethod(sqlite3_vtab *pVtab){
191938  int rc;
191939  Fts5Table *pTab = (Fts5Table*)pVtab;
191940  fts5CheckTransactionState(pTab, FTS5_ROLLBACK, 0);
191941  rc = sqlite3Fts5StorageRollback(pTab->pStorage);
191942  return rc;
191943 }
191944 
191945 static int fts5CsrPoslist(Fts5Cursor*, int, const u8**, int*);
191946 
191947 static void *fts5ApiUserData(Fts5Context *pCtx){
191948  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191949  return pCsr->pAux->pUserData;
191950 }
191951 
191952 static int fts5ApiColumnCount(Fts5Context *pCtx){
191953  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191954  return ((Fts5Table*)(pCsr->base.pVtab))->pConfig->nCol;
191955 }
191956 
191957 static int fts5ApiColumnTotalSize(
191958  Fts5Context *pCtx,
191959  int iCol,
191960  sqlite3_int64 *pnToken
191961 ){
191962  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191963  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191964  return sqlite3Fts5StorageSize(pTab->pStorage, iCol, pnToken);
191965 }
191966 
191967 static int fts5ApiRowCount(Fts5Context *pCtx, i64 *pnRow){
191968  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191969  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191970  return sqlite3Fts5StorageRowCount(pTab->pStorage, pnRow);
191971 }
191972 
191973 static int fts5ApiTokenize(
191974  Fts5Context *pCtx,
191975  const char *pText, int nText,
191976  void *pUserData,
191977  int (*xToken)(void*, int, const char*, int, int, int)
191978 ){
191979  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191980  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
191981  return sqlite3Fts5Tokenize(
191982  pTab->pConfig, FTS5_TOKENIZE_AUX, pText, nText, pUserData, xToken
191983  );
191984 }
191985 
191986 static int fts5ApiPhraseCount(Fts5Context *pCtx){
191987  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191988  return sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
191989 }
191990 
191991 static int fts5ApiPhraseSize(Fts5Context *pCtx, int iPhrase){
191992  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
191993  return sqlite3Fts5ExprPhraseSize(pCsr->pExpr, iPhrase);
191994 }
191995 
191996 static int fts5ApiColumnText(
191997  Fts5Context *pCtx,
191998  int iCol,
191999  const char **pz,
192000  int *pn
192001 ){
192002  int rc = SQLITE_OK;
192003  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192004  if( fts5IsContentless((Fts5Table*)(pCsr->base.pVtab)) ){
192005  *pz = 0;
192006  *pn = 0;
192007  }else{
192008  rc = fts5SeekCursor(pCsr, 0);
192009  if( rc==SQLITE_OK ){
192010  *pz = (const char*)sqlite3_column_text(pCsr->pStmt, iCol+1);
192011  *pn = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
192012  }
192013  }
192014  return rc;
192015 }
192016 
192017 static int fts5CsrPoslist(
192018  Fts5Cursor *pCsr,
192019  int iPhrase,
192020  const u8 **pa,
192021  int *pn
192022 ){
192023  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
192024  int rc = SQLITE_OK;
192025  int bLive = (pCsr->pSorter==0);
192026 
192027  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_POSLIST) ){
192028 
192029  if( pConfig->eDetail!=FTS5_DETAIL_FULL ){
192030  Fts5PoslistPopulator *aPopulator;
192031  int i;
192032  aPopulator = sqlite3Fts5ExprClearPoslists(pCsr->pExpr, bLive);
192033  if( aPopulator==0 ) rc = SQLITE_NOMEM;
192034  for(i=0; i<pConfig->nCol && rc==SQLITE_OK; i++){
192035  int n; const char *z;
192036  rc = fts5ApiColumnText((Fts5Context*)pCsr, i, &z, &n);
192037  if( rc==SQLITE_OK ){
192038  rc = sqlite3Fts5ExprPopulatePoslists(
192039  pConfig, pCsr->pExpr, aPopulator, i, z, n
192040  );
192041  }
192042  }
192043  sqlite3_free(aPopulator);
192044 
192045  if( pCsr->pSorter ){
192046  sqlite3Fts5ExprCheckPoslists(pCsr->pExpr, pCsr->pSorter->iRowid);
192047  }
192048  }
192049  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_POSLIST);
192050  }
192051 
192052  if( pCsr->pSorter && pConfig->eDetail==FTS5_DETAIL_FULL ){
192053  Fts5Sorter *pSorter = pCsr->pSorter;
192054  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
192055  *pn = pSorter->aIdx[iPhrase] - i1;
192056  *pa = &pSorter->aPoslist[i1];
192057  }else{
192058  *pn = sqlite3Fts5ExprPoslist(pCsr->pExpr, iPhrase, pa);
192059  }
192060 
192061  return rc;
192062 }
192063 
192064 /*
192065 ** Ensure that the Fts5Cursor.nInstCount and aInst[] variables are populated
192066 ** correctly for the current view. Return SQLITE_OK if successful, or an
192067 ** SQLite error code otherwise.
192068 */
192069 static int fts5CacheInstArray(Fts5Cursor *pCsr){
192070  int rc = SQLITE_OK;
192071  Fts5PoslistReader *aIter; /* One iterator for each phrase */
192072  int nIter; /* Number of iterators/phrases */
192073 
192074  nIter = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
192075  if( pCsr->aInstIter==0 ){
192076  int nByte = sizeof(Fts5PoslistReader) * nIter;
192077  pCsr->aInstIter = (Fts5PoslistReader*)sqlite3Fts5MallocZero(&rc, nByte);
192078  }
192079  aIter = pCsr->aInstIter;
192080 
192081  if( aIter ){
192082  int nInst = 0; /* Number instances seen so far */
192083  int i;
192084 
192085  /* Initialize all iterators */
192086  for(i=0; i<nIter && rc==SQLITE_OK; i++){
192087  const u8 *a;
192088  int n;
192089  rc = fts5CsrPoslist(pCsr, i, &a, &n);
192090  if( rc==SQLITE_OK ){
192091  sqlite3Fts5PoslistReaderInit(a, n, &aIter[i]);
192092  }
192093  }
192094 
192095  if( rc==SQLITE_OK ){
192096  while( 1 ){
192097  int *aInst;
192098  int iBest = -1;
192099  for(i=0; i<nIter; i++){
192100  if( (aIter[i].bEof==0)
192101  && (iBest<0 || aIter[i].iPos<aIter[iBest].iPos)
192102  ){
192103  iBest = i;
192104  }
192105  }
192106  if( iBest<0 ) break;
192107 
192108  nInst++;
192109  if( nInst>=pCsr->nInstAlloc ){
192110  pCsr->nInstAlloc = pCsr->nInstAlloc ? pCsr->nInstAlloc*2 : 32;
192111  aInst = (int*)sqlite3_realloc(
192112  pCsr->aInst, pCsr->nInstAlloc*sizeof(int)*3
192113  );
192114  if( aInst ){
192115  pCsr->aInst = aInst;
192116  }else{
192117  rc = SQLITE_NOMEM;
192118  break;
192119  }
192120  }
192121 
192122  aInst = &pCsr->aInst[3 * (nInst-1)];
192123  aInst[0] = iBest;
192124  aInst[1] = FTS5_POS2COLUMN(aIter[iBest].iPos);
192125  aInst[2] = FTS5_POS2OFFSET(aIter[iBest].iPos);
192126  sqlite3Fts5PoslistReaderNext(&aIter[iBest]);
192127  }
192128  }
192129 
192130  pCsr->nInstCount = nInst;
192131  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_INST);
192132  }
192133  return rc;
192134 }
192135 
192136 static int fts5ApiInstCount(Fts5Context *pCtx, int *pnInst){
192137  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192138  int rc = SQLITE_OK;
192139  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
192140  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr)) ){
192141  *pnInst = pCsr->nInstCount;
192142  }
192143  return rc;
192144 }
192145 
192146 static int fts5ApiInst(
192147  Fts5Context *pCtx,
192148  int iIdx,
192149  int *piPhrase,
192150  int *piCol,
192151  int *piOff
192152 ){
192153  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192154  int rc = SQLITE_OK;
192155  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_INST)==0
192156  || SQLITE_OK==(rc = fts5CacheInstArray(pCsr))
192157  ){
192158  if( iIdx<0 || iIdx>=pCsr->nInstCount ){
192159  rc = SQLITE_RANGE;
192160 #if 0
192161  }else if( fts5IsOffsetless((Fts5Table*)pCsr->base.pVtab) ){
192162  *piPhrase = pCsr->aInst[iIdx*3];
192163  *piCol = pCsr->aInst[iIdx*3 + 2];
192164  *piOff = -1;
192165 #endif
192166  }else{
192167  *piPhrase = pCsr->aInst[iIdx*3];
192168  *piCol = pCsr->aInst[iIdx*3 + 1];
192169  *piOff = pCsr->aInst[iIdx*3 + 2];
192170  }
192171  }
192172  return rc;
192173 }
192174 
192175 static sqlite3_int64 fts5ApiRowid(Fts5Context *pCtx){
192176  return fts5CursorRowid((Fts5Cursor*)pCtx);
192177 }
192178 
192179 static int fts5ColumnSizeCb(
192180  void *pContext, /* Pointer to int */
192181  int tflags,
192182  const char *pUnused, /* Buffer containing token */
192183  int nUnused, /* Size of token in bytes */
192184  int iUnused1, /* Start offset of token */
192185  int iUnused2 /* End offset of token */
192186 ){
192187  int *pCnt = (int*)pContext;
192188  UNUSED_PARAM2(pUnused, nUnused);
192189  UNUSED_PARAM2(iUnused1, iUnused2);
192190  if( (tflags & FTS5_TOKEN_COLOCATED)==0 ){
192191  (*pCnt)++;
192192  }
192193  return SQLITE_OK;
192194 }
192195 
192196 static int fts5ApiColumnSize(Fts5Context *pCtx, int iCol, int *pnToken){
192197  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192198  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192199  Fts5Config *pConfig = pTab->pConfig;
192200  int rc = SQLITE_OK;
192201 
192202  if( CsrFlagTest(pCsr, FTS5CSR_REQUIRE_DOCSIZE) ){
192203  if( pConfig->bColumnsize ){
192204  i64 iRowid = fts5CursorRowid(pCsr);
192205  rc = sqlite3Fts5StorageDocsize(pTab->pStorage, iRowid, pCsr->aColumnSize);
192206  }else if( pConfig->zContent==0 ){
192207  int i;
192208  for(i=0; i<pConfig->nCol; i++){
192209  if( pConfig->abUnindexed[i]==0 ){
192210  pCsr->aColumnSize[i] = -1;
192211  }
192212  }
192213  }else{
192214  int i;
192215  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
192216  if( pConfig->abUnindexed[i]==0 ){
192217  const char *z; int n;
192218  void *p = (void*)(&pCsr->aColumnSize[i]);
192219  pCsr->aColumnSize[i] = 0;
192220  rc = fts5ApiColumnText(pCtx, i, &z, &n);
192221  if( rc==SQLITE_OK ){
192222  rc = sqlite3Fts5Tokenize(
192223  pConfig, FTS5_TOKENIZE_AUX, z, n, p, fts5ColumnSizeCb
192224  );
192225  }
192226  }
192227  }
192228  }
192229  CsrFlagClear(pCsr, FTS5CSR_REQUIRE_DOCSIZE);
192230  }
192231  if( iCol<0 ){
192232  int i;
192233  *pnToken = 0;
192234  for(i=0; i<pConfig->nCol; i++){
192235  *pnToken += pCsr->aColumnSize[i];
192236  }
192237  }else if( iCol<pConfig->nCol ){
192238  *pnToken = pCsr->aColumnSize[iCol];
192239  }else{
192240  *pnToken = 0;
192241  rc = SQLITE_RANGE;
192242  }
192243  return rc;
192244 }
192245 
192246 /*
192247 ** Implementation of the xSetAuxdata() method.
192248 */
192249 static int fts5ApiSetAuxdata(
192250  Fts5Context *pCtx, /* Fts5 context */
192251  void *pPtr, /* Pointer to save as auxdata */
192252  void(*xDelete)(void*) /* Destructor for pPtr (or NULL) */
192253 ){
192254  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192255  Fts5Auxdata *pData;
192256 
192257  /* Search through the cursors list of Fts5Auxdata objects for one that
192258  ** corresponds to the currently executing auxiliary function. */
192259  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
192260  if( pData->pAux==pCsr->pAux ) break;
192261  }
192262 
192263  if( pData ){
192264  if( pData->xDelete ){
192265  pData->xDelete(pData->pPtr);
192266  }
192267  }else{
192268  int rc = SQLITE_OK;
192269  pData = (Fts5Auxdata*)sqlite3Fts5MallocZero(&rc, sizeof(Fts5Auxdata));
192270  if( pData==0 ){
192271  if( xDelete ) xDelete(pPtr);
192272  return rc;
192273  }
192274  pData->pAux = pCsr->pAux;
192275  pData->pNext = pCsr->pAuxdata;
192276  pCsr->pAuxdata = pData;
192277  }
192278 
192279  pData->xDelete = xDelete;
192280  pData->pPtr = pPtr;
192281  return SQLITE_OK;
192282 }
192283 
192284 static void *fts5ApiGetAuxdata(Fts5Context *pCtx, int bClear){
192285  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192286  Fts5Auxdata *pData;
192287  void *pRet = 0;
192288 
192289  for(pData=pCsr->pAuxdata; pData; pData=pData->pNext){
192290  if( pData->pAux==pCsr->pAux ) break;
192291  }
192292 
192293  if( pData ){
192294  pRet = pData->pPtr;
192295  if( bClear ){
192296  pData->pPtr = 0;
192297  pData->xDelete = 0;
192298  }
192299  }
192300 
192301  return pRet;
192302 }
192303 
192304 static void fts5ApiPhraseNext(
192305  Fts5Context *pUnused,
192306  Fts5PhraseIter *pIter,
192307  int *piCol, int *piOff
192308 ){
192309  UNUSED_PARAM(pUnused);
192310  if( pIter->a>=pIter->b ){
192311  *piCol = -1;
192312  *piOff = -1;
192313  }else{
192314  int iVal;
192315  pIter->a += fts5GetVarint32(pIter->a, iVal);
192316  if( iVal==1 ){
192317  pIter->a += fts5GetVarint32(pIter->a, iVal);
192318  *piCol = iVal;
192319  *piOff = 0;
192320  pIter->a += fts5GetVarint32(pIter->a, iVal);
192321  }
192322  *piOff += (iVal-2);
192323  }
192324 }
192325 
192326 static int fts5ApiPhraseFirst(
192327  Fts5Context *pCtx,
192328  int iPhrase,
192329  Fts5PhraseIter *pIter,
192330  int *piCol, int *piOff
192331 ){
192332  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192333  int n;
192334  int rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
192335  if( rc==SQLITE_OK ){
192336  pIter->b = &pIter->a[n];
192337  *piCol = 0;
192338  *piOff = 0;
192339  fts5ApiPhraseNext(pCtx, pIter, piCol, piOff);
192340  }
192341  return rc;
192342 }
192343 
192344 static void fts5ApiPhraseNextColumn(
192345  Fts5Context *pCtx,
192346  Fts5PhraseIter *pIter,
192347  int *piCol
192348 ){
192349  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192350  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
192351 
192352  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
192353  if( pIter->a>=pIter->b ){
192354  *piCol = -1;
192355  }else{
192356  int iIncr;
192357  pIter->a += fts5GetVarint32(&pIter->a[0], iIncr);
192358  *piCol += (iIncr-2);
192359  }
192360  }else{
192361  while( 1 ){
192362  int dummy;
192363  if( pIter->a>=pIter->b ){
192364  *piCol = -1;
192365  return;
192366  }
192367  if( pIter->a[0]==0x01 ) break;
192368  pIter->a += fts5GetVarint32(pIter->a, dummy);
192369  }
192370  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
192371  }
192372 }
192373 
192374 static int fts5ApiPhraseFirstColumn(
192375  Fts5Context *pCtx,
192376  int iPhrase,
192377  Fts5PhraseIter *pIter,
192378  int *piCol
192379 ){
192380  int rc = SQLITE_OK;
192381  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192382  Fts5Config *pConfig = ((Fts5Table*)(pCsr->base.pVtab))->pConfig;
192383 
192384  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
192385  Fts5Sorter *pSorter = pCsr->pSorter;
192386  int n;
192387  if( pSorter ){
192388  int i1 = (iPhrase==0 ? 0 : pSorter->aIdx[iPhrase-1]);
192389  n = pSorter->aIdx[iPhrase] - i1;
192390  pIter->a = &pSorter->aPoslist[i1];
192391  }else{
192392  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, iPhrase, &pIter->a, &n);
192393  }
192394  if( rc==SQLITE_OK ){
192395  pIter->b = &pIter->a[n];
192396  *piCol = 0;
192397  fts5ApiPhraseNextColumn(pCtx, pIter, piCol);
192398  }
192399  }else{
192400  int n;
192401  rc = fts5CsrPoslist(pCsr, iPhrase, &pIter->a, &n);
192402  if( rc==SQLITE_OK ){
192403  pIter->b = &pIter->a[n];
192404  if( n<=0 ){
192405  *piCol = -1;
192406  }else if( pIter->a[0]==0x01 ){
192407  pIter->a += 1 + fts5GetVarint32(&pIter->a[1], *piCol);
192408  }else{
192409  *piCol = 0;
192410  }
192411  }
192412  }
192413 
192414  return rc;
192415 }
192416 
192417 
192418 static int fts5ApiQueryPhrase(Fts5Context*, int, void*,
192419  int(*)(const Fts5ExtensionApi*, Fts5Context*, void*)
192420 );
192421 
192422 static const Fts5ExtensionApi sFts5Api = {
192423  2, /* iVersion */
192424  fts5ApiUserData,
192425  fts5ApiColumnCount,
192426  fts5ApiRowCount,
192427  fts5ApiColumnTotalSize,
192428  fts5ApiTokenize,
192429  fts5ApiPhraseCount,
192430  fts5ApiPhraseSize,
192431  fts5ApiInstCount,
192432  fts5ApiInst,
192433  fts5ApiRowid,
192434  fts5ApiColumnText,
192435  fts5ApiColumnSize,
192436  fts5ApiQueryPhrase,
192437  fts5ApiSetAuxdata,
192438  fts5ApiGetAuxdata,
192439  fts5ApiPhraseFirst,
192440  fts5ApiPhraseNext,
192441  fts5ApiPhraseFirstColumn,
192442  fts5ApiPhraseNextColumn,
192443 };
192444 
192445 /*
192446 ** Implementation of API function xQueryPhrase().
192447 */
192448 static int fts5ApiQueryPhrase(
192449  Fts5Context *pCtx,
192450  int iPhrase,
192451  void *pUserData,
192452  int(*xCallback)(const Fts5ExtensionApi*, Fts5Context*, void*)
192453 ){
192454  Fts5Cursor *pCsr = (Fts5Cursor*)pCtx;
192455  Fts5Table *pTab = (Fts5Table*)(pCsr->base.pVtab);
192456  int rc;
192457  Fts5Cursor *pNew = 0;
192458 
192459  rc = fts5OpenMethod(pCsr->base.pVtab, (sqlite3_vtab_cursor**)&pNew);
192460  if( rc==SQLITE_OK ){
192461  pNew->ePlan = FTS5_PLAN_MATCH;
192462  pNew->iFirstRowid = SMALLEST_INT64;
192463  pNew->iLastRowid = LARGEST_INT64;
192464  pNew->base.pVtab = (sqlite3_vtab*)pTab;
192465  rc = sqlite3Fts5ExprClonePhrase(pCsr->pExpr, iPhrase, &pNew->pExpr);
192466  }
192467 
192468  if( rc==SQLITE_OK ){
192469  for(rc = fts5CursorFirst(pTab, pNew, 0);
192470  rc==SQLITE_OK && CsrFlagTest(pNew, FTS5CSR_EOF)==0;
192471  rc = fts5NextMethod((sqlite3_vtab_cursor*)pNew)
192472  ){
192473  rc = xCallback(&sFts5Api, (Fts5Context*)pNew, pUserData);
192474  if( rc!=SQLITE_OK ){
192475  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
192476  break;
192477  }
192478  }
192479  }
192480 
192481  fts5CloseMethod((sqlite3_vtab_cursor*)pNew);
192482  return rc;
192483 }
192484 
192485 static void fts5ApiInvoke(
192486  Fts5Auxiliary *pAux,
192487  Fts5Cursor *pCsr,
192488  sqlite3_context *context,
192489  int argc,
192490  sqlite3_value **argv
192491 ){
192492  assert( pCsr->pAux==0 );
192493  pCsr->pAux = pAux;
192494  pAux->xFunc(&sFts5Api, (Fts5Context*)pCsr, context, argc, argv);
192495  pCsr->pAux = 0;
192496 }
192497 
192498 static Fts5Cursor *fts5CursorFromCsrid(Fts5Global *pGlobal, i64 iCsrId){
192499  Fts5Cursor *pCsr;
192500  for(pCsr=pGlobal->pCsr; pCsr; pCsr=pCsr->pNext){
192501  if( pCsr->iCsrId==iCsrId ) break;
192502  }
192503  return pCsr;
192504 }
192505 
192506 static void fts5ApiCallback(
192507  sqlite3_context *context,
192508  int argc,
192509  sqlite3_value **argv
192510 ){
192511 
192512  Fts5Auxiliary *pAux;
192513  Fts5Cursor *pCsr;
192514  i64 iCsrId;
192515 
192516  assert( argc>=1 );
192517  pAux = (Fts5Auxiliary*)sqlite3_user_data(context);
192518  iCsrId = sqlite3_value_int64(argv[0]);
192519 
192520  pCsr = fts5CursorFromCsrid(pAux->pGlobal, iCsrId);
192521  if( pCsr==0 ){
192522  char *zErr = sqlite3_mprintf("no such cursor: %lld", iCsrId);
192523  sqlite3_result_error(context, zErr, -1);
192524  sqlite3_free(zErr);
192525  }else{
192526  fts5ApiInvoke(pAux, pCsr, context, argc-1, &argv[1]);
192527  }
192528 }
192529 
192530 
192531 /*
192532 ** Given cursor id iId, return a pointer to the corresponding Fts5Index
192533 ** object. Or NULL If the cursor id does not exist.
192534 **
192535 ** If successful, set *ppConfig to point to the associated config object
192536 ** before returning.
192537 */
192538 static Fts5Index *sqlite3Fts5IndexFromCsrid(
192539  Fts5Global *pGlobal, /* FTS5 global context for db handle */
192540  i64 iCsrId, /* Id of cursor to find */
192541  Fts5Config **ppConfig /* OUT: Configuration object */
192542 ){
192543  Fts5Cursor *pCsr;
192544  Fts5Table *pTab;
192545 
192546  pCsr = fts5CursorFromCsrid(pGlobal, iCsrId);
192547  pTab = (Fts5Table*)pCsr->base.pVtab;
192548  *ppConfig = pTab->pConfig;
192549 
192550  return pTab->pIndex;
192551 }
192552 
192553 /*
192554 ** Return a "position-list blob" corresponding to the current position of
192555 ** cursor pCsr via sqlite3_result_blob(). A position-list blob contains
192556 ** the current position-list for each phrase in the query associated with
192557 ** cursor pCsr.
192558 **
192559 ** A position-list blob begins with (nPhrase-1) varints, where nPhrase is
192560 ** the number of phrases in the query. Following the varints are the
192561 ** concatenated position lists for each phrase, in order.
192562 **
192563 ** The first varint (if it exists) contains the size of the position list
192564 ** for phrase 0. The second (same disclaimer) contains the size of position
192565 ** list 1. And so on. There is no size field for the final position list,
192566 ** as it can be derived from the total size of the blob.
192567 */
192568 static int fts5PoslistBlob(sqlite3_context *pCtx, Fts5Cursor *pCsr){
192569  int i;
192570  int rc = SQLITE_OK;
192571  int nPhrase = sqlite3Fts5ExprPhraseCount(pCsr->pExpr);
192572  Fts5Buffer val;
192573 
192574  memset(&val, 0, sizeof(Fts5Buffer));
192575  switch( ((Fts5Table*)(pCsr->base.pVtab))->pConfig->eDetail ){
192576  case FTS5_DETAIL_FULL:
192577 
192578  /* Append the varints */
192579  for(i=0; i<(nPhrase-1); i++){
192580  const u8 *dummy;
192581  int nByte = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &dummy);
192582  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
192583  }
192584 
192585  /* Append the position lists */
192586  for(i=0; i<nPhrase; i++){
192587  const u8 *pPoslist;
192588  int nPoslist;
192589  nPoslist = sqlite3Fts5ExprPoslist(pCsr->pExpr, i, &pPoslist);
192590  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
192591  }
192592  break;
192593 
192594  case FTS5_DETAIL_COLUMNS:
192595 
192596  /* Append the varints */
192597  for(i=0; rc==SQLITE_OK && i<(nPhrase-1); i++){
192598  const u8 *dummy;
192599  int nByte;
192600  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &dummy, &nByte);
192601  sqlite3Fts5BufferAppendVarint(&rc, &val, nByte);
192602  }
192603 
192604  /* Append the position lists */
192605  for(i=0; rc==SQLITE_OK && i<nPhrase; i++){
192606  const u8 *pPoslist;
192607  int nPoslist;
192608  rc = sqlite3Fts5ExprPhraseCollist(pCsr->pExpr, i, &pPoslist, &nPoslist);
192609  sqlite3Fts5BufferAppendBlob(&rc, &val, nPoslist, pPoslist);
192610  }
192611  break;
192612 
192613  default:
192614  break;
192615  }
192616 
192617  sqlite3_result_blob(pCtx, val.p, val.n, sqlite3_free);
192618  return rc;
192619 }
192620 
192621 /*
192622 ** This is the xColumn method, called by SQLite to request a value from
192623 ** the row that the supplied cursor currently points to.
192624 */
192625 static int fts5ColumnMethod(
192626  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
192627  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
192628  int iCol /* Index of column to read value from */
192629 ){
192630  Fts5Table *pTab = (Fts5Table*)(pCursor->pVtab);
192631  Fts5Config *pConfig = pTab->pConfig;
192632  Fts5Cursor *pCsr = (Fts5Cursor*)pCursor;
192633  int rc = SQLITE_OK;
192634 
192635  assert( CsrFlagTest(pCsr, FTS5CSR_EOF)==0 );
192636 
192637  if( pCsr->ePlan==FTS5_PLAN_SPECIAL ){
192638  if( iCol==pConfig->nCol ){
192639  sqlite3_result_int64(pCtx, pCsr->iSpecial);
192640  }
192641  }else
192642 
192643  if( iCol==pConfig->nCol ){
192644  /* User is requesting the value of the special column with the same name
192645  ** as the table. Return the cursor integer id number. This value is only
192646  ** useful in that it may be passed as the first argument to an FTS5
192647  ** auxiliary function. */
192648  sqlite3_result_int64(pCtx, pCsr->iCsrId);
192649  }else if( iCol==pConfig->nCol+1 ){
192650 
192651  /* The value of the "rank" column. */
192652  if( pCsr->ePlan==FTS5_PLAN_SOURCE ){
192653  fts5PoslistBlob(pCtx, pCsr);
192654  }else if(
192655  pCsr->ePlan==FTS5_PLAN_MATCH
192656  || pCsr->ePlan==FTS5_PLAN_SORTED_MATCH
192657  ){
192658  if( pCsr->pRank || SQLITE_OK==(rc = fts5FindRankFunction(pCsr)) ){
192659  fts5ApiInvoke(pCsr->pRank, pCsr, pCtx, pCsr->nRankArg, pCsr->apRankArg);
192660  }
192661  }
192662  }else if( !fts5IsContentless(pTab) ){
192663  rc = fts5SeekCursor(pCsr, 1);
192664  if( rc==SQLITE_OK ){
192665  sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
192666  }
192667  }
192668  return rc;
192669 }
192670 
192671 
192672 /*
192673 ** This routine implements the xFindFunction method for the FTS3
192674 ** virtual table.
192675 */
192676 static int fts5FindFunctionMethod(
192677  sqlite3_vtab *pVtab, /* Virtual table handle */
192678  int nUnused, /* Number of SQL function arguments */
192679  const char *zName, /* Name of SQL function */
192680  void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
192681  void **ppArg /* OUT: User data for *pxFunc */
192682 ){
192683  Fts5Table *pTab = (Fts5Table*)pVtab;
192684  Fts5Auxiliary *pAux;
192685 
192686  UNUSED_PARAM(nUnused);
192687  pAux = fts5FindAuxiliary(pTab, zName);
192688  if( pAux ){
192689  *pxFunc = fts5ApiCallback;
192690  *ppArg = (void*)pAux;
192691  return 1;
192692  }
192693 
192694  /* No function of the specified name was found. Return 0. */
192695  return 0;
192696 }
192697 
192698 /*
192699 ** Implementation of FTS5 xRename method. Rename an fts5 table.
192700 */
192701 static int fts5RenameMethod(
192702  sqlite3_vtab *pVtab, /* Virtual table handle */
192703  const char *zName /* New name of table */
192704 ){
192705  Fts5Table *pTab = (Fts5Table*)pVtab;
192706  return sqlite3Fts5StorageRename(pTab->pStorage, zName);
192707 }
192708 
192709 /*
192710 ** The xSavepoint() method.
192711 **
192712 ** Flush the contents of the pending-terms table to disk.
192713 */
192714 static int fts5SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
192715  Fts5Table *pTab = (Fts5Table*)pVtab;
192716  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
192717  fts5CheckTransactionState(pTab, FTS5_SAVEPOINT, iSavepoint);
192718  fts5TripCursors(pTab);
192719  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
192720 }
192721 
192722 /*
192723 ** The xRelease() method.
192724 **
192725 ** This is a no-op.
192726 */
192727 static int fts5ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
192728  Fts5Table *pTab = (Fts5Table*)pVtab;
192729  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
192730  fts5CheckTransactionState(pTab, FTS5_RELEASE, iSavepoint);
192731  fts5TripCursors(pTab);
192732  return sqlite3Fts5StorageSync(pTab->pStorage, 0);
192733 }
192734 
192735 /*
192736 ** The xRollbackTo() method.
192737 **
192738 ** Discard the contents of the pending terms table.
192739 */
192740 static int fts5RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
192741  Fts5Table *pTab = (Fts5Table*)pVtab;
192742  UNUSED_PARAM(iSavepoint); /* Call below is a no-op for NDEBUG builds */
192743  fts5CheckTransactionState(pTab, FTS5_ROLLBACKTO, iSavepoint);
192744  fts5TripCursors(pTab);
192745  return sqlite3Fts5StorageRollback(pTab->pStorage);
192746 }
192747 
192748 /*
192749 ** Register a new auxiliary function with global context pGlobal.
192750 */
192751 static int fts5CreateAux(
192752  fts5_api *pApi, /* Global context (one per db handle) */
192753  const char *zName, /* Name of new function */
192754  void *pUserData, /* User data for aux. function */
192755  fts5_extension_function xFunc, /* Aux. function implementation */
192756  void(*xDestroy)(void*) /* Destructor for pUserData */
192757 ){
192758  Fts5Global *pGlobal = (Fts5Global*)pApi;
192759  int rc = sqlite3_overload_function(pGlobal->db, zName, -1);
192760  if( rc==SQLITE_OK ){
192761  Fts5Auxiliary *pAux;
192762  int nName; /* Size of zName in bytes, including \0 */
192763  int nByte; /* Bytes of space to allocate */
192764 
192765  nName = (int)strlen(zName) + 1;
192766  nByte = sizeof(Fts5Auxiliary) + nName;
192767  pAux = (Fts5Auxiliary*)sqlite3_malloc(nByte);
192768  if( pAux ){
192769  memset(pAux, 0, nByte);
192770  pAux->zFunc = (char*)&pAux[1];
192771  memcpy(pAux->zFunc, zName, nName);
192772  pAux->pGlobal = pGlobal;
192773  pAux->pUserData = pUserData;
192774  pAux->xFunc = xFunc;
192775  pAux->xDestroy = xDestroy;
192776  pAux->pNext = pGlobal->pAux;
192777  pGlobal->pAux = pAux;
192778  }else{
192779  rc = SQLITE_NOMEM;
192780  }
192781  }
192782 
192783  return rc;
192784 }
192785 
192786 /*
192787 ** Register a new tokenizer. This is the implementation of the
192788 ** fts5_api.xCreateTokenizer() method.
192789 */
192790 static int fts5CreateTokenizer(
192791  fts5_api *pApi, /* Global context (one per db handle) */
192792  const char *zName, /* Name of new function */
192793  void *pUserData, /* User data for aux. function */
192794  fts5_tokenizer *pTokenizer, /* Tokenizer implementation */
192795  void(*xDestroy)(void*) /* Destructor for pUserData */
192796 ){
192797  Fts5Global *pGlobal = (Fts5Global*)pApi;
192798  Fts5TokenizerModule *pNew;
192799  int nName; /* Size of zName and its \0 terminator */
192800  int nByte; /* Bytes of space to allocate */
192801  int rc = SQLITE_OK;
192802 
192803  nName = (int)strlen(zName) + 1;
192804  nByte = sizeof(Fts5TokenizerModule) + nName;
192805  pNew = (Fts5TokenizerModule*)sqlite3_malloc(nByte);
192806  if( pNew ){
192807  memset(pNew, 0, nByte);
192808  pNew->zName = (char*)&pNew[1];
192809  memcpy(pNew->zName, zName, nName);
192810  pNew->pUserData = pUserData;
192811  pNew->x = *pTokenizer;
192812  pNew->xDestroy = xDestroy;
192813  pNew->pNext = pGlobal->pTok;
192814  pGlobal->pTok = pNew;
192815  if( pNew->pNext==0 ){
192816  pGlobal->pDfltTok = pNew;
192817  }
192818  }else{
192819  rc = SQLITE_NOMEM;
192820  }
192821 
192822  return rc;
192823 }
192824 
192825 static Fts5TokenizerModule *fts5LocateTokenizer(
192826  Fts5Global *pGlobal,
192827  const char *zName
192828 ){
192829  Fts5TokenizerModule *pMod = 0;
192830 
192831  if( zName==0 ){
192832  pMod = pGlobal->pDfltTok;
192833  }else{
192834  for(pMod=pGlobal->pTok; pMod; pMod=pMod->pNext){
192835  if( sqlite3_stricmp(zName, pMod->zName)==0 ) break;
192836  }
192837  }
192838 
192839  return pMod;
192840 }
192841 
192842 /*
192843 ** Find a tokenizer. This is the implementation of the
192844 ** fts5_api.xFindTokenizer() method.
192845 */
192846 static int fts5FindTokenizer(
192847  fts5_api *pApi, /* Global context (one per db handle) */
192848  const char *zName, /* Name of new function */
192849  void **ppUserData,
192850  fts5_tokenizer *pTokenizer /* Populate this object */
192851 ){
192852  int rc = SQLITE_OK;
192853  Fts5TokenizerModule *pMod;
192854 
192855  pMod = fts5LocateTokenizer((Fts5Global*)pApi, zName);
192856  if( pMod ){
192857  *pTokenizer = pMod->x;
192858  *ppUserData = pMod->pUserData;
192859  }else{
192860  memset(pTokenizer, 0, sizeof(fts5_tokenizer));
192861  rc = SQLITE_ERROR;
192862  }
192863 
192864  return rc;
192865 }
192866 
192867 static int sqlite3Fts5GetTokenizer(
192868  Fts5Global *pGlobal,
192869  const char **azArg,
192870  int nArg,
192871  Fts5Tokenizer **ppTok,
192872  fts5_tokenizer **ppTokApi,
192873  char **pzErr
192874 ){
192875  Fts5TokenizerModule *pMod;
192876  int rc = SQLITE_OK;
192877 
192878  pMod = fts5LocateTokenizer(pGlobal, nArg==0 ? 0 : azArg[0]);
192879  if( pMod==0 ){
192880  assert( nArg>0 );
192881  rc = SQLITE_ERROR;
192882  *pzErr = sqlite3_mprintf("no such tokenizer: %s", azArg[0]);
192883  }else{
192884  rc = pMod->x.xCreate(pMod->pUserData, &azArg[1], (nArg?nArg-1:0), ppTok);
192885  *ppTokApi = &pMod->x;
192886  if( rc!=SQLITE_OK && pzErr ){
192887  *pzErr = sqlite3_mprintf("error in tokenizer constructor");
192888  }
192889  }
192890 
192891  if( rc!=SQLITE_OK ){
192892  *ppTokApi = 0;
192893  *ppTok = 0;
192894  }
192895 
192896  return rc;
192897 }
192898 
192899 static void fts5ModuleDestroy(void *pCtx){
192900  Fts5TokenizerModule *pTok, *pNextTok;
192901  Fts5Auxiliary *pAux, *pNextAux;
192902  Fts5Global *pGlobal = (Fts5Global*)pCtx;
192903 
192904  for(pAux=pGlobal->pAux; pAux; pAux=pNextAux){
192905  pNextAux = pAux->pNext;
192906  if( pAux->xDestroy ) pAux->xDestroy(pAux->pUserData);
192907  sqlite3_free(pAux);
192908  }
192909 
192910  for(pTok=pGlobal->pTok; pTok; pTok=pNextTok){
192911  pNextTok = pTok->pNext;
192912  if( pTok->xDestroy ) pTok->xDestroy(pTok->pUserData);
192913  sqlite3_free(pTok);
192914  }
192915 
192916  sqlite3_free(pGlobal);
192917 }
192918 
192919 static void fts5Fts5Func(
192920  sqlite3_context *pCtx, /* Function call context */
192921  int nArg, /* Number of args */
192922  sqlite3_value **apUnused /* Function arguments */
192923 ){
192924  Fts5Global *pGlobal = (Fts5Global*)sqlite3_user_data(pCtx);
192925  char buf[8];
192926  UNUSED_PARAM2(nArg, apUnused);
192927  assert( nArg==0 );
192928  assert( sizeof(buf)>=sizeof(pGlobal) );
192929  memcpy(buf, (void*)&pGlobal, sizeof(pGlobal));
192930  sqlite3_result_blob(pCtx, buf, sizeof(pGlobal), SQLITE_TRANSIENT);
192931 }
192932 
192933 /*
192934 ** Implementation of fts5_source_id() function.
192935 */
192936 static void fts5SourceIdFunc(
192937  sqlite3_context *pCtx, /* Function call context */
192938  int nArg, /* Number of args */
192939  sqlite3_value **apUnused /* Function arguments */
192940 ){
192941  assert( nArg==0 );
192942  UNUSED_PARAM2(nArg, apUnused);
192943  sqlite3_result_text(pCtx, "fts5: 2016-05-18 10:57:30 fc49f556e48970561d7ab6a2f24fdd7d9eb81ff2", -1, SQLITE_TRANSIENT);
192944 }
192945 
192946 static int fts5Init(sqlite3 *db){
192947  static const sqlite3_module fts5Mod = {
192948  /* iVersion */ 2,
192949  /* xCreate */ fts5CreateMethod,
192950  /* xConnect */ fts5ConnectMethod,
192951  /* xBestIndex */ fts5BestIndexMethod,
192952  /* xDisconnect */ fts5DisconnectMethod,
192953  /* xDestroy */ fts5DestroyMethod,
192954  /* xOpen */ fts5OpenMethod,
192955  /* xClose */ fts5CloseMethod,
192956  /* xFilter */ fts5FilterMethod,
192957  /* xNext */ fts5NextMethod,
192958  /* xEof */ fts5EofMethod,
192959  /* xColumn */ fts5ColumnMethod,
192960  /* xRowid */ fts5RowidMethod,
192961  /* xUpdate */ fts5UpdateMethod,
192962  /* xBegin */ fts5BeginMethod,
192963  /* xSync */ fts5SyncMethod,
192964  /* xCommit */ fts5CommitMethod,
192965  /* xRollback */ fts5RollbackMethod,
192966  /* xFindFunction */ fts5FindFunctionMethod,
192967  /* xRename */ fts5RenameMethod,
192968  /* xSavepoint */ fts5SavepointMethod,
192969  /* xRelease */ fts5ReleaseMethod,
192970  /* xRollbackTo */ fts5RollbackToMethod,
192971  };
192972 
192973  int rc;
192974  Fts5Global *pGlobal = 0;
192975 
192976  pGlobal = (Fts5Global*)sqlite3_malloc(sizeof(Fts5Global));
192977  if( pGlobal==0 ){
192978  rc = SQLITE_NOMEM;
192979  }else{
192980  void *p = (void*)pGlobal;
192981  memset(pGlobal, 0, sizeof(Fts5Global));
192982  pGlobal->db = db;
192983  pGlobal->api.iVersion = 2;
192984  pGlobal->api.xCreateFunction = fts5CreateAux;
192985  pGlobal->api.xCreateTokenizer = fts5CreateTokenizer;
192986  pGlobal->api.xFindTokenizer = fts5FindTokenizer;
192987  rc = sqlite3_create_module_v2(db, "fts5", &fts5Mod, p, fts5ModuleDestroy);
192988  if( rc==SQLITE_OK ) rc = sqlite3Fts5IndexInit(db);
192989  if( rc==SQLITE_OK ) rc = sqlite3Fts5ExprInit(pGlobal, db);
192990  if( rc==SQLITE_OK ) rc = sqlite3Fts5AuxInit(&pGlobal->api);
192991  if( rc==SQLITE_OK ) rc = sqlite3Fts5TokenizerInit(&pGlobal->api);
192992  if( rc==SQLITE_OK ) rc = sqlite3Fts5VocabInit(pGlobal, db);
192993  if( rc==SQLITE_OK ){
192995  db, "fts5", 0, SQLITE_UTF8, p, fts5Fts5Func, 0, 0
192996  );
192997  }
192998  if( rc==SQLITE_OK ){
193000  db, "fts5_source_id", 0, SQLITE_UTF8, p, fts5SourceIdFunc, 0, 0
193001  );
193002  }
193003  }
193004 
193005  /* If SQLITE_FTS5_ENABLE_TEST_MI is defined, assume that the file
193006  ** fts5_test_mi.c is compiled and linked into the executable. And call
193007  ** its entry point to enable the matchinfo() demo. */
193008 #ifdef SQLITE_FTS5_ENABLE_TEST_MI
193009  if( rc==SQLITE_OK ){
193010  extern int sqlite3Fts5TestRegisterMatchinfo(sqlite3*);
193011  rc = sqlite3Fts5TestRegisterMatchinfo(db);
193012  }
193013 #endif
193014 
193015  return rc;
193016 }
193017 
193018 /*
193019 ** The following functions are used to register the module with SQLite. If
193020 ** this module is being built as part of the SQLite core (SQLITE_CORE is
193021 ** defined), then sqlite3_open() will call sqlite3Fts5Init() directly.
193022 **
193023 ** Or, if this module is being built as a loadable extension,
193024 ** sqlite3Fts5Init() is omitted and the two standard entry points
193025 ** sqlite3_fts_init() and sqlite3_fts5_init() defined instead.
193026 */
193027 #ifndef SQLITE_CORE
193028 #ifdef _WIN32
193029 __declspec(dllexport)
193030 #endif
193031 SQLITE_API int SQLITE_STDCALL sqlite3_fts_init(
193032  sqlite3 *db,
193033  char **pzErrMsg,
193034  const sqlite3_api_routines *pApi
193035 ){
193036  SQLITE_EXTENSION_INIT2(pApi);
193037  (void)pzErrMsg; /* Unused parameter */
193038  return fts5Init(db);
193039 }
193040 
193041 #ifdef _WIN32
193042 __declspec(dllexport)
193043 #endif
193044 SQLITE_API int SQLITE_STDCALL sqlite3_fts5_init(
193045  sqlite3 *db,
193046  char **pzErrMsg,
193047  const sqlite3_api_routines *pApi
193048 ){
193049  SQLITE_EXTENSION_INIT2(pApi);
193050  (void)pzErrMsg; /* Unused parameter */
193051  return fts5Init(db);
193052 }
193053 #else
193054 SQLITE_PRIVATE int sqlite3Fts5Init(sqlite3 *db){
193055  return fts5Init(db);
193056 }
193057 #endif
193058 
193059 /*
193060 ** 2014 May 31
193061 **
193062 ** The author disclaims copyright to this source code. In place of
193063 ** a legal notice, here is a blessing:
193064 **
193065 ** May you do good and not evil.
193066 ** May you find forgiveness for yourself and forgive others.
193067 ** May you share freely, never taking more than you give.
193068 **
193069 ******************************************************************************
193070 **
193071 */
193072 
193073 
193074 
193075 /* #include "fts5Int.h" */
193076 
193077 struct Fts5Storage {
193078  Fts5Config *pConfig;
193079  Fts5Index *pIndex;
193080  int bTotalsValid; /* True if nTotalRow/aTotalSize[] are valid */
193081  i64 nTotalRow; /* Total number of rows in FTS table */
193082  i64 *aTotalSize; /* Total sizes of each column */
193083  sqlite3_stmt *aStmt[11];
193084 };
193085 
193086 
193087 #if FTS5_STMT_SCAN_ASC!=0
193088 # error "FTS5_STMT_SCAN_ASC mismatch"
193089 #endif
193090 #if FTS5_STMT_SCAN_DESC!=1
193091 # error "FTS5_STMT_SCAN_DESC mismatch"
193092 #endif
193093 #if FTS5_STMT_LOOKUP!=2
193094 # error "FTS5_STMT_LOOKUP mismatch"
193095 #endif
193096 
193097 #define FTS5_STMT_INSERT_CONTENT 3
193098 #define FTS5_STMT_REPLACE_CONTENT 4
193099 #define FTS5_STMT_DELETE_CONTENT 5
193100 #define FTS5_STMT_REPLACE_DOCSIZE 6
193101 #define FTS5_STMT_DELETE_DOCSIZE 7
193102 #define FTS5_STMT_LOOKUP_DOCSIZE 8
193103 #define FTS5_STMT_REPLACE_CONFIG 9
193104 #define FTS5_STMT_SCAN 10
193105 
193106 /*
193107 ** Prepare the two insert statements - Fts5Storage.pInsertContent and
193108 ** Fts5Storage.pInsertDocsize - if they have not already been prepared.
193109 ** Return SQLITE_OK if successful, or an SQLite error code if an error
193110 ** occurs.
193111 */
193112 static int fts5StorageGetStmt(
193113  Fts5Storage *p, /* Storage handle */
193114  int eStmt, /* FTS5_STMT_XXX constant */
193115  sqlite3_stmt **ppStmt, /* OUT: Prepared statement handle */
193116  char **pzErrMsg /* OUT: Error message (if any) */
193117 ){
193118  int rc = SQLITE_OK;
193119 
193120  /* If there is no %_docsize table, there should be no requests for
193121  ** statements to operate on it. */
193122  assert( p->pConfig->bColumnsize || (
193123  eStmt!=FTS5_STMT_REPLACE_DOCSIZE
193124  && eStmt!=FTS5_STMT_DELETE_DOCSIZE
193125  && eStmt!=FTS5_STMT_LOOKUP_DOCSIZE
193126  ));
193127 
193128  assert( eStmt>=0 && eStmt<ArraySize(p->aStmt) );
193129  if( p->aStmt[eStmt]==0 ){
193130  const char *azStmt[] = {
193131  "SELECT %s FROM %s T WHERE T.%Q >= ? AND T.%Q <= ? ORDER BY T.%Q ASC",
193132  "SELECT %s FROM %s T WHERE T.%Q <= ? AND T.%Q >= ? ORDER BY T.%Q DESC",
193133  "SELECT %s FROM %s T WHERE T.%Q=?", /* LOOKUP */
193134 
193135  "INSERT INTO %Q.'%q_content' VALUES(%s)", /* INSERT_CONTENT */
193136  "REPLACE INTO %Q.'%q_content' VALUES(%s)", /* REPLACE_CONTENT */
193137  "DELETE FROM %Q.'%q_content' WHERE id=?", /* DELETE_CONTENT */
193138  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)", /* REPLACE_DOCSIZE */
193139  "DELETE FROM %Q.'%q_docsize' WHERE id=?", /* DELETE_DOCSIZE */
193140 
193141  "SELECT sz FROM %Q.'%q_docsize' WHERE id=?", /* LOOKUP_DOCSIZE */
193142 
193143  "REPLACE INTO %Q.'%q_config' VALUES(?,?)", /* REPLACE_CONFIG */
193144  "SELECT %s FROM %s AS T", /* SCAN */
193145  };
193146  Fts5Config *pC = p->pConfig;
193147  char *zSql = 0;
193148 
193149  switch( eStmt ){
193150  case FTS5_STMT_SCAN:
193151  zSql = sqlite3_mprintf(azStmt[eStmt],
193152  pC->zContentExprlist, pC->zContent
193153  );
193154  break;
193155 
193156  case FTS5_STMT_SCAN_ASC:
193157  case FTS5_STMT_SCAN_DESC:
193158  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zContentExprlist,
193159  pC->zContent, pC->zContentRowid, pC->zContentRowid,
193160  pC->zContentRowid
193161  );
193162  break;
193163 
193164  case FTS5_STMT_LOOKUP:
193165  zSql = sqlite3_mprintf(azStmt[eStmt],
193166  pC->zContentExprlist, pC->zContent, pC->zContentRowid
193167  );
193168  break;
193169 
193170  case FTS5_STMT_INSERT_CONTENT:
193171  case FTS5_STMT_REPLACE_CONTENT: {
193172  int nCol = pC->nCol + 1;
193173  char *zBind;
193174  int i;
193175 
193176  zBind = sqlite3_malloc(1 + nCol*2);
193177  if( zBind ){
193178  for(i=0; i<nCol; i++){
193179  zBind[i*2] = '?';
193180  zBind[i*2 + 1] = ',';
193181  }
193182  zBind[i*2-1] = '\0';
193183  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName, zBind);
193184  sqlite3_free(zBind);
193185  }
193186  break;
193187  }
193188 
193189  default:
193190  zSql = sqlite3_mprintf(azStmt[eStmt], pC->zDb, pC->zName);
193191  break;
193192  }
193193 
193194  if( zSql==0 ){
193195  rc = SQLITE_NOMEM;
193196  }else{
193197  rc = sqlite3_prepare_v2(pC->db, zSql, -1, &p->aStmt[eStmt], 0);
193198  sqlite3_free(zSql);
193199  if( rc!=SQLITE_OK && pzErrMsg ){
193200  *pzErrMsg = sqlite3_mprintf("%s", sqlite3_errmsg(pC->db));
193201  }
193202  }
193203  }
193204 
193205  *ppStmt = p->aStmt[eStmt];
193206  sqlite3_reset(*ppStmt);
193207  return rc;
193208 }
193209 
193210 
193211 static int fts5ExecPrintf(
193212  sqlite3 *db,
193213  char **pzErr,
193214  const char *zFormat,
193215  ...
193216 ){
193217  int rc;
193218  va_list ap; /* ... printf arguments */
193219  char *zSql;
193220 
193221  va_start(ap, zFormat);
193222  zSql = sqlite3_vmprintf(zFormat, ap);
193223 
193224  if( zSql==0 ){
193225  rc = SQLITE_NOMEM;
193226  }else{
193227  rc = sqlite3_exec(db, zSql, 0, 0, pzErr);
193228  sqlite3_free(zSql);
193229  }
193230 
193231  va_end(ap);
193232  return rc;
193233 }
193234 
193235 /*
193236 ** Drop all shadow tables. Return SQLITE_OK if successful or an SQLite error
193237 ** code otherwise.
193238 */
193239 static int sqlite3Fts5DropAll(Fts5Config *pConfig){
193240  int rc = fts5ExecPrintf(pConfig->db, 0,
193241  "DROP TABLE IF EXISTS %Q.'%q_data';"
193242  "DROP TABLE IF EXISTS %Q.'%q_idx';"
193243  "DROP TABLE IF EXISTS %Q.'%q_config';",
193244  pConfig->zDb, pConfig->zName,
193245  pConfig->zDb, pConfig->zName,
193246  pConfig->zDb, pConfig->zName
193247  );
193248  if( rc==SQLITE_OK && pConfig->bColumnsize ){
193249  rc = fts5ExecPrintf(pConfig->db, 0,
193250  "DROP TABLE IF EXISTS %Q.'%q_docsize';",
193251  pConfig->zDb, pConfig->zName
193252  );
193253  }
193254  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
193255  rc = fts5ExecPrintf(pConfig->db, 0,
193256  "DROP TABLE IF EXISTS %Q.'%q_content';",
193257  pConfig->zDb, pConfig->zName
193258  );
193259  }
193260  return rc;
193261 }
193262 
193263 static void fts5StorageRenameOne(
193264  Fts5Config *pConfig, /* Current FTS5 configuration */
193265  int *pRc, /* IN/OUT: Error code */
193266  const char *zTail, /* Tail of table name e.g. "data", "config" */
193267  const char *zName /* New name of FTS5 table */
193268 ){
193269  if( *pRc==SQLITE_OK ){
193270  *pRc = fts5ExecPrintf(pConfig->db, 0,
193271  "ALTER TABLE %Q.'%q_%s' RENAME TO '%q_%s';",
193272  pConfig->zDb, pConfig->zName, zTail, zName, zTail
193273  );
193274  }
193275 }
193276 
193277 static int sqlite3Fts5StorageRename(Fts5Storage *pStorage, const char *zName){
193278  Fts5Config *pConfig = pStorage->pConfig;
193279  int rc = sqlite3Fts5StorageSync(pStorage, 1);
193280 
193281  fts5StorageRenameOne(pConfig, &rc, "data", zName);
193282  fts5StorageRenameOne(pConfig, &rc, "idx", zName);
193283  fts5StorageRenameOne(pConfig, &rc, "config", zName);
193284  if( pConfig->bColumnsize ){
193285  fts5StorageRenameOne(pConfig, &rc, "docsize", zName);
193286  }
193287  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
193288  fts5StorageRenameOne(pConfig, &rc, "content", zName);
193289  }
193290  return rc;
193291 }
193292 
193293 /*
193294 ** Create the shadow table named zPost, with definition zDefn. Return
193295 ** SQLITE_OK if successful, or an SQLite error code otherwise.
193296 */
193297 static int sqlite3Fts5CreateTable(
193298  Fts5Config *pConfig, /* FTS5 configuration */
193299  const char *zPost, /* Shadow table to create (e.g. "content") */
193300  const char *zDefn, /* Columns etc. for shadow table */
193301  int bWithout, /* True for without rowid */
193302  char **pzErr /* OUT: Error message */
193303 ){
193304  int rc;
193305  char *zErr = 0;
193306 
193307  rc = fts5ExecPrintf(pConfig->db, &zErr, "CREATE TABLE %Q.'%q_%q'(%s)%s",
193308  pConfig->zDb, pConfig->zName, zPost, zDefn, bWithout?" WITHOUT ROWID":""
193309  );
193310  if( zErr ){
193311  *pzErr = sqlite3_mprintf(
193312  "fts5: error creating shadow table %q_%s: %s",
193313  pConfig->zName, zPost, zErr
193314  );
193315  sqlite3_free(zErr);
193316  }
193317 
193318  return rc;
193319 }
193320 
193321 /*
193322 ** Open a new Fts5Index handle. If the bCreate argument is true, create
193323 ** and initialize the underlying tables
193324 **
193325 ** If successful, set *pp to point to the new object and return SQLITE_OK.
193326 ** Otherwise, set *pp to NULL and return an SQLite error code.
193327 */
193328 static int sqlite3Fts5StorageOpen(
193329  Fts5Config *pConfig,
193330  Fts5Index *pIndex,
193331  int bCreate,
193332  Fts5Storage **pp,
193333  char **pzErr /* OUT: Error message */
193334 ){
193335  int rc = SQLITE_OK;
193336  Fts5Storage *p; /* New object */
193337  int nByte; /* Bytes of space to allocate */
193338 
193339  nByte = sizeof(Fts5Storage) /* Fts5Storage object */
193340  + pConfig->nCol * sizeof(i64); /* Fts5Storage.aTotalSize[] */
193341  *pp = p = (Fts5Storage*)sqlite3_malloc(nByte);
193342  if( !p ) return SQLITE_NOMEM;
193343 
193344  memset(p, 0, nByte);
193345  p->aTotalSize = (i64*)&p[1];
193346  p->pConfig = pConfig;
193347  p->pIndex = pIndex;
193348 
193349  if( bCreate ){
193350  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
193351  int nDefn = 32 + pConfig->nCol*10;
193352  char *zDefn = sqlite3_malloc(32 + pConfig->nCol * 10);
193353  if( zDefn==0 ){
193354  rc = SQLITE_NOMEM;
193355  }else{
193356  int i;
193357  int iOff;
193358  sqlite3_snprintf(nDefn, zDefn, "id INTEGER PRIMARY KEY");
193359  iOff = (int)strlen(zDefn);
193360  for(i=0; i<pConfig->nCol; i++){
193361  sqlite3_snprintf(nDefn-iOff, &zDefn[iOff], ", c%d", i);
193362  iOff += (int)strlen(&zDefn[iOff]);
193363  }
193364  rc = sqlite3Fts5CreateTable(pConfig, "content", zDefn, 0, pzErr);
193365  }
193366  sqlite3_free(zDefn);
193367  }
193368 
193369  if( rc==SQLITE_OK && pConfig->bColumnsize ){
193370  rc = sqlite3Fts5CreateTable(
193371  pConfig, "docsize", "id INTEGER PRIMARY KEY, sz BLOB", 0, pzErr
193372  );
193373  }
193374  if( rc==SQLITE_OK ){
193375  rc = sqlite3Fts5CreateTable(
193376  pConfig, "config", "k PRIMARY KEY, v", 1, pzErr
193377  );
193378  }
193379  if( rc==SQLITE_OK ){
193380  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
193381  }
193382  }
193383 
193384  if( rc ){
193385  sqlite3Fts5StorageClose(p);
193386  *pp = 0;
193387  }
193388  return rc;
193389 }
193390 
193391 /*
193392 ** Close a handle opened by an earlier call to sqlite3Fts5StorageOpen().
193393 */
193394 static int sqlite3Fts5StorageClose(Fts5Storage *p){
193395  int rc = SQLITE_OK;
193396  if( p ){
193397  int i;
193398 
193399  /* Finalize all SQL statements */
193400  for(i=0; i<ArraySize(p->aStmt); i++){
193401  sqlite3_finalize(p->aStmt[i]);
193402  }
193403 
193404  sqlite3_free(p);
193405  }
193406  return rc;
193407 }
193408 
193409 typedef struct Fts5InsertCtx Fts5InsertCtx;
193410 struct Fts5InsertCtx {
193411  Fts5Storage *pStorage;
193412  int iCol;
193413  int szCol; /* Size of column value in tokens */
193414 };
193415 
193416 /*
193417 ** Tokenization callback used when inserting tokens into the FTS index.
193418 */
193419 static int fts5StorageInsertCallback(
193420  void *pContext, /* Pointer to Fts5InsertCtx object */
193421  int tflags,
193422  const char *pToken, /* Buffer containing token */
193423  int nToken, /* Size of token in bytes */
193424  int iUnused1, /* Start offset of token */
193425  int iUnused2 /* End offset of token */
193426 ){
193427  Fts5InsertCtx *pCtx = (Fts5InsertCtx*)pContext;
193428  Fts5Index *pIdx = pCtx->pStorage->pIndex;
193429  UNUSED_PARAM2(iUnused1, iUnused2);
193430  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
193431  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
193432  pCtx->szCol++;
193433  }
193434  return sqlite3Fts5IndexWrite(pIdx, pCtx->iCol, pCtx->szCol-1, pToken, nToken);
193435 }
193436 
193437 /*
193438 ** If a row with rowid iDel is present in the %_content table, add the
193439 ** delete-markers to the FTS index necessary to delete it. Do not actually
193440 ** remove the %_content row at this time though.
193441 */
193442 static int fts5StorageDeleteFromIndex(
193443  Fts5Storage *p,
193444  i64 iDel,
193445  sqlite3_value **apVal
193446 ){
193447  Fts5Config *pConfig = p->pConfig;
193448  sqlite3_stmt *pSeek = 0; /* SELECT to read row iDel from %_data */
193449  int rc; /* Return code */
193450  int rc2; /* sqlite3_reset() return code */
193451  int iCol;
193452  Fts5InsertCtx ctx;
193453 
193454  if( apVal==0 ){
193455  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP, &pSeek, 0);
193456  if( rc!=SQLITE_OK ) return rc;
193457  sqlite3_bind_int64(pSeek, 1, iDel);
193458  if( sqlite3_step(pSeek)!=SQLITE_ROW ){
193459  return sqlite3_reset(pSeek);
193460  }
193461  }
193462 
193463  ctx.pStorage = p;
193464  ctx.iCol = -1;
193465  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 1, iDel);
193466  for(iCol=1; rc==SQLITE_OK && iCol<=pConfig->nCol; iCol++){
193467  if( pConfig->abUnindexed[iCol-1]==0 ){
193468  const char *zText;
193469  int nText;
193470  if( pSeek ){
193471  zText = (const char*)sqlite3_column_text(pSeek, iCol);
193472  nText = sqlite3_column_bytes(pSeek, iCol);
193473  }else{
193474  zText = (const char*)sqlite3_value_text(apVal[iCol-1]);
193475  nText = sqlite3_value_bytes(apVal[iCol-1]);
193476  }
193477  ctx.szCol = 0;
193478  rc = sqlite3Fts5Tokenize(pConfig, FTS5_TOKENIZE_DOCUMENT,
193479  zText, nText, (void*)&ctx, fts5StorageInsertCallback
193480  );
193481  p->aTotalSize[iCol-1] -= (i64)ctx.szCol;
193482  }
193483  }
193484  p->nTotalRow--;
193485 
193486  rc2 = sqlite3_reset(pSeek);
193487  if( rc==SQLITE_OK ) rc = rc2;
193488  return rc;
193489 }
193490 
193491 
193492 /*
193493 ** Insert a record into the %_docsize table. Specifically, do:
193494 **
193495 ** INSERT OR REPLACE INTO %_docsize(id, sz) VALUES(iRowid, pBuf);
193496 **
193497 ** If there is no %_docsize table (as happens if the columnsize=0 option
193498 ** is specified when the FTS5 table is created), this function is a no-op.
193499 */
193500 static int fts5StorageInsertDocsize(
193501  Fts5Storage *p, /* Storage module to write to */
193502  i64 iRowid, /* id value */
193503  Fts5Buffer *pBuf /* sz value */
193504 ){
193505  int rc = SQLITE_OK;
193506  if( p->pConfig->bColumnsize ){
193507  sqlite3_stmt *pReplace = 0;
193508  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
193509  if( rc==SQLITE_OK ){
193510  sqlite3_bind_int64(pReplace, 1, iRowid);
193511  sqlite3_bind_blob(pReplace, 2, pBuf->p, pBuf->n, SQLITE_STATIC);
193512  sqlite3_step(pReplace);
193513  rc = sqlite3_reset(pReplace);
193514  }
193515  }
193516  return rc;
193517 }
193518 
193519 /*
193520 ** Load the contents of the "averages" record from disk into the
193521 ** p->nTotalRow and p->aTotalSize[] variables. If successful, and if
193522 ** argument bCache is true, set the p->bTotalsValid flag to indicate
193523 ** that the contents of aTotalSize[] and nTotalRow are valid until
193524 ** further notice.
193525 **
193526 ** Return SQLITE_OK if successful, or an SQLite error code if an error
193527 ** occurs.
193528 */
193529 static int fts5StorageLoadTotals(Fts5Storage *p, int bCache){
193530  int rc = SQLITE_OK;
193531  if( p->bTotalsValid==0 ){
193532  rc = sqlite3Fts5IndexGetAverages(p->pIndex, &p->nTotalRow, p->aTotalSize);
193533  p->bTotalsValid = bCache;
193534  }
193535  return rc;
193536 }
193537 
193538 /*
193539 ** Store the current contents of the p->nTotalRow and p->aTotalSize[]
193540 ** variables in the "averages" record on disk.
193541 **
193542 ** Return SQLITE_OK if successful, or an SQLite error code if an error
193543 ** occurs.
193544 */
193545 static int fts5StorageSaveTotals(Fts5Storage *p){
193546  int nCol = p->pConfig->nCol;
193547  int i;
193548  Fts5Buffer buf;
193549  int rc = SQLITE_OK;
193550  memset(&buf, 0, sizeof(buf));
193551 
193552  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->nTotalRow);
193553  for(i=0; i<nCol; i++){
193554  sqlite3Fts5BufferAppendVarint(&rc, &buf, p->aTotalSize[i]);
193555  }
193556  if( rc==SQLITE_OK ){
193557  rc = sqlite3Fts5IndexSetAverages(p->pIndex, buf.p, buf.n);
193558  }
193559  sqlite3_free(buf.p);
193560 
193561  return rc;
193562 }
193563 
193564 /*
193565 ** Remove a row from the FTS table.
193566 */
193567 static int sqlite3Fts5StorageDelete(Fts5Storage *p, i64 iDel, sqlite3_value **apVal){
193568  Fts5Config *pConfig = p->pConfig;
193569  int rc;
193570  sqlite3_stmt *pDel = 0;
193571 
193572  assert( pConfig->eContent!=FTS5_CONTENT_NORMAL || apVal==0 );
193573  rc = fts5StorageLoadTotals(p, 1);
193574 
193575  /* Delete the index records */
193576  if( rc==SQLITE_OK ){
193577  rc = fts5StorageDeleteFromIndex(p, iDel, apVal);
193578  }
193579 
193580  /* Delete the %_docsize record */
193581  if( rc==SQLITE_OK && pConfig->bColumnsize ){
193582  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_DOCSIZE, &pDel, 0);
193583  if( rc==SQLITE_OK ){
193584  sqlite3_bind_int64(pDel, 1, iDel);
193585  sqlite3_step(pDel);
193586  rc = sqlite3_reset(pDel);
193587  }
193588  }
193589 
193590  /* Delete the %_content record */
193591  if( pConfig->eContent==FTS5_CONTENT_NORMAL ){
193592  if( rc==SQLITE_OK ){
193593  rc = fts5StorageGetStmt(p, FTS5_STMT_DELETE_CONTENT, &pDel, 0);
193594  }
193595  if( rc==SQLITE_OK ){
193596  sqlite3_bind_int64(pDel, 1, iDel);
193597  sqlite3_step(pDel);
193598  rc = sqlite3_reset(pDel);
193599  }
193600  }
193601 
193602  /* Write the averages record */
193603  if( rc==SQLITE_OK ){
193604  rc = fts5StorageSaveTotals(p);
193605  }
193606 
193607  return rc;
193608 }
193609 
193610 /*
193611 ** Delete all entries in the FTS5 index.
193612 */
193613 static int sqlite3Fts5StorageDeleteAll(Fts5Storage *p){
193614  Fts5Config *pConfig = p->pConfig;
193615  int rc;
193616 
193617  /* Delete the contents of the %_data and %_docsize tables. */
193618  rc = fts5ExecPrintf(pConfig->db, 0,
193619  "DELETE FROM %Q.'%q_data';"
193620  "DELETE FROM %Q.'%q_idx';",
193621  pConfig->zDb, pConfig->zName,
193622  pConfig->zDb, pConfig->zName
193623  );
193624  if( rc==SQLITE_OK && pConfig->bColumnsize ){
193625  rc = fts5ExecPrintf(pConfig->db, 0,
193626  "DELETE FROM %Q.'%q_docsize';",
193627  pConfig->zDb, pConfig->zName
193628  );
193629  }
193630 
193631  /* Reinitialize the %_data table. This call creates the initial structure
193632  ** and averages records. */
193633  if( rc==SQLITE_OK ){
193634  rc = sqlite3Fts5IndexReinit(p->pIndex);
193635  }
193636  if( rc==SQLITE_OK ){
193637  rc = sqlite3Fts5StorageConfigValue(p, "version", 0, FTS5_CURRENT_VERSION);
193638  }
193639  return rc;
193640 }
193641 
193642 static int sqlite3Fts5StorageRebuild(Fts5Storage *p){
193643  Fts5Buffer buf = {0,0,0};
193644  Fts5Config *pConfig = p->pConfig;
193645  sqlite3_stmt *pScan = 0;
193646  Fts5InsertCtx ctx;
193647  int rc;
193648 
193649  memset(&ctx, 0, sizeof(Fts5InsertCtx));
193650  ctx.pStorage = p;
193651  rc = sqlite3Fts5StorageDeleteAll(p);
193652  if( rc==SQLITE_OK ){
193653  rc = fts5StorageLoadTotals(p, 1);
193654  }
193655 
193656  if( rc==SQLITE_OK ){
193657  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
193658  }
193659 
193660  while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pScan) ){
193661  i64 iRowid = sqlite3_column_int64(pScan, 0);
193662 
193663  sqlite3Fts5BufferZero(&buf);
193664  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
193665  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
193666  ctx.szCol = 0;
193667  if( pConfig->abUnindexed[ctx.iCol]==0 ){
193668  rc = sqlite3Fts5Tokenize(pConfig,
193670  (const char*)sqlite3_column_text(pScan, ctx.iCol+1),
193671  sqlite3_column_bytes(pScan, ctx.iCol+1),
193672  (void*)&ctx,
193673  fts5StorageInsertCallback
193674  );
193675  }
193676  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
193677  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
193678  }
193679  p->nTotalRow++;
193680 
193681  if( rc==SQLITE_OK ){
193682  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
193683  }
193684  }
193685  sqlite3_free(buf.p);
193686 
193687  /* Write the averages record */
193688  if( rc==SQLITE_OK ){
193689  rc = fts5StorageSaveTotals(p);
193690  }
193691  return rc;
193692 }
193693 
193694 static int sqlite3Fts5StorageOptimize(Fts5Storage *p){
193695  return sqlite3Fts5IndexOptimize(p->pIndex);
193696 }
193697 
193698 static int sqlite3Fts5StorageMerge(Fts5Storage *p, int nMerge){
193699  return sqlite3Fts5IndexMerge(p->pIndex, nMerge);
193700 }
193701 
193702 static int sqlite3Fts5StorageReset(Fts5Storage *p){
193703  return sqlite3Fts5IndexReset(p->pIndex);
193704 }
193705 
193706 /*
193707 ** Allocate a new rowid. This is used for "external content" tables when
193708 ** a NULL value is inserted into the rowid column. The new rowid is allocated
193709 ** by inserting a dummy row into the %_docsize table. The dummy will be
193710 ** overwritten later.
193711 **
193712 ** If the %_docsize table does not exist, SQLITE_MISMATCH is returned. In
193713 ** this case the user is required to provide a rowid explicitly.
193714 */
193715 static int fts5StorageNewRowid(Fts5Storage *p, i64 *piRowid){
193716  int rc = SQLITE_MISMATCH;
193717  if( p->pConfig->bColumnsize ){
193718  sqlite3_stmt *pReplace = 0;
193719  rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_DOCSIZE, &pReplace, 0);
193720  if( rc==SQLITE_OK ){
193721  sqlite3_bind_null(pReplace, 1);
193722  sqlite3_bind_null(pReplace, 2);
193723  sqlite3_step(pReplace);
193724  rc = sqlite3_reset(pReplace);
193725  }
193726  if( rc==SQLITE_OK ){
193727  *piRowid = sqlite3_last_insert_rowid(p->pConfig->db);
193728  }
193729  }
193730  return rc;
193731 }
193732 
193733 /*
193734 ** Insert a new row into the FTS content table.
193735 */
193736 static int sqlite3Fts5StorageContentInsert(
193737  Fts5Storage *p,
193738  sqlite3_value **apVal,
193739  i64 *piRowid
193740 ){
193741  Fts5Config *pConfig = p->pConfig;
193742  int rc = SQLITE_OK;
193743 
193744  /* Insert the new row into the %_content table. */
193745  if( pConfig->eContent!=FTS5_CONTENT_NORMAL ){
193746  if( sqlite3_value_type(apVal[1])==SQLITE_INTEGER ){
193747  *piRowid = sqlite3_value_int64(apVal[1]);
193748  }else{
193749  rc = fts5StorageNewRowid(p, piRowid);
193750  }
193751  }else{
193752  sqlite3_stmt *pInsert = 0; /* Statement to write %_content table */
193753  int i; /* Counter variable */
193754  rc = fts5StorageGetStmt(p, FTS5_STMT_INSERT_CONTENT, &pInsert, 0);
193755  for(i=1; rc==SQLITE_OK && i<=pConfig->nCol+1; i++){
193756  rc = sqlite3_bind_value(pInsert, i, apVal[i]);
193757  }
193758  if( rc==SQLITE_OK ){
193759  sqlite3_step(pInsert);
193760  rc = sqlite3_reset(pInsert);
193761  }
193762  *piRowid = sqlite3_last_insert_rowid(pConfig->db);
193763  }
193764 
193765  return rc;
193766 }
193767 
193768 /*
193769 ** Insert new entries into the FTS index and %_docsize table.
193770 */
193771 static int sqlite3Fts5StorageIndexInsert(
193772  Fts5Storage *p,
193773  sqlite3_value **apVal,
193774  i64 iRowid
193775 ){
193776  Fts5Config *pConfig = p->pConfig;
193777  int rc = SQLITE_OK; /* Return code */
193778  Fts5InsertCtx ctx; /* Tokenization callback context object */
193779  Fts5Buffer buf; /* Buffer used to build up %_docsize blob */
193780 
193781  memset(&buf, 0, sizeof(Fts5Buffer));
193782  ctx.pStorage = p;
193783  rc = fts5StorageLoadTotals(p, 1);
193784 
193785  if( rc==SQLITE_OK ){
193786  rc = sqlite3Fts5IndexBeginWrite(p->pIndex, 0, iRowid);
193787  }
193788  for(ctx.iCol=0; rc==SQLITE_OK && ctx.iCol<pConfig->nCol; ctx.iCol++){
193789  ctx.szCol = 0;
193790  if( pConfig->abUnindexed[ctx.iCol]==0 ){
193791  rc = sqlite3Fts5Tokenize(pConfig,
193793  (const char*)sqlite3_value_text(apVal[ctx.iCol+2]),
193794  sqlite3_value_bytes(apVal[ctx.iCol+2]),
193795  (void*)&ctx,
193796  fts5StorageInsertCallback
193797  );
193798  }
193799  sqlite3Fts5BufferAppendVarint(&rc, &buf, ctx.szCol);
193800  p->aTotalSize[ctx.iCol] += (i64)ctx.szCol;
193801  }
193802  p->nTotalRow++;
193803 
193804  /* Write the %_docsize record */
193805  if( rc==SQLITE_OK ){
193806  rc = fts5StorageInsertDocsize(p, iRowid, &buf);
193807  }
193808  sqlite3_free(buf.p);
193809 
193810  /* Write the averages record */
193811  if( rc==SQLITE_OK ){
193812  rc = fts5StorageSaveTotals(p);
193813  }
193814 
193815  return rc;
193816 }
193817 
193818 static int fts5StorageCount(Fts5Storage *p, const char *zSuffix, i64 *pnRow){
193819  Fts5Config *pConfig = p->pConfig;
193820  char *zSql;
193821  int rc;
193822 
193823  zSql = sqlite3_mprintf("SELECT count(*) FROM %Q.'%q_%s'",
193824  pConfig->zDb, pConfig->zName, zSuffix
193825  );
193826  if( zSql==0 ){
193827  rc = SQLITE_NOMEM;
193828  }else{
193829  sqlite3_stmt *pCnt = 0;
193830  rc = sqlite3_prepare_v2(pConfig->db, zSql, -1, &pCnt, 0);
193831  if( rc==SQLITE_OK ){
193832  if( SQLITE_ROW==sqlite3_step(pCnt) ){
193833  *pnRow = sqlite3_column_int64(pCnt, 0);
193834  }
193835  rc = sqlite3_finalize(pCnt);
193836  }
193837  }
193838 
193839  sqlite3_free(zSql);
193840  return rc;
193841 }
193842 
193843 /*
193844 ** Context object used by sqlite3Fts5StorageIntegrity().
193845 */
193846 typedef struct Fts5IntegrityCtx Fts5IntegrityCtx;
193847 struct Fts5IntegrityCtx {
193848  i64 iRowid;
193849  int iCol;
193850  int szCol;
193851  u64 cksum;
193852  Fts5Termset *pTermset;
193853  Fts5Config *pConfig;
193854 };
193855 
193856 
193857 /*
193858 ** Tokenization callback used by integrity check.
193859 */
193860 static int fts5StorageIntegrityCallback(
193861  void *pContext, /* Pointer to Fts5IntegrityCtx object */
193862  int tflags,
193863  const char *pToken, /* Buffer containing token */
193864  int nToken, /* Size of token in bytes */
193865  int iUnused1, /* Start offset of token */
193866  int iUnused2 /* End offset of token */
193867 ){
193868  Fts5IntegrityCtx *pCtx = (Fts5IntegrityCtx*)pContext;
193869  Fts5Termset *pTermset = pCtx->pTermset;
193870  int bPresent;
193871  int ii;
193872  int rc = SQLITE_OK;
193873  int iPos;
193874  int iCol;
193875 
193876  UNUSED_PARAM2(iUnused1, iUnused2);
193877  if( nToken>FTS5_MAX_TOKEN_SIZE ) nToken = FTS5_MAX_TOKEN_SIZE;
193878 
193879  if( (tflags & FTS5_TOKEN_COLOCATED)==0 || pCtx->szCol==0 ){
193880  pCtx->szCol++;
193881  }
193882 
193883  switch( pCtx->pConfig->eDetail ){
193884  case FTS5_DETAIL_FULL:
193885  iPos = pCtx->szCol-1;
193886  iCol = pCtx->iCol;
193887  break;
193888 
193889  case FTS5_DETAIL_COLUMNS:
193890  iPos = pCtx->iCol;
193891  iCol = 0;
193892  break;
193893 
193894  default:
193895  assert( pCtx->pConfig->eDetail==FTS5_DETAIL_NONE );
193896  iPos = 0;
193897  iCol = 0;
193898  break;
193899  }
193900 
193901  rc = sqlite3Fts5TermsetAdd(pTermset, 0, pToken, nToken, &bPresent);
193902  if( rc==SQLITE_OK && bPresent==0 ){
193903  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
193904  pCtx->iRowid, iCol, iPos, 0, pToken, nToken
193905  );
193906  }
193907 
193908  for(ii=0; rc==SQLITE_OK && ii<pCtx->pConfig->nPrefix; ii++){
193909  const int nChar = pCtx->pConfig->aPrefix[ii];
193910  int nByte = sqlite3Fts5IndexCharlenToBytelen(pToken, nToken, nChar);
193911  if( nByte ){
193912  rc = sqlite3Fts5TermsetAdd(pTermset, ii+1, pToken, nByte, &bPresent);
193913  if( bPresent==0 ){
193914  pCtx->cksum ^= sqlite3Fts5IndexEntryCksum(
193915  pCtx->iRowid, iCol, iPos, ii+1, pToken, nByte
193916  );
193917  }
193918  }
193919  }
193920 
193921  return rc;
193922 }
193923 
193924 /*
193925 ** Check that the contents of the FTS index match that of the %_content
193926 ** table. Return SQLITE_OK if they do, or SQLITE_CORRUPT if not. Return
193927 ** some other SQLite error code if an error occurs while attempting to
193928 ** determine this.
193929 */
193930 static int sqlite3Fts5StorageIntegrity(Fts5Storage *p){
193931  Fts5Config *pConfig = p->pConfig;
193932  int rc; /* Return code */
193933  int *aColSize; /* Array of size pConfig->nCol */
193934  i64 *aTotalSize; /* Array of size pConfig->nCol */
193935  Fts5IntegrityCtx ctx;
193936  sqlite3_stmt *pScan;
193937 
193938  memset(&ctx, 0, sizeof(Fts5IntegrityCtx));
193939  ctx.pConfig = p->pConfig;
193940  aTotalSize = (i64*)sqlite3_malloc(pConfig->nCol * (sizeof(int)+sizeof(i64)));
193941  if( !aTotalSize ) return SQLITE_NOMEM;
193942  aColSize = (int*)&aTotalSize[pConfig->nCol];
193943  memset(aTotalSize, 0, sizeof(i64) * pConfig->nCol);
193944 
193945  /* Generate the expected index checksum based on the contents of the
193946  ** %_content table. This block stores the checksum in ctx.cksum. */
193947  rc = fts5StorageGetStmt(p, FTS5_STMT_SCAN, &pScan, 0);
193948  if( rc==SQLITE_OK ){
193949  int rc2;
193950  while( SQLITE_ROW==sqlite3_step(pScan) ){
193951  int i;
193952  ctx.iRowid = sqlite3_column_int64(pScan, 0);
193953  ctx.szCol = 0;
193954  if( pConfig->bColumnsize ){
193955  rc = sqlite3Fts5StorageDocsize(p, ctx.iRowid, aColSize);
193956  }
193957  if( rc==SQLITE_OK && pConfig->eDetail==FTS5_DETAIL_NONE ){
193958  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
193959  }
193960  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
193961  if( pConfig->abUnindexed[i] ) continue;
193962  ctx.iCol = i;
193963  ctx.szCol = 0;
193964  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193965  rc = sqlite3Fts5TermsetNew(&ctx.pTermset);
193966  }
193967  if( rc==SQLITE_OK ){
193968  rc = sqlite3Fts5Tokenize(pConfig,
193970  (const char*)sqlite3_column_text(pScan, i+1),
193971  sqlite3_column_bytes(pScan, i+1),
193972  (void*)&ctx,
193973  fts5StorageIntegrityCallback
193974  );
193975  }
193976  if( rc==SQLITE_OK && pConfig->bColumnsize && ctx.szCol!=aColSize[i] ){
193977  rc = FTS5_CORRUPT;
193978  }
193979  aTotalSize[i] += ctx.szCol;
193980  if( pConfig->eDetail==FTS5_DETAIL_COLUMNS ){
193981  sqlite3Fts5TermsetFree(ctx.pTermset);
193982  ctx.pTermset = 0;
193983  }
193984  }
193985  sqlite3Fts5TermsetFree(ctx.pTermset);
193986  ctx.pTermset = 0;
193987 
193988  if( rc!=SQLITE_OK ) break;
193989  }
193990  rc2 = sqlite3_reset(pScan);
193991  if( rc==SQLITE_OK ) rc = rc2;
193992  }
193993 
193994  /* Test that the "totals" (sometimes called "averages") record looks Ok */
193995  if( rc==SQLITE_OK ){
193996  int i;
193997  rc = fts5StorageLoadTotals(p, 0);
193998  for(i=0; rc==SQLITE_OK && i<pConfig->nCol; i++){
193999  if( p->aTotalSize[i]!=aTotalSize[i] ) rc = FTS5_CORRUPT;
194000  }
194001  }
194002 
194003  /* Check that the %_docsize and %_content tables contain the expected
194004  ** number of rows. */
194005  if( rc==SQLITE_OK && pConfig->eContent==FTS5_CONTENT_NORMAL ){
194006  i64 nRow = 0;
194007  rc = fts5StorageCount(p, "content", &nRow);
194008  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
194009  }
194010  if( rc==SQLITE_OK && pConfig->bColumnsize ){
194011  i64 nRow = 0;
194012  rc = fts5StorageCount(p, "docsize", &nRow);
194013  if( rc==SQLITE_OK && nRow!=p->nTotalRow ) rc = FTS5_CORRUPT;
194014  }
194015 
194016  /* Pass the expected checksum down to the FTS index module. It will
194017  ** verify, amongst other things, that it matches the checksum generated by
194018  ** inspecting the index itself. */
194019  if( rc==SQLITE_OK ){
194020  rc = sqlite3Fts5IndexIntegrityCheck(p->pIndex, ctx.cksum);
194021  }
194022 
194023  sqlite3_free(aTotalSize);
194024  return rc;
194025 }
194026 
194027 /*
194028 ** Obtain an SQLite statement handle that may be used to read data from the
194029 ** %_content table.
194030 */
194031 static int sqlite3Fts5StorageStmt(
194032  Fts5Storage *p,
194033  int eStmt,
194034  sqlite3_stmt **pp,
194035  char **pzErrMsg
194036 ){
194037  int rc;
194038  assert( eStmt==FTS5_STMT_SCAN_ASC
194039  || eStmt==FTS5_STMT_SCAN_DESC
194040  || eStmt==FTS5_STMT_LOOKUP
194041  );
194042  rc = fts5StorageGetStmt(p, eStmt, pp, pzErrMsg);
194043  if( rc==SQLITE_OK ){
194044  assert( p->aStmt[eStmt]==*pp );
194045  p->aStmt[eStmt] = 0;
194046  }
194047  return rc;
194048 }
194049 
194050 /*
194051 ** Release an SQLite statement handle obtained via an earlier call to
194052 ** sqlite3Fts5StorageStmt(). The eStmt parameter passed to this function
194053 ** must match that passed to the sqlite3Fts5StorageStmt() call.
194054 */
194055 static void sqlite3Fts5StorageStmtRelease(
194056  Fts5Storage *p,
194057  int eStmt,
194058  sqlite3_stmt *pStmt
194059 ){
194060  assert( eStmt==FTS5_STMT_SCAN_ASC
194061  || eStmt==FTS5_STMT_SCAN_DESC
194062  || eStmt==FTS5_STMT_LOOKUP
194063  );
194064  if( p->aStmt[eStmt]==0 ){
194065  sqlite3_reset(pStmt);
194066  p->aStmt[eStmt] = pStmt;
194067  }else{
194068  sqlite3_finalize(pStmt);
194069  }
194070 }
194071 
194072 static int fts5StorageDecodeSizeArray(
194073  int *aCol, int nCol, /* Array to populate */
194074  const u8 *aBlob, int nBlob /* Record to read varints from */
194075 ){
194076  int i;
194077  int iOff = 0;
194078  for(i=0; i<nCol; i++){
194079  if( iOff>=nBlob ) return 1;
194080  iOff += fts5GetVarint32(&aBlob[iOff], aCol[i]);
194081  }
194082  return (iOff!=nBlob);
194083 }
194084 
194085 /*
194086 ** Argument aCol points to an array of integers containing one entry for
194087 ** each table column. This function reads the %_docsize record for the
194088 ** specified rowid and populates aCol[] with the results.
194089 **
194090 ** An SQLite error code is returned if an error occurs, or SQLITE_OK
194091 ** otherwise.
194092 */
194093 static int sqlite3Fts5StorageDocsize(Fts5Storage *p, i64 iRowid, int *aCol){
194094  int nCol = p->pConfig->nCol; /* Number of user columns in table */
194095  sqlite3_stmt *pLookup = 0; /* Statement to query %_docsize */
194096  int rc; /* Return Code */
194097 
194098  assert( p->pConfig->bColumnsize );
194099  rc = fts5StorageGetStmt(p, FTS5_STMT_LOOKUP_DOCSIZE, &pLookup, 0);
194100  if( rc==SQLITE_OK ){
194101  int bCorrupt = 1;
194102  sqlite3_bind_int64(pLookup, 1, iRowid);
194103  if( SQLITE_ROW==sqlite3_step(pLookup) ){
194104  const u8 *aBlob = sqlite3_column_blob(pLookup, 0);
194105  int nBlob = sqlite3_column_bytes(pLookup, 0);
194106  if( 0==fts5StorageDecodeSizeArray(aCol, nCol, aBlob, nBlob) ){
194107  bCorrupt = 0;
194108  }
194109  }
194110  rc = sqlite3_reset(pLookup);
194111  if( bCorrupt && rc==SQLITE_OK ){
194112  rc = FTS5_CORRUPT;
194113  }
194114  }
194115 
194116  return rc;
194117 }
194118 
194119 static int sqlite3Fts5StorageSize(Fts5Storage *p, int iCol, i64 *pnToken){
194120  int rc = fts5StorageLoadTotals(p, 0);
194121  if( rc==SQLITE_OK ){
194122  *pnToken = 0;
194123  if( iCol<0 ){
194124  int i;
194125  for(i=0; i<p->pConfig->nCol; i++){
194126  *pnToken += p->aTotalSize[i];
194127  }
194128  }else if( iCol<p->pConfig->nCol ){
194129  *pnToken = p->aTotalSize[iCol];
194130  }else{
194131  rc = SQLITE_RANGE;
194132  }
194133  }
194134  return rc;
194135 }
194136 
194137 static int sqlite3Fts5StorageRowCount(Fts5Storage *p, i64 *pnRow){
194138  int rc = fts5StorageLoadTotals(p, 0);
194139  if( rc==SQLITE_OK ){
194140  *pnRow = p->nTotalRow;
194141  }
194142  return rc;
194143 }
194144 
194145 /*
194146 ** Flush any data currently held in-memory to disk.
194147 */
194148 static int sqlite3Fts5StorageSync(Fts5Storage *p, int bCommit){
194149  if( bCommit && p->bTotalsValid ){
194150  int rc = fts5StorageSaveTotals(p);
194151  p->bTotalsValid = 0;
194152  if( rc!=SQLITE_OK ) return rc;
194153  }
194154  return sqlite3Fts5IndexSync(p->pIndex, bCommit);
194155 }
194156 
194157 static int sqlite3Fts5StorageRollback(Fts5Storage *p){
194158  p->bTotalsValid = 0;
194159  return sqlite3Fts5IndexRollback(p->pIndex);
194160 }
194161 
194162 static int sqlite3Fts5StorageConfigValue(
194163  Fts5Storage *p,
194164  const char *z,
194165  sqlite3_value *pVal,
194166  int iVal
194167 ){
194168  sqlite3_stmt *pReplace = 0;
194169  int rc = fts5StorageGetStmt(p, FTS5_STMT_REPLACE_CONFIG, &pReplace, 0);
194170  if( rc==SQLITE_OK ){
194171  sqlite3_bind_text(pReplace, 1, z, -1, SQLITE_STATIC);
194172  if( pVal ){
194173  sqlite3_bind_value(pReplace, 2, pVal);
194174  }else{
194175  sqlite3_bind_int(pReplace, 2, iVal);
194176  }
194177  sqlite3_step(pReplace);
194178  rc = sqlite3_reset(pReplace);
194179  }
194180  if( rc==SQLITE_OK && pVal ){
194181  int iNew = p->pConfig->iCookie + 1;
194182  rc = sqlite3Fts5IndexSetCookie(p->pIndex, iNew);
194183  if( rc==SQLITE_OK ){
194184  p->pConfig->iCookie = iNew;
194185  }
194186  }
194187  return rc;
194188 }
194189 
194190 /*
194191 ** 2014 May 31
194192 **
194193 ** The author disclaims copyright to this source code. In place of
194194 ** a legal notice, here is a blessing:
194195 **
194196 ** May you do good and not evil.
194197 ** May you find forgiveness for yourself and forgive others.
194198 ** May you share freely, never taking more than you give.
194199 **
194200 ******************************************************************************
194201 */
194202 
194203 
194204 /* #include "fts5Int.h" */
194205 
194206 /**************************************************************************
194207 ** Start of ascii tokenizer implementation.
194208 */
194209 
194210 /*
194211 ** For tokenizers with no "unicode" modifier, the set of token characters
194212 ** is the same as the set of ASCII range alphanumeric characters.
194213 */
194214 static unsigned char aAsciiTokenChar[128] = {
194215  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x00..0x0F */
194216  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x10..0x1F */
194217  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x20..0x2F */
194218  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 0x30..0x3F */
194219  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x40..0x4F */
194220  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x50..0x5F */
194221  0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 0x60..0x6F */
194222  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 0x70..0x7F */
194223 };
194224 
194225 typedef struct AsciiTokenizer AsciiTokenizer;
194226 struct AsciiTokenizer {
194227  unsigned char aTokenChar[128];
194228 };
194229 
194230 static void fts5AsciiAddExceptions(
194231  AsciiTokenizer *p,
194232  const char *zArg,
194233  int bTokenChars
194234 ){
194235  int i;
194236  for(i=0; zArg[i]; i++){
194237  if( (zArg[i] & 0x80)==0 ){
194238  p->aTokenChar[(int)zArg[i]] = (unsigned char)bTokenChars;
194239  }
194240  }
194241 }
194242 
194243 /*
194244 ** Delete a "ascii" tokenizer.
194245 */
194246 static void fts5AsciiDelete(Fts5Tokenizer *p){
194247  sqlite3_free(p);
194248 }
194249 
194250 /*
194251 ** Create an "ascii" tokenizer.
194252 */
194253 static int fts5AsciiCreate(
194254  void *pUnused,
194255  const char **azArg, int nArg,
194256  Fts5Tokenizer **ppOut
194257 ){
194258  int rc = SQLITE_OK;
194259  AsciiTokenizer *p = 0;
194260  UNUSED_PARAM(pUnused);
194261  if( nArg%2 ){
194262  rc = SQLITE_ERROR;
194263  }else{
194264  p = sqlite3_malloc(sizeof(AsciiTokenizer));
194265  if( p==0 ){
194266  rc = SQLITE_NOMEM;
194267  }else{
194268  int i;
194269  memset(p, 0, sizeof(AsciiTokenizer));
194270  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
194271  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
194272  const char *zArg = azArg[i+1];
194273  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
194274  fts5AsciiAddExceptions(p, zArg, 1);
194275  }else
194276  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
194277  fts5AsciiAddExceptions(p, zArg, 0);
194278  }else{
194279  rc = SQLITE_ERROR;
194280  }
194281  }
194282  if( rc!=SQLITE_OK ){
194283  fts5AsciiDelete((Fts5Tokenizer*)p);
194284  p = 0;
194285  }
194286  }
194287  }
194288 
194289  *ppOut = (Fts5Tokenizer*)p;
194290  return rc;
194291 }
194292 
194293 
194294 static void asciiFold(char *aOut, const char *aIn, int nByte){
194295  int i;
194296  for(i=0; i<nByte; i++){
194297  char c = aIn[i];
194298  if( c>='A' && c<='Z' ) c += 32;
194299  aOut[i] = c;
194300  }
194301 }
194302 
194303 /*
194304 ** Tokenize some text using the ascii tokenizer.
194305 */
194306 static int fts5AsciiTokenize(
194307  Fts5Tokenizer *pTokenizer,
194308  void *pCtx,
194309  int iUnused,
194310  const char *pText, int nText,
194311  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
194312 ){
194313  AsciiTokenizer *p = (AsciiTokenizer*)pTokenizer;
194314  int rc = SQLITE_OK;
194315  int ie;
194316  int is = 0;
194317 
194318  char aFold[64];
194319  int nFold = sizeof(aFold);
194320  char *pFold = aFold;
194321  unsigned char *a = p->aTokenChar;
194322 
194323  UNUSED_PARAM(iUnused);
194324 
194325  while( is<nText && rc==SQLITE_OK ){
194326  int nByte;
194327 
194328  /* Skip any leading divider characters. */
194329  while( is<nText && ((pText[is]&0x80)==0 && a[(int)pText[is]]==0) ){
194330  is++;
194331  }
194332  if( is==nText ) break;
194333 
194334  /* Count the token characters */
194335  ie = is+1;
194336  while( ie<nText && ((pText[ie]&0x80) || a[(int)pText[ie]] ) ){
194337  ie++;
194338  }
194339 
194340  /* Fold to lower case */
194341  nByte = ie-is;
194342  if( nByte>nFold ){
194343  if( pFold!=aFold ) sqlite3_free(pFold);
194344  pFold = sqlite3_malloc(nByte*2);
194345  if( pFold==0 ){
194346  rc = SQLITE_NOMEM;
194347  break;
194348  }
194349  nFold = nByte*2;
194350  }
194351  asciiFold(pFold, &pText[is], nByte);
194352 
194353  /* Invoke the token callback */
194354  rc = xToken(pCtx, 0, pFold, nByte, is, ie);
194355  is = ie+1;
194356  }
194357 
194358  if( pFold!=aFold ) sqlite3_free(pFold);
194359  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
194360  return rc;
194361 }
194362 
194363 /**************************************************************************
194364 ** Start of unicode61 tokenizer implementation.
194365 */
194366 
194367 
194368 /*
194369 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
194370 ** from the sqlite3 source file utf.c. If this file is compiled as part
194371 ** of the amalgamation, they are not required.
194372 */
194373 #ifndef SQLITE_AMALGAMATION
194374 
194375 static const unsigned char sqlite3Utf8Trans1[] = {
194376  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
194377  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
194378  0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
194379  0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
194380  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
194381  0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
194382  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
194383  0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
194384 };
194385 
194386 #define READ_UTF8(zIn, zTerm, c) \
194387  c = *(zIn++); \
194388  if( c>=0xc0 ){ \
194389  c = sqlite3Utf8Trans1[c-0xc0]; \
194390  while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
194391  c = (c<<6) + (0x3f & *(zIn++)); \
194392  } \
194393  if( c<0x80 \
194394  || (c&0xFFFFF800)==0xD800 \
194395  || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
194396  }
194397 
194398 
194399 #define WRITE_UTF8(zOut, c) { \
194400  if( c<0x00080 ){ \
194401  *zOut++ = (unsigned char)(c&0xFF); \
194402  } \
194403  else if( c<0x00800 ){ \
194404  *zOut++ = 0xC0 + (unsigned char)((c>>6)&0x1F); \
194405  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
194406  } \
194407  else if( c<0x10000 ){ \
194408  *zOut++ = 0xE0 + (unsigned char)((c>>12)&0x0F); \
194409  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
194410  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
194411  }else{ \
194412  *zOut++ = 0xF0 + (unsigned char)((c>>18) & 0x07); \
194413  *zOut++ = 0x80 + (unsigned char)((c>>12) & 0x3F); \
194414  *zOut++ = 0x80 + (unsigned char)((c>>6) & 0x3F); \
194415  *zOut++ = 0x80 + (unsigned char)(c & 0x3F); \
194416  } \
194417 }
194418 
194419 #endif /* ifndef SQLITE_AMALGAMATION */
194420 
194421 typedef struct Unicode61Tokenizer Unicode61Tokenizer;
194422 struct Unicode61Tokenizer {
194423  unsigned char aTokenChar[128]; /* ASCII range token characters */
194424  char *aFold; /* Buffer to fold text into */
194425  int nFold; /* Size of aFold[] in bytes */
194426  int bRemoveDiacritic; /* True if remove_diacritics=1 is set */
194427  int nException;
194428  int *aiException;
194429 };
194430 
194431 static int fts5UnicodeAddExceptions(
194432  Unicode61Tokenizer *p, /* Tokenizer object */
194433  const char *z, /* Characters to treat as exceptions */
194434  int bTokenChars /* 1 for 'tokenchars', 0 for 'separators' */
194435 ){
194436  int rc = SQLITE_OK;
194437  int n = (int)strlen(z);
194438  int *aNew;
194439 
194440  if( n>0 ){
194441  aNew = (int*)sqlite3_realloc(p->aiException, (n+p->nException)*sizeof(int));
194442  if( aNew ){
194443  int nNew = p->nException;
194444  const unsigned char *zCsr = (const unsigned char*)z;
194445  const unsigned char *zTerm = (const unsigned char*)&z[n];
194446  while( zCsr<zTerm ){
194447  int iCode;
194448  int bToken;
194449  READ_UTF8(zCsr, zTerm, iCode);
194450  if( iCode<128 ){
194451  p->aTokenChar[iCode] = (unsigned char)bTokenChars;
194452  }else{
194453  bToken = sqlite3Fts5UnicodeIsalnum(iCode);
194454  assert( (bToken==0 || bToken==1) );
194455  assert( (bTokenChars==0 || bTokenChars==1) );
194456  if( bToken!=bTokenChars && sqlite3Fts5UnicodeIsdiacritic(iCode)==0 ){
194457  int i;
194458  for(i=0; i<nNew; i++){
194459  if( aNew[i]>iCode ) break;
194460  }
194461  memmove(&aNew[i+1], &aNew[i], (nNew-i)*sizeof(int));
194462  aNew[i] = iCode;
194463  nNew++;
194464  }
194465  }
194466  }
194467  p->aiException = aNew;
194468  p->nException = nNew;
194469  }else{
194470  rc = SQLITE_NOMEM;
194471  }
194472  }
194473 
194474  return rc;
194475 }
194476 
194477 /*
194478 ** Return true if the p->aiException[] array contains the value iCode.
194479 */
194480 static int fts5UnicodeIsException(Unicode61Tokenizer *p, int iCode){
194481  if( p->nException>0 ){
194482  int *a = p->aiException;
194483  int iLo = 0;
194484  int iHi = p->nException-1;
194485 
194486  while( iHi>=iLo ){
194487  int iTest = (iHi + iLo) / 2;
194488  if( iCode==a[iTest] ){
194489  return 1;
194490  }else if( iCode>a[iTest] ){
194491  iLo = iTest+1;
194492  }else{
194493  iHi = iTest-1;
194494  }
194495  }
194496  }
194497 
194498  return 0;
194499 }
194500 
194501 /*
194502 ** Delete a "unicode61" tokenizer.
194503 */
194504 static void fts5UnicodeDelete(Fts5Tokenizer *pTok){
194505  if( pTok ){
194506  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTok;
194507  sqlite3_free(p->aiException);
194508  sqlite3_free(p->aFold);
194509  sqlite3_free(p);
194510  }
194511  return;
194512 }
194513 
194514 /*
194515 ** Create a "unicode61" tokenizer.
194516 */
194517 static int fts5UnicodeCreate(
194518  void *pUnused,
194519  const char **azArg, int nArg,
194520  Fts5Tokenizer **ppOut
194521 ){
194522  int rc = SQLITE_OK; /* Return code */
194523  Unicode61Tokenizer *p = 0; /* New tokenizer object */
194524 
194525  UNUSED_PARAM(pUnused);
194526 
194527  if( nArg%2 ){
194528  rc = SQLITE_ERROR;
194529  }else{
194530  p = (Unicode61Tokenizer*)sqlite3_malloc(sizeof(Unicode61Tokenizer));
194531  if( p ){
194532  int i;
194533  memset(p, 0, sizeof(Unicode61Tokenizer));
194534  memcpy(p->aTokenChar, aAsciiTokenChar, sizeof(aAsciiTokenChar));
194535  p->bRemoveDiacritic = 1;
194536  p->nFold = 64;
194537  p->aFold = sqlite3_malloc(p->nFold * sizeof(char));
194538  if( p->aFold==0 ){
194539  rc = SQLITE_NOMEM;
194540  }
194541  for(i=0; rc==SQLITE_OK && i<nArg; i+=2){
194542  const char *zArg = azArg[i+1];
194543  if( 0==sqlite3_stricmp(azArg[i], "remove_diacritics") ){
194544  if( (zArg[0]!='0' && zArg[0]!='1') || zArg[1] ){
194545  rc = SQLITE_ERROR;
194546  }
194547  p->bRemoveDiacritic = (zArg[0]=='1');
194548  }else
194549  if( 0==sqlite3_stricmp(azArg[i], "tokenchars") ){
194550  rc = fts5UnicodeAddExceptions(p, zArg, 1);
194551  }else
194552  if( 0==sqlite3_stricmp(azArg[i], "separators") ){
194553  rc = fts5UnicodeAddExceptions(p, zArg, 0);
194554  }else{
194555  rc = SQLITE_ERROR;
194556  }
194557  }
194558  }else{
194559  rc = SQLITE_NOMEM;
194560  }
194561  if( rc!=SQLITE_OK ){
194562  fts5UnicodeDelete((Fts5Tokenizer*)p);
194563  p = 0;
194564  }
194565  *ppOut = (Fts5Tokenizer*)p;
194566  }
194567  return rc;
194568 }
194569 
194570 /*
194571 ** Return true if, for the purposes of tokenizing with the tokenizer
194572 ** passed as the first argument, codepoint iCode is considered a token
194573 ** character (not a separator).
194574 */
194575 static int fts5UnicodeIsAlnum(Unicode61Tokenizer *p, int iCode){
194576  assert( (sqlite3Fts5UnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
194577  return sqlite3Fts5UnicodeIsalnum(iCode) ^ fts5UnicodeIsException(p, iCode);
194578 }
194579 
194580 static int fts5UnicodeTokenize(
194581  Fts5Tokenizer *pTokenizer,
194582  void *pCtx,
194583  int iUnused,
194584  const char *pText, int nText,
194585  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
194586 ){
194587  Unicode61Tokenizer *p = (Unicode61Tokenizer*)pTokenizer;
194588  int rc = SQLITE_OK;
194589  unsigned char *a = p->aTokenChar;
194590 
194591  unsigned char *zTerm = (unsigned char*)&pText[nText];
194592  unsigned char *zCsr = (unsigned char *)pText;
194593 
194594  /* Output buffer */
194595  char *aFold = p->aFold;
194596  int nFold = p->nFold;
194597  const char *pEnd = &aFold[nFold-6];
194598 
194599  UNUSED_PARAM(iUnused);
194600 
194601  /* Each iteration of this loop gobbles up a contiguous run of separators,
194602  ** then the next token. */
194603  while( rc==SQLITE_OK ){
194604  int iCode; /* non-ASCII codepoint read from input */
194605  char *zOut = aFold;
194606  int is;
194607  int ie;
194608 
194609  /* Skip any separator characters. */
194610  while( 1 ){
194611  if( zCsr>=zTerm ) goto tokenize_done;
194612  if( *zCsr & 0x80 ) {
194613  /* A character outside of the ascii range. Skip past it if it is
194614  ** a separator character. Or break out of the loop if it is not. */
194615  is = zCsr - (unsigned char*)pText;
194616  READ_UTF8(zCsr, zTerm, iCode);
194617  if( fts5UnicodeIsAlnum(p, iCode) ){
194618  goto non_ascii_tokenchar;
194619  }
194620  }else{
194621  if( a[*zCsr] ){
194622  is = zCsr - (unsigned char*)pText;
194623  goto ascii_tokenchar;
194624  }
194625  zCsr++;
194626  }
194627  }
194628 
194629  /* Run through the tokenchars. Fold them into the output buffer along
194630  ** the way. */
194631  while( zCsr<zTerm ){
194632 
194633  /* Grow the output buffer so that there is sufficient space to fit the
194634  ** largest possible utf-8 character. */
194635  if( zOut>pEnd ){
194636  aFold = sqlite3_malloc(nFold*2);
194637  if( aFold==0 ){
194638  rc = SQLITE_NOMEM;
194639  goto tokenize_done;
194640  }
194641  zOut = &aFold[zOut - p->aFold];
194642  memcpy(aFold, p->aFold, nFold);
194643  sqlite3_free(p->aFold);
194644  p->aFold = aFold;
194645  p->nFold = nFold = nFold*2;
194646  pEnd = &aFold[nFold-6];
194647  }
194648 
194649  if( *zCsr & 0x80 ){
194650  /* An non-ascii-range character. Fold it into the output buffer if
194651  ** it is a token character, or break out of the loop if it is not. */
194652  READ_UTF8(zCsr, zTerm, iCode);
194653  if( fts5UnicodeIsAlnum(p,iCode)||sqlite3Fts5UnicodeIsdiacritic(iCode) ){
194654  non_ascii_tokenchar:
194655  iCode = sqlite3Fts5UnicodeFold(iCode, p->bRemoveDiacritic);
194656  if( iCode ) WRITE_UTF8(zOut, iCode);
194657  }else{
194658  break;
194659  }
194660  }else if( a[*zCsr]==0 ){
194661  /* An ascii-range separator character. End of token. */
194662  break;
194663  }else{
194664  ascii_tokenchar:
194665  if( *zCsr>='A' && *zCsr<='Z' ){
194666  *zOut++ = *zCsr + 32;
194667  }else{
194668  *zOut++ = *zCsr;
194669  }
194670  zCsr++;
194671  }
194672  ie = zCsr - (unsigned char*)pText;
194673  }
194674 
194675  /* Invoke the token callback */
194676  rc = xToken(pCtx, 0, aFold, zOut-aFold, is, ie);
194677  }
194678 
194679  tokenize_done:
194680  if( rc==SQLITE_DONE ) rc = SQLITE_OK;
194681  return rc;
194682 }
194683 
194684 /**************************************************************************
194685 ** Start of porter stemmer implementation.
194686 */
194687 
194688 /* Any tokens larger than this (in bytes) are passed through without
194689 ** stemming. */
194690 #define FTS5_PORTER_MAX_TOKEN 64
194691 
194692 typedef struct PorterTokenizer PorterTokenizer;
194693 struct PorterTokenizer {
194694  fts5_tokenizer tokenizer; /* Parent tokenizer module */
194695  Fts5Tokenizer *pTokenizer; /* Parent tokenizer instance */
194696  char aBuf[FTS5_PORTER_MAX_TOKEN + 64];
194697 };
194698 
194699 /*
194700 ** Delete a "porter" tokenizer.
194701 */
194702 static void fts5PorterDelete(Fts5Tokenizer *pTok){
194703  if( pTok ){
194704  PorterTokenizer *p = (PorterTokenizer*)pTok;
194705  if( p->pTokenizer ){
194706  p->tokenizer.xDelete(p->pTokenizer);
194707  }
194708  sqlite3_free(p);
194709  }
194710 }
194711 
194712 /*
194713 ** Create a "porter" tokenizer.
194714 */
194715 static int fts5PorterCreate(
194716  void *pCtx,
194717  const char **azArg, int nArg,
194718  Fts5Tokenizer **ppOut
194719 ){
194720  fts5_api *pApi = (fts5_api*)pCtx;
194721  int rc = SQLITE_OK;
194722  PorterTokenizer *pRet;
194723  void *pUserdata = 0;
194724  const char *zBase = "unicode61";
194725 
194726  if( nArg>0 ){
194727  zBase = azArg[0];
194728  }
194729 
194730  pRet = (PorterTokenizer*)sqlite3_malloc(sizeof(PorterTokenizer));
194731  if( pRet ){
194732  memset(pRet, 0, sizeof(PorterTokenizer));
194733  rc = pApi->xFindTokenizer(pApi, zBase, &pUserdata, &pRet->tokenizer);
194734  }else{
194735  rc = SQLITE_NOMEM;
194736  }
194737  if( rc==SQLITE_OK ){
194738  int nArg2 = (nArg>0 ? nArg-1 : 0);
194739  const char **azArg2 = (nArg2 ? &azArg[1] : 0);
194740  rc = pRet->tokenizer.xCreate(pUserdata, azArg2, nArg2, &pRet->pTokenizer);
194741  }
194742 
194743  if( rc!=SQLITE_OK ){
194744  fts5PorterDelete((Fts5Tokenizer*)pRet);
194745  pRet = 0;
194746  }
194747  *ppOut = (Fts5Tokenizer*)pRet;
194748  return rc;
194749 }
194750 
194751 typedef struct PorterContext PorterContext;
194752 struct PorterContext {
194753  void *pCtx;
194754  int (*xToken)(void*, int, const char*, int, int, int);
194755  char *aBuf;
194756 };
194757 
194758 typedef struct PorterRule PorterRule;
194759 struct PorterRule {
194760  const char *zSuffix;
194761  int nSuffix;
194762  int (*xCond)(char *zStem, int nStem);
194763  const char *zOutput;
194764  int nOutput;
194765 };
194766 
194767 #if 0
194768 static int fts5PorterApply(char *aBuf, int *pnBuf, PorterRule *aRule){
194769  int ret = -1;
194770  int nBuf = *pnBuf;
194771  PorterRule *p;
194772 
194773  for(p=aRule; p->zSuffix; p++){
194774  assert( strlen(p->zSuffix)==p->nSuffix );
194775  assert( strlen(p->zOutput)==p->nOutput );
194776  if( nBuf<p->nSuffix ) continue;
194777  if( 0==memcmp(&aBuf[nBuf - p->nSuffix], p->zSuffix, p->nSuffix) ) break;
194778  }
194779 
194780  if( p->zSuffix ){
194781  int nStem = nBuf - p->nSuffix;
194782  if( p->xCond==0 || p->xCond(aBuf, nStem) ){
194783  memcpy(&aBuf[nStem], p->zOutput, p->nOutput);
194784  *pnBuf = nStem + p->nOutput;
194785  ret = p - aRule;
194786  }
194787  }
194788 
194789  return ret;
194790 }
194791 #endif
194792 
194793 static int fts5PorterIsVowel(char c, int bYIsVowel){
194794  return (
194795  c=='a' || c=='e' || c=='i' || c=='o' || c=='u' || (bYIsVowel && c=='y')
194796  );
194797 }
194798 
194799 static int fts5PorterGobbleVC(char *zStem, int nStem, int bPrevCons){
194800  int i;
194801  int bCons = bPrevCons;
194802 
194803  /* Scan for a vowel */
194804  for(i=0; i<nStem; i++){
194805  if( 0==(bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) break;
194806  }
194807 
194808  /* Scan for a consonent */
194809  for(i++; i<nStem; i++){
194810  if( (bCons = !fts5PorterIsVowel(zStem[i], bCons)) ) return i+1;
194811  }
194812  return 0;
194813 }
194814 
194815 /* porter rule condition: (m > 0) */
194816 static int fts5Porter_MGt0(char *zStem, int nStem){
194817  return !!fts5PorterGobbleVC(zStem, nStem, 0);
194818 }
194819 
194820 /* porter rule condition: (m > 1) */
194821 static int fts5Porter_MGt1(char *zStem, int nStem){
194822  int n;
194823  n = fts5PorterGobbleVC(zStem, nStem, 0);
194824  if( n && fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
194825  return 1;
194826  }
194827  return 0;
194828 }
194829 
194830 /* porter rule condition: (m = 1) */
194831 static int fts5Porter_MEq1(char *zStem, int nStem){
194832  int n;
194833  n = fts5PorterGobbleVC(zStem, nStem, 0);
194834  if( n && 0==fts5PorterGobbleVC(&zStem[n], nStem-n, 1) ){
194835  return 1;
194836  }
194837  return 0;
194838 }
194839 
194840 /* porter rule condition: (*o) */
194841 static int fts5Porter_Ostar(char *zStem, int nStem){
194842  if( zStem[nStem-1]=='w' || zStem[nStem-1]=='x' || zStem[nStem-1]=='y' ){
194843  return 0;
194844  }else{
194845  int i;
194846  int mask = 0;
194847  int bCons = 0;
194848  for(i=0; i<nStem; i++){
194849  bCons = !fts5PorterIsVowel(zStem[i], bCons);
194850  assert( bCons==0 || bCons==1 );
194851  mask = (mask << 1) + bCons;
194852  }
194853  return ((mask & 0x0007)==0x0005);
194854  }
194855 }
194856 
194857 /* porter rule condition: (m > 1 and (*S or *T)) */
194858 static int fts5Porter_MGt1_and_S_or_T(char *zStem, int nStem){
194859  assert( nStem>0 );
194860  return (zStem[nStem-1]=='s' || zStem[nStem-1]=='t')
194861  && fts5Porter_MGt1(zStem, nStem);
194862 }
194863 
194864 /* porter rule condition: (*v*) */
194865 static int fts5Porter_Vowel(char *zStem, int nStem){
194866  int i;
194867  for(i=0; i<nStem; i++){
194868  if( fts5PorterIsVowel(zStem[i], i>0) ){
194869  return 1;
194870  }
194871  }
194872  return 0;
194873 }
194874 
194875 
194876 /**************************************************************************
194877 ***************************************************************************
194878 ** GENERATED CODE STARTS HERE (mkportersteps.tcl)
194879 */
194880 
194881 static int fts5PorterStep4(char *aBuf, int *pnBuf){
194882  int ret = 0;
194883  int nBuf = *pnBuf;
194884  switch( aBuf[nBuf-2] ){
194885 
194886  case 'a':
194887  if( nBuf>2 && 0==memcmp("al", &aBuf[nBuf-2], 2) ){
194888  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
194889  *pnBuf = nBuf - 2;
194890  }
194891  }
194892  break;
194893 
194894  case 'c':
194895  if( nBuf>4 && 0==memcmp("ance", &aBuf[nBuf-4], 4) ){
194896  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
194897  *pnBuf = nBuf - 4;
194898  }
194899  }else if( nBuf>4 && 0==memcmp("ence", &aBuf[nBuf-4], 4) ){
194900  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
194901  *pnBuf = nBuf - 4;
194902  }
194903  }
194904  break;
194905 
194906  case 'e':
194907  if( nBuf>2 && 0==memcmp("er", &aBuf[nBuf-2], 2) ){
194908  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
194909  *pnBuf = nBuf - 2;
194910  }
194911  }
194912  break;
194913 
194914  case 'i':
194915  if( nBuf>2 && 0==memcmp("ic", &aBuf[nBuf-2], 2) ){
194916  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
194917  *pnBuf = nBuf - 2;
194918  }
194919  }
194920  break;
194921 
194922  case 'l':
194923  if( nBuf>4 && 0==memcmp("able", &aBuf[nBuf-4], 4) ){
194924  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
194925  *pnBuf = nBuf - 4;
194926  }
194927  }else if( nBuf>4 && 0==memcmp("ible", &aBuf[nBuf-4], 4) ){
194928  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
194929  *pnBuf = nBuf - 4;
194930  }
194931  }
194932  break;
194933 
194934  case 'n':
194935  if( nBuf>3 && 0==memcmp("ant", &aBuf[nBuf-3], 3) ){
194936  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194937  *pnBuf = nBuf - 3;
194938  }
194939  }else if( nBuf>5 && 0==memcmp("ement", &aBuf[nBuf-5], 5) ){
194940  if( fts5Porter_MGt1(aBuf, nBuf-5) ){
194941  *pnBuf = nBuf - 5;
194942  }
194943  }else if( nBuf>4 && 0==memcmp("ment", &aBuf[nBuf-4], 4) ){
194944  if( fts5Porter_MGt1(aBuf, nBuf-4) ){
194945  *pnBuf = nBuf - 4;
194946  }
194947  }else if( nBuf>3 && 0==memcmp("ent", &aBuf[nBuf-3], 3) ){
194948  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194949  *pnBuf = nBuf - 3;
194950  }
194951  }
194952  break;
194953 
194954  case 'o':
194955  if( nBuf>3 && 0==memcmp("ion", &aBuf[nBuf-3], 3) ){
194956  if( fts5Porter_MGt1_and_S_or_T(aBuf, nBuf-3) ){
194957  *pnBuf = nBuf - 3;
194958  }
194959  }else if( nBuf>2 && 0==memcmp("ou", &aBuf[nBuf-2], 2) ){
194960  if( fts5Porter_MGt1(aBuf, nBuf-2) ){
194961  *pnBuf = nBuf - 2;
194962  }
194963  }
194964  break;
194965 
194966  case 's':
194967  if( nBuf>3 && 0==memcmp("ism", &aBuf[nBuf-3], 3) ){
194968  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194969  *pnBuf = nBuf - 3;
194970  }
194971  }
194972  break;
194973 
194974  case 't':
194975  if( nBuf>3 && 0==memcmp("ate", &aBuf[nBuf-3], 3) ){
194976  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194977  *pnBuf = nBuf - 3;
194978  }
194979  }else if( nBuf>3 && 0==memcmp("iti", &aBuf[nBuf-3], 3) ){
194980  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194981  *pnBuf = nBuf - 3;
194982  }
194983  }
194984  break;
194985 
194986  case 'u':
194987  if( nBuf>3 && 0==memcmp("ous", &aBuf[nBuf-3], 3) ){
194988  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194989  *pnBuf = nBuf - 3;
194990  }
194991  }
194992  break;
194993 
194994  case 'v':
194995  if( nBuf>3 && 0==memcmp("ive", &aBuf[nBuf-3], 3) ){
194996  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
194997  *pnBuf = nBuf - 3;
194998  }
194999  }
195000  break;
195001 
195002  case 'z':
195003  if( nBuf>3 && 0==memcmp("ize", &aBuf[nBuf-3], 3) ){
195004  if( fts5Porter_MGt1(aBuf, nBuf-3) ){
195005  *pnBuf = nBuf - 3;
195006  }
195007  }
195008  break;
195009 
195010  }
195011  return ret;
195012 }
195013 
195014 
195015 static int fts5PorterStep1B2(char *aBuf, int *pnBuf){
195016  int ret = 0;
195017  int nBuf = *pnBuf;
195018  switch( aBuf[nBuf-2] ){
195019 
195020  case 'a':
195021  if( nBuf>2 && 0==memcmp("at", &aBuf[nBuf-2], 2) ){
195022  memcpy(&aBuf[nBuf-2], "ate", 3);
195023  *pnBuf = nBuf - 2 + 3;
195024  ret = 1;
195025  }
195026  break;
195027 
195028  case 'b':
195029  if( nBuf>2 && 0==memcmp("bl", &aBuf[nBuf-2], 2) ){
195030  memcpy(&aBuf[nBuf-2], "ble", 3);
195031  *pnBuf = nBuf - 2 + 3;
195032  ret = 1;
195033  }
195034  break;
195035 
195036  case 'i':
195037  if( nBuf>2 && 0==memcmp("iz", &aBuf[nBuf-2], 2) ){
195038  memcpy(&aBuf[nBuf-2], "ize", 3);
195039  *pnBuf = nBuf - 2 + 3;
195040  ret = 1;
195041  }
195042  break;
195043 
195044  }
195045  return ret;
195046 }
195047 
195048 
195049 static int fts5PorterStep2(char *aBuf, int *pnBuf){
195050  int ret = 0;
195051  int nBuf = *pnBuf;
195052  switch( aBuf[nBuf-2] ){
195053 
195054  case 'a':
195055  if( nBuf>7 && 0==memcmp("ational", &aBuf[nBuf-7], 7) ){
195056  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
195057  memcpy(&aBuf[nBuf-7], "ate", 3);
195058  *pnBuf = nBuf - 7 + 3;
195059  }
195060  }else if( nBuf>6 && 0==memcmp("tional", &aBuf[nBuf-6], 6) ){
195061  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
195062  memcpy(&aBuf[nBuf-6], "tion", 4);
195063  *pnBuf = nBuf - 6 + 4;
195064  }
195065  }
195066  break;
195067 
195068  case 'c':
195069  if( nBuf>4 && 0==memcmp("enci", &aBuf[nBuf-4], 4) ){
195070  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195071  memcpy(&aBuf[nBuf-4], "ence", 4);
195072  *pnBuf = nBuf - 4 + 4;
195073  }
195074  }else if( nBuf>4 && 0==memcmp("anci", &aBuf[nBuf-4], 4) ){
195075  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195076  memcpy(&aBuf[nBuf-4], "ance", 4);
195077  *pnBuf = nBuf - 4 + 4;
195078  }
195079  }
195080  break;
195081 
195082  case 'e':
195083  if( nBuf>4 && 0==memcmp("izer", &aBuf[nBuf-4], 4) ){
195084  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195085  memcpy(&aBuf[nBuf-4], "ize", 3);
195086  *pnBuf = nBuf - 4 + 3;
195087  }
195088  }
195089  break;
195090 
195091  case 'g':
195092  if( nBuf>4 && 0==memcmp("logi", &aBuf[nBuf-4], 4) ){
195093  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195094  memcpy(&aBuf[nBuf-4], "log", 3);
195095  *pnBuf = nBuf - 4 + 3;
195096  }
195097  }
195098  break;
195099 
195100  case 'l':
195101  if( nBuf>3 && 0==memcmp("bli", &aBuf[nBuf-3], 3) ){
195102  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
195103  memcpy(&aBuf[nBuf-3], "ble", 3);
195104  *pnBuf = nBuf - 3 + 3;
195105  }
195106  }else if( nBuf>4 && 0==memcmp("alli", &aBuf[nBuf-4], 4) ){
195107  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195108  memcpy(&aBuf[nBuf-4], "al", 2);
195109  *pnBuf = nBuf - 4 + 2;
195110  }
195111  }else if( nBuf>5 && 0==memcmp("entli", &aBuf[nBuf-5], 5) ){
195112  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195113  memcpy(&aBuf[nBuf-5], "ent", 3);
195114  *pnBuf = nBuf - 5 + 3;
195115  }
195116  }else if( nBuf>3 && 0==memcmp("eli", &aBuf[nBuf-3], 3) ){
195117  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
195118  memcpy(&aBuf[nBuf-3], "e", 1);
195119  *pnBuf = nBuf - 3 + 1;
195120  }
195121  }else if( nBuf>5 && 0==memcmp("ousli", &aBuf[nBuf-5], 5) ){
195122  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195123  memcpy(&aBuf[nBuf-5], "ous", 3);
195124  *pnBuf = nBuf - 5 + 3;
195125  }
195126  }
195127  break;
195128 
195129  case 'o':
195130  if( nBuf>7 && 0==memcmp("ization", &aBuf[nBuf-7], 7) ){
195131  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
195132  memcpy(&aBuf[nBuf-7], "ize", 3);
195133  *pnBuf = nBuf - 7 + 3;
195134  }
195135  }else if( nBuf>5 && 0==memcmp("ation", &aBuf[nBuf-5], 5) ){
195136  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195137  memcpy(&aBuf[nBuf-5], "ate", 3);
195138  *pnBuf = nBuf - 5 + 3;
195139  }
195140  }else if( nBuf>4 && 0==memcmp("ator", &aBuf[nBuf-4], 4) ){
195141  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195142  memcpy(&aBuf[nBuf-4], "ate", 3);
195143  *pnBuf = nBuf - 4 + 3;
195144  }
195145  }
195146  break;
195147 
195148  case 's':
195149  if( nBuf>5 && 0==memcmp("alism", &aBuf[nBuf-5], 5) ){
195150  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195151  memcpy(&aBuf[nBuf-5], "al", 2);
195152  *pnBuf = nBuf - 5 + 2;
195153  }
195154  }else if( nBuf>7 && 0==memcmp("iveness", &aBuf[nBuf-7], 7) ){
195155  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
195156  memcpy(&aBuf[nBuf-7], "ive", 3);
195157  *pnBuf = nBuf - 7 + 3;
195158  }
195159  }else if( nBuf>7 && 0==memcmp("fulness", &aBuf[nBuf-7], 7) ){
195160  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
195161  memcpy(&aBuf[nBuf-7], "ful", 3);
195162  *pnBuf = nBuf - 7 + 3;
195163  }
195164  }else if( nBuf>7 && 0==memcmp("ousness", &aBuf[nBuf-7], 7) ){
195165  if( fts5Porter_MGt0(aBuf, nBuf-7) ){
195166  memcpy(&aBuf[nBuf-7], "ous", 3);
195167  *pnBuf = nBuf - 7 + 3;
195168  }
195169  }
195170  break;
195171 
195172  case 't':
195173  if( nBuf>5 && 0==memcmp("aliti", &aBuf[nBuf-5], 5) ){
195174  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195175  memcpy(&aBuf[nBuf-5], "al", 2);
195176  *pnBuf = nBuf - 5 + 2;
195177  }
195178  }else if( nBuf>5 && 0==memcmp("iviti", &aBuf[nBuf-5], 5) ){
195179  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195180  memcpy(&aBuf[nBuf-5], "ive", 3);
195181  *pnBuf = nBuf - 5 + 3;
195182  }
195183  }else if( nBuf>6 && 0==memcmp("biliti", &aBuf[nBuf-6], 6) ){
195184  if( fts5Porter_MGt0(aBuf, nBuf-6) ){
195185  memcpy(&aBuf[nBuf-6], "ble", 3);
195186  *pnBuf = nBuf - 6 + 3;
195187  }
195188  }
195189  break;
195190 
195191  }
195192  return ret;
195193 }
195194 
195195 
195196 static int fts5PorterStep3(char *aBuf, int *pnBuf){
195197  int ret = 0;
195198  int nBuf = *pnBuf;
195199  switch( aBuf[nBuf-2] ){
195200 
195201  case 'a':
195202  if( nBuf>4 && 0==memcmp("ical", &aBuf[nBuf-4], 4) ){
195203  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195204  memcpy(&aBuf[nBuf-4], "ic", 2);
195205  *pnBuf = nBuf - 4 + 2;
195206  }
195207  }
195208  break;
195209 
195210  case 's':
195211  if( nBuf>4 && 0==memcmp("ness", &aBuf[nBuf-4], 4) ){
195212  if( fts5Porter_MGt0(aBuf, nBuf-4) ){
195213  *pnBuf = nBuf - 4;
195214  }
195215  }
195216  break;
195217 
195218  case 't':
195219  if( nBuf>5 && 0==memcmp("icate", &aBuf[nBuf-5], 5) ){
195220  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195221  memcpy(&aBuf[nBuf-5], "ic", 2);
195222  *pnBuf = nBuf - 5 + 2;
195223  }
195224  }else if( nBuf>5 && 0==memcmp("iciti", &aBuf[nBuf-5], 5) ){
195225  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195226  memcpy(&aBuf[nBuf-5], "ic", 2);
195227  *pnBuf = nBuf - 5 + 2;
195228  }
195229  }
195230  break;
195231 
195232  case 'u':
195233  if( nBuf>3 && 0==memcmp("ful", &aBuf[nBuf-3], 3) ){
195234  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
195235  *pnBuf = nBuf - 3;
195236  }
195237  }
195238  break;
195239 
195240  case 'v':
195241  if( nBuf>5 && 0==memcmp("ative", &aBuf[nBuf-5], 5) ){
195242  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195243  *pnBuf = nBuf - 5;
195244  }
195245  }
195246  break;
195247 
195248  case 'z':
195249  if( nBuf>5 && 0==memcmp("alize", &aBuf[nBuf-5], 5) ){
195250  if( fts5Porter_MGt0(aBuf, nBuf-5) ){
195251  memcpy(&aBuf[nBuf-5], "al", 2);
195252  *pnBuf = nBuf - 5 + 2;
195253  }
195254  }
195255  break;
195256 
195257  }
195258  return ret;
195259 }
195260 
195261 
195262 static int fts5PorterStep1B(char *aBuf, int *pnBuf){
195263  int ret = 0;
195264  int nBuf = *pnBuf;
195265  switch( aBuf[nBuf-2] ){
195266 
195267  case 'e':
195268  if( nBuf>3 && 0==memcmp("eed", &aBuf[nBuf-3], 3) ){
195269  if( fts5Porter_MGt0(aBuf, nBuf-3) ){
195270  memcpy(&aBuf[nBuf-3], "ee", 2);
195271  *pnBuf = nBuf - 3 + 2;
195272  }
195273  }else if( nBuf>2 && 0==memcmp("ed", &aBuf[nBuf-2], 2) ){
195274  if( fts5Porter_Vowel(aBuf, nBuf-2) ){
195275  *pnBuf = nBuf - 2;
195276  ret = 1;
195277  }
195278  }
195279  break;
195280 
195281  case 'n':
195282  if( nBuf>3 && 0==memcmp("ing", &aBuf[nBuf-3], 3) ){
195283  if( fts5Porter_Vowel(aBuf, nBuf-3) ){
195284  *pnBuf = nBuf - 3;
195285  ret = 1;
195286  }
195287  }
195288  break;
195289 
195290  }
195291  return ret;
195292 }
195293 
195294 /*
195295 ** GENERATED CODE ENDS HERE (mkportersteps.tcl)
195296 ***************************************************************************
195297 **************************************************************************/
195298 
195299 static void fts5PorterStep1A(char *aBuf, int *pnBuf){
195300  int nBuf = *pnBuf;
195301  if( aBuf[nBuf-1]=='s' ){
195302  if( aBuf[nBuf-2]=='e' ){
195303  if( (nBuf>4 && aBuf[nBuf-4]=='s' && aBuf[nBuf-3]=='s')
195304  || (nBuf>3 && aBuf[nBuf-3]=='i' )
195305  ){
195306  *pnBuf = nBuf-2;
195307  }else{
195308  *pnBuf = nBuf-1;
195309  }
195310  }
195311  else if( aBuf[nBuf-2]!='s' ){
195312  *pnBuf = nBuf-1;
195313  }
195314  }
195315 }
195316 
195317 static int fts5PorterCb(
195318  void *pCtx,
195319  int tflags,
195320  const char *pToken,
195321  int nToken,
195322  int iStart,
195323  int iEnd
195324 ){
195325  PorterContext *p = (PorterContext*)pCtx;
195326 
195327  char *aBuf;
195328  int nBuf;
195329 
195330  if( nToken>FTS5_PORTER_MAX_TOKEN || nToken<3 ) goto pass_through;
195331  aBuf = p->aBuf;
195332  nBuf = nToken;
195333  memcpy(aBuf, pToken, nBuf);
195334 
195335  /* Step 1. */
195336  fts5PorterStep1A(aBuf, &nBuf);
195337  if( fts5PorterStep1B(aBuf, &nBuf) ){
195338  if( fts5PorterStep1B2(aBuf, &nBuf)==0 ){
195339  char c = aBuf[nBuf-1];
195340  if( fts5PorterIsVowel(c, 0)==0
195341  && c!='l' && c!='s' && c!='z' && c==aBuf[nBuf-2]
195342  ){
195343  nBuf--;
195344  }else if( fts5Porter_MEq1(aBuf, nBuf) && fts5Porter_Ostar(aBuf, nBuf) ){
195345  aBuf[nBuf++] = 'e';
195346  }
195347  }
195348  }
195349 
195350  /* Step 1C. */
195351  if( aBuf[nBuf-1]=='y' && fts5Porter_Vowel(aBuf, nBuf-1) ){
195352  aBuf[nBuf-1] = 'i';
195353  }
195354 
195355  /* Steps 2 through 4. */
195356  fts5PorterStep2(aBuf, &nBuf);
195357  fts5PorterStep3(aBuf, &nBuf);
195358  fts5PorterStep4(aBuf, &nBuf);
195359 
195360  /* Step 5a. */
195361  assert( nBuf>0 );
195362  if( aBuf[nBuf-1]=='e' ){
195363  if( fts5Porter_MGt1(aBuf, nBuf-1)
195364  || (fts5Porter_MEq1(aBuf, nBuf-1) && !fts5Porter_Ostar(aBuf, nBuf-1))
195365  ){
195366  nBuf--;
195367  }
195368  }
195369 
195370  /* Step 5b. */
195371  if( nBuf>1 && aBuf[nBuf-1]=='l'
195372  && aBuf[nBuf-2]=='l' && fts5Porter_MGt1(aBuf, nBuf-1)
195373  ){
195374  nBuf--;
195375  }
195376 
195377  return p->xToken(p->pCtx, tflags, aBuf, nBuf, iStart, iEnd);
195378 
195379  pass_through:
195380  return p->xToken(p->pCtx, tflags, pToken, nToken, iStart, iEnd);
195381 }
195382 
195383 /*
195384 ** Tokenize using the porter tokenizer.
195385 */
195386 static int fts5PorterTokenize(
195387  Fts5Tokenizer *pTokenizer,
195388  void *pCtx,
195389  int flags,
195390  const char *pText, int nText,
195391  int (*xToken)(void*, int, const char*, int nToken, int iStart, int iEnd)
195392 ){
195393  PorterTokenizer *p = (PorterTokenizer*)pTokenizer;
195394  PorterContext sCtx;
195395  sCtx.xToken = xToken;
195396  sCtx.pCtx = pCtx;
195397  sCtx.aBuf = p->aBuf;
195398  return p->tokenizer.xTokenize(
195399  p->pTokenizer, (void*)&sCtx, flags, pText, nText, fts5PorterCb
195400  );
195401 }
195402 
195403 /*
195404 ** Register all built-in tokenizers with FTS5.
195405 */
195406 static int sqlite3Fts5TokenizerInit(fts5_api *pApi){
195407  struct BuiltinTokenizer {
195408  const char *zName;
195409  fts5_tokenizer x;
195410  } aBuiltin[] = {
195411  { "unicode61", {fts5UnicodeCreate, fts5UnicodeDelete, fts5UnicodeTokenize}},
195412  { "ascii", {fts5AsciiCreate, fts5AsciiDelete, fts5AsciiTokenize }},
195413  { "porter", {fts5PorterCreate, fts5PorterDelete, fts5PorterTokenize }},
195414  };
195415 
195416  int rc = SQLITE_OK; /* Return code */
195417  int i; /* To iterate through builtin functions */
195418 
195419  for(i=0; rc==SQLITE_OK && i<ArraySize(aBuiltin); i++){
195420  rc = pApi->xCreateTokenizer(pApi,
195421  aBuiltin[i].zName,
195422  (void*)pApi,
195423  &aBuiltin[i].x,
195424  0
195425  );
195426  }
195427 
195428  return rc;
195429 }
195430 
195431 
195432 
195433 /*
195434 ** 2012 May 25
195435 **
195436 ** The author disclaims copyright to this source code. In place of
195437 ** a legal notice, here is a blessing:
195438 **
195439 ** May you do good and not evil.
195440 ** May you find forgiveness for yourself and forgive others.
195441 ** May you share freely, never taking more than you give.
195442 **
195443 ******************************************************************************
195444 */
195445 
195446 /*
195447 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
195448 */
195449 
195450 
195451 /* #include <assert.h> */
195452 
195453 /*
195454 ** Return true if the argument corresponds to a unicode codepoint
195455 ** classified as either a letter or a number. Otherwise false.
195456 **
195457 ** The results are undefined if the value passed to this function
195458 ** is less than zero.
195459 */
195460 static int sqlite3Fts5UnicodeIsalnum(int c){
195461  /* Each unsigned integer in the following array corresponds to a contiguous
195462  ** range of unicode codepoints that are not either letters or numbers (i.e.
195463  ** codepoints for which this function should return 0).
195464  **
195465  ** The most significant 22 bits in each 32-bit value contain the first
195466  ** codepoint in the range. The least significant 10 bits are used to store
195467  ** the size of the range (always at least 1). In other words, the value
195468  ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
195469  ** C. It is not possible to represent a range larger than 1023 codepoints
195470  ** using this format.
195471  */
195472  static const unsigned int aEntry[] = {
195473  0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
195474  0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
195475  0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
195476  0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
195477  0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
195478  0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
195479  0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
195480  0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
195481  0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
195482  0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
195483  0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
195484  0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
195485  0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
195486  0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
195487  0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
195488  0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
195489  0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
195490  0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
195491  0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
195492  0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
195493  0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
195494  0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
195495  0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
195496  0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
195497  0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
195498  0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
195499  0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
195500  0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
195501  0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
195502  0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
195503  0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
195504  0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
195505  0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
195506  0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
195507  0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
195508  0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
195509  0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
195510  0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
195511  0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
195512  0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
195513  0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
195514  0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
195515  0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
195516  0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
195517  0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
195518  0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
195519  0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
195520  0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
195521  0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
195522  0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
195523  0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
195524  0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
195525  0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
195526  0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
195527  0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
195528  0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
195529  0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
195530  0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
195531  0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
195532  0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
195533  0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
195534  0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
195535  0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
195536  0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
195537  0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
195538  0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
195539  0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
195540  0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
195541  0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
195542  0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
195543  0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
195544  0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
195545  0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
195546  0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
195547  0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
195548  0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
195549  0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
195550  0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
195551  0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
195552  0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
195553  0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
195554  0x380400F0,
195555  };
195556  static const unsigned int aAscii[4] = {
195557  0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
195558  };
195559 
195560  if( (unsigned int)c<128 ){
195561  return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
195562  }else if( (unsigned int)c<(1<<22) ){
195563  unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
195564  int iRes = 0;
195565  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
195566  int iLo = 0;
195567  while( iHi>=iLo ){
195568  int iTest = (iHi + iLo) / 2;
195569  if( key >= aEntry[iTest] ){
195570  iRes = iTest;
195571  iLo = iTest+1;
195572  }else{
195573  iHi = iTest-1;
195574  }
195575  }
195576  assert( aEntry[0]<key );
195577  assert( key>=aEntry[iRes] );
195578  return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
195579  }
195580  return 1;
195581 }
195582 
195583 
195584 /*
195585 ** If the argument is a codepoint corresponding to a lowercase letter
195586 ** in the ASCII range with a diacritic added, return the codepoint
195587 ** of the ASCII letter only. For example, if passed 235 - "LATIN
195588 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
195589 ** E"). The resuls of passing a codepoint that corresponds to an
195590 ** uppercase letter are undefined.
195591 */
195592 static int fts5_remove_diacritic(int c){
195593  unsigned short aDia[] = {
195594  0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
195595  2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
195596  2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
195597  2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
195598  3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
195599  3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
195600  4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
195601  6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
195602  61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
195603  61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
195604  62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
195605  62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
195606  62924, 63050, 63082, 63274, 63390,
195607  };
195608  char aChar[] = {
195609  '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
195610  'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
195611  's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
195612  'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
195613  'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
195614  '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
195615  'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
195616  'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
195617  'e', 'i', 'o', 'u', 'y',
195618  };
195619 
195620  unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
195621  int iRes = 0;
195622  int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
195623  int iLo = 0;
195624  while( iHi>=iLo ){
195625  int iTest = (iHi + iLo) / 2;
195626  if( key >= aDia[iTest] ){
195627  iRes = iTest;
195628  iLo = iTest+1;
195629  }else{
195630  iHi = iTest-1;
195631  }
195632  }
195633  assert( key>=aDia[iRes] );
195634  return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
195635 }
195636 
195637 
195638 /*
195639 ** Return true if the argument interpreted as a unicode codepoint
195640 ** is a diacritical modifier character.
195641 */
195642 static int sqlite3Fts5UnicodeIsdiacritic(int c){
195643  unsigned int mask0 = 0x08029FDF;
195644  unsigned int mask1 = 0x000361F8;
195645  if( c<768 || c>817 ) return 0;
195646  return (c < 768+32) ?
195647  (mask0 & (1 << (c-768))) :
195648  (mask1 & (1 << (c-768-32)));
195649 }
195650 
195651 
195652 /*
195653 ** Interpret the argument as a unicode codepoint. If the codepoint
195654 ** is an upper case character that has a lower case equivalent,
195655 ** return the codepoint corresponding to the lower case version.
195656 ** Otherwise, return a copy of the argument.
195657 **
195658 ** The results are undefined if the value passed to this function
195659 ** is less than zero.
195660 */
195661 static int sqlite3Fts5UnicodeFold(int c, int bRemoveDiacritic){
195662  /* Each entry in the following array defines a rule for folding a range
195663  ** of codepoints to lower case. The rule applies to a range of nRange
195664  ** codepoints starting at codepoint iCode.
195665  **
195666  ** If the least significant bit in flags is clear, then the rule applies
195667  ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
195668  ** need to be folded). Or, if it is set, then the rule only applies to
195669  ** every second codepoint in the range, starting with codepoint C.
195670  **
195671  ** The 7 most significant bits in flags are an index into the aiOff[]
195672  ** array. If a specific codepoint C does require folding, then its lower
195673  ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
195674  **
195675  ** The contents of this array are generated by parsing the CaseFolding.txt
195676  ** file distributed as part of the "Unicode Character Database". See
195677  ** http://www.unicode.org for details.
195678  */
195679  static const struct TableEntry {
195680  unsigned short iCode;
195681  unsigned char flags;
195682  unsigned char nRange;
195683  } aEntry[] = {
195684  {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
195685  {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
195686  {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
195687  {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
195688  {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
195689  {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
195690  {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
195691  {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
195692  {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
195693  {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
195694  {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
195695  {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
195696  {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
195697  {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
195698  {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
195699  {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
195700  {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
195701  {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
195702  {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
195703  {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
195704  {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
195705  {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
195706  {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
195707  {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
195708  {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
195709  {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
195710  {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
195711  {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
195712  {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
195713  {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
195714  {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
195715  {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
195716  {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
195717  {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
195718  {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
195719  {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
195720  {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
195721  {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
195722  {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
195723  {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
195724  {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
195725  {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
195726  {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
195727  {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
195728  {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
195729  {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
195730  {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
195731  {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
195732  {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
195733  {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
195734  {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
195735  {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
195736  {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
195737  {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
195738  {65313, 14, 26},
195739  };
195740  static const unsigned short aiOff[] = {
195741  1, 2, 8, 15, 16, 26, 28, 32,
195742  37, 38, 40, 48, 63, 64, 69, 71,
195743  79, 80, 116, 202, 203, 205, 206, 207,
195744  209, 210, 211, 213, 214, 217, 218, 219,
195745  775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
195746  54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
195747  57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
195748  65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
195749  65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
195750  65514, 65521, 65527, 65528, 65529,
195751  };
195752 
195753  int ret = c;
195754 
195755  assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
195756 
195757  if( c<128 ){
195758  if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
195759  }else if( c<65536 ){
195760  const struct TableEntry *p;
195761  int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
195762  int iLo = 0;
195763  int iRes = -1;
195764 
195765  assert( c>aEntry[0].iCode );
195766  while( iHi>=iLo ){
195767  int iTest = (iHi + iLo) / 2;
195768  int cmp = (c - aEntry[iTest].iCode);
195769  if( cmp>=0 ){
195770  iRes = iTest;
195771  iLo = iTest+1;
195772  }else{
195773  iHi = iTest-1;
195774  }
195775  }
195776 
195777  assert( iRes>=0 && c>=aEntry[iRes].iCode );
195778  p = &aEntry[iRes];
195779  if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
195780  ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
195781  assert( ret>0 );
195782  }
195783 
195784  if( bRemoveDiacritic ) ret = fts5_remove_diacritic(ret);
195785  }
195786 
195787  else if( c>=66560 && c<66600 ){
195788  ret = c + 40;
195789  }
195790 
195791  return ret;
195792 }
195793 
195794 /*
195795 ** 2015 May 30
195796 **
195797 ** The author disclaims copyright to this source code. In place of
195798 ** a legal notice, here is a blessing:
195799 **
195800 ** May you do good and not evil.
195801 ** May you find forgiveness for yourself and forgive others.
195802 ** May you share freely, never taking more than you give.
195803 **
195804 ******************************************************************************
195805 **
195806 ** Routines for varint serialization and deserialization.
195807 */
195808 
195809 
195810 /* #include "fts5Int.h" */
195811 
195812 /*
195813 ** This is a copy of the sqlite3GetVarint32() routine from the SQLite core.
195814 ** Except, this version does handle the single byte case that the core
195815 ** version depends on being handled before its function is called.
195816 */
195817 static int sqlite3Fts5GetVarint32(const unsigned char *p, u32 *v){
195818  u32 a,b;
195819 
195820  /* The 1-byte case. Overwhelmingly the most common. */
195821  a = *p;
195822  /* a: p0 (unmasked) */
195823  if (!(a&0x80))
195824  {
195825  /* Values between 0 and 127 */
195826  *v = a;
195827  return 1;
195828  }
195829 
195830  /* The 2-byte case */
195831  p++;
195832  b = *p;
195833  /* b: p1 (unmasked) */
195834  if (!(b&0x80))
195835  {
195836  /* Values between 128 and 16383 */
195837  a &= 0x7f;
195838  a = a<<7;
195839  *v = a | b;
195840  return 2;
195841  }
195842 
195843  /* The 3-byte case */
195844  p++;
195845  a = a<<14;
195846  a |= *p;
195847  /* a: p0<<14 | p2 (unmasked) */
195848  if (!(a&0x80))
195849  {
195850  /* Values between 16384 and 2097151 */
195851  a &= (0x7f<<14)|(0x7f);
195852  b &= 0x7f;
195853  b = b<<7;
195854  *v = a | b;
195855  return 3;
195856  }
195857 
195858  /* A 32-bit varint is used to store size information in btrees.
195859  ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
195860  ** A 3-byte varint is sufficient, for example, to record the size
195861  ** of a 1048569-byte BLOB or string.
195862  **
195863  ** We only unroll the first 1-, 2-, and 3- byte cases. The very
195864  ** rare larger cases can be handled by the slower 64-bit varint
195865  ** routine.
195866  */
195867  {
195868  u64 v64;
195869  u8 n;
195870  p -= 2;
195871  n = sqlite3Fts5GetVarint(p, &v64);
195872  *v = (u32)v64;
195873  assert( n>3 && n<=9 );
195874  return n;
195875  }
195876 }
195877 
195878 
195879 /*
195880 ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
195881 ** are defined here rather than simply putting the constant expressions
195882 ** inline in order to work around bugs in the RVT compiler.
195883 **
195884 ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
195885 **
195886 ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
195887 */
195888 #define SLOT_2_0 0x001fc07f
195889 #define SLOT_4_2_0 0xf01fc07f
195890 
195891 /*
195892 ** Read a 64-bit variable-length integer from memory starting at p[0].
195893 ** Return the number of bytes read. The value is stored in *v.
195894 */
195895 static u8 sqlite3Fts5GetVarint(const unsigned char *p, u64 *v){
195896  u32 a,b,s;
195897 
195898  a = *p;
195899  /* a: p0 (unmasked) */
195900  if (!(a&0x80))
195901  {
195902  *v = a;
195903  return 1;
195904  }
195905 
195906  p++;
195907  b = *p;
195908  /* b: p1 (unmasked) */
195909  if (!(b&0x80))
195910  {
195911  a &= 0x7f;
195912  a = a<<7;
195913  a |= b;
195914  *v = a;
195915  return 2;
195916  }
195917 
195918  /* Verify that constants are precomputed correctly */
195919  assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
195920  assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
195921 
195922  p++;
195923  a = a<<14;
195924  a |= *p;
195925  /* a: p0<<14 | p2 (unmasked) */
195926  if (!(a&0x80))
195927  {
195928  a &= SLOT_2_0;
195929  b &= 0x7f;
195930  b = b<<7;
195931  a |= b;
195932  *v = a;
195933  return 3;
195934  }
195935 
195936  /* CSE1 from below */
195937  a &= SLOT_2_0;
195938  p++;
195939  b = b<<14;
195940  b |= *p;
195941  /* b: p1<<14 | p3 (unmasked) */
195942  if (!(b&0x80))
195943  {
195944  b &= SLOT_2_0;
195945  /* moved CSE1 up */
195946  /* a &= (0x7f<<14)|(0x7f); */
195947  a = a<<7;
195948  a |= b;
195949  *v = a;
195950  return 4;
195951  }
195952 
195953  /* a: p0<<14 | p2 (masked) */
195954  /* b: p1<<14 | p3 (unmasked) */
195955  /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
195956  /* moved CSE1 up */
195957  /* a &= (0x7f<<14)|(0x7f); */
195958  b &= SLOT_2_0;
195959  s = a;
195960  /* s: p0<<14 | p2 (masked) */
195961 
195962  p++;
195963  a = a<<14;
195964  a |= *p;
195965  /* a: p0<<28 | p2<<14 | p4 (unmasked) */
195966  if (!(a&0x80))
195967  {
195968  /* we can skip these cause they were (effectively) done above in calc'ing s */
195969  /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
195970  /* b &= (0x7f<<14)|(0x7f); */
195971  b = b<<7;
195972  a |= b;
195973  s = s>>18;
195974  *v = ((u64)s)<<32 | a;
195975  return 5;
195976  }
195977 
195978  /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
195979  s = s<<7;
195980  s |= b;
195981  /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
195982 
195983  p++;
195984  b = b<<14;
195985  b |= *p;
195986  /* b: p1<<28 | p3<<14 | p5 (unmasked) */
195987  if (!(b&0x80))
195988  {
195989  /* we can skip this cause it was (effectively) done above in calc'ing s */
195990  /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
195991  a &= SLOT_2_0;
195992  a = a<<7;
195993  a |= b;
195994  s = s>>18;
195995  *v = ((u64)s)<<32 | a;
195996  return 6;
195997  }
195998 
195999  p++;
196000  a = a<<14;
196001  a |= *p;
196002  /* a: p2<<28 | p4<<14 | p6 (unmasked) */
196003  if (!(a&0x80))
196004  {
196005  a &= SLOT_4_2_0;
196006  b &= SLOT_2_0;
196007  b = b<<7;
196008  a |= b;
196009  s = s>>11;
196010  *v = ((u64)s)<<32 | a;
196011  return 7;
196012  }
196013 
196014  /* CSE2 from below */
196015  a &= SLOT_2_0;
196016  p++;
196017  b = b<<14;
196018  b |= *p;
196019  /* b: p3<<28 | p5<<14 | p7 (unmasked) */
196020  if (!(b&0x80))
196021  {
196022  b &= SLOT_4_2_0;
196023  /* moved CSE2 up */
196024  /* a &= (0x7f<<14)|(0x7f); */
196025  a = a<<7;
196026  a |= b;
196027  s = s>>4;
196028  *v = ((u64)s)<<32 | a;
196029  return 8;
196030  }
196031 
196032  p++;
196033  a = a<<15;
196034  a |= *p;
196035  /* a: p4<<29 | p6<<15 | p8 (unmasked) */
196036 
196037  /* moved CSE2 up */
196038  /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
196039  b &= SLOT_2_0;
196040  b = b<<8;
196041  a |= b;
196042 
196043  s = s<<4;
196044  b = p[-4];
196045  b &= 0x7f;
196046  b = b>>3;
196047  s |= b;
196048 
196049  *v = ((u64)s)<<32 | a;
196050 
196051  return 9;
196052 }
196053 
196054 /*
196055 ** The variable-length integer encoding is as follows:
196056 **
196057 ** KEY:
196058 ** A = 0xxxxxxx 7 bits of data and one flag bit
196059 ** B = 1xxxxxxx 7 bits of data and one flag bit
196060 ** C = xxxxxxxx 8 bits of data
196061 **
196062 ** 7 bits - A
196063 ** 14 bits - BA
196064 ** 21 bits - BBA
196065 ** 28 bits - BBBA
196066 ** 35 bits - BBBBA
196067 ** 42 bits - BBBBBA
196068 ** 49 bits - BBBBBBA
196069 ** 56 bits - BBBBBBBA
196070 ** 64 bits - BBBBBBBBC
196071 */
196072 
196073 #ifdef SQLITE_NOINLINE
196074 # define FTS5_NOINLINE SQLITE_NOINLINE
196075 #else
196076 # define FTS5_NOINLINE
196077 #endif
196078 
196079 /*
196080 ** Write a 64-bit variable-length integer to memory starting at p[0].
196081 ** The length of data write will be between 1 and 9 bytes. The number
196082 ** of bytes written is returned.
196083 **
196084 ** A variable-length integer consists of the lower 7 bits of each byte
196085 ** for all bytes that have the 8th bit set and one byte with the 8th
196086 ** bit clear. Except, if we get to the 9th byte, it stores the full
196087 ** 8 bits and is the last byte.
196088 */
196089 static int FTS5_NOINLINE fts5PutVarint64(unsigned char *p, u64 v){
196090  int i, j, n;
196091  u8 buf[10];
196092  if( v & (((u64)0xff000000)<<32) ){
196093  p[8] = (u8)v;
196094  v >>= 8;
196095  for(i=7; i>=0; i--){
196096  p[i] = (u8)((v & 0x7f) | 0x80);
196097  v >>= 7;
196098  }
196099  return 9;
196100  }
196101  n = 0;
196102  do{
196103  buf[n++] = (u8)((v & 0x7f) | 0x80);
196104  v >>= 7;
196105  }while( v!=0 );
196106  buf[0] &= 0x7f;
196107  assert( n<=9 );
196108  for(i=0, j=n-1; j>=0; j--, i++){
196109  p[i] = buf[j];
196110  }
196111  return n;
196112 }
196113 
196114 static int sqlite3Fts5PutVarint(unsigned char *p, u64 v){
196115  if( v<=0x7f ){
196116  p[0] = v&0x7f;
196117  return 1;
196118  }
196119  if( v<=0x3fff ){
196120  p[0] = ((v>>7)&0x7f)|0x80;
196121  p[1] = v&0x7f;
196122  return 2;
196123  }
196124  return fts5PutVarint64(p,v);
196125 }
196126 
196127 
196128 static int sqlite3Fts5GetVarintLen(u32 iVal){
196129 #if 0
196130  if( iVal<(1 << 7 ) ) return 1;
196131 #endif
196132  assert( iVal>=(1 << 7) );
196133  if( iVal<(1 << 14) ) return 2;
196134  if( iVal<(1 << 21) ) return 3;
196135  if( iVal<(1 << 28) ) return 4;
196136  return 5;
196137 }
196138 
196139 
196140 /*
196141 ** 2015 May 08
196142 **
196143 ** The author disclaims copyright to this source code. In place of
196144 ** a legal notice, here is a blessing:
196145 **
196146 ** May you do good and not evil.
196147 ** May you find forgiveness for yourself and forgive others.
196148 ** May you share freely, never taking more than you give.
196149 **
196150 ******************************************************************************
196151 **
196152 ** This is an SQLite virtual table module implementing direct access to an
196153 ** existing FTS5 index. The module may create several different types of
196154 ** tables:
196155 **
196156 ** col:
196157 ** CREATE TABLE vocab(term, col, doc, cnt, PRIMARY KEY(term, col));
196158 **
196159 ** One row for each term/column combination. The value of $doc is set to
196160 ** the number of fts5 rows that contain at least one instance of term
196161 ** $term within column $col. Field $cnt is set to the total number of
196162 ** instances of term $term in column $col (in any row of the fts5 table).
196163 **
196164 ** row:
196165 ** CREATE TABLE vocab(term, doc, cnt, PRIMARY KEY(term));
196166 **
196167 ** One row for each term in the database. The value of $doc is set to
196168 ** the number of fts5 rows that contain at least one instance of term
196169 ** $term. Field $cnt is set to the total number of instances of term
196170 ** $term in the database.
196171 */
196172 
196173 
196174 /* #include "fts5Int.h" */
196175 
196176 
196177 typedef struct Fts5VocabTable Fts5VocabTable;
196178 typedef struct Fts5VocabCursor Fts5VocabCursor;
196179 
196180 struct Fts5VocabTable {
196181  sqlite3_vtab base;
196182  char *zFts5Tbl; /* Name of fts5 table */
196183  char *zFts5Db; /* Db containing fts5 table */
196184  sqlite3 *db; /* Database handle */
196185  Fts5Global *pGlobal; /* FTS5 global object for this database */
196186  int eType; /* FTS5_VOCAB_COL or ROW */
196187 };
196188 
196189 struct Fts5VocabCursor {
196190  sqlite3_vtab_cursor base;
196191  sqlite3_stmt *pStmt; /* Statement holding lock on pIndex */
196192  Fts5Index *pIndex; /* Associated FTS5 index */
196193 
196194  int bEof; /* True if this cursor is at EOF */
196195  Fts5IndexIter *pIter; /* Term/rowid iterator object */
196196 
196197  int nLeTerm; /* Size of zLeTerm in bytes */
196198  char *zLeTerm; /* (term <= $zLeTerm) paramater, or NULL */
196199 
196200  /* These are used by 'col' tables only */
196201  Fts5Config *pConfig; /* Fts5 table configuration */
196202  int iCol;
196203  i64 *aCnt;
196204  i64 *aDoc;
196205 
196206  /* Output values used by 'row' and 'col' tables */
196207  i64 rowid; /* This table's current rowid value */
196208  Fts5Buffer term; /* Current value of 'term' column */
196209 };
196210 
196211 #define FTS5_VOCAB_COL 0
196212 #define FTS5_VOCAB_ROW 1
196213 
196214 #define FTS5_VOCAB_COL_SCHEMA "term, col, doc, cnt"
196215 #define FTS5_VOCAB_ROW_SCHEMA "term, doc, cnt"
196216 
196217 /*
196218 ** Bits for the mask used as the idxNum value by xBestIndex/xFilter.
196219 */
196220 #define FTS5_VOCAB_TERM_EQ 0x01
196221 #define FTS5_VOCAB_TERM_GE 0x02
196222 #define FTS5_VOCAB_TERM_LE 0x04
196223 
196224 
196225 /*
196226 ** Translate a string containing an fts5vocab table type to an
196227 ** FTS5_VOCAB_XXX constant. If successful, set *peType to the output
196228 ** value and return SQLITE_OK. Otherwise, set *pzErr to an error message
196229 ** and return SQLITE_ERROR.
196230 */
196231 static int fts5VocabTableType(const char *zType, char **pzErr, int *peType){
196232  int rc = SQLITE_OK;
196233  char *zCopy = sqlite3Fts5Strndup(&rc, zType, -1);
196234  if( rc==SQLITE_OK ){
196235  sqlite3Fts5Dequote(zCopy);
196236  if( sqlite3_stricmp(zCopy, "col")==0 ){
196237  *peType = FTS5_VOCAB_COL;
196238  }else
196239 
196240  if( sqlite3_stricmp(zCopy, "row")==0 ){
196241  *peType = FTS5_VOCAB_ROW;
196242  }else
196243  {
196244  *pzErr = sqlite3_mprintf("fts5vocab: unknown table type: %Q", zCopy);
196245  rc = SQLITE_ERROR;
196246  }
196247  sqlite3_free(zCopy);
196248  }
196249 
196250  return rc;
196251 }
196252 
196253 
196254 /*
196255 ** The xDisconnect() virtual table method.
196256 */
196257 static int fts5VocabDisconnectMethod(sqlite3_vtab *pVtab){
196258  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
196259  sqlite3_free(pTab);
196260  return SQLITE_OK;
196261 }
196262 
196263 /*
196264 ** The xDestroy() virtual table method.
196265 */
196266 static int fts5VocabDestroyMethod(sqlite3_vtab *pVtab){
196267  Fts5VocabTable *pTab = (Fts5VocabTable*)pVtab;
196268  sqlite3_free(pTab);
196269  return SQLITE_OK;
196270 }
196271 
196272 /*
196273 ** This function is the implementation of both the xConnect and xCreate
196274 ** methods of the FTS3 virtual table.
196275 **
196276 ** The argv[] array contains the following:
196277 **
196278 ** argv[0] -> module name ("fts5vocab")
196279 ** argv[1] -> database name
196280 ** argv[2] -> table name
196281 **
196282 ** then:
196283 **
196284 ** argv[3] -> name of fts5 table
196285 ** argv[4] -> type of fts5vocab table
196286 **
196287 ** or, for tables in the TEMP schema only.
196288 **
196289 ** argv[3] -> name of fts5 tables database
196290 ** argv[4] -> name of fts5 table
196291 ** argv[5] -> type of fts5vocab table
196292 */
196293 static int fts5VocabInitVtab(
196294  sqlite3 *db, /* The SQLite database connection */
196295  void *pAux, /* Pointer to Fts5Global object */
196296  int argc, /* Number of elements in argv array */
196297  const char * const *argv, /* xCreate/xConnect argument array */
196298  sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
196299  char **pzErr /* Write any error message here */
196300 ){
196301  const char *azSchema[] = {
196302  "CREATE TABlE vocab(" FTS5_VOCAB_COL_SCHEMA ")",
196303  "CREATE TABlE vocab(" FTS5_VOCAB_ROW_SCHEMA ")"
196304  };
196305 
196306  Fts5VocabTable *pRet = 0;
196307  int rc = SQLITE_OK; /* Return code */
196308  int bDb;
196309 
196310  bDb = (argc==6 && strlen(argv[1])==4 && memcmp("temp", argv[1], 4)==0);
196311 
196312  if( argc!=5 && bDb==0 ){
196313  *pzErr = sqlite3_mprintf("wrong number of vtable arguments");
196314  rc = SQLITE_ERROR;
196315  }else{
196316  int nByte; /* Bytes of space to allocate */
196317  const char *zDb = bDb ? argv[3] : argv[1];
196318  const char *zTab = bDb ? argv[4] : argv[3];
196319  const char *zType = bDb ? argv[5] : argv[4];
196320  int nDb = (int)strlen(zDb)+1;
196321  int nTab = (int)strlen(zTab)+1;
196322  int eType = 0;
196323 
196324  rc = fts5VocabTableType(zType, pzErr, &eType);
196325  if( rc==SQLITE_OK ){
196326  assert( eType>=0 && eType<ArraySize(azSchema) );
196327  rc = sqlite3_declare_vtab(db, azSchema[eType]);
196328  }
196329 
196330  nByte = sizeof(Fts5VocabTable) + nDb + nTab;
196331  pRet = sqlite3Fts5MallocZero(&rc, nByte);
196332  if( pRet ){
196333  pRet->pGlobal = (Fts5Global*)pAux;
196334  pRet->eType = eType;
196335  pRet->db = db;
196336  pRet->zFts5Tbl = (char*)&pRet[1];
196337  pRet->zFts5Db = &pRet->zFts5Tbl[nTab];
196338  memcpy(pRet->zFts5Tbl, zTab, nTab);
196339  memcpy(pRet->zFts5Db, zDb, nDb);
196340  sqlite3Fts5Dequote(pRet->zFts5Tbl);
196341  sqlite3Fts5Dequote(pRet->zFts5Db);
196342  }
196343  }
196344 
196345  *ppVTab = (sqlite3_vtab*)pRet;
196346  return rc;
196347 }
196348 
196349 
196350 /*
196351 ** The xConnect() and xCreate() methods for the virtual table. All the
196352 ** work is done in function fts5VocabInitVtab().
196353 */
196354 static int fts5VocabConnectMethod(
196355  sqlite3 *db, /* Database connection */
196356  void *pAux, /* Pointer to tokenizer hash table */
196357  int argc, /* Number of elements in argv array */
196358  const char * const *argv, /* xCreate/xConnect argument array */
196359  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
196360  char **pzErr /* OUT: sqlite3_malloc'd error message */
196361 ){
196362  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
196363 }
196364 static int fts5VocabCreateMethod(
196365  sqlite3 *db, /* Database connection */
196366  void *pAux, /* Pointer to tokenizer hash table */
196367  int argc, /* Number of elements in argv array */
196368  const char * const *argv, /* xCreate/xConnect argument array */
196369  sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
196370  char **pzErr /* OUT: sqlite3_malloc'd error message */
196371 ){
196372  return fts5VocabInitVtab(db, pAux, argc, argv, ppVtab, pzErr);
196373 }
196374 
196375 /*
196376 ** Implementation of the xBestIndex method.
196377 */
196378 static int fts5VocabBestIndexMethod(
196379  sqlite3_vtab *pUnused,
196380  sqlite3_index_info *pInfo
196381 ){
196382  int i;
196383  int iTermEq = -1;
196384  int iTermGe = -1;
196385  int iTermLe = -1;
196386  int idxNum = 0;
196387  int nArg = 0;
196388 
196389  UNUSED_PARAM(pUnused);
196390 
196391  for(i=0; i<pInfo->nConstraint; i++){
196392  struct sqlite3_index_constraint *p = &pInfo->aConstraint[i];
196393  if( p->usable==0 ) continue;
196394  if( p->iColumn==0 ){ /* term column */
196395  if( p->op==SQLITE_INDEX_CONSTRAINT_EQ ) iTermEq = i;
196396  if( p->op==SQLITE_INDEX_CONSTRAINT_LE ) iTermLe = i;
196397  if( p->op==SQLITE_INDEX_CONSTRAINT_LT ) iTermLe = i;
196398  if( p->op==SQLITE_INDEX_CONSTRAINT_GE ) iTermGe = i;
196399  if( p->op==SQLITE_INDEX_CONSTRAINT_GT ) iTermGe = i;
196400  }
196401  }
196402 
196403  if( iTermEq>=0 ){
196404  idxNum |= FTS5_VOCAB_TERM_EQ;
196405  pInfo->aConstraintUsage[iTermEq].argvIndex = ++nArg;
196406  pInfo->estimatedCost = 100;
196407  }else{
196408  pInfo->estimatedCost = 1000000;
196409  if( iTermGe>=0 ){
196410  idxNum |= FTS5_VOCAB_TERM_GE;
196411  pInfo->aConstraintUsage[iTermGe].argvIndex = ++nArg;
196412  pInfo->estimatedCost = pInfo->estimatedCost / 2;
196413  }
196414  if( iTermLe>=0 ){
196415  idxNum |= FTS5_VOCAB_TERM_LE;
196416  pInfo->aConstraintUsage[iTermLe].argvIndex = ++nArg;
196417  pInfo->estimatedCost = pInfo->estimatedCost / 2;
196418  }
196419  }
196420 
196421  pInfo->idxNum = idxNum;
196422 
196423  return SQLITE_OK;
196424 }
196425 
196426 /*
196427 ** Implementation of xOpen method.
196428 */
196429 static int fts5VocabOpenMethod(
196430  sqlite3_vtab *pVTab,
196431  sqlite3_vtab_cursor **ppCsr
196432 ){
196433  Fts5VocabTable *pTab = (Fts5VocabTable*)pVTab;
196434  Fts5Index *pIndex = 0;
196435  Fts5Config *pConfig = 0;
196436  Fts5VocabCursor *pCsr = 0;
196437  int rc = SQLITE_OK;
196438  sqlite3_stmt *pStmt = 0;
196439  char *zSql = 0;
196440 
196441  zSql = sqlite3Fts5Mprintf(&rc,
196442  "SELECT t.%Q FROM %Q.%Q AS t WHERE t.%Q MATCH '*id'",
196443  pTab->zFts5Tbl, pTab->zFts5Db, pTab->zFts5Tbl, pTab->zFts5Tbl
196444  );
196445  if( zSql ){
196446  rc = sqlite3_prepare_v2(pTab->db, zSql, -1, &pStmt, 0);
196447  }
196448  sqlite3_free(zSql);
196449  assert( rc==SQLITE_OK || pStmt==0 );
196450  if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
196451 
196452  if( pStmt && sqlite3_step(pStmt)==SQLITE_ROW ){
196453  i64 iId = sqlite3_column_int64(pStmt, 0);
196454  pIndex = sqlite3Fts5IndexFromCsrid(pTab->pGlobal, iId, &pConfig);
196455  }
196456 
196457  if( rc==SQLITE_OK && pIndex==0 ){
196458  rc = sqlite3_finalize(pStmt);
196459  pStmt = 0;
196460  if( rc==SQLITE_OK ){
196461  pVTab->zErrMsg = sqlite3_mprintf(
196462  "no such fts5 table: %s.%s", pTab->zFts5Db, pTab->zFts5Tbl
196463  );
196464  rc = SQLITE_ERROR;
196465  }
196466  }
196467 
196468  if( rc==SQLITE_OK ){
196469  int nByte = pConfig->nCol * sizeof(i64) * 2 + sizeof(Fts5VocabCursor);
196470  pCsr = (Fts5VocabCursor*)sqlite3Fts5MallocZero(&rc, nByte);
196471  }
196472 
196473  if( pCsr ){
196474  pCsr->pIndex = pIndex;
196475  pCsr->pStmt = pStmt;
196476  pCsr->pConfig = pConfig;
196477  pCsr->aCnt = (i64*)&pCsr[1];
196478  pCsr->aDoc = &pCsr->aCnt[pConfig->nCol];
196479  }else{
196480  sqlite3_finalize(pStmt);
196481  }
196482 
196483  *ppCsr = (sqlite3_vtab_cursor*)pCsr;
196484  return rc;
196485 }
196486 
196487 static void fts5VocabResetCursor(Fts5VocabCursor *pCsr){
196488  pCsr->rowid = 0;
196489  sqlite3Fts5IterClose(pCsr->pIter);
196490  pCsr->pIter = 0;
196491  sqlite3_free(pCsr->zLeTerm);
196492  pCsr->nLeTerm = -1;
196493  pCsr->zLeTerm = 0;
196494 }
196495 
196496 /*
196497 ** Close the cursor. For additional information see the documentation
196498 ** on the xClose method of the virtual table interface.
196499 */
196500 static int fts5VocabCloseMethod(sqlite3_vtab_cursor *pCursor){
196501  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196502  fts5VocabResetCursor(pCsr);
196503  sqlite3Fts5BufferFree(&pCsr->term);
196504  sqlite3_finalize(pCsr->pStmt);
196505  sqlite3_free(pCsr);
196506  return SQLITE_OK;
196507 }
196508 
196509 
196510 /*
196511 ** Advance the cursor to the next row in the table.
196512 */
196513 static int fts5VocabNextMethod(sqlite3_vtab_cursor *pCursor){
196514  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196515  Fts5VocabTable *pTab = (Fts5VocabTable*)pCursor->pVtab;
196516  int rc = SQLITE_OK;
196517  int nCol = pCsr->pConfig->nCol;
196518 
196519  pCsr->rowid++;
196520 
196521  if( pTab->eType==FTS5_VOCAB_COL ){
196522  for(pCsr->iCol++; pCsr->iCol<nCol; pCsr->iCol++){
196523  if( pCsr->aDoc[pCsr->iCol] ) break;
196524  }
196525  }
196526 
196527  if( pTab->eType==FTS5_VOCAB_ROW || pCsr->iCol>=nCol ){
196528  if( sqlite3Fts5IterEof(pCsr->pIter) ){
196529  pCsr->bEof = 1;
196530  }else{
196531  const char *zTerm;
196532  int nTerm;
196533 
196534  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
196535  if( pCsr->nLeTerm>=0 ){
196536  int nCmp = MIN(nTerm, pCsr->nLeTerm);
196537  int bCmp = memcmp(pCsr->zLeTerm, zTerm, nCmp);
196538  if( bCmp<0 || (bCmp==0 && pCsr->nLeTerm<nTerm) ){
196539  pCsr->bEof = 1;
196540  return SQLITE_OK;
196541  }
196542  }
196543 
196544  sqlite3Fts5BufferSet(&rc, &pCsr->term, nTerm, (const u8*)zTerm);
196545  memset(pCsr->aCnt, 0, nCol * sizeof(i64));
196546  memset(pCsr->aDoc, 0, nCol * sizeof(i64));
196547  pCsr->iCol = 0;
196548 
196549  assert( pTab->eType==FTS5_VOCAB_COL || pTab->eType==FTS5_VOCAB_ROW );
196550  while( rc==SQLITE_OK ){
196551  const u8 *pPos; int nPos; /* Position list */
196552  i64 iPos = 0; /* 64-bit position read from poslist */
196553  int iOff = 0; /* Current offset within position list */
196554 
196555  pPos = pCsr->pIter->pData;
196556  nPos = pCsr->pIter->nData;
196557  switch( pCsr->pConfig->eDetail ){
196558  case FTS5_DETAIL_FULL:
196559  pPos = pCsr->pIter->pData;
196560  nPos = pCsr->pIter->nData;
196561  if( pTab->eType==FTS5_VOCAB_ROW ){
196562  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
196563  pCsr->aCnt[0]++;
196564  }
196565  pCsr->aDoc[0]++;
196566  }else{
196567  int iCol = -1;
196568  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff, &iPos) ){
196569  int ii = FTS5_POS2COLUMN(iPos);
196570  pCsr->aCnt[ii]++;
196571  if( iCol!=ii ){
196572  if( ii>=nCol ){
196573  rc = FTS5_CORRUPT;
196574  break;
196575  }
196576  pCsr->aDoc[ii]++;
196577  iCol = ii;
196578  }
196579  }
196580  }
196581  break;
196582 
196583  case FTS5_DETAIL_COLUMNS:
196584  if( pTab->eType==FTS5_VOCAB_ROW ){
196585  pCsr->aDoc[0]++;
196586  }else{
196587  while( 0==sqlite3Fts5PoslistNext64(pPos, nPos, &iOff,&iPos) ){
196588  assert_nc( iPos>=0 && iPos<nCol );
196589  if( iPos>=nCol ){
196590  rc = FTS5_CORRUPT;
196591  break;
196592  }
196593  pCsr->aDoc[iPos]++;
196594  }
196595  }
196596  break;
196597 
196598  default:
196599  assert( pCsr->pConfig->eDetail==FTS5_DETAIL_NONE );
196600  pCsr->aDoc[0]++;
196601  break;
196602  }
196603 
196604  if( rc==SQLITE_OK ){
196605  rc = sqlite3Fts5IterNextScan(pCsr->pIter);
196606  }
196607 
196608  if( rc==SQLITE_OK ){
196609  zTerm = sqlite3Fts5IterTerm(pCsr->pIter, &nTerm);
196610  if( nTerm!=pCsr->term.n || memcmp(zTerm, pCsr->term.p, nTerm) ){
196611  break;
196612  }
196613  if( sqlite3Fts5IterEof(pCsr->pIter) ) break;
196614  }
196615  }
196616  }
196617  }
196618 
196619  if( rc==SQLITE_OK && pCsr->bEof==0 && pTab->eType==FTS5_VOCAB_COL ){
196620  while( pCsr->aDoc[pCsr->iCol]==0 ) pCsr->iCol++;
196621  assert( pCsr->iCol<pCsr->pConfig->nCol );
196622  }
196623  return rc;
196624 }
196625 
196626 /*
196627 ** This is the xFilter implementation for the virtual table.
196628 */
196629 static int fts5VocabFilterMethod(
196630  sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
196631  int idxNum, /* Strategy index */
196632  const char *zUnused, /* Unused */
196633  int nUnused, /* Number of elements in apVal */
196634  sqlite3_value **apVal /* Arguments for the indexing scheme */
196635 ){
196636  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196637  int rc = SQLITE_OK;
196638 
196639  int iVal = 0;
196640  int f = FTS5INDEX_QUERY_SCAN;
196641  const char *zTerm = 0;
196642  int nTerm = 0;
196643 
196644  sqlite3_value *pEq = 0;
196645  sqlite3_value *pGe = 0;
196646  sqlite3_value *pLe = 0;
196647 
196648  UNUSED_PARAM2(zUnused, nUnused);
196649 
196650  fts5VocabResetCursor(pCsr);
196651  if( idxNum & FTS5_VOCAB_TERM_EQ ) pEq = apVal[iVal++];
196652  if( idxNum & FTS5_VOCAB_TERM_GE ) pGe = apVal[iVal++];
196653  if( idxNum & FTS5_VOCAB_TERM_LE ) pLe = apVal[iVal++];
196654 
196655  if( pEq ){
196656  zTerm = (const char *)sqlite3_value_text(pEq);
196657  nTerm = sqlite3_value_bytes(pEq);
196658  f = 0;
196659  }else{
196660  if( pGe ){
196661  zTerm = (const char *)sqlite3_value_text(pGe);
196662  nTerm = sqlite3_value_bytes(pGe);
196663  }
196664  if( pLe ){
196665  const char *zCopy = (const char *)sqlite3_value_text(pLe);
196666  pCsr->nLeTerm = sqlite3_value_bytes(pLe);
196667  pCsr->zLeTerm = sqlite3_malloc(pCsr->nLeTerm+1);
196668  if( pCsr->zLeTerm==0 ){
196669  rc = SQLITE_NOMEM;
196670  }else{
196671  memcpy(pCsr->zLeTerm, zCopy, pCsr->nLeTerm+1);
196672  }
196673  }
196674  }
196675 
196676 
196677  if( rc==SQLITE_OK ){
196678  rc = sqlite3Fts5IndexQuery(pCsr->pIndex, zTerm, nTerm, f, 0, &pCsr->pIter);
196679  }
196680  if( rc==SQLITE_OK ){
196681  rc = fts5VocabNextMethod(pCursor);
196682  }
196683 
196684  return rc;
196685 }
196686 
196687 /*
196688 ** This is the xEof method of the virtual table. SQLite calls this
196689 ** routine to find out if it has reached the end of a result set.
196690 */
196691 static int fts5VocabEofMethod(sqlite3_vtab_cursor *pCursor){
196692  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196693  return pCsr->bEof;
196694 }
196695 
196696 static int fts5VocabColumnMethod(
196697  sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
196698  sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
196699  int iCol /* Index of column to read value from */
196700 ){
196701  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196702  int eDetail = pCsr->pConfig->eDetail;
196703  int eType = ((Fts5VocabTable*)(pCursor->pVtab))->eType;
196704  i64 iVal = 0;
196705 
196706  if( iCol==0 ){
196708  pCtx, (const char*)pCsr->term.p, pCsr->term.n, SQLITE_TRANSIENT
196709  );
196710  }else if( eType==FTS5_VOCAB_COL ){
196711  assert( iCol==1 || iCol==2 || iCol==3 );
196712  if( iCol==1 ){
196713  if( eDetail!=FTS5_DETAIL_NONE ){
196714  const char *z = pCsr->pConfig->azCol[pCsr->iCol];
196715  sqlite3_result_text(pCtx, z, -1, SQLITE_STATIC);
196716  }
196717  }else if( iCol==2 ){
196718  iVal = pCsr->aDoc[pCsr->iCol];
196719  }else{
196720  iVal = pCsr->aCnt[pCsr->iCol];
196721  }
196722  }else{
196723  assert( iCol==1 || iCol==2 );
196724  if( iCol==1 ){
196725  iVal = pCsr->aDoc[0];
196726  }else{
196727  iVal = pCsr->aCnt[0];
196728  }
196729  }
196730 
196731  if( iVal>0 ) sqlite3_result_int64(pCtx, iVal);
196732  return SQLITE_OK;
196733 }
196734 
196735 /*
196736 ** This is the xRowid method. The SQLite core calls this routine to
196737 ** retrieve the rowid for the current row of the result set. The
196738 ** rowid should be written to *pRowid.
196739 */
196740 static int fts5VocabRowidMethod(
196741  sqlite3_vtab_cursor *pCursor,
196742  sqlite_int64 *pRowid
196743 ){
196744  Fts5VocabCursor *pCsr = (Fts5VocabCursor*)pCursor;
196745  *pRowid = pCsr->rowid;
196746  return SQLITE_OK;
196747 }
196748 
196749 static int sqlite3Fts5VocabInit(Fts5Global *pGlobal, sqlite3 *db){
196750  static const sqlite3_module fts5Vocab = {
196751  /* iVersion */ 2,
196752  /* xCreate */ fts5VocabCreateMethod,
196753  /* xConnect */ fts5VocabConnectMethod,
196754  /* xBestIndex */ fts5VocabBestIndexMethod,
196755  /* xDisconnect */ fts5VocabDisconnectMethod,
196756  /* xDestroy */ fts5VocabDestroyMethod,
196757  /* xOpen */ fts5VocabOpenMethod,
196758  /* xClose */ fts5VocabCloseMethod,
196759  /* xFilter */ fts5VocabFilterMethod,
196760  /* xNext */ fts5VocabNextMethod,
196761  /* xEof */ fts5VocabEofMethod,
196762  /* xColumn */ fts5VocabColumnMethod,
196763  /* xRowid */ fts5VocabRowidMethod,
196764  /* xUpdate */ 0,
196765  /* xBegin */ 0,
196766  /* xSync */ 0,
196767  /* xCommit */ 0,
196768  /* xRollback */ 0,
196769  /* xFindFunction */ 0,
196770  /* xRename */ 0,
196771  /* xSavepoint */ 0,
196772  /* xRelease */ 0,
196773  /* xRollbackTo */ 0,
196774  };
196775  void *p = (void*)pGlobal;
196776 
196777  return sqlite3_create_module_v2(db, "fts5vocab", &fts5Vocab, p, 0);
196778 }
196779 
196780 
196781 
196782 
196783 
196784 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS5) */
196785 
196786 /************** End of fts5.c ************************************************/
static int selectExpander(Walker *pWalker, Select *p)
Definition: sqlite3.c:117026
#define TK_UPDATE
Definition: sqlite3.c:11210
SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *)
Definition: sqlite3.c:24040
int bNot
Definition: sqlite3.c:130719
sqlite3_file * pFd
Definition: sqlite3.c:56049
static void destroyRootPage(Parse *pParse, int iTable, int iDb)
Definition: sqlite3.c:99067
SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *, Mem *)
Definition: sqlite3.c:69005
SQLITE_PRIVATE void sqlite3StatusHighwater(int, int)
Definition: sqlite3.c:18064
int nChunkSize
Definition: sqlite3.c:86886
int nOBSat
Definition: sqlite3.c:112856
#define pcache1
Definition: sqlite3.c:44140
SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *, int onoff)
Definition: sqlite3.c:139019
#define ISAUTOVACUUM
Definition: sqlite3.c:57331
#define SQLITE_SYNC_MASK
Definition: sqlite3.c:45716
AggInfo * pAggInfo
Definition: sqlite3.c:14997
static u16 operatorMask(int op)
Definition: sqlite3.c:124697
#define SQLITE_MAX_ATTACHED
Definition: sqlite3.c:10582
u32 minFrame
Definition: sqlite3.c:53662
SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *)
Definition: sqlite3.c:116705
void * pTraceArg
Definition: sqlite3.c:13711
static int unixSectorSize(sqlite3_file *NotUsed)
Definition: sqlite3.c:32962
#define TK_AUTOINCR
Definition: sqlite3.c:11206
static const char * unixNextSystemCall(sqlite3_vfs *p, const char *zName)
Definition: sqlite3.c:29684
SQLITE_PRIVATE void sqlite3BeginTrigger(Parse *, Token *, Token *, int, int, IdList *, SrcList *, Expr *, int, int)
Definition: sqlite3.c:118773
#define EXTRA_SIZE
Definition: sqlite3.c:56985
SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *)
Definition: sqlite3.c:89309
static int pushDownWhereTerms(sqlite3 *db, Select *pSubq, Expr *pWhere, int iCursor)
Definition: sqlite3.c:116584
const Token * pName
Definition: sqlite3.c:15532
SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *)
Definition: sqlite3.c:68745
SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse *, Table *, int, int, int, int *, int, int, int)
Definition: sqlite3.c:107464
#define OPFLG_IN1
Definition: sqlite3.c:12506
SQLITE_PRIVATE void sqlite3DeleteColumnNames(sqlite3 *, Table *)
Definition: sqlite3.c:97326
int(* xFindTokenizer)(fts5_api *pApi, const char *zName, void **ppContext, fts5_tokenizer *pTokenizer)
Definition: sqlite3.c:10412
#define OP_Expire
Definition: sqlite3.c:12487
#define SQLITE_INDEX_SCAN_UNIQUE
Definition: sqlite3.c:6050
void * pAux
Definition: sqlite3.c:17695
#define PTRMAP_PAGENO(pBt, pgno)
Definition: sqlite3.c:57274
#define osOpen
#define sqlite3Isalpha(x)
Definition: sqlite3.c:15779
SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(const char *filename, sqlite3 **ppDb, int flags, const char *zVfs)
Definition: sqlite3.c:138646
#define SQLITE_MUTEX_STATIC_MASTER
Definition: sqlite3.c:6705
static int pagerOpentemp(Pager *pPager, sqlite3_file *pFile, int vfsFlags)
Definition: sqlite3.c:49390
#define EP_IntValue
Definition: sqlite3.c:14724
u8 sharable
Definition: sqlite3.c:57030
#define UNIXFILE_RDONLY
Definition: sqlite3.c:29167
static int vdbeCompareMemString(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl, u8 *prcErr)
Definition: sqlite3.c:73571
SQLITE_PRIVATE int sqlite3BtreeCursor(Btree *, int iTable, int wrFlag, struct KeyInfo *, BtCursor *pCursor)
Definition: sqlite3.c:61817
void(* xDlClose)(sqlite3_vfs *, void *)
Definition: sqlite3.c:1464
SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75502
#define YY_MAX_REDUCE
Definition: sqlite3.c:130964
#define SQLITE_CANTOPEN_FULLPATH
Definition: sqlite3.c:739
int(* xClose)(sqlite3_file *)
Definition: sqlite3.c:987
SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *)
Definition: sqlite3.c:76042
#define OPFLAG_SAVEPOSITION
Definition: sqlite3.c:15427
static void fkScanChildren(Parse *pParse, SrcList *pSrc, Table *pTab, Index *pIdx, FKey *pFKey, int *aiCol, int regData, int nIncr)
Definition: sqlite3.c:104935
u8 * apOvfl[5]
Definition: sqlite3.c:56968
#define SQLITE_READONLY
Definition: sqlite3.c:665
static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem)
Definition: sqlite3.c:76881
#define CODEC2(P, D, N, X, E, O)
Definition: sqlite3.c:46236
#define SQLITE_ABORT
Definition: sqlite3.c:661
#define COLNAME_TABLE
Definition: sqlite3.c:12311
#define FLAG_INTERN
Definition: sqlite3.c:24500
SQLITE_PRIVATE struct Pager * sqlite3BtreePager(Btree *)
Definition: sqlite3.c:66483
int nFunc
Definition: sqlite3.c:14585
static int robust_ftruncate(int h, sqlite3_int64 sz)
Definition: sqlite3.c:29874
struct WherePath WherePath
Definition: sqlite3.c:122275
static int parseDateOrTime(sqlite3_context *context, const char *zDate, DateTime *p)
Definition: sqlite3.c:18648
#define TK_AFTER
Definition: sqlite3.c:11159
Select * pSelect
Definition: sqlite3.c:15511
Expr * pLimit
Definition: sqlite3.c:130709
int aiCurOnePass[2]
Definition: sqlite3.c:122662
SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int)
Definition: sqlite3.c:137867
FuncDef * pNext
Definition: sqlite3.c:13902
#define IsPowerOfTwo(X)
Definition: sqlite3.c:11713
static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock)
Definition: sqlite3.c:30846
#define CC_RP
Definition: sqlite3.c:134362
char * zJournal
Definition: sqlite3.c:46504
#define SQLITE_SHM_UNLOCK
Definition: sqlite3.c:1534
#define OpenCounter(X)
Definition: sqlite3.c:29374
static void unixShmBarrier(sqlite3_file *fd)
Definition: sqlite3.c:33729
SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *, int)
Definition: sqlite3.c:68846
SQLITE_PRIVATE IdList * sqlite3IdListAppend(sqlite3 *, IdList *, Token *)
Definition: sqlite3.c:100325
char * zBase
Definition: sqlite3.c:15541
#define IN_INDEX_NOOP
Definition: sqlite3.c:16541
static const FuncDef statPushFuncdef
Definition: sqlite3.c:94798
Token eOperator
Definition: sqlite3.c:130718
static void sqlite3MallocAlarm(int nByte)
Definition: sqlite3.c:23820
int errMask
Definition: sqlite3.c:13677
#define PAGER_MAX_PGNO
Definition: sqlite3.c:46615
#define PAGER_INCR(v)
Definition: sqlite3.c:46546
int walkerDepth
Definition: sqlite3.c:15656
#define SQLITE_FUNC_LENGTH
Definition: sqlite3.c:13950
#define unlikely(X)
Definition: sqlite3.c:10996
#define TK_AGG_COLUMN
Definition: sqlite3.c:11254
#define SQLITE_FUNC_SLOCHNG
Definition: sqlite3.c:13957
ExprList * pGroupBy
Definition: sqlite3.c:15053
static void insertElement(Hash *pH, struct _ht *pEntry, HashElem *pNew)
Definition: sqlite3.c:28517
u32 selFlags
Definition: sqlite3.c:15045
SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *)
Definition: sqlite3.c:96809
u32 aWalData[WAL_SAVEPOINT_NDATA]
Definition: sqlite3.c:46269
SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *)
Definition: sqlite3.c:55604
etByte charset
Definition: sqlite3.c:24492
#define SQLITE_LOCKED
Definition: sqlite3.c:663
static void verifyDbFile(unixFile *pFile)
Definition: sqlite3.c:30454
int nIndent
Definition: sqlite3.c:17733
static int btreeSetHasContent(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:58220
static void parserDoubleLinkSelect(Parse *pParse, Select *p)
Definition: sqlite3.c:130753
SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *)
Definition: sqlite3.c:76853
#define PTF_INTKEY
Definition: sqlite3.c:56932
static int copyPayload(void *pPayload, void *pBuf, int nByte, int eOp, DbPage *pDbPage)
Definition: sqlite3.c:62064
Btree * pBt
Definition: sqlite3.c:13510
static int memjrnlCreateFile(MemJournal *p)
Definition: sqlite3.c:86967
SQLITE_PRIVATE const char * sqlite3BtreeGetJournalname(Btree *)
Definition: sqlite3.c:67124
#define SF_MinMaxAgg
Definition: sqlite3.c:15084
#define SQLITE_DBSTATUS_CACHE_HIT
Definition: sqlite3.c:7072
Select * pSelect
Definition: sqlite3.c:15695
BtShared * pNext
Definition: sqlite3.c:57120
u32 pageSize
Definition: sqlite3.c:57110
SQLITE_PRIVATE void sqlite3Put4byte(u8 *, u32)
u64 Bitmask
Definition: sqlite3.c:14857
static void spanUnaryPrefix(ExprSpan *pOut, Parse *pParse, int op, ExprSpan *pOperand, Token *pPreOp)
Definition: sqlite3.c:130836
u8 eCreate
Definition: sqlite3.c:43101
SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix)
Definition: sqlite3.c:60312
#define OP_Init
Definition: sqlite3.c:12408
static int pager_truncate(Pager *pPager, Pgno nPage)
Definition: sqlite3.c:48381
#define SWAP(TYPE, A, B)
Definition: sqlite3.c:11388
#define SQLITE_MAX_PAGE_SIZE
Definition: sqlite3.c:10607
SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *, double)
Definition: sqlite3.c:68885
#define WHERE_COLUMN_IN
Definition: sqlite3.c:122763
Trigger * pNewTrigger
Definition: sqlite3.c:15366
#define SQLITE_READ
Definition: sqlite3.c:2989
#define WAL_HEAPMEMORY_MODE
Definition: sqlite3.c:53679
GLint level
u8 printfFlags
Definition: sqlite3.c:15547
SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *)
Definition: sqlite3.c:19720
Pgno dbOrigSize
Definition: sqlite3.c:46470
static void setStrAccumError(StrAccum *p, u8 eError)
Definition: sqlite3.c:24575
#define put32bits(A, B)
Definition: sqlite3.c:46888
static SQLITE_WSD struct sqlite3StatType sqlite3Stat
#define UNIXFILE_DELETE
Definition: sqlite3.c:29175
#define VdbeCoverage(v)
Definition: sqlite3.c:12674
SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(sqlite3 *, const char *zName, int eTextRep, void *pArg, int(*xCompare)(void *, int, const void *, int, const void *))
Definition: sqlite3.c:138698
#define SQLITE_DROP_VTABLE
Definition: sqlite3.c:2999
#define OP_Function
Definition: sqlite3.c:12427
static int pagerUnlockDb(Pager *pPager, int eLock)
Definition: sqlite3.c:46910
#define PragTyp_FOREIGN_KEY_CHECK
Definition: sqlite3.c:109533
MergeEngine * pMerger
Definition: sqlite3.c:84388
#define etDYNSTRING
Definition: sqlite3.c:24462
SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *, int)
Definition: sqlite3.c:19568
static int vdbePmaReaderIncrInit(PmaReader *pReadr, int eMode)
Definition: sqlite3.c:86328
Pgno nPage
Definition: sqlite3.c:57352
#define MEM_Str
Definition: sqlite3.c:17636
#define TF_NoVisibleRowid
Definition: sqlite3.c:14244
struct RowSetEntry * pLast
Definition: sqlite3.c:45276
SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id)
Definition: sqlite3.c:19618
sqlite3_mem_methods m
Definition: sqlite3.c:15585
static void sqlite3SkipAccumulatorLoad(sqlite3_context *context)
Definition: sqlite3.c:102607
FuncDef * pFunc
Definition: sqlite3.c:17715
#define OP_And
Definition: sqlite3.c:12367
SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff)
Definition: sqlite3.c:109299
static int isLookaside(sqlite3 *db, void *p)
Definition: sqlite3.c:24007
#define OP_ResetSorter
Definition: sqlite3.c:12469
int n
Definition: sqlite3.c:17603
u8 padToSectorBoundary
Definition: sqlite3.c:53660
Bitvec * pInJournal
Definition: sqlite3.c:46477
#define TK_COMMA
Definition: sqlite3.c:11126
#define SQLITE_LoadExtFunc
Definition: sqlite3.c:13829
#define WRC_Abort
Definition: sqlite3.c:15683
static const char * explainIndexColumnName(Index *pIdx, int i)
Definition: sqlite3.c:122808
static int moveToRoot(BtCursor *pCur)
Definition: sqlite3.c:62518
u32 aReadMark[WAL_NREADER]
Definition: sqlite3.c:53595
StrAccum errMsg
Definition: sqlite3.c:57358
#define NC_IdxExpr
Definition: sqlite3.c:15017
Schema * pTabSchema
Definition: sqlite3.c:15454
SrcList * pSrcList
Definition: sqlite3.c:14995
SorterList list
Definition: sqlite3.c:84365
#define WAL_RETRY
Definition: sqlite3.c:55339
#define BTREE_FORDELETE
Definition: sqlite3.c:12048
#define O_NOFOLLOW
Definition: sqlite3.c:29393
SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *)
Definition: sqlite3.c:57661
SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *)
Definition: sqlite3.c:109446
struct WhereLoop * pWLoop
Definition: sqlite3.c:122325
#define OP_ShiftRight
Definition: sqlite3.c:12385
#define wsdHooks
Definition: sqlite3.c:19939
struct SorterRecord SorterRecord
Definition: sqlite3.c:84228
SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *)
Definition: sqlite3.c:52936
#define EP_xIsSelect
Definition: sqlite3.c:14725
SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *, int)
Definition: sqlite3.c:19576
static int pager_playback(Pager *pPager, int isHot)
Definition: sqlite3.c:48524
Bitmask indexable
Definition: sqlite3.c:122569
void * pKey
Definition: sqlite3.c:57188
SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value *)
Definition: sqlite3.c:74693
#define TK_VACUUM
Definition: sqlite3.c:11189
SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *)
Definition: sqlite3.c:97300
#define DFUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:14000
static int unixShmUnmap(sqlite3_file *fd, int deleteFlag)
Definition: sqlite3.c:33745
static SQLITE_WSD struct sqlite3PrngType sqlite3Prng
static const unsigned char sqlite3Utf8Trans1[]
Definition: sqlite3.c:26495
#define SQLITE_CONFIG_GETMUTEX
Definition: sqlite3.c:2101
static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut)
Definition: sqlite3.c:84645
static int vdbeRecordCompareString(int nKey1, const void *pKey1, UnpackedRecord *pPKey2)
Definition: sqlite3.c:74082
static int accessPayload(BtCursor *pCur, u32 offset, u32 amt, unsigned char *pBuf, int eOp)
Definition: sqlite3.c:62115
static void pcache1Cachesize(sqlite3_pcache *p, int nMax)
Definition: sqlite3.c:44700
SQLITE_PRIVATE LogEst sqlite3WhereOutputRowCount(WhereInfo *)
Definition: sqlite3.c:125944
#define NC_MinMaxAgg
Definition: sqlite3.c:15019
Select * pSelect
Definition: sqlite3.c:14685
SQLITE_PRIVATE int sqlite3VdbeAddOp4Dup8(Vdbe *, int, int, int, int, const u8 *, int)
Definition: sqlite3.c:70175
int nTab
Definition: sqlite3.c:15291
#define MEMCELLSIZE
Definition: sqlite3.c:17621
#define IsUniqueIndex(X)
Definition: sqlite3.c:14510
unixShmNode * pShmNode
Definition: sqlite3.c:30180
GLboolean GLboolean GLboolean b
#define TK_FLOAT
Definition: sqlite3.c:11233
#define VdbeBranchTaken(I, M)
Definition: sqlite3.c:76667
#define COLFLAG_HASTYPE
Definition: sqlite3.c:14072
union Mem::MemValue u
#define OP_IdxGE
Definition: sqlite3.c:12398
ExprList * pGroupBy
Definition: sqlite3.c:14566
int(* xRead)(sqlite3_file *, void *, int iAmt, sqlite3_int64 iOfst)
Definition: sqlite3.c:988
const char ** azColl
Definition: sqlite3.c:14475
static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit)
Definition: sqlite3.c:45034
#define SQLITE_BIGENDIAN
Definition: sqlite3.c:11565
#define sqlite3_column_table_name16
Definition: sqlite3.c:108728
#define MEMDB
Definition: sqlite3.c:46599
#define UINT8_TYPE
Definition: sqlite3.c:11432
static int checkTreePage(IntegrityCk *pCheck, int iPage, i64 *piMinKey, i64 maxKey)
Definition: sqlite3.c:66728
static int dupedExprSize(Expr *p, int flags)
Definition: sqlite3.c:89757
ExprList * pList
Definition: sqlite3.c:14684
SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *)
Definition: sqlite3.c:22248
#define SQLITE_EXPERIMENTAL
Definition: sqlite3.c:327
int busyTimeout
Definition: sqlite3.c:13761
SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse *, ExprList *, int, int, int)
Definition: sqlite3.c:98040
int eFWErr
Definition: sqlite3.c:84480
SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db)
Definition: sqlite3.c:121892
#define WHERE_TOP_LIMIT
Definition: sqlite3.c:122766
static void transferParseError(Parse *pTo, Parse *pFrom)
Definition: sqlite3.c:119465
char * zText
Definition: sqlite3.c:15542
#define BTCURSOR_MAX_DEPTH
Definition: sqlite3.c:57160
#define WHERE_ONEPASS_MULTIROW
Definition: sqlite3.c:14961
static int robust_open(const char *z, int f, mode_t m)
Definition: sqlite3.c:29725
GLint y
u8 suppressErr
Definition: sqlite3.c:13687
#define PTRMAP_OVERFLOW2
Definition: sqlite3.c:57312
#define WHERE_ORDERBY_MIN
Definition: sqlite3.c:14948
#define swapMixedEndianFloat(X)
Definition: sqlite3.c:73147
struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]
Definition: sqlite3.c:45264
BtShared * pBt
Definition: sqlite3.c:57183
int(* xSectorSize)(sqlite3_file *)
Definition: sqlite3.c:997
char * zMalloc
Definition: sqlite3.c:17606
#define OP_IfNotZero
Definition: sqlite3.c:12404
Definition: sqlite3.c:53642
#define SQLITE_DBCONFIG_ENABLE_TRIGGER
Definition: sqlite3.c:2208
static void changes(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103111
#define OP_RowSetTest
Definition: sqlite3.c:12400
#define DB_SchemaLoaded
Definition: sqlite3.c:13566
#define WO_OR
Definition: sqlite3.c:122748
SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag)
Definition: sqlite3.c:18110
static int checkColumnOverlap(IdList *pIdList, ExprList *pEList)
Definition: sqlite3.c:119294
static int pageFreeArray(MemPage *pPg, int iFirst, int nCell, CellArray *pCArray)
Definition: sqlite3.c:64245
#define JT_NATURAL
Definition: sqlite3.c:14933
#define SQLITE_NULLEQ
Definition: sqlite3.c:14137
SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal)
Definition: sqlite3.c:55828
#define ADDR(X)
Definition: sqlite3.c:12329
PgHdr1 * pLruPrev
Definition: sqlite3.c:44029
#define SQLITE_STMTSTATUS_AUTOINDEX
Definition: sqlite3.c:7144
#define VdbeFrameMem(p)
Definition: sqlite3.c:17579
#define TK_RESTRICT
Definition: sqlite3.c:11186
int nChildCsr
Definition: sqlite3.c:17574
#define EP_Subquery
Definition: sqlite3.c:14735
static int sqlite3Step(Vdbe *p)
Definition: sqlite3.c:74994
#define TRACE(X)
Definition: sqlite3.c:57702
static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2)
Definition: sqlite3.c:73608
struct WalWriter WalWriter
#define MAX_SECTOR_SIZE
Definition: sqlite3.c:46245
PgHdr1 lru
Definition: sqlite3.c:44060
#define SQLITE_FULL
Definition: sqlite3.c:670
#define TK_PRIMARY
Definition: sqlite3.c:11202
#define SQLITE_OPEN_MAIN_JOURNAL
Definition: sqlite3.c:780
#define osFcntl
#define FUNC_PERFECT_MATCH
Definition: sqlite3.c:101432
static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p)
Definition: sqlite3.c:124582
#define EP_CanBeNull
Definition: sqlite3.c:14734
#define PragTyp_STATS
Definition: sqlite3.c:109549
SQLITE_PRIVATE void * sqlite3PagerTempSpace(Pager *)
Definition: sqlite3.c:49538
#define SQLITE_IOERR_MMAP
Definition: sqlite3.c:729
Expr * pDflt
Definition: sqlite3.c:14060
yDbMask cookieMask
Definition: sqlite3.c:15315
void * pArg
Definition: sqlite3.c:11682
static void trimFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103808
#define PAGERID(p)
Definition: sqlite3.c:45947
static int checkForMultiColumnSelectError(Parse *pParse, SelectDest *pDest, int nExpr)
Definition: sqlite3.c:113452
#define OP_ResetCount
Definition: sqlite3.c:12455
#define SQLITE_QueryOnly
Definition: sqlite3.c:13832
unsigned int htsize
Definition: sqlite3.c:11043
tRowcnt * anEq
Definition: sqlite3.c:14526
u8 notNull
Definition: sqlite3.c:14062
static int whereLoopResize(sqlite3 *, WhereLoop *, int)
Definition: sqlite3.c:127654
#define FOUR_BYTE_INT(x)
Definition: sqlite3.c:73206
static SQLITE_NOINLINE int valueBytes(sqlite3_value *pVal, u8 enc)
Definition: sqlite3.c:69870
#define YY_SHIFT_MIN
Definition: sqlite3.c:131344
SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64)
Definition: sqlite3.c:84032
char ** azVar
Definition: sqlite3.c:17776
yDbMask btreeMask
Definition: sqlite3.c:17798
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:121484
LogEst nRowLogEst
Definition: sqlite3.c:14209
sqlite_uint64 u64
Definition: sqlite3.c:11446
u8 memDb
Definition: sqlite3.c:46450
SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *)
Definition: sqlite3.c:71313
static int sqlite3MemInit(void *NotUsed)
Definition: sqlite3.c:20274
#define SQLITE_STATUS_PAGECACHE_SIZE
Definition: sqlite3.c:6946
#define PAGER_LOCKINGMODE_NORMAL
Definition: sqlite3.c:12759
#define OP_PrevIfOpen
Definition: sqlite3.c:12343
char * table
Definition: sqlite3.c:15447
#define SETBIT(V, I)
Definition: sqlite3.c:42940
SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *)
Definition: sqlite3.c:91505
SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *, SrcList *)
Definition: sqlite3.c:100510
SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *)
Definition: sqlite3.c:42914
static void vfsUnlink(sqlite3_vfs *pVfs)
Definition: sqlite3.c:19826
SQLITE_API char * sqlite3_temp_directory
Definition: sqlite3.c:5284
SQLITE_PRIVATE void sqlite3WhereExprAnalyze(SrcList *, WhereClause *)
Definition: sqlite3.c:125859
union SorterRecord::@134 u
u32 aSalt[2]
Definition: sqlite3.c:53530
SQLITE_PRIVATE int sqlite3PagerOpen(sqlite3_vfs *, Pager **ppPager, const char *, int, int, int, void(*)(DbPage *))
Definition: sqlite3.c:50385
#define TKFLG_MASK
Definition: sqlite3.c:11264
static PgHdr1 * pcache1AllocPage(PCache1 *pCache, int benignMalloc)
Definition: sqlite3.c:44324
#define SQLITE_MAX_VARIABLE_NUMBER
Definition: sqlite3.c:10590
SQLITE_PRIVATE void sqlite3AlterFunctions(void)
Definition: sqlite3.c:93446
SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N)
Definition: sqlite3.c:137573
#define SQLITE_FUNC_TYPEOF
Definition: sqlite3.c:13951
SQLITE_PRIVATE void sqlite3PagerRef(DbPage *)
Definition: sqlite3.c:49905
SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value *)
Definition: sqlite3.c:74679
SQLITE_PRIVATE void sqlite3RegisterPerConnectionBuiltinFunctions(sqlite3 *)
Definition: sqlite3.c:104192
SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *)
Definition: sqlite3.c:100711
#define SQLITE_DEFAULT_MEMSTATUS
Definition: sqlite3.c:10782
static int btreeMoveto(BtCursor *pCur, const void *pKey, i64 nKey, int bias, int *pRes)
Definition: sqlite3.c:58420
static int unixFileSize(sqlite3_file *id, i64 *pSize)
Definition: sqlite3.c:32743
static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs)
Definition: sqlite3.c:70444
Select * pSelect
Definition: sqlite3.c:14200
#define SQLITE_TEXT
Definition: sqlite3.c:4225
#define SQLITE_PTR_TO_INT(X)
Definition: sqlite3.c:10710
Pgno pgnoRoot
Definition: sqlite3.c:17494
u16 omitMask
Definition: sqlite3.c:122366
static void decodeIntArray(char *zIntArray, int nOut, tRowcnt *aOut, LogEst *aLog, Index *pIndex)
Definition: sqlite3.c:95441
#define SQLITE_TOOBIG
Definition: sqlite3.c:675
#define TK_RSHIFT
Definition: sqlite3.c:11146
SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte)
Definition: sqlite3.c:26826
u8 curIntKey
Definition: sqlite3.c:57201
SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *, i64 *pSize)
Definition: sqlite3.c:61946
SQLITE_PRIVATE sqlite3_mutex * sqlite3Pcache1Mutex(void)
Definition: sqlite3.c:45100
u8 notUsed1
Definition: sqlite3.c:12211
SQLITE_API int SQLITE_CDECL sqlite3_config(int,...)
Definition: sqlite3.c:135948
static int SQLITE_NOINLINE saveCursorsOnList(BtCursor *, Pgno, BtCursor *)
Definition: sqlite3.c:58383
u32 expmask
Definition: sqlite3.c:17814
SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL 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 *)
SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *, int N)
Definition: sqlite3.c:75602
#define OP_BitOr
Definition: sqlite3.c:12383
static int unixSetSystemCall(sqlite3_vfs *pNotUsed, const char *zName, sqlite3_syscall_ptr pNewFunc)
Definition: sqlite3.c:29622
#define MEM_Real
Definition: sqlite3.c:17638
SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *, u8 flags)
Definition: sqlite3.c:65786
#define SQLITE_LIMIT_ATTACHED
Definition: sqlite3.c:3536
#define SQLITE_MAX_DEFAULT_PAGE_SIZE
Definition: sqlite3.c:10629
#define SQLITE_RANGE
Definition: sqlite3.c:682
#define BTALLOC_EXACT
Definition: sqlite3.c:57720
SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *)
Definition: sqlite3.c:55808
static int identLength(const char *z)
Definition: sqlite3.c:98238
#define isMalloced(X)
Definition: sqlite3.c:15555
#define SQLITE_IOERR_TRUNCATE
Definition: sqlite3.c:711
#define osPwrite
#define sqlite3Isquote(x)
Definition: sqlite3.c:15783
#define SQLITE_CORRUPT
Definition: sqlite3.c:668
int(* xCurrentTime)(sqlite3_vfs *, double *)
Definition: sqlite3.c:1467
#define CURSOR_FAULT
Definition: sqlite3.c:57252
#define SRT_Table
Definition: sqlite3.c:15173
int nByte
Definition: sqlite3.c:83584
#define OP_NotNull
Definition: sqlite3.c:12374
static void freePage(MemPage *pPage, int *pRC)
Definition: sqlite3.c:63650
VdbeFrame * pParent
Definition: sqlite3.c:17559
static struct RowSetEntry * rowSetNDeepTree(struct RowSetEntry **ppList, int iDepth)
Definition: sqlite3.c:45501
#define osPread64
#define DbMaskAllZero(M)
Definition: sqlite3.c:15252
list Z
Definition: rmse.py:133
sqlite3 * db
Definition: sqlite3.c:17761
static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg)
Definition: sqlite3.c:91393
SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse *, Token *, Token *, Token *, int)
Definition: sqlite3.c:121311
#define P4_TABLE
Definition: sqlite3.c:12295
SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *, int *pRes)
Definition: sqlite3.c:63058
WhereClause * pWC
Definition: sqlite3.c:122494
#define CC_ID
Definition: sqlite3.c:134346
sqlite3_file * pFd
Definition: sqlite3.c:84486
SQLITE_API int SQLITE_STDCALL sqlite3_db_cacheflush(sqlite3 *)
Definition: sqlite3.c:136351
typedef void(APIENTRY *GLDEBUGPROC)(GLenum source
#define THREE_BYTE_INT(x)
Definition: sqlite3.c:73204
AggInfo * pAggInfo
Definition: sqlite3.c:14707
static SQLITE_NOINLINE int pagerOpenSavepoint(Pager *pPager, int nSavepoint)
Definition: sqlite3.c:52387
#define MEM_TypeMask
Definition: sqlite3.c:17645
static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p)
Definition: sqlite3.c:33986
#define MUTEX_LOGIC(X)
Definition: sqlite3.c:13464
tRowcnt * anDLt
Definition: sqlite3.c:14528
#define columnType(A, B, C, D, E, F)
Definition: sqlite3.c:114138
#define wsdPrng
ExprList * pDistinctSet
Definition: sqlite3.c:122646
u8 eLock
Definition: sqlite3.c:46462
#define SQLITE_FILE_HEADER
Definition: sqlite3.c:56925
#define SQLITE_MUTEX_STATIC_VFS3
Definition: sqlite3.c:6718
#define COLUMN_MASK(x)
Definition: sqlite3.c:105444
SQLITE_PRIVATE void sqlite3ParserFree(void *, void(*)(void *))
Definition: sqlite3.c:132265
int orconf
Definition: sqlite3.c:15233
#define OP_NotFound
Definition: sqlite3.c:12369
#define WHERE_LOOP_XFER_SZ
Definition: sqlite3.c:122374
static void total_changes(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103125
#define TK_ORDER
Definition: sqlite3.c:11226
#define SQLITE_FCNTL_BUSYHANDLER
Definition: sqlite3.c:1258
SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75497
#define STAT_GET_NLT
Definition: sqlite3.c:94812
bft explain
Definition: sqlite3.c:17790
#define BTALLOC_LE
Definition: sqlite3.c:57721
PmaReader * pReader
Definition: sqlite3.c:84387
#define OP_Not
Definition: sqlite3.c:12358
#define OP_Real
Definition: sqlite3.c:12472
static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr)
Definition: sqlite3.c:83612
#define SQLITE_CONFIG_GETPCACHE2
Definition: sqlite3.c:2109
#define SQLITE3_MUTEX_INITIALIZER
Definition: sqlite3.c:22585
u8 walSyncFlags
Definition: sqlite3.c:46445
#define TK_DOT
Definition: sqlite3.c:11222
#define TERM_VIRTUAL
Definition: sqlite3.c:122503
int szSpill
Definition: sqlite3.c:43097
int(* xBegin)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:5906
ExprList * pOrderBy
Definition: sqlite3.c:122645
static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew)
Definition: sqlite3.c:127091
u32 uTemp
Definition: sqlite3.c:17608
SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(sqlite3 *, const char *zDb, const char *zTable, const char *zColumn, sqlite3_int64 iRow, int flags, sqlite3_blob **ppBlob)
Definition: sqlite3.c:83666
Table * pTable
Definition: sqlite3.c:14470
#define MEM_RowSet
Definition: sqlite3.c:17641
SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int, int *)
Definition: sqlite3.c:42974
int szMalloc
Definition: sqlite3.c:17607
SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int)
Definition: sqlite3.c:24424
SQLITE_PRIVATE Index * sqlite3CreateIndex(Parse *, Token *, Token *, SrcList *, ExprList *, int, Token *, Expr *, int, int)
Definition: sqlite3.c:99636
static void pcache1Destroy(sqlite3_pcache *p)
Definition: sqlite3.c:45049
int anStat[3]
Definition: sqlite3.c:13602
void(* xFinalize)(sqlite3_context *)
Definition: sqlite3.c:13904
SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName)
Definition: sqlite3.c:19802
#define PragFlag_NeedSchema
Definition: sqlite3.c:109563
static void btreeParseCellPtrIndex(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:58830
SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *)
Definition: sqlite3.c:137795
SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *, int)
Definition: sqlite3.c:89219
Mem * aColName
Definition: sqlite3.c:17765
#define WALTRACE(X)
Definition: sqlite3.c:53469
SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *, Table *)
Definition: sqlite3.c:97398
static int vdbeIncrPopulate(IncrMerger *pIncr)
Definition: sqlite3.c:85935
struct sqlite3_index_info::sqlite3_index_constraint * aConstraint
#define CC_BANG
Definition: sqlite3.c:134359
BtLock * pLock
Definition: sqlite3.c:57121
u8 checkSchema
Definition: sqlite3.c:15278
u8 tempFile
Definition: sqlite3.c:46447
SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *, int addr)
Definition: sqlite3.c:70674
#define SQLITE_DBSTATUS_CACHE_WRITE
Definition: sqlite3.c:7074
int szExtra
Definition: sqlite3.c:43099
void * pUpdateArg
Definition: sqlite3.c:13718
#define TK_BITNOT
Definition: sqlite3.c:11154
static void vdbePmaWriterInit(sqlite3_file *pFd, PmaWriter *p, int nBuf, i64 iStart)
Definition: sqlite3.c:85516
#define READ_UTF16BE(zIn, TERM, c)
Definition: sqlite3.c:26561
YYMINORTYPE minor
Definition: sqlite3.c:131613
#define PragTyp_BUSY_TIMEOUT
Definition: sqlite3.c:109523
#define EP_Resolved
Definition: sqlite3.c:14716
SQLITE_PRIVATE Expr * sqlite3Expr(sqlite3 *, int, const char *)
Definition: sqlite3.c:89396
#define SQLITE_UTF16BE
Definition: sqlite3.c:4589
static int writeMasterJournal(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:47442
SQLITE_PRIVATE PgHdr * sqlite3PcacheFetchFinish(PCache *, Pgno, sqlite3_pcache_page *pPage)
Definition: sqlite3.c:43532
int addrFirst
Definition: sqlite3.c:122305
static int getTempStore(const char *z)
Definition: sqlite3.c:110063
struct SrcList::SrcList_item a[1]
static void moveToParent(BtCursor *pCur)
Definition: sqlite3.c:62481
#define SF_Recursive
Definition: sqlite3.c:15085
SQLITE_PRIVATE int sqlite3FaultSim(int)
Definition: sqlite3.c:27022
SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *)
Definition: sqlite3.c:74619
i64 nStmtDefImmCons
Definition: sqlite3.c:17808
With * pWith
Definition: sqlite3.c:15060
bft runOnlyOnce
Definition: sqlite3.c:17792
static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p)
Definition: sqlite3.c:24068
SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64)
Definition: sqlite3.c:52958
BtLock * pNext
Definition: sqlite3.c:56998
SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *, ExprList *, int)
Definition: sqlite3.c:92812
KeyInfo * pKeyInfo
Definition: sqlite3.c:17504
SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager *, int(*)(void *), void *)
Definition: sqlite3.c:49429
#define TK_INITIALLY
Definition: sqlite3.c:11176
#define OP_IdxLT
Definition: sqlite3.c:12397
#define SQLITE_TEMP_FILE_PREFIX
Definition: sqlite3.c:13245
SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *, const char *z, int n, int)
Definition: sqlite3.c:69947
int bUnderPressure
Definition: sqlite3.c:44132
int(* xMutexTry)(sqlite3_mutex *)
Definition: sqlite3.c:6653
#define SQLITE_DEFAULT_SECTOR_SIZE
Definition: sqlite3.c:13220
SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int)
Definition: sqlite3.c:27286
sqlite3 * pSrcDb
Definition: sqlite3.c:67408
sqlite3_rtree_dbl rScore
Definition: sqlite3.c:8560
#define SQLITE_LoadExtension
Definition: sqlite3.c:13828
SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table *)
Definition: sqlite3.c:105768
GLenum const void * addr
Definition: glext.h:8864
SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *)
Definition: sqlite3.c:55706
static void returnSingleText(Vdbe *v, const char *zLabel, const char *zValue)
Definition: sqlite3.c:110145
#define WHERE_DISTINCTBY
Definition: sqlite3.c:14957
#define SQLITE_DROP_INDEX
Definition: sqlite3.c:2979
static int rebuildPage(MemPage *pPg, int nCell, u8 **apCell, u16 *szCell)
Definition: sqlite3.c:64130
#define JT_ERROR
Definition: sqlite3.c:14937
GLdouble GLdouble GLdouble top
static void computeHMS(DateTime *p)
Definition: sqlite3.c:18697
static int yy_find_reduce_action(int stateno, YYCODETYPE iLookAhead)
Definition: sqlite3.c:132360
SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int)
Definition: sqlite3.c:121962
#define SQLITE_FUNC_LIKE
Definition: sqlite3.c:13946
FileChunk * pNext
Definition: sqlite3.c:86856
#define P4_SUBPROGRAM
Definition: sqlite3.c:12293
#define SF_Values
Definition: sqlite3.c:15081
static SQLITE_NOINLINE void getCellInfo(BtCursor *pCur)
Definition: sqlite3.c:61913
u8 * aDataEnd
Definition: sqlite3.c:56971
Bitvec * pInSavepoint
Definition: sqlite3.c:46265
SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int)
Definition: sqlite3.c:57759
#define SQLITE_NullCallback
Definition: sqlite3.c:13813
GLint i1
Expr * pOffset
Definition: sqlite3.c:15059
#define assertParentIndex(x, y, z)
Definition: sqlite3.c:62470
static void pushOntoSorter(Parse *pParse, SortCtx *pSort, Select *pSelect, int regData, int regOrigData, int nData, int nPrefixReg)
Definition: sqlite3.c:113307
#define P4_DYNAMIC
Definition: sqlite3.c:12279
SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *, int, int *)
Definition: sqlite3.c:66171
i16 ynVar
Definition: sqlite3.c:14599
#define PragTyp_FLAG
Definition: sqlite3.c:109522
#define SQLITE_DBSTATUS_LOOKASIDE_HIT
Definition: sqlite3.c:7069
int nOnceFlag
Definition: sqlite3.c:17572
#define SQLITE_FUNC_HASH_SZ
Definition: sqlite3.c:13618
u8 childPtrSize
Definition: sqlite3.c:56957
SQLITE_PRIVATE sqlite3_value * sqlite3ValueNew(sqlite3 *)
Definition: sqlite3.c:69258
PgHdr * pDirty
Definition: sqlite3.c:43093
static int vdbeUnbind(Vdbe *p, int i)
Definition: sqlite3.c:75700
#define READ_UTF16LE(zIn, TERM, c)
Definition: sqlite3.c:26551
int(* xColumn)(sqlite3_vtab_cursor *, sqlite3_context *, int)
Definition: sqlite3.c:5903
int nExtension
Definition: sqlite3.c:13708
SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *, int, int, int *, int *)
Definition: sqlite3.c:137702
char * zCanonicalName
Definition: sqlite3.c:29945
int isPCacheInit
Definition: sqlite3.c:15608
static char * whereForeignKeys(Parse *pParse, Table *pTab)
Definition: sqlite3.c:93493
u16 nKeyCol
Definition: sqlite3.c:14480
static void compileoptiongetFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103511
IdList * pColumns
Definition: sqlite3.c:15451
#define CURTYPE_BTREE
Definition: sqlite3.c:17465
#define SQLITE_CREATE_TRIGGER
Definition: sqlite3.c:2976
static volatile WalCkptInfo * walCkptInfo(Wal *pWal)
Definition: sqlite3.c:53796
int(* xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor)
Definition: sqlite3.c:5897
#define SQLITE_NOMEM
Definition: sqlite3.c:664
Parse * pParse
Definition: sqlite3.c:15527
#define PAGER_JOURNALMODE_TRUNCATE
Definition: sqlite3.c:12773
static void unixShmPurge(unixFile *pFd)
Definition: sqlite3.c:33270
WhereClause * pWC
Definition: sqlite3.c:122622
static int btreeGetPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, int flags)
Definition: sqlite3.c:59588
#define PTF_LEAFDATA
Definition: sqlite3.c:56934
#define PragTyp_HEXKEY
Definition: sqlite3.c:109558
SQLITE_PRIVATE void sqlite3VdbeReusable(Vdbe *)
Definition: sqlite3.c:70289
#define TF_Virtual
Definition: sqlite3.c:14242
SQLITE_PRIVATE With * sqlite3WithAdd(Parse *, With *, Token *, ExprList *, Select *)
Definition: sqlite3.c:101117
SQLITE_PRIVATE int sqlite3ParseUri(const char *, const char *, unsigned int *, sqlite3_vfs **, char **, char **)
Definition: sqlite3.c:138083
#define VdbeCoverageIf(v, x)
Definition: sqlite3.c:12675
SQLITE_PRIVATE void * sqlite3DbRealloc(sqlite3 *, void *, u64)
Definition: sqlite3.c:24281
int nVtabLock
Definition: sqlite3.c:15354
static int pagerUseWal(Pager *pPager)
Definition: sqlite3.c:46636
#define SQLITE_MAGIC_OPEN
Definition: sqlite3.c:13881
#define WAL_NORMAL_MODE
Definition: sqlite3.c:53677
i64 iReadOff
Definition: sqlite3.c:84416
#define BTREE_DATA_VERSION
Definition: sqlite3.c:11977
SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs *, sqlite3_file *, const char *, int, i64, Wal **)
Definition: sqlite3.c:54494
GLdouble s
Pgno mxPgno
Definition: sqlite3.c:46501
#define assertTruncateConstraint(pPager)
Definition: sqlite3.c:49695
sqlite3_file * fd
Definition: sqlite3.c:46478
#define SQLITE_API
Definition: sqlite3.c:304
SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe *, Parse *)
Definition: sqlite3.c:71747
char affinity
Definition: sqlite3.c:14063
static struct RowSetEntry * rowSetListToTree(struct RowSetEntry *pList)
Definition: sqlite3.c:45537
#define IS_BIG_INT(X)
Definition: sqlite3.c:10986
static void walChecksumBytes(int nativeCksum, u8 *a, int nByte, const u32 *aIn, u32 *aOut)
Definition: sqlite3.c:53830
SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *, int)
Definition: sqlite3.c:75627
#define OP_RowSetRead
Definition: sqlite3.c:12399
bft usesStmtJournal
Definition: sqlite3.c:17793
u16 aiOvfl[5]
Definition: sqlite3.c:56966
SQLITE_PRIVATE void sqlite3RowidConstraint(Parse *, int, Table *)
Definition: sqlite3.c:100927
Btree * pNext
Definition: sqlite3.c:57036
SQLITE_PRIVATE int sqlite3BitvecTestNotNull(Bitvec *, u32)
Definition: sqlite3.c:42767
#define INT8_TYPE
Definition: sqlite3.c:11439
SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(sqlite3 *db, const char *zDb, int eMode, int *pnLog, int *pnCkpt)
Definition: sqlite3.c:137621
#define OP_NotExists
Definition: sqlite3.c:12371
void(* xDelUser)(void *)
Definition: sqlite3.c:8550
static void * allocSpace(struct ReusableSpace *p, void *pBuf, int nByte)
Definition: sqlite3.c:71671
long long current_time()
SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *, Select *)
Definition: sqlite3.c:87318
#define SQLITE_DEFAULT_AUTOVACUUM
Definition: sqlite3.c:11856
void *(* xDlOpen)(sqlite3_vfs *, const char *zFilename)
Definition: sqlite3.c:1461
Token sNameToken
Definition: sqlite3.c:15368
#define PragTyp_WAL_AUTOCHECKPOINT
Definition: sqlite3.c:109555
int nChildMem
Definition: sqlite3.c:17573
unsigned isResized
Definition: sqlite3.c:14486
SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *, int)
Definition: sqlite3.c:100784
#define OP_IdxRowid
Definition: sqlite3.c:12466
u8 max1bytePayload
Definition: sqlite3.c:56958
SQLITE_PRIVATE sqlite3_mutex * sqlite3MallocMutex(void)
Definition: sqlite3.c:23683
struct SrcCount * pSrcCount
Definition: sqlite3.c:15663
SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int, char *, const char *,...)
Definition: sqlite3.c:25455
int(* xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName, void(**pxFunc)(sqlite3_context *, int, sqlite3_value **), void **ppArg)
Definition: sqlite3.c:5910
Parse * pToplevel
Definition: sqlite3.c:15331
#define SRVAL(p)
Definition: sqlite3.c:84521
static void setJoinExpr(Expr *p, int iTable)
Definition: sqlite3.c:113176
LogEst truthProb
Definition: sqlite3.c:122489
int(* xFileControl)(sqlite3_file *, int op, void *pArg)
Definition: sqlite3.c:996
static void computeYMD(DateTime *p)
Definition: sqlite3.c:18671
SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *, i64 *)
Definition: sqlite3.c:45569
#define BTS_PAGESIZE_FIXED
Definition: sqlite3.c:57131
SrcList * pSrc
Definition: sqlite3.c:15051
static int sqlite3LockAndPrepare(sqlite3 *db, const char *zSql, int nBytes, int saveSqlFlag, Vdbe *pOld, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:112612
Vdbe * pReprepare
Definition: sqlite3.c:15363
SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void)
Definition: sqlite3.c:109424
#define BTREE_OMIT_JOURNAL
Definition: sqlite3.c:11886
tRowcnt nPSample
Definition: sqlite3.c:94307
#define SQLITE_NOTICE_RECOVER_ROLLBACK
Definition: sqlite3.c:758
unixInodeInfo * pInode
Definition: sqlite3.c:33126
#define PAGER_JOURNALMODE_QUERY
Definition: sqlite3.c:12769
#define SQLITE_TESTCTRL_ISKEYWORD
Definition: sqlite3.c:6809
#define TK_USING
Definition: sqlite3.c:11225
#define OP_Sort
Definition: sqlite3.c:12392
#define TK_ABORT
Definition: sqlite3.c:11157
VTable * pVtab
Definition: sqlite3.c:12226
SQLITE_PRIVATE void sqlite3AddColumn(Parse *, Token *, Token *)
Definition: sqlite3.c:97801
SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *)
#define sqlite3_column_table_name
Definition: sqlite3.c:108727
#define CC_KYWD
Definition: sqlite3.c:134345
#define OE_SetNull
Definition: sqlite3.c:14359
struct AggInfo::AggInfo_func * aFunc
static int vdbePmaReadBlob(PmaReader *p, int nByte, u8 **ppOut)
Definition: sqlite3.c:84551
SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64)
Definition: sqlite3.c:23897
sqlite3_vtab * pVtab
Definition: sqlite3.c:6153
static int databaseIsUnmoved(Pager *pPager)
Definition: sqlite3.c:50678
static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS)
Definition: sqlite3.c:125345
#define OP_Cast
Definition: sqlite3.c:12430
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *, int, const char *)
Definition: sqlite3.c:97215
unsigned bft
Definition: sqlite3.c:17741
SQLITE_PRIVATE void sqlite3Parser(void *, int, Token, Parse *)
#define SQLITE_SCANSTAT_NLOOP
Definition: sqlite3.c:8120
SrcList * pSrcList
Definition: sqlite3.c:15662
NameContext * pNC
Definition: sqlite3.c:15659
#define TK_EXPLAIN
Definition: sqlite3.c:11102
static void walEncodeFrame(Wal *pWal, u32 iPage, u32 nTruncate, u8 *aData, u8 *aFrame)
Definition: sqlite3.c:53905
SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context *, int N, void *, void(*)(void *))
Definition: sqlite3.c:75301
u8 isAnchor
Definition: sqlite3.c:44025
SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int)
Definition: sqlite3.c:19625
#define OP_Remainder
Definition: sqlite3.c:12390
#define TK_RELEASE
Definition: sqlite3.c:11114
struct ScratchFreeslot ScratchFreeslot
#define UNKNOWN_LOCK
Definition: sqlite3.c:46223
#define IfNotOmitAV(expr)
Definition: sqlite3.c:57730
Vdbe * v
Definition: sqlite3.c:17558
SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum *, const char *, va_list)
Definition: sqlite3.c:24610
SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName)
Definition: sqlite3.c:139489
SQLITE_PRIVATE LogEst sqlite3LogEst(u64)
Definition: sqlite3.c:28391
static int pager_wait_on_lock(Pager *pPager, int locktype)
Definition: sqlite3.c:49645
LogEst * aiRowLogEst
Definition: sqlite3.c:14469
#define OP_AggFinal
Definition: sqlite3.c:12486
static int pthreadMutexInit(void)
Definition: sqlite3.c:22629
sqlite3_int64 sqlite3StatValueType
Definition: sqlite3.c:17973
#define OP_OffsetLimit
Definition: sqlite3.c:12483
#define BTREE_AUXDELETE
Definition: sqlite3.c:12078
#define OP_Found
Definition: sqlite3.c:12370
SQLITE_PRIVATE int sqlite3PendingByte
Definition: sqlite3.c:16922
static void ctimeFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19357
Parse * pParse
Definition: sqlite3.c:14994
SQLITE_PRIVATE char * sqlite3Utf16to8(sqlite3 *, const void *, int, u8)
Definition: sqlite3.c:26880
int addrCrTab
Definition: sqlite3.c:15333
static int readsTable(Parse *p, int iDb, Table *pTab)
Definition: sqlite3.c:105972
static void removeElementGivenHash(Hash *pH, HashElem *elem, unsigned int h)
Definition: sqlite3.c:28625
SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor *)
Definition: sqlite3.c:71856
#define SQLITE_LOCKED_SHAREDCACHE
Definition: sqlite3.c:734
static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags)
Definition: sqlite3.c:124606
#define WHERE_GROUPBY
Definition: sqlite3.c:14956
#define SQLITE_ANALYZE
Definition: sqlite3.c:2997
#define SQLITE_FSFLAGS_IS_MSDOS
Definition: sqlite3.c:29034
int mnPmaSize
Definition: sqlite3.c:84383
#define CURSOR_INVALID
Definition: sqlite3.c:57248
u32 newmask
Definition: sqlite3.c:15336
PCache1 * pCache
Definition: sqlite3.c:44027
#define PAGER_LOCKINGMODE_QUERY
Definition: sqlite3.c:12758
u32 nSet
Definition: sqlite3.c:42733
#define PAGER_JOURNALMODE_MEMORY
Definition: sqlite3.c:12774
PgHdr1 * pFree
Definition: sqlite3.c:44094
SQLITE_PRIVATE int sqlite3Select(Parse *, Select *, SelectDest *)
Definition: sqlite3.c:117611
GLfloat GLfloat p
Definition: glext.h:12687
static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage)
Definition: sqlite3.c:63522
static void unlockBtreeIfUnused(BtShared *pBt)
Definition: sqlite3.c:60689
SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *)
Definition: sqlite3.c:125960
static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove)
Definition: sqlite3.c:43209
#define SQLITE_IOERR_CLOSE
Definition: sqlite3.c:721
#define OP_IsNull
Definition: sqlite3.c:12373
static MemPage * btreePageLookup(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:59610
const char * zType
Definition: sqlite3.c:15531
#define SQLITE_CHECKPOINT_RESTART
Definition: sqlite3.c:7983
#define SQLITE_AFF_INTEGER
Definition: sqlite3.c:14115
int(* xDisconnect)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:5895
const char * zAuthContext
Definition: sqlite3.c:15367
const GLfloat * m
Definition: glext.h:6814
u8 leaf
Definition: sqlite3.c:56955
SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *)
Definition: sqlite3.c:68092
#define IsStat3
Definition: sqlite3.c:94176
#define SQLITE_PRINTF_SQLFUNC
Definition: sqlite3.c:15552
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75507
GLboolean reset
Expr * pWhen
Definition: sqlite3.c:15450
#define OP_AggStep0
Definition: sqlite3.c:12484
#define BTCF_Incrblob
Definition: sqlite3.c:57215
SQLITE_PRIVATE void * sqlite3DbMallocRaw(sqlite3 *, u64)
Definition: sqlite3.c:24232
#define SQLITE_ACCESS_READWRITE
Definition: sqlite3.c:1509
#define TK_LSHIFT
Definition: sqlite3.c:11145
SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(sqlite3 *, int(*)(void *, sqlite3 *, const char *, int), void *)
Definition: sqlite3.c:137594
#define SQLITE_LITTLEENDIAN
Definition: sqlite3.c:11566
#define HAVE_FCHOWN
Definition: sqlite3.c:159
#define OPFLAG_USESEEKRESULT
Definition: sqlite3.c:15416
#define SF_Resolved
Definition: sqlite3.c:15074
static i64 doubleToInt64(double r)
Definition: sqlite3.c:68603
#define OPFLAG_LENGTHARG
Definition: sqlite3.c:15420
sqlite3_syscall_ptr pDefault
Definition: sqlite3.c:29453
WhereTerm * aLTermSpace[3]
Definition: sqlite3.c:122378
#define DbMaskNonZero(M)
Definition: sqlite3.c:15253
int errCode
Definition: sqlite3.c:13676
#define SQLITE_DETACH
Definition: sqlite3.c:2994
void(* xMutexLeave)(sqlite3_mutex *)
Definition: sqlite3.c:6654
#define OP_Savepoint
Definition: sqlite3.c:12339
PgHdr * pDirtyNext
Definition: sqlite3.c:12974
#define OP_Compare
Definition: sqlite3.c:12432
static Trigger * fkActionTrigger(Parse *pParse, Table *pTab, FKey *pFKey, ExprList *pChanges)
Definition: sqlite3.c:105550
SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *)
Definition: sqlite3.c:74143
struct VdbeSorter VdbeSorter
Definition: sqlite3.c:17456
#define OP_HaltIfNull
Definition: sqlite3.c:12411
SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void(*xEntryPoint)(void))
Definition: sqlite3.c:109356
#define BITVEC_NBIT
Definition: sqlite3.c:42694
#define P4_NOTUSED
Definition: sqlite3.c:12278
#define MAX(A, B)
Definition: sqlite3.c:11382
SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *)
Definition: sqlite3.c:51329
static int createModule(sqlite3 *db, const char *zName, const sqlite3_module *pModule, void *pAux, void(*xDestroy)(void *))
Definition: sqlite3.c:121040
static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102705
#define BTS_PENDING
Definition: sqlite3.c:57136
#define SQLITE_CREATE_VTABLE
Definition: sqlite3.c:2998
Bitvec * pHasContent
Definition: sqlite3.c:57117
const char * zCteErr
Definition: sqlite3.c:15696
#define WAL_HDRSIZE
Definition: sqlite3.c:53616
SQLITE_PRIVATE void sqlite3EndBenignMalloc(void)
Definition: sqlite3.c:19967
struct AggInfo::AggInfo_col * aCol
#define CC_SLASH
Definition: sqlite3.c:134360
tRowcnt * anDLt
Definition: sqlite3.c:94292
#define SQLITE_ALLOW_COVERING_INDEX_SCAN
Definition: sqlite3.c:16809
#define COLFLAG_HIDDEN
Definition: sqlite3.c:14071
static void attachFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:95972
SQLITE_PRIVATE void sqlite3ScratchFree(void *)
Definition: sqlite3.c:23960
#define TK_RENAME
Definition: sqlite3.c:11194
#define sqlite3MemdebugNoType(X, Y)
Definition: sqlite3.c:16634
SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context *, const char *, sqlite3_uint64, void(*)(void *), unsigned char encoding)
Definition: sqlite3.c:74868
SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[]
Definition: sqlite3.c:16932
SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *, int, int)
Definition: sqlite3.c:91525
int bPurgeable
Definition: sqlite3.c:44081
#define OP_SorterSort
Definition: sqlite3.c:12381
unixInodeInfo * pPrev
Definition: sqlite3.c:30184
#define XN_EXPR
Definition: sqlite3.c:14516
#define TK_CONSTRAINT
Definition: sqlite3.c:11199
GLenum GLenum GLenum GLenum GLenum scale
Definition: glext.h:10806
SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n)
Definition: sqlite3.c:44168
#define osFchown
#define TK_INTERSECT
Definition: sqlite3.c:11218
SQLITE_PRIVATE sqlite3_backup ** sqlite3PagerBackupPtr(Pager *)
Definition: sqlite3.c:52972
static int exprStructSize(Expr *p)
Definition: sqlite3.c:89669
GLboolean invert
BtLock lock
Definition: sqlite3.c:57039
u8 isBulkLocal
Definition: sqlite3.c:44024
#define HASHTABLE_HASH_1
Definition: sqlite3.c:53730
static void hexFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103673
SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context *, const void *, sqlite3_uint64, void(*)(void *))
Definition: sqlite3.c:74809
int * aAltMap
Definition: sqlite3.c:17509
#define OP_Ne
Definition: sqlite3.c:12375
static void * vdbeIncrPopulateThread(void *pCtx)
Definition: sqlite3.c:85977
IdList * pIdList
Definition: sqlite3.c:15515
int cookieValue[SQLITE_MAX_ATTACHED+2]
Definition: sqlite3.c:15316
Parse * pParse
Definition: sqlite3.c:69272
static void sqliteAuthBadReturnCode(Parse *pParse)
Definition: sqlite3.c:96587
#define TK_VARIABLE
Definition: sqlite3.c:11235
#define YY_MIN_REDUCE
Definition: sqlite3.c:130963
SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *, With *)
Definition: sqlite3.c:101167
#define WHERE_ORDERBY_NORMAL
Definition: sqlite3.c:14947
#define etSQLESCAPE3
Definition: sqlite3.c:24472
Hash idxHash
Definition: sqlite3.c:13537
SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *)
Definition: sqlite3.c:71911
static void functionDestroy(sqlite3 *db, FuncDef *p)
Definition: sqlite3.c:136559
static void checkAppendMsg(IntegrityCk *pCheck, const char *zFormat,...)
Definition: sqlite3.c:66491
u32 nChar
Definition: sqlite3.c:15543
static void datetimeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19147
Pgno dbFileSize
Definition: sqlite3.c:46471
#define TK_RP
Definition: sqlite3.c:11123
u32 cacheCtr
Definition: sqlite3.c:17779
#define SQLITE_STATUS_MALLOC_SIZE
Definition: sqlite3.c:6944
#define getVarint32(A, B)
Definition: sqlite3.c:16257
sqlite3 * db
Definition: sqlite3.c:45274
#define SQLITE_SCHEMA
Definition: sqlite3.c:674
#define TK_INSTEAD
Definition: sqlite3.c:11177
#define SQLITE_IOERR_ACCESS
Definition: sqlite3.c:718
int * aLabel
Definition: sqlite3.c:15303
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem)
Definition: sqlite3.c:91206
#define TIMER_ELAPSED
Definition: sqlite3.c:29324
#define SHARED_SIZE
Definition: sqlite3.c:13333
SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *, u32 addr, int P1)
Definition: sqlite3.c:70657
SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *, int)
Definition: sqlite3.c:24158
#define IsStat4
Definition: sqlite3.c:94175
SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *)
Definition: sqlite3.c:125977
SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt *, int, const char *, int, void(*)(void *))
Definition: sqlite3.c:75836
#define noopFunc
Definition: sqlite3.c:103036
#define SQLITE_FCNTL_SYNC
Definition: sqlite3.c:1263
#define BTREE_INCR_VACUUM
Definition: sqlite3.c:11975
SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *, u8, u8)
Definition: sqlite3.c:68769
int iBufStart
Definition: sqlite3.c:84483
void(* xDel)(void *)
Definition: sqlite3.c:17610
int mnReg
Definition: sqlite3.c:14565
#define YYWILDCARD
Definition: sqlite3.c:130931
SQLITE_PRIVATE Table * sqlite3FindTable(sqlite3 *, const char *, const char *)
Definition: sqlite3.c:97066
static void exprAnalyze(SrcList *, WhereClause *, int)
Definition: sqlite3.c:125429
static void heightOfSelect(Select *p, int *pnHeight)
Definition: sqlite3.c:89255
ExprList * pOrderBy
Definition: sqlite3.c:15055
#define SQLITE_STMTSTATUS_SORT
Definition: sqlite3.c:7143
#define BTREE_TEXT_ENCODING
Definition: sqlite3.c:11973
PgHdr * pSynced
Definition: sqlite3.c:43094
NameContext * pNext
Definition: sqlite3.c:14998
SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *)
Definition: sqlite3.c:57657
static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx)
Definition: sqlite3.c:95335
SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *, int)
Definition: sqlite3.c:98222
pthread_t tid
Definition: sqlite3.c:26209
#define CC_TILDA
Definition: sqlite3.c:134369
SQLITE_PRIVATE WhereInfo * sqlite3WhereBegin(Parse *, SrcList *, Expr *, ExprList *, ExprList *, u16, int)
Definition: sqlite3.c:130014
struct TrigEvent yy410
Definition: sqlite3.c:130947
sqlite3 * db
Definition: sqlite3.c:15273
static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit)
Definition: sqlite3.c:61146
Mem * aNew
Definition: sqlite3.c:17850
#define BTREE_APPLICATION_ID
Definition: sqlite3.c:11976
#define FTS5_TOKENIZE_QUERY
Definition: sqlite3.c:10382
static void setAllColumnNames(Vdbe *v, int N, const char **azCol)
Definition: sqlite3.c:110118
static void pageReinit(DbPage *pData)
Definition: sqlite3.c:59751
u32 vfsFlags
Definition: sqlite3.c:46498
static SQLITE_NOINLINE void * createAggContext(sqlite3_context *p, int nByte)
Definition: sqlite3.c:75243
#define TIMER_START
Definition: sqlite3.c:29322
SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *, int, int n)
Definition: sqlite3.c:75903
SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void)
Definition: sqlite3.c:36528
#define SQLITE_MAX_TRIGGER_DEPTH
Definition: sqlite3.c:10664
#define osFstat
#define SQLITE_DEFAULT_FILE_PERMISSIONS
Definition: sqlite3.c:29049
bft isPrepareV2
Definition: sqlite3.c:17796
int(* xFunc)(void *, int)
Definition: sqlite3.c:11681
SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *)
Definition: sqlite3.c:57441
SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int)
Definition: sqlite3.c:23634
#define P4_REAL
Definition: sqlite3.c:12289
#define HAVE_MREMAP
Definition: sqlite3.c:29416
static const char * selectOpName(int id)
Definition: sqlite3.c:113904
int nMemory
Definition: sqlite3.c:84394
int(* xProgress)(void *)
Definition: sqlite3.c:13745
#define SQLITE_OPEN_NOMUTEX
Definition: sqlite3.c:784
#define PragTyp_INDEX_LIST
Definition: sqlite3.c:109537
#define SQLITE_DENY
Definition: sqlite3.c:2947
#define SQLITE_AFF_MASK
Definition: sqlite3.c:14124
WhereClause * pOrigWC
Definition: sqlite3.c:122524
GLuint64 GLenum void * handle
Definition: glext.h:7785
SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *, FuncDef *)
Definition: sqlite3.c:68508
#define YYNOCODE
Definition: sqlite3.c:130929
int nHeight
Definition: sqlite3.c:14694
void *(* xTask)(void *)
Definition: sqlite3.c:26212
#define PragTyp_PARSER_TRACE
Definition: sqlite3.c:109562
static PgHdr1 * pcache1FetchNoMutex(sqlite3_pcache *p, unsigned int iKey, int createFlag)
Definition: sqlite3.c:44882
SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char *, u32, Mem *)
Definition: sqlite3.c:73253
SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *)
Definition: sqlite3.c:136687
SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *)
Definition: sqlite3.c:137767
sqlite3_backup * pBackup
Definition: sqlite3.c:46483
#define PragTyp_TABLE_INFO
Definition: sqlite3.c:109551
int flags
Definition: sqlite3.c:83583
u16 schemaFlags
Definition: sqlite3.c:13543
static void codeAttach(Parse *pParse, int type, FuncDef const *pFunc, Expr *pAuthArg, Expr *pFilename, Expr *pDbname, Expr *pKey)
Definition: sqlite3.c:96226
#define get2byte(x)
Definition: sqlite3.c:57365
#define PAGER_GET_NOCONTENT
Definition: sqlite3.c:12780
#define OP_DecrJumpZero
Definition: sqlite3.c:12405
#define TK_COLUMNKW
Definition: sqlite3.c:11167
#define TRIGGER_BEFORE
Definition: sqlite3.c:15466
struct KeyInfo * pKeyInfo
Definition: sqlite3.c:57202
#define DOTLOCK_SUFFIX
Definition: sqlite3.c:31158
sqlite3 * db
Definition: sqlite3.c:14183
sqlite3_value ** apSqlParam
Definition: sqlite3.c:8562
GLsizei const GLint * box
Definition: glext.h:8982
#define SQLITE_FCNTL_HAS_MOVED
Definition: sqlite3.c:1262
#define SQLITE_DEPRECATED
Definition: sqlite3.c:326
#define GLOBAL(t, v)
Definition: sqlite3.c:11747
SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void)
Definition: sqlite3.c:135644
SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *)
Definition: sqlite3.c:74665
int szOsFile
Definition: sqlite3.c:1451
#define etORDINAL
Definition: sqlite3.c:24473
SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p)
Definition: sqlite3.c:67979
SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *)
Definition: sqlite3.c:52310
SQLITE_PRIVATE void sqlite3PrngRestoreState(void)
Definition: sqlite3.c:26156
u8 * aSortOrder
Definition: sqlite3.c:14474
static void sqlite3MemFree(void *pPrior)
Definition: sqlite3.c:20197
#define SF_UsesEphemeral
Definition: sqlite3.c:15077
#define UNIXFILE_EXCL
Definition: sqlite3.c:29166
static const char *const azCompileOpt[]
Definition: sqlite3.c:16969
TriggerPrg * pNext
Definition: sqlite3.c:15231
#define TK_SELECT
Definition: sqlite3.c:11219
PCache * pCache
Definition: sqlite3.c:12972
#define getVarint
Definition: sqlite3.c:16262
#define SQLITE_SORTER_PMASZ
Definition: sqlite3.c:16816
void * pHeap
Definition: sqlite3.c:15588
static SQLITE_NOINLINE void autoIncrementEnd(Parse *pParse)
Definition: sqlite3.c:106127
int iTab
Definition: sqlite3.c:96794
SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *)
Definition: sqlite3.c:67132
GLsizei const GLchar *const * path
Definition: glext.h:4276
sqlite3_pcache_page * pPage
Definition: sqlite3.c:12956
SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int)
Definition: sqlite3.c:68261
SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *, int, int, int, void volatile **)
Definition: sqlite3.c:19634
u8 opcode
Definition: sqlite3.c:12209
static void markTermAsChild(WhereClause *pWC, int iChild, int iParent)
Definition: sqlite3.c:124887
unsigned int openFlags
Definition: sqlite3.c:13675
#define EP_Generic
Definition: sqlite3.c:14723
static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo)
Definition: sqlite3.c:127697
#define SQLITE_IOERR_SHMSIZE
Definition: sqlite3.c:724
static void generateColumnTypes(Parse *pParse, SrcList *pTabList, ExprList *pEList)
Definition: sqlite3.c:114291
static int unixDeviceCharacteristics(sqlite3_file *id)
Definition: sqlite3.c:33061
Parse * pParse
Definition: sqlite3.c:15652
Trigger * pNext
Definition: sqlite3.c:15456
u8 readOnly
Definition: sqlite3.c:53657
static void spanUnaryPostfix(Parse *pParse, int op, ExprSpan *pOperand, Token *pPostOp)
Definition: sqlite3.c:130813
#define SQLITE_IOERR_DELETE
Definition: sqlite3.c:715
#define TK_REM
Definition: sqlite3.c:11151
SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *)
Definition: sqlite3.c:75356
#define isOpen(pFd)
Definition: sqlite3.c:46629
#define SQLITE_WARNING
Definition: sqlite3.c:685
int nCursor
Definition: sqlite3.c:17770
WhereTerm ** aLTerm
Definition: sqlite3.c:122376
static void analyzeOneTable(Parse *pParse, Table *pTab, Index *pOnlyIdx, int iStatCur, int iMem, int iTab)
Definition: sqlite3.c:94972
void * pUserData
Definition: sqlite3.c:13901
SQLITE_PRIVATE void sqlite3PcacheShutdown(void)
Definition: sqlite3.c:43321
static int vdbeIncrSwap(IncrMerger *)
Definition: sqlite3.c:86011
int(* xSavepoint)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:5916
static void computeYMD_HMS(DateTime *p)
Definition: sqlite3.c:18715
SQLITE_PRIVATE int sqlite3SubInt64(i64 *, i64)
Definition: sqlite3.c:28273
static int resolveCompoundOrderBy(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:88304
SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_snapshot_free(sqlite3_snapshot *)
#define SQLITE_N_COLCACHE
Definition: sqlite3.c:15208
#define SQLITE_GroupByOrder
Definition: sqlite3.c:13846
static void walCleanupHash(Wal *pWal)
Definition: sqlite3.c:54149
GLfloat value
u8 nColCache
Definition: sqlite3.c:15286
#define TWO_BYTE_INT(x)
Definition: sqlite3.c:73203
SQLITE_PRIVATE const char * sqlite3PagerFilename(Pager *, int)
Definition: sqlite3.c:52531
Bool isEphemeral
Definition: sqlite3.c:17491
#define SQLITE_USE_URI
Definition: sqlite3.c:16801
double s
Definition: sqlite3.c:18371
SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem *, const char *, int, u8, void(*)(void *))
Definition: sqlite3.c:69031
i16 nField
Definition: sqlite3.c:17495
GLint GLuint mask
SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse *, Table *, FKey *, Index **, int **)
Definition: sqlite3.c:104580
#define SQLITE_REINDEX
Definition: sqlite3.c:2996
SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData)
Definition: sqlite3.c:55963
static int readJournalHdr(Pager *pPager, int isHot, i64 journalSize, u32 *pNRec, u32 *pDbSize)
Definition: sqlite3.c:47317
SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse *, Expr *, int, u8)
Definition: sqlite3.c:92192
#define P4_TRANSIENT
Definition: sqlite3.c:12286
#define pagerReportSize(X)
Definition: sqlite3.c:47972
u32 magic
Definition: sqlite3.c:13691
#define OP_Return
Definition: sqlite3.c:12409
u16 flags
Definition: sqlite3.c:12965
Bitmask prereqRight
Definition: sqlite3.c:122495
ExprList * pEList
Definition: sqlite3.c:15042
#define OPFLAG_LASTROWID
Definition: sqlite3.c:15413
void(* xMutexEnter)(sqlite3_mutex *)
Definition: sqlite3.c:6652
#define NC_IsCheck
Definition: sqlite3.c:15014
static void errlogFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103471
static void explainTempTable(Parse *pParse, const char *zUsage)
Definition: sqlite3.c:113926
volatile u32 ** apWiData
Definition: sqlite3.c:53650
SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *)
Definition: sqlite3.c:74662
static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8)
Definition: sqlite3.c:63200
#define SQLITE_DROP_TEMP_INDEX
Definition: sqlite3.c:2981
#define WALINDEX_HDR_SIZE
Definition: sqlite3.c:53609
static ExprList * parserAddExprIdListTerm(Parse *pParse, ExprList *pPrior, Token *pIdToken, int hasCollate, int sortOrder)
Definition: sqlite3.c:130853
SQLITE_PRIVATE DbPage * sqlite3PagerLookup(Pager *pPager, Pgno pgno)
Definition: sqlite3.c:51310
SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *)
Definition: sqlite3.c:100185
#define OP_ColumnsUsed
Definition: sqlite3.c:12449
#define SRT_Exists
Definition: sqlite3.c:15158
double rSum
Definition: sqlite3.c:103986
WalIndexHdr hdr
Definition: sqlite3.c:53661
#define TK_NOT
Definition: sqlite3.c:11119
#define SQLITE_Stat34
Definition: sqlite3.c:13855
u16(* xCellSize)(MemPage *, u8 *)
Definition: sqlite3.c:56975
char * zName
Definition: sqlite3.c:15693
int addrSortIndex
Definition: sqlite3.c:112860
static void walIndexWriteHdr(Wal *pWal)
Definition: sqlite3.c:53879
static int subjournalPageIfRequired(PgHdr *pPg)
Definition: sqlite3.c:50242
SQLITE_API int SQLITE_STDCALL 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:137269
static void substrFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102832
#define OP_IdxInsert
Definition: sqlite3.c:12463
CollSeq * pDfltColl
Definition: sqlite3.c:13668
unsigned bUnordered
Definition: sqlite3.c:14484
SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *)
Definition: sqlite3.c:74952
#define SQLITE_IOERR_SHORT_READ
Definition: sqlite3.c:707
static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace)
Definition: sqlite3.c:64436
#define PAGER_STAT_MISS
Definition: sqlite3.c:46532
SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse *, Trigger *, ExprList *, int, int, Table *, int)
Definition: sqlite3.c:119763
u8 untestedTerms
Definition: sqlite3.c:122655
SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *)
Definition: sqlite3.c:85827
#define OE_Replace
Definition: sqlite3.c:14356
#define SQLITE_TEMP_STORE
Definition: sqlite3.c:11333
SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void(*xEntryPoint)(void))
Definition: sqlite3.c:109401
#define SQLITE_IDXTYPE_PRIMARYKEY
Definition: sqlite3.c:14504
#define SQLITE_IOERR
Definition: sqlite3.c:667
#define SQLITE_STAT4_SAMPLES
Definition: sqlite3.c:94178
static void instrFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102754
#define MEM_Frame
Definition: sqlite3.c:17642
SQLITE_PRIVATE void sqlite3HashInit(Hash *)
Definition: sqlite3.c:28472
int(* xLock)(sqlite3_file *, int)
Definition: sqlite3.c:993
#define TRANS_WRITE
Definition: sqlite3.c:57052
#define YY_ACTTAB_COUNT
Definition: sqlite3.c:131035
static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut)
Definition: sqlite3.c:94954
static int btreeHeapPull(u32 *aHeap, u32 *pOut)
Definition: sqlite3.c:66694
void * pBulk
Definition: sqlite3.c:44095
#define SQLITE_ANY
Definition: sqlite3.c:4591
u32 nSubRec
Definition: sqlite3.c:46476
#define NEVER(X)
Definition: sqlite3.c:10930
static void disconnectAllVtab(sqlite3 *db)
Definition: sqlite3.c:136574
#define TK_INDEX
Definition: sqlite3.c:11240
#define TK_IF
Definition: sqlite3.c:11118
Btree * pDest
Definition: sqlite3.c:67403
static int termCanDriveIndex(WhereTerm *pTerm, struct SrcList_item *pSrc, Bitmask notReady)
Definition: sqlite3.c:126493
static void walLimitSize(Wal *pWal, i64 nMax)
Definition: sqlite3.c:55120
#define TK_ILLEGAL
Definition: sqlite3.c:11261
char dbFileVers[16]
Definition: sqlite3.c:46487
SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *)
Definition: sqlite3.c:19700
SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *, int, int)
Definition: sqlite3.c:61547
#define SQLITE_CONFIG_PCACHE2
Definition: sqlite3.c:2108
static int vdbeSorterCreateThread(SortSubtask *pTask, void *(*xTask)(void *), void *pIn)
Definition: sqlite3.c:85195
SortSubtask aTask[1]
Definition: sqlite3.c:84400
SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset)
Definition: sqlite3.c:84000
static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p)
Definition: sqlite3.c:124574
static SQLITE_NOINLINE u16 computeCellSize(CellArray *p, int N)
Definition: sqlite3.c:64105
#define VdbeMemDynamic(X)
Definition: sqlite3.c:17668
#define put4byte
Definition: sqlite3.c:57368
#define EXPRDUP_REDUCE
Definition: sqlite3.c:14775
SQLITE_PRIVATE int sqlite3IsNaN(double)
Definition: sqlite3.c:27035
#define SQLITE_SYNC_NORMAL
Definition: sqlite3.c:874
static int unixOpen(sqlite3_vfs *pVfs, const char *zPath, sqlite3_file *pFile, int flags, int *pOutFlags)
Definition: sqlite3.c:34730
SQLITE_PRIVATE TriggerStep * sqlite3TriggerDeleteStep(sqlite3 *, Token *, Expr *)
Definition: sqlite3.c:119139
SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *, int, u32 *)
Definition: sqlite3.c:73011
i64 nStmtDefCons
Definition: sqlite3.c:17807
int schema_cookie
Definition: sqlite3.c:13534
#define TK_LT
Definition: sqlite3.c:11140
#define WAL_FRAME_HDRSIZE
Definition: sqlite3.c:53612
#define MEM_Cleared
Definition: sqlite3.c:17644
SQLITE_PRIVATE void sqlite3VtabEponymousTableClear(sqlite3 *, Module *)
Definition: sqlite3.c:122144
char validHMS
Definition: sqlite3.c:18373
int nSavepoint
Definition: sqlite3.c:13762
#define TK_ALTER
Definition: sqlite3.c:11241
int nSample
Definition: sqlite3.c:94315
SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *)
Definition: sqlite3.c:68686
#define PragTyp_COMPILE_OPTIONS
Definition: sqlite3.c:109528
#define OP_SorterOpen
Definition: sqlite3.c:12445
SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache *, Pgno, sqlite3_pcache_page **)
Definition: sqlite3.c:43450
int nDb
Definition: sqlite3.c:13671
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_count(sqlite3 *)
SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(sqlite3 *, int(*xAuth)(void *, int, const char *, const char *, const char *, const char *), void *pUserData)
Definition: sqlite3.c:96567
SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *)
Definition: sqlite3.c:51340
static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere)
Definition: sqlite3.c:128431
SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *)
Definition: sqlite3.c:43600
int(* xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *)
Definition: sqlite3.c:5905
SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *)
Definition: sqlite3.c:90326
SQLITE_PRIVATE int sqlite3CorruptError(int)
Definition: sqlite3.c:138846
#define SQLITE_MUTEX_STATIC_MEM
Definition: sqlite3.c:6706
#define TERM_IS
Definition: sqlite3.c:122517
#define etSRCLIST
Definition: sqlite3.c:24470
static void SQLITE_NOINLINE btreeLockCarefully(Btree *p)
Definition: sqlite3.c:57475
#define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
Definition: sqlite3.c:29056
#define ROWSET_ENTRY_PER_CHUNK
Definition: sqlite3.c:45239
BusyHandler busyHandler
Definition: sqlite3.c:13758
#define MEM_AffMask
Definition: sqlite3.c:17640
#define CTIMEOPT_VAL(opt)
SQLITE_PRIVATE int sqlite3BtreeSetSpillSize(Btree *, int)
Definition: sqlite3.c:60245
char * zWal
Definition: sqlite3.c:46522
u32 iDivisor
Definition: sqlite3.c:42736
static void * sqlite3MemRealloc(void *pPrior, int nByte)
Definition: sqlite3.c:20235
#define SQLITE_SYNC_DATAONLY
Definition: sqlite3.c:876
#define tkCREATE
Definition: sqlite3.c:135254
static void walMergesort(const u32 *aContent, ht_slot *aBuffer, ht_slot *aList, int *pnList)
Definition: sqlite3.c:54692
int nMem
Definition: sqlite3.c:17768
#define SQLITE_OPEN_READONLY
Definition: sqlite3.c:769
#define TERM_DYNAMIC
Definition: sqlite3.c:122502
static int generateOutputSubroutine(Parse *pParse, Select *p, SelectDest *pIn, SelectDest *pDest, int regReturn, int regPrev, KeyInfo *pKeyInfo, int iBreak)
Definition: sqlite3.c:115384
int szRegion
Definition: sqlite3.c:33130
u8 bBusy
Definition: sqlite3.c:56959
#define SQLITE_DistinctOpt
Definition: sqlite3.c:13849
#define sqlite3ParseToplevel(p)
Definition: sqlite3.c:16187
#define VVA_ONLY(X)
Definition: sqlite3.c:10904
#define SQLITE_Transitive
Definition: sqlite3.c:13853
#define SQLITE_MAGIC_ZOMBIE
Definition: sqlite3.c:13886
#define ONE_BYTE_INT(x)
Definition: sqlite3.c:73202
SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *)
Definition: sqlite3.c:68714
SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64 *)
Definition: sqlite3.c:19733
SQLITE_PRIVATE void * sqlite3HexToBlob(sqlite3 *, const char *z, int n)
Definition: sqlite3.c:28178
u8 nTempReg
Definition: sqlite3.c:15280
int(* xRollbackTo)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:5918
#define OPFLG_OUT2
Definition: sqlite3.c:12509
#define VDBE_MAGIC_RUN
Definition: sqlite3.c:17830
i64 nKey
Definition: sqlite3.c:57187
SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *, void **)
Definition: sqlite3.c:26254
SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *)
Definition: sqlite3.c:136514
#define WHERE_AUTO_INDEX
Definition: sqlite3.c:122776
#define SQLITE_ShortColNames
Definition: sqlite3.c:13809
#define sqlite3_column_database_name16
Definition: sqlite3.c:108726
#define OP_Clear
Definition: sqlite3.c:12468
SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *, int N)
Definition: sqlite3.c:75597
#define OP_AddImm
Definition: sqlite3.c:12428
IdList * b
Definition: sqlite3.c:130731
#define SORTFLAG_UseSorter
Definition: sqlite3.c:112864
unsigned int nHash
Definition: sqlite3.c:44092
#define etSQLESCAPE
Definition: sqlite3.c:24466
sqlite3 * db
Definition: sqlite3.c:14380
#define CC_STAR
Definition: sqlite3.c:134365
u16 nLSlot
Definition: sqlite3.c:122375
static void generateColumnNames(Parse *pParse, SrcList *pTabList, ExprList *pEList)
Definition: sqlite3.c:114331
static void glob(const std::string &directory, const std::string &spec, std::function< void(std::string const &) > fn, bool recursive=true, bool includeDirectories=false)
Definition: filesystem.h:269
Table * pTab
Definition: sqlite3.c:83591
u16 nFree
Definition: sqlite3.c:56963
#define SRT_DistQueue
Definition: sqlite3.c:15163
static int checkReadTransaction(sqlite3 *db, Btree *p)
Definition: sqlite3.c:67511
SQLITE_PRIVATE int sqlite3FkRequired(Parse *, Table *, int *, int)
Definition: sqlite3.c:105490
SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *)
Definition: sqlite3.c:72436
static void logBadConnection(const char *zType)
Definition: sqlite3.c:28199
u32 bDisable
Definition: sqlite3.c:13597
static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin)
Definition: sqlite3.c:85208
void(* xCollNeeded)(void *, sqlite3 *, int eTextRep, const char *)
Definition: sqlite3.c:13731
static int compare2pow63(const char *zNum, int incr)
Definition: sqlite3.c:27511
sqlite3_int64 estimatedRows
Definition: sqlite3.c:6040
#define SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER
Definition: sqlite3.c:2209
#define BTS_EXCLUSIVE
Definition: sqlite3.c:57135
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_cmp(sqlite3_snapshot *p1, sqlite3_snapshot *p2)
SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[]
Definition: sqlite3.c:16680
const char * zTail
Definition: sqlite3.c:15364
int nextPagesize
Definition: sqlite3.c:13690
int pageSize
Definition: sqlite3.c:46500
SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *, Select *)
Definition: sqlite3.c:112975
sqlite3_uint64 colUsed
Definition: sqlite3.c:6044
SQLITE_PRIVATE int sqlite3VdbeChangeToNoop(Vdbe *, int addr)
Definition: sqlite3.c:70775
#define tkEND
Definition: sqlite3.c:135257
UINT8_TYPE u8
Definition: sqlite3.c:11450
static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N)
Definition: sqlite3.c:98355
static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
Definition: sqlite3.c:95948
SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *)
Definition: sqlite3.c:75123
#define etINVALID
Definition: sqlite3.c:24475
LogEst szIdxRow
Definition: sqlite3.c:14479
int(* xRowid)(sqlite3_vtab_cursor *, sqlite3_int64 *pRowid)
Definition: sqlite3.c:5904
GLuint GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat t1
Definition: glext.h:9721
#define TK_DEFERRABLE
Definition: sqlite3.c:11212
SQLITE_PRIVATE void sqlite3FixInit(DbFixer *, Parse *, int, const char *, const Token *)
Definition: sqlite3.c:96337
volatile int isInterrupted
Definition: sqlite3.c:13736
#define TK_EXISTS
Definition: sqlite3.c:11120
#define SQLITE_TESTCTRL_ASSERT
Definition: sqlite3.c:6805
#define MEM_Agg
Definition: sqlite3.c:17657
#define SQLITE_SHM_NLOCK
Definition: sqlite3.c:1547
SQLITE_API int SQLITE_STDCALL 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:137326
int p1
Definition: sqlite3.c:12213
SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void)
Definition: sqlite3.c:135728
static int sqlite3IntFloatCompare(i64 i, double r)
Definition: sqlite3.c:73619
static u8 * pageFindSlot(MemPage *pPg, int nByte, int *pRc)
Definition: sqlite3.c:59086
static int vdbeSortAllocUnpacked(SortSubtask *pTask)
Definition: sqlite3.c:85393
#define PAGER_CACHESPILL
Definition: sqlite3.c:12798
#define SQLITE_IOCAP_ATOMIC512
Definition: sqlite3.c:821
SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer *, SrcList *)
Definition: sqlite3.c:96370
WhereLoop * pLoops
Definition: sqlite3.c:122647
SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *, BtCursor *, i64 *)
Definition: sqlite3.c:74189
static struct Cte * searchWith(With *pWith, struct SrcList_item *pItem, With **ppContext)
Definition: sqlite3.c:116818
u16 maxLeaf
Definition: sqlite3.c:57108
#define SQLITE_ReadUncommitted
Definition: sqlite3.c:13820
SQLITE_PRIVATE void * sqlite3DbReallocOrFree(sqlite3 *, void *, u64)
Definition: sqlite3.c:24318
SQLITE_PRIVATE int sqlite3WalkSelect(Walker *, Select *)
Definition: sqlite3.c:87373
static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof)
Definition: sqlite3.c:85571
SQLITE_PRIVATE u8 sqlite3HexToInt(int h)
Definition: sqlite3.c:28160
static int walIteratorNext(WalIterator *p, u32 *piPage, u32 *piFrame)
Definition: sqlite3.c:54582
SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double)
Definition: sqlite3.c:28409
#define OP_Eq
Definition: sqlite3.c:12376
#define OP_Program
Definition: sqlite3.c:12401
u8 explain
Definition: sqlite3.c:15351
static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp)
Definition: sqlite3.c:84678
#define OP_MaxPgcnt
Definition: sqlite3.c:12496
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE
Definition: sqlite3.c:7070
char * zName
Definition: sqlite3.c:14467
unsigned short int ctrlFlags
Definition: sqlite3.c:29108
#define SQLITE_CONSTRAINT_TRIGGER
Definition: sqlite3.c:753
#define OP_Multiply
Definition: sqlite3.c:12388
static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom)
Definition: sqlite3.c:127670
static int pthreadMutexEnd(void)
Definition: sqlite3.c:22630
#define TF_Autoincrement
Definition: sqlite3.c:14241
static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData, int bUpdate)
Definition: sqlite3.c:67614
SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *, const char *,...)
Definition: sqlite3.c:25525
#define TESTONLY(X)
Definition: sqlite3.c:10890
etByte type
Definition: sqlite3.c:24491
SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *, int)
Definition: sqlite3.c:49549
#define WHERE_ONEROW
Definition: sqlite3.c:122774
struct With::Cte a[1]
static void createMask(WhereMaskSet *pMaskSet, int iCursor)
Definition: sqlite3.c:126081
#define ONLY_IF_REALLOC_STRESS(X)
Definition: sqlite3.c:10945
#define BTCF_ValidNKey
Definition: sqlite3.c:57212
#define SQLITE_STOREP2
Definition: sqlite3.c:14136
static const int aHardLimit[]
Definition: sqlite3.c:137952
sqlite3_syscall_ptr pCurrent
Definition: sqlite3.c:29452
unsigned char j
Definition: sqlite3.c:26055
SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse)
Definition: sqlite3.c:112342
static void * vdbePmaReaderBgIncrInit(void *pCtx)
Definition: sqlite3.c:86307
unsigned Bool
Definition: sqlite3.c:17453
#define SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION
Definition: sqlite3.c:2210
static SQLITE_NOINLINE void vdbeMemClear(Mem *p)
Definition: sqlite3.c:68570
unsigned int nMax
Definition: sqlite3.c:44083
SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *)
Definition: sqlite3.c:75201
static int syncJournal(Pager *pPager, int newHdr)
Definition: sqlite3.c:49944
int szPage
Definition: sqlite3.c:44078
#define SQLITE_FullFSync
Definition: sqlite3.c:13806
#define NC_AllowAgg
Definition: sqlite3.c:15012
SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(sqlite3 *, void *, void(*)(void *, sqlite3 *, int eTextRep, const char *))
Definition: sqlite3.c:138766
u32 nCkpt
Definition: sqlite3.c:53665
int mxKeysize
Definition: sqlite3.c:84385
#define SQLITE_DEFAULT_WAL_SYNCHRONOUS
Definition: sqlite3.c:13498
#define PENDING_BYTE_PAGE(pBt)
Definition: sqlite3.c:57257
SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *, Expr *, int)
Definition: sqlite3.c:92282
u8 * aPgRef
Definition: sqlite3.c:57351
#define IN_DECLARE_VTAB
Definition: sqlite3.c:15386
static int unixLock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:30597
static int sqlite3MemRoundup(int n)
Definition: sqlite3.c:20267
char tzSet
Definition: sqlite3.c:18376
#define PGHDR_NEED_SYNC
Definition: sqlite3.c:12982
int nAlias
Definition: sqlite3.c:15356
#define TK_SET
Definition: sqlite3.c:11211
GLint GLint GLsizei GLsizei GLsizei depth
static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask)
Definition: sqlite3.c:85109
static void sqlite3MemShutdown(void *NotUsed)
Definition: sqlite3.c:20310
SQLITE_API int SQLITE_STDCALL sqlite3_get_table(sqlite3 *db, const char *zSql, char ***pazResult, int *pnRow, int *pnColumn, char **pzErrmsg)
Definition: sqlite3.c:118608
u32 iReCksum
Definition: sqlite3.c:53663
static SrcList * targetSrcList(Parse *pParse, TriggerStep *pStep)
Definition: sqlite3.c:119345
#define TK_GROUP
Definition: sqlite3.c:11227
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_old(sqlite3 *, int, sqlite3_value **)
u32 iDataVersion
Definition: sqlite3.c:46486
#define SQLITE_CORRUPT_VTAB
Definition: sqlite3.c:741
#define SQLITE_CONFIG_COVERING_INDEX_SCAN
Definition: sqlite3.c:2110
#define SQLITE_CONFIG_PAGECACHE
Definition: sqlite3.c:2097
static void lockBtreeMutex(Btree *p)
Definition: sqlite3.c:57397
#define HAVE_LSTAT
Definition: sqlite3.c:161
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag)
Definition: sqlite3.c:23811
static SQLITE_NOINLINE void vdbeClrCopy(Mem *pTo, const Mem *pFrom, int eType)
Definition: sqlite3.c:68961
SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(sqlite3 *, void *, void(*)(void *, sqlite3 *, int eTextRep, const void *))
Definition: sqlite3.c:138787
static Table * isSimpleCount(Select *p, AggInfo *pAggInfo)
Definition: sqlite3.c:116674
int yyidx
Definition: sqlite3.c:131621
static const YYACTIONTYPE yy_action[]
Definition: sqlite3.c:131036
SQLITE_PRIVATE Select * sqlite3SelectDup(sqlite3 *, Select *, int)
Definition: sqlite3.c:90013
#define OP_Once
Definition: sqlite3.c:12359
static BtShared *SQLITE_WSD sqlite3SharedCacheList
Definition: sqlite3.c:57747
Expr * pPartIdxWhere
Definition: sqlite3.c:14476
static void vdbeFreeOpArray(sqlite3 *, Op *, int)
Definition: sqlite3.c:70749
static int matchQuality(FuncDef *p, int nArg, u8 enc)
Definition: sqlite3.c:101433
static void vdbeMergeEngineFree(MergeEngine *pMerger)
Definition: sqlite3.c:85261
#define COLNAME_DATABASE
Definition: sqlite3.c:12310
UnpackedRecord ** ppRec
Definition: sqlite3.c:69274
#define PragTyp_JOURNAL_MODE
Definition: sqlite3.c:109539
SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut)
Definition: sqlite3.c:19691
#define sqlite3SelectSetName(A, B)
Definition: sqlite3.c:16151
SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:67260
SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3 *, const char *)
Definition: sqlite3.c:24366
SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int)
Definition: sqlite3.c:23891
#define CKCNSTRNT_COLUMN
Definition: sqlite3.c:106890
SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *, Expr *, int)
Definition: sqlite3.c:92295
u8 okConstFactor
Definition: sqlite3.c:15284
SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *)
Definition: sqlite3.c:43840
i64 iKey2
Definition: sqlite3.c:17848
#define TK_ISNULL
Definition: sqlite3.c:11134
#define SQLITE_ACCESS_READ
Definition: sqlite3.c:1510
SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n)
Definition: sqlite3.c:52432
void(* xRollbackCallback)(void *)
Definition: sqlite3.c:13717
#define OP_DropTrigger
Definition: sqlite3.c:12477
#define READ_LOCK
Definition: sqlite3.c:57002
SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *)
Definition: sqlite3.c:68920
#define TK_BLOB
Definition: sqlite3.c:11234
#define SRT_Output
Definition: sqlite3.c:15168
LogEst rSetup
Definition: sqlite3.c:122354
void * pExtra
Definition: sqlite3.c:12958
#define SQLITE_TESTCTRL_VDBE_COVERAGE
Definition: sqlite3.c:6814
static int zeroJournalHdr(Pager *pPager, int doTruncate)
Definition: sqlite3.c:47149
const char * zName
Definition: sqlite3.c:29451
static void juliandayFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19130
SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *)
Definition: sqlite3.c:60376
#define WHERE_DISTINCT_UNORDERED
Definition: sqlite3.c:14970
#define SQLITE_ROLLBACK
Definition: sqlite3.c:8067
#define SQLITE_PRIVATE
Definition: sqlite3.c:23
#define CC_MINUS
Definition: sqlite3.c:134355
const sqlite3_module * pModule
Definition: sqlite3.c:14047
#define DIRECT_MODE
static int unixShmSystemLock(unixFile *pFile, int lockType, int ofst, int n)
Definition: sqlite3.c:33177
#define OP_Add
Definition: sqlite3.c:12386
SQLITE_PRIVATE SrcList * sqlite3SrcListAppendFromTerm(Parse *, SrcList *, Token *, Token *, Token *, Select *, Expr *, IdList *)
Definition: sqlite3.c:100562
static void replaceFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103724
#define SQLITE_LOCK_EXCLUSIVE
Definition: sqlite3.c:846
static struct RowSetEntry * rowSetEntryAlloc(RowSet *p)
Definition: sqlite3.c:45345
SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3 *, int(*)(void *), void *)
Definition: sqlite3.c:137448
#define jrnlBufferSize(x)
Definition: sqlite3.c:46991
#define SQLITE_MAX_SCHEMA_RETRY
Definition: sqlite3.c:17429
#define OP_CollSeq
Definition: sqlite3.c:12425
int(* xCommitCallback)(void *)
Definition: sqlite3.c:13715
SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *)
Definition: sqlite3.c:121458
CollSeq * aColl[1]
Definition: sqlite3.c:14382
static void vdbeSorterMerge(SortSubtask *pTask, SorterRecord *p1, SorterRecord *p2, SorterRecord **ppOut)
Definition: sqlite3.c:85412
struct SrcList::SrcList_item::@129 fg
#define sqlite3GlobalConfig
Definition: sqlite3.c:11748
int nRangeReg
Definition: sqlite3.c:15288
static PgHdr1 * pcache1PinPage(PgHdr1 *pPage)
Definition: sqlite3.c:44484
static int clearDatabasePage(BtShared *pBt, Pgno pgno, int freePageFlag, int *pnChange)
Definition: sqlite3.c:66104
SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *, sqlite3_int64)
Definition: sqlite3.c:74845
u8 * aSortOrder
Definition: sqlite3.c:14381
#define TK_VIEW
Definition: sqlite3.c:11190
SQLITE_PRIVATE int sqlite3FixExpr(DbFixer *, Expr *)
Definition: sqlite3.c:96433
TriggerStep * step_list
Definition: sqlite3.c:15455
SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(sqlite3 *pDest, const char *zDestName, sqlite3 *pSource, const char *zSourceName)
Definition: sqlite3.c:67527
SQLITE_PRIVATE int sqlite3Init(sqlite3 *, char **)
Definition: sqlite3.c:112298
static int lockBtree(BtShared *pBt)
Definition: sqlite3.c:60475
SQLITE_PRIVATE char * sqlite3ColumnType(Column *, char *)
Definition: sqlite3.c:27095
SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *, int n)
Definition: sqlite3.c:74917
static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt)
Definition: sqlite3.c:136254
#define SQLITE_ROW
Definition: sqlite3.c:686
static char * createTableStmt(sqlite3 *db, Table *p)
Definition: sqlite3.c:98287
static int walRestartLog(Wal *pWal)
Definition: sqlite3.c:56000
static void pagerReleaseMapPage(PgHdr *pPg)
Definition: sqlite3.c:49803
u8 * aCellIdx
Definition: sqlite3.c:56972
#define PGHDR_MMAP
Definition: sqlite3.c:12985
#define SF_All
Definition: sqlite3.c:15073
u16 sharedMask
Definition: sqlite3.c:33161
#define SQLITE_DBSTATUS_STMT_USED
Definition: sqlite3.c:7068
#define SQLITE_PreferBuiltin
Definition: sqlite3.c:13827
SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *)
Definition: sqlite3.c:90200
static void printfFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102796
#define OP_IfPos
Definition: sqlite3.c:12403
int szCache
Definition: sqlite3.c:43096
SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256]
Definition: sqlite3.c:16750
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_new(sqlite3 *, int, sqlite3_value **)
static int allSpaces(const char *z, int n)
Definition: sqlite3.c:136435
static const char aDigits[]
Definition: sqlite3.c:24508
SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int, const void *, UnpackedRecord *)
Definition: sqlite3.c:73972
#define SQLITE_OPEN_AUTOPROXY
Definition: sqlite3.c:774
#define TK_AND
Definition: sqlite3.c:11128
SQLITE_PRIVATE FKey * sqlite3FkReferences(Table *)
Definition: sqlite3.c:105060
u8 incrVacuum
Definition: sqlite3.c:57097
SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *)
Definition: sqlite3.c:47519
#define IN_INDEX_LOOP
Definition: sqlite3.c:16547
SQLITE_PRIVATE Select * sqlite3SelectNew(Parse *, ExprList *, SrcList *, Expr *, ExprList *, Expr *, ExprList *, u32, Expr *, Expr *)
Definition: sqlite3.c:112904
u8 accError
Definition: sqlite3.c:15546
#define SQLITE_FCNTL_TEMPFILENAME
Definition: sqlite3.c:1259
static void releaseAllSavepoints(Pager *pPager)
Definition: sqlite3.c:47529
GLdouble GLdouble GLdouble w
#define SQLITE_CREATE_TABLE
Definition: sqlite3.c:2971
SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *, const Mem *, int)
Definition: sqlite3.c:68966
SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *)
Definition: sqlite3.c:27810
SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob64(sqlite3_stmt *, int, sqlite3_uint64)
Definition: sqlite3.c:75913
void(* xSelectCallback2)(Walker *, Select *)
Definition: sqlite3.c:15655
#define SQLITE_MISUSE_BKPT
Definition: sqlite3.c:15732
#define SQLITE_TESTCTRL_RESERVE
Definition: sqlite3.c:6807
static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg)
Definition: sqlite3.c:120653
SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_value_dup(const sqlite3_value *)
Definition: sqlite3.c:74733
#define SQLITE_BLOB
Definition: sqlite3.c:4220
unsigned int nMin
Definition: sqlite3.c:44082
int addrExplain
Definition: sqlite3.c:17745
SQLITE_PRIVATE int sqlite3MallocInit(void)
Definition: sqlite3.c:23739
SQLITE_PRIVATE void sqlite3VtabLock(VTable *)
Definition: sqlite3.c:121121
#define SQLITE_ATTACH
Definition: sqlite3.c:2993
#define P4_INTARRAY
Definition: sqlite3.c:12292
static int unixDelete(sqlite3_vfs *NotUsed, const char *zPath, int dirSync)
Definition: sqlite3.c:34986
SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *)
Definition: sqlite3.c:74327
#define CURTYPE_SORTER
Definition: sqlite3.c:17466
#define SQLITE_UTF16LE
Definition: sqlite3.c:4588
#define sqlite3Isspace(x)
Definition: sqlite3.c:15777
INT8_TYPE i8
Definition: sqlite3.c:11451
#define TK_CASE
Definition: sqlite3.c:11236
#define OE_Abort
Definition: sqlite3.c:14353
ExprList * pConstExpr
Definition: sqlite3.c:15312
static void pcacheUnpin(PgHdr *p)
Definition: sqlite3.c:43282
static sqlite3_index_info * allocateIndexInfo(Parse *pParse, WhereClause *pWC, Bitmask mUnusable, struct SrcList_item *pSrc, ExprList *pOrderBy)
Definition: sqlite3.c:126722
static int pagerUndoCallback(void *pCtx, Pgno iPg)
Definition: sqlite3.c:48821
#define SQLITE_IOERR_NOMEM_BKPT
Definition: sqlite3.c:15741
int(* xPhraseCount)(Fts5Context *)
Definition: sqlite3.c:10142
#define SQLITE_PRINTF_MALLOCED
Definition: sqlite3.c:15553
SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe *, int, int, int, int, const char *zP4, int)
Definition: sqlite3.c:70157
static const FuncDef statGetFuncdef
Definition: sqlite3.c:94943
d
Definition: rmse.py:171
int(* xAccess)(sqlite3_vfs *, const char *zName, int flags, int *pResOut)
Definition: sqlite3.c:1459
#define OP_String
Definition: sqlite3.c:12415
#define OPFLG_JUMP
Definition: sqlite3.c:12505
#define SQLITE_SOURCE_ID
Definition: sqlite3.c:368
#define PAGER_SYNCHRONOUS_OFF
Definition: sqlite3.c:12791
static int btreeInvokeBusyHandler(void *pArg)
Definition: sqlite3.c:59773
static volatile WalIndexHdr * walIndexHdr(Wal *pWal)
Definition: sqlite3.c:53804
#define WHERE_IDX_ONLY
Definition: sqlite3.c:122769
SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *, int, double)
Definition: sqlite3.c:75804
#define COLNAME_NAME
Definition: sqlite3.c:12308
#define TK_AS
Definition: sqlite3.c:11124
#define SQLITE_SYNC_FULL
Definition: sqlite3.c:875
#define SQLITE_READONLY_ROLLBACK
Definition: sqlite3.c:744
static int vdbeSorterJoinThread(SortSubtask *pTask)
Definition: sqlite3.c:85174
SQLITE_PRIVATE void sqlite3DropTrigger(Parse *, SrcList *, int)
Definition: sqlite3.c:119176
#define WHERE_COLUMN_EQ
Definition: sqlite3.c:122761
#define OP_SCopy
Definition: sqlite3.c:12422
VtabCtx * pPrior
Definition: sqlite3.c:121031
#define WAL_SAVEPOINT_NDATA
Definition: sqlite3.c:45740
#define ALWAYS(X)
Definition: sqlite3.c:10929
SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe *)
Definition: sqlite3.c:77180
#define TWOPOWER32
Definition: sqlite3.c:28284
int(* xStress)(void *, PgHdr *)
Definition: sqlite3.c:43102
static void groupConcatFinalize(sqlite3_context *context)
Definition: sqlite3.c:104172
#define SQLITE_LIMIT_VARIABLE_NUMBER
Definition: sqlite3.c:3538
static void substExprList(sqlite3 *, ExprList *, int, ExprList *)
Definition: sqlite3.c:115953
PgHdr * pDirty
Definition: sqlite3.c:12959
static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op)
Definition: sqlite3.c:130825
static int patternCompare(const u8 *zPattern, const u8 *zString, const struct compareInfo *pInfo, u32 matchOther)
Definition: sqlite3.c:103203
u8 setMaster
Definition: sqlite3.c:46464
SQLITE_PRIVATE void * sqlite3BtreeSchema(Btree *, int, void(*)(void *))
Definition: sqlite3.c:67197
SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *, int)
Definition: sqlite3.c:75622
#define MEM_Term
Definition: sqlite3.c:17653
#define SQLITE_CORRUPT_BKPT
Definition: sqlite3.c:15731
#define SQLITE_DONE
Definition: sqlite3.c:687
#define OptimizationDisabled(db, mask)
Definition: sqlite3.c:13863
#define WHERE_VIRTUALTABLE
Definition: sqlite3.c:122772
static SQLITE_NOINLINE void * dbMallocRawFinish(sqlite3 *db, u64 n)
Definition: sqlite3.c:24200
static void compileoptionusedFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103487
int nSrc
Definition: sqlite3.c:14892
SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *, int id, int newVal)
Definition: sqlite3.c:138015
static void pagerUnlockAndRollback(Pager *pPager)
Definition: sqlite3.c:47916
static void checkPtrmap(IntegrityCk *pCheck, Pgno iChild, u8 eType, Pgno iParent)
Definition: sqlite3.c:66563
SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *)
Definition: sqlite3.c:109286
struct PCache1 PCache1
Definition: sqlite3.c:44009
#define SQLITE_MUTEX_RECURSIVE
Definition: sqlite3.c:6704
static void lengthFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102665
char * zErrMsg
Definition: sqlite3.c:6131
SorterList list
Definition: sqlite3.c:84392
#define SQLITE_CONFIG_STMTJRNL_SPILL
Definition: sqlite3.c:2116
#define SQLITE_CREATE_TEMP_TRIGGER
Definition: sqlite3.c:2974
u8 enc
Definition: sqlite3.c:14085
PGroup * pGroup
Definition: sqlite3.c:44077
Expr * pExpr
Definition: sqlite3.c:14819
static void btreeParseCell(MemPage *pPage, int iCell, CellInfo *pInfo)
Definition: sqlite3.c:58867
static int codeEqualityTerm(Parse *pParse, WhereTerm *pTerm, WhereLevel *pLevel, int iEq, int bRev, int iTarget)
Definition: sqlite3.c:123108
#define OP_CursorHint
Definition: sqlite3.c:12497
SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage *)
Definition: sqlite3.c:51816
static int parseYyyyMmDd(const char *zDate, DateTime *p)
Definition: sqlite3.c:18585
static void SQLITE_NOINLINE vdbeChangeP4Full(Vdbe *p, Op *pOp, const char *zP4, int n)
Definition: sqlite3.c:70816
SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int)
Definition: sqlite3.c:18019
Module * pMod
Definition: sqlite3.c:14184
#define sqlite3IsNumericAffinity(X)
Definition: sqlite3.c:14118
SQLITE_API int SQLITE_STDCALL sqlite3_strlike(const char *zGlob, const char *zStr, unsigned int cEsc)
Definition: sqlite3.c:103332
#define WAL_NREADER
Definition: sqlite3.c:53498
static int walBusyLock(Wal *pWal, int(*xBusy)(void *), void *pBusyArg, int lockIdx, int n)
Definition: sqlite3.c:54853
static void spanBinaryExpr(Parse *pParse, int op, ExprSpan *pLeft, ExprSpan *pRight)
Definition: sqlite3.c:130792
static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed)
Definition: sqlite3.c:95512
char * zName
Definition: sqlite3.c:14197
SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *)
Definition: sqlite3.c:27273
char * zName
Definition: sqlite3.c:14059
SQLITE_PRIVATE Table * sqlite3SrcListLookup(Parse *, SrcList *)
Definition: sqlite3.c:101701
SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *, sqlite3_uint64)
Definition: sqlite3.c:24165
i64 journalOff
Definition: sqlite3.c:46481
SQLITE_API int SQLITE_STDCALL sqlite3_prepare(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:112688
static Expr * exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer)
Definition: sqlite3.c:89776
#define SQLITE_CONFIG_GETPCACHE
Definition: sqlite3.c:2105
#define SQLITE_SubqCoroutine
Definition: sqlite3.c:13852
#define SQLITE_UTF8
Definition: sqlite3.c:4587
SQLITE_PRIVATE void sqlite3Error(sqlite3 *, int)
Definition: sqlite3.c:27115
u32 nAlloc
Definition: sqlite3.c:118522
static int exprIsConst(Expr *p, int initFlag, int iCur)
Definition: sqlite3.c:90297
u8 inTransaction
Definition: sqlite3.c:57100
#define WHERE_DISTINCT_ORDERED
Definition: sqlite3.c:14969
sqlite3_mutex * mutex
Definition: sqlite3.c:33127
SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(sqlite3 *db, const void *zSql, int nByte, sqlite3_stmt **ppStmt, const void **pzTail)
Definition: sqlite3.c:112776
static void groupConcatStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104140
static void releasePage(MemPage *pPage)
Definition: sqlite3.c:59709
int nMaxSorterMmap
Definition: sqlite3.c:13695
#define SQLITE_OPEN_EXCLUSIVE
Definition: sqlite3.c:773
yDbMask lockMask
Definition: sqlite3.c:17799
SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *, int)
Definition: sqlite3.c:136810
SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3 *, void(*xProfile)(void *, const char *, sqlite3_uint64), void *)
Definition: sqlite3.c:137421
u32 nAlloc
Definition: sqlite3.c:15544
u8 nested
Definition: sqlite3.c:15279
sqlite_uint64 sqlite3_uint64
Definition: sqlite3.c:513
static KeyInfo * keyInfoFromExprList(Parse *pParse, ExprList *pList, int iStart, int nExtra)
Definition: sqlite3.c:113874
#define TRACE_IDX_INPUTS(A)
Definition: sqlite3.c:126483
SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *, int, int *)
Definition: sqlite3.c:66321
static void pthreadMutexEnter(sqlite3_mutex *p)
Definition: sqlite3.c:22772
#define HASHTABLE_NPAGE
Definition: sqlite3.c:53729
SQLITE_PRIVATE int sqlite3WalkExprList(Walker *, ExprList *)
Definition: sqlite3.c:87301
GLenum src
Definition: glext.h:1751
#define checkProfileCallback(DB, P)
Definition: sqlite3.c:74556
struct et_info et_info
#define PragTyp_MMAP_SIZE
Definition: sqlite3.c:109544
PgFreeslot * pNext
Definition: sqlite3.c:44103
SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *, const void *, int amt, i64 offset)
Definition: sqlite3.c:19561
#define TK_ID
Definition: sqlite3.c:11155
MemPage * pRef
Definition: sqlite3.c:64078
GLfloat GLfloat GLfloat GLfloat h
Definition: glext.h:1960
int(* xSetAuxdata)(Fts5Context *, void *pAux, void(*xDelete)(void *))
Definition: sqlite3.c:10155
BtShared * pBt
Definition: sqlite3.c:57028
static int vdbeSorterSetupMerge(VdbeSorter *pSorter)
Definition: sqlite3.c:86550
struct RowSetEntry * pForest
Definition: sqlite3.c:45278
GLdouble GLdouble z
SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *)
Definition: sqlite3.c:61268
u16 nField
Definition: sqlite3.c:14378
static int resolveOrderGroupBy(NameContext *pNC, Select *pSelect, ExprList *pOrderBy, const char *zType)
Definition: sqlite3.c:88453
#define SQLITE_CANTOPEN_CONVPATH
Definition: sqlite3.c:740
SQLITE_PRIVATE int sqlite3VdbeGoto(Vdbe *, int)
Definition: sqlite3.c:70118
u32 aHash[BITVEC_NINT]
Definition: sqlite3.c:42742
static const Mem * columnNullValue(void)
Definition: sqlite3.c:75383
static int walIndexTryHdr(Wal *pWal, int *pChanged)
Definition: sqlite3.c:55216
#define TK_REGISTER
Definition: sqlite3.c:11257
int nSavepoint
Definition: sqlite3.c:46485
SQLITE_API const char sqlite3_version[]
Definition: sqlite3.c:400
#define SQLITE_VdbeListing
Definition: sqlite3.c:13816
static void statPush(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:94729
static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut)
Definition: sqlite3.c:31108
SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *)
Definition: sqlite3.c:71395
#define WO_ALL
Definition: sqlite3.c:122753
unsigned int nCurrentPage
Definition: sqlite3.c:44059
#define TK_DISTINCT
Definition: sqlite3.c:11221
ynVar nVar
Definition: sqlite3.c:15348
static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags)
Definition: sqlite3.c:65949
int(* xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info *)
Definition: sqlite3.c:5894
#define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
Definition: sqlite3.c:12718
SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(BtCursor *, UnpackedRecord *pUnKey, i64 intKey, int bias, int *pRes)
Definition: sqlite3.c:62738
SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *, Expr *)
Definition: sqlite3.c:89566
#define SQLITE_FCNTL_TRACE
Definition: sqlite3.c:1261
#define CC_EQ
Definition: sqlite3.c:134358
static void reindexDatabases(Parse *pParse, char const *zColl)
Definition: sqlite3.c:100989
SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *, Vdbe *)
Definition: sqlite3.c:69969
GLdouble n
Definition: glext.h:1966
#define sqlite3ConnectionBlocked(x, y)
Definition: sqlite3.c:16576
GLint limit
Definition: glext.h:9964
ExprList * aColExpr
Definition: sqlite3.c:14477
static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType)
Definition: sqlite3.c:60991
unsigned char uint8_t
Definition: stdint.h:78
#define PragTyp_COLLATION_LIST
Definition: sqlite3.c:109527
#define SQLITE_IOERR_UNLOCK
Definition: sqlite3.c:713
#define CC_AND
Definition: sqlite3.c:134368
Bitvec * apSub[BITVEC_NPTR]
Definition: sqlite3.c:42743
i8 isOrdered
Definition: sqlite3.c:122425
static int fileHasMoved(unixFile *pFile)
Definition: sqlite3.c:30434
struct WalIterator WalIterator
Definition: sqlite3.c:53503
static int findIndexCol(Parse *pParse, ExprList *pList, int iBase, Index *pIdx, int iCol)
Definition: sqlite3.c:126282
const char * zPath
Definition: sqlite3.c:29112
#define SQLITE_TESTCTRL_ISINIT
Definition: sqlite3.c:6816
SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *)
Definition: sqlite3.c:75932
#define wsdAutoextInit
Definition: sqlite3.c:109347
int iStatement
Definition: sqlite3.c:17800
#define SF_Aggregate
Definition: sqlite3.c:15075
SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *)
Definition: sqlite3.c:68898
WhereOrInfo * pOrInfo
Definition: sqlite3.c:122486
KeyInfo * pKeyInfo
Definition: sqlite3.c:14421
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:137875
#define SHARED_FIRST
Definition: sqlite3.c:13332
#define NC_InAggFunc
Definition: sqlite3.c:15015
static int moveToChild(BtCursor *pCur, u32 newPgno)
Definition: sqlite3.c:62433
SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *)
Definition: sqlite3.c:68838
#define get2byteNotZero(X)
Definition: sqlite3.c:57714
unsigned int * anQueue
Definition: sqlite3.c:8552
sqlite3_mutex_methods mutex
Definition: sqlite3.c:15586
#define sqlite3_column_origin_name16
Definition: sqlite3.c:108730
static void returnSingleInt(Vdbe *v, const char *zLabel, i64 value)
Definition: sqlite3.c:110136
#define SPILLFLAG_ROLLBACK
Definition: sqlite3.c:46277
SQLITE_PRIVATE FuncDefHash sqlite3BuiltinFunctions
Definition: sqlite3.c:16892
FuncDef * pFunc
Definition: sqlite3.c:12222
#define CODEC1(P, D, N, X, E)
Definition: sqlite3.c:46235
#define PAGER_READER
Definition: sqlite3.c:46168
static void reindexTable(Parse *pParse, Table *pTab, char const *zColl)
Definition: sqlite3.c:100970
e
Definition: rmse.py:177
SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int)
Definition: sqlite3.c:119856
struct PgHdr PgHdr
Definition: sqlite3.c:12948
SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock)
Definition: sqlite3.c:67230
static int vdbeSorterOpenTempFile(sqlite3 *db, i64 nExtend, sqlite3_file **ppFd)
Definition: sqlite3.c:85366
#define INCRINIT_ROOT
Definition: sqlite3.c:86142
#define OP_InsertInt
Definition: sqlite3.c:12453
#define sqlite3_column_database_name
Definition: sqlite3.c:108725
SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *, int, void *)
Definition: sqlite3.c:19614
SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse)
Definition: sqlite3.c:106162
#define PragTyp_SECURE_DELETE
Definition: sqlite3.c:109546
static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p)
Definition: sqlite3.c:105072
#define SQLITE_CONSTRAINT_PRIMARYKEY
Definition: sqlite3.c:752
static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC)
Definition: sqlite3.c:58972
static void SQLITE_NOINLINE deleteTable(sqlite3 *db, Table *pTable)
Definition: sqlite3.c:97355
VdbeFrame * pFrame
Definition: sqlite3.c:17598
#define TK_STRING
Definition: sqlite3.c:11197
static void clearSelect(sqlite3 *db, Select *p, int bFree)
Definition: sqlite3.c:112870
static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104063
SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse *, int, Index *)
Definition: sqlite3.c:100894
UnpackedRecord * pUnpacked
Definition: sqlite3.c:17844
#define SQLITE_INTEGER
Definition: sqlite3.c:4218
static int pagerSyncHotJournal(Pager *pPager)
Definition: sqlite3.c:49740
#define OP_Transaction
Definition: sqlite3.c:12341
PgHdr1 * pNext
Definition: sqlite3.c:44026
sqlite3_vfs * pVfs
Definition: sqlite3.c:53643
#define valueFromFunction(a, b, c, d, e, f)
Definition: sqlite3.c:69432
u8 curPagerFlags
Definition: sqlite3.c:57194
#define TK_COLUMN
Definition: sqlite3.c:11252
static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef)
Definition: sqlite3.c:70684
SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *)
Definition: sqlite3.c:27265
SQLITE_PRIVATE int sqlite3FixSelect(DbFixer *, Select *)
Definition: sqlite3.c:96400
static int walWriteOneFrame(WalWriter *p, PgHdr *pPage, int nTruncate, sqlite3_int64 iOffset)
Definition: sqlite3.c:56088
#define TK_FAIL
Definition: sqlite3.c:11173
GLuint coord
Definition: glext.h:6213
void(* xDelete)(void *)
Definition: sqlite3.c:17696
sqlite3_context * pCtx
Definition: sqlite3.c:12223
#define OE_Rollback
Definition: sqlite3.c:14352
#define SQLITE_MUTEX_STATIC_VFS1
Definition: sqlite3.c:6716
#define TK_ON
Definition: sqlite3.c:11207
SQLITE_PRIVATE void * sqlite3PagerGetData(DbPage *)
Definition: sqlite3.c:52782
SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar)
Definition: sqlite3.c:26901
static void whereCombineDisjuncts(SrcList *pSrc, WhereClause *pWC, WhereTerm *pOne, WhereTerm *pTwo)
Definition: sqlite3.c:124928
signed char p1
Definition: sqlite3.c:12269
static const YYCODETYPE yy_lookahead[]
Definition: sqlite3.c:131189
static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg)
Definition: sqlite3.c:66521
int n
Definition: sqlite3.c:15660
#define SQLITE_IOERR_FSTAT
Definition: sqlite3.c:712
#define SQLITE_ERROR
Definition: sqlite3.c:658
int mxPathname
Definition: sqlite3.c:1452
#define SQLITE_DROP_VIEW
Definition: sqlite3.c:2986
#define JOURNAL_HDR_SZ(pPager)
Definition: sqlite3.c:46588
#define JOURNAL_PG_SZ(pPager)
Definition: sqlite3.c:46582
SQLITE_PRIVATE const char * sqlite3ErrStr(int)
Definition: sqlite3.c:136968
#define OP_VDestroy
Definition: sqlite3.c:12491
SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *, int)
Definition: sqlite3.c:134741
#define SQLITE_CREATE_VIEW
Definition: sqlite3.c:2977
#define UNIX_SHM_BASE
Definition: sqlite3.c:33168
static int nolockClose(sqlite3_file *id)
Definition: sqlite3.c:31125
int iLeftJoin
Definition: sqlite3.c:122298
u32 wsFlags
Definition: sqlite3.c:122370
#define CHECK_PAGE(x)
Definition: sqlite3.c:47034
#define SF_Distinct
Definition: sqlite3.c:15072
#define SQLITE_BUSY_RECOVERY
Definition: sqlite3.c:735
#define OS_VXWORKS
Definition: sqlite3.c:158
SQLITE_PRIVATE char * sqlite3NameFromToken(sqlite3 *, Token *)
Definition: sqlite3.c:97438
static void codeTableLocks(Parse *pParse)
Definition: sqlite3.c:96849
SQLITE_PRIVATE void sqlite3AuthContextPush(Parse *, AuthContext *, const char *)
Definition: sqlite3.c:96735
u8 inTrans
Definition: sqlite3.c:57029
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
GLuint GLsizei const void GLenum preserve
Definition: glext.h:6342
int(* xExprCallback)(Walker *, Expr *)
Definition: sqlite3.c:15653
UnpackedRecord * pUnpacked
Definition: sqlite3.c:84364
SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *)
Definition: sqlite3.c:28237
static int write32bits(sqlite3_file *fd, i64 offset, u32 val)
Definition: sqlite3.c:46895
#define findCellPastPtr(P, I)
Definition: sqlite3.c:58690
#define SQLITE_OPEN_MASTER_JOURNAL
Definition: sqlite3.c:783
#define SQLITE_INTERRUPT
Definition: sqlite3.c:666
#define osGetcwd
SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int)
Definition: sqlite3.c:139003
static void yy_reduce(yyParser *yypParser, unsigned int yyruleno)
Definition: sqlite3.c:132806
#define ArraySize(X)
Definition: sqlite3.c:11708
SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *)
Definition: sqlite3.c:75978
Expr * pRight
Definition: sqlite3.c:14682
SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *)
Definition: sqlite3.c:68439
u8 isInit
Definition: sqlite3.c:56951
#define WRITE_UTF16BE(zOut, c)
Definition: sqlite3.c:26539
int(* xRelease)(sqlite3_vtab *pVTab, int)
Definition: sqlite3.c:5917
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo)
Definition: sqlite3.c:92943
SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *)
Definition: sqlite3.c:28114
def all()
Definition: devices.py:166
#define sqlite3VdbeVerifyNoMallocRequired(A, B)
Definition: sqlite3.c:12564
int * aiCol
Definition: sqlite3.c:15665
#define PragTyp_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:109531
#define TK_ROW
Definition: sqlite3.c:11187
#define TK_UNION
Definition: sqlite3.c:11215
#define SQLITE_MAX_PAGE_COUNT
Definition: sqlite3.c:10645
static SQLITE_NOINLINE int pagerAddPageToRollbackJournal(PgHdr *pPg)
Definition: sqlite3.c:51524
#define BTREE_FREE_PAGE_COUNT
Definition: sqlite3.c:11968
int addrBody
Definition: sqlite3.c:122306
void(* xDlError)(sqlite3_vfs *, int nByte, char *zErrMsg)
Definition: sqlite3.c:1462
static int hasColumn(const i16 *aiCol, int nCol, int x)
Definition: sqlite3.c:98407
#define PTRMAP_PTROFFSET(pgptrmap, pgno)
Definition: sqlite3.c:57275
#define PragTyp_LOCK_STATUS
Definition: sqlite3.c:109561
#define OP_Prev
Definition: sqlite3.c:12345
static const char * unixTempFileDir(void)
Definition: sqlite3.c:34503
#define UNIX_SHM_DMS
Definition: sqlite3.c:33169
static void unixLeaveMutex(void)
Definition: sqlite3.c:29779
SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *)
Definition: sqlite3.c:87232
SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int)
Definition: sqlite3.c:61690
#define TK_ALL
Definition: sqlite3.c:11216
char * z
Definition: sqlite3.c:17604
static void attachBackupObject(sqlite3_backup *p)
Definition: sqlite3.c:67723
#define SQLITE_TESTCTRL_PRNG_SAVE
Definition: sqlite3.c:6798
signed char p2
Definition: sqlite3.c:12270
static const sqlite3_api_routines sqlite3Apis
Definition: sqlite3.c:108823
static int sqliteProcessJoin(Parse *pParse, Select *p)
Definition: sqlite3.c:113207
const u8 * aRow
Definition: sqlite3.c:17527
#define SQLITE_CoverIdxScan
Definition: sqlite3.c:13850
#define PAGER_OMIT_JOURNAL
Definition: sqlite3.c:12752
i64 nKey
Definition: sqlite3.c:57144
SQLITE_API int SQLITE_STDCALL 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:138711
#define VisibleRowid(X)
Definition: sqlite3.c:14279
#define btreeIntegrity(p)
Definition: sqlite3.c:57318
u8 writeLock
Definition: sqlite3.c:53655
SQLITE_PRIVATE char * sqlite3VMPrintf(sqlite3 *, const char *, va_list)
Definition: sqlite3.c:25359
SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *)
Definition: sqlite3.c:52373
SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *)
Definition: sqlite3.c:93943
int bUseThread
Definition: sqlite3.c:84467
PgHdr * pDirtyTail
Definition: sqlite3.c:43093
sqlite3ParserARG_SDECL yyStackEntry yystack[YYSTACKDEPTH]
Definition: sqlite3.c:131633
SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *)
Definition: sqlite3.c:19660
#define SQLITE_FUNC_UNLIKELY
Definition: sqlite3.c:13954
static int incrAggDepth(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:87431
DbPage * pDbPage
Definition: sqlite3.c:56974
void * pEnd
Definition: sqlite3.c:13605
SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt)
Definition: sqlite3.c:76053
SQLITE_PRIVATE void sqlite3Vacuum(Parse *)
Definition: sqlite3.c:120732
SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *, int)
Definition: sqlite3.c:75827
#define OP_BitNot
Definition: sqlite3.c:12393
#define CLEARBIT(V, I)
Definition: sqlite3.c:42941
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *)
Definition: sqlite3.c:136501
#define OP_Seek
Definition: sqlite3.c:12465
#define SQLITE_MISUSE
Definition: sqlite3.c:678
unixShmNode * pShmNode
Definition: sqlite3.c:33157
GLenum GLuint id
#define SQLITE_DEFAULT_MMAP_SIZE
Definition: sqlite3.c:11638
int iBatch
Definition: sqlite3.c:45281
int(* xMutexInit)(void)
Definition: sqlite3.c:6648
static int fkChildIsModified(Table *pTab, FKey *p, int *aChange, int bChngRowid)
Definition: sqlite3.c:105161
static void estimateIndexWidth(Index *pIdx)
Definition: sqlite3.c:98393
int szOpAlloc
Definition: sqlite3.c:15296
#define HASHTABLE_NPAGE_ONE
Definition: sqlite3.c:53738
static void minmaxFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102614
#define sqlite3ColumnPropertiesFromName(T, C)
Definition: sqlite3.c:15962
#define COLNAME_COLUMN
Definition: sqlite3.c:12312
static int walIndexReadHdr(Wal *pWal, int *pChanged)
Definition: sqlite3.c:55274
SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **)
Definition: sqlite3.c:97510
SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int)
Definition: sqlite3.c:19727
#define sqlite3ParserARG_SDECL
Definition: sqlite3.c:130953
static SQLITE_NOINLINE Vdbe * allocVdbe(Parse *pParse)
Definition: sqlite3.c:114596
#define SQLITE_BYTEORDER
Definition: sqlite3.c:11564
static const char * columnTypeImpl(NameContext *pNC, Expr *pExpr, u8 *pEstWidth)
Definition: sqlite3.c:114140
#define VdbeNoopComment(X)
Definition: sqlite3.c:12640
int aiCur[11]
Definition: sqlite3.c:122533
SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *)
Definition: sqlite3.c:19876
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *, ExprList *)
Definition: sqlite3.c:93116
static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes)
Definition: sqlite3.c:46876
#define TK_CTIME_KW
Definition: sqlite3.c:11195
static FuncDef * functionSearch(int h, const char *zFunc)
Definition: sqlite3.c:101468
#define TK_VALUES
Definition: sqlite3.c:11220
SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *, int, int, int, int)
Definition: sqlite3.c:70060
static LogEst whereSortingCost(WhereInfo *pWInfo, LogEst nRow, int nOrderBy, int nSorted)
Definition: sqlite3.c:129453
SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *, int)
Definition: sqlite3.c:74841
#define osGeteuid
static void rowSetTreeToList(struct RowSetEntry *pIn, struct RowSetEntry **ppFirst, struct RowSetEntry **ppLast)
Definition: sqlite3.c:45466
SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *)
Definition: sqlite3.c:74849
static int pager_delmaster(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:48271
static int unixShmRegionPerMap(void)
Definition: sqlite3.c:33256
static void pagerUnlockIfUnused(Pager *pPager)
Definition: sqlite3.c:51071
#define ExprSetVVAProperty(E, P)
Definition: sqlite3.c:14759
#define SQLITE_IOERR_NOMEM
Definition: sqlite3.c:717
status
Defines return codes that SDK interfaces use. Negative values indicate errors, a zero value indicates...
static int subjRequiresPage(PgHdr *pPg)
Definition: sqlite3.c:46846
static SQLITE_NOINLINE int apiOomError(sqlite3 *db)
Definition: sqlite3.c:24406
SQLITE_PRIVATE void sqlite3Dequote(char *)
Definition: sqlite3.c:27221
Schema * pSchema
Definition: sqlite3.c:13513
SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint)
Definition: sqlite3.c:52474
static int vdbeSorterTreeDepth(int nPMA)
Definition: sqlite3.c:86397
Bitmask prereq
Definition: sqlite3.c:122386
i16 iAgg
Definition: sqlite3.c:14702
static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull)
Definition: sqlite3.c:90550
#define osPread
SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *, unsigned int mask)
Definition: sqlite3.c:67354
SQLITE_PRIVATE int sqlite3AuthCheck(Parse *, int, const char *, const char *, const char *)
Definition: sqlite3.c:96695
static int resolveExprStep(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:87968
#define TK_ISNOT
Definition: sqlite3.c:11248
#define pcache1EnterMutex(X)
Definition: sqlite3.c:44146
u16 nRef
Definition: sqlite3.c:14208
u8 * aBuffer
Definition: sqlite3.c:84423
#define TK_SPACE
Definition: sqlite3.c:11260
#define BTREE_FILE_FORMAT
Definition: sqlite3.c:11970
SQLITE_PRIVATE int sqlite3IsRowid(const char *)
Definition: sqlite3.c:90484
SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *, i64)
Definition: sqlite3.c:45370
#define OP_JournalMode
Definition: sqlite3.c:12348
#define SQLITE_FCNTL_LOCKSTATE
Definition: sqlite3.c:1244
#define BTREE_SEEK_EQ
Definition: sqlite3.c:12022
static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt)
Definition: sqlite3.c:109994
i64 lastRowid
Definition: sqlite3.c:17566
SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *, int)
Definition: sqlite3.c:102562
struct RowSetEntry * pFresh
Definition: sqlite3.c:45277
SQLITE_PRIVATE void sqlite3Pragma(Parse *, Token *, Token *, Token *, int)
Definition: sqlite3.c:110245
static void walUnlockExclusive(Wal *pWal, int lockIdx, int n)
Definition: sqlite3.c:54041
SQLITE_PRIVATE void sqlite3MultiWrite(Parse *)
Definition: sqlite3.c:100843
#define SQLITE_MAX_VDBE_OP
Definition: sqlite3.c:10544
#define SAVEPOINT_ROLLBACK
Definition: sqlite3.c:14038
SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *, DbPage *, Pgno, int)
Definition: sqlite3.c:52639
static void storeLastErrno(unixFile *pFile, int error)
Definition: sqlite3.c:30292
static void * pcache1Alloc(int nByte)
Definition: sqlite3.c:44236
#define SQLITE_MAGIC_BUSY
Definition: sqlite3.c:13884
int nVdbeRead
Definition: sqlite3.c:13704
void * pSchema
Definition: sqlite3.c:57114
Btree * pBtree
Definition: sqlite3.c:57182
#define Deephemeralize(P)
Definition: sqlite3.c:76703
u16 nColumn
Definition: sqlite3.c:14481
static int nocaseCollatingFunc(void *NotUsed, int nKey1, const void *pKey1, int nKey2, const void *pKey2)
Definition: sqlite3.c:136484
LogEst rUnsorted
Definition: sqlite3.c:122424
#define PragTyp_TEMP_STORE_DIRECTORY
Definition: sqlite3.c:109553
#define SQLITE_EXTENSION_INIT2(v)
Definition: sqlite3.c:108706
struct KeyInfo KeyInfo
Definition: sqlite3.c:11792
int tnum
Definition: sqlite3.c:14478
Hash fkeyHash
Definition: sqlite3.c:13539
u8 enc
Definition: sqlite3.c:17601
SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *, int)
Definition: sqlite3.c:74370
#define yytestcase(X)
Definition: sqlite3.c:130690
static void schemaIsValid(Parse *pParse)
Definition: sqlite3.c:112362
int nTotalChange
Definition: sqlite3.c:13693
#define TERM_VNULL
Definition: sqlite3.c:122512
SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *, int, char)
Definition: sqlite3.c:25245
SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *)
Definition: sqlite3.c:121861
SQLITE_PRIVATE SrcList * sqlite3SrcListDup(sqlite3 *, SrcList *, int)
Definition: sqlite3.c:89948
#define WHERE_COLUMN_RANGE
Definition: sqlite3.c:122762
#define SQLITE_READONLY_RECOVERY
Definition: sqlite3.c:742
u32 nPage
Definition: sqlite3.c:57113
SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *, Expr *, int, int)
Definition: sqlite3.c:92453
union WhereTerm::@140 u
#define OP_IncrVacuum
Definition: sqlite3.c:12406
#define sqlite3FileSuffix3(X, Y)
Definition: sqlite3.c:16302
#define SQLITE_MAX_LENGTH
Definition: sqlite3.c:10478
#define PragTyp_FOREIGN_KEY_LIST
Definition: sqlite3.c:109534
int idxNum
Definition: sqlite3.c:122363
#define BTREE_SAVEPOSITION
Definition: sqlite3.c:12077
SQLITE_PRIVATE void sqlite3ParserReset(Parse *)
Definition: sqlite3.c:112439
#define sqliteHashNext(E)
Definition: sqlite3.c:11085
static void yy_destructor(yyParser *yypParser, YYCODETYPE yymajor, YYMINORTYPE *yypminor)
Definition: sqlite3.c:132142
unixShm * pFirst
Definition: sqlite3.c:33135
GLdouble t
#define SQLITE_DETERMINISTIC
Definition: sqlite3.c:4602
#define P5_ConstraintFK
Definition: sqlite3.c:12302
#define PAGER_WRITER_CACHEMOD
Definition: sqlite3.c:46170
TableLock * aTableLock
Definition: sqlite3.c:15326
static int xferCompatibleIndex(Index *pDest, Index *pSrc)
Definition: sqlite3.c:107626
Index * pIndex
Definition: sqlite3.c:14199
const unsigned char * b
Definition: sqlite3.c:9909
#define OP_Or
Definition: sqlite3.c:12366
#define SQLITE_STATUS_SCRATCH_OVERFLOW
Definition: sqlite3.c:6943
static const char aPrefix[]
Definition: sqlite3.c:24509
sqlite3 * db
Definition: sqlite3.c:57091
GLboolean GLboolean GLboolean GLboolean a
SQLITE_PRIVATE void sqlite3PcacheClear(PCache *)
Definition: sqlite3.c:43735
#define SF_Compound
Definition: sqlite3.c:15080
FKey * pFKey
Definition: sqlite3.c:14201
SQLITE_PRIVATE void sqlite3StatusDown(int, int)
Definition: sqlite3.c:18050
#define OP_Null
Definition: sqlite3.c:12416
Expr * pOffset
Definition: sqlite3.c:130710
#define PragTyp_INDEX_INFO
Definition: sqlite3.c:109536
static int exprSrcCount(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:92880
u8 * aMemory
Definition: sqlite3.c:84253
#define SRT_Set
Definition: sqlite3.c:15170
#define SQLITE_LIMIT_COLUMN
Definition: sqlite3.c:3531
SQLITE_PRIVATE Table * sqlite3ResultSetOfSelect(Parse *, Select *)
Definition: sqlite3.c:114560
static const struct compareInfo likeInfoNorm
Definition: sqlite3.c:103163
etByte prefix
Definition: sqlite3.c:24493
SQLITE_PRIVATE Expr * sqlite3PExpr(Parse *, int, Expr *, Expr *, const Token *)
Definition: sqlite3.c:89443
SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse *, Table *, int, int, int *, int)
Definition: sqlite3.c:102440
sqlite3_vfs * pNext
Definition: sqlite3.c:1453
GLenum GLuint GLenum GLsizei const GLchar * buf
#define BTREE_SCHEMA_VERSION
Definition: sqlite3.c:11969
static int walIteratorInit(Wal *pWal, WalIterator **pp)
Definition: sqlite3.c:54771
SQLITE_PRIVATE int sqlite3WalDefaultHook(void *, sqlite3 *, const char *, int)
Definition: sqlite3.c:137547
char validYMD
Definition: sqlite3.c:18372
static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName)
Definition: sqlite3.c:93543
static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p)
Definition: sqlite3.c:57411
u16 maskPage
Definition: sqlite3.c:56965
GLenum GLsizei len
Definition: glext.h:3285
SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *)
Definition: sqlite3.c:68124
GLuint GLfloat * val
GLuint64 key
Definition: glext.h:8966
SQLITE_PRIVATE void sqlite3AuthRead(Parse *, Expr *, Schema *, SrcList *)
Definition: sqlite3.c:96638
#define SQLITE_OPEN_TEMP_JOURNAL
Definition: sqlite3.c:781
#define SQLITE_OPEN_DELETEONCLOSE
Definition: sqlite3.c:772
i64 mxWalSize
Definition: sqlite3.c:53647
With * pOuter
Definition: sqlite3.c:15691
SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *, int, int)
Definition: sqlite3.c:100829
static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage)
Definition: sqlite3.c:99505
SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt *, int, const void *, int n, void(*)(void *))
Definition: sqlite3.c:75778
#define MemSetTypeFlag(p, f)
Definition: sqlite3.c:17674
static int balance_nonroot(MemPage *pParent, int iParentIdx, u8 *aOvflSpace, int isRoot, int bBulk)
Definition: sqlite3.c:64659
SQLITE_PRIVATE int sqlite3RunParser(Parse *, const char *, char **)
Definition: sqlite3.c:135080
static int hasHotJournal(Pager *pPager, int *pExists)
Definition: sqlite3.c:50729
ExprList * pEList
Definition: sqlite3.c:14996
int iSavepoint
Definition: sqlite3.c:14188
#define CC_DOLLAR
Definition: sqlite3.c:134348
#define vdbeSorterExtendFile(x, y, z)
Definition: sqlite3.c:85358
static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize)
Definition: sqlite3.c:59239
def info(name, value, persistent=False)
Definition: test.py:301
SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int)
Definition: sqlite3.c:22227
SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *, int)
Definition: sqlite3.c:70267
#define SQLITE_DBSTATUS_LOOKASIDE_USED
Definition: sqlite3.c:7065
int nThis
Definition: sqlite3.c:92873
static void exprCodeBetween(Parse *pParse, Expr *pExpr, int dest, int jumpIfTrue, int jumpIfNull)
Definition: sqlite3.c:92396
#define OP_Checkpoint
Definition: sqlite3.c:12347
sqlite3 * db
Definition: sqlite3.c:95432
bft readOnly
Definition: sqlite3.c:17794
static int indexColumnNotNull(Index *pIdx, int iCol)
Definition: sqlite3.c:126311
SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3 *, void(*)(void *), void *)
Definition: sqlite3.c:137498
#define CC_QUOTE
Definition: sqlite3.c:134352
static int isSetNullAction(Parse *pParse, FKey *pFKey)
Definition: sqlite3.c:105217
static int vdbeMergeEngineStep(MergeEngine *pMerger, int *pbEof)
Definition: sqlite3.c:85675
SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *, void *, int amt, i64 offset)
Definition: sqlite3.c:19557
SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *)
Definition: sqlite3.c:61510
#define OSTRACE(X)
Definition: sqlite3.c:10957
#define pager_set_pagehash(X)
Definition: sqlite3.c:47033
int(* xCreateFunction)(fts5_api *pApi, const char *zName, void *pContext, fts5_extension_function xFunction, void(*xDestroy)(void *))
Definition: sqlite3.c:10420
static const char statMutex[]
Definition: sqlite3.c:17987
SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *, int)
Definition: sqlite3.c:75943
SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *, int op, int resetFlg)
Definition: sqlite3.c:76074
#define SQLITE_EnableTrigger
Definition: sqlite3.c:13830
ExprSpan yy342
Definition: sqlite3.c:130944
static int growVTrans(sqlite3 *db)
Definition: sqlite3.c:121647
void sqliteViewTriggers(Parse *, Table *, Expr *, int, ExprList *)
unsigned int yDbMask
Definition: sqlite3.c:15248
int(* xInst)(Fts5Context *, int iIdx, int *piPhrase, int *piCol, int *piOff)
Definition: sqlite3.c:10146
struct sqlite3_index_info::sqlite3_index_orderby * aOrderBy
SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *, int ms)
Definition: sqlite3.c:137137
int(* xCreateTokenizer)(fts5_api *pApi, const char *zName, void *pContext, fts5_tokenizer *pTokenizer, void(*xDestroy)(void *))
Definition: sqlite3.c:10403
union ExprList::ExprList_item::@127 u
SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse *, Expr *)
Definition: sqlite3.c:98114
SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName)
Definition: sqlite3.c:139473
#define TK_INTEGER
Definition: sqlite3.c:11232
int aLimit[SQLITE_N_LIMIT]
Definition: sqlite3.c:13694
#define SQLITE_IOERR_WRITE
Definition: sqlite3.c:708
#define ExprHasProperty(E, P)
Definition: sqlite3.c:14747
static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2)
Definition: sqlite3.c:31117
#define SQLITE_FUNC_EPHEM
Definition: sqlite3.c:13948
int nOvflAlloc
Definition: sqlite3.c:57190
Trigger * pTrig
Definition: sqlite3.c:15510
ExprList * pOrderBy
Definition: sqlite3.c:112855
#define TK_SEMI
Definition: sqlite3.c:11101
static SQLITE_NOINLINE void invokeProfileCallback(sqlite3 *db, Vdbe *p)
Definition: sqlite3.c:74542
SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(sqlite3 *pBlocked, void(*xNotify)(void **apArg, int nArg), void *pNotifyArg)
static int pagerFlushOnCommit(Pager *pPager, int bCommit)
Definition: sqlite3.c:47710
SQLITE_PRIVATE Vdbe * sqlite3GetVdbe(Parse *)
Definition: sqlite3.c:114606
int(* xTokenize)(Fts5Context *, const char *pText, int nText, void *pCtx, int(*xToken)(void *, int, const char *, int, int, int))
Definition: sqlite3.c:10136
#define OP_VOpen
Definition: sqlite3.c:12492
static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd)
Definition: sqlite3.c:130774
void(* xDestroy)(void *)
Definition: sqlite3.c:13928
static int exprAlwaysFalse(Expr *p)
Definition: sqlite3.c:89500
#define WRC_Prune
Definition: sqlite3.c:15682
static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock)
Definition: sqlite3.c:57917
u8 p5
Definition: sqlite3.c:12212
static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno)
Definition: sqlite3.c:58641
i64 iCurrentTime
Definition: sqlite3.c:17805
#define SQLITE_ECEL_FACTOR
Definition: sqlite3.c:16083
SQLITE_PRIVATE void sqlite3AddCollateType(Parse *, Token *)
Definition: sqlite3.c:98139
#define osGetpagesize
SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt)
Definition: sqlite3.c:69961
static void vdbePmaReaderClear(PmaReader *pReadr)
Definition: sqlite3.c:84534
static UnixUnusedFd * findReusableFd(const char *zPath, int flags)
Definition: sqlite3.c:34587
static int whereShortCut(WhereLoopBuilder *pBuilder)
Definition: sqlite3.c:129848
SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void)
Definition: sqlite3.c:67368
PgHdr * pDirtyPrev
Definition: sqlite3.c:12975
SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void)
Definition: sqlite3.c:135649
Parse * pParse
Definition: sqlite3.c:15395
SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *, int makeDflt)
Definition: sqlite3.c:19848
u16 nXField
Definition: sqlite3.c:14379
#define SQLITE_BIG_DBL
Definition: sqlite3.c:11295
SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *, Trigger *)
Definition: sqlite3.c:119158
SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt *, int, const char *, sqlite3_uint64, void(*)(void *), unsigned char encoding)
Definition: sqlite3.c:75845
#define SQLITE_FCNTL_POWERSAFE_OVERWRITE
Definition: sqlite3.c:1256
#define WHERE_ORDERBY_MAX
Definition: sqlite3.c:14949
Btree * pBtree
Definition: sqlite3.c:56995
#define SQLITE_CONFIG_SCRATCH
Definition: sqlite3.c:2096
#define DB_Empty
Definition: sqlite3.c:13568
ynVar nzVar
Definition: sqlite3.c:17778
SQLITE_PRIVATE void * sqlite3Realloc(void *, u64)
Definition: sqlite3.c:24106
#define sqlite3VdbeIOTraceSql(X)
Definition: sqlite3.c:16596
static int getAutoVacuum(const char *z)
Definition: sqlite3.c:110047
u8 bConstraint
Definition: sqlite3.c:14187
SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *)
Definition: sqlite3.c:68398
static int moveToLeftmost(BtCursor *pCur)
Definition: sqlite3.c:62596
u8 op2
Definition: sqlite3.c:14704
static int blobReadWrite(sqlite3_blob *pBlob, void *z, int n, int iOffset, int(*xCall)(BtCursor *, u32, u32, void *))
Definition: sqlite3.c:83927
#define WALINDEX_PGSZ
Definition: sqlite3.c:53741
static int analyzeAggregate(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:92960
SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *)
Definition: sqlite3.c:70767
Pgno * aOverflow
Definition: sqlite3.c:57185
SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor *, const void *pKey, i64 nKey, const void *pData, int nData, int nZero, int bias, int seekResult)
Definition: sqlite3.c:65619
SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *, int)
Definition: sqlite3.c:60406
SQLITE_PRIVATE char * sqlite3StrAccumFinish(StrAccum *)
Definition: sqlite3.c:25302
char * zName
Definition: sqlite3.c:15446
SQLITE_PRIVATE int sqlite3PagerRollback(Pager *)
Definition: sqlite3.c:52244
static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N)
Definition: sqlite3.c:25262
SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *)
Definition: sqlite3.c:59627
u32 nRef
Definition: sqlite3.c:14376
static int unixShmMap(sqlite3_file *fd, int iRegion, int szRegion, int bExtend, void volatile **pp)
Definition: sqlite3.c:33479
int szExtra
Definition: sqlite3.c:44079
GLdouble f
SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse *, Select *, NameContext *)
Definition: sqlite3.c:88849
u8 isDeferred
Definition: sqlite3.c:14317
static int decodeFlags(MemPage *pPage, int flagByte)
Definition: sqlite3.c:59338
int seekResult
Definition: sqlite3.c:17505
static void setPendingFd(unixFile *pFile)
Definition: sqlite3.c:30824
static int pagerOpenWal(Pager *pPager)
Definition: sqlite3.c:53045
static void walIndexClose(Wal *pWal, int isDelete)
Definition: sqlite3.c:54467
static void yy_pop_parser_stack(yyParser *pParser)
Definition: sqlite3.c:132243
SQLITE_PRIVATE void sqlite3WalLimit(Wal *, i64)
Definition: sqlite3.c:54568
static const struct compareInfo likeInfoAlt
Definition: sqlite3.c:103166
SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *, int *pRes)
Definition: sqlite3.c:62667
#define TK_EXCLUSIVE
Definition: sqlite3.c:11109
#define OP_SeekGE
Definition: sqlite3.c:12364
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void)
Definition: sqlite3.c:23800
SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *)
Definition: sqlite3.c:52980
int iOffset
Definition: sqlite3.c:83585
SQLITE_PRIVATE sqlite3_value * sqlite3VdbeGetBoundValue(Vdbe *, int, u8)
Definition: sqlite3.c:74349
static void pagerFreeMapHdrs(Pager *pPager)
Definition: sqlite3.c:49816
#define WO_NOOP
Definition: sqlite3.c:122751
#define BTREE_WRCSR
Definition: sqlite3.c:12047
#define likely(X)
Definition: sqlite3.c:10995
#define OP_VNext
Definition: sqlite3.c:12407
#define TK_THEN
Definition: sqlite3.c:11238
u8 * aOnceFlag
Definition: sqlite3.c:17563
static SQLITE_NOINLINE void vdbeLeave(Vdbe *p)
Definition: sqlite3.c:71299
#define WHERE_BTM_LIMIT
Definition: sqlite3.c:122767
static u16 cellSizePtr(MemPage *pPage, u8 *pCell)
Definition: sqlite3.c:58887
#define TK_EQ
Definition: sqlite3.c:11137
SQLITE_PRIVATE int sqlite3GetTempRange(Parse *, int)
Definition: sqlite3.c:93161
u32 usableSize
Definition: sqlite3.c:57111
#define WRITE_UTF16LE(zOut, c)
Definition: sqlite3.c:26527
static int isDistinctRedundant(Parse *pParse, SrcList *pTabList, WhereClause *pWC, ExprList *pDistinct)
Definition: sqlite3.c:126334
static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p)
Definition: sqlite3.c:116744
GLenum mode
#define CC_SEMI
Definition: sqlite3.c:134363
Wal * pWal
Definition: sqlite3.c:46521
#define OP_ReopenIdx
Definition: sqlite3.c:12440
#define CORRUPT_DB
Definition: sqlite3.c:15646
i16 * aiColumn
Definition: sqlite3.c:14468
SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N)
Definition: sqlite3.c:23731
static int vdbeIncrBgPopulate(IncrMerger *pIncr)
Definition: sqlite3.c:85987
i64 journalSizeLimit
Definition: sqlite3.c:46502
#define TK_CREATE
Definition: sqlite3.c:11117
int nBuffer
Definition: sqlite3.c:84424
static int walWriteToLog(WalWriter *p, void *pContent, int iAmt, sqlite3_int64 iOffset)
Definition: sqlite3.c:56063
int(* xClose)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:5898
#define SQLITE_OPEN_TEMP_DB
Definition: sqlite3.c:778
static CollSeq * findCollSeqEntry(sqlite3 *db, const char *zName, int create)
Definition: sqlite3.c:101333
#define sqlite3_column_origin_name
Definition: sqlite3.c:108729
SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *, Select *)
Definition: sqlite3.c:87336
static int noopMutexEnd(void)
Definition: sqlite3.c:22349
SQLITE_PRIVATE sqlite3_mutex_methods const * sqlite3DefaultMutex(void)
Definition: sqlite3.c:22894
static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow)
Definition: sqlite3.c:35273
static void generateSortTail(Parse *pParse, Select *p, SortCtx *pSort, int nColumn, SelectDest *pDest)
Definition: sqlite3.c:113992
SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt)
Definition: sqlite3.c:74571
#define OP_Concat
Definition: sqlite3.c:12391
int nChange
Definition: sqlite3.c:13692
SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *, int)
Definition: sqlite3.c:60226
SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt)
Definition: sqlite3.c:67361
#define OP_Goto
Definition: sqlite3.c:12352
u16 nResColumn
Definition: sqlite3.c:17785
SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *, int)
Definition: sqlite3.c:60794
#define TK_AGG_FUNCTION
Definition: sqlite3.c:11253
#define SQLITE_CellSizeCk
Definition: sqlite3.c:13835
SQLITE_PRIVATE void sqlite3MayAbort(Parse *)
Definition: sqlite3.c:100864
char * zErrMsg
Definition: sqlite3.c:17772
SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql)
Definition: sqlite3.c:135478
static int pcache1Pagecount(sqlite3_pcache *p)
Definition: sqlite3.c:44736
#define SQLITE_ABORT_ROLLBACK
Definition: sqlite3.c:746
static void setSectorSize(Pager *pPager)
Definition: sqlite3.c:48451
#define SQLITE_UTF16
Definition: sqlite3.c:4590
static KeyInfo * multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra)
Definition: sqlite3.c:114716
int nzVar
Definition: sqlite3.c:15349
#define SORTER_TYPE_INTEGER
Definition: sqlite3.c:84403
#define MEM_Dyn
Definition: sqlite3.c:17654
#define SQLITE_CONFIG_HEAP
Definition: sqlite3.c:2098
static int btreeRestoreCursorPosition(BtCursor *pCur)
Definition: sqlite3.c:58460
TriggerStep * pNext
Definition: sqlite3.c:15516
#define MIN(A, B)
Definition: sqlite3.c:11379
#define BTREE_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:11971
SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset)
Definition: sqlite3.c:84007
#define SQLITE_CONSTRAINT_UNIQUE
Definition: sqlite3.c:754
#define ExpandBlob(P)
Definition: sqlite3.c:17958
int nFrame
Definition: sqlite3.c:17813
void(* xReiniter)(DbPage *)
Definition: sqlite3.c:46511
SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N)
Definition: sqlite3.c:17375
#define BTREE_AUTOVACUUM_NONE
Definition: sqlite3.c:11859
u16 nLocal
Definition: sqlite3.c:57147
u16 nLTerm
Definition: sqlite3.c:122371
SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *, Expr *, int, int)
Definition: sqlite3.c:92574
u8 extraSync
Definition: sqlite3.c:46443
#define enable_simulated_io_errors()
Definition: sqlite3.c:49579
u32 tRowcnt
Definition: sqlite3.c:11470
#define OP_Integer
Definition: sqlite3.c:12413
#define SF_FixedLimit
Definition: sqlite3.c:15086
u8 * aRecord
Definition: sqlite3.c:17842
SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *)
Definition: sqlite3.c:137067
SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *)
Definition: sqlite3.c:42929
#define TERM_LIKE
Definition: sqlite3.c:122516
GLfloat bias
Definition: glext.h:7937
int sortingIdx
Definition: sqlite3.c:14562
int mxSample
Definition: sqlite3.c:94310
static void convertToWithoutRowidTable(Parse *pParse, Table *pTab)
Definition: sqlite3.c:98435
char affSdst
Definition: sqlite3.c:15181
static int pager_incr_changecounter(Pager *pPager, int isDirectMode)
Definition: sqlite3.c:51850
static const struct sPragmaNames aPragmaNames[]
#define SQLITE_JUMPIFNULL
Definition: sqlite3.c:14135
unsigned char iEquiv
Definition: sqlite3.c:122530
#define ROUNDDOWN8(x)
Definition: sqlite3.c:11587
SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *, const char *)
Definition: sqlite3.c:25292
static int whereOrInsert(WhereOrSet *pSet, Bitmask prereq, LogEst rRun, LogEst nOut)
Definition: sqlite3.c:126025
Trigger * pTrigger
Definition: sqlite3.c:14224
static void sqlite3ExprCodeIN(Parse *pParse, Expr *pExpr, int destIfFalse, int destIfNull)
Definition: sqlite3.c:91029
#define SQLITE_PERM
Definition: sqlite3.c:660
void(* fts5_extension_function)(const Fts5ExtensionApi *pApi, Fts5Context *pFts, sqlite3_context *pCtx, int nVal, sqlite3_value **apVal)
Definition: sqlite3.c:9899
SQLITE_PRIVATE void sqlite3SelectPrep(Parse *, Select *, NameContext *)
Definition: sqlite3.c:117412
INT16_TYPE LogEst
Definition: sqlite3.c:11496
u8 ** apCell
Definition: sqlite3.c:64079
SQLITE_PRIVATE int sqlite3ResolveExprListNames(NameContext *, ExprList *)
Definition: sqlite3.c:88824
SQLITE_PRIVATE CollSeq * sqlite3LocateCollSeq(Parse *pParse, const char *zName)
Definition: sqlite3.c:98191
static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp)
Definition: sqlite3.c:33955
void(* xSFunc)(sqlite3_context *, int, sqlite3_value **)
Definition: sqlite3.c:13903
pthread_mutex_t mutex
Definition: sqlite3.c:22570
SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:62343
#define MX_CELL_SIZE(pBt)
Definition: sqlite3.c:56898
u8 tr_tm
Definition: sqlite3.c:15449
#define TK_WITH
Definition: sqlite3.c:11192
#define OP_IfNot
Definition: sqlite3.c:12361
#define putVarint
Definition: sqlite3.c:16263
#define osAccess
SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *, SrcList *)
Definition: sqlite3.c:92909
#define P4_STATIC
Definition: sqlite3.c:12280
static int vdbeSorterCompareInt(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:84909
SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *)
Definition: sqlite3.c:84992
static int saveCursorPosition(BtCursor *pCur)
Definition: sqlite3.c:58319
HashElem * next
Definition: sqlite3.c:11059
SQLITE_PRIVATE CollSeq * sqlite3GetCollSeq(Parse *, u8, CollSeq *, const char *)
Definition: sqlite3.c:101264
#define PAGER_SYNCHRONOUS_MASK
Definition: sqlite3.c:12795
#define TK_SAVEPOINT
Definition: sqlite3.c:11113
static void whereLoopInit(WhereLoop *p)
Definition: sqlite3.c:127618
void * pScratchEnd
Definition: sqlite3.c:23667
With * pWithToFree
Definition: sqlite3.c:15377
static int parseHhMmSs(const char *zDate, DateTime *p)
Definition: sqlite3.c:18497
static void samplePushPrevious(Stat4Accum *p, int iChng)
Definition: sqlite3.c:94663
#define pcacheDump(X)
Definition: sqlite3.c:43146
#define SQLITE_LIMIT_COMPOUND_SELECT
Definition: sqlite3.c:3533
static void sourceidFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103455
#define OPFLAG_P2ISREG
Definition: sqlite3.c:15425
void * pWalArg
Definition: sqlite3.c:13729
Select * pNext
Definition: sqlite3.c:15057
#define TK_LIMIT
Definition: sqlite3.c:11229
GLsizeiptr size
static int unixTruncate(sqlite3_file *id, i64 nByte)
Definition: sqlite3.c:32693
int labelDone
Definition: sqlite3.c:112861
static unixInodeInfo * inodeList
Definition: sqlite3.c:30197
#define SQLITE_FCNTL_PERSIST_WAL
Definition: sqlite3.c:1253
SQLITE_PRIVATE void * sqlite3ArrayAllocate(sqlite3 *, void *, int, int *, int *)
Definition: sqlite3.c:100294
sqlite3_stmt * pStmt
Definition: sqlite3.c:83588
struct Fts5Tokenizer Fts5Tokenizer
Definition: sqlite3.c:10361
#define SQLITE_FUNC_ENCMASK
Definition: sqlite3.c:13945
SQLITE_PRIVATE int sqlite3MutexInit(void)
Definition: sqlite3.c:22170
u8 declareVtab
Definition: sqlite3.c:15353
SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2)
Definition: sqlite3.c:89085
static void sumFinalize(sqlite3_context *context)
Definition: sqlite3.c:104024
static int multiSelectOrderBy(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:115595
u8 mallocFailed
Definition: sqlite3.c:13683
static int pagerExclusiveLock(Pager *pPager)
Definition: sqlite3.c:53025
#define tkOTHER
Definition: sqlite3.c:135251
#define etSTRING
Definition: sqlite3.c:24461
Expr * pExpr
Definition: sqlite3.c:122481
#define OE_SetDflt
Definition: sqlite3.c:14360
#define PAGER_FLAGS_MASK
Definition: sqlite3.c:12799
#define SQLITE_MAX_U32
Definition: sqlite3.c:11459
i64 startTime
Definition: sqlite3.c:17803
void(* xUpdateCallback)(void *, int, const char *, const char *, sqlite_int64)
Definition: sqlite3.c:13719
int * pnBytesFreed
Definition: sqlite3.c:13766
#define TK_UPLUS
Definition: sqlite3.c:11256
struct ExprList::ExprList_item * a
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo)
Definition: sqlite3.c:92927
static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size)
Definition: sqlite3.c:87084
#define PragTyp_SOFT_HEAP_LIMIT
Definition: sqlite3.c:109548
VdbeSorter * pSorter
Definition: sqlite3.c:84363
sqlite3_value * argv[1]
Definition: sqlite3.c:17723
static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey)
Definition: sqlite3.c:73738
#define SQLITE_IDXTYPE_APPDEF
Definition: sqlite3.c:14502
#define USEFETCH(x)
Definition: sqlite3.c:46609
#define OP_RowKey
Definition: sqlite3.c:12458
#define SQLITE_STMTJRNL_SPILL
Definition: sqlite3.c:16828
SQLITE_PRIVATE int sqlite3HeaderSizePcache(void)
Definition: sqlite3.c:43895
u8 op
Definition: sqlite3.c:15043
int(* xWalCallback)(void *, sqlite3 *, const char *, int)
Definition: sqlite3.c:13728
i64 iEof
Definition: sqlite3.c:84417
static SQLITE_WSD struct BenignMallocHooks sqlite3Hooks
SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *, int)
Definition: sqlite3.c:49233
static const struct @122 yyRuleInfo[]
static int setDestPgsz(sqlite3_backup *p)
Definition: sqlite3.c:67499
u8 colNamesSet
Definition: sqlite3.c:15277
u8 noSync
Definition: sqlite3.c:46441
void * pStart
Definition: sqlite3.c:44123
#define sqlite3Isxdigit(x)
Definition: sqlite3.c:15781
GLuint writeBuffer
Definition: glext.h:2633
#define SORTER_TYPE_TEXT
Definition: sqlite3.c:84404
char * zName
Definition: sqlite3.c:17750
#define ROUND8(x)
Definition: sqlite3.c:11582
#define WAL_RDONLY
Definition: sqlite3.c:53685
SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32)
Definition: sqlite3.c:73083
u8 isTransactionSavepoint
Definition: sqlite3.c:13689
#define P5_ConstraintNotNull
Definition: sqlite3.c:12299
SQLITE_PRIVATE VTable * sqlite3GetVTable(sqlite3 *, Table *)
Definition: sqlite3.c:121131
static const char hexdigits[]
Definition: sqlite3.c:103529
LogEst nRowOut
Definition: sqlite3.c:122649
#define TIMER_END
Definition: sqlite3.c:29323
#define WAL_MAGIC
Definition: sqlite3.c:53627
static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val)
Definition: sqlite3.c:68861
FileChunk * pFirst
Definition: sqlite3.c:86890
static void addToVTrans(sqlite3 *db, VTable *pVTab)
Definition: sqlite3.c:121669
#define OP_Delete
Definition: sqlite3.c:12454
#define SQLITE_IOERR_CHECKRESERVEDLOCK
Definition: sqlite3.c:719
SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst, LogEst)
Definition: sqlite3.c:28364
static int binCollFunc(void *padFlag, int nKey1, const void *pKey1, int nKey2, const void *pKey2)
Definition: sqlite3.c:136447
u32 nColumn
Definition: sqlite3.c:118524
#define SQLITE_TESTCTRL_PRNG_RESTORE
Definition: sqlite3.c:6799
SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *)
Definition: sqlite3.c:112411
i64 iKey1
Definition: sqlite3.c:17847
#define PTF_ZERODATA
Definition: sqlite3.c:56933
static int walCheckpoint(Wal *pWal, int eMode, int(*xBusy)(void *), void *pBusyArg, int sync_flags, u8 *zBuf)
Definition: sqlite3.c:54939
SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat,...)
Definition: sqlite3.c:25491
#define SQLITE_OPEN_CREATE
Definition: sqlite3.c:771
#define WHERE_NO_AUTOINDEX
Definition: sqlite3.c:14955
#define SQLITE_LegacyFileFmt
Definition: sqlite3.c:13821
SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *, int, int)
Definition: sqlite3.c:112891
#define TF_Ephemeral
Definition: sqlite3.c:14239
#define READMARK_NOT_USED
Definition: sqlite3.c:53600
#define PragTyp_AUTO_VACUUM
Definition: sqlite3.c:109521
int nTableLock
Definition: sqlite3.c:15325
RowSet * pRowSet
Definition: sqlite3.c:17597
int(* xSync)(sqlite3_file *, int flags)
Definition: sqlite3.c:991
static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng
Definition: sqlite3.c:26148
static struct RowSetEntry * rowSetEntrySort(struct RowSetEntry *pIn)
Definition: sqlite3.c:45438
#define PragTyp_SHRINK_MEMORY
Definition: sqlite3.c:109547
SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int)
Definition: sqlite3.c:19631
SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *)
Definition: sqlite3.c:58499
#define OP_Halt
Definition: sqlite3.c:12412
union VdbeOp::p4union p4
SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *, int)
Definition: sqlite3.c:74930
#define WRITE_LOCK
Definition: sqlite3.c:57003
const GLubyte * c
Definition: glext.h:12690
#define OPFLAG_SEEKEQ
Definition: sqlite3.c:15423
SQLITE_PRIVATE int sqlite3AbsInt32(int)
Definition: sqlite3.c:28321
static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate)
Definition: sqlite3.c:127770
static int addToSavepointBitvecs(Pager *pPager, Pgno pgno)
Definition: sqlite3.c:47548
#define SQLITE_OPEN_MEMORY
Definition: sqlite3.c:776
#define OP_VColumn
Definition: sqlite3.c:12493
SQLITE_PRIVATE Index * sqlite3FindIndex(sqlite3 *, const char *, const char *)
Definition: sqlite3.c:97175
#define FTS5_TOKEN_COLOCATED
Definition: sqlite3.c:10389
sqlite3ParserTOKENTYPE yy0
Definition: sqlite3.c:130935
#define CC_PIPE
Definition: sqlite3.c:134354
SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity)
Definition: sqlite3.c:89135
static void cdateFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19371
int isMallocInit
Definition: sqlite3.c:15607
static int balance(BtCursor *pCur)
Definition: sqlite3.c:65480
struct WhereLevel::@135::@136 in
#define SQLITE_LIMIT_LENGTH
Definition: sqlite3.c:3529
SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve)
Definition: sqlite3.c:68296
u8 * aAlloc
Definition: sqlite3.c:84421
static u32 pager_cksum(Pager *pPager, const u8 *aData)
Definition: sqlite3.c:47950
SQLITE_PRIVATE void * sqlite3MallocZero(u64)
Definition: sqlite3.c:24176
SQLITE_PRIVATE int sqlite3OsInit(void)
Definition: sqlite3.c:19785
VdbeFrame * pDelFrame
Definition: sqlite3.c:17812
SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager *, const char *zMaster, int)
Definition: sqlite3.c:52001
GLdouble GLdouble r
static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:117437
static MergeEngine * vdbeMergeEngineNew(int nReader)
Definition: sqlite3.c:85238
TriggerPrg * pTriggerPrg
Definition: sqlite3.c:15375
struct FileChunk FileChunk
Definition: sqlite3.c:86847
static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg)
Definition: sqlite3.c:112078
SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int *)
Definition: sqlite3.c:19669
SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *)
Definition: sqlite3.c:55137
#define SQLITE_VdbeEQP
Definition: sqlite3.c:13833
#define CURSOR_SKIPNEXT
Definition: sqlite3.c:57250
#define SQLITE_BUSY
Definition: sqlite3.c:662
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_preupdate_depth(sqlite3 *)
static int vdbeSorterCompareText(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:84868
struct sqlite3_stmt sqlite3_stmt
Definition: sqlite3.c:3429
#define TK_CAST
Definition: sqlite3.c:11166
sqlite3_io_methods const * pMethod
Definition: sqlite3.c:29103
static int writeJournalHdr(Pager *pPager)
Definition: sqlite3.c:47199
Vdbe * pVdbe
Definition: sqlite3.c:15275
#define SQLITE_IOERR_CONVPATH
Definition: sqlite3.c:731
#define OptimizationEnabled(db, mask)
Definition: sqlite3.c:13864
#define SQLITE_UTF16NATIVE
Definition: sqlite3.c:11567
static void setOneColumnName(Vdbe *v, const char *z)
Definition: sqlite3.c:110129
#define IdChar(C)
Definition: sqlite3.c:134769
#define SQLITE_ECEL_REF
Definition: sqlite3.c:16084
#define SF_HasTypeInfo
Definition: sqlite3.c:15079
int nCell
Definition: sqlite3.c:64077
SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *, int *)
Definition: sqlite3.c:58516
Schema * pSchema
Definition: sqlite3.c:15453
#define SQLITE_INTEGRITY_CHECK_ERROR_MAX
SQLITE_PRIVATE void sqlite3EndTable(Parse *, Token *, Token *, u8, Select *)
Definition: sqlite3.c:98575
int nVdbeWrite
Definition: sqlite3.c:13705
#define SQLITE_CHECKPOINT_FULL
Definition: sqlite3.c:7982
SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *, int)
Definition: sqlite3.c:60393
#define READ_UTF8(zIn, zTerm, c)
Definition: sqlite3.c:26598
GLenum GLint GLint * precision
Definition: glext.h:1883
SQLITE_PRIVATE Index * sqlite3AllocateIndexObject(sqlite3 *, i16, int, char **)
Definition: sqlite3.c:99592
struct Vdbe * pVdbe
Definition: sqlite3.c:13667
int(* xRename)(sqlite3_vtab *pVtab, const char *zNew)
Definition: sqlite3.c:5913
SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75527
SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *)
Definition: sqlite3.c:52321
static int unixFileLock(unixFile *pFile, struct flock *pLock)
Definition: sqlite3.c:30547
#define PTRMAP_BTREE
Definition: sqlite3.c:57313
static void exprCommute(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:124666
SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(sqlite3 *, void(*)(void *, int, char const *, char const *, sqlite3_int64), void *)
Definition: sqlite3.c:137473
SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse *, Table *, Trigger *, int, int, int, i16, u8, u8, u8, int)
Definition: sqlite3.c:102296
#define PragTyp_ACTIVATE_EXTENSIONS
Definition: sqlite3.c:109557
#define OP_Noop
Definition: sqlite3.c:12498
SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *)
Definition: sqlite3.c:52353
static void whereLoopOutputAdjust(WhereClause *pWC, WhereLoop *pLoop, LogEst nRow)
Definition: sqlite3.c:128020
#define OP_Ge
Definition: sqlite3.c:12380
u8 isPinned
Definition: sqlite3.c:44023
SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *)
Definition: sqlite3.c:43555
#define vdbeInvokeSqllog(x)
Definition: sqlite3.c:72685
SQLITE_PRIVATE void sqlite3PExprAddSelect(Parse *, Expr *, Select *)
Definition: sqlite3.c:89468
#define EXPR_TOKENONLYSIZE
Definition: sqlite3.c:14769
static int invokeValueDestructor(const void *p, void(*xDel)(void *), sqlite3_context *pCtx)
Definition: sqlite3.c:74783
SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8)
Definition: sqlite3.c:76867
SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *, u8, u8)
Definition: sqlite3.c:68464
#define PAGER_SYNCHRONOUS_EXTRA
Definition: sqlite3.c:12794
SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p)
Definition: sqlite3.c:68591
#define OP_OpenEphemeral
Definition: sqlite3.c:12444
u8 aAction[2]
Definition: sqlite3.c:14318
#define TK_ESCAPE
Definition: sqlite3.c:11142
#define UpperToLower
Definition: sqlite3.c:27253
#define initMaskSet(P)
Definition: sqlite3.c:122614
#define SQLITE_MAX_SYMLINKS
Definition: sqlite3.c:29067
int iTable
Definition: sqlite3.c:14696
SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *)
Definition: sqlite3.c:75189
#define EXCLUSIVE_LOCK
Definition: sqlite3.c:13269
SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *)
Definition: sqlite3.c:136527
SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *)
Definition: sqlite3.c:97468
#define SQLITE_TESTCTRL_BYTEORDER
Definition: sqlite3.c:6815
#define sqlite3VdbeScanStatus(a, b, c, d, e)
Definition: sqlite3.c:12684
static int nameInUsingClause(IdList *pUsing, const char *zCol)
Definition: sqlite3.c:87513
SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *, int *pRes)
Definition: sqlite3.c:63160
static void pcache1ResizeHash(PCache1 *p)
Definition: sqlite3.c:44443
#define TK_REPLACE
Definition: sqlite3.c:11185
ExprList * pExprList
Definition: sqlite3.c:15514
UINT32_TYPE u32
Definition: sqlite3.c:11447
SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db)
Definition: sqlite3.c:137849
#define SQLITE_CDECL
Definition: sqlite3.c:307
#define TK_CONCAT
Definition: sqlite3.c:11152
UnixUnusedFd * pNext
Definition: sqlite3.c:29094
static int codeCompare(Parse *pParse, Expr *pLeft, Expr *pRight, int opcode, int in1, int in2, int dest, int jumpIfNull)
Definition: sqlite3.c:89192
GLdouble x
static void pcache1RemoveFromHash(PgHdr1 *pPage, int freeFlag)
Definition: sqlite3.c:44512
Definition: sqlite3.c:13508
int nearlyFull
Definition: sqlite3.c:23675
int iDb
Definition: sqlite3.c:15565
#define TERM_COPIED
Definition: sqlite3.c:122505
#define BTS_READ_ONLY
Definition: sqlite3.c:57130
static void * sqlite3MemMalloc(int nByte)
Definition: sqlite3.c:20165
#define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
Definition: sqlite3.c:10572
#define SQLITE_CountRows
Definition: sqlite3.c:13810
#define TK_ASC
Definition: sqlite3.c:11161
unsigned char bProcessLock
Definition: sqlite3.c:30178
Pager * pPager
Definition: sqlite3.c:12960
unsigned int mxPinned
Definition: sqlite3.c:44058
static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf)
Definition: sqlite3.c:35186
SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *, int, const char *,...)
Definition: sqlite3.c:27154
SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *)
Definition: sqlite3.c:68639
#define OPFLG_INITIALIZER
Definition: sqlite3.c:12511
SQLITE_PRIVATE int sqlite3Atoi(const char *)
Definition: sqlite3.c:27721
SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *, int, const sqlite3_value *)
Definition: sqlite3.c:75872
#define SQLITE_DBCONFIG_ENABLE_FKEY
Definition: sqlite3.c:2207
#define tkTRIGGER
Definition: sqlite3.c:135256
Expr * pLeft
Definition: sqlite3.c:14681
#define SQLITE_CONFIG_URI
Definition: sqlite3.c:2107
struct LimitVal yy64
Definition: sqlite3.c:130936
unsigned char eFileLock
Definition: sqlite3.c:30177
Hash aModule
Definition: sqlite3.c:13751
MemPage * apPage[BTCURSOR_MAX_DEPTH]
Definition: sqlite3.c:57205
static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p)
Definition: sqlite3.c:18879
static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc)
Definition: sqlite3.c:126013
void * pProfileArg
Definition: sqlite3.c:13713
struct PCache PCache
Definition: sqlite3.c:12949
#define TK_TRIGGER
Definition: sqlite3.c:11188
u32 cacheStatus
Definition: sqlite3.c:17523
SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *, const char *zDbName, int op, void *)
Definition: sqlite3.c:139032
#define VDBE_OFFSET_LINENO(x)
Definition: sqlite3.c:12678
static int memjrnlRead(sqlite3_file *pJfd, void *zBuf, int iAmt, sqlite_int64 iOfst)
Definition: sqlite3.c:86903
#define BTREE_UNORDERED
Definition: sqlite3.c:11889
#define OP_Column
Definition: sqlite3.c:12433
UnixUnusedFd * pUnused
Definition: sqlite3.c:30182
SQLITE_PRIVATE int sqlite3JoinType(Parse *, Token *, Token *, Token *)
Definition: sqlite3.c:113004
SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault)
Definition: sqlite3.c:139432
i8 iPage
Definition: sqlite3.c:57200
SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion)
Definition: sqlite3.c:67319
sqlite3 * db
Definition: sqlite3.c:94318
#define osFchmod
union Bitvec::@133 u
sqlite3_mutex * pInitMutex
Definition: sqlite3.c:15610
#define PragTyp_REKEY
Definition: sqlite3.c:109560
SQLITE_PRIVATE char * sqlite3DbStrDup(sqlite3 *, const char *)
Definition: sqlite3.c:24334
_W64 unsigned int uintptr_t
Definition: stdint.h:119
#define SQLITE_DBSTATUS_DEFERRED_FKS
Definition: sqlite3.c:7075
int separateCache
Definition: sqlite3.c:44118
static int subjournalPage(PgHdr *pPg)
Definition: sqlite3.c:50205
SQLITE_PRIVATE FuncDef * sqlite3FindFunction(sqlite3 *, const char *, int, u8, u8)
Definition: sqlite3.c:101528
#define SQLITE_STATUS_PARSER_STACK
Definition: sqlite3.c:6945
#define SQLITE_TESTCTRL_SCRATCHMALLOC
Definition: sqlite3.c:6810
static WhereTerm * whereScanNext(WhereScan *pScan)
Definition: sqlite3.c:126091
#define SQLITE_IOERR_DIR_FSYNC
Definition: sqlite3.c:710
LogEst rRun
Definition: sqlite3.c:122355
#define wsdHooksInit
Definition: sqlite3.c:19938
SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *, u32 offset, u32 amt, void *)
Definition: sqlite3.c:62326
unsigned uniqNotNull
Definition: sqlite3.c:14485
static int codeTriggerProgram(Parse *pParse, TriggerStep *pStepList, int orconf)
Definition: sqlite3.c:119370
static int pager_error(Pager *pPager, int rc)
Definition: sqlite3.c:47677
SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p)
Definition: sqlite3.c:60360
static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103541
int mxParserStack
Definition: sqlite3.c:15599
void ** aExtension
Definition: sqlite3.c:13709
static int sqlite3Prepare(sqlite3 *db, const char *zSql, int nBytes, int saveSqlFlag, Vdbe *pReprepare, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:112455
sqlite3_int64 szMmap
Definition: sqlite3.c:15591
LogEst nRow
Definition: sqlite3.c:122422
struct WhereLoop::@137::@139 vtab
static char * whereTempTriggers(Parse *pParse, Table *pTab)
Definition: sqlite3.c:93509
#define OP_ReadCookie
Definition: sqlite3.c:12438
sqlite3_int64 iRowid
Definition: sqlite3.c:8556
#define YY_REDUCE_USE_DFLT
Definition: sqlite3.c:131392
Pgno pgnoRoot
Definition: sqlite3.c:57189
struct sqlite3_index_info::sqlite3_index_constraint_usage * aConstraintUsage
union FuncDef::@124 u
void * pAppData
Definition: sqlite3.c:1455
static int whereLoopAddBtree(WhereLoopBuilder *pBuilder, Bitmask mPrereq)
Definition: sqlite3.c:128485
static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt)
Definition: sqlite3.c:55391
SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *)
Definition: sqlite3.c:100606
SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context *, const char *, int, void(*)(void *))
Definition: sqlite3.c:74859
int(* xCheckReservedLock)(sqlite3_file *, int *pResOut)
Definition: sqlite3.c:995
#define etPOINTER
Definition: sqlite3.c:24471
void(* xCollNeeded16)(void *, sqlite3 *, int eTextRep, const void *)
Definition: sqlite3.c:13732
SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *, u8 op)
Definition: sqlite3.c:70791
static SQLITE_NOINLINE Mem * out2PrereleaseWithClear(Mem *pOut)
Definition: sqlite3.c:77156
#define etSIZE
Definition: sqlite3.c:24460
#define SimulateIOError(A)
Definition: sqlite3.c:29363
#define checkActiveVdbeCnt(x)
Definition: sqlite3.c:72330
#define OP_LoadAnalysis
Definition: sqlite3.c:12474
GLdouble GLdouble x2
#define OP_VBegin
Definition: sqlite3.c:12489
#define SQLITE_EXTENSION_INIT1
Definition: sqlite3.c:108705
Pgno dbHintSize
Definition: sqlite3.c:46472
SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *)
Definition: sqlite3.c:67374
struct RowSetEntry * pEntry
Definition: sqlite3.c:45275
static void autoIncStep(Parse *pParse, int memId, int regRowid)
Definition: sqlite3.c:106114
#define PAGER_JOURNALMODE_PERSIST
Definition: sqlite3.c:12771
SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *)
Definition: sqlite3.c:125952
sqlite3_mutex * mutex
Definition: sqlite3.c:44055
sqlite3_value * pErr
Definition: sqlite3.c:13734
#define SQLITE_OPEN_READWRITE
Definition: sqlite3.c:770
#define sqlite3MemdebugSetType(X, Y)
Definition: sqlite3.c:16632
int(* xMutexHeld)(sqlite3_mutex *)
Definition: sqlite3.c:6655
static SQLITE_NOINLINE int vdbeMemFromBtreeResize(BtCursor *pCur, u32 offset, u32 amt, int key, Mem *pMem)
Definition: sqlite3.c:69131
i64 nDeferredCons
Definition: sqlite3.c:14027
LogEst iLimit
Definition: sqlite3.c:122650
int neverCorrupt
Definition: sqlite3.c:15581
u8 doNotSpill
Definition: sqlite3.c:46465
SQLITE_PRIVATE void sqlite3FkDropTable(Parse *, SrcList *, Table *)
Definition: sqlite3.c:105100
i64 iWriteOff
Definition: sqlite3.c:84485
SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *, const char *, int)
Definition: sqlite3.c:25275
static const void * columnName(sqlite3_stmt *pStmt, int N, const void *(*xFunc)(Mem *), int useType)
Definition: sqlite3.c:75555
#define OP_Insert
Definition: sqlite3.c:12452
sqlite3_mutex * mutex
Definition: sqlite3.c:23658
SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *, Expr *, int)
Definition: sqlite3.c:91580
#define SQLITE_CONFIG_LOOKASIDE
Definition: sqlite3.c:2103
SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *, int, sqlite3_int64)
Definition: sqlite3.c:75817
#define OP_Sequence
Definition: sqlite3.c:12450
static void dropCell(MemPage *pPage, int idx, int sz, int *pRC)
Definition: sqlite3.c:63930
Table * pTab
Definition: sqlite3.c:12230
#define SQLITE_CONSTRAINT
Definition: sqlite3.c:676
int iCur
Definition: sqlite3.c:15661
#define YY_SHIFT_COUNT
Definition: sqlite3.c:131343
AuxData * pAuxData
Definition: sqlite3.c:17818
static int findNextHostParameter(const char *zSql, int *pnToken)
Definition: sqlite3.c:76368
const char * zEnd
Definition: sqlite3.c:14821
static VdbeCursor * allocateCursor(Vdbe *p, int iCur, int nField, int iDb, u8 eCurType)
Definition: sqlite3.c:76714
SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *)
Definition: sqlite3.c:97318
#define SQLITE_FCNTL_JOURNAL_POINTER
Definition: sqlite3.c:1270
#define CC_X
Definition: sqlite3.c:134344
int nId
Definition: sqlite3.c:14844
#define MEM_Blob
Definition: sqlite3.c:17639
#define IN_INDEX_INDEX_DESC
Definition: sqlite3.c:16540
SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *)
Definition: sqlite3.c:72699
#define fdatasync
Definition: sqlite3.c:32471
#define SQLITE_FCNTL_VFSNAME
Definition: sqlite3.c:1255
#define SQLITE_PRINTF_INTERNAL
Definition: sqlite3.c:15551
static void checkList(IntegrityCk *pCheck, int isFreeList, int iPage, int N)
Definition: sqlite3.c:66592
SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *, u32 addr, int P2)
Definition: sqlite3.c:70660
#define TK_RECURSIVE
Definition: sqlite3.c:11184
static int vdbePmaReaderInit(SortSubtask *pTask, SorterFile *pFile, i64 iStart, PmaReader *pReadr, i64 *pnByte)
Definition: sqlite3.c:84789
static int walNextHash(int iPriorHash)
Definition: sqlite3.c:54059
int iMemory
Definition: sqlite3.c:84393
static int exprProbability(Expr *p)
Definition: sqlite3.c:87948
u8 * aOnceFlag
Definition: sqlite3.c:17817
#define SQLITE_LIMIT_WORKER_THREADS
Definition: sqlite3.c:3540
int iNewReg
Definition: sqlite3.c:17846
SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse *, Table *, int, Expr *, ExprList *)
Definition: sqlite3.c:88876
static int walLockShared(Wal *pWal, int lockIdx)
Definition: sqlite3.c:54015
static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102927
static int pagerLockDb(Pager *pPager, int eLock)
Definition: sqlite3.c:46937
#define SQLITE_UTF16_ALIGNED
Definition: sqlite3.c:4592
#define SQLITE_OPEN_URI
Definition: sqlite3.c:775
unsigned noSkipScan
Definition: sqlite3.c:14488
static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow)
Definition: sqlite3.c:35305
SQLITE_PRIVATE int sqlite3VdbeList(Vdbe *)
Definition: sqlite3.c:71423
SQLITE_PRIVATE sqlite3_file * sqlite3WalFile(Wal *pWal)
Definition: sqlite3.c:56650
static SQLITE_NOINLINE int growOp3(Vdbe *p, int op, int p1, int p2, int p3)
Definition: sqlite3.c:70054
static void heightOfExprList(ExprList *p, int *pnHeight)
Definition: sqlite3.c:89247
SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *)
Definition: sqlite3.c:74675
SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt *, int, const void *, int, void(*)(void *))
Definition: sqlite3.c:75862
#define disable_simulated_io_errors()
Definition: sqlite3.c:49578
#define SQLITE_IOERR_BLOCKED
Definition: sqlite3.c:716
double notUsed1
Definition: sqlite3.c:13737
SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *)
Definition: sqlite3.c:51959
sqlite_int64 sqlite3_int64
Definition: sqlite3.c:512
#define SQLITE_STATUS_SCRATCH_USED
Definition: sqlite3.c:6942
BtCursor * pCursor
Definition: sqlite3.c:57092
Bitmask maskSelf
Definition: sqlite3.c:122348
#define WHERE_INDEXED
Definition: sqlite3.c:122771
u16 wctrlFlags
Definition: sqlite3.c:122651
SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75533
u32 nPayload
Definition: sqlite3.c:57146
#define etTOKEN
Definition: sqlite3.c:24469
#define sqlite3VtabInSync(db)
Definition: sqlite3.c:16448
static void charFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103632
static void setResultStrOrError(sqlite3_context *pCtx, const char *z, int n, u8 enc, void(*xDel)(void *))
Definition: sqlite3.c:74772
#define pcacheTrace(X)
Definition: sqlite3.c:43145
#define SQLITE_FCNTL_SET_LOCKPROXYFILE
Definition: sqlite3.c:1246
static int vdbeIncrMergerNew(SortSubtask *pTask, MergeEngine *pMerger, IncrMerger **ppOut)
Definition: sqlite3.c:86050
#define BITVEC_SZELEM
Definition: sqlite3.c:42690
#define BITVEC_SZ
Definition: sqlite3.c:42677
#define SQLITE_CONFIG_MALLOC
Definition: sqlite3.c:2094
#define sqlite3ParserARG_STORE
Definition: sqlite3.c:130956
#define sqlite3Isdigit(x)
Definition: sqlite3.c:15780
SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *, u32)
Definition: sqlite3.c:42806
#define SQLITE_TESTCTRL_LOCALTIME_FAULT
Definition: sqlite3.c:6811
Bitmask maskLoop
Definition: sqlite3.c:122420
static int allocateSpace(MemPage *pPage, int nByte, int *pIdx)
Definition: sqlite3.c:59149
u8 max1bytePayload
Definition: sqlite3.c:57101
static void unicodeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103617
#define TK_DROP
Definition: sqlite3.c:11214
#define TK_IGNORE
Definition: sqlite3.c:11175
#define HASHTABLE_NSLOT
Definition: sqlite3.c:53731
Vdbe * pVdbe
Definition: sqlite3.c:17731
static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p)
Definition: sqlite3.c:68540
#define YY_SHIFT_USE_DFLT
Definition: sqlite3.c:131342
#define PragTyp_CACHE_SIZE
Definition: sqlite3.c:109524
#define SQLITE_OPEN_MAIN_DB
Definition: sqlite3.c:777
static void explainComposite(Parse *pParse, int op, int iSub1, int iSub2, int bUseTmp)
Definition: sqlite3.c:113964
#define UNIXFILE_PSOW
Definition: sqlite3.c:29174
#define SQLITE_SHM_LOCK
Definition: sqlite3.c:1535
int szFirstBlock
Definition: sqlite3.c:53649
SQLITE_PRIVATE FuncDef * sqlite3VtabOverloadFunction(sqlite3 *, FuncDef *, int nArg, Expr *)
Definition: sqlite3.c:122008
SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer *, TriggerStep *)
Definition: sqlite3.c:96476
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_get(sqlite3 *db, const char *zSchema, sqlite3_snapshot **ppSnapshot)
#define STAT_GET_STAT1
Definition: sqlite3.c:94809
SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *)
Definition: sqlite3.c:72859
#define CACHE_STALE
Definition: sqlite3.c:17584
#define OP_SorterCompare
Definition: sqlite3.c:12456
#define OP_Explain
Definition: sqlite3.c:12499
#define YYSTACKDEPTH
Definition: sqlite3.c:130951
#define SQLITE_FUNCTION
Definition: sqlite3.c:3000
#define TK_BITOR
Definition: sqlite3.c:11144
unsigned char etByte
Definition: sqlite3.c:24481
static int xferOptimization(Parse *pParse, Table *pDest, Select *pSelect, int onError, int iDbDest)
Definition: sqlite3.c:107687
SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *, const char *,...)
Definition: sqlite3.c:27187
VTable * pVTable
Definition: sqlite3.c:14222
#define SQLITE_THREADSAFE
Definition: sqlite3.c:10764
static int btreeGetHasContent(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:58242
char fmttype
Definition: sqlite3.c:24488
#define SQLITE_WARNING_AUTOINDEX
Definition: sqlite3.c:759
static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:127628
SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int)
Definition: sqlite3.c:56167
static void likeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103358
static void memjrnlFreeChunks(MemJournal *p)
Definition: sqlite3.c:86954
u32 iVersion
Definition: sqlite3.c:53521
static sqlite3_mutex * noopMutexAlloc(int id)
Definition: sqlite3.c:22350
#define BTALLOC_ANY
Definition: sqlite3.c:57719
SQLITE_PRIVATE void sqlite3ExprCodeLoadIndexColumn(Parse *, Index *, int, int, int)
Definition: sqlite3.c:91406
SQLITE_PRIVATE char * sqlite3BtreeIntegrityCheck(Btree *, int *aRoot, int nRoot, int, int *)
Definition: sqlite3.c:66992
SQLITE_PRIVATE Bitmask sqlite3WhereCodeOneLoopStart(WhereInfo *pWInfo, int iLevel, Bitmask notReady)
Definition: sqlite3.c:123561
u16 minLeaf
Definition: sqlite3.c:57109
SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *, Pgno)
Definition: sqlite3.c:49709
struct PmaReader PmaReader
Definition: sqlite3.c:84226
SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal)
Definition: sqlite3.c:56511
Stat4Sample current
Definition: sqlite3.c:94311
static void vdbeIncrMergerSetThreads(IncrMerger *pIncr)
Definition: sqlite3.c:86074
#define osUnlink
SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *, int, int *, int *)
Definition: sqlite3.c:67146
i64 iStartOff
Definition: sqlite3.c:84464
#define OP_IntegrityCk
Definition: sqlite3.c:12478
#define TK_NULL
Definition: sqlite3.c:11201
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:137170
int nKey
Definition: sqlite3.c:84419
u32 nBackfill
Definition: sqlite3.c:53594
#define etSQLESCAPE2
Definition: sqlite3.c:24467
static void insertCell(MemPage *pPage, int i, u8 *pCell, int sz, u8 *pTemp, Pgno iChild, int *pRC)
Definition: sqlite3.c:63984
int nSet
Definition: sqlite3.c:15293
#define SQLITE_CONSTRAINT_VTAB
Definition: sqlite3.c:755
static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p)
Definition: sqlite3.c:89640
#define EXPR_FULLSIZE
Definition: sqlite3.c:14767
static void pcache1Rekey(sqlite3_pcache *p, sqlite3_pcache_page *pPg, unsigned int iOld, unsigned int iNew)
Definition: sqlite3.c:44994
#define BTCF_WriteFlag
Definition: sqlite3.c:57211
SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *, int op,...)
Definition: sqlite3.c:122179
static void Cleanup(Vdbe *p)
Definition: sqlite3.c:71969
SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *, Index *)
Definition: sqlite3.c:70873
SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *, int)
Definition: sqlite3.c:100669
#define sqlite3StrNICmp
Definition: sqlite3.c:15804
SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *, Trigger *)
Definition: sqlite3.c:119226
SQLITE_PRIVATE void sqlite3PagerShrink(Pager *)
Definition: sqlite3.c:49271
SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3 *, Expr *, Expr *, Expr *)
Definition: sqlite3.c:89413
u8 bUseFetch
Definition: sqlite3.c:46467
SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *)
static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p)
Definition: sqlite3.c:72885
#define CURSOR_VALID
Definition: sqlite3.c:57249
SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *)
Definition: sqlite3.c:22270
FKey * pNextTo
Definition: sqlite3.c:14313
LookasideSlot * pNext
Definition: sqlite3.c:13608
static void randomFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103041
SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *)
Definition: sqlite3.c:43660
SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *, void *)
Definition: sqlite3.c:24022
int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *)
TriggerStep * pLast
Definition: sqlite3.c:15517
static void pager_write_changecounter(PgHdr *pPg)
Definition: sqlite3.c:48794
static Table * tableOfTrigger(Trigger *pTrigger)
Definition: sqlite3.c:119218
static sqlite3_int64 localtimeOffset(DateTime *p, sqlite3_context *pCtx, int *pRc)
Definition: sqlite3.c:18800
SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *)
Definition: sqlite3.c:57513
Stat4Sample * aBest
Definition: sqlite3.c:94313
SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *)
Definition: sqlite3.c:72926
char idxaff
Definition: sqlite3.c:122528
WhereOrSet * pOrSet
Definition: sqlite3.c:122625
SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p)
Definition: sqlite3.c:89299
SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value *, int, const void *, u8, void(*)(void *))
Definition: sqlite3.c:69846
SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *)
Definition: sqlite3.c:75174
SorterCompare xCompare
Definition: sqlite3.c:84367
static int sqlite3MemSize(void *pPrior)
Definition: sqlite3.c:20212
#define PCACHE_DIRTYLIST_ADD
Definition: sqlite3.c:43200
static int changeTempStorage(Parse *pParse, const char *zStorageType)
Definition: sqlite3.c:110103
SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *)
Definition: sqlite3.c:70282
#define WHERE_WANT_DISTINCT
Definition: sqlite3.c:14958
#define MAX_6BYTE
SQLITE_PRIVATE int sqlite3VdbeRecordCompareWithSkip(int, const void *, UnpackedRecord *, int)
Definition: sqlite3.c:73793
etByte flags
Definition: sqlite3.c:24490
#define OPFLAG_NCHANGE
Definition: sqlite3.c:15410
#define TK_IS
Definition: sqlite3.c:11129
static void * contextMalloc(sqlite3_context *context, i64 nByte)
Definition: sqlite3.c:102968
std::string trim(std::string const &str)
Returns a new string without whitespace at the start/end.
int(* xGetLastError)(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:1468
#define PragTyp_CACHE_SPILL
Definition: sqlite3.c:109525
#define IOTRACE(A)
Definition: sqlite3.c:16595
#define YYACTIONTYPE
Definition: sqlite3.c:130930
static int synthCollSeq(sqlite3 *db, CollSeq *pColl)
Definition: sqlite3.c:101234
u32 mxAlloc
Definition: sqlite3.c:15545
SQLITE_PRIVATE void sqlite3WhereClauseClear(WhereClause *)
Definition: sqlite3.c:125798
#define SQLITE_EXTERN
Definition: sqlite3.c:301
SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *)
Definition: sqlite3.c:136313
int(* RecordCompare)(int, const void *, UnpackedRecord *)
Definition: sqlite3.c:12614
#define PAGER_ERROR
Definition: sqlite3.c:46173
AuxData * pNext
Definition: sqlite3.c:17697
static sqlite3_mutex * pthreadMutexAlloc(int iType)
Definition: sqlite3.c:22680
SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse *, Table *)
Definition: sqlite3.c:105450
#define SAVEPOINT_RELEASE
Definition: sqlite3.c:14037
SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor **, int *)
Definition: sqlite3.c:72947
LogEst nOut
Definition: sqlite3.c:122388
SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *, Pgno, u16)
Definition: sqlite3.c:52773
#define IsVirtual(X)
Definition: sqlite3.c:14254
#define SQLITE_IOERR_RDLOCK
Definition: sqlite3.c:714
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *, int, const char *)
Definition: sqlite3.c:97410
SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *)
Definition: sqlite3.c:43574
u8 disableLookaside
Definition: sqlite3.c:15285
int iValue
Definition: sqlite3.c:14673
#define SQLITE_WriteSchema
Definition: sqlite3.c:13817
GLenum target
Definition: glext.h:1565
#define EXPR_REDUCEDSIZE
Definition: sqlite3.c:14768
#define PGHDR_WRITEABLE
Definition: sqlite3.c:12981
#define SQLITE_OmitNoopJoin
Definition: sqlite3.c:13854
#define OP_Move
Definition: sqlite3.c:12420
VdbeCursor ** apCsr
Definition: sqlite3.c:17564
#define COLNAME_DECLTYPE
Definition: sqlite3.c:12309
static u16 cellSizePtrNoPayload(MemPage *pPage, u8 *pCell)
Definition: sqlite3.c:58935
int addrVisit
Definition: sqlite3.c:17747
static void downgradeAllSharedCacheTableLocks(Btree *p)
Definition: sqlite3.c:58097
static int memjrnlSync(sqlite3_file *pJfd, int flags)
Definition: sqlite3.c:87112
static const FuncDef statInitFuncdef
Definition: sqlite3.c:94499
static void releaseMemArray(Mem *p, int N)
Definition: sqlite3.c:71349
u8 useSortingIdx
Definition: sqlite3.c:14560
u8 hasHeldSharedLock
Definition: sqlite3.c:46468
static void computeJD(DateTime *p)
Definition: sqlite3.c:18539
SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *)
Definition: sqlite3.c:68107
static void updateVirtualTable(Parse *pParse, SrcList *pSrc, Table *pTab, ExprList *pChanges, Expr *pRowidExpr, int *aXRef, Expr *pWhere, int onError)
Definition: sqlite3.c:120523
#define WO_IS
Definition: sqlite3.c:122746
#define MASKBIT32(n)
Definition: sqlite3.c:14869
GLbitfield flags
def finish()
Definition: test.py:373
static void pcache1FreePage(PgHdr1 *p)
Definition: sqlite3.c:44374
SQLITE_PRIVATE char * sqlite3DbStrNDup(sqlite3 *, const char *, u64)
Definition: sqlite3.c:24348
#define ExprClearProperty(E, P)
Definition: sqlite3.c:14750
unixInodeInfo * pNext
Definition: sqlite3.c:30183
SQLITE_PRIVATE int sqlite3PagerGet(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag)
Definition: sqlite3.c:51127
#define TK_CHECK
Definition: sqlite3.c:11204
u32 cksumInit
Definition: sqlite3.c:46475
static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff)
Definition: sqlite3.c:123069
u8 directMode
Definition: sqlite3.c:14558
SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *, Expr *, int)
Definition: sqlite3.c:92846
#define OP_Rowid
Definition: sqlite3.c:12460
u16 funcFlags
Definition: sqlite3.c:13900
SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage)
Definition: sqlite3.c:67735
#define tkWS
Definition: sqlite3.c:135250
static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate)
Definition: sqlite3.c:127894
static int unixAccess(sqlite3_vfs *NotUsed, const char *zPath, int flags, int *pResOut)
Definition: sqlite3.c:35034
#define WHERE_SKIPSCAN
Definition: sqlite3.c:122777
int(* xSync)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:5907
static int unixFullPathname(sqlite3_vfs *pVfs, const char *zPath, int nOut, char *zOut)
Definition: sqlite3.c:35093
const char *const zName
Definition: sqlite3.c:109566
#define OPFLG_IN2
Definition: sqlite3.c:12507
#define SQLITE_MAX_FUNCTION_ARG
Definition: sqlite3.c:10551
SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *, Table *, int, int)
Definition: sqlite3.c:99177
#define SQLITE_AutoIndex
Definition: sqlite3.c:13826
def callback(frame)
Definition: t265_stereo.py:91
#define BTREE_MEMORY
Definition: sqlite3.c:11887
#define TRANS_READ
Definition: sqlite3.c:57051
u16 * szCell
Definition: sqlite3.c:64080
#define assertCellInfo(x)
Definition: sqlite3.c:61911
SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void)
Definition: sqlite3.c:138877
#define NB
Definition: sqlite3.c:64409
SQLITE_PRIVATE void sqlite3Update(Parse *, SrcList *, ExprList *, Expr *, int)
Definition: sqlite3.c:119884
static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token t)
Definition: sqlite3.c:130783
int addrSkip
Definition: sqlite3.c:122303
#define SQLITE_MUTEX_STATIC_PRNG
Definition: sqlite3.c:6709
u32 aCksum[2]
Definition: sqlite3.c:53531
static const et_info fmtinfo[]
Definition: sqlite3.c:24510
void(* xTrace)(void *, const char *)
Definition: sqlite3.c:13710
#define SQLITE_CONFIG_LOG
Definition: sqlite3.c:2106
u32 iLikeRepCntr
Definition: sqlite3.c:122308
SQLITE_PRIVATE void sqlite3Reindex(Parse *, Token *, Token *)
Definition: sqlite3.c:101021
BtCursor * pNext
Definition: sqlite3.c:57184
char * zSql
Definition: sqlite3.c:17809
SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *, int idx, u32 value)
Definition: sqlite3.c:66380
#define findCell(P, I)
Definition: sqlite3.c:58688
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *, int)
Definition: sqlite3.c:61478
static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst)
Definition: sqlite3.c:129498
static WhereLoop ** whereLoopFindLesser(WhereLoop **ppPrev, const WhereLoop *pTemplate)
Definition: sqlite3.c:127806
SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context *, int, sqlite3_value **)
Definition: sqlite3.c:75225
SQLITE_PRIVATE int sqlite3MemCompare(const Mem *, const Mem *, const CollSeq *)
Definition: sqlite3.c:73652
int addrLikeRep
Definition: sqlite3.c:122309
#define OP_Gt
Definition: sqlite3.c:12377
#define SQLITE_STMTSTATUS_VM_STEP
Definition: sqlite3.c:7145
sqlite3_mutex * mutex
Definition: sqlite3.c:57116
SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *)
Definition: sqlite3.c:86680
#define WHERE_DUPLICATES_OK
Definition: sqlite3.c:14951
#define PTF_LEAF
Definition: sqlite3.c:56935
const char * zAuthContext
Definition: sqlite3.c:15394
SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:74885
#define OP_SorterData
Definition: sqlite3.c:12457
#define TK_MATCH
Definition: sqlite3.c:11130
#define WHERE_DISTINCT_NOOP
Definition: sqlite3.c:14967
SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *)
Definition: sqlite3.c:84017
static void codeDistinct(Parse *pParse, int iTab, int addrRepeat, int N, int iMem)
Definition: sqlite3.c:113426
#define SQLITE_PROTOCOL
Definition: sqlite3.c:672
#define SQLITE_CONSTRAINT_FOREIGNKEY
Definition: sqlite3.c:749
static int bindText(sqlite3_stmt *pStmt, int i, const void *zData, int nData, void(*xDel)(void *), u8 encoding)
Definition: sqlite3.c:75744
std::enable_if< std::is_integral< T >::value &&!std::is_same< T, bool >::value, GeneratorWrapper< T > >::type random(T a, T b)
Definition: catch.hpp:4638
#define WO_AND
Definition: sqlite3.c:122749
#define MEM_Subtype
Definition: sqlite3.c:17659
#define ROWSET_NEXT
Definition: sqlite3.c:45288
SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *)
Definition: sqlite3.c:83907
#define SQLITE_FREE(x)
Definition: sqlite3.c:20114
void * pFree
Definition: sqlite3.c:17810
#define SQLITE_IGNORE
Definition: sqlite3.c:2948
Mem ** apArg
Definition: sqlite3.c:17764
int nColumn
Definition: sqlite3.c:14575
static int memjrnlClose(sqlite3_file *pJfd)
Definition: sqlite3.c:87100
#define TK_ACTION
Definition: sqlite3.c:11158
SQLITE_PRIVATE void sqlite3TokenInit(Token *, char *)
Definition: sqlite3.c:27247
SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *)
Definition: sqlite3.c:74685
sqlite3_file * sjfd
Definition: sqlite3.c:46480
#define SQLITE_SCANSTAT_NAME
Definition: sqlite3.c:8123
u32 opMask
Definition: sqlite3.c:122531
#define CC_DOT
Definition: sqlite3.c:134370
u8 enc
Definition: sqlite3.c:13680
int nBackup
Definition: sqlite3.c:57034
SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int)
Definition: sqlite3.c:90799
#define sqlite3ParserARG_FETCH
Definition: sqlite3.c:130955
SorterFile file
Definition: sqlite3.c:84368
static int pthreadMutexTry(sqlite3_mutex *p)
Definition: sqlite3.c:22814
#define WO_EQ
Definition: sqlite3.c:122740
SQLITE_PRIVATE int sqlite3InitCallback(void *, int, char **, char **)
Definition: sqlite3.c:111996
Table * pFrom
Definition: sqlite3.c:14310
SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *)
Definition: sqlite3.c:43637
static int withExpand(Walker *pWalker, struct SrcList_item *pFrom)
Definition: sqlite3.c:116874
void * pCommitArg
Definition: sqlite3.c:13714
static int rehash(Hash *pH, unsigned int new_size)
Definition: sqlite3.c:28551
SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *)
Definition: sqlite3.c:87199
u8 szEst
Definition: sqlite3.c:14064
SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *)
Definition: sqlite3.c:113831
SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *, int, unsigned char *)
Definition: sqlite3.c:49596
int(* xMutexEnd)(void)
Definition: sqlite3.c:6649
static int openSubJournal(Pager *pPager)
Definition: sqlite3.c:50179
KeyInfo * pKeyInfo
Definition: sqlite3.c:12227
#define OP_VUpdate
Definition: sqlite3.c:12351
#define OPFLAG_TYPEOFARG
Definition: sqlite3.c:15421
#define FULLY_WITHIN
Definition: sqlite3.c:8570
FKey * pNextFrom
Definition: sqlite3.c:14311
#define YY_SHIFT_MAX
Definition: sqlite3.c:131345
SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int, char *, const char *, va_list)
Definition: sqlite3.c:25441
void init(void)
Definition: boing.c:180
GLuint start
Op * aOp
Definition: sqlite3.c:17762
SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *)
Definition: sqlite3.c:60345
#define SQLITE_TESTCTRL_SORTER_MMAP
Definition: sqlite3.c:6817
#define get2byteAligned(x)
Definition: sqlite3.c:57384
struct TableLock TableLock
Definition: sqlite3.c:11808
SQLITE_PRIVATE Schema * sqlite3SchemaGet(sqlite3 *, Btree *)
Definition: sqlite3.c:101650
#define VdbeComment(X)
Definition: sqlite3.c:12639
static int pager_write(PgHdr *pPg)
Definition: sqlite3.c:51581
int nDbChange
Definition: sqlite3.c:17576
SQLITE_PRIVATE VdbeOp * sqlite3VdbeTakeOpArray(Vdbe *, int *, int *)
Definition: sqlite3.c:70558
Expr * pWhere
Definition: sqlite3.c:15052
#define ONEPASS_MULTI
Definition: sqlite3.c:16062
int nMem
Definition: sqlite3.c:17571
static int done
#define WALINDEX_MAX_VERSION
Definition: sqlite3.c:53486
#define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags)
Definition: sqlite3.c:14003
#define OE_Default
Definition: sqlite3.c:14363
SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3 *, VdbeCursor *, UnpackedRecord *, int *)
Definition: sqlite3.c:74267
static void renameParentFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:93317
static int openDirectory(const char *, int *)
Definition: sqlite3.c:32606
GLint j
static int pagerAcquireMapPage(Pager *pPager, Pgno pgno, void *pData, PgHdr **ppPage)
Definition: sqlite3.c:49761
Index * pIndex
Definition: sqlite3.c:122360
#define tkSEMI
Definition: sqlite3.c:135249
SQLITE_PRIVATE Bitmask sqlite3WhereExprListUsage(WhereMaskSet *, ExprList *)
Definition: sqlite3.c:125839
ExprList * pOrderBy
Definition: sqlite3.c:122623
static void addArgumentToVtab(Parse *pParse)
Definition: sqlite3.c:121361
static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList)
Definition: sqlite3.c:85461
#define SQLITE_FUNC_CONSTANT
Definition: sqlite3.c:13955
u8 onError
Definition: sqlite3.c:14482
#define DbMaskTest(M, I)
Definition: sqlite3.c:15249
SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **)
Definition: sqlite3.c:69580
LookasideSlot * pFree
Definition: sqlite3.c:13603
int addColOffset
Definition: sqlite3.c:14217
static int vdbeSorterMergeTreeBuild(VdbeSorter *pSorter, MergeEngine **ppOut)
Definition: sqlite3.c:86471
int(* xSelectCallback)(Walker *, Select *)
Definition: sqlite3.c:15654
#define PAGERTRACE(X)
Definition: sqlite3.c:45936
int p2
Definition: sqlite3.c:12214
static int pcache1UnderMemoryPressure(PCache1 *pCache)
Definition: sqlite3.c:44426
#define SQLITE_NOLFS
Definition: sqlite3.c:679
i16 nCol
Definition: sqlite3.c:14207
static int checkConstraintExprNode(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:106898
void(* xMutexFree)(sqlite3_mutex *)
Definition: sqlite3.c:6651
struct ExprList::ExprList_item::@127::@128 x
#define BITVEC_MXHASH
Definition: sqlite3.c:42700
SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *, int, int, int)
Definition: sqlite3.c:70112
SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p)
Definition: sqlite3.c:60750
SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *,...)
Definition: sqlite3.c:25416
#define SQLITE_OPEN_SUBJOURNAL
Definition: sqlite3.c:782
SubProgram * pNext
Definition: sqlite3.c:12260
SQLITE_PRIVATE int sqlite3MatchSpanName(const char *, const char *, const char *, const char *)
Definition: sqlite3.c:87530
union Walker::@131 u
char * zToken
Definition: sqlite3.c:14672
struct TreeView TreeView
Definition: sqlite3.c:11810
int count
Definition: sqlite3.c:11047
static int btreeCursor(Btree *p, int iTable, int wrFlag, struct KeyInfo *pKeyInfo, BtCursor *pCur)
Definition: sqlite3.c:61757
SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *)
Definition: sqlite3.c:43586
#define osRead
void(* xProfile)(void *, const char *, u64)
Definition: sqlite3.c:13712
#define P4_INT64
Definition: sqlite3.c:12290
#define TK_TO
Definition: sqlite3.c:11115
#define WO_LE
Definition: sqlite3.c:122742
i64 movetoTarget
Definition: sqlite3.c:17507
#define WHERE_IN_ABLE
Definition: sqlite3.c:122773
#define PENDING_LOCK
Definition: sqlite3.c:13268
static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103953
#define PTRMAP_ISPAGE(pBt, pgno)
Definition: sqlite3.c:57276
#define SQLITE_DBSTATUS_CACHE_USED
Definition: sqlite3.c:7066
#define SQLITE_CacheSpill
Definition: sqlite3.c:13808
SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *, sqlite3_stmt *)
Definition: sqlite3.c:76005
#define SQLITE_INDEX_CONSTRAINT_LT
Definition: sqlite3.c:6063
static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem)
Definition: sqlite3.c:68426
GLint left
Definition: glext.h:1963
#define osMmap
#define OPFLAG_AUXDELETE
Definition: sqlite3.c:15428
int tz
Definition: sqlite3.c:18370
#define PragTyp_ENCODING
Definition: sqlite3.c:109532
MergeEngine * pMerger
Definition: sqlite3.c:84463
#define SQLITE_DBSTATUS_SCHEMA_USED
Definition: sqlite3.c:7067
#define osReadlink
int nOnceFlag
Definition: sqlite3.c:17816
Schema * pSchema
Definition: sqlite3.c:14473
HashElem * prev
Definition: sqlite3.c:11059
#define BTREE_SINGLE
Definition: sqlite3.c:11888
#define SQLITE_ENABLE_LOCKING_STYLE
Definition: sqlite3.c:28969
SQLITE_PRIVATE Expr * sqlite3ExprFunction(Parse *, ExprList *, Token *)
Definition: sqlite3.c:89535
#define SQLITE_TESTCTRL_BITVEC_TEST
Definition: sqlite3.c:6801
int iSDParm
Definition: sqlite3.c:15182
SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *)
Definition: sqlite3.c:101305
sqlite3_value ** apArg
Definition: sqlite3.c:15892
SrcList * pSrc
Definition: sqlite3.c:92872
#define IN_INDEX_ROWID
Definition: sqlite3.c:16537
int(* xNext)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:5901
#define OPFLAG_BULKCSR
Definition: sqlite3.c:15422
u32 aType[1]
Definition: sqlite3.c:17529
struct IndexSample IndexSample
Definition: sqlite3.c:11790
SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *)
Definition: sqlite3.c:100656
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:90238
SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal)
Definition: sqlite3.c:56586
GLint first
int iVersion
Definition: sqlite3.c:1450
int(* xCreate)(sqlite3 *, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVTab, char **)
Definition: sqlite3.c:5888
static int memjrnlWrite(sqlite3_file *pJfd, const void *zBuf, int iAmt, sqlite_int64 iOfst)
Definition: sqlite3.c:87006
i64 iSum
Definition: sqlite3.c:103987
static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint)
Definition: sqlite3.c:49121
UnixUnusedFd * pUnused
Definition: sqlite3.c:29111
#define SQLITE_SCANSTAT_NVISIT
Definition: sqlite3.c:8121
SQLITE_PRIVATE int sqlite3MisuseError(int)
Definition: sqlite3.c:138850
#define EP_Distinct
Definition: sqlite3.c:14718
static int editPage(MemPage *pPg, int iOld, int iNew, int nNew, CellArray *pCArray)
Definition: sqlite3.c:64302
#define WAL_RECOVER_LOCK
Definition: sqlite3.c:53496
#define TK_ROLLBACK
Definition: sqlite3.c:11112
#define TK_EXCEPT
Definition: sqlite3.c:11217
static void vdbeIncrFree(IncrMerger *)
Definition: sqlite3.c:85275
#define SQLITE_NOTICE_RECOVER_WAL
Definition: sqlite3.c:757
static SQLITE_WSD struct PCacheGlobal pcache1_g
#define TK_JOIN_KW
Definition: sqlite3.c:11198
static int cannotBeFunction(Parse *pParse, struct SrcList_item *pFrom)
Definition: sqlite3.c:116799
static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax)
Definition: sqlite3.c:116638
#define PragTyp_INTEGRITY_CHECK
Definition: sqlite3.c:109538
u8 eCode
Definition: sqlite3.c:15657
#define sqlite3ConnectionClosed(x)
Definition: sqlite3.c:16578
int iParent
Definition: sqlite3.c:122482
SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *)
Definition: sqlite3.c:74509
#define PAGER_GET_READONLY
Definition: sqlite3.c:12781
SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe *, int, int, const char *, void(*)(void *))
Definition: sqlite3.c:72021
#define SQLITE_CHECKPOINT_PASSIVE
Definition: sqlite3.c:7981
#define PAGER_LOCKINGMODE_EXCLUSIVE
Definition: sqlite3.c:12760
int nExpr
Definition: sqlite3.c:14794
char * zTo
Definition: sqlite3.c:14312
static void resolveAlias(Parse *pParse, ExprList *pEList, int iCol, Expr *pExpr, const char *zType, int nSubquery)
Definition: sqlite3.c:87464
WhereTerm * a
Definition: sqlite3.c:122555
#define SQLITE_CONFIG_PCACHE_HDRSZ
Definition: sqlite3.c:2114
SQLITE_PRIVATE void sqlite3Insert(Parse *, SrcList *, Select *, IdList *, int)
Definition: sqlite3.c:106281
int leftColumn
Definition: sqlite3.c:122485
SQLITE_PRIVATE char sqlite3AffinityType(const char *, u8 *)
Definition: sqlite3.c:97896
Definition: sqlite3.c:17591
int(* xInstCount)(Fts5Context *, int *pnInst)
Definition: sqlite3.c:10145
static void openStatTable(Parse *pParse, int iDb, int iStatCur, const char *zWhere, const char *zWhereType)
Definition: sqlite3.c:94195
#define CC_VARNUM
Definition: sqlite3.c:134350
GLbyte nx
Definition: glext.h:6424
SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int *)
Definition: sqlite3.c:90649
void(* sqlite3_syscall_ptr)(void)
Definition: sqlite3.c:1448
void(* xParseCell)(MemPage *, u8 *, CellInfo *)
Definition: sqlite3.c:56976
Token sArg
Definition: sqlite3.c:15371
#define TERM_CODED
Definition: sqlite3.c:122504
#define PCACHE_DIRTYLIST_REMOVE
Definition: sqlite3.c:43199
static SQLITE_NOINLINE const void * valueToText(sqlite3_value *pVal, u8 enc)
Definition: sqlite3.c:69197
double sqlite3_rtree_dbl
Definition: sqlite3.c:8492
static void walUnlockShared(Wal *pWal, int lockIdx)
Definition: sqlite3.c:54025
#define SQLITE_MAX_FILE_FORMAT
Definition: sqlite3.c:11315
#define EP_InfixFunc
Definition: sqlite3.c:14721
static int unixOpenSharedMemory(unixFile *pDbFd)
Definition: sqlite3.c:33330
int nCursor
Definition: sqlite3.c:17568
u8 tabFlags
Definition: sqlite3.c:14214
#define P4_INT32
Definition: sqlite3.c:12291
static void timeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19167
SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p)
Definition: sqlite3.c:121206
int(* xEof)(sqlite3_vtab_cursor *)
Definition: sqlite3.c:5902
SQLITE_PRIVATE TriggerStep * sqlite3TriggerUpdateStep(sqlite3 *, Token *, ExprList *, Expr *, u8)
Definition: sqlite3.c:119114
int(* xCurrentTimeInt64)(sqlite3_vfs *, sqlite3_int64 *)
Definition: sqlite3.c:1473
#define SQLITE_N_LIMIT
Definition: sqlite3.c:13574
SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *)
Definition: sqlite3.c:86632
SQLITE_PRIVATE void sqlite3StatusUp(int, int)
Definition: sqlite3.c:18039
#define SQLITE_CONFIG_MMAP_SIZE
Definition: sqlite3.c:2112
#define SQLITE_IOERR_SHMOPEN
Definition: sqlite3.c:723
LogEst nSelectRow
Definition: sqlite3.c:15044
#define WO_IN
Definition: sqlite3.c:122739
SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(sqlite3_stmt *pStmt, int idx, int iScanStatusOp, void *pOut)
#define PAGER_WRITER_FINISHED
Definition: sqlite3.c:46172
int(* xSleep)(sqlite3_vfs *, int microseconds)
Definition: sqlite3.c:1466
static u16 cachedCellSize(CellArray *p, int N)
Definition: sqlite3.c:64111
i16 iPKey
Definition: sqlite3.c:14206
static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster)
Definition: sqlite3.c:47062
void(* xDestroy)(void *)
Definition: sqlite3.c:14050
#define PragTyp_THREADS
Definition: sqlite3.c:109554
#define EP_Static
Definition: sqlite3.c:14729
static const YYACTIONTYPE yy_default[]
Definition: sqlite3.c:131430
Pgno dbSize
Definition: sqlite3.c:46469
#define PAGER_CKPT_FULLFSYNC
Definition: sqlite3.c:12797
static int vdbeSorterFlushPMA(VdbeSorter *pSorter)
Definition: sqlite3.c:85760
sqlite3_int64 iOffset
Definition: sqlite3.c:86876
SQLITE_PRIVATE void sqlite3VdbeChangeOpcode(Vdbe *, u32 addr, u8)
Definition: sqlite3.c:70654
static int resolveOrderByTermToExprList(Parse *pParse, Select *pSelect, Expr *pE)
Definition: sqlite3.c:88231
static void callFinaliser(sqlite3 *db, int offset)
Definition: sqlite3.c:121833
u16 nSize
Definition: sqlite3.c:57148
static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt)
Definition: sqlite3.c:32212
int nVdbeExec
Definition: sqlite3.c:13706
#define SF_NestedFrom
Definition: sqlite3.c:15083
static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC)
Definition: sqlite3.c:64578
SorterRecord * pNext
Definition: sqlite3.c:84510
sqlite3_rtree_dbl * aParam
Definition: sqlite3.c:8516
#define TK_CONFLICT
Definition: sqlite3.c:11168
#define BTCF_AtLast
Definition: sqlite3.c:57214
SQLITE_PRIVATE const char * sqlite3BtreeGetFilename(Btree *)
Definition: sqlite3.c:67111
SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *, int, void *)
Definition: sqlite3.c:19596
SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt)
Definition: sqlite3.c:74598
SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void)
Definition: sqlite3.c:135638
Bitmask notReady
Definition: sqlite3.c:122326
SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *)
Definition: sqlite3.c:121244
SQLITE_PRIVATE int sqlite3PagerBegin(Pager *, int exFlag, int)
Definition: sqlite3.c:51455
#define CC_LP
Definition: sqlite3.c:134361
#define SQLITE_STDCALL
Definition: sqlite3.c:310
i64 szMmap
Definition: sqlite3.c:13674
#define sqlite3StackAllocRaw(D, N)
Definition: sqlite3.c:15844
#define YY_MAX_SHIFT
Definition: sqlite3.c:130960
SQLITE_PRIVATE Btree * sqlite3DbNameToBtree(sqlite3 *, const char *)
Definition: sqlite3.c:139457
unsigned int iMaxKey
Definition: sqlite3.c:44085
#define SQLITE_SqlTrace
Definition: sqlite3.c:13815
u8 eSubtype
Definition: sqlite3.c:17602
#define TK_DESC
Definition: sqlite3.c:11170
#define SQLITE_IgnoreChecks
Definition: sqlite3.c:13819
Expr * pWhere
Definition: sqlite3.c:15513
#define UNIXFILE_DIRSYNC
Definition: sqlite3.c:29170
static void selectPopWith(Walker *pWalker, Select *p)
Definition: sqlite3.c:116990
u16 nHdrParsed
Definition: sqlite3.c:17496
#define SQLITE_QueryFlattener
Definition: sqlite3.c:13844
static int pagerBeginReadTransaction(Pager *pPager)
Definition: sqlite3.c:48959
Mem * pResultSet
Definition: sqlite3.c:17766
static SQLITE_WSD struct sqlite3AutoExtList sqlite3Autoext
SQLITE_PRIVATE int sqlite3VtabEponymousTableInit(Parse *, Module *)
Definition: sqlite3.c:122107
u32 nQueryLoop
Definition: sqlite3.c:15334
#define WAL_EXCLUSIVE_MODE
Definition: sqlite3.c:53678
#define PragTyp_PAGE_COUNT
Definition: sqlite3.c:109543
#define CC_COMMA
Definition: sqlite3.c:134367
u8 nOverflow
Definition: sqlite3.c:56952
Vdbe * pPrev
Definition: sqlite3.c:17773
#define restoreCursorPosition(p)
Definition: sqlite3.c:58482
u64 uptr
Definition: sqlite3.c:11519
static int unixFileControl(sqlite3_file *id, int op, void *pArg)
Definition: sqlite3.c:32866
static int whereLoopAddAll(WhereLoopBuilder *pBuilder)
Definition: sqlite3.c:129094
#define OpHelp(X)
Definition: sqlite3.c:28728
SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *, int N)
Definition: sqlite3.c:75280
#define TK_END
Definition: sqlite3.c:11111
SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int)
Definition: sqlite3.c:52838
#define OP_Yield
Definition: sqlite3.c:12355
sqlite3_vfs * pVfs
Definition: sqlite3.c:46437
#define MEMTYPE_HEAP
Definition: sqlite3.c:16636
struct vxworksFileId * pNext
Definition: sqlite3.c:29942
#define TOKEN
SQLITE_PRIVATE void sqlite3Detach(Parse *, Expr *)
Definition: sqlite3.c:96299
#define YYNSTATE
Definition: sqlite3.c:130958
Table * pTab
Definition: sqlite3.c:121030
#define TRACE_IDX_OUTPUTS(A)
Definition: sqlite3.c:126484
static const u8 sqlite3SmallTypeSizes[]
Definition: sqlite3.c:73063
u8 curFlags
Definition: sqlite3.c:57193
SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *)
Definition: sqlite3.c:67308
SQLiteThread * pThread
Definition: sqlite3.c:84361
#define WO_GT
Definition: sqlite3.c:122743
SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75512
#define sqlite3IsToplevel(p)
Definition: sqlite3.c:16188
#define sqlite3Tolower(x)
Definition: sqlite3.c:15782
#define SimulateDiskfullError(A)
Definition: sqlite3.c:29364
static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p)
Definition: sqlite3.c:126850
#define WHERE_PARTIALIDX
Definition: sqlite3.c:122779
u8 bDoTruncate
Definition: sqlite3.c:57098
int nChange
Definition: sqlite3.c:17797
static void minMaxFinalize(sqlite3_context *context)
Definition: sqlite3.c:104126
static const struct sqlite3_io_methods MemJournalMethods
Definition: sqlite3.c:87129
#define SQLITE_POWERSAFE_OVERWRITE
Definition: sqlite3.c:10773
static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg)
Definition: sqlite3.c:66529
static void walIteratorFree(WalIterator *p)
Definition: sqlite3.c:54755
struct TriggerStep TriggerStep
Definition: sqlite3.c:11813
int(* xColumnText)(Fts5Context *, int iCol, const char **pz, int *pn)
Definition: sqlite3.c:10149
#define SQLITE_LOCK_SHARED
Definition: sqlite3.c:843
int addrCont
Definition: sqlite3.c:122304
SQLITE_API int SQLITE_STDCALL sqlite3_system_errno(sqlite3 *)
Definition: sqlite3.c:137858
#define OP_IdxDelete
Definition: sqlite3.c:12464
SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse *, ExprList *, Token *, ExprList *, int)
Definition: sqlite3.c:99363
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:112718
#define BTREE_BLOBKEY
Definition: sqlite3.c:11939
#define SQLITE_VTAB_CONSTRAINT_SUPPORT
Definition: sqlite3.c:8041
i64 seqCount
Definition: sqlite3.c:17506
SQLITE_PRIVATE void sqlite3FinishCoding(Parse *)
Definition: sqlite3.c:96890
const char * pKey
Definition: sqlite3.c:11061
#define TERM_ORINFO
Definition: sqlite3.c:122506
#define SRT_Discard
Definition: sqlite3.c:15159
void(* sqlite3_destructor_type)(void *)
Definition: sqlite3.c:4857
SQLITE_PRIVATE const char * sqlite3OpcodeName(int)
Definition: sqlite3.c:28730
#define etGENERIC
Definition: sqlite3.c:24459
tRowcnt * anLt
Definition: sqlite3.c:14527
static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap)
Definition: sqlite3.c:25478
SQLITE_PRIVATE int sqlite3Atoi64(const char *, i64 *, int, u8)
Definition: sqlite3.c:27547
static void noopMutexFree(sqlite3_mutex *p)
Definition: sqlite3.c:22354
SQLITE_PRIVATE int sqlite3ExprCompare(Expr *, Expr *, int)
Definition: sqlite3.c:92754
SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *)
Definition: sqlite3.c:74943
#define TK_REINDEX
Definition: sqlite3.c:11193
#define OP_Count
Definition: sqlite3.c:12437
u8 ckptLock
Definition: sqlite3.c:53656
int(* xBusyHandler)(void *)
Definition: sqlite3.c:46505
BITVEC_TELEM aBitmap[BITVEC_NELEM]
Definition: sqlite3.c:42741
static int walDecodeFrame(Wal *pWal, u32 *piPage, u32 *pnTruncate, u8 *aData, u8 *aFrame)
Definition: sqlite3.c:53936
static VTable * vtabDisconnectAll(sqlite3 *db, Table *p)
Definition: sqlite3.c:121166
static int multiSelectValues(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:114931
static void pagerFixMaplimit(Pager *pPager)
Definition: sqlite3.c:49248
#define IsStat34
Definition: sqlite3.c:94180
#define SQLITE_IOCAP_ATOMIC64K
Definition: sqlite3.c:828
SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *, int *pRes)
Definition: sqlite3.c:62644
SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *)
Definition: sqlite3.c:43826
u8 bBenignMalloc
Definition: sqlite3.c:13684
#define SQLITE_INTERNAL
Definition: sqlite3.c:659
KeyInfo * pKeyInfo
Definition: sqlite3.c:84390
Pgno pgno
Definition: sqlite3.c:56977
#define SQLITE_WITHIN(P, S, E)
Definition: sqlite3.c:11530
static HashElem * findElementWithHash(const Hash *pH, const char *pKey, unsigned int *pHash)
Definition: sqlite3.c:28591
SQLITE_PRIVATE void sqlite3FkActions(Parse *, Table *, ExprList *, int, int *, int)
Definition: sqlite3.c:105736
SQLITE_PRIVATE void sqlite3OsClose(sqlite3_file *)
Definition: sqlite3.c:19551
#define TK_GE
Definition: sqlite3.c:11141
#define CC_QUOTE2
Definition: sqlite3.c:134353
bft expired
Definition: sqlite3.c:17787
static void freeP4(sqlite3 *db, int p4type, void *p4)
Definition: sqlite3.c:70695
const char * zDatabase
Definition: sqlite3.c:95433
#define TK_BEFORE
Definition: sqlite3.c:11163
#define RESERVED_BYTE
Definition: sqlite3.c:13331
static int dotlockUnlock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31261
SQLITE_PRIVATE const char * sqlite3JournalModename(int)
Definition: sqlite3.c:110211
#define OE_None
Definition: sqlite3.c:14351
#define OE_Ignore
Definition: sqlite3.c:14355
MemPage * pPage1
Definition: sqlite3.c:57093
int iCacheLevel
Definition: sqlite3.c:15300
i64 nDeferredImmCons
Definition: sqlite3.c:13765
static int walPagesize(Wal *pWal)
Definition: sqlite3.c:54871
#define YYMALLOCARGTYPE
Definition: sqlite3.c:130702
sqlite3 * pDestDb
Definition: sqlite3.c:67402
#define SQLITE_NOTFOUND
Definition: sqlite3.c:669
#define SQLITE_CANTOPEN_ISDIR
Definition: sqlite3.c:738
SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void)
Definition: sqlite3.c:135894
u8 locked
Definition: sqlite3.c:57031
#define TK_TABLE
Definition: sqlite3.c:11116
#define SQLITE_MAX_EXPR_DEPTH
Definition: sqlite3.c:10524
SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *, TriggerStep *)
Definition: sqlite3.c:118712
SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *, int)
Definition: sqlite3.c:99484
SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *)
Definition: sqlite3.c:136676
int nBuffer
Definition: sqlite3.c:84482
action
Definition: enums.py:62
void * token
Definition: sqlite3.c:17565
SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *, const char *, int)
Definition: sqlite3.c:75956
SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen)
Definition: sqlite3.c:53090
u8 eState
Definition: sqlite3.c:46461
int skipNext
Definition: sqlite3.c:57191
static int mallocWithAlarm(int n, void **pp)
Definition: sqlite3.c:23831
u8 autoVacuum
Definition: sqlite3.c:57096
SQLITE_PRIVATE void * sqlite3PageMalloc(int)
Definition: sqlite3.c:44398
static int codeAllEqualityTerms(Parse *pParse, WhereLevel *pLevel, int bRev, int nExtraReg, char **pzAff)
Definition: sqlite3.c:123226
#define SQLITE_MAX_SQL_LENGTH
Definition: sqlite3.c:10510
#define WAL_WRITE_LOCK
Definition: sqlite3.c:53493
#define etPERCENT
Definition: sqlite3.c:24463
SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *, const char *zSQL)
Definition: sqlite3.c:121724
#define MASTER_ROOT
Definition: sqlite3.c:11697
int iSelectID
Definition: sqlite3.c:17748
#define MEMTYPE_LOOKASIDE
Definition: sqlite3.c:16637
SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo *, int, const void *, UnpackedRecord *)
Definition: sqlite3.c:73389
SQLITE_PRIVATE Vdbe * sqlite3VdbeCreate(Parse *)
Definition: sqlite3.c:69912
static int mkFullPathname(const char *zPath, char *zOut, int nOut)
Definition: sqlite3.c:35060
static void versionFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103439
#define DbClearProperty(D, I, P)
Definition: sqlite3.c:13554
#define UNUSED_PARAMETER2(x, y)
Definition: sqlite3.c:11768
BtShared * pBt
Definition: sqlite3.c:57349
#define TK_VIRTUAL
Definition: sqlite3.c:11191
static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm)
Definition: sqlite3.c:123038
SorterRecord * pList
Definition: sqlite3.c:84252
void * pStart
Definition: sqlite3.c:13604
#define SQLITE_IOERR_READ
Definition: sqlite3.c:706
SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *)
Definition: sqlite3.c:136542
i16 nReserve
Definition: sqlite3.c:46497
int iSelfTab
Definition: sqlite3.c:15299
SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *)
Definition: sqlite3.c:112651
#define OP_Permutation
Definition: sqlite3.c:12431
int nHeight
Definition: sqlite3.c:15357
struct VdbeOp Op
Definition: sqlite3.c:17448
u8 hasMutex
Definition: sqlite3.c:33159
static void applyNumericAffinity(Mem *pRec, int bTryForInt)
Definition: sqlite3.c:76783
ynVar nVar
Definition: sqlite3.c:17777
#define SQLITE_MAX_COMPOUND_SELECT
Definition: sqlite3.c:10536
#define vdbeSorterRewindDebug(y)
Definition: sqlite3.c:85165
static int unixSleep(sqlite3_vfs *NotUsed, int microseconds)
Definition: sqlite3.c:35233
#define PragTyp_JOURNAL_SIZE_LIMIT
Definition: sqlite3.c:109540
static void exprAnalyzeOrTerm(SrcList *pSrc, WhereClause *pWC, int idxTerm)
Definition: sqlite3.c:125054
static int whereLoopCheaperProperSubset(const WhereLoop *pX, const WhereLoop *pY)
Definition: sqlite3.c:127733
SQLITE_PRIVATE int sqlite3ExprWalkNoop(Walker *, Expr *)
Definition: sqlite3.c:117305
SQLITE_PRIVATE int sqlite3BtreeCursorSize(void)
Definition: sqlite3.c:61843
static int lookupName(Parse *pParse, const char *zDb, const char *zTab, const char *zCol, NameContext *pNC, Expr *pExpr)
Definition: sqlite3.c:87580
static void destroyTable(Parse *pParse, Table *pTab)
Definition: sqlite3.c:99096
static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord)
Definition: sqlite3.c:85096
SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *)
Definition: sqlite3.c:61863
SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *)
Definition: sqlite3.c:93808
u8 * aMap
Definition: sqlite3.c:84425
#define WALINDEX_LOCK_OFFSET
Definition: sqlite3.c:53608
#define osRmdir
u8 hasCompound
Definition: sqlite3.c:15283
SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *)
Definition: sqlite3.c:68728
SQLITE_API int SQLITE_STDCALL sqlite3_create_module(sqlite3 *db, const char *zName, const sqlite3_module *p, void *pClientData)
Definition: sqlite3.c:121085
#define OP_IdxGT
Definition: sqlite3.c:12396
#define MASKBIT(n)
Definition: sqlite3.c:14868
Pgno iTable
Definition: sqlite3.c:56996
SQLITE_PRIVATE int sqlite3PagerSetSpillsize(Pager *, int)
Definition: sqlite3.c:49241
#define SQLITE_FCNTL_CHUNK_SIZE
Definition: sqlite3.c:1249
#define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
Definition: sqlite3.c:831
u8 fullSync
Definition: sqlite3.c:46442
SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *)
Definition: sqlite3.c:91356
SQLITE_PRIVATE int sqlite3RunVacuum(char **, sqlite3 *)
Definition: sqlite3.c:120744
#define SQLITE_REALLOC(x, y)
Definition: sqlite3.c:20115
u8 temp_store
Definition: sqlite3.c:13682
PgHdr1 ** apHash
Definition: sqlite3.c:44093
#define CC_LT
Definition: sqlite3.c:134356
int sortingIdxPTab
Definition: sqlite3.c:14563
#define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags)
Definition: sqlite3.c:14015
static void substSelect(sqlite3 *, Select *, int, ExprList *, int)
Definition: sqlite3.c:115965
#define REGISTER_TRACE(R, M)
Definition: sqlite3.c:77029
static const short yy_shift_ofst[]
Definition: sqlite3.c:131346
#define BITVEC_TELEM
Definition: sqlite3.c:42688
#define TK_DATABASE
Definition: sqlite3.c:11169
static void avgFinalize(sqlite3_context *context)
Definition: sqlite3.c:104037
#define SQLITE_N_BTREE_META
Definition: sqlite3.c:11849
SQLITE_PRIVATE SrcList * sqlite3SrcListEnlarge(sqlite3 *, SrcList *, int, int)
Definition: sqlite3.c:100391
yDbMask writeMask
Definition: sqlite3.c:15314
static void whereLikeOptimizationStringFixup(Vdbe *v, WhereLevel *pLevel, WhereTerm *pTerm)
Definition: sqlite3.c:123340
#define BTCF_ValidOvfl
Definition: sqlite3.c:57213
static double getDoubleArg(PrintfArguments *p)
Definition: sqlite3.c:24588
static void exprSetHeight(Expr *p)
Definition: sqlite3.c:89278
SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *, i64 size)
Definition: sqlite3.c:19565
#define WHERE_SEEK_TABLE
Definition: sqlite3.c:14963
static void pthreadMutexFree(sqlite3_mutex *p)
Definition: sqlite3.c:22745
static SQLITE_NOINLINE PgHdr * pcacheFetchFinishWithInit(PCache *pCache, Pgno pgno, sqlite3_pcache_page *pPage)
Definition: sqlite3.c:43506
u8 exclusiveMode
Definition: sqlite3.c:46438
static void zeroblobFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103701
SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam)
Definition: sqlite3.c:139417
char ** azResult
Definition: sqlite3.c:118520
#define SQLITE_MINIMUM_FILE_DESCRIPTOR
Definition: sqlite3.c:29705
#define PAGER_MEMORY
Definition: sqlite3.c:12753
static int vdbeMergeEngineLevel0(SortSubtask *pTask, int nPMA, i64 *piOffset, MergeEngine **ppOut)
Definition: sqlite3.c:86358
#define BTREE_AUTOVACUUM_INCR
Definition: sqlite3.c:11861
#define YY_MIN_SHIFTREDUCE
Definition: sqlite3.c:130961
Pgno pgno
Definition: sqlite3.c:12961
PCache * pPCache
Definition: sqlite3.c:46519
#define EP_Skip
Definition: sqlite3.c:14726
LogEst rRun
Definition: sqlite3.c:122387
int iSysErrno
Definition: sqlite3.c:13678
SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager)
Definition: sqlite3.c:53015
SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr)
Definition: sqlite3.c:88934
#define SQLITE_GET_LOCKPROXYFILE
Definition: sqlite3.c:1273
SQLITE_PRIVATE sqlite3_file * sqlite3PagerJrnlFile(Pager *)
Definition: sqlite3.c:52555
#define SQLITE_CONFIG_WIN32_HEAPSIZE
Definition: sqlite3.c:2113
static int btreeInitPage(MemPage *pPage)
Definition: sqlite3.c:59396
#define PGHDR_DONT_WRITE
Definition: sqlite3.c:12984
SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *, Table *)
Definition: sqlite3.c:122074
int pc
Definition: sqlite3.c:17780
static int robustFchown(int fd, uid_t uid, gid_t gid)
Definition: sqlite3.c:29608
SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *)
Definition: sqlite3.c:67171
#define OPFLAG_FORDELETE
Definition: sqlite3.c:15424
SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *, int, u8)
Definition: sqlite3.c:27321
SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *, i16)
Definition: sqlite3.c:97569
#define SQLITE_BUSY_SNAPSHOT
Definition: sqlite3.c:736
Definition: sql.cpp:11
static const char * actionName(u8 action)
Definition: sqlite3.c:110191
SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *, Token *)
Definition: sqlite3.c:97485
SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *, u8 P5)
Definition: sqlite3.c:70666
static int pagerPagecount(Pager *pPager, Pgno *pnPage)
Definition: sqlite3.c:48992
#define SQLITE_INT_TO_PTR(X)
Definition: sqlite3.c:10709
SQLITE_PRIVATE Trigger * sqlite3TriggersExist(Parse *, Table *, int, ExprList *, int *pMask)
Definition: sqlite3.c:119309
u8 eState
Definition: sqlite3.c:57195
static char * getTextArg(PrintfArguments *p)
Definition: sqlite3.c:24592
SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int)
Definition: sqlite3.c:119629
SQLITE_PRIVATE void sqlite3ExprListSetName(Parse *, ExprList *, Token *, int)
Definition: sqlite3.c:90118
u8 mayAbort
Definition: sqlite3.c:15282
static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable)
Definition: sqlite3.c:128969
static void nullifFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:103423
#define SQLITE_SKIP_UTF8(zIn)
Definition: sqlite3.c:15715
#define etEXP
Definition: sqlite3.c:24458
#define SQLITE_CHECKPOINT_TRUNCATE
Definition: sqlite3.c:7984
char affinity
Definition: sqlite3.c:14669
int nOpAlloc
Definition: sqlite3.c:15295
#define OP_Lt
Definition: sqlite3.c:12379
u8 hints
Definition: sqlite3.c:57196
SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75487
int(* xDestroy)(sqlite3_vtab *pVTab)
Definition: sqlite3.c:5896
SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *)
Definition: sqlite3.c:138820
SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *, Expr *, int)
Definition: sqlite3.c:92315
static int whereLoopAddVirtualOne(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUsable, u16 mExclude, sqlite3_index_info *pIdxInfo, int *pbIn)
Definition: sqlite3.c:128702
static int termIsEquivalence(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:125315
u8 enc
Definition: sqlite3.c:13542
SQLITE_PRIVATE sqlite3_file * sqlite3PagerFile(Pager *)
Definition: sqlite3.c:52547
int iNextSelectId
Definition: sqlite3.c:15360
#define OP_SorterInsert
Definition: sqlite3.c:12462
#define WHERE_REOPEN_IDX
Definition: sqlite3.c:14960
char * zName
Definition: sqlite3.c:14084
static int vdbeCommit(sqlite3 *db, Vdbe *p)
Definition: sqlite3.c:72049
StrAccum str
Definition: sqlite3.c:17732
#define OP_Vacuum
Definition: sqlite3.c:12349
char * zName
Definition: sqlite3.c:14026
SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *)
Definition: sqlite3.c:68831
struct CCurHint * pCCurHint
Definition: sqlite3.c:15664
int nCte
Definition: sqlite3.c:15690
u8 overflow
Definition: sqlite3.c:103989
static void pthreadMutexLeave(sqlite3_mutex *p)
Definition: sqlite3.c:22871
SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id)
Definition: sqlite3.c:19628
static void yyStackOverflow(yyParser *yypParser)
Definition: sqlite3.c:132390
#define SRT_EphemTab
Definition: sqlite3.c:15171
#define TK_FOREIGN
Definition: sqlite3.c:11213
SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *, int)
Definition: sqlite3.c:97274
sqlite3_pcache_methods2 pcache2
Definition: sqlite3.c:15587
#define SQLITE_CONFIG_MULTITHREAD
Definition: sqlite3.c:2092
static int connectionIsBusy(sqlite3 *db)
Definition: sqlite3.c:136605
SQLITE_PRIVATE TriggerStep * sqlite3TriggerInsertStep(sqlite3 *, Token *, IdList *, Select *, u8)
Definition: sqlite3.c:119085
unsigned char eFileLock
Definition: sqlite3.c:29107
#define TK_PLAN
Definition: sqlite3.c:11104
#define SQLITE_OPEN_WAL
Definition: sqlite3.c:788
#define O_BINARY
Definition: sqlite3.c:29396
SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal)
Definition: sqlite3.c:55690
sqlite3_int64 mxMmap
Definition: sqlite3.c:15592
static int noopMutexTry(sqlite3_mutex *p)
Definition: sqlite3.c:22356
bft doingRerun
Definition: sqlite3.c:17788
u8 changeCountDone
Definition: sqlite3.c:46463
static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC)
Definition: sqlite3.c:58589
#define FTS5_TOKENIZE_DOCUMENT
Definition: sqlite3.c:10384
#define SF_Converted
Definition: sqlite3.c:15088
#define CC_DIGIT
Definition: sqlite3.c:134347
GLsizei maxCount
static char * whereOrName(sqlite3 *db, char *zWhere, char *zConstant)
Definition: sqlite3.c:93475
static int walHash(u32 iPage)
Definition: sqlite3.c:54054
static void ctimestampFunc(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:19385
sqlite3 * db
Definition: sqlite3.c:57027
u8 bUseThreads
Definition: sqlite3.c:84396
u32 iCallback
Definition: sqlite3.c:53646
SQLITE_PRIVATE void * sqlite3PagerGetExtra(DbPage *)
Definition: sqlite3.c:52791
#define TRIGGER_AFTER
Definition: sqlite3.c:15467
sqlite3_vtab_cursor * pVCur
Definition: sqlite3.c:17499
#define MEM_Ephem
Definition: sqlite3.c:17656
SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75517
#define SQLITE_VdbeAddopTrace
Definition: sqlite3.c:13818
void * pLogArg
Definition: sqlite3.c:15612
#define WHERE_OMIT_OPEN_CLOSE
Definition: sqlite3.c:14952
#define MAX_PATHNAME
Definition: sqlite3.c:29062
#define UNIXFILE_NOLOCK
Definition: sqlite3.c:29177
AuxData * pAuxData
Definition: sqlite3.c:17567
static int autoVacuumCommit(BtShared *pBt)
Definition: sqlite3.c:61310
#define OP_RowData
Definition: sqlite3.c:12459
SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *, sqlite3_vtab *)
Definition: sqlite3.c:74385
#define SQLITE_FUNC_MINMAX
Definition: sqlite3.c:13956
#define SQLITE_FCNTL_WIN32_SET_HANDLE
Definition: sqlite3.c:1265
SQLITE_PRIVATE Bitmask sqlite3WhereExprUsage(WhereMaskSet *, Expr *)
Definition: sqlite3.c:125823
#define SQLITE_IOCAP_SAFE_APPEND
Definition: sqlite3.c:829
SQLITE_PRIVATE TriggerStep * sqlite3TriggerSelectStep(sqlite3 *, Select *)
Definition: sqlite3.c:119042
int regRoot
Definition: sqlite3.c:15318
const struct sqlite3_io_methods * pMethods
Definition: sqlite3.c:891
static int tableAndColumnIndex(SrcList *pSrc, int N, const char *zCol, int *piTab, int *piCol)
Definition: sqlite3.c:113082
#define P4_ADVANCE
Definition: sqlite3.c:12294
#define BTREE_INTKEY
Definition: sqlite3.c:11938
static int pagerWalFrames(Pager *pPager, PgHdr *pList, Pgno nTruncate, int isCommit)
Definition: sqlite3.c:48892
#define SQLITE_RecoveryMode
Definition: sqlite3.c:13822
static LogEst estLog(LogEst N)
Definition: sqlite3.c:126395
SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *)
Definition: sqlite3.c:58408
#define MEMJOURNAL_DFLT_FILECHUNKSIZE
Definition: sqlite3.c:86863
SQLITE_PRIVATE char * sqlite3VdbeExpandSql(Vdbe *, const char *)
Definition: sqlite3.c:76411
unixShm * pNext
Definition: sqlite3.c:33158
#define osStat
SubProgram * pProgram
Definition: sqlite3.c:15232
#define SimulateIOErrorBenign(X)
Definition: sqlite3.c:29362
SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *, Expr *, int *, char *)
Definition: sqlite3.c:104244
#define BITVEC_NPTR
Definition: sqlite3.c:42707
static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno)
Definition: sqlite3.c:58565
SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p)
Definition: sqlite3.c:68031
static SQLITE_NOINLINE void sqlite3ErrorFinish(sqlite3 *db, int err_code)
Definition: sqlite3.c:27105
static int checkRef(IntegrityCk *pCheck, Pgno iPage)
Definition: sqlite3.c:66543
SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse *, ExprList *, const char *)
Definition: sqlite3.c:90164
#define SQLITE_CkptFullFSync
Definition: sqlite3.c:13807
#define MEM_Undefined
Definition: sqlite3.c:17643
static void explainSimpleCount(Parse *pParse, Table *pTab, Index *pIdx)
Definition: sqlite3.c:117577
static void closePendingFds(unixFile *pFile)
Definition: sqlite3.c:30299
SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void)
Definition: sqlite3.c:36627
struct RowSetChunk * pChunk
Definition: sqlite3.c:45273
#define OP_OpenRead
Definition: sqlite3.c:12441
#define SQLITE_IOCAP_ATOMIC
Definition: sqlite3.c:820
SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *)
Definition: sqlite3.c:125968
SQLITE_PRIVATE void sqlite3OsCloseFree(sqlite3_file *)
Definition: sqlite3.c:19773
SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *)
Definition: sqlite3.c:86744
SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *)
Definition: sqlite3.c:66413
static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal)
Definition: sqlite3.c:104203
static int sqlite3InRhsIsConstant(Expr *pIn)
Definition: sqlite3.c:90566
u16 nFresh
Definition: sqlite3.c:45279
#define SQLITE_DYNAMIC
Definition: sqlite3.c:11723
static const void * fetchPayload(BtCursor *pCur, u32 *pAmt)
Definition: sqlite3.c:62382
int(* xAdvance)(BtCursor *, int *)
Definition: sqlite3.c:12234
#define osPwrite64
SrcList * yy347
Definition: sqlite3.c:130945
static const unsigned char aJournalMagic[]
Definition: sqlite3.c:46574
#define P4_EXPR
Definition: sqlite3.c:12284
static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr)
Definition: sqlite3.c:29899
#define SQLITE_STATUS_MALLOC_COUNT
Definition: sqlite3.c:6948
#define YY_ERROR_ACTION
Definition: sqlite3.c:130965
unsigned int nMinPage
Definition: sqlite3.c:44057
#define SQLITE_OPEN_FULLMUTEX
Definition: sqlite3.c:785
SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse *, ExprList *, int, int, u8)
Definition: sqlite3.c:92343
int aStat[3]
Definition: sqlite3.c:46507
#define CC_PLUS
Definition: sqlite3.c:134364
#define OP_SeekLT
Definition: sqlite3.c:12362
static MemPage * btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt)
Definition: sqlite3.c:59564
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoAlloc(sqlite3 *, int, int)
Definition: sqlite3.c:113811
u8 isMultiWrite
Definition: sqlite3.c:15281
int iSelectId
Definition: sqlite3.c:15359
SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *, va_list)
Definition: sqlite3.c:25392
u8 enc
Definition: sqlite3.c:14377
VdbeOp * aOp
Definition: sqlite3.c:12254
WhereInfo * pWInfo
Definition: sqlite3.c:122550
static int vdbeSafety(Vdbe *p)
Definition: sqlite3.c:74520
signed char p4type
Definition: sqlite3.c:12210
void(* xFreeSchema)(void *)
Definition: sqlite3.c:57115
int * aTree
Definition: sqlite3.c:84324
static sqlite3_pcache * pcache1Create(int szPage, int szExtra, int bPurgeable)
Definition: sqlite3.c:44653
#define WHERETRACE(K, X)
Definition: sqlite3.c:122264
SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int)
Definition: sqlite3.c:87163
SQLITE_PRIVATE int sqlite3FixExprList(DbFixer *, ExprList *)
Definition: sqlite3.c:96459
SQLITE_PRIVATE u8 sqlite3VdbeOneByteSerialTypeLen(u8)
Definition: sqlite3.c:73092
#define TF_HasPrimaryKey
Definition: sqlite3.c:14240
Btree * pWriter
Definition: sqlite3.c:57122
int bLocaltimeFault
Definition: sqlite3.c:15627
SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt)
Definition: sqlite3.c:76035
#define OP_VCreate
Definition: sqlite3.c:12490
#define HAS_UPDATE_HOOK(DB)
Definition: sqlite3.c:76626
SQLITE_PRIVATE SrcList * sqlite3SrcListAppend(sqlite3 *, SrcList *, Token *, Token *)
Definition: sqlite3.c:100473
SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *, Expr *)
Definition: sqlite3.c:89660
#define BITVEC_NELEM
Definition: sqlite3.c:42692
#define TK_OR
Definition: sqlite3.c:11127
SorterFile file2
Definition: sqlite3.c:84369
struct sqlite3::sqlite3InitInfo init
#define TF_WithoutRowid
Definition: sqlite3.c:14243
#define SQLITE_AUTH_USER
Definition: sqlite3.c:760
#define TK_INTO
Definition: sqlite3.c:11231
static void dateFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19186
#define SRT_Except
Definition: sqlite3.c:15157
#define YY_ACCEPT_ACTION
Definition: sqlite3.c:130966
char * zName
Definition: sqlite3.c:13509
VTable ** aVTrans
Definition: sqlite3.c:13753
#define TK_INDEXED
Definition: sqlite3.c:11156
static const char zMagicHeader[]
Definition: sqlite3.c:57692
u8 eLock
Definition: sqlite3.c:56997
SQLITE_PRIVATE UnpackedRecord * sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **)
Definition: sqlite3.c:73352
#define SQLITE_FCNTL_DB_UNCHANGED
Definition: sqlite3.c:13354
Table * pEpoTab
Definition: sqlite3.c:14051
#define SORTER_MAX_MERGE_COUNT
Definition: sqlite3.c:84525
static void addWhereTerm(Parse *pParse, SrcList *pSrc, int iLeft, int iColLeft, int iRight, int iColRight, int isOuterJoin, Expr **ppWhere)
Definition: sqlite3.c:113117
#define TK_ADD
Definition: sqlite3.c:11242
#define SCHEMA_TABLE(x)
Definition: sqlite3.c:11702
SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char *, Mem *, u32)
#define SQLITE_RECURSIVE
Definition: sqlite3.c:3003
SQLITE_PRIVATE int sqlite3GetInt32(const char *, int *)
Definition: sqlite3.c:27663
SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P)
Definition: sqlite3.c:26062
SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *, u32)
Definition: sqlite3.c:42790
#define SQLITE_TESTCTRL_NEVER_CORRUPT
Definition: sqlite3.c:6813
#define JT_OUTER
Definition: sqlite3.c:14936
#define SQLITE_OPEN_SHAREDCACHE
Definition: sqlite3.c:786
#define WAL_CKPT_LOCK
Definition: sqlite3.c:53495
#define OMIT_TEMPDB
Definition: sqlite3.c:11306
#define etCHARX
Definition: sqlite3.c:24464
SQLITE_PRIVATE void sqlite3OomClear(sqlite3 *)
Definition: sqlite3.c:24394
#define OP_DropTable
Definition: sqlite3.c:12475
static sqlite3_pcache_page * pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag)
Definition: sqlite3.c:44927
struct Fts5Context Fts5Context
Definition: sqlite3.c:9896
static void * vdbeSorterRowkey(const VdbeSorter *pSorter, int *pnKey)
Definition: sqlite3.c:86717
#define UNIXFILE_URI
Definition: sqlite3.c:29176
#define BTREE_BULKLOAD
Definition: sqlite3.c:12021
#define SQLITE_CONFIG_SQLLOG
Definition: sqlite3.c:2111
int iContinue
Definition: sqlite3.c:122659
SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db)
Definition: sqlite3.c:121883
#define sqlite3StackFree(D, P)
Definition: sqlite3.c:15846
SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *, Token *)
Definition: sqlite3.c:121374
SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse *, Table *, int, int, int, u8)
Definition: sqlite3.c:91462
int szPage
Definition: sqlite3.c:43098
int(* xDelete)(sqlite3_vfs *, const char *zName, int syncDir)
Definition: sqlite3.c:1458
#define sqlite3ParserARG_PDECL
Definition: sqlite3.c:130954
#define SQLITE_CursorHints
Definition: sqlite3.c:13856
static sqlite3_syscall_ptr unixGetSystemCall(sqlite3_vfs *pNotUsed, const char *zName)
Definition: sqlite3.c:29665
#define SF_Expanded
Definition: sqlite3.c:15078
#define YY_REDUCE_COUNT
Definition: sqlite3.c:131393
int szPage
Definition: sqlite3.c:56052
#define SRT_Fifo
Definition: sqlite3.c:15160
SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(sqlite3 *db, const char *zQueryFunc, int(*xQueryFunc)(sqlite3_rtree_query_info *), void *pContext, void(*xDestructor)(void *))
SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *)
Definition: sqlite3.c:76027
SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *)
Definition: sqlite3.c:121275
SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager)
Definition: sqlite3.c:53129
#define fileChunkSize(nChunkSize)
Definition: sqlite3.c:86869
SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *, void(*xTrace)(void *, const char *), void *)
Definition: sqlite3.c:137397
GLdouble GLdouble GLint GLint GLdouble v1
u8 op
Definition: sqlite3.c:14668
u32 magic
Definition: sqlite3.c:17771
static int vdbePmaReaderNext(PmaReader *pReadr)
Definition: sqlite3.c:84742
SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *, int nBytes)
Definition: sqlite3.c:75265
#define OP_SequenceTest
Definition: sqlite3.c:12446
static TriggerPrg * getRowTrigger(Parse *pParse, Trigger *pTrigger, Table *pTab, int orconf)
Definition: sqlite3.c:119595
int nOnce
Definition: sqlite3.c:15294
#define IsOrdinaryHiddenColumn(X)
Definition: sqlite3.c:14270
SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *, int, const char *)
Definition: sqlite3.c:119266
#define SQLITE_MAGIC_ERROR
Definition: sqlite3.c:13885
#define SQLITE_SELECT
Definition: sqlite3.c:2990
char * zDb
Definition: sqlite3.c:83590
SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *)
Definition: sqlite3.c:45323
#define EP_Propagate
Definition: sqlite3.c:14741
void next(auto_any_t cur, type2type< T, C > *)
Definition: foreach.hpp:757
SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id)
Definition: sqlite3.c:19622
SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void)
Definition: sqlite3.c:135655
static int isDate(sqlite3_context *context, int argc, sqlite3_value **argv, DateTime *p)
Definition: sqlite3.c:19089
WhereMaskSet sMaskSet
Definition: sqlite3.c:122663
Bool isOrdered
Definition: sqlite3.c:17493
static void codeOffset(Vdbe *v, int iOffset, int iContinue)
Definition: sqlite3.c:113406
SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *, ExprSpan *)
Definition: sqlite3.c:97968
#define TK_BY
Definition: sqlite3.c:11164
#define SQLITE_INDEX_CONSTRAINT_REGEXP
Definition: sqlite3.c:6068
#define TF_Readonly
Definition: sqlite3.c:14238
#define sqliteHashData(E)
Definition: sqlite3.c:11086
#define SQLITE_DEFAULT_PAGE_SIZE
Definition: sqlite3.c:10614
SQLITE_PRIVATE void sqlite3Analyze(Parse *, Token *, Token *)
Definition: sqlite3.c:95366
u32 nAlloc
Definition: sqlite3.c:14893
#define SQLITE_FCNTL_FILE_POINTER
Definition: sqlite3.c:1250
ExprList * pCols
Definition: sqlite3.c:15694
static void walShmBarrier(Wal *pWal)
Definition: sqlite3.c:53868
#define XN_ROWID
Definition: sqlite3.c:14515
FuncDestructor * pDestructor
Definition: sqlite3.c:13908
SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse *, Index *, int, int, int, int *, Index *, int)
Definition: sqlite3.c:102504
#define WHERE_CONSTRAINT
Definition: sqlite3.c:122765
u32 iSize
Definition: sqlite3.c:42732
SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(sqlite3 *db, const void *zSql, int nByte, sqlite3_stmt **ppStmt, const void **pzTail)
Definition: sqlite3.c:112788
#define SQLITE_DELETE
Definition: sqlite3.c:2978
#define sqlite3ConnectionUnlocked(x)
Definition: sqlite3.c:16577
#define memAboutToChange(P, M)
Definition: sqlite3.c:76566
SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int)
Definition: sqlite3.c:74303
u8 * aData
Definition: sqlite3.c:56970
SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *)
Definition: sqlite3.c:86777
static const struct compareInfo globInfo
Definition: sqlite3.c:103160
#define OP_AutoCommit
Definition: sqlite3.c:12340
u8 useJournal
Definition: sqlite3.c:46440
#define SQLITE_AFF_TEXT
Definition: sqlite3.c:14113
#define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS
Definition: sqlite3.c:6803
#define SQLITE_FullColNames
Definition: sqlite3.c:13805
int nSortingColumn
Definition: sqlite3.c:14564
static int readDbPage(PgHdr *pPg, u32 iFrame)
Definition: sqlite3.c:48732
static int columnIndex(Table *pTab, const char *zCol)
Definition: sqlite3.c:113065
#define SQLITE_DROP_TEMP_VIEW
Definition: sqlite3.c:2984
static void selectInnerLoop(Parse *pParse, Select *p, ExprList *pEList, int srcTab, SortCtx *pSort, DistinctCtx *pDistinct, SelectDest *pDest, int iContinue, int iBreak)
Definition: sqlite3.c:113477
#define VDBE_MAGIC_DEAD
Definition: sqlite3.c:17832
char * zColAff
Definition: sqlite3.c:14202
u8 * pTmpSpace
Definition: sqlite3.c:57124
#define OP_Destroy
Definition: sqlite3.c:12467
int(* xPhraseSize)(Fts5Context *, int iPhrase)
Definition: sqlite3.c:10143
sqlite3_pcache * pCache
Definition: sqlite3.c:43104
SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql)
Definition: sqlite3.c:135313
sqlite3_rtree_dbl * aParam
Definition: sqlite3.c:8548
long long int sqlite_int64
Definition: sqlite3.c:509
#define pcache1LeaveMutex(X)
Definition: sqlite3.c:44147
int nKeyCol
Definition: sqlite3.c:94309
#define N_OR_COST
Definition: sqlite3.c:122395
#define FTS5_TOKENIZE_AUX
Definition: sqlite3.c:10385
#define testcase(X)
Definition: sqlite3.c:10879
#define __inline__
Definition: linux.hpp:101
SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree)
Definition: sqlite3.c:67213
GLuint GLfloat GLfloat GLfloat x1
Definition: glext.h:9721
WhereClause * pOuter
Definition: sqlite3.c:122551
SQLITE_PRIVATE void sqlite3ExprCode(Parse *, Expr *, int)
Definition: sqlite3.c:92262
int leftCursor
Definition: sqlite3.c:122483
static int findCreateFileMode(const char *zPath, int flags, mode_t *pMode, uid_t *pUid, gid_t *pGid)
Definition: sqlite3.c:34650
#define WHERE_MULTI_OR
Definition: sqlite3.c:122775
#define TK_DELETE
Definition: sqlite3.c:11209
LogEst nEst
Definition: sqlite3.c:17749
#define CC_VARALPHA
Definition: sqlite3.c:134349
#define DbMaskSet(M, I)
Definition: sqlite3.c:15251
SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *)
Definition: sqlite3.c:85292
#define OP_CreateTable
Definition: sqlite3.c:12471
#define SQLITE_FUNC_COALESCE
Definition: sqlite3.c:13953
#define PAGER_WRITER_LOCKED
Definition: sqlite3.c:46169
#define SQLITE_WSD
Definition: sqlite3.c:11746
#define TK_TEMP
Definition: sqlite3.c:11121
char ** apRegion
Definition: sqlite3.c:33133
int iGeneration
Definition: sqlite3.c:13535
static With * withDup(sqlite3 *db, With *p)
Definition: sqlite3.c:89869
SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void)
Definition: sqlite3.c:45094
u16 maxLocal
Definition: sqlite3.c:56960
#define MEMTYPE_SCRATCH
Definition: sqlite3.c:16638
static int collationMatch(const char *zColl, Index *pIndex)
Definition: sqlite3.c:100951
SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *)
Definition: sqlite3.c:27981
#define SELECTTRACE(K, P, S, X)
Definition: sqlite3.c:112832
SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int)
Definition: sqlite3.c:43364
SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *, const void *, int)
Definition: sqlite3.c:74834
SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *)
Definition: sqlite3.c:85325
static SQLITE_NOINLINE void backupUpdate(sqlite3_backup *p, Pgno iPage, const u8 *aData)
Definition: sqlite3.c:68067
#define SPILLFLAG_NOSYNC
Definition: sqlite3.c:46278
u32 payloadSize
Definition: sqlite3.c:17524
void * data
Definition: sqlite3.c:11060
static void btreeParseCellPtrNoPayload(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:58745
const char * zStart
Definition: sqlite3.c:14820
#define PragTyp_DATA_STORE_DIRECTORY
Definition: sqlite3.c:109529
#define UPDATE_MAX_BLOBSIZE(P)
Definition: sqlite3.c:76647
ino_t ino
Definition: sqlite3.c:30161
static int fkParentIsModified(Table *pTab, FKey *p, int *aChange, int bChngRowid)
Definition: sqlite3.c:105188
#define PragTyp_PAGE_SIZE
Definition: sqlite3.c:109545
int iCacheCnt
Definition: sqlite3.c:15301
u8 file_format
Definition: sqlite3.c:13541
#define INCRINIT_TASK
Definition: sqlite3.c:86141
static int unixCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:30487
#define OP_MakeRecord
Definition: sqlite3.c:12435
#define OP_If
Definition: sqlite3.c:12360
u8 * aKey
Definition: sqlite3.c:84422
void * pPage
Definition: sqlite3.c:15596
YYCODETYPE major
Definition: sqlite3.c:131611
SQLITE_PRIVATE CollSeq * sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *)
Definition: sqlite3.c:89169
#define EP_Collate
Definition: sqlite3.c:14722
Mem * aMem
Definition: sqlite3.c:17763
void * pUser
Definition: sqlite3.c:14086
#define PARTLY_WITHIN
Definition: sqlite3.c:8569
int nAlloc
Definition: sqlite3.c:84418
#define ALLBITS
Definition: sqlite3.c:14870
list Y
Definition: rmse.py:132
SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *, u32 *pSize)
Definition: sqlite3.c:61966
#define SQLITE_SHM_EXCLUSIVE
Definition: sqlite3.c:1537
SQLITE_PRIVATE void sqlite3MemoryBarrier(void)
Definition: sqlite3.c:22618
CellInfo info
Definition: sqlite3.c:57186
#define SQLITE_CONFIG_MUTEX
Definition: sqlite3.c:2100
static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock)
Definition: sqlite3.c:57989
Table * pTab
Definition: sqlite3.c:14708
#define N_SORT_BUCKET
Definition: sqlite3.c:43777
#define EP_Alias
Definition: sqlite3.c:14736
u32 aCounter[5]
Definition: sqlite3.c:17801
SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *)
Definition: sqlite3.c:72779
SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *)
Definition: sqlite3.c:121905
SQLITE_PRIVATE const void * sqlite3BtreeKeyFetch(BtCursor *, u32 *pAmt)
Definition: sqlite3.c:62416
#define TK_JOIN
Definition: sqlite3.c:11224
SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *)
Definition: sqlite3.c:57565
#define SQLITE_READONLY_CANTLOCK
Definition: sqlite3.c:743
#define WHERE_USE_LIMIT
Definition: sqlite3.c:14962
Wal * pWal
Definition: sqlite3.c:56048
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N)
Definition: sqlite3.c:23709
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char *, const char *, sqlite3_int64)
Definition: sqlite3.c:139441
static int pcache1Init(void *NotUsed)
Definition: sqlite3.c:44586
SQLITE_PRIVATE void sqlite3AddNotNull(Parse *, int)
Definition: sqlite3.c:97864
#define SQLITE_TESTCTRL_PENDING_BYTE
Definition: sqlite3.c:6804
#define OP_Close
Definition: sqlite3.c:12448
SrcList * pTabList
Definition: sqlite3.c:122644
WhereLoop * pNew
Definition: sqlite3.c:122624
i16 readLock
Definition: sqlite3.c:53652
WhereClause wc
Definition: sqlite3.c:122568
#define mem0
Definition: sqlite3.c:23678
SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *)
Definition: sqlite3.c:57556
u8 sortFlags
Definition: sqlite3.c:112862
Schema * pSchema
Definition: sqlite3.c:14225
u8 dfltLockMode
Definition: sqlite3.c:13685
int iLimit
Definition: sqlite3.c:15046
#define P4_VTAB
Definition: sqlite3.c:12287
#define OP_VRename
Definition: sqlite3.c:12494
#define SQLITE_CONFIG_SINGLETHREAD
Definition: sqlite3.c:2091
#define ONEPASS_OFF
Definition: sqlite3.c:16060
#define SQLITE_IOERR_FSYNC
Definition: sqlite3.c:709
SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **)
Definition: sqlite3.c:19656
static int vdbeSorterCompareTail(SortSubtask *pTask, int *pbKey2Cached, const void *pKey1, int nKey1, const void *pKey2, int nKey2)
Definition: sqlite3.c:84822
static int vdbeMergeEngineInit(SortSubtask *pTask, MergeEngine *pMerger, int eMode)
Definition: sqlite3.c:86169
#define PAGER_STAT_HIT
Definition: sqlite3.c:46531
const char * zName
Definition: sqlite3.c:1454
int flags
Definition: sqlite3.c:13672
#define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal)
Definition: sqlite3.c:14012
GLdouble GLdouble GLdouble q
SQLITE_PRIVATE void sqlite3MaterializeView(Parse *, Table *, Expr *, int)
Definition: sqlite3.c:101759
int nLabel
Definition: sqlite3.c:15302
bft changeCntOn
Definition: sqlite3.c:17791
#define TK_CASCADE
Definition: sqlite3.c:11165
static void estimateTableWidth(Table *pTab)
Definition: sqlite3.c:98379
static void incrAggFunctionDepth(Expr *pExpr, int N)
Definition: sqlite3.c:87435
#define OP_InitCoroutine
Definition: sqlite3.c:12354
static void last_insert_rowid(sqlite3_context *context, int NotUsed, sqlite3_value **NotUsed2)
Definition: sqlite3.c:103091
FuncDef * pDef
Definition: sqlite3.c:17596
static void yy_syntax_error(yyParser *yypParser, int yymajor, sqlite3ParserTOKENTYPE yyminor)
Definition: sqlite3.c:134088
static void walMerge(const u32 *aContent, ht_slot *aLeft, int nLeft, ht_slot **paRight, int *pnRight, ht_slot *aTmp)
Definition: sqlite3.c:54635
int ix[BMS]
Definition: sqlite3.c:122608
u8 intKeyLeaf
Definition: sqlite3.c:56954
i64 journalHdr
Definition: sqlite3.c:46482
#define TK_SPAN
Definition: sqlite3.c:11259
static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak)
Definition: sqlite3.c:114635
SQLITE_PRIVATE Index * sqlite3PrimaryKeyIndex(Table *)
Definition: sqlite3.c:97559
int(* xFullPathname)(sqlite3_vfs *, const char *zName, int nOut, char *zOut)
Definition: sqlite3.c:1460
SQLITE_PRIVATE void sqlite3WhereSplit(WhereClause *, Expr *, u8)
Definition: sqlite3.c:125767
SQLITE_PRIVATE Expr * sqlite3ExprDup(sqlite3 *, Expr *, int)
Definition: sqlite3.c:89907
#define ONEPASS_SINGLE
Definition: sqlite3.c:16061
static void robust_close(unixFile *pFile, int h, int lineno)
Definition: sqlite3.c:30281
static int invalidateTempStorage(Parse *pParse)
Definition: sqlite3.c:110081
static void clearAllSharedCacheTableLocks(Btree *p)
Definition: sqlite3.c:58053
static void pager_unlock(Pager *pPager)
Definition: sqlite3.c:47580
#define P4_FUNCDEF
Definition: sqlite3.c:12282
SQLITE_PRIVATE void sqlite3SystemError(sqlite3 *, int)
Definition: sqlite3.c:27125
SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *)
Definition: sqlite3.c:90421
SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *, double)
Definition: sqlite3.c:74823
#define O_LARGEFILE
Definition: sqlite3.c:29386
SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *)
Definition: sqlite3.c:72638
#define put2byte(p, v)
Definition: sqlite3.c:57366
#define SQLITE_FCNTL_LAST_ERRNO
Definition: sqlite3.c:1247
#define SF_IncludeHidden
Definition: sqlite3.c:15089
int nVdbeActive
Definition: sqlite3.c:13703
#define WHERE_ONEPASS_DESIRED
Definition: sqlite3.c:14950
#define etRADIX
Definition: sqlite3.c:24456
static void exprNot(Parse *pParse, int doNot, ExprSpan *pSpan)
Definition: sqlite3.c:130805
#define OP_NewRowid
Definition: sqlite3.c:12451
#define SQLITE_INDEX_CONSTRAINT_LE
Definition: sqlite3.c:6062
void(* xDel)(void *)
Definition: sqlite3.c:14088
#define EP_DblQuoted
Definition: sqlite3.c:14720
Pager * pPager
Definition: sqlite3.c:57350
#define NC_PartIdx
Definition: sqlite3.c:15013
char * zErrMsg
Definition: sqlite3.c:118521
SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(sqlite3 *, const void *zName, int eTextRep, void *pArg, int(*xCompare)(void *, int, const void *, int, const void *))
Definition: sqlite3.c:138736
int mx
Definition: rmse.py:54
WhereClause sWC
Definition: sqlite3.c:122664
CollSeq * pColl
Definition: sqlite3.c:12224
WhereInfo * pWInfo
Definition: sqlite3.c:122621
SQLITE_PRIVATE int sqlite3BtreeClose(Btree *)
Definition: sqlite3.c:60164
i16 nRef
Definition: sqlite3.c:12971
u8 syncFlags
Definition: sqlite3.c:46446
#define SQLITE_FCNTL_VFS_POINTER
Definition: sqlite3.c:1269
#define SQLITE_OPEN_TRANSIENT_DB
Definition: sqlite3.c:779
u8 exclusiveMode
Definition: sqlite3.c:53654
static void yy_shift(yyParser *yypParser, int yyNewState, int yyMajor, sqlite3ParserTOKENTYPE yyMinor)
Definition: sqlite3.c:132431
#define DB_UnresetViews
Definition: sqlite3.c:13567
Bitmask prereq
Definition: sqlite3.c:122347
static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode)
Definition: sqlite3.c:86240
u8 truncateOnCommit
Definition: sqlite3.c:53658
SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *, u8)
Definition: sqlite3.c:69873
#define osOpenDirectory
#define OP_Variable
Definition: sqlite3.c:12419
static void cacheEntryClear(Parse *pParse, struct yColCache *p)
Definition: sqlite3.c:91255
u8 disableTriggers
Definition: sqlite3.c:15339
SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *)
Definition: sqlite3.c:130476
SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt)
Definition: sqlite3.c:75365
#define TK_LIKE_KW
Definition: sqlite3.c:11131
#define UINT16_TYPE
Definition: sqlite3.c:11418
static char * displayP4(Op *pOp, char *zTemp, int nTemp)
Definition: sqlite3.c:71123
SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *, int *, int flags)
Definition: sqlite3.c:66092
sqlite3_file * pDbFd
Definition: sqlite3.c:53644
HashElem * chain
Definition: sqlite3.c:11048
void * pOut
Definition: sqlite3.c:26211
Btree * pPrev
Definition: sqlite3.c:57037
SQLITE_PRIVATE int sqlite3JournalIsInMemory(sqlite3_file *p)
Definition: sqlite3.c:87224
SQLITE_PRIVATE void * sqlite3ScratchMalloc(int)
Definition: sqlite3.c:23923
SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *)
Definition: sqlite3.c:43619
SQLITE_API char * sqlite3_data_directory
Definition: sqlite3.c:5321
static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed)
Definition: sqlite3.c:90292
#define etFLOAT
Definition: sqlite3.c:24457
#define EP_Agg
Definition: sqlite3.c:14715
SQLITE_PRIVATE VdbeOp * sqlite3VdbeGetOp(Vdbe *, int)
Definition: sqlite3.c:70938
GLboolean enable
Definition: glext.h:5688
SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config
Definition: sqlite3.c:16835
SQLITE_PRIVATE void sqlite3PageFree(void *)
Definition: sqlite3.c:44405
#define HAVE_FULLFSYNC
Definition: sqlite3.c:32482
#define TERM_OR_OK
Definition: sqlite3.c:122508
int iArg
Definition: sqlite3.c:17694
#define TK_WHERE
Definition: sqlite3.c:11230
static void analyzeDatabase(Parse *pParse, int iDb)
Definition: sqlite3.c:95308
#define PCACHE_DIRTYLIST_FRONT
Definition: sqlite3.c:43201
#define vdbeSorterWorkDebug(x, y)
Definition: sqlite3.c:85164
SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *, int)
Definition: sqlite3.c:19580
#define IN_INDEX_MEMBERSHIP
Definition: sqlite3.c:16546
#define PGHDR_WAL_APPEND
Definition: sqlite3.c:12987
int nRefInitMutex
Definition: sqlite3.c:15609
static int flattenSubquery(Parse *pParse, Select *p, int iFrom, int isAgg, int subqueryIsAgg)
Definition: sqlite3.c:116134
#define yyTraceShift(X, Y)
Definition: sqlite3.c:132425
static struct RowSetEntry * rowSetEntryMerge(struct RowSetEntry *pA, struct RowSetEntry *pB)
Definition: sqlite3.c:45401
static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize)
Definition: sqlite3.c:87120
u16 maxLocal
Definition: sqlite3.c:57106
SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager)
Definition: sqlite3.c:53007
static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree)
Definition: sqlite3.c:61242
u8 * pPayload
Definition: sqlite3.c:57145
#define WO_SINGLE
Definition: sqlite3.c:122754
LogEst szTabRow
Definition: sqlite3.c:14210
#define OP_Int64
Definition: sqlite3.c:12414
#define PTRMAP_ROOTPAGE
Definition: sqlite3.c:57309
SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *)
Definition: sqlite3.c:71694
WhereLoop ** aLoop
Definition: sqlite3.c:122426
#define SQLITE_INDEX_CONSTRAINT_GT
Definition: sqlite3.c:6061
SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void *, sqlite3_int64, int), void *, sqlite3_int64)
GLdouble right
ExprList * pOrderBy
Definition: sqlite3.c:15185
int(* xShmMap)(sqlite3_file *, int iPg, int pgsz, int, void volatile **)
Definition: sqlite3.c:1000
int(* xMutexNotheld)(sqlite3_mutex *)
Definition: sqlite3.c:6656
#define SQLITE_CONFIG_GETMALLOC
Definition: sqlite3.c:2095
#define SRT_Union
Definition: sqlite3.c:15156
SQLITE_PRIVATE int sqlite3PCachePercentDirty(PCache *)
Definition: sqlite3.c:43901
struct FKey::sColMap aCol[1]
#define SQLITE_CREATE_TEMP_VIEW
Definition: sqlite3.c:2975
struct unixFileId fileId
Definition: sqlite3.c:30175
VTable * pVTable
Definition: sqlite3.c:121029
GLbitfield GLuint64 timeout
static Expr * exprTableRegister(Parse *pParse, Table *pTab, int regBase, i16 iCol)
Definition: sqlite3.c:104856
static void applyAffinity(Mem *pRec, char affinity, u8 enc)
Definition: sqlite3.c:76817
static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg)
Definition: sqlite3.c:32850
static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv)
Definition: sqlite3.c:118534
#define ExprSetProperty(E, P)
Definition: sqlite3.c:14749
static SQLITE_NOINLINE void * dbReallocFinish(sqlite3 *db, void *p, u64 n)
Definition: sqlite3.c:24288
static Btree * findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb)
Definition: sqlite3.c:67462
static void pcache1Shutdown(void *NotUsed)
Definition: sqlite3.c:44639
SQLITE_PRIVATE char * sqlite3MPrintf(sqlite3 *, const char *,...)
Definition: sqlite3.c:25379
#define OP_AggStep
Definition: sqlite3.c:12485
SQLITE_PRIVATE int sqlite3Strlen30(const char *)
Definition: sqlite3.c:27083
#define OP_Blob
Definition: sqlite3.c:12418
static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList)
Definition: sqlite3.c:85611
SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(sqlite3 *db, const char *zSql, int nByte, sqlite3_stmt **ppStmt, const char **pzTail)
Definition: sqlite3.c:112700
SQLITE_PRIVATE Table * sqlite3LocateTableItem(Parse *, int isView, struct SrcList_item *)
Definition: sqlite3.c:97147
static pid_t randomnessPid
Definition: sqlite3.c:29161
static Pgno btreePagecount(BtShared *pBt)
Definition: sqlite3.c:59624
u16 rsFlags
Definition: sqlite3.c:45280
int errCode
Definition: sqlite3.c:46473
SQLITE_API void SQLITE_STDCALL sqlite3_result_subtype(sqlite3_context *, unsigned int)
Definition: sqlite3.c:74853
#define PAGER_MJ_PGNO(x)
Definition: sqlite3.c:12745
SQLITE_API int SQLITE_STDCALL sqlite3_open16(const void *filename, sqlite3 **ppDb)
Definition: sqlite3.c:138659
union sqlite3::@123 u1
SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse *, SrcList *, Token *)
Definition: sqlite3.c:93604
#define DbMaskZero(M)
Definition: sqlite3.c:15250
#define TK_FOR
Definition: sqlite3.c:11174
GLuint in
Definition: glext.h:8859
BtCursor * pCursor
Definition: sqlite3.c:17498
#define ENC(db)
Definition: sqlite3.c:13793
int lastErrno
Definition: sqlite3.c:29109
SQLITE_PRIVATE sqlite3_mutex_methods const * sqlite3NoopMutex(void)
Definition: sqlite3.c:22362
SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal)
Definition: sqlite3.c:55849
SQLITE_PRIVATE Table * sqlite3LocateTable(Parse *, int isView, const char *, const char *)
Definition: sqlite3.c:97099
SQLITE_API int SQLITE_STDCALL 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:137283
#define LIKEFUNC(zName, nArg, arg, flags)
Definition: sqlite3.c:14009
struct Mem Mem
Definition: sqlite3.c:12200
Savepoint * pNext
Definition: sqlite3.c:14029
FuncDef * pHash
Definition: sqlite3.c:13907
GLenum type
WhereAndInfo * pAndInfo
Definition: sqlite3.c:122487
u8 ckptSyncFlags
Definition: sqlite3.c:46444
#define SQLITE_VERSION
Definition: sqlite3.c:366
const char * zName
Definition: sqlite3.c:96796
#define SQLITE_MAGIC_SICK
Definition: sqlite3.c:13883
SQLITE_PRIVATE Expr * sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int)
Definition: sqlite3.c:87903
SQLITE_PRIVATE int sqlite3CantopenError(int)
Definition: sqlite3.c:138854
int bDeclared
Definition: sqlite3.c:121032
#define TERM_ANDINFO
Definition: sqlite3.c:122507
#define DbHasProperty(D, I, P)
Definition: sqlite3.c:13551
#define SQLITE_INDEX_CONSTRAINT_GE
Definition: sqlite3.c:6064
#define PTRMAP_OVERFLOW1
Definition: sqlite3.c:57311
#define PGHDR_DIRTY
Definition: sqlite3.c:12980
static int vdbeSafetyNotNull(Vdbe *p)
Definition: sqlite3.c:74528
SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *)
Definition: sqlite3.c:52178
SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op)
Definition: sqlite3.c:56544
const char * zDb
Definition: sqlite3.c:15530
SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(sqlite3 *, AuxData **, int, int)
Definition: sqlite3.c:72805
u8 bPurgeable
Definition: sqlite3.c:43100
#define SQLITE_MAX_COLUMN
Definition: sqlite3.c:10499
SQLITE_PRIVATE Expr * sqlite3ExprAddCollateToken(Parse *pParse, Expr *, const Token *, int)
Definition: sqlite3.c:88970
#define OP_Next
Definition: sqlite3.c:12346
#define SQLITE_ForeignKeys
Definition: sqlite3.c:13825
#define sqlite3StackAllocZero(D, N)
Definition: sqlite3.c:15845
struct WalIterator::WalSegment aSegment[1]
int iOp
Definition: sqlite3.c:17693
static int keywordCode(const char *z, int n, int *pType)
Definition: sqlite3.c:134476
AutoincInfo * pAinc
Definition: sqlite3.c:15328
u16 exclMask
Definition: sqlite3.c:33162
u8 openFlags
Definition: sqlite3.c:57094
#define OPFLAG_APPEND
Definition: sqlite3.c:15415
void log(std::string message)
#define COLFLAG_PRIMKEY
Definition: sqlite3.c:14070
VdbeCursor * pAltCursor
Definition: sqlite3.c:17508
#define OP_OpenPseudo
Definition: sqlite3.c:12447
static int walFramePage(u32 iFrame)
Definition: sqlite3.c:54115
#define SQLITE_SO_DESC
Definition: sqlite3.c:14095
SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *, int)
Definition: sqlite3.c:90336
char ** azVar
Definition: sqlite3.c:15362
static void transferJoinMarkings(Expr *pDerived, Expr *pBase)
Definition: sqlite3.c:124877
SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem)
Definition: sqlite3.c:26788
SQLITE_PRIVATE void sqlite3Attach(Parse *, Expr *, Expr *, Expr *)
Definition: sqlite3.c:96318
#define SQLITE_CONFIG_PMASZ
Definition: sqlite3.c:2115
#define TK_ATTACH
Definition: sqlite3.c:11162
unsigned int nMaxPage
Definition: sqlite3.c:44056
SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(sqlite3 *db, const char *zName, const sqlite3_module *p, void *pClientData, void(*xDestroy)(void *))
Definition: sqlite3.c:121100
Expr * yy122
Definition: sqlite3.c:130937
SQLITE_PRIVATE void sqlite3SelectAddColumnTypeAndCollation(Parse *, Table *, Select *)
Definition: sqlite3.c:114511
sqlite3_vfs * pVfs
Definition: sqlite3.c:29104
#define PragTyp_INCREMENTAL_VACUUM
Definition: sqlite3.c:109535
#define PragTyp_CASE_SENSITIVE_LIKE
Definition: sqlite3.c:109526
#define SQLITE_INSERT
Definition: sqlite3.c:2987
static void invalidateAllOverflowCache(BtShared *pBt)
Definition: sqlite3.c:58139
Index * pCovidx
Definition: sqlite3.c:122323
#define OP_EndCoroutine
Definition: sqlite3.c:12410
SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *)
Definition: sqlite3.c:97248
sqlite3 * db
Definition: sqlite3.c:15540
SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3 *, int op, int *pCur, int *pHiwtr, int resetFlg)
Definition: sqlite3.c:18127
struct RowSetEntry * pRight
Definition: sqlite3.c:45252
sqlite3_int64 iJD
Definition: sqlite3.c:18367
static void invalidateIncrblobCursors(Btree *pBtree, i64 iRow, int isClearTable)
Definition: sqlite3.c:58161
int min(int a, int b)
Definition: lz4s.c:73
u8 bSyncSet
Definition: sqlite3.c:13512
SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *)
Definition: sqlite3.c:52293
#define CURTYPE_VTAB
Definition: sqlite3.c:17467
#define SQLITE_CONSTRAINT_NOTNULL
Definition: sqlite3.c:751
#define OP_Param
Definition: sqlite3.c:12480
GLuint GLint GLboolean GLint GLenum access
Definition: glext.h:2180
int nSegment
Definition: sqlite3.c:53711
#define SRT_Queue
Definition: sqlite3.c:15162
static void vdbeMergeEngineCompare(MergeEngine *pMerger, int iOut)
Definition: sqlite3.c:86087
static int allowedOp(int op)
Definition: sqlite3.c:124646
#define SQLITE_OPEN_PRIVATECACHE
Definition: sqlite3.c:787
#define SQLITE_NOTNULL
Definition: sqlite3.c:14138
#define vdbeSorterPopulateDebug(x, y)
Definition: sqlite3.c:85166
#define unixLogError(a, b, c)
Definition: sqlite3.c:30215
u16 dbOptFlags
Definition: sqlite3.c:13679
#define TK_COMMIT
Definition: sqlite3.c:11110
static PgHdr * pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB)
Definition: sqlite3.c:43743
#define ApplyCostMultiplier(C, T)
Definition: sqlite3.c:128073
#define osFallocate
#define OP_Pagecount
Definition: sqlite3.c:12495
SQLITE_PRIVATE int sqlite3BtreeOpen(sqlite3_vfs *pVfs, const char *zFilename, sqlite3 *db, Btree **ppBtree, int flags, int vfsFlags)
Definition: sqlite3.c:59801
#define EP_MemToken
Definition: sqlite3.c:14730
SQLITE_PRIVATE void sqlite3InsertBuiltinFuncs(FuncDef *, int)
Definition: sqlite3.c:101484
#define SQLITE_OrderByIdxJoin
Definition: sqlite3.c:13851
char validTZ
Definition: sqlite3.c:18375
sqlite3 * db
Definition: sqlite3.c:17609
static int getAndInitPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, BtCursor *pCur, int bReadOnly)
Definition: sqlite3.c:59646
#define invalidateOverflowCache(pCur)
Definition: sqlite3.c:58133
#define SQLITE_STATUS_MEMORY_USED
Definition: sqlite3.c:6939
SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *, u32, void *)
Definition: sqlite3.c:42877
static void pcache1Unpin(sqlite3_pcache *p, sqlite3_pcache_page *pPg, int reuseUnlikely)
Definition: sqlite3.c:44958
#define sqlite3Isalnum(x)
Definition: sqlite3.c:15778
double estimatedCost
Definition: sqlite3.c:6038
#define MEMTYPE_PCACHE
Definition: sqlite3.c:16639
#define PAGER_OPEN
Definition: sqlite3.c:46167
#define SQLITE_READONLY_DBMOVED
Definition: sqlite3.c:745
SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int)
Definition: sqlite3.c:72409
#define CC_GT
Definition: sqlite3.c:134357
u32 nBackfillAttempted
Definition: sqlite3.c:53597
#define threadid
Definition: sqlite3.c:29404
SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db)
Definition: sqlite3.c:137840
#define EP_VarSelect
Definition: sqlite3.c:14719
SQLITE_PRIVATE int sqlite3PcacheInitialize(void)
Definition: sqlite3.c:43312
SQLITE_PRIVATE void * sqlite3HashInsert(Hash *, const char *pKey, void *pData)
Definition: sqlite3.c:28684
static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:117478
static int vdbePmaReaderSeek(SortSubtask *pTask, PmaReader *pReadr, SorterFile *pFile, i64 iOff)
Definition: sqlite3.c:84695
signed char p3
Definition: sqlite3.c:12271
#define SQLITE_CONSTRAINT_CHECK
Definition: sqlite3.c:747
int nMaxArg
Definition: sqlite3.c:15319
static int setChildPtrmaps(MemPage *pPage)
Definition: sqlite3.c:60941
#define OE_Fail
Definition: sqlite3.c:14354
#define sqlite3ParserTOKENTYPE
Definition: sqlite3.c:130932
#define OP_Le
Definition: sqlite3.c:12378
static void btreeParseCellPtr(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:58762
#define SQLITE_PTRSIZE
Definition: sqlite3.c:11508
#define DbSetProperty(D, I, P)
Definition: sqlite3.c:13553
SQLITE_PRIVATE void sqlite3VdbeMultiLoad(Vdbe *, int, const char *,...)
Definition: sqlite3.c:70137
SQLITE_PRIVATE void sqlite3SchemaClear(void *)
Definition: sqlite3.c:101618
SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse *, Table *, int, u8, int, u8 *, int *, int *)
Definition: sqlite3.c:107548
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe *, Table *, int, int, int)
Definition: sqlite3.c:91428
sqlite3_rtree_dbl rParentScore
Definition: sqlite3.c:8557
#define PGHDR_CLEAN
Definition: sqlite3.c:12979
SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int)
Definition: sqlite3.c:43857
static void pcache1Shrink(sqlite3_pcache *p)
Definition: sqlite3.c:44719
#define sqliteHashFirst(H)
Definition: sqlite3.c:11084
#define TERM_LIKECOND
Definition: sqlite3.c:122515
SQLITE_PRIVATE void sqlite3PrngSaveState(void)
Definition: sqlite3.c:26149
#define PTRMAP_FREEPAGE
Definition: sqlite3.c:57310
int nAccumulator
Definition: sqlite3.c:14576
static void noopMutexEnter(sqlite3_mutex *p)
Definition: sqlite3.c:22355
unsigned isCovering
Definition: sqlite3.c:14487
static CollSeq * multiSelectCollSeq(Parse *pParse, Select *p, int iCol)
Definition: sqlite3.c:114690
Pager * pPager
Definition: sqlite3.c:57090
#define SQLITE_Fts3Tokenizer
Definition: sqlite3.c:13836
static i8 wherePathSatisfiesOrderBy(WhereInfo *pWInfo, ExprList *pOrderBy, WherePath *pPath, u16 wctrlFlags, u16 nLoop, WhereLoop *pLast, Bitmask *pRevMask)
Definition: sqlite3.c:129159
Table * pZombieTab
Definition: sqlite3.c:15374
SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *, Table *, int)
Definition: sqlite3.c:101722
GLint GLsizei count
sqlite3_file * jfd
Definition: sqlite3.c:46479
static void btreeHeapInsert(u32 *aHeap, u32 x)
Definition: sqlite3.c:66684
#define WAL_READ_LOCK(I)
Definition: sqlite3.c:53497
i64 cnt
Definition: sqlite3.c:103988
int nTransaction
Definition: sqlite3.c:57112
SQLITE_PRIVATE void * sqlite3DbMallocZero(sqlite3 *, u64)
Definition: sqlite3.c:24188
void * pCollNeededArg
Definition: sqlite3.c:13733
static void pager_reset(Pager *pPager)
Definition: sqlite3.c:47510
#define SQLITE_DROP_TABLE
Definition: sqlite3.c:2980
SQLITE_PRIVATE int sqlite3AuthReadCol(Parse *, const char *, const char *, int)
Definition: sqlite3.c:96601
SQLITE_PRIVATE int sqlite3WhereExplainOneScan(Parse *pParse, SrcList *pTabList, WhereLevel *pLevel, int iLevel, int iFrom, u16 wctrlFlags)
Definition: sqlite3.c:122864
#define TK_RAISE
Definition: sqlite3.c:11183
#define HAVE_READLINK
Definition: sqlite3.c:160
SQLITE_PRIVATE int sqlite3IdListIndex(IdList *, const char *)
Definition: sqlite3.c:100363
static int pager_write_pagelist(Pager *pPager, PgHdr *pList)
Definition: sqlite3.c:50087
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoOfIndex(Parse *, Index *)
Definition: sqlite3.c:101085
Table ** apVtabLock
Definition: sqlite3.c:15372
#define TK_TRANSACTION
Definition: sqlite3.c:11106
u8 iPkSortOrder
Definition: sqlite3.c:15350
static int vdbeRecordCompareInt(int nKey1, const void *pKey1, UnpackedRecord *pPKey2)
Definition: sqlite3.c:73989
#define SQLITE_TRANSIENT
Definition: sqlite3.c:4859
void * lockingContext
Definition: sqlite3.c:29110
struct Parse::yColCache aColCache[SQLITE_N_COLCACHE]
#define OP_IntCopy
Definition: sqlite3.c:12423
void * padding1
Definition: sqlite3.c:57203
sqlite3_vtab * pVtab
Definition: sqlite3.c:14185
u32 aFrameCksum[2]
Definition: sqlite3.c:53529
Op * aOp
Definition: sqlite3.c:17560
#define OP_SeekGT
Definition: sqlite3.c:12365
#define STAT_GET_NDLT
Definition: sqlite3.c:94813
void * pStress
Definition: sqlite3.c:43103
#define SQLITE_INDEX_CONSTRAINT_GLOB
Definition: sqlite3.c:6067
Expr * pIdxExpr
Definition: sqlite3.c:122527
static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo)
Definition: sqlite3.c:117494
SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *, int op,...)
Definition: sqlite3.c:136380
SQLITE_PRIVATE void sqlite3WhereClauseInit(WhereClause *, WhereInfo *)
Definition: sqlite3.c:125782
SQLITE_PRIVATE CollSeq * sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr)
Definition: sqlite3.c:89021
Table * pNextZombie
Definition: sqlite3.c:14226
SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster)
Definition: sqlite3.c:51933
static void sqliteViewResetAll(sqlite3 *db, int idx)
Definition: sqlite3.c:99001
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:84849
#define SQLITE_STATUS_SCRATCH_SIZE
Definition: sqlite3.c:6947
SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *, sqlite3 *, u16)
Definition: sqlite3.c:68811
SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3 *, const char *zFuncName, int nArg)
Definition: sqlite3.c:137366
#define INCRINIT_NORMAL
Definition: sqlite3.c:86140
static unsigned int yy_find_shift_action(yyParser *pParser, YYCODETYPE iLookAhead)
Definition: sqlite3.c:132294
static int unixGetpagesize(void)
Definition: sqlite3.c:33082
UnpackedRecord * pUnpacked
Definition: sqlite3.c:84391
i64 nDeferredImmCons
Definition: sqlite3.c:14028
#define SQLITE_CONSTRAINT_ROWID
Definition: sqlite3.c:756
const sqlite3_module * pModule
Definition: sqlite3.c:6129
#define SQLITE_FLOAT
Definition: sqlite3.c:4219
SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *, int)
Definition: sqlite3.c:61659
#define SRT_DistFifo
Definition: sqlite3.c:15161
static void releaseInodeInfo(unixFile *pFile)
Definition: sqlite3.c:30317
static const YYCODETYPE yyFallback[]
Definition: sqlite3.c:131493
SQLITE_PRIVATE void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p)
Definition: sqlite3.c:115355
#define TKFLG_DONTFOLD
Definition: sqlite3.c:11268
SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue)
Definition: sqlite3.c:66350
#define IS_LOCK_ERROR(x)
Definition: sqlite3.c:29077
SQLITE_PRIVATE void sqlite3PcacheClose(PCache *)
Definition: sqlite3.c:43726
Vdbe * pNext
Definition: sqlite3.c:17773
int mallocFailed
Definition: sqlite3.c:57355
static const unsigned char aiClass[]
Definition: sqlite3.c:134373
SQLITE_PRIVATE VdbeOp * sqlite3VdbeAddOpList(Vdbe *, int nOp, VdbeOpList const *aOp, int iLineno)
Definition: sqlite3.c:70578
int(* xWrite)(sqlite3_file *, const void *, int iAmt, sqlite3_int64 iOfst)
Definition: sqlite3.c:989
#define pager_pagehash(X)
Definition: sqlite3.c:47032
#define WRITE_UTF8(zOut, c)
Definition: sqlite3.c:26507
SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int)
Definition: sqlite3.c:52805
u8 isWriteLock
Definition: sqlite3.c:96795
#define OP_NoConflict
Definition: sqlite3.c:12368
SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *)
Definition: sqlite3.c:136675
int nModuleArg
Definition: sqlite3.c:14220
#define TK_WHEN
Definition: sqlite3.c:11237
#define MAX_ROWID
PagerSavepoint * aSavepoint
Definition: sqlite3.c:46484
SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *, int, const char *)
Definition: sqlite3.c:121795
#define OP_SorterNext
Definition: sqlite3.c:12342
SQLITE_PRIVATE void sqlite3WhereTabFuncArgs(Parse *, struct SrcList_item *, WhereClause *)
Definition: sqlite3.c:125876
static void freeIndex(sqlite3 *db, Index *p)
Definition: sqlite3.c:97195
#define etBUFSIZE
Definition: sqlite3.c:24605
#define JT_RIGHT
Definition: sqlite3.c:14935
SQLITE_PRIVATE const char * sqlite3IndexAffinityStr(sqlite3 *, Index *)
Definition: sqlite3.c:105879
#define SQLITE_DEFAULT_SYNCHRONOUS
Definition: sqlite3.c:13495
void * pScratch
Definition: sqlite3.c:15593
Btree * pSrc
Definition: sqlite3.c:67409
SQLITE_PRIVATE Bitvec * sqlite3BitvecCreate(u32)
Definition: sqlite3.c:42752
#define SQLITE_SET_LOCKPROXYFILE
Definition: sqlite3.c:1274
#define SQLITE_SCANSTAT_EXPLAIN
Definition: sqlite3.c:8124
#define SQLITE_LIMIT_TRIGGER_DEPTH
Definition: sqlite3.c:3539
#define BITVEC_HASH(X)
Definition: sqlite3.c:42705
#define SQLITE_ReverseOrder
Definition: sqlite3.c:13823
static int nolockLock(sqlite3_file *NotUsed, int NotUsed2)
Definition: sqlite3.c:31113
u8 errorAction
Definition: sqlite3.c:17786
static const double pi
Definition: src/types.h:57
SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *)
Definition: sqlite3.c:70248
u8 hdrOffset
Definition: sqlite3.c:56956
SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(void)
Definition: sqlite3.c:104277
int cache_size
Definition: sqlite3.c:13544
#define YYCODETYPE
Definition: sqlite3.c:130928
static Expr * substExpr(sqlite3 *db, Expr *pExpr, int iTable, ExprList *pEList)
Definition: sqlite3.c:115924
int(* SorterCompare)(SortSubtask *, int *, const void *, int, const void *, int)
Definition: sqlite3.c:84359
SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *, i64 *)
Definition: sqlite3.c:27633
SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3 *, int, int(*)(void *), void *)
Definition: sqlite3.c:137106
int(* xColumnSize)(Fts5Context *, int iCol, int *pnToken)
Definition: sqlite3.c:10150
u16 wtFlags
Definition: sqlite3.c:122491
#define WRC_Continue
Definition: sqlite3.c:15681
SQLITE_PRIVATE sqlite3_mutex * sqlite3MutexAlloc(int)
Definition: sqlite3.c:22236
Trigger * pTrigger
Definition: sqlite3.c:15230
#define OP_BitAnd
Definition: sqlite3.c:12382
Hash aFunc
Definition: sqlite3.c:13756
static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:104003
SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *)
Definition: sqlite3.c:25322
#define NC_VarSelect
Definition: sqlite3.c:15018
#define JT_INNER
Definition: sqlite3.c:14931
sqlite3_xauth xAuth
Definition: sqlite3.c:13741
#define WAL_SHM_RDONLY
Definition: sqlite3.c:53686
#define TK_SLASH
Definition: sqlite3.c:11150
struct sqlite3_snapshot sqlite3_snapshot
Definition: sqlite3.c:8342
static int whereRangeScanEst(Parse *pParse, WhereLoopBuilder *pBuilder, WhereTerm *pLower, WhereTerm *pUpper, WhereLoop *pLoop)
Definition: sqlite3.c:127266
#define OP_ShiftLeft
Definition: sqlite3.c:12384
#define SQLITE_PRAGMA
Definition: sqlite3.c:2988
unixShm * pShm
Definition: sqlite3.c:29113
struct RowSetEntry * pLeft
Definition: sqlite3.c:45253
i16 iRightJoinTable
Definition: sqlite3.c:14703
i16 aiColumn[11]
Definition: sqlite3.c:122534
SQLITE_PRIVATE const char * sqlite3PagerJournalname(Pager *)
Definition: sqlite3.c:52566
SQLITE_PRIVATE void * sqlite3HashFind(const Hash *, const char *pKey)
Definition: sqlite3.c:28660
static int reportError(int iErr, int lineno, const char *zType)
Definition: sqlite3.c:138841
SQLITE_PRIVATE void * sqlite3Malloc(u64)
Definition: sqlite3.c:23866
#define SQLITE_EMPTY
Definition: sqlite3.c:673
#define SQLITE_CONSTRAINT_COMMITHOOK
Definition: sqlite3.c:748
Parse * pParse
Definition: sqlite3.c:122643
unsigned int nRecyclable
Definition: sqlite3.c:44090
static int isMatchOfColumn(Expr *pExpr, unsigned char *peOp2)
Definition: sqlite3.c:124835
u8 eDistinct
Definition: sqlite3.c:122656
static TriggerPrg * codeRowTrigger(Parse *pParse, Trigger *pTrigger, Table *pTab, int orconf)
Definition: sqlite3.c:119481
static int pagerStress(void *p, PgHdr *pPg)
Definition: sqlite3.c:50269
char * pTmpSpace
Definition: sqlite3.c:46518
#define WO_MATCH
Definition: sqlite3.c:122745
SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager *, unsigned)
Definition: sqlite3.c:49327
u16 minLocal
Definition: sqlite3.c:57107
SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree *, unsigned)
Definition: sqlite3.c:60279
SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *, int *)
Definition: sqlite3.c:90376
#define SQLITE_ACCESS_EXISTS
Definition: sqlite3.c:1508
int(* sqlite3_callback)(void *, int, char **, char **)
Definition: sqlite3.c:573
SQLITE_PRIVATE KeyInfo * sqlite3KeyInfoRef(KeyInfo *)
Definition: sqlite3.c:113842
#define SQLITE_MALLOC_SOFT_LIMIT
Definition: sqlite3.c:10823
static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg)
Definition: sqlite3.c:121292
union WhereLevel::@135 u
i64 nFkConstraint
Definition: sqlite3.c:17806
int iFixedOp
Definition: sqlite3.c:15297
#define TK_MINUS
Definition: sqlite3.c:11148
#define TK_IMMEDIATE
Definition: sqlite3.c:11108
#define OE_Restrict
Definition: sqlite3.c:14358
SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *, int)
Definition: sqlite3.c:104216
SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *, ExprList *)
Definition: sqlite3.c:90192
SQLITE_API int SQLITE_STDCALL sqlite3_exec(sqlite3 *, const char *sql, int(*callback)(void *, int, char **, char **), void *, char **errmsg)
Definition: sqlite3.c:108027
static u32 walFramePgno(Wal *pWal, u32 iFrame)
Definition: sqlite3.c:54129
#define SQLITE_CREATE_INDEX
Definition: sqlite3.c:2970
SortSubtask * pTask
Definition: sqlite3.c:84323
static void heightOfExpr(Expr *p, int *pnHeight)
Definition: sqlite3.c:89240
static sqlite3_value * valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p)
Definition: sqlite3.c:69289
Token constraintName
Definition: sqlite3.c:15313
Hash aCollSeq
Definition: sqlite3.c:13757
u32 iHdrOffset
Definition: sqlite3.c:17526
static int exprAlwaysTrue(Expr *p)
Definition: sqlite3.c:89494
#define OP_OpenAutoindex
Definition: sqlite3.c:12443
#define SQLITE_FCNTL_COMMIT_PHASETWO
Definition: sqlite3.c:1264
#define TK_BEGIN
Definition: sqlite3.c:11105
SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData)
Definition: sqlite3.c:55949
SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int, int *)
Definition: sqlite3.c:19751
SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int)
Definition: sqlite3.c:97453
SQLITE_PRIVATE void sqlite3BtreeCursorHintFlags(BtCursor *, unsigned)
Definition: sqlite3.c:58549
SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75492
M
Definition: rmse.py:42
#define SQLITE_IOERR_DIR_CLOSE
Definition: sqlite3.c:722
static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit)
Definition: sqlite3.c:47770
IncrMerger * pIncr
Definition: sqlite3.c:84426
#define VdbeModuleComment(X)
Definition: sqlite3.c:12641
#define PAGER_JOURNALMODE_DELETE
Definition: sqlite3.c:12770
u16 minLocal
Definition: sqlite3.c:56961
#define TK_DEFERRED
Definition: sqlite3.c:11107
Lookaside lookaside
Definition: sqlite3.c:13739
static int isFatalError(int rc)
Definition: sqlite3.c:67605
static i64 journalHdrOffset(Pager *pPager)
Definition: sqlite3.c:47116
static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p)
Definition: sqlite3.c:18622
static int walHashGet(Wal *pWal, int iHash, volatile ht_slot **paHash, volatile u32 **paPgno, u32 *piZero)
Definition: sqlite3.c:54077
#define TK_PLUS
Definition: sqlite3.c:11147
struct KeyClass KeyClass
Definition: sqlite3.c:11791
u32 * aOffset
Definition: sqlite3.c:17528
int tnum
Definition: sqlite3.c:14205
static int growOpArray(Vdbe *v, int nOp)
Definition: sqlite3.c:69998
SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *, Expr *)
Definition: sqlite3.c:93100
static void releasePageNotNull(MemPage *pPage)
Definition: sqlite3.c:59700
LogEst rCost
Definition: sqlite3.c:122423
int nCol
Definition: sqlite3.c:14315
u8 readOnly
Definition: sqlite3.c:46449
SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:74894
SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *, Index *)
Definition: sqlite3.c:95570
#define SQLITE_FactorOutConst
Definition: sqlite3.c:13847
SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *)
Definition: sqlite3.c:137153
#define pager_datahash(X, Y)
Definition: sqlite3.c:47031
VdbeCursor * pCsr
Definition: sqlite3.c:17840
sqlite3 * db
Definition: sqlite3.c:15563
SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result)
Definition: sqlite3.c:118677
#define SQLITE_NOINLINE
Definition: sqlite3.c:10728
u32 szPage
Definition: sqlite3.c:53651
SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse *, ExprList *, ExprSpan *)
Definition: sqlite3.c:90143
#define TK_INSERT
Definition: sqlite3.c:11208
sqlite_int64 i64
Definition: sqlite3.c:11445
VdbeCursor ** apCsr
Definition: sqlite3.c:17774
SQLITE_PRIVATE int sqlite3PcacheOpen(int szPage, int szExtra, int bPurgeable, int(*xStress)(void *, PgHdr *), void *pStress, PCache *pToInit)
Definition: sqlite3.c:43339
static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:117388
u8 approx
Definition: sqlite3.c:103990
SQLITE_PRIVATE const char sqlite3StrBINARY[]
Definition: sqlite3.c:16937
int nRefSum
Definition: sqlite3.c:43095
ExprList * yy442
Definition: sqlite3.c:130948
#define OP_SoftNull
Definition: sqlite3.c:12417
int nVDestroy
Definition: sqlite3.c:13707
#define TK_QUERY
Definition: sqlite3.c:11103
static void sqlite3SelectExpand(Parse *pParse, Select *pSelect)
Definition: sqlite3.c:117323
#define SQLITE_MAX_LIKE_PATTERN_LENGTH
Definition: sqlite3.c:10653
#define P5_ConstraintCheck
Definition: sqlite3.c:12301
#define OP_RealAffinity
Definition: sqlite3.c:12429
#define WAL_SYNC_TRANSACTIONS
Definition: sqlite3.c:45715
#define FOUR_BYTE_UINT(x)
Definition: sqlite3.c:73205
bft bIsReader
Definition: sqlite3.c:17795
int iPKey
Definition: sqlite3.c:17849
static int seekAndWriteFd(int fd, i64 iOff, const void *pBuf, int nBuf, int *piErrno)
Definition: sqlite3.c:32320
union Expr::@125 u
#define SQLITE_NOTICE
Definition: sqlite3.c:684
const int sqlite3one
Definition: sqlite3.c:11560
static void whereLoopDelete(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:127689
static int sqliteDefaultBusyCallback(void *ptr, int count)
Definition: sqlite3.c:137021
#define TK_NO
Definition: sqlite3.c:11178
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect)
Definition: sqlite3.c:93085
static void randomBlob(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103067
#define osGetpid(X)
Definition: sqlite3.c:29071
#define OE_Cascade
Definition: sqlite3.c:14361
SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *, sqlite3 *, char *, int, int)
Definition: sqlite3.c:25345
#define IN_INDEX_INDEX_ASC
Definition: sqlite3.c:16539
char * idxStr
Definition: sqlite3.c:122367
#define FUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:13994
SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *)
Definition: sqlite3.c:74656
Bitmask revLoop
Definition: sqlite3.c:122421
sqlite3_int64 szMmap
Definition: sqlite3.c:46490
#define TK_ANALYZE
Definition: sqlite3.c:11160
tRowcnt * anEq
Definition: sqlite3.c:94291
SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *)
Definition: sqlite3.c:51767
SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *)
Definition: sqlite3.c:74313
#define SQLITE_IDXTYPE_UNIQUE
Definition: sqlite3.c:14503
#define TESTBIT(V, I)
Definition: sqlite3.c:42942
const char * zJournal
Definition: sqlite3.c:86896
sqlite3_rtree_dbl * aCoord
Definition: sqlite3.c:8551
#define vdbeSorterBlockDebug(x, y, z)
Definition: sqlite3.c:85167
static unsigned int strHash(const char *z)
Definition: sqlite3.c:28504
#define OP_FkCounter
Definition: sqlite3.c:12481
LZ4LIB_API char * dest
Definition: lz4.h:438
static void closeAllCursors(Vdbe *p)
Definition: sqlite3.c:71942
static int unixSync(sqlite3_file *id, int flags)
Definition: sqlite3.c:32643
int nOther
Definition: sqlite3.c:92874
tRowcnt nRow
Definition: sqlite3.c:94306
int iBufEnd
Definition: sqlite3.c:84484
Savepoint * pSavepoint
Definition: sqlite3.c:13760
#define OP_ParseSchema
Definition: sqlite3.c:12473
Column * aCol
Definition: sqlite3.c:14198
unsigned char nrhs
Definition: sqlite3.c:132470
sqlite3_file * pFd
Definition: sqlite3.c:84420
#define TWOPOWER31
Definition: sqlite3.c:28285
#define SQLITE_AUTH
Definition: sqlite3.c:680
SQLITE_PRIVATE void sqlite3PCacheSetDefault(void)
Definition: sqlite3.c:45072
#define SQLITE_FORMAT
Definition: sqlite3.c:681
#define MEM_Static
Definition: sqlite3.c:17655
#define SPILLFLAG_OFF
Definition: sqlite3.c:46276
SQLITE_PRIVATE int sqlite3WalkExpr(Walker *, Expr *)
Definition: sqlite3.c:87293
static int backupTruncateFile(sqlite3_file *pFile, i64 iSize)
Definition: sqlite3.c:67710
void * pIn
Definition: sqlite3.c:26213
u32 nScratchFree
Definition: sqlite3.c:23669
static int relocatePage(BtShared *pBt, MemPage *pDbPage, u8 eType, Pgno iPtrPage, Pgno iFreePage, int isCommit)
Definition: sqlite3.c:61053
static Mem * columnMem(sqlite3_stmt *pStmt, int i)
Definition: sqlite3.c:75423
static const char * encoding
Definition: model-views.h:201
#define SQLITE_OK
Definition: sqlite3.c:656
SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *, const char *zName)
Definition: sqlite3.c:75971
#define P5_ConstraintUnique
Definition: sqlite3.c:12300
#define PAGER_FULLFSYNC
Definition: sqlite3.c:12796
u32 Pgno
Definition: sqlite3.c:12725
SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal)
Definition: sqlite3.c:55887
Hash tblHash
Definition: sqlite3.c:13536
#define SQLITE_DEFAULT_CACHE_SIZE
Definition: sqlite3.c:10564
SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *)
Definition: sqlite3.c:67165
#define STAT_GET_NEQ
Definition: sqlite3.c:94811
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem)
Definition: sqlite3.c:91188
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:56402
#define P4_MEM
Definition: sqlite3.c:12285
#define BTREE_AUTOVACUUM_FULL
Definition: sqlite3.c:11860
SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *)
Definition: sqlite3.c:74643
static int walIndexRecover(Wal *pWal)
Definition: sqlite3.c:54300
u32 notUsed0
Definition: sqlite3.c:53598
SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(sqlite3 *db, const char *zFile, const char *zProc, char **pzErrMsg)
Definition: sqlite3.c:109268
#define SRT_Mem
Definition: sqlite3.c:15169
#define MEM_Zero
Definition: sqlite3.c:17658
static int numberOfCachePages(PCache *p)
Definition: sqlite3.c:43294
static int findInodeInfo(unixFile *pFile, unixInodeInfo **ppInode)
Definition: sqlite3.c:30351
#define vfsList
Definition: sqlite3.c:19796
#define WO_LT
Definition: sqlite3.c:122741
#define SQLITE_IOCAP_ATOMIC4K
Definition: sqlite3.c:824
#define EP_Reduced
Definition: sqlite3.c:14727
int(* xQueryPhrase)(Fts5Context *, int iPhrase, void *pUserData, int(*)(const Fts5ExtensionApi *, Fts5Context *, void *))
Definition: sqlite3.c:10152
SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe *, int, int, int, int, int)
Definition: sqlite3.c:70206
static int unixRead(sqlite3_file *id, void *pBuf, int amt, sqlite3_int64 offset)
Definition: sqlite3.c:32261
#define VDBE_MAGIC_INIT
Definition: sqlite3.c:17829
#define SQLITE_MUTEX_STATIC_OPEN
Definition: sqlite3.c:6708
int nRec
Definition: sqlite3.c:46474
void * token
Definition: sqlite3.c:12259
#define ConstFactorOk(P)
Definition: sqlite3.c:13874
static int dotlockClose(sqlite3_file *id)
Definition: sqlite3.c:31304
#define SQLITE_N_KEYWORD
Definition: sqlite3.c:134746
SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *)
Definition: sqlite3.c:121142
SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *, int *)
Definition: sqlite3.c:49624
SubProgram * pProgram
Definition: sqlite3.c:12229
static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept)
Definition: sqlite3.c:58366
#define NO_LOCK
Definition: sqlite3.c:13265
#define CC_SPACE
Definition: sqlite3.c:134351
static void renameTableFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:93252
#define OP_Jump
Definition: sqlite3.c:12357
static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes)
Definition: sqlite3.c:63101
u16 nExtra
Definition: sqlite3.c:46496
static int whereLoopAddBtreeIndex(WhereLoopBuilder *pBuilder, struct SrcList_item *pSrc, Index *pProbe, LogEst nInMul)
Definition: sqlite3.c:128088
struct Hash::_ht * ht
SQLITE_PRIVATE int sqlite3PcacheSetSpillsize(PCache *, int)
Definition: sqlite3.c:43869
static int getOverflowPage(BtShared *pBt, Pgno ovfl, MemPage **ppPage, Pgno *pPgnoNext)
Definition: sqlite3.c:61996
u8 eOrconf
Definition: sqlite3.c:15338
SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *)
Select * yy159
Definition: sqlite3.c:130938
#define OP_ResultRow
Definition: sqlite3.c:12424
#define OP_NextIfOpen
Definition: sqlite3.c:12344
#define SQLITE_ALTER_TABLE
Definition: sqlite3.c:2995
#define NOT_WITHIN
Definition: sqlite3.c:8568
static void whereLoopClear(sqlite3 *db, WhereLoop *p)
Definition: sqlite3.c:127645
#define SQLITE_RecTriggers
Definition: sqlite3.c:13824
#define TK_STAR
Definition: sqlite3.c:11149
SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p)
Definition: sqlite3.c:68045
SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *, int addr, const char *zP4, int N)
Definition: sqlite3.c:70835
#define NULL
Definition: tinycthread.c:47
static int unixShmLock(sqlite3_file *fd, int ofst, int n, int flags)
Definition: sqlite3.c:33617
#define SQLITE_CANTOPEN
Definition: sqlite3.c:671
u16 eOperator
Definition: sqlite3.c:122490
SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *, u32 addr, int P3)
Definition: sqlite3.c:70663
#define sqlite3WhereAddScanStatus(a, b, c, d)
Definition: sqlite3.c:122704
static void disableLookaside(Parse *pParse)
Definition: sqlite3.c:130742
SQLITE_PRIVATE void sqlite3OomFault(sqlite3 *)
Definition: sqlite3.c:24377
static int dupedExprStructSize(Expr *p, int flags)
Definition: sqlite3.c:89709
#define MEM_Null
Definition: sqlite3.c:17635
SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *, u8)
Definition: sqlite3.c:90349
void * pProgressArg
Definition: sqlite3.c:13746
SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *)
Definition: sqlite3.c:137746
#define OP_RowSetAdd
Definition: sqlite3.c:12479
SQLITE_PRIVATE void sqlite3FinishTrigger(Parse *, TriggerStep *, Token *)
Definition: sqlite3.c:118962
int addrInTop
Definition: sqlite3.c:122319
#define RESERVED_LOCK
Definition: sqlite3.c:13267
static CollSeq * sqlite3GetFuncCollSeq(sqlite3_context *context)
Definition: sqlite3.c:102594
#define EP_Unlikely
Definition: sqlite3.c:14732
SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *, SrcList *)
Definition: sqlite3.c:100528
u8 syncHeader
Definition: sqlite3.c:53659
#define IN_INDEX_NOOP_OK
Definition: sqlite3.c:16545
struct LikeOp yy318
Definition: sqlite3.c:130941
#define SQLITE_VERSION_NUMBER
Definition: sqlite3.c:367
u8 eTriggerOp
Definition: sqlite3.c:15337
VTable * pNext
Definition: sqlite3.c:14189
#define TRUE
Definition: tinycthread.c:50
SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *)
Definition: sqlite3.c:61855
static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3)
Definition: sqlite3.c:35323
static u16 numericType(Mem *pMem)
Definition: sqlite3.c:76900
SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *)
Definition: sqlite3.c:122161
static void closeCursorsInFrame(Vdbe *p)
Definition: sqlite3.c:71893
SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *, void *)
Definition: sqlite3.c:24076
Trigger * apTrigger[2]
Definition: sqlite3.c:14319
int nMmapOut
Definition: sqlite3.c:46489
static void translateColumnToCopy(Vdbe *v, int iStart, int iTabCur, int iRegister, int bIncrRowid)
Definition: sqlite3.c:126411
Hash trigHash
Definition: sqlite3.c:13538
Select * pPrior
Definition: sqlite3.c:15056
u16 aiIdx[BTCURSOR_MAX_DEPTH]
Definition: sqlite3.c:57204
int nRef
Definition: sqlite3.c:14186
SQLITE_PRIVATE int sqlite3ColumnsFromExprList(Parse *, ExprList *, i16 *, Column **)
Definition: sqlite3.c:114410
#define SQLITE_MUTEX_STATIC_PMEM
Definition: sqlite3.c:6712
int regReturn
Definition: sqlite3.c:112858
#define SQLITE_NOMEM_BKPT
Definition: sqlite3.c:15740
Mem * aMem
Definition: sqlite3.c:17562
SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *)
Definition: sqlite3.c:60449
#define TRANS_NONE
Definition: sqlite3.c:57050
SQLITE_PRIVATE Expr * sqlite3ExprAnd(sqlite3 *, Expr *, Expr *)
Definition: sqlite3.c:89515
int i
#define WHERE_SORTBYGROUP
Definition: sqlite3.c:14959
const char * z
Definition: sqlite3.c:14540
static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList)
Definition: sqlite3.c:90180
int rc
Definition: sqlite3.c:17781
sqlite3_backup * pNext
Definition: sqlite3.c:67420
#define PENDING_BYTE
Definition: sqlite3.c:13329
#define P4_MPRINTF
Definition: sqlite3.c:12288
SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:19714
SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *)
Definition: sqlite3.c:52945
#define offsetof(STRUCTURE, FIELD)
Definition: sqlite3.c:11372
GLdouble u1
const char * zCollName
Definition: sqlite3.c:122526
struct WalIndexHdr WalIndexHdr
Definition: sqlite3.c:53502
GLenum GLuint GLenum GLsizei length
#define SQLITE_CREATE_TEMP_INDEX
Definition: sqlite3.c:2972
#define SQLITE_MAX_MMAP_SIZE
Definition: sqlite3.c:11627
int iECursor
Definition: sqlite3.c:112857
int nStatement
Definition: sqlite3.c:13763
char * zCol
Definition: sqlite3.c:14322
static void setAllPagerFlags(sqlite3 *db)
Definition: sqlite3.c:110163
#define SQLITE_LIMIT_EXPR_DEPTH
Definition: sqlite3.c:3532
GLuint res
Definition: glext.h:8856
YYACTIONTYPE stateno
Definition: sqlite3.c:131610
static void noopMutexLeave(sqlite3_mutex *p)
Definition: sqlite3.c:22360
int nMem
Definition: sqlite3.c:15292
#define TK_LE
Definition: sqlite3.c:11139
SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *)
Definition: sqlite3.c:134800
unixInodeInfo * pInode
Definition: sqlite3.c:29105
void * pBusyHandlerArg
Definition: sqlite3.c:46506
SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *, Token *)
Definition: sqlite3.c:121468
struct sqlite3_blob sqlite3_blob
Definition: sqlite3.c:6208
#define TK_IN
Definition: sqlite3.c:11133
#define SQLITE_STATUS_PAGECACHE_USED
Definition: sqlite3.c:6940
#define SQLITE_TESTCTRL_ALWAYS
Definition: sqlite3.c:6806
static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt)
Definition: sqlite3.c:32366
static void resolveOutOfRangeError(Parse *pParse, const char *zType, int i, int mx)
Definition: sqlite3.c:88278
int nErr
Definition: sqlite3.c:15290
static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg)
Definition: sqlite3.c:51673
int nVTrans
Definition: sqlite3.c:13750
static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal)
Definition: sqlite3.c:85590
SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3 *, int(*)(void *, int), void *)
Definition: sqlite3.c:137083
#define TK_ASTERISK
Definition: sqlite3.c:11258
#define OP_Function0
Definition: sqlite3.c:12426
#define OP_FkIfZero
Definition: sqlite3.c:12402
#define OP_CreateIndex
Definition: sqlite3.c:12470
#define WHERE_UNQ_WANTED
Definition: sqlite3.c:122778
sqlite3_file * pFd
Definition: sqlite3.c:84239
#define OP_SetCookie
Definition: sqlite3.c:12439
#define TK_OF
Definition: sqlite3.c:11180
AutoincInfo * pNext
Definition: sqlite3.c:15198
#define TK_NOTNULL
Definition: sqlite3.c:11135
int nOut
Definition: sqlite3.c:13600
SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *, const char *zMaster)
Definition: sqlite3.c:61389
int(* sqlite3_xauth)(void *, int, const char *, const char *, const char *, const char *)
Definition: sqlite3.c:13657
PGroup grp
Definition: sqlite3.c:44110
#define SQLITE_REPLACE
Definition: sqlite3.c:8071
#define osWrite
static PgHdr * pcacheSortDirtyList(PgHdr *pIn)
Definition: sqlite3.c:43778
#define osMunmap
#define LARGEST_INT64
Definition: sqlite3.c:11575
Parse * pParse
Definition: sqlite3.c:17767
SQLITE_PRIVATE Trigger * sqlite3TriggerList(Parse *, Table *)
Definition: sqlite3.c:118740
int wantToLock
Definition: sqlite3.c:57033
static int walLockExclusive(Wal *pWal, int lockIdx, int n)
Definition: sqlite3.c:54031
unsigned int iKey
Definition: sqlite3.c:44022
const GLdouble * v2
#define SQLITE_FCNTL_WIN32_AV_RETRY
Definition: sqlite3.c:1252
static int removeFromSharingList(BtShared *pBt)
Definition: sqlite3.c:60085
unsigned int count
Definition: sqlite3.c:11044
SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *)
Definition: sqlite3.c:69859
static int closeUnixFile(sqlite3_file *id)
Definition: sqlite3.c:31028
void * pAuthArg
Definition: sqlite3.c:13742
SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor *, u32, u32, int, Mem *)
Definition: sqlite3.c:69157
SQLITE_PRIVATE WhereTerm * sqlite3WhereFindTerm(WhereClause *pWC, int iCur, int iColumn, Bitmask notReady, u32 op, Index *pIdx)
Definition: sqlite3.c:126248
unsigned nProgressOps
Definition: sqlite3.c:13747
static int pageInsertArray(MemPage *pPg, u8 *pBegin, u8 **ppData, u8 *pCellptr, int iFirst, int nCell, CellArray *pCArray)
Definition: sqlite3.c:64199
#define BYTESWAP32(x)
Definition: sqlite3.c:53816
int(* xOpen)(sqlite3_vfs *, const char *zName, sqlite3_file *, int flags, int *pOutFlags)
Definition: sqlite3.c:1456
#define SQLITE_DROP_TEMP_TABLE
Definition: sqlite3.c:2982
#define TK_ELSE
Definition: sqlite3.c:11239
static void pcache1Free(void *p)
Definition: sqlite3.c:44274
SQLITE_API int SQLITE_STDCALL sqlite3_status64(int op, sqlite3_int64 *pCurrent, sqlite3_int64 *pHighwater, int resetFlag)
Definition: sqlite3.c:18085
VdbeFrame * pFrame
Definition: sqlite3.c:17811
u8 keyConf
Definition: sqlite3.c:14215
static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData)
Definition: sqlite3.c:85538
static int clearCell(MemPage *pPage, unsigned char *pCell, u16 *pnSize)
Definition: sqlite3.c:63661
static int btreeGetUnusedPage(BtShared *pBt, Pgno pgno, MemPage **ppPage, int flags)
Definition: sqlite3.c:59722
int rc
Definition: sqlite3.c:15566
SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr)
Definition: sqlite3.c:103325
int rc
Definition: sqlite3.c:15276
#define SLOT_2_0
Definition: sqlite3.c:27802
#define SQLITE_CONFIG_SERIALIZED
Definition: sqlite3.c:2093
#define WHERE_COLUMN_NULL
Definition: sqlite3.c:122764
static int fillInCell(MemPage *pPage, unsigned char *pCell, const void *pKey, i64 nKey, const void *pData, int nData, int nZero, int *pnSize)
Definition: sqlite3.c:63742
int nChange
Definition: sqlite3.c:17575
int mxOut
Definition: sqlite3.c:13601
FileChunk * pChunk
Definition: sqlite3.c:86877
int syncFlags
Definition: sqlite3.c:56051
WhereClause wc
Definition: sqlite3.c:122577
GLuint GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat GLfloat s1
Definition: glext.h:9721
T prior(T x)
Definition: next_prior.hpp:155
const unsigned char * a
Definition: sqlite3.c:9908
WhereTerm aStatic[8]
Definition: sqlite3.c:122559
SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *, int *)
Definition: sqlite3.c:125998
int(* xUnlock)(sqlite3_file *, int)
Definition: sqlite3.c:994
dev_t dev
Definition: sqlite3.c:30157
Expr * pHaving
Definition: sqlite3.c:15054
SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *)
Definition: sqlite3.c:62962
#define SQLITE_STATUS_PAGECACHE_OVERFLOW
Definition: sqlite3.c:6941
SQLITE_PRIVATE int sqlite3OsGetLastError(sqlite3_vfs *)
Definition: sqlite3.c:19730
SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *, int)
Definition: sqlite3.c:71993
BtShared * pBt
Definition: sqlite3.c:56969
unsigned int n90pct
Definition: sqlite3.c:44084
SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *, Pgno x)
Definition: sqlite3.c:43693
int regRowid
Definition: sqlite3.c:15317
static SQLITE_NOINLINE PgHdr1 * pcache1FetchStage2(PCache1 *pCache, unsigned int iKey, int createFlag)
Definition: sqlite3.c:44754
static int isLikeOrGlob(Parse *pParse, Expr *pExpr, Expr **ppPrefix, int *pisComplete, int *pnoCase)
Definition: sqlite3.c:124735
SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *)
Definition: sqlite3.c:48417
char * zTarget
Definition: sqlite3.c:15512
SQLITE_API unsigned int SQLITE_STDCALL sqlite3_value_subtype(sqlite3_value *)
Definition: sqlite3.c:74671
SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *, int, char *)
Definition: sqlite3.c:70197
SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *)
Definition: sqlite3.c:43833
void(*(* xDlSym)(sqlite3_vfs *, void *, const char *zSymbol))(void)
Definition: sqlite3.c:1463
LogEst nOut
Definition: sqlite3.c:122356
#define SQLITE_CANTOPEN_BKPT
Definition: sqlite3.c:15733
SQLITE_PRIVATE void sqlite3DropIndex(Parse *, SrcList *, int)
Definition: sqlite3.c:100213
static int saveCursorKey(BtCursor *pCur)
Definition: sqlite3.c:58281
#define PAGER_JOURNALMODE_OFF
Definition: sqlite3.c:12772
#define SQLITE_ColumnCache
Definition: sqlite3.c:13845
Vdbe * v
Definition: sqlite3.c:17839
#define OP_SeekLE
Definition: sqlite3.c:12363
SQLITE_PRIVATE const Token sqlite3IntTokens[]
Definition: sqlite3.c:16897
static void totalFinalize(sqlite3_context *context)
Definition: sqlite3.c:104044
SorterFile aFile[2]
Definition: sqlite3.c:84468
PgHdr1 * pLruNext
Definition: sqlite3.c:44028
signed int int32_t
Definition: stdint.h:77
IdList * yy180
Definition: sqlite3.c:130939
SQLITE_PRIVATE void sqlite3HashClear(Hash *)
Definition: sqlite3.c:28484
static sqlite3_int64 getIntArg(PrintfArguments *p)
Definition: sqlite3.c:24584
SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *)
Definition: sqlite3.c:74659
#define tkTEMP
Definition: sqlite3.c:135255
static void allocateTempSpace(BtShared *pBt)
Definition: sqlite3.c:60124
#define WO_ISNULL
Definition: sqlite3.c:122747
SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *, int, int)
Definition: sqlite3.c:61590
#define STAT_GET_ROWID
Definition: sqlite3.c:94810
char * zFilename
Definition: sqlite3.c:33128
unsigned idxType
Definition: sqlite3.c:14483
list X
Definition: rmse.py:131
static int getDigits(const char *zDate, const char *zFormat,...)
Definition: sqlite3.c:18407
#define SQLITE_TESTCTRL_PRNG_RESET
Definition: sqlite3.c:6800
static int full_fsync(int fd, int fullSync, int dataOnly)
Definition: sqlite3.c:32510
SQLITE_PRIVATE int sqlite3VarintLen(u64 v)
Definition: sqlite3.c:28104
sqlite3_vfs * pVfs
Definition: sqlite3.c:86895
#define JT_CROSS
Definition: sqlite3.c:14932
struct RowSetChunk * pNextChunk
Definition: sqlite3.c:45263
#define SQLITE_CONFIG_MEMSTATUS
Definition: sqlite3.c:2099
u32 * heap
Definition: sqlite3.c:57359
#define OP_NullRow
Definition: sqlite3.c:12461
#define SQLITE_IOERR_SEEK
Definition: sqlite3.c:727
static void corruptSchema(InitData *pData, const char *zObj, const char *zExtra)
Definition: sqlite3.c:111967
FilePoint endpoint
Definition: sqlite3.c:86891
#define osLstat
#define SQLITE_FCNTL_MMAP_SIZE
Definition: sqlite3.c:1260
#define IN_INDEX_EPH
Definition: sqlite3.c:16538
SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *)
Definition: sqlite3.c:93186
static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage)
Definition: sqlite3.c:53754
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull)
Definition: sqlite3.c:89151
#define DO_OS_MALLOC_TEST(x)
Definition: sqlite3.c:19542
#define WHERE_ONETABLE_ONLY
Definition: sqlite3.c:14954
#define SQLITE_DROP_TRIGGER
Definition: sqlite3.c:2985
FKey * pPrevTo
Definition: sqlite3.c:14314
#define OP_Divide
Definition: sqlite3.c:12389
SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *, int)
Definition: sqlite3.c:93144
static int indexMightHelpWithOrderBy(WhereLoopBuilder *pBuilder, Index *pIndex, int iCursor)
Definition: sqlite3.c:128380
#define TK_UNIQUE
Definition: sqlite3.c:11203
#define PragTyp_WAL_CHECKPOINT
Definition: sqlite3.c:109556
SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *, i64)
Definition: sqlite3.c:68871
static Bitmask columnsInIndex(Index *pIdx)
Definition: sqlite3.c:128414
#define Stringify(P, enc)
Definition: sqlite3.c:76688
Bitmask revMask
Definition: sqlite3.c:122648
#define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP)
Definition: sqlite3.c:34054
#define JT_LEFT
Definition: sqlite3.c:14934
#define SQLITE_CONSTRAINT_FUNCTION
Definition: sqlite3.c:750
static int sqlite3LoadExtension(sqlite3 *db, const char *zFile, const char *zProc, char **pzErrMsg)
Definition: sqlite3.c:109128
u8 syncFlags
Definition: sqlite3.c:53653
ScratchFreeslot * pScratchFree
Definition: sqlite3.c:23668
int szChunk
Definition: sqlite3.c:29114
#define OP_String8
Definition: sqlite3.c:12436
#define BTS_NO_WAL
Definition: sqlite3.c:57134
const char * zName
Definition: sqlite3.c:13905
#define WAL_MAX_VERSION
Definition: sqlite3.c:53485
#define SQLITE_AFF_BLOB
Definition: sqlite3.c:14112
Schema * pSchema
Definition: sqlite3.c:15528
#define SQLITE_CREATE_TEMP_TABLE
Definition: sqlite3.c:2973
static void loadAnalysis(Parse *pParse, int iDb)
Definition: sqlite3.c:95298
#define SQLITE_LIMIT_FUNCTION_ARG
Definition: sqlite3.c:3535
#define OP_Copy
Definition: sqlite3.c:12421
#define UNUSED_PARAMETER(x)
Definition: sqlite3.c:11767
SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *)
Definition: sqlite3.c:96750
const char * zName
Definition: sqlite3.c:14048
static void pcache1TruncateUnsafe(PCache1 *pCache, unsigned int iLimit)
Definition: sqlite3.c:44555
SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *, char)
Definition: sqlite3.c:90451
struct sqlite3_pcache sqlite3_pcache
Definition: sqlite3.c:7158
#define CKCNSTRNT_ROWID
Definition: sqlite3.c:106891
static int exprMightBeIndexed(SrcList *pFrom, Bitmask mPrereq, Expr *pExpr, int *piCur, int *piColumn)
Definition: sqlite3.c:125378
#define SQLITE_STMTSTATUS_FULLSCAN_STEP
Definition: sqlite3.c:7142
FilePoint readpoint
Definition: sqlite3.c:86892
static void generateWithRecursiveQuery(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:114782
SQLITE_PRIVATE IdList * sqlite3IdListDup(sqlite3 *, IdList *)
Definition: sqlite3.c:89989
#define VDBE_MAGIC_HALT
Definition: sqlite3.c:17831
GLuint64 GLenum GLint fd
Definition: glext.h:7768
static void statInit(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:94417
#define PragTyp_TEMP_STORE
Definition: sqlite3.c:109552
#define SQLITE_Vacuum
Definition: sqlite3.c:13834
int(* xRandomness)(sqlite3_vfs *, int nByte, char *zOut)
Definition: sqlite3.c:1465
SQLITE_API void SQLITE_STDCALL sqlite3_value_free(sqlite3_value *)
Definition: sqlite3.c:74756
root
Definition: repo.py:7
#define SQLITE_IOERR_SHMLOCK
Definition: sqlite3.c:725
SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *, int, int, int)
Definition: sqlite3.c:91272
sqlite3_int64 iSyncPoint
Definition: sqlite3.c:56050
#define OP_IdxLE
Definition: sqlite3.c:12395
#define SQLITE_MAGIC_CLOSED
Definition: sqlite3.c:13882
WhereLevel a[1]
Definition: sqlite3.c:122665
static int unixLogErrorAtLine(int errcode, const char *zFunc, const char *zPath, int iLine)
Definition: sqlite3.c:30216
#define SMALLEST_INT64
Definition: sqlite3.c:11576
unsigned int n
Definition: sqlite3.c:14541
u16 flags
Definition: sqlite3.c:17600
#define OP_Last
Definition: sqlite3.c:12372
#define SQLITE_TESTCTRL_OPTIMIZATIONS
Definition: sqlite3.c:6808
#define PAGER_JOURNALMODE_WAL
Definition: sqlite3.c:12775
void * pData
Definition: sqlite3.c:12957
SQLITE_PRIVATE void sqlite3NestedParse(Parse *, const char *,...)
Definition: sqlite3.c:97018
SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int *, int *)
Definition: sqlite3.c:52994
SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *, int)
Definition: sqlite3.c:71247
SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *, int, int)
Definition: sqlite3.c:91340
#define TK_FUNCTION
Definition: sqlite3.c:11251
#define SQLITE_FUNC_CASE
Definition: sqlite3.c:13947
#define PAGER_WRITER_DBMOD
Definition: sqlite3.c:46171
SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p)
Definition: sqlite3.c:72650
static void minmaxStep(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:104088
SQLITE_PRIVATE void sqlite3BenignMallocHooks(void(*)(void), void(*)(void))
Definition: sqlite3.c:19947
SQLITE_PRIVATE sqlite3_vfs * sqlite3PagerVfs(Pager *)
Definition: sqlite3.c:52538
#define SQLITE_TESTCTRL_FAULT_INSTALL
Definition: sqlite3.c:6802
int p3
Definition: sqlite3.c:12215
ynVar iColumn
Definition: sqlite3.c:14700
SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *)
Definition: sqlite3.c:66195
#define SQLITE_DEFAULT_WORKER_THREADS
Definition: sqlite3.c:11350
SQLITE_PRIVATE const void * sqlite3ValueText(sqlite3_value *, u8)
Definition: sqlite3.c:69241
SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *, int, int)
Definition: sqlite3.c:70109
static int getLockingMode(const char *z)
Definition: sqlite3.c:110032
#define WHERE_IPK
Definition: sqlite3.c:122770
#define SQLITE_UPDATE
Definition: sqlite3.c:2992
#define SQLITE_MAX_WORKER_THREADS
Definition: sqlite3.c:11347
u16 cellOffset
Definition: sqlite3.c:56962
SQLITE_PRIVATE void sqlite3OpenTable(Parse *, int iCur, int iDb, Table *, int)
Definition: sqlite3.c:105833
static void constructAutomaticIndex(Parse *pParse, WhereClause *pWC, struct SrcList_item *pSrc, Bitmask notReady, WhereLevel *pLevel)
Definition: sqlite3.c:126517
SQLITE_PRIVATE int sqlite3AddInt64(i64 *, i64)
Definition: sqlite3.c:28257
SQLITE_PRIVATE sqlite3_pcache_page * sqlite3PcacheFetch(PCache *, Pgno, int createFlag)
Definition: sqlite3.c:43408
static struct unix_syscall aSyscall[]
SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *, Vdbe *)
Definition: sqlite3.c:72831
SQLITE_API int SQLITE_STDCALL 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:138885
#define TK_DEFAULT
Definition: sqlite3.c:11200
#define SQLITE_LIMIT_SQL_LENGTH
Definition: sqlite3.c:3530
SQLITE_PRIVATE int sqlite3VdbeLoadString(Vdbe *, int, const char *)
Definition: sqlite3.c:70125
#define TERM_LIKEOPT
Definition: sqlite3.c:122514
#define COLNAME_N
Definition: sqlite3.c:12319
#define SQLITE_DEFAULT_PCACHE_INITSZ
Definition: sqlite3.c:11364
PmaReader * aReadr
Definition: sqlite3.c:84325
struct MergeEngine MergeEngine
Definition: sqlite3.c:84225
SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *)
Definition: sqlite3.c:129430
static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:31170
SQLITE_PRIVATE void sqlite3CreateView(Parse *, Token *, Token *, Token *, ExprList *, Select *, int, int)
Definition: sqlite3.c:98817
SQLITE_PRIVATE int sqlite3MulInt64(i64 *, i64)
Definition: sqlite3.c:28286
#define SQLITE_FUNC_COUNT
Definition: sqlite3.c:13952
#define D(...)
Definition: usbhost.c:33
#define SQLITE_FCNTL_GET_LOCKPROXYFILE
Definition: sqlite3.c:1245
SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *)
Definition: sqlite3.c:28220
#define SQLITE_SCANSTAT_SELECTID
Definition: sqlite3.c:8125
#define charMap(X)
Definition: sqlite3.c:134424
#define MX_CELL(pBt)
Definition: sqlite3.c:56905
#define SQLITE_IOCAP_SEQUENTIAL
Definition: sqlite3.c:830
int pseudoTableReg
Definition: sqlite3.c:17500
int(* xRowCount)(Fts5Context *, sqlite3_int64 *pnRow)
Definition: sqlite3.c:10133
static void statGet(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:94828
u16 nCell
Definition: sqlite3.c:56964
SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *, int, int)
Definition: sqlite3.c:75814
SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *, u8)
Definition: sqlite3.c:26645
#define FALSE
Definition: tinycthread.c:53
u32 flags
Definition: sqlite3.c:14670
i8 nArg
Definition: sqlite3.c:13899
#define SQLITE_DeferFKs
Definition: sqlite3.c:13831
static int balance_deeper(MemPage *pRoot, MemPage **ppChild)
Definition: sqlite3.c:65423
u8 * aDataOfst
Definition: sqlite3.c:56973
#define SQLITE_FAIL
Definition: sqlite3.c:8069
#define SHARED_LOCK
Definition: sqlite3.c:13266
#define FLAG_SIGNED
Definition: sqlite3.c:24499
SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *)
Definition: sqlite3.c:100694
#define BMS
Definition: sqlite3.c:14863
SQLITE_PRIVATE void sqlite3VdbeError(Vdbe *, const char *,...)
Definition: sqlite3.c:69936
SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *)
Definition: sqlite3.c:91370
static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql)
Definition: sqlite3.c:120665
SQLITE_PRIVATE ExprList * sqlite3ExprListDup(sqlite3 *, ExprList *, int)
Definition: sqlite3.c:89911
#define PAGER_SYNCHRONOUS_FULL
Definition: sqlite3.c:12793
#define codeCursorHint(A, B, C)
Definition: sqlite3.c:123506
unsigned int nPage
Definition: sqlite3.c:44091
void * pAux
Definition: sqlite3.c:14049
#define get4byte
Definition: sqlite3.c:57367
int bVarOnly
Definition: sqlite3.c:15529
SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *)
Definition: sqlite3.c:74682
sqlite3_mutex * mutex
Definition: sqlite3.c:13669
int iBreak
Definition: sqlite3.c:122660
u8 intKey
Definition: sqlite3.c:56953
#define WHERE_FORCE_TABLE
Definition: sqlite3.c:14953
SQLITE_PRIVATE const void * sqlite3BtreeDataFetch(BtCursor *, u32 *pAmt)
Definition: sqlite3.c:62419
static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:102989
#define osMkdir
#define TK_KEY
Definition: sqlite3.c:11179
static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop)
Definition: sqlite3.c:122829
struct YYMINORTYPE::@141 yy207
u8 deferredMoveto
Definition: sqlite3.c:17485
int labelBkOut
Definition: sqlite3.c:112859
u8 vtabOnConflict
Definition: sqlite3.c:13688
SQLITE_PRIVATE void * sqlite3ParserAlloc(void *(*)(u64))
#define SQLITE_AFF_REAL
Definition: sqlite3.c:14116
With * yy331
Definition: sqlite3.c:130943
KeyInfo keyinfo
Definition: sqlite3.c:17843
SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *, int iCol)
Definition: sqlite3.c:75477
u8 subjInMemory
Definition: sqlite3.c:46466
static int sqlite3StrAccumEnlarge(StrAccum *p, int N)
Definition: sqlite3.c:25193
SQLITE_PRIVATE int sqlite3GetTempReg(Parse *)
Definition: sqlite3.c:93129
#define walFrameOffset(iFrame, szPage)
Definition: sqlite3.c:53634
SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_snapshot_open(sqlite3 *db, const char *zSchema, sqlite3_snapshot *pSnapshot)
SQLITE_PRIVATE void sqlite3FkCheck(Parse *, Table *, int, int, int *, int)
Definition: sqlite3.c:105250
u8 zChunk[8]
Definition: sqlite3.c:86857
etByte base
Definition: sqlite3.c:24489
SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n)
Definition: sqlite3.c:68353
struct TabResult TabResult
#define SQLITE_IOERR_SHMMAP
Definition: sqlite3.c:726
GLboolean * data
int nSpill
Definition: sqlite3.c:86888
int(* xColumnTotalSize)(Fts5Context *, int iCol, sqlite3_int64 *pnToken)
Definition: sqlite3.c:10134
#define VFUNCTION(zName, nArg, iArg, bNC, xFunc)
Definition: sqlite3.c:13997
SQLITE_PRIVATE int sqlite3IsIdChar(u8)
Definition: sqlite3.c:134792
#define TK_BITAND
Definition: sqlite3.c:11143
Table * pSeqTab
Definition: sqlite3.c:13540
WhereOrCost a[N_OR_COST]
Definition: sqlite3.c:122398
#define EP_ConstFunc
Definition: sqlite3.c:14733
#define SQLITE_DROP_TEMP_TRIGGER
Definition: sqlite3.c:2983
static void detachFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:96174
int iCol
Definition: sqlite3.c:83586
#define SQLITE_CONFIG_PCACHE
Definition: sqlite3.c:2104
static void typeofFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:102644
sqlite3_mutex *(* xMutexAlloc)(int)
Definition: sqlite3.c:6650
static int resolveSelectStep(Walker *pWalker, Select *p)
Definition: sqlite3.c:88511
#define BTREE_HINT_RANGE
Definition: sqlite3.c:12006
static int pagerOpenWalIfPresent(Pager *pPager)
Definition: sqlite3.c:49052
#define SQLITE_MALLOC(x)
Definition: sqlite3.c:20113
static void * vdbeSorterFlushThread(void *pCtx)
Definition: sqlite3.c:85746
static void freeTempSpace(BtShared *pBt)
Definition: sqlite3.c:60153
int szAlloc
Definition: sqlite3.c:44080
SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void)
Definition: sqlite3.c:19961
SQLITE_PRIVATE int sqlite3PagerFlush(Pager *)
Definition: sqlite3.c:50338
#define SQLITE_MUTEX_FAST
Definition: sqlite3.c:6703
#define P4_FUNCCTX
Definition: sqlite3.c:12296
#define WHERE_BOTH_LIMIT
Definition: sqlite3.c:122768
#define TK_NE
Definition: sqlite3.c:11136
BtCursor * pCsr
Definition: sqlite3.c:83587
#define INT16_TYPE
Definition: sqlite3.c:11425
#define osClose
SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *, int, int, int)
Definition: sqlite3.c:99037
#define OP_Subtract
Definition: sqlite3.c:12387
ExprList * pFuncArg
Definition: sqlite3.c:14922
int addrOpenEphm[2]
Definition: sqlite3.c:15050
static int defragmentPage(MemPage *pPage)
Definition: sqlite3.c:58996
#define EP_NoReduce
Definition: sqlite3.c:14731
#define SQLITE_INDEX_CONSTRAINT_MATCH
Definition: sqlite3.c:6065
#define PragTyp_SYNCHRONOUS
Definition: sqlite3.c:109550
SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *, int, int)
Definition: sqlite3.c:93175
static const short yy_reduce_ofst[]
Definition: sqlite3.c:131396
SQLITE_PRIVATE RowSet * sqlite3RowSetInit(sqlite3 *, void *, unsigned int)
Definition: sqlite3.c:45302
#define PragTyp_LOCKING_MODE
Definition: sqlite3.c:109542
SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:74799
#define Utf8Read(A)
Definition: sqlite3.c:103157
#define SQLITE_SO_UNDEFINED
Definition: sqlite3.c:14096
Index * pNext
Definition: sqlite3.c:14472
WhereClause * pWC
Definition: sqlite3.c:122525
SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *, int, int, int)
Definition: sqlite3.c:91533
int aTempReg[8]
Definition: sqlite3.c:15287
void * p
Definition: sqlite3.c:14524
static Select * findRightmost(Select *p)
Definition: sqlite3.c:112982
int sharedCacheEnabled
Definition: sqlite3.c:15600
u32 iDataVersion
Definition: sqlite3.c:57035
#define SQLITE_IOCAP_IMMUTABLE
Definition: sqlite3.c:833
SQLITE_PRIVATE Expr * sqlite3ExprSkipCollate(Expr *)
Definition: sqlite3.c:88997
u32 sectorSize
Definition: sqlite3.c:46499
#define ROWSET_SORTED
Definition: sqlite3.c:45287
SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8 **)
Table * pTriggerTab
Definition: sqlite3.c:15332
static Mem * out2Prerelease(Vdbe *p, VdbeOp *pOp)
Definition: sqlite3.c:77161
#define EIGHT_BYTE_ALIGNMENT(X)
Definition: sqlite3.c:11601
#define SQLITE_AFF_NUMERIC
Definition: sqlite3.c:14114
SQLITE_PRIVATE int sqlite3MallocSize(void *)
Definition: sqlite3.c:24018
#define SQLITE_INDEX_CONSTRAINT_EQ
Definition: sqlite3.c:6060
#define TK_COLLATE
Definition: sqlite3.c:11153
VdbeSorter * pSorter
Definition: sqlite3.c:17501
#define wsdAutoext
Definition: sqlite3.c:109348
static void explainAppendTerm(StrAccum *pStr, int iTerm, const char *zColumn, const char *zOp)
Definition: sqlite3.c:122793
static int doWalCallbacks(sqlite3 *db)
Definition: sqlite3.c:74964
#define TK_OFFSET
Definition: sqlite3.c:11181
u8 hasIncrblobCur
Definition: sqlite3.c:57032
static void strftimeFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:19219
#define OP_VFilter
Definition: sqlite3.c:12350
#define wsdStatInit
Definition: sqlite3.c:18011
static void pcache1EnforceMaxPage(PCache1 *pCache)
Definition: sqlite3.c:44530
SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *, int)
Definition: sqlite3.c:70106
sqlite3_mutex * mutex
Definition: sqlite3.c:44125
char * zErrMsg
Definition: sqlite3.c:15274
#define P4_COLLSEQ
Definition: sqlite3.c:12281
char * zFilename
Definition: sqlite3.c:46503
SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse *, Trigger *, int, ExprList *, int, Table *, int, int, int)
Definition: sqlite3.c:119701
SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *, const char *, int)
Definition: sqlite3.c:74827
static Select * isCandidateForInOpt(Expr *pX)
Definition: sqlite3.c:90499
static int checkConstraintUnchanged(Expr *pExpr, int *aiChng, int chngRowid)
Definition: sqlite3.c:106922
#define SAVE_SZ
SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *)
Definition: sqlite3.c:70528
static int noopMutexInit(void)
Definition: sqlite3.c:22348
#define SRT_Coroutine
Definition: sqlite3.c:15172
SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *)
Definition: sqlite3.c:19724
static WhereTerm * whereScanInit(WhereScan *pScan, WhereClause *pWC, int iCur, int iColumn, u32 opMask, Index *pIdx)
Definition: sqlite3.c:126187
u8 * aBuffer
Definition: sqlite3.c:84481
#define SQLITE_IOERR_GETTEMPPATH
Definition: sqlite3.c:730
#define SQLITE_DBSTATUS_CACHE_MISS
Definition: sqlite3.c:7073
SQLITE_API void SQLITE_STDCALL sqlite3_free(void *)
Definition: sqlite3.c:24049
static int newDatabase(BtShared *pBt)
Definition: sqlite3.c:60706
u8 safety_level
Definition: sqlite3.c:13511
static int isSystemTable(Parse *pParse, const char *zName)
Definition: sqlite3.c:93592
#define TK_REFERENCES
Definition: sqlite3.c:11205
const char * zWalName
Definition: sqlite3.c:53664
Bool useRandomRowid
Definition: sqlite3.c:17492
SQLITE_API int SQLITE_STDCALL sqlite3_result_zeroblob64(sqlite3_context *, sqlite3_uint64 n)
Definition: sqlite3.c:74921
#define BTCF_Multiple
Definition: sqlite3.c:57216
Definition: na_fwd.hpp:22
#define PragTyp_HEADER_VALUE
Definition: sqlite3.c:109520
SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *, i64 *pSize)
Definition: sqlite3.c:19572
static void btreeEndTransaction(Btree *p)
Definition: sqlite3.c:61416
SQLITE_PRIVATE void sqlite3ExprIfFalseDup(Parse *, Expr *, int, int)
Definition: sqlite3.c:92722
#define FILEHANDLEID(fd)
Definition: sqlite3.c:45948
static void stat4Destructor(void *pOld)
Definition: sqlite3.c:94383
SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut)
Definition: sqlite3.c:19583
#define sqlite3Toupper(x)
Definition: sqlite3.c:15776
GLint GLint i2
SQLITE_PRIVATE Bitmask sqlite3WhereGetMask(WhereMaskSet *, int)
Definition: sqlite3.c:126062
#define SQLITE_NULL
Definition: sqlite3.c:4221
char ** pzErrMsg
Definition: sqlite3.c:15564
SQLITE_PRIVATE int sqlite3PcacheSize(void)
Definition: sqlite3.c:43331
WhereLoop * pNextLoop
Definition: sqlite3.c:122377
u8 bMalloced
Definition: sqlite3.c:13599
SQLITE_PRIVATE int sqlite3CodeOnce(Parse *)
Definition: sqlite3.c:90539
char * zColl
Definition: sqlite3.c:14061
SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64)
Definition: sqlite3.c:49263
VtabCtx * pVtabCtx
Definition: sqlite3.c:13752
SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext *, Expr *)
Definition: sqlite3.c:88779
#define explainSetInteger(a, b)
Definition: sqlite3.c:113941
SortSubtask * pTask
Definition: sqlite3.c:84462
static int fcntlSizeHint(unixFile *pFile, i64 nByte)
Definition: sqlite3.c:32781
SQLITE_PRIVATE PgHdr * sqlite3PcacheDirtyList(PCache *)
Definition: sqlite3.c:43812
SQLITE_API int SQLITE_STDCALL sqlite3_open(const char *filename, sqlite3 **ppDb)
Definition: sqlite3.c:138639
sqlite3_file * pWalFd
Definition: sqlite3.c:53645
SQLITE_PRIVATE void sqlite3PcacheClearWritable(PCache *)
Definition: sqlite3.c:43648
SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(sqlite3 *db, const char *zGeom, int(*xGeom)(sqlite3_rtree_geometry *, int, sqlite3_rtree_dbl *, int *), void *pContext)
SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *)
Definition: sqlite3.c:22285
GLuint64EXT * result
Definition: glext.h:10921
SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse *, Table *, int *, int, int, int, int, u8, u8, int, int *, int *)
Definition: sqlite3.c:107023
SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *, int, const char *, char **)
Definition: sqlite3.c:121683
int(* xFilter)(sqlite3_vtab_cursor *, int idxNum, const char *idxStr, int argc, sqlite3_value **argv)
Definition: sqlite3.c:5899
#define OP_MustBeInt
Definition: sqlite3.c:12356
i64 nDeferredCons
Definition: sqlite3.c:13764
SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *, u32 *, int)
Definition: sqlite3.c:49475
unsigned char isInit
Definition: sqlite3.c:26054
#define __volatile__
Definition: linux.hpp:92
#define SQLITE_MISMATCH
Definition: sqlite3.c:677
SQLITE_PRIVATE void sqlite3StartTable(Parse *, Token *, Token *, int, int, int, int)
Definition: sqlite3.c:97593
#define SQLITE_MX_JUMP_OPCODE
Definition: sqlite3.c:12540
static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt)
Definition: sqlite3.c:24559
static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes)
Definition: sqlite3.c:62991
int nRef
Definition: sqlite3.c:57119
#define SQLITE_FCNTL_OVERWRITE
Definition: sqlite3.c:1254
SubProgram * pProgram
Definition: sqlite3.c:17815
#define BTS_INITIALLY_EMPTY
Definition: sqlite3.c:57133
double * pReal
Definition: sqlite3.c:12221
SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op,...)
Definition: sqlite3.c:139072
SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt *, int, const void *, sqlite3_uint64, void(*)(void *))
Definition: sqlite3.c:75790
#define PragFlag_ReadOnly
Definition: sqlite3.c:109564
SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager)
Definition: sqlite3.c:50849
u32 oldmask
Definition: sqlite3.c:15335
GLdouble v
SQLITE_PRIVATE void sqlite3VdbeEndCoroutine(Vdbe *, int)
Definition: sqlite3.c:70221
#define BTREE_USER_VERSION
Definition: sqlite3.c:11974
SQLITE_PRIVATE void sqlite3WithPush(Parse *, With *, u8)
Definition: sqlite3.c:116849
int(* xConnect)(sqlite3 *, void *pAux, int argc, const char *const *argv, sqlite3_vtab **ppVTab, char **)
Definition: sqlite3.c:5891
#define HasRowid(X)
Definition: sqlite3.c:14278
Expr * pLimit
Definition: sqlite3.c:15058
static int moveToRightmost(BtCursor *pCur)
Definition: sqlite3.c:62621
SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *)
Definition: sqlite3.c:68664
#define BTREE_LARGEST_ROOT_PAGE
Definition: sqlite3.c:11972
u8 bigEndCksum
Definition: sqlite3.c:53525
SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *, Table *)
Definition: sqlite3.c:98889
SQLITE_PRIVATE int sqlite3MutexEnd(void)
Definition: sqlite3.c:22211
#define OPFLG_OUT3
Definition: sqlite3.c:12510
static void callCollNeeded(sqlite3 *db, int enc, const char *zName)
Definition: sqlite3.c:101205
#define SQLITE_TESTCTRL_IMPOSTER
Definition: sqlite3.c:6818
#define IsPrimaryKeyIndex(X)
Definition: sqlite3.c:14507
int(* xCmp)(void *, int, const void *, int, const void *)
Definition: sqlite3.c:14087
SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse)
Definition: sqlite3.c:106059
#define OP_Gosub
Definition: sqlite3.c:12353
SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *, u64)
Definition: sqlite3.c:27780
Table * pNewTable
Definition: sqlite3.c:15365
#define P4_KEYINFO
Definition: sqlite3.c:12283
#define OP_MemMax
Definition: sqlite3.c:12482
signed char nextAutovac
Definition: sqlite3.c:13686
static int walRewriteChecksums(Wal *pWal, u32 iLast)
Definition: sqlite3.c:56118
#define SQLITE_MUTEX_STATIC_LRU
Definition: sqlite3.c:6710
union WhereLoop::@137 u
#define PragTyp_LOCK_PROXY_FILE
Definition: sqlite3.c:109541
static int unixGetTempname(int nBuf, char *zBuf)
Definition: sqlite3.c:34537
SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager)
Definition: sqlite3.c:49840
static void unixEnterMutex(void)
Definition: sqlite3.c:29776
SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt)
Definition: sqlite3.c:75374
Db aDbStatic[2]
Definition: sqlite3.c:13759
#define SQLITE_IOCAP_POWERSAFE_OVERWRITE
Definition: sqlite3.c:832
sqlite3 * db
Definition: sqlite3.c:84389
#define TF_OOOHidden
Definition: sqlite3.c:14245
#define SQLITE_SAVEPOINT
Definition: sqlite3.c:3001
SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *)
Definition: sqlite3.c:74668
const char * zPfx
Definition: sqlite3.c:57356
GLint GLint GLint GLint j2
YYCODETYPE lhs
Definition: sqlite3.c:132469
static void columnMallocFailure(sqlite3_stmt *pStmt)
Definition: sqlite3.c:75459
void *(* xGetAuxdata)(Fts5Context *, int bClear)
Definition: sqlite3.c:10156
#define CURSOR_REQUIRESEEK
Definition: sqlite3.c:57251
SQLITE_PRIVATE Expr * sqlite3ExprAlloc(sqlite3 *, int, const Token *, int)
Definition: sqlite3.c:89347
static TriggerStep * triggerStepAllocate(sqlite3 *db, u8 op, Token *pName)
Definition: sqlite3.c:119060
static int pcache1InitBulk(PCache1 *pCache)
Definition: sqlite3.c:44193
#define osFtruncate
SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *, Table *)
Definition: sqlite3.c:121613
#define CURTYPE_PSEUDO
Definition: sqlite3.c:17468
u8 autoCommit
Definition: sqlite3.c:13681
UnpackedRecord * pNewUnpacked
Definition: sqlite3.c:17845
SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *)
Definition: sqlite3.c:22259
#define UNIXFILE_PERSIST_WAL
Definition: sqlite3.c:29168
#define EP_TokenOnly
Definition: sqlite3.c:14728
#define MEM_Int
Definition: sqlite3.c:17637
static void walRestartHdr(Wal *pWal, u32 salt1)
Definition: sqlite3.c:54892
SQLITE_PRIVATE ExprList * sqlite3ExprListAppend(Parse *, ExprList *, Expr *)
Definition: sqlite3.c:90057
#define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL
Definition: sqlite3.c:7071
#define BTS_SECURE_DELETE
Definition: sqlite3.c:57132
#define TK_UMINUS
Definition: sqlite3.c:11255
TriggerStep * yy327
Definition: sqlite3.c:130942
#define WHERE_DISTINCT_UNIQUE
Definition: sqlite3.c:14968
static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved)
Definition: sqlite3.c:66219
#define STRACCUM_NOMEM
Definition: sqlite3.c:15549
SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *, sqlite3_value *)
Definition: sqlite3.c:74913
i64 * anExec
Definition: sqlite3.c:17561
static void codeDeferredSeek(WhereInfo *pWInfo, Index *pIdx, int iCur, int iIdxCur)
Definition: sqlite3.c:123527
static int unixUnlock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31006
SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int(*xUndo)(void *, Pgno), void *pUndoCtx)
Definition: sqlite3.c:55909
#define LONGDOUBLE_TYPE
Definition: sqlite3.c:11443
#define SQLITE_INDEX_CONSTRAINT_LIKE
Definition: sqlite3.c:6066
int nWiData
Definition: sqlite3.c:53648
#define SQLITE_SHM_SHARED
Definition: sqlite3.c:1536
#define putVarint32(A, B)
Definition: sqlite3.c:16259
i64 lastRowid
Definition: sqlite3.c:13673
SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int)
Definition: sqlite3.c:72343
SQLITE_PRIVATE Expr * sqlite3ExprAddCollateString(Parse *, Expr *, const char *)
Definition: sqlite3.c:88986
SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *)
Definition: sqlite3.c:68371
#define SQLITE_FCNTL_PRAGMA
Definition: sqlite3.c:1257
#define SQLITE_SCANSTAT_EST
Definition: sqlite3.c:8122
#define isSorter(x)
Definition: sqlite3.c:76708
VTable * pDisconnect
Definition: sqlite3.c:13754
static int valueFromExpr(sqlite3 *db, Expr *pExpr, u8 enc, u8 affinity, sqlite3_value **ppVal, struct ValueNewStat4Ctx *pCtx)
Definition: sqlite3.c:69445
SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *)
Definition: sqlite3.c:97546
static void zeroPage(MemPage *pPage, int flags)
Definition: sqlite3.c:59527
Stat4Sample * a
Definition: sqlite3.c:94317
#define vdbeAssertFieldCountWithinLimits(A, B, C)
Definition: sqlite3.c:73562
#define tkEXPLAIN
Definition: sqlite3.c:135253
SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void)
Definition: sqlite3.c:138809
UINT16_TYPE u16
Definition: sqlite3.c:11448
SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *)
Definition: sqlite3.c:100749
SQLITE_PRIVATE void sqlite3ExprCodeGetColumnToReg(Parse *, Table *, int, int, int)
Definition: sqlite3.c:91490
static void exprToRegister(Expr *p, int iReg)
Definition: sqlite3.c:91562
struct IdList::IdList_item * a
#define SQLITE_IOERR_DELETE_NOENT
Definition: sqlite3.c:728
static int unixWrite(sqlite3_file *id, const void *pBuf, int amt, sqlite3_int64 offset)
Definition: sqlite3.c:32375
SQLITE_PRIVATE void sqlite3MemSetDefault(void)
Definition: sqlite3.c:20321
sqlite3_vfs * pVfs
Definition: sqlite3.c:13666
#define sqlite3MemdebugHasType(X, Y)
Definition: sqlite3.c:16633
u8 journalMode
Definition: sqlite3.c:46439
SQLITE_PRIVATE void * sqlite3OsDlOpen(sqlite3_vfs *, const char *)
Definition: sqlite3.c:19711
SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context *, const void *, int, void(*)(void *))
Definition: sqlite3.c:74903
SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *, int, int, char *, i8, u8)
Definition: sqlite3.c:100874
static int dotlockLock(sqlite3_file *id, int eFileLock)
Definition: sqlite3.c:31211
#define IsHiddenColumn(X)
Definition: sqlite3.c:14269
#define VdbeCoverageNeverTaken(v)
Definition: sqlite3.c:12677
const sqlite3_io_methods * pMethod
Definition: sqlite3.c:86885
void * pRollbackArg
Definition: sqlite3.c:13716
Definition: parser.hpp:150
static int dupedExprNodeSize(Expr *p, int flags)
Definition: sqlite3.c:89736
SQLITE_PRIVATE CollSeq * sqlite3FindCollSeq(sqlite3 *, u8 enc, const char *, int)
Definition: sqlite3.c:101386
#define SQLITE_LIMIT_VDBE_OP
Definition: sqlite3.c:3534
u16 btsFlags
Definition: sqlite3.c:57105
SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName)
Definition: sqlite3.c:17347
#define TK_DETACH
Definition: sqlite3.c:11171
struct WhereLoop::@137::@138 btree
int addrLoop
Definition: sqlite3.c:17746
#define OP_Rewind
Definition: sqlite3.c:12394
static void btreeClearHasContent(BtShared *pBt)
Definition: sqlite3.c:58251
#define IgnorableOrderby(X)
Definition: sqlite3.c:15166
static void populateCellCache(CellArray *p, int idx, int N)
Definition: sqlite3.c:64087
static WhereTerm * whereNthSubterm(WhereTerm *pTerm, int N)
Definition: sqlite3.c:124898
SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse *, Select *, ExprList *, const char *)
Definition: sqlite3.c:88402
static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p)
Definition: sqlite3.c:72911
SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *, const Mem *)
Definition: sqlite3.c:68982
static int posixOpen(const char *zFile, int flags, int mode)
Definition: sqlite3.c:29436
static Expr * exprTableColumn(sqlite3 *db, Table *pTab, int iCursor, i16 iCol)
Definition: sqlite3.c:104888
#define NC_HasAgg
Definition: sqlite3.c:15016
#define BITVEC_NINT
Definition: sqlite3.c:42697
#define TK_HAVING
Definition: sqlite3.c:11228
static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p)
Definition: sqlite3.c:117354
#define SQLITE_SO_ASC
Definition: sqlite3.c:14094
#define TK_BETWEEN
Definition: sqlite3.c:11132
#define SQLITE_TRANSACTION
Definition: sqlite3.c:2991
static int pager_open_journal(Pager *pPager)
Definition: sqlite3.c:51366
Mem * aVar
Definition: sqlite3.c:17775
static int unixClose(sqlite3_file *id)
Definition: sqlite3.c:31063
#define SQLITE_IOERR_LOCK
Definition: sqlite3.c:720
#define TK_WITHOUT
Definition: sqlite3.c:11125
GLint GLsizei width
SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *, Table *, int)
Definition: sqlite3.c:105937
SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *, Expr *, int *)
Definition: sqlite3.c:92224
#define WO_GE
Definition: sqlite3.c:122744
unsigned long long int sqlite_uint64
Definition: sqlite3.c:510
static int parseTimezone(const char *zDate, DateTime *p)
Definition: sqlite3.c:18461
u8 minWriteFileFormat
Definition: sqlite3.c:17789
int iRangeReg
Definition: sqlite3.c:15289
#define CC_PERCENT
Definition: sqlite3.c:134366
#define SQLITE_DBCONFIG_LOOKASIDE
Definition: sqlite3.c:2206
SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *, int iBatch, i64)
Definition: sqlite3.c:45603
static SQLITE_NOINLINE void btreeParseCellAdjustSizeForOverflow(MemPage *pPage, u8 *pCell, CellInfo *pInfo)
Definition: sqlite3.c:58700
static int autoIncBegin(Parse *pParse, int iDb, Table *pTab)
Definition: sqlite3.c:106027
#define SLOT_4_2_0
Definition: sqlite3.c:27803
sqlite3_pcache_page page
Definition: sqlite3.c:44021
static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v)
Definition: sqlite3.c:27756
INT16_TYPE i16
Definition: sqlite3.c:11449
u16 ht_slot
Definition: sqlite3.c:53692
static int pagerRollbackWal(Pager *pPager)
Definition: sqlite3.c:48860
#define PragTyp_KEY
Definition: sqlite3.c:109559
i8 isOrdered
Definition: sqlite3.c:122365
ExprList * pCheck
Definition: sqlite3.c:14203
static char comparisonAffinity(Expr *pExpr)
Definition: sqlite3.c:89112
#define SQLITE_FCNTL_ZIPVFS
Definition: sqlite3.c:1267
static void sqlite3ClearStatTables(Parse *pParse, int iDb, const char *zType, const char *zName)
Definition: sqlite3.c:99154
SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *, Pgno)
Definition: sqlite3.c:43671
#define EP_FromJoin
Definition: sqlite3.c:14714
void copy(void *dst, void const *src, size_t size)
Definition: types.cpp:836
sqlite3_int64 alarmThreshold
Definition: sqlite3.c:23659
u32 aColmask[2]
Definition: sqlite3.c:15234
#define OP_DropIndex
Definition: sqlite3.c:12476
Token sLastToken
Definition: sqlite3.c:15369
#define SQLITE_ECEL_DUP
Definition: sqlite3.c:16082
Db * aDb
Definition: sqlite3.c:13670
Btree * pBt
Definition: sqlite3.c:17503
PgFreeslot * pFree
Definition: sqlite3.c:44126
u8 noLock
Definition: sqlite3.c:46448
#define STRACCUM_TOOBIG
Definition: sqlite3.c:15550
static void btreeReleaseAllCursorPages(BtCursor *pCur)
Definition: sqlite3.c:58259
static int osLocaltime(time_t *t, struct tm *pTm)
Definition: sqlite3.c:18761
int iOffset
Definition: sqlite3.c:15046
#define SQLITE_InternChanges
Definition: sqlite3.c:13804
static void notValid(Parse *pParse, NameContext *pNC, const char *zMsg, int validMask)
Definition: sqlite3.c:87926
#define SQLITE_MAX_PMASZ
Definition: sqlite3.c:84220
SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8)
Definition: sqlite3.c:110019
#define SQLITE_VdbeTrace
Definition: sqlite3.c:13803
GLintptr offset
#define PragTyp_DATABASE_LIST
Definition: sqlite3.c:109530
SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *, const char *zDb)
Definition: sqlite3.c:100805
#define OP_Affinity
Definition: sqlite3.c:12434
With * pWith
Definition: sqlite3.c:15376
#define TK_EACH
Definition: sqlite3.c:11172
#define TK_LP
Definition: sqlite3.c:11122
char * zColAff
Definition: sqlite3.c:14471
PgHdr * pMmapFreelist
Definition: sqlite3.c:46491
static void clearYMD_HMS_TZ(DateTime *p)
Definition: sqlite3.c:18723
#define SQLITE_LIMIT_LIKE_PATTERN_LENGTH
Definition: sqlite3.c:3537
#define TK_PRAGMA
Definition: sqlite3.c:11182
SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int)
Definition: sqlite3.c:19686
int iVersion
Definition: sqlite3.c:10400
int mxReg
Definition: sqlite3.c:14565
#define YY_MAX_SHIFTREDUCE
Definition: sqlite3.c:130962
Table * pTab
Definition: sqlite3.c:15199
#define EP_Error
Definition: sqlite3.c:14717
SQLITE_PRIVATE void * sqlite3DbMallocRawNN(sqlite3 *, u64)
Definition: sqlite3.c:24239
static void yy_accept(yyParser *)
Definition: sqlite3.c:134107
static SQLITE_NOINLINE int walkExpr(Walker *pWalker, Expr *pExpr)
Definition: sqlite3.c:87276
SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *)
Definition: sqlite3.c:90316
SQLITE_PRIVATE int sqlite3HeapNearlyFull(void)
Definition: sqlite3.c:23783
static void renameTriggerFunc(sqlite3_context *context, int NotUsed, sqlite3_value **argv)
Definition: sqlite3.c:93374
SQLITE_PRIVATE sqlite3 * sqlite3VdbeDb(Vdbe *)
Definition: sqlite3.c:74337
#define SF_MultiValue
Definition: sqlite3.c:15082
static void countFinalize(sqlite3_context *context)
Definition: sqlite3.c:104079
int nOp
Definition: sqlite3.c:17769
u8 colFlags
Definition: sqlite3.c:14065
#define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc)
Definition: sqlite3.c:14006
unsigned char nEquiv
Definition: sqlite3.c:122529
struct ScratchFreeslot * pNext
Definition: sqlite3.c:23651
#define OPFLAG_ISUPDATE
Definition: sqlite3.c:15414
HashElem * first
Definition: sqlite3.c:11045
#define SQLITE_PRINT_BUF_SIZE
Definition: sqlite3.c:24603
#define WO_EQUIV
Definition: sqlite3.c:122750
static int multiSelect(Parse *pParse, Select *p, SelectDest *pDest)
Definition: sqlite3.c:114994
#define OP_TableLock
Definition: sqlite3.c:12488
#define TK_GT
Definition: sqlite3.c:11138
SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *)
Definition: sqlite3.c:43886
SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb)
Definition: sqlite3.c:137676
int ckBase
Definition: sqlite3.c:15298
static int sqlite3Close(sqlite3 *db, int forceZombie)
Definition: sqlite3.c:136619
#define UNIXVFS(VFSNAME, FINDER)
#define OPFLAG_PERMUTE
Definition: sqlite3.c:15426
#define SQLITE_STATIC
Definition: sqlite3.c:4858
#define UINT32_TYPE
Definition: sqlite3.c:11411
SQLITE_PRIVATE void sqlite3Savepoint(Parse *, int, Token *)
Definition: sqlite3.c:100729
static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv)
Definition: sqlite3.c:103008
SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *)
Definition: sqlite3.c:136327
SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *, IdList *)
Definition: sqlite3.c:100349
#define SCHEMA_ENC(db)
Definition: sqlite3.c:13792
char ** azModuleArg
Definition: sqlite3.c:14221
#define SQLITE_NOTADB
Definition: sqlite3.c:683
union Expr::@126 x
static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql)
Definition: sqlite3.c:120684
#define OP_OpenWrite
Definition: sqlite3.c:12442
#define SQLITE_FCNTL_SIZE_HINT
Definition: sqlite3.c:1248
#define OPFLG_IN3
Definition: sqlite3.c:12508
sqlite3 * db
Definition: sqlite3.c:83589
int savedNQueryLoop
Definition: sqlite3.c:122661
static int resolveAsName(Parse *pParse, ExprList *pEList, Expr *pE)
Definition: sqlite3.c:88192
void * pUserData
Definition: sqlite3.c:13929
SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *, int iDB)
Definition: sqlite3.c:95848
#define WAL_ALL_BUT_WRITE
Definition: sqlite3.c:53494
#define TK_FROM
Definition: sqlite3.c:11223
static int pager_playback_one_page(Pager *pPager, i64 *pOffset, Bitvec *pDone, int isMainJrnl, int isSavepnt)
Definition: sqlite3.c:48026
SQLITE_PRIVATE void sqlite3MallocEnd(void)
Definition: sqlite3.c:23790
static void fkLookupParent(Parse *pParse, int iDb, Table *pTab, Index *pIdx, FKey *pFKey, int *aiCol, int regData, int nIncr, int isIgnore)
Definition: sqlite3.c:104715
static void sqlite3StringToId(Expr *p)
Definition: sqlite3.c:98014
SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void)
Definition: sqlite3.c:19446
SQLITE_PRIVATE void sqlite3SrcListFuncArgs(Parse *, SrcList *, ExprList *)
Definition: sqlite3.c:100628
static u32 SQLITE_NOINLINE serialGet(const unsigned char *buf, u32 serial_type, Mem *pMem)
Definition: sqlite3.c:73217
SQLITE_PRIVATE void sqlite3ExprListSetSortOrder(ExprList *, int)
Definition: sqlite3.c:90099
#define SQLITE_CANTOPEN_NOTEMPDIR
Definition: sqlite3.c:737
#define wsdStat
Definition: sqlite3.c:18012
static int whereLoopAddVirtual(WhereLoopBuilder *pBuilder, Bitmask mPrereq, Bitmask mUnusable)
Definition: sqlite3.c:128854
#define PAGER_STAT_WRITE
Definition: sqlite3.c:46533
static int vdbeSorterAddToTree(SortSubtask *pTask, int nDepth, int iSeq, MergeEngine *pRoot, MergeEngine *pLeaf)
Definition: sqlite3.c:86415
Bitmask prereqAll
Definition: sqlite3.c:122496
static SorterCompare vdbeSorterGetCompare(VdbeSorter *p)
Definition: sqlite3.c:85447
#define SAVEPOINT_BEGIN
Definition: sqlite3.c:14036
SQLITE_PRIVATE void sqlite3DeleteFrom(Parse *, SrcList *, Expr *)
Definition: sqlite3.c:101878
SQLITE_PRIVATE void sqlite3DropTable(Parse *, SrcList *, int, int)
Definition: sqlite3.c:99248
SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *)
Definition: sqlite3.c:71278
#define SQLITE_FCNTL_RBU
Definition: sqlite3.c:1268
SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int)
Definition: sqlite3.c:60425
static int openDatabase(const char *zFilename, sqlite3 **ppDb, unsigned int flags, const char *zVfs)
Definition: sqlite3.c:138310
SQLITE_PRIVATE void(*)(void) sqlite3OsDlSym(sqlite3_vfs *, void *, const char *)
Definition: sqlite3.c:13375
int mxPmaSize
Definition: sqlite3.c:84384
static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage)
Definition: sqlite3.c:54211
static void identPut(char *z, int *pIdx, char *zSignedIdent)
Definition: sqlite3.c:98259
char validJD
Definition: sqlite3.c:18374
union VdbeCursor::@132 uc
#define osMremap
#define SQLITE_EXTENSION_INIT3
Definition: sqlite3.c:108707
#define SQLITE_FUNC_NEEDCOLL
Definition: sqlite3.c:13949


librealsense2
Author(s): Sergey Dorodnicov , Doron Hirshberg , Mark Horn , Reagan Lopez , Itay Carpis
autogenerated on Mon May 3 2021 02:50:10